diff --git a/.devops/nix/package.nix b/.devops/nix/package.nix index ba499303b38f..78995be55896 100644 --- a/.devops/nix/package.nix +++ b/.devops/nix/package.nix @@ -13,7 +13,6 @@ blas, cudaPackages, autoAddDriverRunpath, - darwin, rocmPackages, vulkan-headers, vulkan-loader, @@ -104,17 +103,6 @@ let ln -s /usr/bin/xcrun $out/bin ''; - # apple_sdk is supposed to choose sane defaults, no need to handle isAarch64 - # separately - darwinBuildInputs = - with darwin.apple_sdk.frameworks; - [ - Accelerate - CoreVideo - CoreGraphics - ] - ++ optionals useMetalKit [ MetalKit ]; - cudaBuildInputs = with cudaPackages; [ cuda_cudart cuda_nvml_dev @@ -244,8 +232,7 @@ effectiveStdenv.mkDerivation (finalAttrs: { ++ optionals syclAot [ oclocAot ]; buildInputs = - optionals effectiveStdenv.hostPlatform.isDarwin darwinBuildInputs - ++ optionals useCuda cudaBuildInputs + optionals useCuda cudaBuildInputs ++ optionals useMpi [ mpi ] ++ optionals useRocm rocmBuildInputs ++ optionals useBlas [ blas ] diff --git a/.github/workflows/ci-self-hosted-vulkan.yml b/.github/workflows/ci-self-hosted-vulkan.yml index 1ce68bfe0a0b..79501bfd7d98 100644 --- a/.github/workflows/ci-self-hosted-vulkan.yml +++ b/.github/workflows/ci-self-hosted-vulkan.yml @@ -49,94 +49,94 @@ env: jobs: gpu-vulkan-nvidia-cm: - # runs-on: "hf-jobs-t4-small:ubuntu26_04" - runs-on: [self-hosted, Linux, NVIDIA] + runs-on: [self-hosted, Linux, gb10] + container: "ubuntu:26.04" steps: - name: Clone id: checkout uses: actions/checkout@v6 - # - name: Install dependencies - # run: | - # sudo apt update - # sudo apt install -y build-essential cmake libxcb-xinput0 libxcb-xinerama0 libxcb-cursor-dev libvulkan-dev glslc spirv-headers vulkan-tools mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 libssl-dev time unzip wget python3 python3-venv python3-pip + - name: Install dependencies + run: | + apt update + apt install -y build-essential cmake jq git git-lfs libxcb-xinput0 libxcb-xinerama0 libxcb-cursor-dev libvulkan-dev glslc spirv-headers vulkan-tools mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 libssl-dev time unzip wget python3 python3-venv python3-pip - # - name: ccache - # uses: ggml-org/ccache-action@v1.2.24 - # with: - # restore: false - # save: false + - name: ccache + uses: ggml-org/ccache-action@v1.2.24 + with: + restore: false + save: false - # - name: ccache-buckets-restore - # uses: ./.github/actions/ccache-buckets - # with: - # key: self-hosted-vulkan-nvidia-cm - # folder: llama.cpp - # hf_bucket: ggml-org/cache + - name: ccache-buckets-restore + uses: ./.github/actions/ccache-buckets + with: + key: self-hosted-vulkan-nvidia-cm-gb10 + folder: llama.cpp + hf_bucket: ggml-org/cache - name: Test id: ggml-ci run: | vulkaninfo --summary - GG_BUILD_VULKAN=1 GGML_VK_DISABLE_COOPMAT2=1 bash ./ci/run.sh ~/results/llama.cpp/$RUNNER_NAME ~/mnt/llama.cpp - - # - name: ccache-buckets-save - # if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }} - # uses: ./.github/actions/ccache-buckets - # env: - # HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }} - # with: - # key: self-hosted-vulkan-nvidia-cm - # folder: llama.cpp - # evict-old-files: 1d - # hf_bucket: ggml-org/cache - # save: true + GG_BUILD_VULKAN=1 GGML_VK_DISABLE_COOPMAT2=1 bash ./ci/run.sh ~/results/llama.cpp /mnt/cache/llama.cpp + + - name: ccache-buckets-save + if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }} + uses: ./.github/actions/ccache-buckets + env: + HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }} + with: + key: self-hosted-vulkan-nvidia-cm-gb10 + folder: llama.cpp + evict-old-files: 1d + hf_bucket: ggml-org/cache + save: true gpu-vulkan-nvidia-cm2: - # runs-on: "hf-jobs-t4-small:ubuntu26_04" - runs-on: [self-hosted, Linux, NVIDIA, COOPMAT2] + runs-on: [self-hosted, Linux, gb10] + container: "ubuntu:26.04" steps: - name: Clone id: checkout uses: actions/checkout@v6 - # - name: Install dependencies - # run: | - # sudo apt update - # sudo apt install -y build-essential cmake libxcb-xinput0 libxcb-xinerama0 libxcb-cursor-dev libvulkan-dev glslc spirv-headers vulkan-tools mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 libssl-dev time unzip wget python3 python3-venv python3-pip + - name: Install dependencies + run: | + apt update + apt install -y build-essential cmake jq git git-lfs libxcb-xinput0 libxcb-xinerama0 libxcb-cursor-dev libvulkan-dev glslc spirv-headers vulkan-tools mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 libssl-dev time unzip wget python3 python3-venv python3-pip - # - name: ccache - # uses: ggml-org/ccache-action@v1.2.24 - # with: - # restore: false - # save: false + - name: ccache + uses: ggml-org/ccache-action@v1.2.24 + with: + restore: false + save: false - # - name: ccache-buckets-restore - # uses: ./.github/actions/ccache-buckets - # with: - # key: self-hosted-vulkan-nvidia-cm2 - # folder: llama.cpp - # hf_bucket: ggml-org/cache + - name: ccache-buckets-restore + uses: ./.github/actions/ccache-buckets + with: + key: self-hosted-vulkan-nvidia-cm2-gb10 + folder: llama.cpp + hf_bucket: ggml-org/cache - name: Test id: ggml-ci run: | vulkaninfo --summary - GG_BUILD_VULKAN=1 bash ./ci/run.sh ~/results/llama.cpp/$RUNNER_NAME ~/mnt/llama.cpp + GG_BUILD_VULKAN=1 bash ./ci/run.sh ~/results/llama.cpp /mnt/cache/llama.cpp - # - name: ccache-buckets-save - # if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }} - # uses: ./.github/actions/ccache-buckets - # env: - # HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }} - # with: - # key: self-hosted-vulkan-nvidia-cm2 - # folder: llama.cpp - # evict-old-files: 1d - # hf_bucket: ggml-org/cache - # save: true + - name: ccache-buckets-save + if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }} + uses: ./.github/actions/ccache-buckets + env: + HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }} + with: + key: self-hosted-vulkan-nvidia-cm2-gb10 + folder: llama.cpp + evict-old-files: 1d + hf_bucket: ggml-org/cache + save: true gpu-vulkan-apple: runs-on: [self-hosted, macOS, ARM64] diff --git a/.github/workflows/hip-quality-check.yml b/.github/workflows/hip-quality-check.yml index 325e1ebaa4e8..fea09c41bb64 100644 --- a/.github/workflows/hip-quality-check.yml +++ b/.github/workflows/hip-quality-check.yml @@ -11,7 +11,8 @@ on: '**/*.cuh', 'ggml/src/ggml-hip/CMakeLists.txt', 'ggml/src/ggml-cuda/vendors/hip.h', - 'scripts/hip/gcn-cdna-vgpr-check.py' + 'scripts/hip/gcn-cdna-metrics.py', + 'scripts/hip/test_gcn_cdna_metrics.py' ] pull_request: @@ -22,7 +23,8 @@ on: '**/*.cuh', 'ggml/src/ggml-hip/CMakeLists.txt', 'ggml/src/ggml-cuda/vendors/hip.h', - 'scripts/hip/gcn-cdna-vgpr-check.py' + 'scripts/hip/gcn-cdna-metrics.py', + 'scripts/hip/test_gcn_cdna_metrics.py' ] cache-mode: none @@ -45,15 +47,32 @@ jobs: runs-on: ubuntu-22.04 container: rocm/dev-ubuntu-22.04:7.2.1 steps: + - name: Dependencies + id: depends + run: | + sudo apt-get update + sudo apt-get install -y build-essential git cmake rocblas-dev hipblas-dev libssl-dev python3 python3-venv python3-pip python3-yaml jq + - name: Clone id: checkout uses: actions/checkout@v6 + with: + fetch-depth: 2 - - name: Dependencies - id: depends + # The first parent of the tested merge commit is the exact baseline. + - name: Get baseline SHA + if: ${{ github.event_name == 'pull_request' }} + id: master_sha run: | - sudo apt-get update - sudo apt-get install -y build-essential git cmake rocblas-dev hipblas-dev libssl-dev python3 python3-venv python3-pip jq + git config --global --add safe.directory "$GITHUB_WORKSPACE" + git rev-parse --verify HEAD^2 > /dev/null + baseline_sha=$(git rev-parse HEAD^1) + pr_sha=$(git rev-parse HEAD) + printf 'sha=%s\npr_sha=%s\n' "$baseline_sha" "$pr_sha" >> "$GITHUB_OUTPUT" + printf 'Baseline commit: %s\nPR merge commit: %s\n' "$baseline_sha" "$pr_sha" + + - name: Test HIP kernel metrics scripts + run: python3 -m unittest discover -s scripts/hip -p 'test_gcn_cdna_metrics.py' - name: ccache uses: ggml-org/ccache-action@v1.2.24 @@ -70,6 +89,21 @@ jobs: folder: llama.cpp hf_bucket: ggml-org/cache + # Verify device optimization records before starting the expensive builds. + - name: Validate HIP resource remarks + run: | + mkdir -p hip-metrics-probe + cd hip-metrics-probe + printf '%s\n' '#include ' '__global__ void metrics_probe(float * out) { *out = 1.0f; }' > probe.hip + "$(hipconfig -l)/clang" -x hip --offload-arch=gfx908 -O2 -c probe.hip -o probe.o \ + -Rpass-analysis=kernel-resource-usage --save-temps \ + -Xarch_device -fsave-optimization-record=yaml \ + -Xarch_device -foptimization-record-passes=kernel-resource-usage + for metric in NumVGPR Occupancy VGPRSpill SGPRSpill; do + grep -q "Name: *$metric$" probe.opt.yaml || { echo "Missing $metric in GPU optimization records"; exit 1; } + done + python3 ../scripts/hip/gcn-cdna-metrics.py vgpr probe.opt.yaml + - name: Build with Werror id: cmake_build run: | @@ -83,19 +117,178 @@ jobs: cd build make -j $(nproc) - - name: Check for major VGPR spills + - name: Build HIP kernel resource metrics id: vgpr_check + shell: bash run: | cmake -B build -S . \ -DCMAKE_HIP_COMPILER="$(hipconfig -l)/clang" \ -DGPU_TARGETS=gfx908 \ -DGGML_HIP=ON \ -DGGML_HIP_EXPORT_METRICS=On \ - -DCMAKE_HIP_FLAGS="" \ + -DCMAKE_HIP_FLAGS="-Xarch_device -fsave-optimization-record=yaml -Xarch_device -foptimization-record-passes=kernel-resource-usage" \ -DCMAKE_BUILD_TYPE=Release cd build - make -j $(nproc) 2>&1 | tee metrics.log | grep -v 'Rpass-analysis=kernel-resource-usage\|remark:\|^$' - python3 ../scripts/hip/gcn-cdna-vgpr-check.py metrics.log + set -o pipefail + CCACHE_DISABLE=1 make -j $(nproc) ggml-hip 2>&1 | tee metrics.log | sed -e '/Rpass-analysis=kernel-resource-usage/d' -e '/remark:/d' -e '/^$/d' + echo "Optimization record files:" + find . -type f -name '*.opt.yaml' | sed -n '1,10p' + echo "GPU kernel remarks in YAML:" + grep -rl --include='*.opt.yaml' 'kernel-resource-usage' . | sed -n '1,10p' || true + echo "First YAML record:" + first_yaml=$(find ggml/src/ggml-hip -type f -name '*.opt.yaml' -print -quit) + if [ -n "$first_yaml" ]; then head -n 35 "$first_yaml"; fi + echo "GPU resource diagnostics in compiler log:" + grep -m 3 'Function Name:' metrics.log || true + + # The PR comparison evaluates every rule and reports all failures at the end. + - name: Check VGPR limit on master + if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }} + run: python3 scripts/hip/gcn-cdna-metrics.py vgpr build/ggml/src/ggml-hip + + # On master pushes, cache the device optimization records as the baseline for PR checks. + - name: Save master metrics baseline + if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }} + run: | + mkdir -p hip-baseline-metrics + find build/ggml/src/ggml-hip -type f -name '*.opt.yaml' -exec cp --parents {} hip-baseline-metrics/ \; + + - name: Cache master metrics baseline + if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }} + env: + HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }} + run: | + if [ -n "$HF_TOKEN" ]; then + tar -czf hip-baseline-metrics.tar.gz -C hip-baseline-metrics . + .venv-hf/bin/hf buckets cp hip-baseline-metrics.tar.gz "hf://buckets/ggml-org/cache/llama.cpp/hip-quality-check-yaml-device-rocm-7.2.1-gfx908-${{ github.sha }}.tar.gz" || echo "Failed to save HIP metrics baseline" + fi + + - name: Remove old HIP metrics baselines + if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }} + shell: bash + env: + HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }} + run: | + if [ -z "$HF_TOKEN" ]; then + exit 0 + fi + + if ! cache_files=$(.venv-hf/bin/hf buckets list "hf://buckets/ggml-org/cache/llama.cpp/hip-quality-check-yaml-device-rocm-" --json | jq -r ' + .[] + | select(.type == "file") + | select(.path | endswith(".tar.gz")) + | select(try ((.uploaded_at | .[:19]+"Z" | fromdateiso8601) < (now - 30 * 24 * 60 * 60)) catch false) + | .path + '); then + echo "Failed to list HIP metrics baselines" + exit 0 + fi + + while IFS= read -r cache_path; do + [ -n "$cache_path" ] || continue + .venv-hf/bin/hf buckets rm "hf://buckets/ggml-org/cache/$cache_path" -y || echo "Failed to remove $cache_path" + done <<< "$cache_files" + + # Restore the device optimization records for the exact baseline commit. + - name: Restore master metrics baseline + if: ${{ github.event_name == 'pull_request' }} + id: baseline_cache + env: + HF_TOKEN: ${{ secrets.HF_TOKEN_CI }} + run: | + cache_url="hf://buckets/ggml-org/cache/llama.cpp/hip-quality-check-yaml-device-rocm-7.2.1-gfx908-${{ steps.master_sha.outputs.sha }}.tar.gz" + if .venv-hf/bin/hf buckets cp "$cache_url" hip-baseline-metrics.tar.gz; then + mkdir -p hip-baseline-metrics + if tar -xzf hip-baseline-metrics.tar.gz -C hip-baseline-metrics && [ -n "$(find hip-baseline-metrics -type f -name '*.opt.yaml' -print -quit)" ]; then + echo "cache-hit=true" >> "$GITHUB_OUTPUT" + echo "Restored HIP metrics baseline from HF Buckets" + else + rm -rf hip-baseline-metrics + echo "Invalid HIP metrics baseline cache" + fi + rm -f hip-baseline-metrics.tar.gz + else + echo "No HIP metrics baseline in HF Buckets; building from source" + fi + + # Fallback when the baseline commit has no cached metrics. + - name: Checkout baseline (master) + if: ${{ github.event_name == 'pull_request' && steps.baseline_cache.outputs.cache-hit != 'true' }} + uses: actions/checkout@v6 + with: + ref: ${{ steps.master_sha.outputs.sha }} + path: hip-baseline + + - name: Build master metrics baseline + if: ${{ github.event_name == 'pull_request' && steps.baseline_cache.outputs.cache-hit != 'true' }} + shell: bash + run: | + cd hip-baseline + cmake -B build -S . \ + -DCMAKE_HIP_COMPILER="$(hipconfig -l)/clang" \ + -DGPU_TARGETS=gfx908 \ + -DGGML_HIP=ON \ + -DGGML_HIP_EXPORT_METRICS=On \ + -DCMAKE_HIP_FLAGS="-Xarch_device -fsave-optimization-record=yaml -Xarch_device -foptimization-record-passes=kernel-resource-usage" \ + -DCMAKE_BUILD_TYPE=Release + cd build + set -o pipefail + CCACHE_DISABLE=1 make -j $(nproc) ggml-hip 2>&1 | tee metrics.log | sed -e '/Rpass-analysis=kernel-resource-usage/d' -e '/remark:/d' -e '/^$/d' + mkdir -p ../../hip-baseline-metrics + find ggml/src/ggml-hip -type f -name '*.opt.yaml' -exec cp --parents {} ../../hip-baseline-metrics/ \; + + - name: Check kernel resource rules vs master + if: ${{ github.event_name == 'pull_request' }} + id: occupancy_check + env: + BASELINE_SHA: ${{ steps.master_sha.outputs.sha }} + PR_SHA: ${{ steps.master_sha.outputs.pr_sha }} + run: | + # The PR optimization records come from the VGPR spill check build above, so + # this step adds no extra build when the baseline cache hits. + python3 scripts/hip/gcn-cdna-metrics.py compare hip-baseline-metrics build/ggml/src/ggml-hip \ + --dump hip-kernel-metrics-deltas.tsv || check_failed=true + if [ ! -s hip-kernel-metrics-deltas.tsv ]; then + echo "Kernel metrics comparison failed before producing a TSV report" + exit 1 + fi + python3 scripts/hip/gcn-cdna-metrics.py report hip-kernel-metrics-deltas.tsv \ + -o hip-kernel-metrics-report.md + sed -i "3i\\- Baseline commit: $BASELINE_SHA\\n- PR merge commit: $PR_SHA" hip-kernel-metrics-report.md + if [ -n "$check_failed" ]; then + echo "check_failed=true" >> "$GITHUB_OUTPUT" + fi + exit 0 + + - name: Upload kernel metrics report + if: ${{ github.event_name == 'pull_request' }} + id: metrics_report + uses: actions/upload-artifact@v7 + with: + name: hip-kernel-metrics-report + path: hip-kernel-metrics-report.md + + - name: Publish kernel metrics summary + if: ${{ github.event_name == 'pull_request' }} + shell: bash + env: + ARTIFACT_URL: ${{ steps.metrics_report.outputs.artifact-url }} + run: | + { + if [ "$(wc -c < hip-kernel-metrics-report.md)" -le 1000000 ]; then + cat hip-kernel-metrics-report.md + else + sed -n -e '/^# /p' -e '/^- Baseline/p' -e '/^- PR/p' -e '/^Kernels compared:/p' -e 's/^## /- /p' hip-kernel-metrics-report.md + printf '\nThe full report exceeds the GitHub job summary size limit.\n' + fi + printf '\n[Download the full kernel metrics report](%s)\n' "$ARTIFACT_URL" + } | tee -a "$GITHUB_STEP_SUMMARY" + + - name: Fail on blocking regressions + if: ${{ github.event_name == 'pull_request' && steps.occupancy_check.outputs.check_failed == 'true' }} + run: | + echo "Blocking kernel metrics regressions detected, see the job summary and hip-kernel-metrics-report artifact" + exit 1 - name: ccache-buckets-save if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }} diff --git a/.github/workflows/pr-video-demo-label.yml b/.github/workflows/pr-video-demo-label.yml index f6f8567531c3..d6d59e710036 100644 --- a/.github/workflows/pr-video-demo-label.yml +++ b/.github/workflows/pr-video-demo-label.yml @@ -22,7 +22,7 @@ jobs: BODY: ${{ github.event.pull_request.body }} HAS_LABEL: ${{ contains(github.event.pull_request.labels.*.name, 'video demo') }} run: | - # sections written by demo:pr (see ui/apps/chat/demo/cli.ts): the managed comment + # sections written by demo:pr (see ui/lib/demo/src/cli.ts): the managed comment # markers, or a preview linking to a demo video uploaded for this PR has_demo=false if { grep -qF '' <<< "$BODY" && grep -qF '' <<< "$BODY"; } || diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml index 3547bf4c61e5..60e5e8582e48 100644 --- a/.github/workflows/ui.yml +++ b/.github/workflows/ui.yml @@ -83,8 +83,16 @@ jobs: run: npm ci working-directory: ui/apps/chat + # the app's demo helpers import the demo harness (ui/lib/demo), whose sources resolve + # @playwright/test and its other types from its own node_modules + - name: Install demo harness dependencies + id: setup-demo + if: ${{ steps.setup.conclusion == 'success' }} + run: npm ci + working-directory: ui/lib/demo + - name: Run type checking - if: ${{ always() && steps.setup.conclusion == 'success' }} + if: ${{ always() && steps.setup.conclusion == 'success' && steps.setup-demo.conclusion == 'success' }} run: npm run check working-directory: ui/apps/chat @@ -212,6 +220,29 @@ jobs: run: npm run prepack working-directory: ui/lib/harness + demo-checks: + name: Demo 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/demo + + - name: Run type checking + run: npm run check + working-directory: ui/lib/demo + chat-only-build: name: Chat-only build runs-on: ubuntu-24.04 diff --git a/conversion/__init__.py b/conversion/__init__.py index 146c309e65a7..6796820109a9 100644 --- a/conversion/__init__.py +++ b/conversion/__init__.py @@ -146,6 +146,7 @@ "HrmTextForCausalLM": "hrm_text", "HYV3ForCausalLM": "hunyuan", "HYV4ForCausalLM": "hy_v4", + "HYV4FlashForCausalLM": "hy_v4_flash", "IQuestCoderForCausalLM": "llama", "Inkling2ForCausalLM": "inkling2", "Inkling2LoopForCausalLM": "inkling2", @@ -307,6 +308,7 @@ "RWForCausalLM": "falcon", "RWKV6Qwen2ForCausalLM": "rwkv", "RWKV7ForCausalLM": "rwkv", + "Raon1MiniForCausalLM": "raon1_mini", "RobertaForSequenceClassification": "bert", "RobertaModel": "bert", "RuGPT3XLForCausalLM": "gpt2", @@ -390,6 +392,8 @@ "GraniteSpeechPlusForConditionalGeneration": "granite", "HiggsAudio3Model": "higgs_audio", "HunYuanVLForConditionalGeneration": "hunyuan", + "HYV4FlashForCausalLM": "hy_v4_flash", + "HYV4FlashForConditionalGeneration": "hy_v4_flash", "Idefics3ForConditionalGeneration": "smolvlm", "Inkling2ForConditionalGeneration": "inkling2", "Inkling2LoopForConditionalGeneration": "inkling2", diff --git a/conversion/base.py b/conversion/base.py index 540a66ba5098..f55d8560077d 100644 --- a/conversion/base.py +++ b/conversion/base.py @@ -2473,6 +2473,9 @@ def get_vocab_base_pre(self, tokenizer) -> str: if chkhsh == "32d85c31273f8019248f2559fed492d929ea28b17e51d81d3bb36fff23ca72b3": # ref: https://huggingface.co/domyn/Domyn-Edge-Teacher-IF res = "domyn-edge" + if chkhsh == "ffdae2f611dc6903980be2fbb108467cb97376d7d03cd332bb7e2602f87fa1f1": + # ref: https://huggingface.co/KRAFTON/Raon-1-mini-preview + res = "raon" if res is None: logger.warning("\n") diff --git a/conversion/hy_v4_flash.py b/conversion/hy_v4_flash.py new file mode 100644 index 000000000000..309b61b64e68 --- /dev/null +++ b/conversion/hy_v4_flash.py @@ -0,0 +1,650 @@ +from __future__ import annotations + +import json +from pathlib import Path +from typing import Callable, Iterable, cast + +import numpy as np +import torch + +from .base import LazyTorchTensor, MmprojModel, ModelBase, gguf, logger +from .deepseek41 import _StreamedBytes +from .hy_v4 import HYV4Model + +# the reference derives the hash multipliers from the Engram seed, the 1-based layer id and the compressed vocab size +ENGRAM_SEED_STRIDE = 10007 + + +@ModelBase.register("HYV4FlashForCausalLM", "HYV4FlashForConditionalGeneration") +@ModelBase.example("tencent/Hy4-Flash") +class HYV4FlashModel(HYV4Model): + """hy_v4 with sparse and sliding-window MLA layers, sandwich norms, latent routed experts, Engram and a k-pool indexer. + + The MTP draft block is exported as one extra sparse layer. The vision tower and the dfly draft layers are not converted. + """ + + model_arch = gguf.MODEL_ARCH.HY_V4_FLASH + + # the draft block is exported under block ids past the trunk, which skip_mtp would drop + skip_mtp = False + + # dropped subsystems, see the class docstring + DROP_PREFIXES = ("vit.", "model.dfly_layers.") + DROP_SUBSTRINGS = () + + # the released config renamed sparse_attention, both name the same layer type + SPARSE_TYPES = ("sparse_attention", "deepseek_sparse_attention") + + # the released checkpoints ship the token map as a tensor instead of engram_vocab_map.npz + ENGRAM_LOOKUP_TABLE = "lookup_table" + + # compressed_indexer tail -> the tensor the graph reads it as + INDEXER_MAP = { + "token_key_projection.weight": gguf.MODEL_TENSOR.INDEXER_ATTN_K, + "token_key_norm.weight": gguf.MODEL_TENSOR.INDEXER_K_NORM, + "key_value_projection.weight": gguf.MODEL_TENSOR.INDEXER_KPOOL_VALUE, + "key_gate_projection.weight": gguf.MODEL_TENSOR.INDEXER_KPOOL_GATE, + "intra_group_ape": gguf.MODEL_TENSOR.INDEXER_KPOOL_APE, + "key_norm.weight": gguf.MODEL_TENSOR.INDEXER_COMPRESSOR_NORM, + "query_projection.weight": gguf.MODEL_TENSOR.INDEXER_ATTN_Q_B, + "head_weight_projection.weight": gguf.MODEL_TENSOR.INDEXER_PROJ, + } + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # the draft block is an extra block, the loader subtracts the nextn count from block_count + if not getattr(self, "no_mtp", False): + self.block_count += self._n_nextn() + self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count) + # Engram weights arrive one at a time but are written fused, so they wait here + self._engram_buf: dict[int, dict[str, torch.Tensor]] = {} + self._engram_tables: dict[int, torch.Tensor] = {} + self._engram_done: set[str] = set() + + @classmethod + def filter_tensors(cls, item): + name = item[0] + if name.startswith(cls.DROP_PREFIXES) or any(s in name for s in cls.DROP_SUBSTRINGS): + return None + if name.startswith("model.mtp_layers."): + # hy_v4 drops the draft block; this model exports it, so skip that filter + return super(HYV4Model, cls).filter_tensors(item) + return super().filter_tensors(item) + + def _layer_types(self) -> list[str]: + cached = getattr(self, "_layer_types_cache", None) + if cached is not None: + return cached + layer_types = self.hparams.get("layer_types") + n_layer = self.hparams["num_hidden_layers"] + if not layer_types or len(layer_types) < n_layer: + raise ValueError("HY_V4_FLASH needs a layer_types entry per layer") + unknown = set(layer_types[:n_layer]) - set(self.SPARSE_TYPES) - {"sliding_attention"} + if unknown: + raise ValueError(f"HY_V4_FLASH unknown layer_types values: {sorted(unknown)}") + # the released config renamed the sparse layers, normalize so the rest reads one name + self._layer_types_cache = ["sparse_attention" if t in self.SPARSE_TYPES else t for t in layer_types[:n_layer]] + return self._layer_types_cache + + # Engram: one n-gram hash module per Engram layer, all buckets in one table as in deepseek41 + + def _engram_enabled(self) -> bool: + # engram_enable is optional, a False turns Engram off + return bool(self.hparams.get("engram_enable", True)) and bool(self.hparams.get("engram_layer_ids")) + + def _engram_ids(self) -> list[int]: + """engram_layer_ids, 1-based and sorted.""" + ids = sorted(int(i) for i in self.hparams["engram_layer_ids"]) + n_layer = self.hparams["num_hidden_layers"] + for i in ids: + # 1-based: the tensors live at model.layers.{i-1}.engram_layer.* + if not 1 <= i <= n_layer: + raise ValueError(f"HY_V4_FLASH engram_layer_ids has {i}, outside 1..{n_layer}") + return ids + + def _engram_primes(self) -> dict[int, list[int]]: + """Per 1-based layer id, the flattened [ngram][head] bucket counts.""" + raw = self.hparams.get("engram_layer_head_vocab_sizes") or {} + n_gram = self.hparams["engram_max_ngram_size"] + n_head = self.hparams["engram_n_head_per_ngram"] + out = {} + for i in self._engram_ids(): + # the keys are strings in the config + groups = raw.get(str(i)) or raw.get(i) + if groups is None: + raise ValueError(f"HY_V4_FLASH engram_layer_head_vocab_sizes has no entry for layer {i}") + if len(groups) != n_gram - 1 or any(len(g) != n_head for g in groups): + raise ValueError( + f"HY_V4_FLASH engram layer {i}: expected {n_gram - 1} groups of {n_head} bucket " + f"counts, got {[len(g) for g in groups]}") + out[i] = [int(p) for g in groups for p in g] + return out + + def _engram_lookup_names(self) -> list[str]: + """The lookup_table tensor of every Engram layer, empty when the checkpoint carries the npz instead.""" + names = [f"model.layers.{i - 1}.engram_layer.{self.ENGRAM_LOOKUP_TABLE}" for i in self._engram_ids()] + present = [n for n in names if n in self.model_tensors] + if present and len(present) != len(names): + raise ValueError(f"HY_V4_FLASH engram is missing the lookup table of {sorted(set(names) - set(present))}") + return present + + def _engram_vocab_map(self) -> tuple[list[int], int]: + """The token -> compressed id map, extended by identity as the reference does, and the compressed vocab size.""" + names = self._engram_lookup_names() + if names: + table = LazyTorchTensor.to_eager(self.model_tensors[names[0]]()).numpy().astype(np.int64) + for other in names[1:]: + if not np.array_equal(LazyTorchTensor.to_eager(self.model_tensors[other]()).numpy().astype(np.int64), table): + raise ValueError(f"HY_V4_FLASH engram lookup table of {other} differs from {names[0]}") + # the map is onto a dense id range from 0, so its largest id gives the compressed vocab size + compressed = int(table.max()) + 1 + if int(table.min()) != 0 or len(np.unique(table)) != compressed: + raise ValueError("HY_V4_FLASH engram lookup table is not a dense id range from 0, supply engram_vocab_map.npz") + else: + path = Path(self.dir_model) / "engram_vocab_map.npz" + if not path.is_file(): + raise FileNotFoundError(f"HY_V4_FLASH engram needs a lookup_table tensor or {path}") + with np.load(path) as z: + table = z["lookup_table"].astype(np.int64) + meta = json.loads(bytes(z["metadata"]).decode("utf-8").rstrip("\x00")) + + compressed = int(meta["compressed_vocab_size"]) + if int(table.max()) + 1 > compressed: + raise ValueError("HY_V4_FLASH engram lookup table exceeds its compressed vocab size") + if int(meta["engram_seed"]) != int(self.hparams.get("engram_seed", 0)): + raise ValueError("HY_V4_FLASH engram seed disagrees between the config and the vocab map") + + n_vocab = self.hparams["vocab_size"] + token_map = list(map(int, table)) + token_map += list(range(len(token_map), n_vocab)) + return token_map, compressed + + def _engram_multipliers(self, layer_id: int, compressed: int) -> list[int]: + seed = int(self.hparams.get("engram_seed", 0)) + n_gram = self.hparams["engram_max_ngram_size"] + bound = max(1, (np.iinfo(np.int64).max // compressed) // 2) + rng = np.random.default_rng(seed + ENGRAM_SEED_STRIDE * layer_id) + return [int(m) for m in rng.integers(0, bound, size=n_gram) * 2 + 1] + + def _engram_set_gguf_parameters(self): + hparams = self.hparams + ids = self._engram_ids() + primes = self._engram_primes() + token_map, compressed = self._engram_vocab_map() + + n_gram = hparams["engram_max_ngram_size"] + n_head = hparams["engram_n_head_per_ngram"] + head_dim, rem = divmod(hparams["engram_n_embed_per_ngram"], n_head) + if rem: + raise ValueError("HY_V4_FLASH engram_n_embed_per_ngram is not a multiple of the head count") + + # rebase each module's buckets into the shared table, row ids are int32 + offsets: list[int] = [] + multipliers: list[int] = [] + base = 0 + for i in ids: + for p in primes[i]: + offsets.append(base) + base += p + multipliers += self._engram_multipliers(i, compressed) + if base > np.iinfo(np.int32).max: + raise ValueError(f"HY_V4_FLASH engram table needs {base} rows, past the int32 row id limit") + + w = self.gguf_writer + w.add_ple_layers([i - 1 for i in ids]) + w.add_ple_ngram_size(n_gram) + w.add_ple_heads_per_ngram(n_head) + w.add_embedding_length_per_layer_input(head_dim) + w.add_ple_layer_multipliers(multipliers) + w.add_ple_head_offsets(offsets) + w.add_ple_head_vocab_sizes([p for i in ids for p in primes[i]]) + w.add_engram_pad_token_id(hparams["engram_pad_id"]) + w.add_engram_token_map(token_map) + + logger.info( + "HY_V4_FLASH engram: %d module(s) at 0-based layers %s, %d-gram x %d heads x %d dims, " + "%d table rows, compressed vocab %d", + len(ids), [i - 1 for i in ids], n_gram, n_head, head_dim, base, compressed) + + def _n_nextn(self) -> int: + return int(self.hparams.get("num_nextn_predict_layers", 0) or 0) + + def _layer_type_of(self, bid: int) -> str: + """Layer type of any block, draft blocks included. Only sparse draft blocks are supported.""" + n_layer = self.hparams["num_hidden_layers"] + if bid < n_layer: + return self._layer_types()[bid] + + types = self.hparams.get("mtp_layer_types") or [] + if not types: + return "sparse_attention" + + t = types[min(bid - n_layer, len(types) - 1)] + if t != "sparse_attention": + raise ValueError( + f"HY_V4_FLASH: mtp_layer_types gives {t!r} for draft block {bid}, " + "but only 'sparse_attention' draft blocks are supported") + return t + + def _write_rope_sections(self, sparse_rope: dict, window_rope: dict): + """Write the M-RoPE sections of the VL checkpoints. Text-only files keep the loader default.""" + sections = sparse_rope.get("mrope_section") + if sections is None: + return + if window_rope.get("mrope_section") != sections: + raise ValueError( + f"HY_V4_FLASH needs one mrope_section for both layer types, but " + f"{window_rope.get('mrope_section')} != {sections}") + if not sparse_rope.get("mrope_interleaved", False): + raise NotImplementedError("HY_V4_FLASH expects mrope_interleaved = true") + + rope_dim = self.hparams["qk_rope_head_dim"] + if len(sections) != 3 or 2 * sum(sections) != rope_dim: + raise ValueError(f"HY_V4_FLASH mrope_section {sections} must sum to qk_rope_head_dim / 2") + + self.gguf_writer.add_rope_dimension_sections(list(sections) + [0]) + + def _rope_for(self, layer_type: str) -> dict: + params = self.hparams.get("rope_parameters") + names = self.SPARSE_TYPES if layer_type == "sparse_attention" else (layer_type,) + found = [params[n] for n in names if isinstance(params, dict) and n in params] + if not found: + raise ValueError(f"HY_V4_FLASH needs rope_parameters[{layer_type!r}]") + if any(f != found[0] for f in found[1:]): + raise ValueError(f"HY_V4_FLASH has conflicting rope_parameters for {names}") + return found[0] + + def set_gguf_parameters(self): + hparams = self.hparams + layer_types = self._layer_types() + is_swa = [t == "sliding_attention" for t in layer_types] + + if not any(is_swa) or all(is_swa): + raise ValueError("HY_V4_FLASH expects a mix of sparse and sliding attention layers") + + # the graph always applies the sandwich post-norms + if not hparams.get("sandwich_norm", False): + raise ValueError("HY_V4_FLASH expects sandwich_norm, the graph always applies the post-norms") + if hparams.get("dsa_skip_attn_post_norm", False): + raise ValueError( + "HY_V4_FLASH: dsa_skip_attn_post_norm is not supported - the graph applies " + "attn_post_norm on the sparse layers too") + + # the non-sliding rope entry is keyed "sparse_attention", not "full_attention" as the base expects + sparse_rope = self._rope_for("sparse_attention") + window_rope = self._rope_for("sliding_attention") + + # hide the key from hy_v4, which warns that it drops the draft block + n_nextn = self.hparams.pop("num_nextn_predict_layers", None) + try: + super().set_gguf_parameters() + finally: + if n_nextn is not None: + self.hparams["num_nextn_predict_layers"] = n_nextn + + self.gguf_writer.add_rope_freq_base(sparse_rope["rope_theta"]) + + # the graph reorders the rope rows itself, so the sections only say how to split them + self._write_rope_sections(sparse_rope, window_rope) + + # per-layer head count: the window layers carry swa_num_attention_heads + n_head = hparams["num_attention_heads"] + n_head_swa = hparams["swa_num_attention_heads"] + self.gguf_writer.remove_key( + gguf.Keys.Attention.HEAD_COUNT.format(arch=self.gguf_writer.arch)) + # the arrays cover n_layer_all, the draft block is a sparse layer + is_swa_all = is_swa + [False] * (0 if getattr(self, "no_mtp", False) else self._n_nextn()) + self.gguf_writer.add_head_count( + [n_head_swa if swa else n_head for swa in is_swa_all]) + + # the base already derives rope.freq_base_swa from rope_parameters["sliding_attention"] + self.gguf_writer.add_sliding_window(hparams["sliding_window"]) + self.gguf_writer.add_sliding_window_pattern(is_swa_all) + + # routed experts run here, the router and the shared expert stay at hidden_size + latent = hparams.get("routed_expert_hidden_size") + if latent: + self.gguf_writer.add_expert_latent_length(latent) + + if self._n_nextn() and not getattr(self, "no_mtp", False): + self.gguf_writer.add_nextn_predict_layers(self._n_nextn()) + + if self._indexer_enabled(): + # the pool size is compress_ratio, and the current group is always kept + ratio = hparams["compressed_indexer_compress_ratio"] + self.gguf_writer.add_indexer_kpool(ratio) + self.gguf_writer.add_indexer_kpool_select_tail(True) + + # same check as the reference + group_topk = hparams.get("compressed_indexer_group_topk") + candidate = hparams.get("compressed_indexer_candidate_topk") + if group_topk and candidate and group_topk * ratio != candidate: + raise ValueError( + f"HY_V4_FLASH indexer: candidate_topk {candidate} != " + f"group_topk {group_topk} x compress_ratio {ratio}") + if hparams["index_topk"] % ratio: + raise ValueError( + f"HY_V4_FLASH indexer: index_topk {hparams['index_topk']} is not a multiple " + f"of compress_ratio {ratio}") + is_full = self.indexer_is_full() or [] + logger.info( + "HY_V4_FLASH indexer: %d pooled groups of %d, keeping the best %d plus the current group (index_topk %d)", + sum(is_full), ratio, hparams["index_topk"] // ratio, hparams["index_topk"]) + + if self._engram_enabled(): + self._engram_set_gguf_parameters() + + self._check_mla_geometry() + + logger.info( + "HY_V4_FLASH: %d sparse (%d heads, rope_theta %g) + %d sliding " + "(%d heads, rope_theta %g, window %d) layers", + is_swa.count(False), n_head, sparse_rope["rope_theta"], + is_swa.count(True), n_head_swa, window_rope["rope_theta"], + hparams["sliding_window"], + ) + if hparams.get("engram_layer_ids") and not self._engram_enabled(): + logger.warning( + "HY_V4_FLASH: engram_enable is off, dropping %d Engram layer(s)", + len(hparams["engram_layer_ids"])) + if hparams.get("use_compressed_indexer") and not self._indexer_enabled(): + logger.warning( + "HY_V4_FLASH: dropping the compressed indexer - the sparse layers will " + "attend their whole context instead of the top %s tokens", + hparams.get("index_topk"), + ) + + def _check_mla_geometry(self): + """Both layer types must share one MLA geometry, only the head count may differ.""" + hparams = self.hparams + for sparse_key, window_key in ( + ("qk_nope_head_dim", "swa_qk_nope_head_dim"), + ("qk_rope_head_dim", "swa_qk_rope_head_dim"), + ("v_head_dim", "swa_v_head_dim"), + ("qk_head_dim", "swa_qk_head_dim"), + ("kv_lora_rank", "swa_kv_lora_rank"), + ): + if window_key not in hparams: + continue + if hparams[window_key] != hparams[sparse_key]: + raise NotImplementedError( + f"HY_V4_FLASH needs one MLA geometry for both layer types, but " + f"{window_key}={hparams[window_key]} != {sparse_key}={hparams[sparse_key]}" + ) + + def _indexer_enabled(self) -> bool: + return bool(self.hparams.get("use_dsa")) and bool(self.hparams.get("use_compressed_indexer")) + + def indexer_is_full(self) -> list[bool] | None: + """Which layers own a k-pool indexer: the sparse ones. The config indexer_types marks every layer.""" + if not self._indexer_enabled(): + return None + n_all = self.hparams["num_hidden_layers"] + self._n_nextn() + return [self._layer_type_of(i) == "sparse_attention" for i in range(n_all)] + + def prepare_tensors(self): + """Check the compressed_indexer tensors instead of hy_v4's self_attn.indexer ones.""" + self.hparams["num_key_value_heads"] = self.hparams["num_attention_heads"] + + is_full = self.indexer_is_full() + if is_full is not None: + want = set(self.INDEXER_MAP) + n_layer = self.hparams["num_hidden_layers"] + present: dict[int, set[str]] = {} + for name in self.model_tensors: + head, sep, tail = name.partition(".self_attn.compressed_indexer.") + if not sep: + continue + # the draft block carries its own indexer, under a different prefix + if head.startswith("model.layers."): + present.setdefault(int(head.split(".")[2]), set()).add(tail) + elif head.startswith("model.mtp_layers."): + present.setdefault(n_layer + int(head.split(".")[2]), set()).add(tail) + for il, expect in enumerate(is_full): + seen = present.get(il, set()) + if expect and seen != want: + raise ValueError( + f"HY_V4_FLASH layer {il} owns an indexer but is missing " + f"{sorted(want - seen)}" + (f" and carries unexpected {sorted(seen - want)}" + if seen - want else "")) + if not expect and seen: + raise ValueError( + f"HY_V4_FLASH layer {il} owns no indexer but carries {sorted(seen)}") + + # straight to the grandparent: hy_v4's own validation does not apply here + super(HYV4Model, self).prepare_tensors() + + if self._engram_enabled(): + T = gguf.MODEL_TENSOR + want = {self.format_tensor_name(T.PER_LAYER_TOKEN_EMBD)} + for i in self._engram_ids(): + for t in (T.ENGRAM_KV, T.ENGRAM_KV_B, T.ENGRAM_GATE, T.ENGRAM_LOOKUP_NORM, T.ENGRAM_HC_SCALE, T.ENGRAM_PRE_GAMMA): + want.add(self.format_tensor_name(t, i - 1)) + if want - self._engram_done: + raise ValueError(f"HY_V4_FLASH: incomplete Engram tensors {sorted(want - self._engram_done)}") + + def tensor_force_quant(self, name: str, new_name: str, bid: int | None, n_dims: int): + # ggml_add / ggml_mul operands, kept f32 as deepseek41 does for engram_gate + if new_name.endswith((".engram_gate.weight", ".engram_kv_b.weight", ".engram_hc_scale.weight")): + return gguf.GGMLQuantizationType.F32 + # the pooled-key position bias is a ggml_add operand too + if new_name.endswith(".indexer_compressor_ape.weight"): + return gguf.GGMLQuantizationType.F32 + # the base rule misses the router of the renumbered draft block + if new_name.endswith((".ffn_gate_inp.weight", ".ffn_gate_inp_shexp.weight")): + return gguf.GGMLQuantizationType.F32 + return super().tensor_force_quant(name, new_name, bid, n_dims) + + def _engram_modify(self, data_torch: torch.Tensor, name: str, + bid: int | None) -> Iterable[tuple[str, torch.Tensor]]: + """Fuse a layer's Engram weights as deepseek41 does, once all parts of a group arrived.""" + if bid is None: + raise ValueError(f"HY_V4_FLASH: engram tensor without a layer id: {name}") + + hc = self.hparams["hc_mult"] + n_head = self.hparams["engram_n_head_per_ngram"] * (self.hparams["engram_max_ngram_size"] - 1) + + tail = name.split(".engram_layer.", 1)[1] + if tail == self.ENGRAM_LOOKUP_TABLE: + # the token map, read through _engram_vocab_map() and written as GGUF metadata + return + + buf = self._engram_buf.setdefault(bid, {}) + buf[tail] = data_torch + + tn = self.format_tensor_name + T = gguf.MODEL_TENSOR + + def ready(*names) -> bool: + return all(n in buf for n in names) + + def take(*names): + return [buf.pop(n) for n in names] + + # hc key projections then the value projection, the order the graph views assume + kv_parts = [f"key_projs.{c}.weight" for c in range(hc)] + ["value_proj.weight"] + if ready(*kv_parts): + yield tn(T.ENGRAM_KV, bid), torch.cat(take(*kv_parts), dim=0) + + kvb_parts = [f"key_projs.{c}.bias" for c in range(hc)] + ["value_proj.bias"] + if ready(*kvb_parts): + yield tn(T.ENGRAM_KV_B, bid), torch.stack(take(*kvb_parts), dim=0) + + # engram_gate folds the key and query norms, as deepseek41 does + gate_parts = [f"norm_key.{c}.weight" for c in range(hc)] + [f"norm_query.{c}.weight" for c in range(hc)] + if ready(*gate_parts): + parts = take(*gate_parts) + yield tn(T.ENGRAM_GATE, bid), torch.stack( + [parts[c] * parts[hc + c] for c in range(hc)], dim=0) + + norm_parts = [f"lookup_per_head_norms.{c}.weight" for c in range(n_head)] + if ready(*norm_parts): + yield tn(T.ENGRAM_LOOKUP_NORM, bid), torch.stack(take(*norm_parts), dim=0) + + scale_parts = [f"unified_per_hc_scales.{c}" for c in range(hc)] + if ready(*scale_parts): + yield tn(T.ENGRAM_HC_SCALE, bid), torch.stack(take(*scale_parts), dim=0) + + if ready("unified_pre_gamma"): + yield tn(T.ENGRAM_PRE_GAMMA, bid), take("unified_pre_gamma")[0] + + # the tables of all modules are concatenated in layer order + if ready("multi_head_embedding.embedding.weight"): + self._engram_tables[bid] = take("multi_head_embedding.embedding.weight")[0] + want = [i - 1 for i in self._engram_ids()] + if all(i in self._engram_tables for i in want): + self._write_engram_tables([self._engram_tables.pop(i) for i in want]) + + def _write_engram_tables(self, tables: list[torch.Tensor]) -> None: + # the concatenated tables are ~127 GB in BF16, so they are streamed one table at a time as deepseek41 does + f32 = self.ftype == gguf.LlamaFileType.ALL_F32 + dim = tables[0].shape[1] + if any(t.shape[1] != dim for t in tables): + raise ValueError("HY_V4_FLASH engram tables differ in width") + n_rows = sum(t.shape[0] for t in tables) + + def chunks() -> Iterable[np.ndarray]: + while tables: + table = LazyTorchTensor.to_eager(tables.pop(0)) + for r0 in range(0, table.shape[0], 1 << 18): + # a copy, so that no chunk still held by the writer keeps the whole table alive + rows = (table[r0:r0 + (1 << 18)].float() if f32 else table[r0:r0 + (1 << 18)].bfloat16()).clone() + yield rows.view(torch.uint8).numpy() + del table, rows + + qt = gguf.GGMLQuantizationType.F32 if f32 else gguf.GGMLQuantizationType.BF16 + data = cast(np.ndarray, _StreamedBytes((n_rows, dim * (4 if f32 else 2)), chunks)) + name = self.format_tensor_name(gguf.MODEL_TENSOR.PER_LAYER_TOKEN_EMBD) + self.gguf_writer.add_tensor(name, data, raw_dtype=qt) + self._engram_done.add(name) + + NEXTN_MAP = { + "eh_proj.weight": gguf.MODEL_TENSOR.NEXTN_EH_PROJ, + "enorm.weight": gguf.MODEL_TENSOR.NEXTN_ENORM, + "hnorm.weight": gguf.MODEL_TENSOR.NEXTN_HNORM, + "final_layernorm.weight": gguf.MODEL_TENSOR.NEXTN_SHARED_HEAD_NORM, + } + + def modify_tensors(self, data_torch: torch.Tensor, name: str, bid: int | None) -> Iterable[tuple[str, torch.Tensor]]: + if name.startswith("model.mtp_layers."): + if not self._n_nextn() or getattr(self, "no_mtp", False): + return + parts = name.split(".", 3) + nbid = self.hparams["num_hidden_layers"] + int(parts[2]) + tail = parts[3] + key = self.NEXTN_MAP.get(tail) + if key is not None: + yield self.format_tensor_name(key, nbid), data_torch + return + # the rest of the block is an ordinary sparse layer, so re-enter under its block index + yield from self.modify_tensors(data_torch, f"model.layers.{nbid}.{tail}", nbid) + return + + if ".compressed_indexer." in name: + # dropped when the indexer is off, the sparse layers then attend their whole context + if not self._indexer_enabled(): + return + tail = name.split(".compressed_indexer.", 1)[1] + key = self.INDEXER_MAP.get(tail) + if key is None: + raise ValueError(f"HY_V4_FLASH: unmapped compressed_indexer tensor {name}") + # intra_group_ape [kpool, head_dim] is already ne (head_dim, kpool) + yield self.format_tensor_name(key, bid), data_torch + return + + if ".engram_layer." in name: + if not self._engram_enabled(): + return + for new_name, t in self._engram_modify(data_torch, name, bid): + self._engram_done.add(new_name) + yield new_name, t + return + + # split kv_b_proj with the head count of this layer, the base uses a global one + if name.endswith("kv_b_proj.weight") and bid is not None: + hparams = self.hparams + n_head = (hparams["swa_num_attention_heads"] + if self._layer_type_of(bid) == "sliding_attention" + else hparams["num_attention_heads"]) + v_head_dim = hparams["v_head_dim"] + qk_nope_head_dim = hparams["qk_nope_head_dim"] + + expected = n_head * (v_head_dim + qk_nope_head_dim) + if data_torch.shape[0] != expected: + raise ValueError( + f"HY_V4_FLASH layer {bid}: {name} has {data_torch.shape[0]} rows, " + f"expected {expected} = {n_head} heads x ({qk_nope_head_dim} + {v_head_dim})" + ) + + kv_b = data_torch.view(n_head, qk_nope_head_dim + v_head_dim, data_torch.shape[-1]) + k_b, v_b = torch.split(kv_b, [qk_nope_head_dim, v_head_dim], dim=1) + k_b = k_b.transpose(1, 2) + + tn = self.format_tensor_name + yield from ModelBase.modify_tensors(self, k_b, tn(gguf.MODEL_TENSOR.ATTN_K_B, bid), bid) + yield from ModelBase.modify_tensors(self, v_b, tn(gguf.MODEL_TENSOR.ATTN_V_B, bid), bid) + return + + yield from super().modify_tensors(data_torch, name, bid) + + +@ModelBase.register("HYV4FlashForCausalLM", "HYV4FlashForConditionalGeneration") +class HYV4FlashVisionModel(MmprojModel): + """Vision tower of HY_V4_FLASH: a SigLIP-shaped encoder with a rmsnorm_mlp_adapter projector. + + Positions come from a learned grid, resampled to the patch grid. The projector merges 2x2 patches with a strided conv2d, runs a 1x1 conv2d and appends a newline embedding to every row. + """ + + projector_type = gguf.VisionProjectorType.HY_V4_FLASH + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + assert self.hparams_vision is not None + # there is no image_size, the position-embedding grid is max_image_size / patch_size + self.hparams_vision["image_size"] = self.hparams_vision.get("max_image_size", 2048) + + def set_gguf_parameters(self): + super().set_gguf_parameters() + assert self.hparams_vision is not None + vcfg = self.hparams_vision + projector_type = vcfg.get("projector_type") + if projector_type != "rmsnorm_mlp_adapter": + raise ValueError(f"unsupported projector_type {projector_type!r}") + # the graph implements the plain variant only + unsupported = { + "use_2d_rope": bool(vcfg.get("use_2d_rope", False)), + "cat_extra_token": bool(vcfg.get("cat_extra_token", False)), + "use_image_newline_token": not vcfg.get("use_image_newline_token", True), + "perceive_post_norm": bool(vcfg.get("perceive_post_norm", False)), + "hidden_act": vcfg.get("hidden_act", "gelu") != "gelu", + "interpolate_mode": vcfg.get("interpolate_mode", "bilinear") != "bilinear", + } + for key, bad in unsupported.items(): + if bad: + raise NotImplementedError(f"HY_V4_FLASH vision config {key}={vcfg.get(key)!r} is not supported") + self.gguf_writer.add_clip_projector_type(self.projector_type) + self.gguf_writer.add_vision_use_gelu(True) + # rms_norm_eps is also the LayerNorm eps of the encoder blocks + self.gguf_writer.add_vision_attention_layernorm_eps(vcfg.get("rms_norm_eps", 1e-5)) + self.gguf_writer.add_vision_spatial_merge_size(vcfg.get("spatial_merge_size", 2)) + self.gguf_writer.add_vision_min_pixels(int(self.preprocessor_config["min_pixels"])) + self.gguf_writer.add_vision_max_pixels(int(self.preprocessor_config["max_pixels"])) + + @classmethod + def filter_tensors(cls, item: tuple[str, Callable[[], torch.Tensor]]) -> tuple[str, Callable[[], torch.Tensor]] | None: + if not item[0].startswith("vit."): + return None + + return super().filter_tensors(item) + + def modify_tensors(self, data_torch: torch.Tensor, name: str, bid: int | None) -> Iterable[tuple[str, torch.Tensor]]: + # row 0 of the position embedding is an unused CLS slot, the reference resamples rows 1: + if "position_embedding" in name: + data_torch = data_torch[1:] + yield from super().modify_tensors(data_torch, name, bid) + + def tensor_force_quant(self, name, new_name, bid, n_dims): + # conv weights in F32 or F16, BF16 IM2COL is not supported on Metal + if ("mm.0." in new_name or "mm.2." in new_name) and new_name.endswith(".weight"): + return gguf.GGMLQuantizationType.F16 if self.ftype == gguf.LlamaFileType.MOSTLY_F16 else gguf.GGMLQuantizationType.F32 + return super().tensor_force_quant(name, new_name, bid, n_dims) diff --git a/conversion/inkling2.py b/conversion/inkling2.py index 16f030619bca..3b4b140e37ff 100644 --- a/conversion/inkling2.py +++ b/conversion/inkling2.py @@ -248,6 +248,12 @@ def tensor_force_quant(self, name: str, new_name: str, bid: int | None, n_dims: 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]]: + # PEFT names the wrapped projections (self_attn.k_proj.linear.weight) and the attention + # output gate (self_attn.o_proj.gate_proj.weight); neither is in the tensor map. + name = name.replace(".linear.", ".") + if name.endswith(".o_proj.gate_proj.weight"): + yield self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_GATE, bid), data_torch + return if name in self._packed_experts: target = name.replace(".w13_weight", ".gate_up_proj").replace(".w2_weight", ".down_proj") yield self.map_tensor_name(target, try_suffixes=()) + ".weight", cast("Tensor", self._packed_experts[name]) diff --git a/conversion/qwen.py b/conversion/qwen.py index 376535460a2c..836d1f3dc855 100644 --- a/conversion/qwen.py +++ b/conversion/qwen.py @@ -868,6 +868,22 @@ class Qwen3_5MoeTextModel(_Qwen35MRopeMixin, _LinearAttentionVReorderBase): class DFlashModel(Qwen3Model): model_arch = gguf.MODEL_ARCH.DFLASH + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._target_is_inkling2 = False + if self.target_model_dir is not None: + target_hparams = ModelBase.load_hparams(self.target_model_dir, False) + self._target_is_inkling2 = get_model_architecture(target_hparams, ModelType.TEXT).startswith("Inkling2") + if self._target_is_inkling2: + # the target GGUF keeps only the tokenizer rows of the padded vocab + target_hparams = {**target_hparams, **target_hparams.get("text_config", {})} + self.hparams["vocab_size"] = target_hparams["unpadded_vocab_size"] + self.hparams["eos_token_id"] = target_hparams["eos_token_id"] + # the loop core runs num_passes times, other looping targets need their own visit count + self._target_n_visits = target_hparams["num_hidden_layers"] + if (loop := target_hparams.get("loop_config")) is not None: + self._target_n_visits += (loop["num_passes"] - 1) * (loop["core_end"] - loop["core_start"]) + def set_vocab(self): if self.target_model_dir is None: raise ValueError( @@ -917,6 +933,11 @@ def set_gguf_parameters(self): self.gguf_writer.add_conv_group_size(int(dflash_config["conv_group_size"])) self.gguf_writer.add_selector_rank(int(dflash_config["selector_rank"])) self.gguf_writer.add_selector_top_k(int(dflash_config["selector_top_k"])) + softcap_mode = dflash_config.get("selector_softcap_mode", "before_correction") + if softcap_mode not in ("before_correction", "after_correction"): + raise ValueError(f"DFlash2: unknown selector_softcap_mode {softcap_mode!r}") + if softcap_mode == "after_correction": + self.gguf_writer.add_selector_softcap_after_correction(True) output_multiplier = dflash_config.get( "output_multiplier", self.hparams.get("output_multiplier") @@ -942,7 +963,10 @@ def set_gguf_parameters(self): target_layer_ids = dflash_config.get("target_layer_ids", self.hparams.get("target_layer_ids", [])) if target_layer_ids: - extract_layer_ids = [i + 1 for i in target_layer_ids] + # Inkling ids count loop visits, the last one is the final norm output + if self._target_is_inkling2 and target_layer_ids[-1] != self._target_n_visits: + raise ValueError(f"Inkling2 DFlash2: target_layer_ids {target_layer_ids} must end at the Inkling final norm ({self._target_n_visits})") + extract_layer_ids = target_layer_ids if self._target_is_inkling2 else [i + 1 for i in target_layer_ids] self.gguf_writer.add_target_layers(extract_layer_ids) use_sliding_window = self.hparams.get("use_sliding_window", False) or dflash_config.get("use_swa", False) @@ -969,19 +993,6 @@ def set_gguf_parameters(self): def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]: yield from super().generate_extra_tensors() - mask_path = self.dir_model / "mask_embedding.pt" - if not mask_path.is_file(): - return - - mask = torch.load(mask_path, map_location="cpu", weights_only=True) - mask_id = self.hparams.get("dflash_config", {}).get("mask_token_id") - if mask_id is None or mask["mask_token_id"] != mask_id: - raise ValueError("mask_embedding.pt mask_token_id does not match dflash_config") - if tuple(mask["embedding"].shape) != (self.hparams["hidden_size"],): - raise ValueError("mask_embedding.pt has an unexpected embedding shape") - if not 0 <= mask_id < self.hparams["vocab_size"]: - raise ValueError("mask_embedding.pt mask_token_id is outside the vocabulary") - def target_tensor(name: str) -> Tensor: if self.target_model_dir is None: raise ValueError("mask_embedding.pt requires --target-model-dir with the target embeddings and output head") @@ -999,6 +1010,23 @@ def target_tensor(name: str) -> Tensor: return LazyTorchTensor.from_local_tensor(part[name]) raise ValueError(f"Target tensor {name!r} was not found in safetensors") + if self._target_is_inkling2: + # the draft borrows the raw target embeddings, Inkling norms them before its first layer + yield "model.embed_norm.weight", target_tensor("model.llm.embed_norm.weight") + + mask_path = self.dir_model / "mask_embedding.pt" + if not mask_path.is_file(): + return + + mask = torch.load(mask_path, map_location="cpu", weights_only=True) + mask_id = self.hparams.get("dflash_config", {}).get("mask_token_id") + if mask_id is None or mask["mask_token_id"] != mask_id: + raise ValueError("mask_embedding.pt mask_token_id does not match dflash_config") + if tuple(mask["embedding"].shape) != (self.hparams["hidden_size"],): + raise ValueError("mask_embedding.pt has an unexpected embedding shape") + if not 0 <= mask_id < self.hparams["vocab_size"]: + raise ValueError("mask_embedding.pt mask_token_id is outside the vocabulary") + embedding_name = "model.embed_tokens.weight" if embedding_name in self.model_tensors: embeddings = self.model_tensors.pop(embedding_name)() @@ -1061,6 +1089,8 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter "model.candidate_selector.predecessor_codebook", "model.candidate_selector.successor_codebook", ): + # padded vocabs (Inkling): the selector only indexes the draft vocab + data_torch = data_torch[:self.hparams["vocab_size"]] name += ".weight" yield from super().modify_tensors(data_torch, name, bid) diff --git a/conversion/raon1_mini.py b/conversion/raon1_mini.py new file mode 100644 index 000000000000..6a195766b84c --- /dev/null +++ b/conversion/raon1_mini.py @@ -0,0 +1,206 @@ +from __future__ import annotations + +from typing import Any, Callable, Iterable + +import torch +from torch import Tensor + +from .base import ModelBase, TextModel, gguf + + +_REQUIRED = object() + + +def _renamed_key(config: dict[str, Any], new: str, old: str, default: Any = _REQUIRED) -> Any: + # the HF config accepts the older spellings (kda_layers, mhc_*): null counts as absent, a conflicting pair is an error + values = [config[key] for key in (new, old) if config.get(key) is not None] + if len(values) == 2 and values[0] != values[1]: + raise ValueError(f"Raon-1 mini config has conflicting {new}={values[0]!r} and {old}={values[1]!r}") + if values: + return values[0] + if default is _REQUIRED: + raise KeyError(f"Raon-1 mini config needs {new} (or the older spelling {old})") + return default + + +def _rda_config(hp: dict[str, Any]) -> dict[str, Any]: + # rda_config is the current spelling; older exports use linear_attn_config with short_conv_kernel_size / use_full_rank_gate / full_attn_layers / kda_layers + if hp.get("rda_config") is not None and hp.get("linear_attn_config") is not None: + raise ValueError("Raon-1 mini config has both rda_config and the older linear_attn_config") + config = hp["rda_config"] if hp.get("rda_config") is not None else hp["linear_attn_config"] + result = { + "num_heads": config["num_heads"], + "head_dim": config["head_dim"], + "conv_kernel_size": _renamed_key(config, "conv_kernel_size", "short_conv_kernel_size"), + "full_rank_gate": _renamed_key(config, "full_rank_gate", "use_full_rank_gate"), + "mla_layers": _renamed_key(config, "mla_layers", "full_attn_layers"), + "rda_layers": _renamed_key(config, "rda_layers", "kda_layers"), + } + # absent and null differ here (see set_gguf_parameters), so the key is copied only when present + if "gate_lower_bound" in config: + result["gate_lower_bound"] = config["gate_lower_bound"] + return result + + +@ModelBase.register("Raon1MiniForCausalLM") +@ModelBase.example("KRAFTON/Raon-1-mini-preview") +class Raon1MiniModel(TextModel): + model_arch = gguf.MODEL_ARCH.RAON1_MINI + + # mHC sites: HF module name -> tensor prefix; each site has 10 parameters, packed into fn / base / scale + _MHC_SITES = (("self_attn_raon_mhc", "HC_ATTN"), ("mlp_raon_mhc", "HC_FFN")) + _MHC_PARTS = ("phi_pre", "phi_post", "res.phi_z", "b_pre", "b_post", "res.b_z", + "alpha_pre", "alpha_post", "res.alpha_z", "res.eta") + # Keep these tensors at F16 for direct conversion to Q8_0, TQ1_0 or TQ2_0. + _KEEP_UNQUANTIZED = ("hc_attn_fn", "hc_ffn_fn", "ssm_f_a", "ssm_f_b", "ssm_beta", "ssm_rda") + _KEEP_UNQUANTIZED_Q8_0 = ("attn_kv_a_mqa", "attn_k_b", "attn_v_b") + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._experts: dict[tuple[int, str], dict[int, Tensor]] = {} + self._mhc: dict[tuple[int, str], dict[str, Tensor]] = {} + self._rda_layers = set(_rda_config(self.hparams)["rda_layers"]) + + def filter_tensors(self, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: + filtered = super().filter_tensors(item) + if filtered is None: + return None + + name, _ = filtered + if name.startswith("model.layers."): + layer = name.split(".", 3)[2] + # MTP layers follow the main model layers. + if layer.isdecimal() and int(layer) >= self.hparams["num_hidden_layers"]: + return None + + return filtered + + def set_gguf_parameters(self): + hp = self.hparams + rda_config = _rda_config(hp) + n_layer = hp["num_hidden_layers"] + # 1-based layer ids, as in the HF config (is_rda_layer: layer_idx + 1 in rda_layers) + rda = self._rda_layers + mla = set(rda_config["mla_layers"]) + if rda & mla or rda | mla != set(range(1, n_layer + 1)): + raise ValueError("Raon-1 mini attention layer lists must partition all layers") + # the hybrid memory needs both layer kinds + if not rda or not mla: + raise ValueError("Raon-1 mini needs at least one RDA (rda_layers) and one MLA (mla_layers) layer") + if hp.get("tie_word_embeddings"): + raise ValueError("Raon-1 mini with tie_word_embeddings is not supported (the released model has a separate lm_head)") + if (not hp["mla_use_nope"] or not hp["mla_use_output_gate"] + or not rda_config["full_rank_gate"] or hp["hidden_act"] != "situ" + or hp["moe_router_activation_func"] != "sigmoid" + or hp.get("use_grouped_topk") or hp.get("routed_expert_hidden_size") + or hp.get("attn_res_block_size") or hp["moe_layer_freq"] != 1): + raise ValueError("Unsupported Raon-1 mini architecture variant") + if rda_config["num_heads"] != hp["num_attention_heads"]: + raise ValueError("Raon-1 mini RDA and MLA head counts must match") + + super().set_gguf_parameters() + self.gguf_writer.add_vocab_size(hp["vocab_size"]) + self.gguf_writer.add_head_count_kv([0 if i + 1 in rda else 1 for i in range(n_layer)]) + self.gguf_writer.add_ssm_conv_kernel(rda_config["conv_kernel_size"]) + # the .get() defaults below are the HF config defaults + self.gguf_writer.add_ssm_time_step_rank(_renamed_key(hp, "rda_decay_rank", "kda_decay_rank", 128)) + self.gguf_writer.add_kda_head_dim(rda_config["head_dim"]) + # HF uses -5.0 when the key is absent; an explicit null selects the unbounded gate + if (bound := rda_config.get("gate_lower_bound", -5.0)) is not None: + self.gguf_writer.add_kda_gate_lower_bound(bound) + self.gguf_writer.add_q_lora_rank(hp["q_lora_rank"]) + self.gguf_writer.add_kv_lora_rank(hp["kv_lora_rank"]) + self.gguf_writer.add_rope_dimension_count(hp["qk_rope_head_dim"]) + self.gguf_writer.add_key_length(hp["kv_lora_rank"] + hp["qk_rope_head_dim"]) + self.gguf_writer.add_value_length(hp["kv_lora_rank"]) + self.gguf_writer.add_key_length_mla(hp["qk_nope_head_dim"] + hp["qk_rope_head_dim"]) + self.gguf_writer.add_value_length_mla(hp["v_head_dim"]) + self.gguf_writer.add_latent_norm_rms_eps(hp.get("mla_latent_norm_eps", 1e-6)) + self.gguf_writer.add_expert_feed_forward_length(hp["moe_intermediate_size"]) + self.gguf_writer.add_expert_shared_count(hp["num_shared_experts"]) + self.gguf_writer.add_leading_dense_block_count(hp["first_k_dense_replace"]) + self.gguf_writer.add_expert_weights_scale(hp["routed_scaling_factor"]) + self.gguf_writer.add_expert_weights_norm(hp["moe_renormalize"]) + self.gguf_writer.add_activation_situ_beta(hp["activation_situ_beta"]) + self.gguf_writer.add_activation_situ_linear_beta(hp["activation_situ_linear_beta"]) + self.gguf_writer.add_hyper_connection_count(_renamed_key(hp, "raon_mhc_streams", "mhc_streams", 4)) + self.gguf_writer.add_hyper_connection_epsilon(_renamed_key(hp, "raon_mhc_selector_eps", "mhc_selector_eps", 1e-5)) + self.gguf_writer.add_hyper_connection_magnitude(_renamed_key(hp, "raon_mhc_post_factor", "mhc_post_factor", 2.0)) + + def prepare_tensors(self): + super().prepare_tensors() + if self._experts or self._mhc: + raise ValueError(f"Incomplete Raon-1 mini tensor groups: experts={list(self._experts)}, mHC={list(self._mhc)}") + + def tensor_force_quant(self, name, new_name, bid, n_dims): + if ".hc_" in new_name and not new_name.endswith("_fn.weight"): + return gguf.GGMLQuantizationType.F32 + quantized = (gguf.LlamaFileType.MOSTLY_Q8_0, gguf.LlamaFileType.MOSTLY_TQ1_0, gguf.LlamaFileType.MOSTLY_TQ2_0) + if self.ftype in quantized and new_name.startswith("blk."): + keep = self._KEEP_UNQUANTIZED + if self.ftype == gguf.LlamaFileType.MOSTLY_Q8_0: + keep += self._KEEP_UNQUANTIZED_Q8_0 + if new_name.split(".")[2] in keep: + return gguf.GGMLQuantizationType.F16 + 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]]: + for site, prefix in self._MHC_SITES: + marker = f".{site}." + if marker not in name: + continue + assert bid is not None + parts = self._mhc.setdefault((bid, site), {}) + suffix = name.split(marker, 1)[1] + if suffix in parts: + raise ValueError(f"Duplicate tensor {name}") + parts[suffix] = data_torch + if len(parts) < len(self._MHC_PARTS): + return + fn = torch.cat([parts[k] for k in ("phi_pre", "phi_post", "res.phi_z")]) + base = torch.cat([parts[k].float() for k in ("b_pre", "b_post", "res.b_z")]) + scale = torch.stack([parts[k].float().reshape(()) for k in ("alpha_pre", "alpha_post", "res.alpha_z", "res.eta")]) + for kind, tensor in (("FN", fn), ("BASE", base), ("SCALE", scale)): + yield from super().modify_tensors(tensor, self.format_tensor_name(getattr(gguf.MODEL_TENSOR, f"{prefix}_{kind}"), bid), bid) + del self._mhc[(bid, site)] + return + + # moe.experts.{e}.{gate,down,up}_proj; older exports: block_sparse_moe.experts.{e}.{w1,w2,w3} + if ".moe.experts." in name or ".block_sparse_moe.experts." in name: + assert bid is not None + tail = name.split(".experts.", 1)[1].split(".") + eid, wid = int(tail[0]), tail[1] + group = self._experts.setdefault((bid, wid), {}) + if eid in group or not 0 <= eid < self.hparams["num_experts"]: + raise ValueError(f"Invalid expert tensor {name}") + group[eid] = data_torch + if len(group) == self.hparams["num_experts"]: + tid = {"gate_proj": gguf.MODEL_TENSOR.FFN_GATE_EXP, "down_proj": gguf.MODEL_TENSOR.FFN_DOWN_EXP, + "up_proj": gguf.MODEL_TENSOR.FFN_UP_EXP, "w1": gguf.MODEL_TENSOR.FFN_GATE_EXP, + "w2": gguf.MODEL_TENSOR.FFN_DOWN_EXP, "w3": gguf.MODEL_TENSOR.FFN_UP_EXP}[wid] + yield from super().modify_tensors(torch.stack([group[i] for i in range(len(group))]), self.format_tensor_name(tid, bid), bid) + del self._experts[(bid, wid)] + return + + if name.endswith("kv_b_proj.weight"): + n_head = self.hparams["num_attention_heads"] + qk_nope_head_dim, v_head_dim = self.hparams["qk_nope_head_dim"], self.hparams["v_head_dim"] + kv_b = data_torch.reshape(n_head, qk_nope_head_dim + v_head_dim, self.hparams["kv_lora_rank"]) + k_b, v_b = torch.split(kv_b, [qk_nope_head_dim, v_head_dim], dim=1) + yield from super().modify_tensors(k_b.transpose(1, 2).contiguous(), name.replace("kv_b_proj", "k_b_proj"), bid) + yield from super().modify_tensors(v_b.contiguous(), name.replace("kv_b_proj", "v_b_proj"), bid) + return + if name.endswith(".self_attn.g_proj.weight"): + assert bid is not None + rda = bid + 1 in self._rda_layers + tid = gguf.MODEL_TENSOR.SSM_G if rda else gguf.MODEL_TENSOR.ATTN_GATE + yield self.format_tensor_name(tid, bid), data_torch + return + if name.endswith((".q_conv1d.weight", ".k_conv1d.weight", ".v_conv1d.weight")): + data_torch = data_torch.reshape(1, -1, 1, data_torch.shape[-1]) + if name.endswith(".A_log"): + data_torch = -torch.exp(data_torch.float()) + # dt_bias -> the name SSM_DT's mapping expects, as for qwen3next + if name.endswith(".dt_bias"): + name = name.removesuffix(".dt_bias") + ".dt_proj.bias" + yield from super().modify_tensors(data_torch, name, bid) diff --git a/convert_hf_to_gguf_update.py b/convert_hf_to_gguf_update.py index 91fb418a5f2d..0b623a7b0d26 100755 --- a/convert_hf_to_gguf_update.py +++ b/convert_hf_to_gguf_update.py @@ -169,6 +169,7 @@ class TOKENIZER_TYPE(IntEnum): {"name": "k2-horizon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/IFM/K2-Horizon-36B", }, {"name": "inkling2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/thinkingmachines/Inkling-2-Small", }, {"name": "domyn-edge", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/domyn/Domyn-Edge-Teacher-IF", }, + {"name": "raon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/KRAFTON/Raon-1-mini-preview", }, ] # some models are known to be broken upstream, so we will skip them as exceptions diff --git a/docs/backend/OPENCL.md b/docs/backend/OPENCL.md index c912d331cbc2..1f04e94ba008 100644 --- a/docs/backend/OPENCL.md +++ b/docs/backend/OPENCL.md @@ -318,6 +318,7 @@ ninja ## Known Issues +- Adreno E17 compiler workarounds are disabled by default. If you encounter Flash Attention compilation failures or incorrect MoE results, set `GGML_OPENCL_ADRENO_E17_QUIRKS=1` before starting llama.cpp. - Flash attention does not always improve performance. - Currently OpenCL backend works on A6xx GPUs with recent drivers and compilers (usually found in IoT platforms). However, it does not work on A6xx GPUs found in phones with old drivers and compilers. diff --git a/docs/backend/SYCL.md b/docs/backend/SYCL.md index 4a1d16aad703..84e12fd7128e 100644 --- a/docs/backend/SYCL.md +++ b/docs/backend/SYCL.md @@ -44,7 +44,7 @@ The following releases are verified and recommended: ### Ubuntu 24.04 -The release packages for Ubuntu 24.04 x64 (FP32/FP16) only include the binary files of the llama.cpp SYCL backend. They require the target machine to have pre-installed Intel GPU drivers and oneAPI packages that are the same version as the build package. To get the version and installation info, refer to [.github/workflows/release.yml#L713](../../.github/workflows/release.yml#L713): ubuntu-24-sycl -> Download & Install oneAPI. +The release packages for Ubuntu 24.04 x64 (FP32/FP16) only include the binary files of the llama.cpp SYCL backend. They require the target machine to have pre-installed Intel GPU drivers and oneAPI packages that are the same version as the build package. To get the version and installation info, refer to [.github/workflows/release.yml#1447](../../.github/workflows/release.yml#L1447): `ubuntu-24-sycl` -> `Download & Install oneAPI`. It is recommended to use them with [Intel Docker](https://hub.docker.com/r/intel/deep-learning-essentials). @@ -822,6 +822,7 @@ User can use the device management in [docs/multi-gpu.md](https://github.com/ggm | GGML_SYCL_MEMTRACE_STEP | 64 (default) or positive integer | With GGML_SYCL_MEMTRACE=1, the minimum growth in memory usage to trigger another log record. | | GGML_SYCL_MKL_FA_DIAG | 0 (default) or 1 | Enable output fingerprinting for MKL flash attention. Dumps the first 64 float output values for the first 6 FA calls with n_kv ≥ 1024, labeled with kernel type (MKL/TILE/VEC) for cross-kernel comparison. | | GGML_SYCL_ENABLE_FUSION | 0 or 1 (default) | Enable fused-kernel dispatch in graph compute. Unsupported types and layouts fall back to the standalone op kernels. See `ggml_sycl_can_fuse()`. | +| GGML_SYCL_FUSE_CONV_WINDOW | 0 or 1 (default) | Fuse four-tap recurrent convolution windows, rollback cache updates and SiLU into one kernel. Other shapes use the existing kernels. | | GGML_SYCL_ENABLE_ESIMD | 0 or 1 (default)| Enable ESIMD kernels when available. | | GGML_SYCL_ENABLE_XMX_ESIMD | 0 or 1 (default) | Use the XMX (DPAS) multi-column mat-vec kernels for reordered Q2_K to Q6_K and Q8_0 weights on Xe2 GPUs. Speeds up speculative decoding and short prompt batches. | | 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. | diff --git a/docs/backend/snapdragon/README.md b/docs/backend/snapdragon/README.md index bd970370591c..aea52a067040 100644 --- a/docs/backend/snapdragon/README.md +++ b/docs/backend/snapdragon/README.md @@ -304,6 +304,22 @@ Unlike host-level tensor-splitting, row-splitting is executed entirely inside th You can also combine row-splitting with layer-splitting across multiple grouped devices (e.g. `--devices 'HTP0[0-1],HTP1[2-3]'` on 4 physical NPUs, or `--devices 'HTP0[0-1:0],HTP1[0-1:1]'` on 2 physical NPUs using virtual sessions 0 and 1). +## Numerical Precision and End-to-End Accuracy + +By default, the Hexagon backend is tuned for higher NPU throughput and lower memory bandwidth while preserving strong +end-to-end accuracy across typical models. Specifically, batched matrix multiplications default to `W8A8` integer HMX +(`--hex-mm-select 3`), which dynamically quantizes activations into 8-bit (`uint8` x `int8`) blocks with a 2048-element +`K`-group scale (using HVX when `M <= 4`), +and internal `FP32` activation tensors within each HTP subgraph are automatically lowered in-place to `FP16` +(`--hex-oplower 1`). If a particular model or workload exhibits accuracy degradation (for example due to large activation +outliers or `FP16` residual overflow), try stepping down to higher-precision configurations in the following order: + +1. `--hex-mm-select 4 --hex-oplower 1`: pure `W8A8` INT HMX everywhere + internal `FP16` lowering (maximum prefill speed) +2. `--hex-mm-select 3 --hex-oplower 1` (default): hybrid `W8A8` INT HMX (FP16 HMX on post-GLU / `GGML_PREC_F32` projections) + internal `FP16` lowering +3. `--hex-mm-select 3 --hex-oplower 0`: hybrid `W8A8` INT HMX + `FP32` intermediate activations +4. `--hex-mm-select 2 --hex-oplower 1`: `FP16` HMX everywhere + internal `FP16` lowering +5. `--hex-mm-select 2 --hex-oplower 0`: `FP16` HMX everywhere + `FP32` intermediate activations + ## Environment variables - `GGML_HEXAGON_DEVICES` (default: not set, defaults to HTP0 session) @@ -398,3 +414,27 @@ on 4 physical NPUs, or `--devices 'HTP0[0-1:0],HTP1[0-1:1]'` on 2 physical NPUs # Disable ADD and SUB on Hexagon (fall back to CPU or GPU) ./scripts/snapdragon/run.py --target adb --hex-opfilter "ADD|SUB" -- llama-cli ... ``` + +- `GGML_HEXAGON_OPLOWER=N` + Controls internal FP32-to-FP16 activation tensor lowering inside HTP opbatches (configurable via `--hex-oplower` in `run.py`): + + - `0`: Disabled - keep internal activations in FP32 + - `1`: Enabled (default) - lower internal `FP32` activation tensors across the opbatch to `FP16` while respecting `GGML_PREC_F32` hints + +- `GGML_HEXAGON_MM_SELECT=N` + Selects the matrix multiplication engine on HTP (configurable via `--hex-mm-select` in `run.py`): + + - `0`: Disabled (falls back to CPU or GPU) + - `1`: HVX vector kernels only + - `2`: FP16 HMX matrix engine (`M > 4`) with HVX decode (`M <= 4`) + - `3`: Hybrid INT HMX `W8A8` (`uint8` activations x `int8` weights) with FP16 HMX fallback on post-GLU / `GGML_PREC_F32` projections and HVX decode (`M <= 4`) (default; automatically defaults to 2 on multi-session v73 hardware unless overridden) + - `4`: Pure INT HMX `W8A8` everywhere (`M > 4`) with HVX decode (`M <= 4`) + +- `GGML_HEXAGON_OPPOLL=N` + Controls host polling while waiting for HTP opbatch completion (configurable via `--hex-oppoll` in `run.py`): + + - `0`: Blocking wait (lowest host CPU usage) + - `1`: Full polling (keeps the host CPU awake for minimum wakeup latency; best for peak benchmarking and profiling) + - `> 1`: Hybrid polling budget in milliseconds - polls for up to `N` ms per opbatch before falling back to a blocking wait (default: `50` when supported by the FastRPC driver, `0` otherwise) + + The default (`50`) is tuned for general performance and thermal/power balance (covers decode batches while letting the CPU sleep during longer prefills). For benchmarking, consider more aggressive settings like `10`-`20` or `1` for full polling. diff --git a/docs/backend/snapdragon/developer.md b/docs/backend/snapdragon/developer.md index c220ad08a3ec..9602848c69ca 100644 --- a/docs/backend/snapdragon/developer.md +++ b/docs/backend/snapdragon/developer.md @@ -30,6 +30,10 @@ The Hexagon NPU backend takes advantage of Snapdragon unified memory where all D The NPU has dedicated tightly-coupled memory called VTCM (Vector Tightly-Coupled Memory). VTCM is used for intermediate data (such as dynamically quantized activations) and streaming buffers (chunks of weight and activation tensors fetched via DMA). +Both DDR and VTCM reserve trailing guard space so HVX kernels can issue full-width vector loads (`vmem` / `vmemu`) on tail elements without boundary branches: +- Shared DDR buffers pad allocations to 4 KB and append a 4 KB guard page. +- Usable VTCM (`htp_vtcm_usable_size`) reserves `HTP_VTCM_GUARD_SIZE` (128 bytes) at the end of the physical VTCM page. + ## Large model handling Hexagon NPU sessions have a 32-bit virtual address space window of around 3.5GB. @@ -72,34 +76,29 @@ For a weight matrix of logical shape `[ne0, ne1]` (where `ne0 = K`, `ne1 = N`): ### Block-32 Quantized Formats -Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`): +Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`). +Quants are stored in 4-K-grouped (`vrmpy`) byte order across 128-byte HVX vectors: +columns `k = 0..31` are split into 8 groups `g = k / 4` of 4 consecutive columns (`j = k % 4`), stored at `4 * row + j` within each vector. - **Q4_0** (576 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q4_0`): - - **Quants** (bytes 0..511, 512 bytes): + - **Quants** (bytes 0..511, 512 bytes, 4 HVX vectors `p = 0..3`): Contains 32 rows x 32 columns of 4-bit quants. - Divided into 16 column pairs `cp = 0..15` covering columns `2*cp` and `2*cp + 1`. - For each column pair `cp`, 32 bytes are stored consecutively for rows `row = 0..31`: - `tile[cp * 32 + row]` holds `(quant[row][2*cp + 1] << 4) | quant[row][2*cp]`. - Low nibble holds the even column; high nibble holds the odd column. + Vector `p` packs column group `2*p` in the low nibble and group `2*p + 1` in the high nibble: + `tile[p * 128 + row * 4 + j]` holds `(quant[row][8*p + 4 + j] << 4) | quant[row][8*p + j]` for `row = 0..31`, `j = 0..3`. - **Scales** (bytes 512..575, 64 bytes): 32 FP16 values (`ggml_half`), storing scale `d` for each row `row = 0..31`. - **Q8_0** (1088 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q8_0`): - - **Quants** (bytes 0..1023, 1024 bytes): + - **Quants** (bytes 0..1023, 1024 bytes, 8 HVX vectors `p = 0..7`): Contains 32 rows x 32 columns of signed 8-bit quants (`int8_t`). - Divided into 16 column pairs `cp = 0..15` covering columns `col0 = 2*cp` and `col1 = 2*cp + 1`. - For each column pair `cp`, 64 bytes store interleaved column elements for each row `row = 0..31`: - `tile[cp * 64 + 2 * row + 0] = quant[row][col0]` - `tile[cp * 64 + 2 * row + 1] = quant[row][col1]` + Vector `p` holds column group `p` (`k = 4*p .. 4*p + 3`): + `tile[p * 128 + row * 4 + j] = quant[row][4*p + j]` for `row = 0..31`, `j = 0..3`. - **Scales** (bytes 1024..1087, 64 bytes): 32 FP16 values (`ggml_half`), storing scale `d` for each row `row = 0..31`. - **IQ4_NL** (576 bytes per tile, `HTP_TENSOR_TILE_SIZE_IQ4_NL`): - **Quants** (bytes 0..511, 512 bytes): - Same nibble transposition and storage layout as `Q4_0`. - Contains 32 rows x 32 columns of non-linear 4-bit indices (values 0..15). - Divided into 16 column pairs `cp = 0..15`: - `tile[cp * 32 + row]` holds `(quant[row][2*cp + 1] << 4) | quant[row][2*cp]`. + Same 4-K-grouped nibble layout as `Q4_0`, storing 4-bit non-linear indices (values 0..15). - **Scales** (bytes 512..575, 64 bytes): 32 FP16 values (`ggml_half`), storing scale `d` for each row `row = 0..31`. - **Dequantization**: @@ -107,10 +106,7 @@ Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`): - **MXFP4** (544 bytes per tile, `HTP_TENSOR_TILE_SIZE_MXFP4`): - **Quants** (bytes 0..511, 512 bytes): - Same nibble transposition and storage layout as `Q4_0`. - Contains 32 rows x 32 columns of 4-bit OCP Microscaling FP4 (E2M1) values. - Divided into 16 column pairs `cp = 0..15`: - `tile[cp * 32 + row]` holds `(quant[row][2*cp + 1] << 4) | quant[row][2*cp]`. + Same 4-K-grouped nibble layout as `Q4_0`, storing 4-bit OCP Microscaling FP4 (E2M1) values. - **Scales** (bytes 512..543, 32 bytes): 32 unsigned 8-bit values (`uint8_t`), storing one 8-bit biased exponent (E8M0, bias 127) scale `e` per row `row = 0..31`. - **Dequantization**: @@ -119,26 +115,25 @@ Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`): - **NVFP4** (576 bytes per tile, `HTP_TENSOR_TILE_SIZE_NVFP4`, lossless tiling with same size as `block_nvfp4`): - A 64-element block spans 2 consecutive k-tiles; k-tile `h` holds sub-blocks `2h` and `2h+1`. - - **Quants** (bytes 0..511): same nibble transposition as `Q4_0`, holding E2M1 values in element order - (within a 16-element sub-block, `qs` byte `j` holds elements `j` and `j+8`). + - **Quants** (bytes 0..511, 4 HVX vectors): 4-K-grouped nibble layout per 16-element sub-block `u = 0..1` (`tile[(2*u + 0)*128 + row*4 + j]` holds low nibbles of `qs_sub[j]` and `qs_sub[4+j]`; `tile[(2*u + 1)*128 + row*4 + j]` holds high nibbles). - **Scales** (bytes 512..575): UE4M3 bytes, `tile[512 + 32*u + row]` for sub-block `u = 0..1` of the k-tile. - The per-tensor F32 scale is not part of the tile. - **Q4_1** (640 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q4_1`): - **Quants** (bytes 0..511, 512 bytes): - Same 4-bit nibble transposition and storage layout as `Q4_0`. + Same 4-K-grouped nibble layout as `Q4_0`. - **Scales** (bytes 512..639, 128 bytes): 32 pairs of FP16 values (`ggml_half`): `scale[2 * row + 0] = d` (scale) and `scale[2 * row + 1] = m` (min) for each row `row = 0..31`. - **Q5_0** (704 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q5_0`): - - **Quants** (bytes 0..511): same 4-bit nibble transposition and storage layout as `Q4_0`, holding the low 4 bits. - - **5th-bit plane** (bytes 512..639): byte `32*c + row` (`c = 0..3`) holds a flag for `k = 2*(4i + c)` at bit `2i` and for `k = 2*(4i + c) + 1` at bit `2i + 1`, for `i = 0..3`. The flag is set when the 5th bit of the quant is clear. + - **Quants** (bytes 0..511): same 4-K-grouped nibble layout as `Q4_0`, holding the low 4 bits. + - **5th-bit plane** (bytes 512..639, 1 HVX vector): 4-K-grouped; `plane[row * 4 + j]` (`j = 0..3`) holds a flag at bit `g` (`0..7`) for `k = 4*g + j`. The flag is set when the 5th bit of the quant is clear. - **Scales** (bytes 640..703, 64 bytes): 32 FP16 values, storing scale `d` for each row `row = 0..31`. - **Dequantization**: `0xF0` is OR-ed into the nibble where the flag is set, giving the signed value `q - 16` (-16..15), scaled by `d`. - **Q5_1** (768 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q5_1`, same layout as the Q5_K tile): - **Quants** (bytes 0..511) and **scales** (bytes 512..639): same as `Q4_1`, holding the low 4 bits and `(d, m)` pairs. - - **5th-bit plane** (bytes 640..767): same as `Q5_K`; a bit is set when the 5th bit of the quant is set. + - **5th-bit plane** (bytes 640..767, 1 HVX vector): 4-K-grouped; `plane[row * 4 + j]` (`j = 0..3`) holds bit `g` (`0..7`) for `k = 4*g + j`, set when the 5th bit of the quant is set. - Uses the `Q5_K` HVX/HMX kernels (Q8_1 activations with block sums). ### Q1_0 Format (1-Bit Quantization) @@ -209,12 +204,12 @@ Byte ordering: `Q2_K`, `Q3_K`, and `Q6_K` use `vrmpy` byte order within each 128 - `bytes 384..511` (vec 3): FP16 scales `d * (scales[] - 32)`: `fp16[0..31]` for k 0..15, `fp16[32..63]` for k 16..31. - **Q4_K** (640 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q4_K`, same layout as Q4_1 tile; each 256-k super-block splits into 8 tiles of 32 k): - - `bytes 0..511` (vec 0..3): 4-bit quants; byte `32*cp + r` holds `k = 2*cp` (low nibble) and `2*cp + 1` (high nibble). + - `bytes 0..511` (vec 0..3): 4-bit quants in 4-K-grouped order; `tile[p * 128 + row * 4 + j]` holds `k = 8*p + j` (low nibble) and `k = 8*p + 4 + j` (high nibble). - `bytes 512..639` (vec 4): 32x2 FP16 per row: `(d * sc, -dmin * m)`. - **Q5_K** (768 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q5_K`): - `bytes 0..639` (vec 0..4): Q4_K tile (low 4 bits + FP16 scale/min pairs). - - `bytes 640..767` (vec 5): 5th-bit plane; byte `l` holds the 8 high bits for lane `l` across vec `i = 0..3` (`bit 2i = lo, 2i+1 = hi`). + - `bytes 640..767` (vec 5): 5th-bit plane in 4-K-grouped order; `plane[row * 4 + j]` holds bit `g` (`0..7`) for `k = 4*g + j`. - **Q6_K** (896 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q6_K`): - `bytes 0..511` (vec 0..3): low 4 bits; vec `i` holds group `2i` (low nibble) and `2i+1` (high nibble). @@ -227,8 +222,9 @@ Writing high-performance operators for Hexagon requires following specific guide ### DDR -> DMA -> VTCM Execution Pipeline -- Strongly prefer the `DDR -> DMA -> VTCM -> compute (HVX/HMX) -> VTCM -> DMA -> DDR` data flow. -- Direct HVX reads/writes from/to DDR are less efficient and should only be used as a fallback. +- All operators must use the `DDR -> DMA -> VTCM -> compute (HVX/HMX) -> VTCM -> DMA -> DDR` data flow. +- **No direct reads or writes to `tensor->data`**: Do not dereference `tensor->data` pointers directly (scalar or HVX). All tensor transfers must go through DMA, because bypass DMA writes are not L1D/L2 coherent and tensors may reside in 40-bit extended address space. +- **Rare exception (small index/position tensors)**: For small metadata tensors that require scalar indexing (such as `ids`, `pos`, or row indices), use [`htp_tensor_read()`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h) to copy into a 128-byte aligned local DDR buffer (`ddr_spad_base` or stack). It handles extended addresses, arbitrary strides, and `dccleaninva` + `syncht` cache maintenance in one place. - Use `dma_addr_t` only for DMA base and final addresses. Form a final address by adding a 32-bit byte offset to a `dma_addr_t` tensor base address. This permits a 64-bit mapped base address on newer platforms while retaining 32-bit relative addressing. @@ -244,8 +240,12 @@ Writing high-performance operators for Hexagon requires following specific guide properly. Flushing is only used in rare exceptions where a batch of operations is pushed without individual pops. - Use the DMA queue interface from [`dma-queue.h`](../../../ggml/src/ggml-hexagon/htp/dma-queue.h) (`dma_queue_push()`, `dma_queue_pop()`, and `dma_queue_flush()`). - See [`cumsum-ops.c`](../../../ggml/src/ggml-hexagon/htp/cumsum-ops.c) and - [`act-ops.c`](../../../ggml/src/ggml-hexagon/htp/act-ops.c) for reference implementations. +- For new simple ops, prefer the generic double-buffered pipeline drivers in + [`dma-pipeline.h`](../../../ggml/src/ggml-hexagon/htp/dma-pipeline.h) (`dma_pipe_io_run`, `dma_pipe_in_run`, + `dma_pipe_out_run`), which use dummy pushes, `dma_queue_pop().src`/`.dst` slot recycling, and `dma_queue_flush()` + at the end of the op. See [`cumsum-ops.c`](../../../ggml/src/ggml-hexagon/htp/cumsum-ops.c), + [`diag-ops.c`](../../../ggml/src/ggml-hexagon/htp/diag-ops.c), and + [`pad-ops.c`](../../../ggml/src/ggml-hexagon/htp/pad-ops.c) for reference implementations. ### Avoid Scalar Reads and Writes to VTCM @@ -256,22 +256,22 @@ Writing high-performance operators for Hexagon requires following specific guide - Hexagon cores do not have hardware division instructions. - For recurring divisions across iterations or threads, use `fastdiv` from [`hex-fastdiv.h`](../../../ggml/src/ggml-hexagon/htp/hex-fastdiv.h) with precomputed divisors (such as - `octx->ctx->mdev.count_div` or `octx->n_threads_div`). + `octx->ctx->mdev.count_div` or `octx->n_hvx_div`). - Do not call `init_fastdiv_values()` for single-use divisions; use standard compiler division (`/`) instead. ### Host-Side Precomputation via `kernel_params` - Precompute tensor shapes, strides, scale conversions, tiling layouts, and validation checks on the host CPU during graph - preparation in [`ggml-hexagon.cpp`](../../../ggml/src/ggml-hexagon/ggml-hexagon.cpp). + preparation in [`htp-kparams.cpp`](../../../ggml/src/ggml-hexagon/htp-kparams.cpp). - Pack precomputed parameters into the operator's fixed `kernel_params` structure in `htp_op_node` (such as `htp_mm_kernel_params`, `htp_unary_kernel_params`, `htp_fa_kernel_params`, `htp_get_rows_kernel_params`). - The NPU executes directly using `octx->kernel_params` without redundant runtime metadata extraction or validation. - **Strict Host-Kernel Alignment**: - Verify that parameters calculated by the host CPU are strictly honored by the NPU kernel. - - Ensure the kernel does not ignore host-computed fields (for example, falling back to `octx->n_threads` instead of - using `kparams->n_threads`, or ignoring precomputed `tasks_per_thread` and chunk counts). + - Ensure the kernel does not ignore host-computed fields (for example, falling back to `octx->n_hvx` instead of + using `kparams->n_hvx`, or ignoring precomputed `tasks_per_hvx` and chunk counts). - Both human developers and coding agents must audit both sides of the interface: ensure fields populated in `kernel_params` - in [`ggml-hexagon.cpp`](../../../ggml/src/ggml-hexagon/ggml-hexagon.cpp) are actively and consistently utilized by the + in [`htp-kparams.cpp`](../../../ggml/src/ggml-hexagon/htp-kparams.cpp) are actively and consistently utilized by the corresponding operator entry point and worker threads in `htp/*-ops.c`. ### Tracing Instrumentation @@ -292,7 +292,7 @@ Writing high-performance operators for Hexagon requires following specific guide - Distribute parallel work across NPU worker threads using the thread pool work queue: ```c - work_queue_run(ctx->work_queue, worker_func, &op_ctx, n_threads); + work_queue_run(ctx->hvx_queue, worker_func, &op_ctx, n_hvx); ``` - Keep worker functions independent and re-entrant. Worker threads should only operate on their designated chunk of rows or elements. @@ -307,6 +307,12 @@ Writing high-performance operators for Hexagon requires following specific guide - **Distinction**: `octx->src[N]` pointers *can* be NULL by design and must be checked when optional. Examples include attention masks, optional bias or weights in fused kernels, and frequency factors. +### Prefer Early Dispatch and Specialized Micro-Kernels + +- Avoid peppering micro-kernels, row or tile compute loops, or DMA worker loops with runtime checks for operand types, optional inputs, broadcast modes, or layout variants. +- Resolve execution variants early during operator setup (`op_*` / `execute_op_*`) via function pointers or dispatch tables so each micro-kernel and inner loop handles a single clean path that the compiler can unroll and software-pipeline without extra branch or register pressure. +- Prefer clean standalone specialized functions; use macros only to avoid genuine code duplication across type or mode instantiations. + ### `supports_op` Independence from Buffer and Repack State - `supports_op` (and op-specific checkers such as `supported_mul_mat()`, `supported_get_rows()`) runs during GGML graph scheduling **before** buffers are allocated and before tensor data is populated. @@ -319,6 +325,10 @@ Writing high-performance operators for Hexagon requires following specific guide - Repacking (converting weights to tiled layout) is an internal optimization applied during `set_tensor()` or rt-repack. Non-weight tensors or test harness tensors with the same type remain in flat layout. - Therefore, any supported type (such as BF16, F16, quantized types) must be supported both when repacked into tiles and when stored flat in memory. +### FP16 and Mixed-Precision Operator Support + +- New and updated Hexagon compute operators must support `F16` (and mixed `F16`/`F32` where applicable for graph lowering) across activation inputs and outputs, even when `ggml-cpu` only implements `F32`. + ### Multiline Macro Formatting - Keep trailing backslashes in multiline `#define` macros cleanly aligned to a consistent column. @@ -361,56 +371,37 @@ python3 scripts/snapdragon/ggml-hexagon-inspect.py --addr2line 0x51a30 0x5ba54 Multi-device (mdev) mode enables row-level tensor parallel execution across multiple physical NPU cores or virtual NPU sessions. -### 128-Byte Cache Line Alignment - -- Shared tensor buffers reside in DDR (RPCMEM) with a 128-byte cache line granularity - (`HEX_L2_LINE_SIZE` = 128 bytes, `HTP_TENSOR_MDEV_LINE_SIZE`). -- **Rule**: Multi-device work partitions that write directly to DDR through HVX/L2 must align destination write regions to - 128-byte cache line boundaries so distinct devices never share or overwrite the same cache line. -- DMA writes to DDR are not subject to this cache-line ownership rule. They may use smaller non-overlapping destination - ranges when the operator only writes through DMA. - -### Partitioning Helpers in `htp-tensor.h` +### Non-Overlapping Output Ranges -Common partitioning logic is factored into reusable inline helpers in -[`htp-tensor.h`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h): +- Because all DDR writes go through bypass DMA, multi-device partitions are **not** subject to 128-byte cache-line + alignment rules. +- Devices only need non-overlapping destination output ranges and any kernel-specific tile or vector granularity + (for example, 32 rows for tiled matmul or 128-byte vector chunks for flat 1D element-wise ops). -1. [`htp_tensor_mdev_rows_per_chunk`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L104): - Determines the minimum number of rows per chunk so that the chunk byte size is a multiple of 128 bytes: +### Partitioning Helper in `htp-tensor.h` - ``` - rows_per_chunk = 128 / hex_gcd_u32(row_size, 128) - ``` +Common partitioning logic is factored into [`htp_tensor_mdev_partition`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h) +in [`htp-tensor.h`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h): - If the active row and outer strides are already multiples of 128 bytes, `rows_per_chunk = 1`. - Returns `false` if the tensor cannot be safely row-partitioned (such as unaligned base pointer, permuted layout, - or non-128-byte aligned outer strides). - -2. [`htp_tensor_mdev_partition`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L131): - Calculates the per-device work range `struct htp_tensor_mdev_range { uint32_t start; uint32_t count; }` given - `total_units`, `units_per_chunk`, `mdev_idx`, `mdev_count`, and the precomputed `mdev_count_div`. - Handles chunk distribution across devices, assigns remainder units to the last device, and automatically triggers - single-device fallback when partitioning is unsafe. +- Calculates the per-device work range `struct htp_tensor_mdev_range { uint32_t start; uint32_t count; }` given + `total_units`, `units_per_chunk`, `mdev_idx`, `mdev_count`, and the precomputed `mdev_count_div`. +- Handles chunk distribution across devices, assigns remainder units to the last device, and automatically falls back + to Device 0 when `units_per_chunk == 0` or `total_units / units_per_chunk < mdev_count`. ### Row-Partitioned Operators -For row-wise operators that write directly to DDR -(such as activations in [`act-ops.c`](../../../ggml/src/ggml-hexagon/htp/act-ops.c), -binary ops in [`binary-ops.c`](../../../ggml/src/ggml-hexagon/htp/binary-ops.c), +For row-wise operators (such as binary ops in [`binary-ops.c`](../../../ggml/src/ggml-hexagon/htp/binary-ops.c) and unary ops in [`unary-ops.c`](../../../ggml/src/ggml-hexagon/htp/unary-ops.c)): ```c -const uint32_t total_rows = ne01 * ne02 * ne03; -const size_t dst_row_size = dst->ne[0] * elem_size; +const uint32_t total_rows = ne01 * ne02 * ne03; uint32_t row_start = 0; uint32_t nrows = total_rows; if (octx->ctx->mdev.count > 1) { - uint32_t rows_per_chunk = 0; - htp_tensor_mdev_rows_per_chunk(dst, elem_size, (uint32_t) dst_row_size, &rows_per_chunk); const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( - total_rows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + total_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); row_start = range.start; nrows = range.count; } @@ -422,24 +413,16 @@ if (nrows == 0) { ### Element-Partitioned Operators -For flat element-wise operations that write directly to DDR: -- Partition total linear elements N = ne0 * ne1 * ne2 * ne3 in 128-byte cache line chunks (`elems_per_line = (elem_size == 4) ? 32 : 64`). -- Requires strict 1D contiguity: - [`htp_tensor_is_contiguous(dst, elem_size)`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L65) - and 128-byte aligned destination pointer - [`htp_tensor_mdev_data_aligned(dst)`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L84). -- If contiguous and aligned, pass `elems_per_line` to - [`htp_tensor_mdev_partition`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L131); - otherwise pass 0 to trigger Device 0 fallback. +For flat 1D element-wise operations: +- Partition total linear elements `N = ne0 * ne1 * ne2 * ne3` in HVX vector-sized chunks (`elems_per_line = 128 / elem_size`). +- Requires 1D contiguity via [`htp_tensor_is_contiguous`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h); otherwise pass + `0` to trigger Device 0 fallback. ### Single-Device Fallback (Device 0) -- Fallback to Device 0 (`mdev.idx == 0`) when partitioning would cause cache line tearing or there are too few aligned chunks. -- Triggers: - 1. Destination tensor cannot be safely partitioned (`rows_per_chunk == 0` or non-contiguous/unaligned buffer). - 2. Total aligned chunks < `mdev_count`. +- Fallback to Device 0 (`mdev.idx == 0`) happens when `units_per_chunk == 0` or `total_chunks < mdev_count`. - Device 0 processes the entire tensor `[0, total_units)`. -- Devices 1 ... N-1 receive `count = 0` and return `HTP_STATUS_OK` immediately. +- Devices `1 ... N-1` receive `count = 0` and return `HTP_STATUS_OK` immediately. ### Flatten Outer Dimensions Globally @@ -494,10 +477,7 @@ Multi-device execution synchronizes worker sessions through atomic fence slots a (htp_mdev_group_barrier) (htp_mdev_group_barrier) | | Kernel Execution Kernel Execution - (Output Slice 0) (Output Slice 1) - | | - Tensor Cache Flush Tensor Cache Flush - (htp_dcache_flush_dirty_tensors) (htp_dcache_flush_dirty_tensors) + (Output Slice 0, via bypass DMA) (Output Slice 1, via bypass DMA) | | Post-Op/Batch Barrier ---------------------- Post-Op/Batch Barrier (htp_mdev_group_barrier) (htp_mdev_group_barrier) @@ -532,11 +512,8 @@ Multi-device execution synchronizes worker sessions through atomic fence slots a misaligned barrier arrivals across iterations. - If any peer reports an error status (`peer_status > HTP_STATUS_OK`), the barrier propagates the error and unblocks immediately. -### Tensor Cache Flush and Pipeline Completion +### Pipeline Completion -- In the kernel, ensure all pushed DMA operations have been popped in strict FIFO order to drain the queue. -- Use [`htp_dcache_flush_dirty_tensors()`](../../../ggml/src/ggml-hexagon/htp/htp-dcache.h) to flush specific dirty tensors back to DDR: - - [`htp_dcache_flush_dirty_tensors()`](../../../ggml/src/ggml-hexagon/htp/htp-dcache.h) flushes modified tensor address ranges, or the - full D-cache when their total size exceeds the flush threshold, ensuring peer devices and the host CPU observe consistent - data in DDR. -- Never signal completion before all DMA transfers are drained and dirty tensor flushes have completed. +- In the kernel, ensure all pushed DMA operations have been popped in strict FIFO order (or flushed via `dma_queue_flush()`) to drain the queue. +- Because all DDR writes use bypass DMA, no per-tensor output cache flush is needed. +- Never signal completion before all DMA transfers are drained. diff --git a/flake.nix b/flake.nix index 8b9fefec743e..c77c52267002 100644 --- a/flake.nix +++ b/flake.nix @@ -112,7 +112,6 @@ systems = [ "aarch64-darwin" "aarch64-linux" - "x86_64-darwin" # x86_64-darwin isn't tested (and likely isn't relevant) "x86_64-linux" ]; diff --git a/ggml/CMakeLists.txt b/ggml/CMakeLists.txt index 2970eebf1bcd..7f365b45250c 100644 --- a/ggml/CMakeLists.txt +++ b/ggml/CMakeLists.txt @@ -5,7 +5,7 @@ project("ggml" C CXX ASM) ### GGML Version set(GGML_VERSION_MAJOR 1) set(GGML_VERSION_MINOR 1) -set(GGML_VERSION_PATCH 0) +set(GGML_VERSION_PATCH 1) set(GGML_VERSION_BASE "${GGML_VERSION_MAJOR}.${GGML_VERSION_MINOR}.${GGML_VERSION_PATCH}") list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/") diff --git a/ggml/cmake/common.cmake b/ggml/cmake/common.cmake index c8d232294740..39c1fbb48982 100644 --- a/ggml/cmake/common.cmake +++ b/ggml/cmake/common.cmake @@ -56,8 +56,8 @@ function(ggml_get_system_arch) endif() endfunction() -# Determines which FlashAttention vector kernel template instances to compile, returns them in OUT_SRCS. -function(ggml_cuda_fattn_vec_instances DIR OUT_SRCS) +# Determines which FlashAttention kernel template instances to compile, returns them in OUT_SRCS. +function(ggml_cuda_fattn_instances DIR OUT_SRCS) set(FA_TYPES q4_0 q4_1 q5_0 q5_1 q8_0 bf16 f16 f8_e4m3) string(TOLOWER "${GGML_CUDA_FA_QUANTS}" FA_QUANTS) @@ -122,6 +122,12 @@ function(ggml_cuda_fattn_vec_instances DIR OUT_SRCS) message(FATAL_ERROR "FlashAttention template instance \"${SRC}\" does not exist") endif() list(APPEND SRCS "${SRC}") + + file(GLOB TILE_SRCS "${DIR}/template-instances/fattn-tile-instance-${COMBINATION}-*.cu") + list(APPEND SRCS ${TILE_SRCS}) + + file(GLOB MMA_SRCS "${DIR}/template-instances/fattn-mma-f16-instance-${COMBINATION}-*.cu") + list(APPEND SRCS ${MMA_SRCS}) endforeach() set(${OUT_SRCS} ${SRCS} PARENT_SCOPE) diff --git a/ggml/src/ggml-cann/ggml-cann.cpp b/ggml/src/ggml-cann/ggml-cann.cpp index abed48060893..d42f19b0a94e 100644 --- a/ggml/src/ggml-cann/ggml-cann.cpp +++ b/ggml/src/ggml-cann/ggml-cann.cpp @@ -2449,10 +2449,12 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten switch (op->src[0]->type) { #ifndef ASCEND_310P case GGML_TYPE_BF16: + return true; #endif case GGML_TYPE_F16: case GGML_TYPE_F32: - return true; + // src1 goes to aclnn as is: a BF16 src1 with F16/F32 weights is not verified + return op->src[1]->type != GGML_TYPE_BF16; case GGML_TYPE_Q8_0: case GGML_TYPE_Q4_0: #ifdef ASCEND_310P @@ -2470,7 +2472,8 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten switch (op->src[0]->type) { case GGML_TYPE_F16: case GGML_TYPE_F32: - return true; + // src1 goes to aclnn as is: a BF16 src1 with F16/F32 weights is not verified + return op->src[1]->type != GGML_TYPE_BF16; case GGML_TYPE_Q8_0: case GGML_TYPE_Q4_0: #ifdef ASCEND_310P diff --git a/ggml/src/ggml-cpu/ggml-cpu.c b/ggml/src/ggml-cpu/ggml-cpu.c index dc0c95bf40c4..b27752714d7e 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.c +++ b/ggml/src/ggml-cpu/ggml-cpu.c @@ -1287,6 +1287,25 @@ static void ggml_compute_forward_mul_mat_one_chunk( } } +// converts n BF16 values (whole blocks of vec_dot_type) to vec_dot_type: widened directly to F32, otherwise via F32 in chunks +static void ggml_cpu_bf16_to_vec_dot_type(const ggml_bf16_t * x, void * y, int64_t n, enum ggml_type vec_dot_type) { + if (vec_dot_type == GGML_TYPE_F32) { + ggml_cpu_bf16_to_fp32(x, (float *) y, n); + return; + } + + ggml_from_float_t const from_float = type_traits_cpu[vec_dot_type].from_float; + const int64_t bs = ggml_blck_size(vec_dot_type); + + float tmp[1024]; + const int64_t chunk = (1024/bs)*bs; + for (int64_t i = 0; i < n; i += chunk) { + const int64_t nc = MIN(chunk, n - i); + ggml_cpu_bf16_to_fp32(x + i, tmp, nc); + from_float(tmp, (char *) y + (i/bs)*ggml_type_size(vec_dot_type), nc); + } +} + void ggml_compute_forward_mul_mat( const struct ggml_compute_params * params, struct ggml_tensor * dst) { @@ -1372,11 +1391,9 @@ UseGgmlGemm1:; const size_t nbw3 = nbw2*ne12; assert(params->wsize >= ne13*nbw3); - // src1 is either packed from F32 into vec_dot_type, or widened from F16 or BF16 into the F32 work buffer - const bool widen = src1->type != GGML_TYPE_F32; - - GGML_ASSERT(!widen || vec_dot_type == GGML_TYPE_F32); - GGML_ASSERT(!widen || src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_BF16); + // src1 is either packed from F32 or BF16 into vec_dot_type, or widened from F16 or BF16 into the F32 work buffer + GGML_ASSERT(src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16 || + (src1->type == GGML_TYPE_F16 && vec_dot_type == GGML_TYPE_F32)); #if 0 for (int64_t i13 = 0; i13 < ne13; ++i13) { @@ -1404,7 +1421,7 @@ UseGgmlGemm1:; if (src1->type == GGML_TYPE_F16) { ggml_cpu_fp16_to_fp32((const ggml_fp16_t *) src1_row, (float *) wdata_row, ne10_block_size); } else if (src1->type == GGML_TYPE_BF16) { - ggml_cpu_bf16_to_fp32((const ggml_bf16_t *) src1_row, (float *) wdata_row, ne10_block_size); + ggml_cpu_bf16_to_vec_dot_type((const ggml_bf16_t *) src1_row, wdata_row, ne10_block_size, vec_dot_type); } else { from_float((const float *) src1_row, wdata_row, ne10_block_size); } @@ -1656,7 +1673,7 @@ static void ggml_compute_forward_mul_mat_id( const size_t nbw3 = nbw2*ne12; assert(params->wsize >= ne13*nbw3); - GGML_ASSERT(src1->type == GGML_TYPE_F32); + GGML_ASSERT(src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16); #if 0 for (int64_t i13 = 0; i13 < ne13; ++i13) { @@ -1675,9 +1692,13 @@ static void ggml_compute_forward_mul_mat_id( size_t bs = ggml_blck_size(vec_dot_type); int64_t ne10_block_start = (ith * ne10/bs) / nth; int64_t ne10_block_end = ((ith + 1) * ne10/bs) / nth; - from_float((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + ne10_block_start*bs*nb10), - (void *) (wdata + i13*nbw3 + i12*nbw2 + i11*nbw1 + ne10_block_start*nbw0), - (ne10_block_end - ne10_block_start) * bs); + const void * src1_row = (const char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + ne10_block_start*bs*nb10; + void * wdata_row = wdata + i13*nbw3 + i12*nbw2 + i11*nbw1 + ne10_block_start*nbw0; + if (src1->type == GGML_TYPE_BF16) { + ggml_cpu_bf16_to_vec_dot_type((const ggml_bf16_t *) src1_row, wdata_row, (ne10_block_end - ne10_block_start) * bs, vec_dot_type); + } else { + from_float((const float *) src1_row, wdata_row, (ne10_block_end - ne10_block_start) * bs); + } } } } diff --git a/ggml/src/ggml-cpu/ggml-cpu.cpp b/ggml/src/ggml-cpu/ggml-cpu.cpp index b7e35d176b64..43fc422102b6 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.cpp +++ b/ggml/src/ggml-cpu/ggml-cpu.cpp @@ -453,14 +453,19 @@ static bool ggml_backend_cpu_device_supports_op(ggml_backend_dev_t dev, const st op->type != GGML_TYPE_IQ1_M; // missing type_traits.from_float case GGML_OP_MUL_MAT: if (ggml_get_op_params_i32(op, 1) == GGML_HINT_SRC0_IS_HADAMARD && - src0->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32) { - return src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16; + src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) { + // the hinted matmul is an FWHT of src1 for every src0 type, which reads F32 or F16 only; + // with use_ref it takes the general path instead, so src1 has to pass the check below too + return false; } - // F16 or BF16 in src1 is widened into the F32 work buffer - return src1->type == GGML_TYPE_F32 || + // F16 in src1 is widened into the F32 work buffer, BF16 is widened or converted to vec_dot_type + return src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16 || src1->type == ggml_get_type_traits_cpu(src0->type)->vec_dot_type || - ((src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_BF16) && - ggml_get_type_traits_cpu(src0->type)->vec_dot_type == GGML_TYPE_F32); + (src1->type == GGML_TYPE_F16 && ggml_get_type_traits_cpu(src0->type)->vec_dot_type == GGML_TYPE_F32); + case GGML_OP_MUL_MAT_ID: + // src1 is converted to vec_dot_type from F32 or BF16 only + return src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16 || + src1->type == ggml_get_type_traits_cpu(src0->type)->vec_dot_type; case GGML_OP_SOFT_MAX_BACK: { if (op->src[0]->type != GGML_TYPE_F32 || op->src[1]->type != GGML_TYPE_F32) { return false; diff --git a/ggml/src/ggml-cpu/tiled/tiled.cpp b/ggml/src/ggml-cpu/tiled/tiled.cpp index 77e1a99450ff..15a17939c088 100644 --- a/ggml/src/ggml-cpu/tiled/tiled.cpp +++ b/ggml/src/ggml-cpu/tiled/tiled.cpp @@ -627,7 +627,7 @@ static bool ggml_tiled_supported(const struct ggml_tensor * src0, case GGML_TYPE_IQ3_S: case GGML_TYPE_IQ1_S: case GGML_TYPE_IQ1_M: - return true; + break; default: return false; } diff --git a/ggml/src/ggml-cuda/CMakeLists.txt b/ggml/src/ggml-cuda/CMakeLists.txt index dcb380535336..00d1156196c5 100644 --- a/ggml/src/ggml-cuda/CMakeLists.txt +++ b/ggml/src/ggml-cuda/CMakeLists.txt @@ -116,16 +116,12 @@ if (CUDAToolkit_FOUND) list(APPEND GGML_HEADERS_CUDA "../../include/ggml-cuda.h") file(GLOB GGML_SOURCES_CUDA "*.cu") - file(GLOB SRCS "template-instances/fattn-tile*.cu") - list(APPEND GGML_SOURCES_CUDA ${SRCS}) - file(GLOB SRCS "template-instances/fattn-mma*.cu") - list(APPEND GGML_SOURCES_CUDA ${SRCS}) file(GLOB SRCS "template-instances/mmq*.cu") list(APPEND GGML_SOURCES_CUDA ${SRCS}) file(GLOB SRCS "template-instances/mmf*.cu") list(APPEND GGML_SOURCES_CUDA ${SRCS}) - ggml_cuda_fattn_vec_instances(${CMAKE_CURRENT_SOURCE_DIR} SRCS) + ggml_cuda_fattn_instances(${CMAKE_CURRENT_SOURCE_DIR} SRCS) list(APPEND GGML_SOURCES_CUDA ${SRCS}) ggml_add_backend_library(ggml-cuda diff --git a/ggml/src/ggml-cuda/common.cuh b/ggml/src/ggml-cuda/common.cuh index 5b3c32858c4a..a06bb678d0d9 100644 --- a/ggml/src/ggml-cuda/common.cuh +++ b/ggml/src/ggml-cuda/common.cuh @@ -412,6 +412,11 @@ static bool ggml_cuda_is_aligned(const ggml_tensor * tensor, const size_t alignm tensor->nb[3] % alignment == 0; } +static bool ggml_cuda_is_view_or_noop(const ggml_tensor * t) { + return ggml_is_empty(t) || t->op == GGML_OP_RESHAPE || t->op == GGML_OP_TRANSPOSE || + t->op == GGML_OP_VIEW || t->op == GGML_OP_PERMUTE || t->op == GGML_OP_NONE; +} + static constexpr __device__ int ggml_cuda_get_physical_warp_size() { #if defined(GGML_USE_HIP) && (defined(__GFX9__) || defined(__GFX8__)) return 64; diff --git a/ggml/src/ggml-cuda/concat.cu b/ggml/src/ggml-cuda/concat.cu index f8dcd95ab008..0039ae483fd6 100644 --- a/ggml/src/ggml-cuda/concat.cu +++ b/ggml/src/ggml-cuda/concat.cu @@ -104,38 +104,41 @@ static __global__ void __launch_bounds__(CUDA_CONCAT_BLOCK_SIZE) uint64_t nb13, int64_t ne0, int64_t /*ne1*/, - int64_t /*ne2*/, - int64_t /*ne3*/, + int64_t ne2, + int64_t ne3, uint64_t nb0, uint64_t nb1, uint64_t nb2, uint64_t nb3) { static_assert(dim >= 0 && dim <= 3, "dim must be in [0, 3]"); - const int64_t i3 = blockIdx.z; - const int64_t i2 = blockIdx.y; const int64_t i1 = blockIdx.x; const T * x; - for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) { - if (i0 < ne00 && i1 < ne01 && i2 < ne02 && i3 < ne03) { - x = (const T *)(src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00); - } else { - if constexpr (dim == 0) { - x = (const T *)(src1 + i3*nb13 + i2*nb12 + i1*nb11 + (i0 - ne00)*nb10); - } else if constexpr (dim == 1) { - x = (const T *)(src1 + i3*nb13 + i2*nb12 + (i1 - ne01)*nb11 + i0*nb10); - } else if constexpr (dim == 2) { - x = (const T *)(src1 + i3*nb13 + (i2 - ne02)*nb12 + i1*nb11 + i0*nb10); - } else if constexpr (dim == 3) { - x = (const T *)(src1 + (i3 - ne03)*nb13 + i2*nb12 + i1*nb11 + i0*nb10); + // gridDim.y and gridDim.z are capped at 65535, loop over the rest of ne2 and ne3 + for (int64_t i3 = blockIdx.z; i3 < ne3; i3 += gridDim.z) { + for (int64_t i2 = blockIdx.y; i2 < ne2; i2 += gridDim.y) { + for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) { + if (i0 < ne00 && i1 < ne01 && i2 < ne02 && i3 < ne03) { + x = (const T *)(src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00); + } else { + if constexpr (dim == 0) { + x = (const T *)(src1 + i3*nb13 + i2*nb12 + i1*nb11 + (i0 - ne00)*nb10); + } else if constexpr (dim == 1) { + x = (const T *)(src1 + i3*nb13 + i2*nb12 + (i1 - ne01)*nb11 + i0*nb10); + } else if constexpr (dim == 2) { + x = (const T *)(src1 + i3*nb13 + (i2 - ne02)*nb12 + i1*nb11 + i0*nb10); + } else if constexpr (dim == 3) { + x = (const T *)(src1 + (i3 - ne03)*nb13 + i2*nb12 + i1*nb11 + i0*nb10); + } + } + + T * y = (T *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0); + + *y = *x; } } - - T * y = (T *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0); - - *y = *x; } } @@ -163,7 +166,7 @@ static void concat_cuda(const ggml_tensor * src0, const ggml_tensor * src1, ggml } else { GGML_ASSERT(!ggml_is_quantized(src0->type)); - dim3 grid_dim(dst->ne[1], dst->ne[2], dst->ne[3]); + dim3 grid_dim(dst->ne[1], std::min(dst->ne[2], 65535), std::min(dst->ne[3], 65535)); auto launch_kernel = [&](auto dim) { concat_non_cont<<>>( (const char *) src0->data, (const char *) src1->data, (char *) dst->data, diff --git a/ggml/src/ggml-cuda/cp-async.cuh b/ggml/src/ggml-cuda/cp-async.cuh index 1071352e7b94..bbef1c7d303d 100644 --- a/ggml/src/ggml-cuda/cp-async.cuh +++ b/ggml/src/ggml-cuda/cp-async.cuh @@ -1,3 +1,5 @@ +#pragma once + // Simplified API for asynchronous data loading. #include "common.cuh" diff --git a/ggml/src/ggml-cuda/fattn-common.cuh b/ggml/src/ggml-cuda/fattn-common.cuh index fc0cc7403910..59fd16abdf36 100644 --- a/ggml/src/ggml-cuda/fattn-common.cuh +++ b/ggml/src/ggml-cuda/fattn-common.cuh @@ -2,6 +2,8 @@ #include "common.cuh" #include "convert.cuh" +#include "cp-async.cuh" +#include "mma.cuh" #include "vecdotq.cuh" #include @@ -18,16 +20,16 @@ // The macro on the following line shifts it by a factor of 2**3=8, as was needed to fix https://github.com/ggml-org/llama.cpp/issues/18606 . #define FATTN_KQ_MAX_OFFSET (3.0f*0.6931f) -typedef void (* fattn_kernel_t)( - const char * __restrict__ Q, - const char * __restrict__ K, - const char * __restrict__ V, - const char * __restrict__ mask, - const char * __restrict__ sinks, - const int * __restrict__ KV_max, - const int * __restrict__ KV_rows, - float * __restrict__ dst, - float2 * __restrict__ dst_meta, +using fattn_kernel_t = void (*)( + const float2 * __restrict__ Q, + const char * __restrict__ K, + const char * __restrict__ V, + const half * __restrict__ mask, + const float * __restrict__ sinks, + const int * __restrict__ KV_max, + const int * __restrict__ KV_rows, + float * __restrict__ dst, + float2 * __restrict__ dst_meta, const float scale, const float max_bias, const float m0, @@ -35,16 +37,21 @@ typedef void (* fattn_kernel_t)( const uint32_t n_head_log2, const float logit_softcap, const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03, - const int32_t nb01, const int32_t nb02, const int32_t nb03, + const int32_t s01, const int32_t s02, const int32_t s03, const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13, - const int32_t nb11, const int32_t nb12, const int64_t nb13, - const int32_t nb21, const int32_t nb22, const int64_t nb23, + const int32_t s11, const int32_t s12, const int64_t s13, + const int32_t s21, const int32_t s22, const int64_t s23, const int32_t ne31, const int32_t ne32, const int32_t ne33, - const int32_t nb31, const int64_t nb32, const int64_t nb33); + const int32_t s31, const int64_t s32, const int64_t s33); typedef float (*vec_dot_KQ_t)( const char * __restrict__ K_c, const void * __restrict__ Q_v, const int * __restrict__ Q_q8 , const void * __restrict__ Q_ds); +template +using fattn_load_tile_t = void (*)( + const T_src * __restrict__ KV, T_dst * __restrict__ tile_KV, const int D2, const int stride_KV, + const int k_VKQ_0, const int i_sup, const int32_t * __restrict__ indices); + struct ggml_cuda_flash_attn_ext_f16_extra_data { uintptr_t K; uintptr_t V; @@ -669,6 +676,253 @@ static __device__ __forceinline__ void dequantize_V_q8_0(const void * __restrict } } +template +struct flash_attn_load_tile_impl; + +template +struct flash_attn_load_tile_impl { + static __device__ __forceinline__ void load( + const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int D2, const int stride_KV, + const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) { + constexpr int cpy_nb = 16; + constexpr int cpy_ne = cpy_nb / 4; + + static_assert(warp_size == 32, "bad warp_size"); + static_assert(!oob_check || use_sparse, "OOB check not compatible with cp_async"); + static_assert(!use_sparse || KV_indirection, "use_sparse requires KV_indirection"); + static_assert(J % 8 == 0, "bad J"); + static_assert((J/2) % cpy_ne == 0, "bad J"); + GGML_UNUSED(indices); + + // K/V data is loaded with decreasing granularity for D for better memory bandwidth. + const int chunks_per_row = D2 / cpy_ne; + + auto load_step = [&] __device__ (const int n) { + const int stride_k = warp_size >> n; + if (stride_k == 0) { + return; + } + + const int k0_start = stride_k == warp_size ? 0 : chunks_per_row - chunks_per_row % (2*stride_k); + const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k); + const int stride_i = warp_size / stride_k; + + if (k0_start == k0_stop) { + return; + } + +#pragma unroll + for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) { + const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k); + + if (i0 + nwarps*stride_i > I && i >= I) { + break; + } + + constexpr int preload = 64; + const unsigned int tile_KV_32 = ggml_cuda_cvta_generic_to_shared(tile_KV); + + int64_t i_KV; + if constexpr (use_sparse) { + // padded slots gather row 0, the -inf mask removes their contribution + const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : 0; + i_KV = index >= 0 ? index : 0; + } else if constexpr (KV_indirection) { + // K/V rows given per mask column, negative rows are padding + i_KV = indices ? max(indices[k_VKQ_0 + i], 0) : k_VKQ_0 + i; + } else { + i_KV = k_VKQ_0 + i; + } + +#pragma unroll + for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) { + const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k); + uint32_t offset = i*stride_tile*sizeof(half2) + k*cpy_nb; + if constexpr (use_swizzle) { + offset = ggml_cuda_mma::swizzle(offset, i); + } + + cp_async_cg_16(tile_KV_32 + offset, KV + i_KV*stride_KV + k*cpy_ne); + } + } + }; + ggml_cuda_unroll<7>{}(load_step); + } +}; + +template +struct flash_attn_load_tile_impl { + static __device__ __forceinline__ void load( + const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int D2, const int stride_KV, + const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) { + constexpr int cpy_nb = 16; + constexpr int cpy_ne = cpy_nb / 4; + + static_assert(!use_sparse || KV_indirection, "use_sparse requires KV_indirection"); + static_assert(J % 8 == 0, "bad J"); + static_assert((J/2) % cpy_ne == 0, "bad J"); + GGML_UNUSED(indices); + + // K/V data is loaded with decreasing granularity for D for better memory bandwidth. + const int chunks_per_row = D2 / cpy_ne; + + auto load_step = [&] __device__ (const int n) { + const int stride_k = warp_size >> n; + if (stride_k == 0) { + return; + } + + const int k0_start = stride_k == warp_size ? 0 : chunks_per_row - chunks_per_row % (2*stride_k); + const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k); + const int stride_i = warp_size / stride_k; + + if (k0_start == k0_stop) { + return; + } + +#pragma unroll + for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) { + const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k); + + if (i0 + nwarps*stride_i > I && i >= I) { + break; + } + + const __align__(16) half2 zero[cpy_ne] = {{0.0f, 0.0f}}; +#pragma unroll + for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) { + const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k); + + const half2 * src; + if constexpr (use_sparse) { + const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1; + src = index >= 0 ? KV + int64_t(index)*stride_KV + k*cpy_ne : zero; + } else if (!oob_check || i < i_sup) { + if constexpr (KV_indirection) { + const int64_t i_KV = indices ? max(indices[k_VKQ_0 + i], 0) : k_VKQ_0 + i; + src = KV + i_KV*stride_KV + k*cpy_ne; + } else { + src = KV + int64_t(k_VKQ_0 + i)*stride_KV + k*cpy_ne; + } + } else { + src = zero; + } + + half2 * dst; + if constexpr (use_swizzle) { + dst = ggml_cuda_mma::swizzle(tile_KV, i*stride_tile + k*cpy_ne, i); + } else { + dst = tile_KV + i*stride_tile + k*cpy_ne; + } + + ggml_cuda_memcpy_1(dst, src); + } + } + }; + ggml_cuda_unroll<7>{}(load_step); + } +}; + +template +struct flash_attn_load_tile_impl { + static __device__ __forceinline__ void load( + const half2 * const __restrict__ KV, float * const __restrict__ tile_KV, const int D2, const int stride_KV, + const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) { + constexpr int cpy_nb = 16; + constexpr int cpy_ne = cpy_nb / 4; + constexpr int h2_per_chunk = cpy_ne / 2; + + static_assert(!use_sparse || KV_indirection, "use_sparse requires KV_indirection"); + static_assert(J % 8 == 0, "bad J"); + static_assert(J % cpy_ne == 0, "bad J"); + GGML_UNUSED(indices); + + // K/V data is loaded with decreasing granularity for D for better memory bandwidth. + const int chunks_per_row = D2 / h2_per_chunk; + const half2 * const __restrict__ KV_0 = use_sparse || (KV_indirection && indices) ? KV : KV + int64_t(k_VKQ_0)*stride_KV; + + auto load_step = [&] __device__ (const int n) { + const int stride_k = warp_size >> n; + if (stride_k == 0) { + return; + } + + const int k0_start = stride_k == warp_size ? 0 : chunks_per_row - chunks_per_row % (2*stride_k); + const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k); + const int stride_i = warp_size / stride_k; + + if (k0_start == k0_stop) { + return; + } + +#pragma unroll + for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) { + const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k); + + if (i0 + nwarps*stride_i > I && i >= I) { + break; + } + + const __align__(16) half2 zero[h2_per_chunk] = {{0.0f, 0.0f}}; +#pragma unroll + for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) { + const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k); + + const half2 * src; + if constexpr (use_sparse) { + const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1; + src = index >= 0 ? KV + int64_t(index)*stride_KV + k*h2_per_chunk : zero; + } else if (!oob_check || i < i_sup) { + if constexpr (KV_indirection) { + if (indices) { + const int64_t i_KV = max(indices[k_VKQ_0 + i], 0); + src = KV_0 + i_KV*stride_KV + k*h2_per_chunk; + } else { + src = KV_0 + i*stride_KV + k*h2_per_chunk; + } + } else { + src = KV_0 + i*stride_KV + k*h2_per_chunk; + } + } else { + src = zero; + } + + __align__(16) half2 tmp_h2[h2_per_chunk]; + ggml_cuda_memcpy_1(tmp_h2, src); + + __align__(16) float2 tmp_f2[h2_per_chunk]; +#pragma unroll + for (int l = 0; l < h2_per_chunk; ++l) { + tmp_f2[l] = __half22float2(tmp_h2[l]); + } + ggml_cuda_memcpy_1(tile_KV + i*stride_tile + k*cpy_ne, tmp_f2); + } + } + }; + ggml_cuda_unroll<7>{}(load_step); + } +}; + +template +static __device__ __forceinline__ void flash_attn_load_tile( + const T_src * const __restrict__ KV, T_dst * const __restrict__ tile_KV, const int D2, const int stride_KV, + const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) { + flash_attn_load_tile_impl::load( + KV, tile_KV, D2, stride_KV, k_VKQ_0, i_sup, indices); +} + +// Helper function to get a C++ type for calculating pointer offsets from a ggml type: +template +static __host__ __device__ auto ggml_cuda_fattn_kv_dtype() { + if constexpr (type == GGML_TYPE_F16) { + return half2{}; + } else { + static_assert(type == -1, "bad type"); + } +} + template constexpr __device__ vec_dot_KQ_t get_vec_dot_KQ() { if constexpr (type_K == GGML_TYPE_F16) { @@ -1028,9 +1282,10 @@ static __global__ void flash_attn_combine_results( dst[tid] = VKQ_numerator / VKQ_denominator; } -template +template void launch_fattn( - ggml_backend_cuda_context & ctx, ggml_tensor * dst, fattn_kernel_t fattn_kernel, const int nwarps, const size_t nbytes_shared, + ggml_backend_cuda_context & ctx, ggml_tensor * dst, fattn_kernel_t fattn_kernel, + const int nwarps, const size_t nbytes_shared, const int nbatch_fa, const bool need_f16_K, const bool need_f16_V, const bool stream_k, const bool use_sparse, const int warp_size = WARP_SIZE, const bool async_kv_preload = false ) { @@ -1148,6 +1403,14 @@ void launch_fattn( } } + GGML_ASSERT(nb11 % sizeof(T_K_stride) == 0); + GGML_ASSERT(nb12 % sizeof(T_K_stride) == 0); + GGML_ASSERT(nb13 % sizeof(T_K_stride) == 0); + + GGML_ASSERT(nb21 % sizeof(T_V_stride) == 0); + GGML_ASSERT(nb22 % sizeof(T_V_stride) == 0); + GGML_ASSERT(nb23 % sizeof(T_V_stride) == 0); + const int ntiles_x = ((Q->ne[1] + ncols1 - 1) / ncols1); const int gqa_ratio = Q->ne[2] / K->ne[2]; const int ntiles_z_gqa = ((gqa_ratio + ncols2 - 1) / ncols2); @@ -1311,20 +1574,24 @@ void launch_fattn( ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(blocks_num, block_dim, nbytes_shared, main_stream); ggml_cuda_kernel_launch(fattn_kernel, launch_params, - (const char *) Q->data, - K_data, - V_data, - mask ? ((const char *) mask->data) : nullptr, - sinks ? ((const char *) sinks->data) : nullptr, + (const float2 *) Q->data, + (const char *) K_data, + (const char *) V_data, + mask ? ((const half *) mask->data) : nullptr, + sinks ? ((const float *) sinks->data) : nullptr, KV_max.ptr, kv_rows ? (const int *) kv_rows->data : nullptr, !stream_k && parallel_blocks > 1 ? dst_tmp.ptr : (float *) KQV->data, dst_tmp_meta.ptr, scale, max_bias, m0, m1, n_head_log2, logit_softcap, - Q->ne[0], ne01, Q->ne[2], Q->ne[3], Q->nb[1], Q->nb[2], Q->nb[3], - K->ne[0], n_kv, K->ne[2], K->ne[3], nb11, nb12, nb13, - nb21, nb22, nb23, + Q->ne[0], ne01, Q->ne[2], Q->ne[3], + int32_t(Q->nb[1] / sizeof(float2)), int32_t(Q->nb[2] / sizeof(float2)), int32_t(Q->nb[3] / sizeof(float2)), + K->ne[0], n_kv, K->ne[2], K->ne[3], + int32_t(nb11 / sizeof(T_K_stride)), int32_t(nb12 / sizeof(T_K_stride)), int64_t(nb13 / sizeof(T_K_stride)), + int32_t(nb21 / sizeof(T_V_stride)), int32_t(nb22 / sizeof(T_V_stride)), int64_t(nb23 / sizeof(T_V_stride)), mask ? mask->ne[1] : 0, mask ? mask->ne[2] : 0, mask ? mask->ne[3] : 0, - mask ? mask->nb[1] : 0, mask ? mask->nb[2] : 0, mask ? mask->nb[3] : 0 + mask ? int32_t(mask->nb[1] / sizeof(half)) : 0, + mask ? int64_t(mask->nb[2] / sizeof(half)) : 0, + mask ? int64_t(mask->nb[3] / sizeof(half)) : 0 ); CUDA_CHECK(cudaGetLastError()); diff --git a/ggml/src/ggml-cuda/fattn-mma-f16.cuh b/ggml/src/ggml-cuda/fattn-mma-f16.cuh index dea8d2ad35ec..5c7a37fb8f0e 100644 --- a/ggml/src/ggml-cuda/fattn-mma-f16.cuh +++ b/ggml/src/ggml-cuda/fattn-mma-f16.cuh @@ -413,116 +413,6 @@ static constexpr __device__ int ggml_cuda_fattn_mma_get_nstages( // ------------------------------------------------------------------------------------------------------------------ -template -static __device__ __forceinline__ void flash_attn_ext_f16_load_tile( - const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int D2, const int stride_KV, - const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) { - constexpr int warp_size = ggml_cuda_get_physical_warp_size(); - // K/V data is loaded with decreasing granularity for D for better memory bandwidth. - // The minimum granularity is 16 bytes. - constexpr int chunk_size = 16; - constexpr int h2_per_chunk = chunk_size / sizeof(half2); - const int chunks_per_row = D2 / h2_per_chunk; - if constexpr (use_cp_async) { - static_assert(warp_size == 32, "bad warp_size"); - static_assert(!oob_check || use_sparse, "OOB check not compatible with cp_async"); - constexpr int preload = 64; - - const unsigned int tile_KV_32 = ggml_cuda_cvta_generic_to_shared(tile_KV); - - auto load = [&] __device__ (auto n) { - const int stride_k = warp_size >> n; - const int k0_start = stride_k == warp_size ? 0 : chunks_per_row - chunks_per_row % (2*stride_k); - const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k); - const int stride_i = warp_size / stride_k; - - if (k0_start == k0_stop) { - return; - } - -#pragma unroll - for (int i0 = 0; i0 < nbatch_fa; i0 += nwarps*stride_i) { - const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k); - - if (i0 + nwarps*stride_i > nbatch_fa && i >= nbatch_fa) { - break; - } - - int64_t i_KV; - if constexpr (use_sparse) { - // padded slots gather row 0, the -inf mask removes their contribution - const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : 0; - i_KV = index >= 0 ? index : 0; - } else if (indices) { - // K/V rows given per mask column, negative rows are padding - i_KV = max(indices[k_VKQ_0 + i], 0); - } else { - i_KV = k_VKQ_0 + i; - } - -#pragma unroll - for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) { - const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k); - - cp_async_cg_16(tile_KV_32 + swizzle(i*stride_tile*sizeof(half2) + k*chunk_size, i), KV + i_KV*stride_KV + k*h2_per_chunk); - } - } - }; - // 1: max 32*16=512 bytes, 256 half - // 2: max 16*16=256 bytes, 128 half - // 3: max 8*16=128 bytes, 64 half - // 4: max 4*16= 64 bytes, 32 half - // 5: max 2*16= 32 bytes, 16 half - // 6: max 1*16= 16 bytes, 8 half - ggml_cuda_unroll<6>{}(load); - } else { - const half2 zero[4] = {{0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}}; - auto load = [&] __device__ (const int n) { - const int stride_k = 32 >> n; - const int k0_start = stride_k == 32 ? 0 : chunks_per_row - chunks_per_row % (2*stride_k); - const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k); - const int stride_i = warp_size / stride_k; - - if (k0_start == k0_stop) { - return; - } - -#pragma unroll - for (int i0 = 0; i0 < nbatch_fa; i0 += nwarps*stride_i) { - const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k); - - if (i0 + nwarps*stride_i > nbatch_fa && i >= nbatch_fa) { - break; - } - -#pragma unroll - for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) { - const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k); - - const half2 * src; - if constexpr (use_sparse) { - const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1; - src = index >= 0 ? KV + int64_t(index)*stride_KV + k*h2_per_chunk : zero; - } else if (!oob_check || i < i_sup) { - const int64_t i_KV = indices ? max(indices[k_VKQ_0 + i], 0) : k_VKQ_0 + i; - src = KV + i_KV*stride_KV + k*h2_per_chunk; - } else { - src = zero; - } - ggml_cuda_memcpy_1<16>(swizzle(tile_KV, i*stride_tile + k*h2_per_chunk, i), src); - } - } - }; - // 1: max 32*16=512 bytes, 256 half - // 2: max 16*16=256 bytes, 128 half - // 3: max 8*16=128 bytes, 64 half - // 4: max 4*16= 64 bytes, 32 half - // 5: max 2*16= 32 bytes, 16 half - // 6: max 1*16= 16 bytes, 8 half - ggml_cuda_unroll<6>{}(load); - } -} - template static __device__ __forceinline__ void flash_attn_ext_f16_load_mask( const half * const __restrict__ mask_h, half * const __restrict__ tile_mask, @@ -612,11 +502,12 @@ static __device__ __forceinline__ void flash_attn_ext_f16_load_mask( template + typename T_A_KQ, typename T_B_KQ, typename T_C_KQ, typename T_A_VKQ, typename T_B_VKQ, typename T_C_VKQ, + typename T_K, typename T_V> static __device__ __forceinline__ void flash_attn_ext_f16_iter( const float2 * const __restrict__ Q_f2, - const half2 * const __restrict__ K_h2, - const half2 * const __restrict__ V_h2, + const T_K * const __restrict__ K_h2, + const T_V * const __restrict__ V_h2, const half * const __restrict__ mask_h, const int32_t * const __restrict__ indices, float2 * const __restrict__ dstk, @@ -653,6 +544,13 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( constexpr bool Q_in_reg = ggml_cuda_fattn_mma_get_Q_in_reg (DKQ, DV, ncols); constexpr int nstages = ggml_cuda_fattn_mma_get_nstages (DKQ, DV, ncols1, ncols2, use_sparse); + // FIXME this is causing performance regressions on AMD/V100. +#ifdef TURING_MMA_AVAILABLE + constexpr bool KV_indirection = true; +#else + constexpr bool KV_indirection = use_sparse; +#endif // TURING_MMA_AVAILABLE + constexpr int DKQp = GGML_PAD(DKQ, 16); constexpr int DVp = GGML_PAD(DV, 16); @@ -676,7 +574,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( constexpr bool use_cp_async = true; cp_async_wait_all(); __syncthreads(); - flash_attn_ext_f16_load_tile + flash_attn_load_tile (V_h2, tile_V, min(nbatch_V2, DV/2), stride_V, k_VKQ_0, k_VKQ_sup, indices); } else { // the sparse mask values are gathered per element, always load them synchronously @@ -696,7 +594,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( if constexpr (nstages <= 1) { const int k0_diff = min(k0_stop, DKQ/2) - k0_start; // Only load the real head size from global memory. constexpr bool use_cp_async = nstages == 1; - flash_attn_ext_f16_load_tile + flash_attn_load_tile (K_h2 + k0_start, tile_K, k0_diff, stride_K, k_VKQ_0, k_VKQ_sup, indices); if (use_cp_async) { cp_async_wait_all(); @@ -1033,7 +931,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( flash_attn_ext_f16_load_mask (mask_h, tile_mask, stride_mask, kb0_next*nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr); } - flash_attn_ext_f16_load_tile + flash_attn_load_tile (K_h2, tile_K, min(nbatch_K2, DKQ/2), stride_K, kb0_next*nbatch_fa, k_VKQ_sup, indices); } } @@ -1049,7 +947,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( const int i0_diff = min(i0_stop, DV) - i0_start; // Only load the real head size from global memory. if (!V_is_K_view || i0_stop > 2*nbatch_K2) { constexpr bool use_cp_async = nstages == 1; - flash_attn_ext_f16_load_tile + flash_attn_load_tile (V_h2 + i0_start/2, tile_V, i0_diff/2, stride_V, k_VKQ_0, k_VKQ_sup, indices); if (use_cp_async) { cp_async_wait_all(); @@ -1261,11 +1159,11 @@ template struct mma_tile_sizes { }; #endif // defined(TURING_MMA_AVAILABLE) -template +template static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( const float2 * const __restrict__ Q_f2, - const half2 * const __restrict__ K_h2, - const half2 * const __restrict__ V_h2, + const T_K * const __restrict__ K_h2, + const T_V * const __restrict__ V_h2, const half * const __restrict__ mask_h, const int32_t * const __restrict__ indices, const float * const __restrict__ sinks_f, @@ -1310,6 +1208,13 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( constexpr bool Q_in_reg = ggml_cuda_fattn_mma_get_Q_in_reg (DKQ, DV, ncols); constexpr int nstages = ggml_cuda_fattn_mma_get_nstages (DKQ, DV, ncols1, ncols2, use_sparse); + // FIXME this is causing performance regressions on AMD/V100. +#ifdef TURING_MMA_AVAILABLE + constexpr bool KV_indirection = true; +#else + constexpr bool KV_indirection = use_sparse; +#endif // TURING_MMA_AVAILABLE + constexpr int DKQp = GGML_PAD(DKQ, 16); constexpr int DVp = GGML_PAD(DV, 16); @@ -1459,7 +1364,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( flash_attn_ext_f16_load_mask (mask_h, tile_mask, stride_mask, kb0*nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr); } - flash_attn_ext_f16_load_tile + flash_attn_load_tile (K_h2, tile_K, min(nbatch_K2, DKQ/2), stride_K, kb0*nbatch_fa, k_VKQ_sup, indices); } @@ -1472,7 +1377,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( constexpr int k_VKQ_sup = nbatch_fa; flash_attn_ext_f16_iter + T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V> (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, KQ_max, KQ_rowsum, jt, kb0, kb0_next, k_VKQ_sup); @@ -1482,7 +1387,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( constexpr int k_VKQ_sup = nbatch_fa; flash_attn_ext_f16_iter + T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V> (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, KQ_max, KQ_rowsum, jt, kb0, kb0, k_VKQ_sup); @@ -1493,7 +1398,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( constexpr int k_VKQ_sup = nbatch_fa; flash_attn_ext_f16_iter + T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V> (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, KQ_max, KQ_rowsum, jt, kb0, kb0 + 1, k_VKQ_sup); @@ -1502,7 +1407,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( const int k_VKQ_sup = ne11 - kb0*nbatch_fa; flash_attn_ext_f16_iter + T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V> (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, KQ_max, KQ_rowsum, jt, kb0, kb0, k_VKQ_sup); @@ -1513,7 +1418,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( constexpr int k_VKQ_sup = nbatch_fa; flash_attn_ext_f16_iter + T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V> (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, KQ_max, KQ_rowsum, jt, kb0, kb0 + 1, k_VKQ_sup); @@ -1522,7 +1427,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile( constexpr int k_VKQ_sup = nbatch_fa; flash_attn_ext_f16_iter + T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V> (Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap, ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C, KQ_max, KQ_rowsum, jt, kb0, kb0, k_VKQ_sup); @@ -1936,18 +1841,18 @@ static constexpr __host__ __device__ bool ggml_cuda_flash_attn_ext_mma_f16_may_u (DKQ == 256 && DV == 256 && ncols1 == 8 && ncols2 == 8); } -template +template __launch_bounds__(ggml_cuda_fattn_mma_get_nthreads(DKQ, DV, ncols1*ncols2), ggml_cuda_fattn_mma_get_occupancy(DKQ, DV, ncols1*ncols2)) static __global__ void flash_attn_ext_f16( - const char * Q_ptr, - const char * K_ptr, - const char * V_ptr, - const char * mask_ptr, - const char * sinks_ptr, - const int * KV_max_ptr, - const int * KV_rows_ptr, - float * dst_ptr, - float2 * dst_meta_ptr, + const float2 * Q_ptr, + const char * K_ptr, + const char * V_ptr, + const half * mask_ptr, + const float * sinks_ptr, + const int * KV_max_ptr, + const int * KV_rows_ptr, + float * dst_ptr, + float2 * dst_meta_ptr, const float scale, const float max_bias, const float m0, @@ -1955,19 +1860,22 @@ static __global__ void flash_attn_ext_f16( const uint32_t n_head_log2, const float logit_softcap, const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03, - const int32_t nb01, const int32_t nb02, const int32_t nb03, + const int32_t s01, const int32_t s02, const int32_t s03, const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13, - const int32_t nb11, const int32_t nb12, const int64_t nb13, - const int32_t nb21, const int32_t nb22, const int64_t nb23, + const int32_t s11, const int32_t s12, const int64_t s13, + const int32_t s21, const int32_t s22, const int64_t s23, const int32_t ne31, const int32_t ne32, const int32_t ne33, - const int32_t nb31, const int64_t nb32, const int64_t nb33) { + const int32_t s31, const int64_t s32, const int64_t s33) { ggml_cuda_pdl_sync(); // TODO optimize placement #if defined(FLASH_ATTN_AVAILABLE) && (defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE)) - const char * GGML_CUDA_RESTRICT Q = Q_ptr; - const char * GGML_CUDA_RESTRICT K = K_ptr; - const char * GGML_CUDA_RESTRICT V = V_ptr; - const char * GGML_CUDA_RESTRICT mask = mask_ptr; - const char * GGML_CUDA_RESTRICT sinks = sinks_ptr; + using T_K = decltype(ggml_cuda_fattn_kv_dtype()); + using T_V = decltype(ggml_cuda_fattn_kv_dtype()); + + const float2 * GGML_CUDA_RESTRICT Q = Q_ptr; + const T_K * GGML_CUDA_RESTRICT K = (const T_K *) K_ptr; + const T_V * GGML_CUDA_RESTRICT V = (const T_V *) V_ptr; + const half * GGML_CUDA_RESTRICT mask = mask_ptr; + const float * GGML_CUDA_RESTRICT sinks = sinks_ptr; // sparse: one index list per (sequence, query tile), the live count of each list follows the lists const int * GGML_CUDA_RESTRICT sparse_indices = use_sparse ? KV_max_ptr : nullptr; const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr; @@ -2024,12 +1932,7 @@ static __global__ void flash_attn_ext_f16( const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix. - const int stride_Q1 = nb01 / sizeof(float2); - const int stride_Q2 = nb02 / sizeof(float2); - const int stride_K = nb11 / sizeof(half2); - const int stride_mask = nb31 / sizeof(half); - - const int stride_V = V_is_K_view ? stride_K : nb21 / sizeof(half2); + const int stride_V = V_is_K_view ? s11 : s21; const int iter_k = (ne11 + (nbatch_fa - 1)) / nbatch_fa; const int iter_j = (ne01.z + (ncols1 - 1)) / ncols1; @@ -2072,14 +1975,14 @@ static __global__ void flash_attn_ext_f16( const int zt_Q = z_KV*gqa_ratio + zt_gqa*ncols2; // Global Q head start index. - const float2 * Q_f2 = (const float2 *) (Q + nb03*sequence + nb02*zt_Q); - const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*z_KV); + const float2 * Q_f2 = Q + s03*sequence + s02*zt_Q; + const T_K * K_h2 = K + s13*sequence + s12*z_KV; const half * mask_h = ncols2 == 1 && !mask ? nullptr : - (const half *) (mask + nb33*(sequence % ne33) + nb32*(zt_Q % ne32)); + mask + s33*(sequence % ne33) + s32*(zt_Q % ne32); float2 * dstk = ((float2 *) dst) + (sequence*ne01.z*ne02 + zt_Q) * (DV/2); - const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*sequence + nb22*z_KV); - const float * sinks_f = sinks ? (const float *) sinks + zt_Q : nullptr; + const T_V * V_h2 = V_is_K_view ? (const T_V *) K_h2 : V + s23*sequence + s22*z_KV; + const float * sinks_f = sinks ? sinks + zt_Q : nullptr; const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 : KV_rows_ptr ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr; @@ -2096,14 +1999,14 @@ static __global__ void flash_attn_ext_f16( constexpr bool is_fixup = false; // All but (potentially) the last iterations write their data to dst rather than the fixup buffer. if (kb0_start == 0) { constexpr bool needs_fixup = false; // CUDA block is working on an entire tile. - flash_attn_ext_f16_process_tile + flash_attn_ext_f16_process_tile (Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap, - ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max); + ne01, ne02, gqa_ratio, ne11, s01, s02, s11, stride_V, s31, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max); } else { constexpr bool needs_fixup = true; // CUDA block is missing the beginning of a tile. - flash_attn_ext_f16_process_tile + flash_attn_ext_f16_process_tile (Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap, - ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max); + ne01, ne02, gqa_ratio, ne11, s01, s02, s11, stride_V, s31, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max); } kbc += iter_k; @@ -2126,14 +2029,14 @@ static __global__ void flash_attn_ext_f16( const int zt_Q = z_KV*gqa_ratio + zt_gqa*ncols2; // Global Q head start index. - const float2 * Q_f2 = (const float2 *) (Q + nb03*sequence + nb02*zt_Q); - const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*z_KV); + const float2 * Q_f2 = Q + s03*sequence + s02*zt_Q; + const T_K * K_h2 = K + s13*sequence + s12*z_KV; const half * mask_h = ncols2 == 1 && !mask ? nullptr : - (const half *) (mask + nb33*(sequence % ne33) + nb32*(zt_Q % ne32)); + mask + s33*(sequence % ne33) + s32*(zt_Q % ne32); float2 * dstk = ((float2 *) dst) + (sequence*ne01.z*ne02 + zt_Q) * (DV/2); - const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*sequence + nb22*z_KV); - const float * sinks_f = sinks ? (const float *) sinks + zt_Q : nullptr; + const T_V * V_h2 = V_is_K_view ? (const T_V *) K_h2 : V + s23*sequence + s22*z_KV; + const float * sinks_f = sinks ? sinks + zt_Q : nullptr; const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 : KV_rows_ptr ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr; @@ -2149,27 +2052,30 @@ static __global__ void flash_attn_ext_f16( constexpr bool is_fixup = true; // Last index writes its data to fixup buffer to avoid data races with other blocks. constexpr bool needs_fixup = false; - flash_attn_ext_f16_process_tile + flash_attn_ext_f16_process_tile (Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap, - ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max); + ne01, ne02, gqa_ratio, ne11, s01, s02, s11, stride_V, s31, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max); #else GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale, max_bias, m0, m1, n_head_log2, logit_softcap, ne00, ne01, ne02, ne03, - nb01, nb02, nb03, + s01, s02, s03, ne10, ne11, ne12, ne13, - nb11, nb12, nb13, - nb21, nb22, nb23, + s11, s12, s13, + s21, s22, s23, ne31, ne32, ne33, - nb31, nb32, nb33); + s31, s32, s33); NO_DEVICE_CODE; #endif // defined(FLASH_ATTN_AVAILABLE) && (defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE)) } bool ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(const int cc, const ggml_tensor * dst, const int ncols1, const int ncols2); -template +template void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { + using T_K = decltype(ggml_cuda_fattn_kv_dtype()); + using T_V = decltype(ggml_cuda_fattn_kv_dtype()); + const ggml_tensor * KQV = dst; const int id = ggml_cuda_get_device(); const int cc = ggml_cuda_info().devices[id].cc; @@ -2223,7 +2129,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml if constexpr (ggml_cuda_flash_attn_ext_mma_f16_may_use_sparse(DKQ, DV, ncols1, ncols2)) { if (ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, ncols1, ncols2)) { constexpr bool use_sparse_kernel = true; - fattn_kernel = flash_attn_ext_f16; + fattn_kernel = flash_attn_ext_f16; use_sparse = true; static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false}; @@ -2233,7 +2139,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml } } else { constexpr bool use_sparse_kernel = false; - fattn_kernel = flash_attn_ext_f16; + fattn_kernel = flash_attn_ext_f16; static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false}; if (!shared_memory_limit_raised[id]) { @@ -2245,7 +2151,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml #endif // !defined(GGML_USE_MUSA) { constexpr bool use_sparse_kernel = false; - fattn_kernel = flash_attn_ext_f16; + fattn_kernel = flash_attn_ext_f16; static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false}; if (!shared_memory_limit_raised[id]) { @@ -2256,7 +2162,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml } else { constexpr bool use_logit_softcap = true; constexpr bool use_sparse_kernel = false; - fattn_kernel = flash_attn_ext_f16; + fattn_kernel = flash_attn_ext_f16; static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false}; if (!shared_memory_limit_raised[id]) { @@ -2266,83 +2172,83 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml } const bool async_kv_preload = nstages == 2 && !use_sparse; - launch_fattn + launch_fattn (ctx, dst, fattn_kernel, nwarps, nbytes_shared_total, nbatch_fa, true, true, true, use_sparse, warp_size_host, async_kv_preload); } -#define DECL_FATTN_MMA_F16_CASE(DKQ, DV, ncols1, ncols2) \ - template void ggml_cuda_flash_attn_ext_mma_f16_case \ - (ggml_backend_cuda_context & ctx, ggml_tensor * dst) \ - -#define DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(DKQ, DV, ncols) \ - extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 1, 1); \ - extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 2, 2); \ - extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 4, 4); \ - extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 8, 8); \ - extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/16, 16); \ - -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 8) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 8) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 8) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 8) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 8) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 8) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 8) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 8) - -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 16) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 16) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 16) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 16) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 16) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 16) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 16) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 16) - -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 32) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 32) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 32) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 32) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 32) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 32) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 32) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 32) - -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 64) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 64) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 64) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 64) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 64) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 64) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 64) -DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 64) - -extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 2); -extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 2); -extern DECL_FATTN_MMA_F16_CASE(512, 512, 16, 2); -extern DECL_FATTN_MMA_F16_CASE(512, 512, 32, 2); -extern DECL_FATTN_MMA_F16_CASE(512, 512, 2, 4); -extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 4); -extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 4); -extern DECL_FATTN_MMA_F16_CASE(512, 512, 16, 4); -extern DECL_FATTN_MMA_F16_CASE(512, 512, 1, 8); -extern DECL_FATTN_MMA_F16_CASE(512, 512, 2, 8); -extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 8); -extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 8); +#define DECL_FATTN_MMA_F16_CASE(DKQ, DV, ncols1, ncols2, type_K, type_V) \ + template void ggml_cuda_flash_attn_ext_mma_f16_case \ + (ggml_backend_cuda_context & ctx, ggml_tensor * dst) \ + +#define DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(DKQ, DV, ncols, type_K, type_V) \ + extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 1, 1, type_K, type_V); \ + extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 2, 2, type_K, type_V); \ + extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 4, 4, type_K, type_V); \ + extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 8, 8, type_K, type_V); \ + extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/16, 16, type_K, type_V); \ + +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 8, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 8, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 8, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 8, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 8, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 8, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 8, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 8, GGML_TYPE_F16, GGML_TYPE_F16) + +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 16, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 16, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 16, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 16, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 16, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 16, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 16, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 16, GGML_TYPE_F16, GGML_TYPE_F16) + +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 32, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 32, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 32, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 32, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 32, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 32, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 32, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 32, GGML_TYPE_F16, GGML_TYPE_F16) + +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 64, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 64, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 64, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 64, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 64, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 64, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 64, GGML_TYPE_F16, GGML_TYPE_F16) +DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 64, GGML_TYPE_F16, GGML_TYPE_F16) + +extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_MMA_F16_CASE(512, 512, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_MMA_F16_CASE(512, 512, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_MMA_F16_CASE(512, 512, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_MMA_F16_CASE(512, 512, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_MMA_F16_CASE(512, 512, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_MMA_F16_CASE(512, 512, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16); // The number of viable configurations for Deepseek is very limited: -extern DECL_FATTN_MMA_F16_CASE(576, 512, 1, 16); -extern DECL_FATTN_MMA_F16_CASE(576, 512, 2, 16); -extern DECL_FATTN_MMA_F16_CASE(576, 512, 4, 16); +extern DECL_FATTN_MMA_F16_CASE(576, 512, 1, 16, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_MMA_F16_CASE(576, 512, 2, 16, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_MMA_F16_CASE(576, 512, 4, 16, GGML_TYPE_F16, GGML_TYPE_F16); // Mistral Small 4 (DKQ=320, DV=256), GQA=32-only build: -extern DECL_FATTN_MMA_F16_CASE(320, 256, 1, 32); -extern DECL_FATTN_MMA_F16_CASE(320, 256, 2, 32); +extern DECL_FATTN_MMA_F16_CASE(320, 256, 1, 32, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_MMA_F16_CASE(320, 256, 2, 32, GGML_TYPE_F16, GGML_TYPE_F16); // For GLM 4.7 Flash -extern DECL_FATTN_MMA_F16_CASE(576, 512, 4, 4); -extern DECL_FATTN_MMA_F16_CASE(576, 512, 8, 4); -extern DECL_FATTN_MMA_F16_CASE(576, 512, 16, 4); -extern DECL_FATTN_MMA_F16_CASE(576, 512, 1, 32); -extern DECL_FATTN_MMA_F16_CASE(576, 512, 2, 32); +extern DECL_FATTN_MMA_F16_CASE(576, 512, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_MMA_F16_CASE(576, 512, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_MMA_F16_CASE(576, 512, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_MMA_F16_CASE(576, 512, 1, 32, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_MMA_F16_CASE(576, 512, 2, 32, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/fattn-tile.cu b/ggml/src/ggml-cuda/fattn-tile.cu index accef6315a1b..42b488aca0e7 100644 --- a/ggml/src/ggml-cuda/fattn-tile.cu +++ b/ggml/src/ggml-cuda/fattn-tile.cu @@ -1,59 +1,75 @@ #include "common.cuh" #include "fattn-tile.cuh" -void ggml_cuda_flash_attn_ext_tile(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { +template +static void ggml_cuda_flash_attn_ext_tile_switch_head_size(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { const ggml_tensor * K = dst->src[1]; const ggml_tensor * V = dst->src[2]; switch (K->ne[0]) { case 40: { GGML_ASSERT(V->ne[0] == K->ne[0]); - ggml_cuda_flash_attn_ext_tile_case< 40, 40>(ctx, dst); + ggml_cuda_flash_attn_ext_tile_case< 40, 40, type_K, type_V>(ctx, dst); } break; case 64: { GGML_ASSERT(V->ne[0] == K->ne[0]); - ggml_cuda_flash_attn_ext_tile_case< 64, 64>(ctx, dst); + ggml_cuda_flash_attn_ext_tile_case< 64, 64, type_K, type_V>(ctx, dst); } break; case 72: { GGML_ASSERT(V->ne[0] == K->ne[0]); - ggml_cuda_flash_attn_ext_tile_case< 72, 72>(ctx, dst); + ggml_cuda_flash_attn_ext_tile_case< 72, 72, type_K, type_V>(ctx, dst); } break; case 80: { GGML_ASSERT(V->ne[0] == K->ne[0]); - ggml_cuda_flash_attn_ext_tile_case< 80, 80>(ctx, dst); + ggml_cuda_flash_attn_ext_tile_case< 80, 80, type_K, type_V>(ctx, dst); } break; case 96: { GGML_ASSERT(V->ne[0] == K->ne[0]); - ggml_cuda_flash_attn_ext_tile_case< 96, 96>(ctx, dst); + ggml_cuda_flash_attn_ext_tile_case< 96, 96, type_K, type_V>(ctx, dst); } break; case 112: { GGML_ASSERT(V->ne[0] == K->ne[0]); - ggml_cuda_flash_attn_ext_tile_case<112, 112>(ctx, dst); + ggml_cuda_flash_attn_ext_tile_case<112, 112, type_K, type_V>(ctx, dst); } break; case 128: { GGML_ASSERT(V->ne[0] == K->ne[0]); - ggml_cuda_flash_attn_ext_tile_case<128, 128>(ctx, dst); + ggml_cuda_flash_attn_ext_tile_case<128, 128, type_K, type_V>(ctx, dst); } break; case 192: { GGML_ASSERT(V->ne[0] == 128); - ggml_cuda_flash_attn_ext_tile_case<192, 128>(ctx, dst); + ggml_cuda_flash_attn_ext_tile_case<192, 128, type_K, type_V>(ctx, dst); } break; case 256: { GGML_ASSERT(V->ne[0] == K->ne[0]); - ggml_cuda_flash_attn_ext_tile_case<256, 256>(ctx, dst); + ggml_cuda_flash_attn_ext_tile_case<256, 256, type_K, type_V>(ctx, dst); } break; case 320: { GGML_ASSERT(V->ne[0] == 256); - ggml_cuda_flash_attn_ext_tile_case<320, 256>(ctx, dst); + ggml_cuda_flash_attn_ext_tile_case<320, 256, type_K, type_V>(ctx, dst); } break; case 512: { GGML_ASSERT(V->ne[0] == K->ne[0]); - ggml_cuda_flash_attn_ext_tile_case<512, 512>(ctx, dst); + ggml_cuda_flash_attn_ext_tile_case<512, 512, type_K, type_V>(ctx, dst); } break; case 576: { GGML_ASSERT(V->ne[0] == 512); - ggml_cuda_flash_attn_ext_tile_case<576, 512>(ctx, dst); + ggml_cuda_flash_attn_ext_tile_case<576, 512, type_K, type_V>(ctx, dst); } break; default: GGML_ABORT("Unsupported head size"); } } + +void ggml_cuda_flash_attn_ext_tile(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { + const ggml_tensor * K = dst->src[1]; + const ggml_tensor * V = dst->src[2]; + + if constexpr (GGML_CUDA_FA_F16_F16) { + if (K->type == GGML_TYPE_F16 && V->type == GGML_TYPE_F16) { + ggml_cuda_flash_attn_ext_tile_switch_head_size(ctx, dst); + return; + } + } + + // Fallback: convert K and V to F16. + ggml_cuda_flash_attn_ext_tile_switch_head_size(ctx, dst); +} diff --git a/ggml/src/ggml-cuda/fattn-tile.cuh b/ggml/src/ggml-cuda/fattn-tile.cuh index 177b2f0653bf..d15c6c884d8f 100644 --- a/ggml/src/ggml-cuda/fattn-tile.cuh +++ b/ggml/src/ggml-cuda/fattn-tile.cuh @@ -373,133 +373,28 @@ static constexpr __device__ int ggml_cuda_fattn_tile_get_nbatch_K(const int DKQ, return (ggml_cuda_fattn_tile_get_config(DKQ, DV, ncols) >> 23) & ((1 << 9) - 1); } -// TODO: deduplicate with mma-f16 -template -static __device__ __forceinline__ void flash_attn_tile_load_tile( - const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int stride_KV, const int i_sup) { - constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); - constexpr int cpy_ne = cpy_nb / 4; - - auto load = [&] __device__ (const int n) { - const int stride_j = warp_size >> n; - - if (stride_j == 0) { - return; - } - - const int j0_start = stride_j == warp_size ? 0 : ((J/2)/cpy_ne) - ((J/2)/cpy_ne) % (2*stride_j); - const int j0_stop = ((J/2)/cpy_ne) - ((J/2)/cpy_ne) % (1*stride_j); - const int stride_i = warp_size / stride_j; - - if (j0_start == j0_stop) { - return; - } - -#pragma unroll - for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) { - const int i = i0 + threadIdx.y*stride_i + (stride_j == warp_size ? 0 : threadIdx.x / stride_j); - - if (i0 + nwarps*stride_i <= I || i < I) { -#pragma unroll - for (int j0 = j0_start; j0 < j0_stop; j0 += stride_j) { - const int j = j0*cpy_ne + (stride_j == warp_size ? threadIdx.x : threadIdx.x % stride_j)*cpy_ne; - - const __align__(16) half2 zero[cpy_ne] = {{0.0f, 0.0f}}; - ggml_cuda_memcpy_1( - tile_KV + i*(J/2 + J_padding) + j, - !oob_check || i < i_sup ? KV + i*stride_KV + j : zero); - } - } - } - }; - // 1: max 64*16=512 bytes, 512 half - // 2: max 32*16=512 bytes, 256 half - // 3: max 16*16=256 bytes, 128 half - // 4: max 8*16=128 bytes, 64 half - // 5: max 4*16= 64 bytes, 32 half - // 6: max 2*16= 32 bytes, 16 half - // 7: max 1*16= 16 bytes, 8 half - static_assert(J % 8 == 0, "bad J"); - static_assert((J/2) % cpy_ne == 0, "bad J"); - ggml_cuda_unroll<7>{}(load); -} - -template -static __device__ __forceinline__ void flash_attn_tile_load_tile( - const half2 * const __restrict__ KV, float * const __restrict__ tile_KV, const int stride_KV, const int i_sup) { - constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); - constexpr int cpy_ne = cpy_nb / 4; - - auto load = [&] __device__ (const int n) { - const int stride_j = warp_size >> n; - - if (stride_j == 0) { - return; - } - - const int j0_start = stride_j == warp_size ? 0 : (J/cpy_ne) - (J/cpy_ne) % (2*stride_j); - const int j0_stop = (J/cpy_ne) - (J/cpy_ne) % (1*stride_j); - const int stride_i = warp_size / stride_j; - - if (j0_start == j0_stop) { - return; - } - -#pragma unroll - for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) { - const int i = i0 + threadIdx.y*stride_i + (stride_j == warp_size ? 0 : threadIdx.x / stride_j); - - if (i0 + nwarps*stride_i <= I || i < I) { -#pragma unroll - for (int j0 = j0_start; j0 < j0_stop; j0 += stride_j) { - const int j = j0*(cpy_ne/2) + (stride_j == warp_size ? threadIdx.x : threadIdx.x % stride_j)*(cpy_ne/2); - - const half2 zero[cpy_ne/2] = {{0.0f, 0.0f}}; - __align__(16) half2 tmp_h2[cpy_ne/2]; - ggml_cuda_memcpy_1( - tmp_h2, !oob_check || i < i_sup ? KV + i*stride_KV + j : zero); - - __align__(16) float2 tmp_f2[cpy_ne/2]; -#pragma unroll - for (int l = 0; l < cpy_ne/2; ++l) { - tmp_f2[l] = __half22float2(tmp_h2[l]); - } - ggml_cuda_memcpy_1(tile_KV + i*(J + J_padding) + 2*j, tmp_f2); - } - } - } - }; - // 1: max 32*16=512 bytes, 128 float - // 2: max 16*16=256 bytes, 64 float - // 3: max 8*16=128 bytes, 32 float - // 4: max 4*16= 64 bytes, 16 float - // 5: max 2*16= 32 bytes, 8 float - static_assert(J % 8 == 0, "bad J"); - static_assert(J % cpy_ne == 0, "bad J"); - ggml_cuda_unroll<5>{}(load); -} - // Function that performs a single iteration in for the KQ matrix multiplication: template + bool use_logit_softcap, bool oob_check, typename T_vec_dot, typename T_K> static __device__ __forceinline__ void flash_attn_tile_iter_KQ( T_vec_dot * const Q_tmp, - const half2 * const __restrict__ K_h2, + const T_K * const __restrict__ K_h2, T_vec_dot * const KV_tmp, const int stride_K2, const int k_VKQ_0, const int k_VKQ_sup, const int k_KQ_0, float * KQ_acc) { - constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); + constexpr int cpy_nb = 16; constexpr int cpy_ne = cpy_nb / 4; constexpr int ncols = ncols1*ncols2; constexpr int cpw = ncols > nwarps ? ncols/nwarps : 1; // Q columns per warp constexpr int np = nwarps > ncols ? nwarps/ncols : 1; // number of parallel warps per Q column - flash_attn_tile_load_tile - (K_h2 + int64_t(k_VKQ_0)*stride_K2 + k_KQ_0/2, KV_tmp, stride_K2, k_VKQ_sup); + constexpr int stride_tile_K = std::is_same_v ? nbatch_K/2 + cpy_ne : nbatch_K + cpy_ne; + flash_attn_load_tile + (K_h2 + k_KQ_0/2, KV_tmp, nbatch_K/2, stride_K2, k_VKQ_0, k_VKQ_sup, nullptr); __syncthreads(); #ifdef FAST_FP16_AVAILABLE @@ -556,11 +451,11 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ( // Function that performs a single iteration of the main loop over up to nbatch_fa tokens. template + bool use_logit_softcap, bool oob_check, typename T_vec_dot, typename T_KQ, typename T_acc, typename T_K, typename T_V> static __device__ __forceinline__ void flash_attn_tile_iter( T_vec_dot * const Q_tmp, - const half2 * const __restrict__ K_h2, - const half2 * const __restrict__ V_h2, + const T_K * const __restrict__ K_h2, + const T_V * const __restrict__ V_h2, const half * const __restrict__ mask, const uint3 ne01, const float logit_softcap, @@ -576,7 +471,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter( const int k_VKQ_0, const int k_VKQ_max, const int col_Q_0) { - constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); + constexpr int cpy_nb = 16; constexpr int cpy_ne = cpy_nb / 4; constexpr int ncols = ncols1*ncols2; @@ -716,10 +611,11 @@ static __device__ __forceinline__ void flash_attn_tile_iter( constexpr int nbatch_V = (DV % nbatch_K == 0 ? nbatch_K : nbatch_K*2/3) * nbatch_fa / DV; // Number of V columns that fit in SRAM for K. static_assert(nbatch_fa % nbatch_V == 0, "bad nbatch_V"); static_assert(nbatch_V % np == 0, "bad nbatch_V"); + constexpr int stride_tile_V = std::is_same_v ? DV/2 : DV; #pragma unroll for (int k0 = 0; k0 < nbatch_fa; k0 += nbatch_V) { - flash_attn_tile_load_tile - (V_h2 + int64_t(k_VKQ_0 + k0)*stride_V2, KV_tmp, stride_V2, k_VKQ_sup - k0); + flash_attn_load_tile + (V_h2, KV_tmp, DV/2, stride_V2, k_VKQ_0 + k0, k_VKQ_sup - k0, nullptr); __syncthreads(); #ifdef FAST_FP16_AVAILABLE @@ -788,18 +684,18 @@ static __device__ __forceinline__ void flash_attn_tile_iter( } } -template // D == head size +template // D == head size __launch_bounds__(ggml_cuda_fattn_tile_get_nthreads(DKQ, DV, ncols1*ncols2), ggml_cuda_fattn_tile_get_occupancy(DKQ, DV, ncols1*ncols2)) static __global__ void flash_attn_tile( - const char * Q_ptr, - const char * K_ptr, - const char * V_ptr, - const char * mask_ptr, - const char * sinks_ptr, - const int * KV_max_ptr, - const int * KV_rows_ptr, - float * dst_ptr, - float2 * dst_meta_ptr, + const float2 * Q_ptr, + const char * K_ptr, + const char * V_ptr, + const half * mask_ptr, + const float * sinks_ptr, + const int * KV_max_ptr, + const int * KV_rows_ptr, + float * dst_ptr, + float2 * dst_meta_ptr, const float scale, const float max_bias, const float m0, @@ -807,21 +703,24 @@ static __global__ void flash_attn_tile( const uint32_t n_head_log2, const float logit_softcap, const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03, - const int32_t nb01, const int32_t nb02, const int32_t nb03, + const int32_t s01, const int32_t s02, const int32_t s03, const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13, - const int32_t nb11, const int32_t nb12, const int64_t nb13, - const int32_t nb21, const int32_t nb22, const int64_t nb23, + const int32_t s11, const int32_t s12, const int64_t s13, + const int32_t s21, const int32_t s22, const int64_t s23, const int32_t ne31, const int32_t ne32, const int32_t ne33, - const int32_t nb31, const int64_t nb32, const int64_t nb33) { + const int32_t s31, const int64_t s32, const int64_t s33) { #ifdef FLASH_ATTN_AVAILABLE - const char * GGML_CUDA_RESTRICT Q = Q_ptr; - const char * GGML_CUDA_RESTRICT K = K_ptr; - const char * GGML_CUDA_RESTRICT V = V_ptr; - const char * GGML_CUDA_RESTRICT mask = mask_ptr; - const char * GGML_CUDA_RESTRICT sinks = sinks_ptr; - const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr; - float * GGML_CUDA_RESTRICT dst = dst_ptr; - float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr; + using T_K = decltype(ggml_cuda_fattn_kv_dtype()); + using T_V = decltype(ggml_cuda_fattn_kv_dtype()); + + const float2 * GGML_CUDA_RESTRICT Q = Q_ptr; + const T_K * GGML_CUDA_RESTRICT K = (const T_K *) K_ptr; + const T_V * GGML_CUDA_RESTRICT V = (const T_V *) V_ptr; + const half * GGML_CUDA_RESTRICT mask = mask_ptr; + const float * GGML_CUDA_RESTRICT sinks = sinks_ptr; + const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr; + float * GGML_CUDA_RESTRICT dst = dst_ptr; + float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr; GGML_UNUSED(KV_rows_ptr); // Skip unused kernel variants for faster compilation: @@ -830,15 +729,22 @@ static __global__ void flash_attn_tile( GGML_UNUSED_VARS(Q, K, V, mask, sinks, KV_max, dst, dst_meta, scale, max_bias, m0, m1, n_head_log2, logit_softcap, ne00, ne01, ne02, ne03, - nb01, nb02, nb03, + s01, s02, s03, ne10, ne11, ne12, ne13, - nb11, nb12, nb13, - nb21, nb22, nb23, + s11, s12, s13, + s21, s22, s23, ne31, ne32, ne33, - nb31, nb32, nb33); + s31, s32, s33); NO_DEVICE_CODE; return; } +#ifdef AMD_MFMA_AVAILABLE + if (ncols1 == 64 && ncols2 == 1) { + // The tile kernel is suffering from register spills for ncols1 == 64 && ncols2 == 1. + NO_DEVICE_CODE; + return; + } +#endif // AMD_MFMA_AVAILABLE static_assert(ggml_cuda_fattn_tile_get_config(DKQ, DV, ncols1*ncols2) != 0, "kernel config not defined"); @@ -855,19 +761,19 @@ static __global__ void flash_attn_tile( const int sequence = blockIdx.z / (ne02/ncols2); const int head0 = blockIdx.z*ncols2 - sequence*ne02; // == blockIdx.z % (ne02/ncols2) const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix. - const float * Q_f = (const float *) (Q + nb03*sequence + nb02* head0); - const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*(head0 / gqa_ratio)); - const half2 * V_h2 = (const half2 *) (V + nb23*sequence + nb22*(head0 / gqa_ratio)); // K and V have same shape + const float2 * Q_f2 = Q + s03*sequence + s02* head0; + const T_K * K_h2 = K + s13*sequence + s12*(head0 / gqa_ratio); + const T_V * V_h2 = V + s23*sequence + s22*(head0 / gqa_ratio); // K and V have same shape - const half * maskh = mask ? (const half *) (mask + nb33*(sequence % ne33) + nb32*(head0 % ne32)) : nullptr; + const half * maskh = mask ? mask + s33*(sequence % ne33) + s32*(head0 % ne32) : nullptr; - const int stride_K2 = nb11 / sizeof(half2); - const int stride_V2 = nb21 / sizeof(half2); - const int stride_mask = nb31 / sizeof(half); + const int stride_K2 = s11; + const int stride_V2 = s21; + const int stride_mask = s31; const float slope = ncols2 == 1 ? get_alibi_slope(max_bias, head0, n_head_log2, m0, m1) : 1.0f; - constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes(); + constexpr int cpy_nb = 16; constexpr int cpy_ne = cpy_nb / 4; constexpr int cpw = ncols > nwarps ? ncols/nwarps : 1; // Q columns per warp. @@ -919,8 +825,7 @@ static __global__ void flash_attn_tile( if (i0 + np*warp_size*cpy_ne_D <= DKQ || i0 + (threadIdx.y % np)*(warp_size*cpy_ne_D) + threadIdx.x*cpy_ne_D < DKQ) { __align__(16) float tmp_f[cpy_ne_D] = {0.0f}; ggml_cuda_memcpy_1 - (tmp_f, &Q_f[c*(nb02/sizeof(float)) + fastmodulo(col_Q_0 + j, ne01)*(nb01/sizeof(float)) - + i0 + (threadIdx.y % np)*(warp_size*cpy_ne_D) + threadIdx.x*cpy_ne_D]); + (tmp_f, Q_f2 + c*s02 + fastmodulo(col_Q_0 + j, ne01)*s01 + i0/2 + (threadIdx.y % np)*(warp_size*(cpy_ne_D/2)) + threadIdx.x*(cpy_ne_D/2)); #pragma unroll for (int i1 = 0; i1 < cpy_ne_D; ++i1) { @@ -1056,7 +961,7 @@ static __global__ void flash_attn_tile( #pragma unroll for (int jc0 = 0; jc0 < cpw; ++jc0) { const int jc = jc0 + (threadIdx.y/np)*cpw; - const float sink = ((const float *) sinks)[head0 + jc % ncols2]; + const float sink = sinks[head0 + jc % ncols2]; float KQ_max_new_j = fmaxf(KQ_max[jc0], sink); const float KQ_max_scale = expf(KQ_max[jc0] - KQ_max_new_j); @@ -1137,18 +1042,21 @@ static __global__ void flash_attn_tile( GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale, max_bias, m0, m1, n_head_log2, logit_softcap, ne00, ne01, ne02, ne03, - nb01, nb02, nb03, + s01, s02, s03, ne10, ne11, ne12, ne13, - nb11, nb12, nb13, - nb21, nb22, nb23, + s11, s12, s13, + s21, s22, s23, ne31, ne32, ne33, - nb31, nb32, nb33); + s31, s32, s33); NO_DEVICE_CODE; #endif // FLASH_ATTN_AVAILABLE } -template +template static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { + using T_K = decltype(ggml_cuda_fattn_kv_dtype()); + using T_V = decltype(ggml_cuda_fattn_kv_dtype()); + const ggml_tensor * Q = dst->src[0]; const int id = ggml_cuda_get_device(); @@ -1159,12 +1067,12 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm #ifdef GGML_USE_HIP if constexpr (DKQ <= 128) { - if (Q->ne[1] > 32/ncols2) { + if (!(amd_mfma_available(cc) && ncols2 == 1) && Q->ne[1] > 32/ncols2) { constexpr int cols_per_block = 64; const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size; const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc); - fattn_kernel_t fattn_kernel = flash_attn_tile; - launch_fattn + fattn_kernel_t fattn_kernel = flash_attn_tile; + launch_fattn (ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size); return; } @@ -1179,8 +1087,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm constexpr int cols_per_block = 32; const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size; const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc); - fattn_kernel_t fattn_kernel = flash_attn_tile; - launch_fattn + fattn_kernel_t fattn_kernel = flash_attn_tile; + launch_fattn (ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size); return; } @@ -1191,8 +1099,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm constexpr int cols_per_block = 16; const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size; const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc); - fattn_kernel_t fattn_kernel = flash_attn_tile; - launch_fattn + fattn_kernel_t fattn_kernel = flash_attn_tile; + launch_fattn (ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size); return; } @@ -1203,8 +1111,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm constexpr int cols_per_block = 8; const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size; const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc); - fattn_kernel_t fattn_kernel = flash_attn_tile; - launch_fattn + fattn_kernel_t fattn_kernel = flash_attn_tile; + launch_fattn (ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size); return; } @@ -1215,8 +1123,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm constexpr int cols_per_block = 4; const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size; const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc); - fattn_kernel_t fattn_kernel = flash_attn_tile; - launch_fattn + fattn_kernel_t fattn_kernel = flash_attn_tile; + launch_fattn (ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size); return; } @@ -1226,8 +1134,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm constexpr int cols_per_block = 2; const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size; const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc); - fattn_kernel_t fattn_kernel = flash_attn_tile; - launch_fattn + fattn_kernel_t fattn_kernel = flash_attn_tile; + launch_fattn (ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size); return; } @@ -1235,7 +1143,7 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm GGML_ABORT("fatal error"); } -template +template static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { const ggml_tensor * KQV = dst; const ggml_tensor * Q = dst->src[0]; @@ -1262,12 +1170,12 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm // Therefore, use a GQA ratio of 16 with 16 columns / block to stay below 48 kiB of SRAM / block. #ifdef GGML_USE_HIP if (use_gqa_opt && gqa_ratio % 32 == 0) { - launch_fattn_tile_switch_ncols1(ctx, dst); + launch_fattn_tile_switch_ncols1(ctx, dst); return; } #else if (use_gqa_opt && gqa_ratio % 16 == 0) { - launch_fattn_tile_switch_ncols1(ctx, dst); + launch_fattn_tile_switch_ncols1(ctx, dst); return; } #endif // GGML_USE_HIP @@ -1276,11 +1184,11 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm if constexpr (DKQ == 576) { if (use_gqa_opt && gqa_ratio % 16 == 0) { - launch_fattn_tile_switch_ncols1(ctx, dst); + launch_fattn_tile_switch_ncols1(ctx, dst); return; } if (use_gqa_opt && gqa_ratio % 4 == 0) { - launch_fattn_tile_switch_ncols1(ctx, dst); + launch_fattn_tile_switch_ncols1(ctx, dst); return; } } @@ -1288,11 +1196,11 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm if constexpr (DKQ == 192) { // MiMo-V2.5 / V2.5-Pro / V2-Flash: gqa_ratio is 8 (SWA) or 16 (full attn) if (use_gqa_opt && gqa_ratio % 16 == 0) { - launch_fattn_tile_switch_ncols1(ctx, dst); + launch_fattn_tile_switch_ncols1(ctx, dst); return; } if (use_gqa_opt && gqa_ratio % 8 == 0) { - launch_fattn_tile_switch_ncols1(ctx, dst); + launch_fattn_tile_switch_ncols1(ctx, dst); return; } GGML_ABORT("flash-attn tile (192/128): expected GQA ratio multiple of 8"); @@ -1300,29 +1208,29 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm if constexpr (DKQ <= 512 && DKQ != 320 && DKQ != 192) { if (use_gqa_opt && gqa_ratio % 8 == 0) { - launch_fattn_tile_switch_ncols1(ctx, dst); + launch_fattn_tile_switch_ncols1(ctx, dst); return; } if (use_gqa_opt && gqa_ratio % 4 == 0) { - launch_fattn_tile_switch_ncols1(ctx, dst); + launch_fattn_tile_switch_ncols1(ctx, dst); return; } if (use_gqa_opt && gqa_ratio % 2 == 0) { - launch_fattn_tile_switch_ncols1(ctx, dst); + launch_fattn_tile_switch_ncols1(ctx, dst); return; } if constexpr (DV <= 256) { - launch_fattn_tile_switch_ncols1(ctx, dst); + launch_fattn_tile_switch_ncols1(ctx, dst); return; } } GGML_ABORT("fatal error"); } -template +template void ggml_cuda_flash_attn_ext_tile_case(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { const ggml_tensor * KQV = dst; @@ -1331,28 +1239,28 @@ void ggml_cuda_flash_attn_ext_tile_case(ggml_backend_cuda_context & ctx, ggml_te if (logit_softcap == 0.0f) { constexpr bool use_logit_softcap = false; - launch_fattn_tile_switch_ncols2(ctx, dst); + launch_fattn_tile_switch_ncols2(ctx, dst); } else { constexpr bool use_logit_softcap = true; - launch_fattn_tile_switch_ncols2(ctx, dst); + launch_fattn_tile_switch_ncols2(ctx, dst); } } void ggml_cuda_flash_attn_ext_tile(ggml_backend_cuda_context & ctx, ggml_tensor * dst); -#define DECL_FATTN_TILE_CASE(DKQ, DV) \ - template void ggml_cuda_flash_attn_ext_tile_case \ - (ggml_backend_cuda_context & ctx, ggml_tensor * dst) \ - -extern DECL_FATTN_TILE_CASE( 40, 40); -extern DECL_FATTN_TILE_CASE( 64, 64); -extern DECL_FATTN_TILE_CASE( 72, 72); -extern DECL_FATTN_TILE_CASE( 80, 80); -extern DECL_FATTN_TILE_CASE( 96, 96); -extern DECL_FATTN_TILE_CASE(112, 112); -extern DECL_FATTN_TILE_CASE(128, 128); -extern DECL_FATTN_TILE_CASE(192, 128); -extern DECL_FATTN_TILE_CASE(256, 256); -extern DECL_FATTN_TILE_CASE(320, 256); -extern DECL_FATTN_TILE_CASE(512, 512); -extern DECL_FATTN_TILE_CASE(576, 512); +#define DECL_FATTN_TILE_CASE(DKQ, DV, type_K, type_V) \ + template void ggml_cuda_flash_attn_ext_tile_case \ + (ggml_backend_cuda_context & ctx, ggml_tensor * dst) \ + +extern DECL_FATTN_TILE_CASE( 40, 40, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_TILE_CASE( 64, 64, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_TILE_CASE( 72, 72, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_TILE_CASE( 80, 80, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_TILE_CASE( 96, 96, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_TILE_CASE(112, 112, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_TILE_CASE(128, 128, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_TILE_CASE(192, 128, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_TILE_CASE(256, 256, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_TILE_CASE(320, 256, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_TILE_CASE(512, 512, GGML_TYPE_F16, GGML_TYPE_F16); +extern DECL_FATTN_TILE_CASE(576, 512, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/fattn-vec.cuh b/ggml/src/ggml-cuda/fattn-vec.cuh index 09a46187d105..978a2a038e32 100644 --- a/ggml/src/ggml-cuda/fattn-vec.cuh +++ b/ggml/src/ggml-cuda/fattn-vec.cuh @@ -19,15 +19,15 @@ static constexpr __device__ int ggml_cuda_fattn_vec_get_nthreads_device() { template // D == head size __launch_bounds__(ggml_cuda_fattn_vec_get_nthreads_device(), 1) static __global__ void flash_attn_ext_vec( - const char * Q_ptr, - const char * K_ptr, - const char * V_ptr, - const char * mask_ptr, - const char * sinks_ptr, - const int * KV_max_ptr, - const int * KV_rows_ptr, - float * dst_ptr, - float2 * dst_meta_ptr, + const float2 * Q_ptr, + const char * K_ptr, + const char * V_ptr, + const half * mask_ptr, + const float * sinks_ptr, + const int * KV_max_ptr, + const int * KV_rows_ptr, + float * dst_ptr, + float2 * dst_meta_ptr, const float scale, const float max_bias, const float m0, @@ -35,22 +35,22 @@ static __global__ void flash_attn_ext_vec( const uint32_t n_head_log2, const float logit_softcap, const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03, - const int32_t nb01, const int32_t nb02, const int32_t nb03, + const int32_t s01, const int32_t s02, const int32_t s03, const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13, - const int32_t nb11, const int32_t nb12, const int64_t nb13, - const int32_t nb21, const int32_t nb22, const int64_t nb23, + const int32_t s11, const int32_t s12, const int64_t s13, + const int32_t s21, const int32_t s22, const int64_t s23, const int32_t ne31, const int32_t ne32, const int32_t ne33, - const int32_t nb31, const int64_t nb32, const int64_t nb33) { + const int32_t s31, const int64_t s32, const int64_t s33) { ggml_cuda_pdl_lc(); #ifdef FLASH_ATTN_AVAILABLE - const char * GGML_CUDA_RESTRICT Q = Q_ptr; - const char * GGML_CUDA_RESTRICT K = K_ptr; - const char * GGML_CUDA_RESTRICT V = V_ptr; - const char * GGML_CUDA_RESTRICT mask = mask_ptr; - const char * GGML_CUDA_RESTRICT sinks = sinks_ptr; - const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr; - float * GGML_CUDA_RESTRICT dst = dst_ptr; - float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr; + const float2 * GGML_CUDA_RESTRICT Q = Q_ptr; + const char * GGML_CUDA_RESTRICT K = K_ptr; + const char * GGML_CUDA_RESTRICT V = V_ptr; + const half * GGML_CUDA_RESTRICT mask = mask_ptr; + const float * GGML_CUDA_RESTRICT sinks = sinks_ptr; + const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr; + float * GGML_CUDA_RESTRICT dst = dst_ptr; + float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr; GGML_UNUSED(KV_rows_ptr); // Skip unused kernel variants for faster compilation: @@ -58,12 +58,12 @@ static __global__ void flash_attn_ext_vec( GGML_UNUSED_VARS(Q, K, V, mask, sinks, KV_max, dst, dst_meta, scale, max_bias, m0, m1, n_head_log2, logit_softcap, ne00, ne01, ne02, ne03, - nb01, nb02, nb03, + s01, s02, s03, ne10, ne11, ne12, ne13, - nb11, nb12, nb13, - nb21, nb22, nb23, + s11, s12, s13, + s21, s22, s23, ne31, ne32, ne33, - nb31, nb32, nb33); + s31, s32, s33); NO_DEVICE_CODE; return; } @@ -108,11 +108,11 @@ static __global__ void flash_attn_ext_vec( const int sequence = blockIdx.z / ne02; const int head = blockIdx.z - sequence*ne02; const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix. - Q += nb03*sequence + nb02* head + nb01*ic0; - K += nb13*sequence + nb12*(head / gqa_ratio); - V += nb23*sequence + nb22*(head / gqa_ratio); + Q += s03*sequence + s02* head + s01*ic0; + K += s13*sequence + s12*(head / gqa_ratio); + V += s23*sequence + s22*(head / gqa_ratio); - const half * maskh = mask ? (const half *) (mask + nb33*(sequence % ne33) + nb32*(head % ne32) + nb31*ic0) : nullptr; + const half * maskh = mask ? mask + s33*(sequence % ne33) + s32*(head % ne32) + s31*ic0 : nullptr; const float slope = get_alibi_slope(max_bias, head, n_head_log2, m0, m1); @@ -176,7 +176,7 @@ static __global__ void flash_attn_ext_vec( tmp_q_ds[threadIdx.x] = make_float2(0.0f, 0.0f); } } else { - const float * Q_f = (const float *) (Q + j*nb01); + const float * Q_f = (const float *) (Q + j*s01); constexpr int nthreads_quantize = D/sizeof(int) < WARP_SIZE ? D/sizeof(int) : WARP_SIZE; #pragma unroll for (int i0 = 0; i0 < int(D/sizeof(int)); i0 += nthreads_quantize) { @@ -206,7 +206,7 @@ static __global__ void flash_attn_ext_vec( } else if constexpr (type_K == GGML_TYPE_F8_E4M3) { #pragma unroll for (int j = 0; j < ncols; ++j) { - const float * Q_j = (const float *) (Q + j*nb01); + const float * Q_j = (const float *) (Q + j*s01); #pragma unroll for (int i0 = 0; i0 < D; i0 += nthreads_KQ*4) { const int i = i0 + (threadIdx.x % nthreads_KQ)*4; @@ -229,7 +229,7 @@ static __global__ void flash_attn_ext_vec( const half2 scale_h2 = make_half2(scale, scale); #pragma unroll for (int j = 0; j < ncols; ++j) { - const float2 * Q_j = (const float2 *) (Q + j*nb01); + const float2 * Q_j = Q + j*s01; #pragma unroll for (int i0 = 0; i0 < D/2; i0 += nthreads_KQ*cpy_ne) { const int i = i0 + (nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ)*cpy_ne; @@ -252,7 +252,7 @@ static __global__ void flash_attn_ext_vec( #else #pragma unroll for (int j = 0; j < ncols; ++j) { - const float2 * Q_j = (const float2 *) (Q + j*nb01); + const float2 * Q_j = Q + j*s01; #pragma unroll for (int i0 = 0; i0 < D/2; i0 += nthreads_KQ*cpy_ne) { const int i = i0 + (nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ)*cpy_ne; @@ -271,12 +271,12 @@ static __global__ void flash_attn_ext_vec( } const int k_VKQ_max = KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11; - K += blockIdx.y*nthreads * nb11; - V += blockIdx.y*nthreads * nb21; + K += blockIdx.y*nthreads * s11; + V += blockIdx.y*nthreads * s21; maskh += blockIdx.y*nthreads; for (int k_VKQ_0 = blockIdx.y*nthreads; k_VKQ_0 < k_VKQ_max; k_VKQ_0 += gridDim.y*nthreads, // Increment pointers after each loop: - K += gridDim.y*nthreads*nb11, V += gridDim.y*nthreads*nb21, maskh += gridDim.y*nthreads) { + K += gridDim.y*nthreads*s11, V += gridDim.y*nthreads*s21, maskh += gridDim.y*nthreads) { // Calculate KQ tile and keep track of new maximum KQ values: float KQ_reg[ncols]; // KQ in registers. @@ -293,7 +293,7 @@ static __global__ void flash_attn_ext_vec( #pragma unroll for (int j = 0; j < ncols; ++j) { - float sum = vec_dot_KQ(K + i_KQ*nb11, Q_reg[j], Q_i32[j], Q_ds[j]); + float sum = vec_dot_KQ(K + i_KQ*s11, Q_reg[j], Q_i32[j], Q_ds[j]); sum = warp_reduce_sum(sum); if (use_logit_softcap) { @@ -357,14 +357,14 @@ static __global__ void flash_attn_ext_vec( half2 tmp[V_rows_per_thread/2]; if constexpr (type_V == GGML_TYPE_BF16) { float2 tmp_f[V_rows_per_thread/2]; - dequantize_V(V + k*nb21, tmp_f, + dequantize_V(V + k*s21, tmp_f, 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); #pragma unroll for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) { tmp[i_VKQ_1] = __float22half2_rn(tmp_f[i_VKQ_1]); } } else { - dequantize_V(V + k*nb21, tmp, + dequantize_V(V + k*s21, tmp, 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); } #pragma unroll @@ -384,7 +384,7 @@ static __global__ void flash_attn_ext_vec( #pragma unroll for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) { float2 tmp[V_rows_per_thread/2]; - dequantize_V(V + k*nb21, tmp, + dequantize_V(V + k*s21, tmp, 2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread); #pragma unroll for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) { @@ -402,7 +402,7 @@ static __global__ void flash_attn_ext_vec( } if (sinks && blockIdx.y == 0) { - const float sink = ((const float *) sinks)[head]; + const float sink = sinks[head]; #pragma unroll for (int j0 = 0; j0 < ncols; j0 += nwarps) { @@ -540,12 +540,12 @@ static __global__ void flash_attn_ext_vec( GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale, max_bias, m0, m1, n_head_log2, logit_softcap, ne00, ne01, ne02, ne03, - nb01, nb02, nb03, + s01, s02, s03, ne10, ne11, ne12, ne13, - nb11, nb12, nb13, - nb21, nb22, nb23, + s11, s12, s13, + s21, s22, s23, ne31, ne32, ne33, - nb31, nb32, nb33); + s31, s32, s33); NO_DEVICE_CODE; #endif // FLASH_ATTN_AVAILABLE } @@ -563,7 +563,7 @@ void ggml_cuda_flash_attn_ext_vec_case_impl(ggml_backend_cuda_context & ctx, ggm const bool need_f16_K = type_K == GGML_TYPE_F16; const bool need_f16_V = type_V == GGML_TYPE_F16; constexpr size_t nbytes_shared = 0; - launch_fattn(ctx, dst, fattn_kernel, nwarps, nbytes_shared, D, need_f16_K, need_f16_V, false, false); + launch_fattn(ctx, dst, fattn_kernel, nwarps, nbytes_shared, D, need_f16_K, need_f16_V, false, false); } template diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index b37065c31dfb..5df28bd1883e 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -159,7 +159,7 @@ bool ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(const int cc, const ggml_ #endif // !defined(GGML_USE_MUSA) } -template +template static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; const ggml_tensor * Q = dst->src[0]; @@ -169,7 +169,7 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ggml_backend_cuda_con // a sparse variant at the full tile width gathers the union of its queries once, prefer it for large batches constexpr bool has_wide_sparse = ggml_cuda_flash_attn_ext_mma_f16_may_use_sparse(DKQ, DV, 64/ncols2, ncols2); if (!(has_wide_sparse && Q->ne[1] > 32/ncols2) && ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, 1, ncols2)) { - ggml_cuda_flash_attn_ext_mma_f16_case(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_case(ctx, dst); return; } } @@ -177,38 +177,39 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ggml_backend_cuda_con if constexpr (ncols2 <= 8) { if (turing_mma_available(cc) && Q->ne[1] <= 8/ncols2) { - ggml_cuda_flash_attn_ext_mma_f16_case(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_case(ctx, dst); return; } } if constexpr (ncols2 <= 16) { if (Q->ne[1] <= 16/ncols2) { - ggml_cuda_flash_attn_ext_mma_f16_case(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_case(ctx, dst); return; } } if (Q->ne[1] <= 32/ncols2 || (GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) == GGML_CUDA_CC_TURING) || (GGML_CUDA_CC_IS_AMD(cc) && DKQ > 256)) { - ggml_cuda_flash_attn_ext_mma_f16_case(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_case(ctx, dst); return; } - ggml_cuda_flash_attn_ext_mma_f16_case(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_case(ctx, dst); } -template +template static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; - const ggml_tensor * KQV = dst; - const ggml_tensor * Q = dst->src[0]; - const ggml_tensor * K = dst->src[1]; - const ggml_tensor * V = dst->src[2]; - const ggml_tensor * mask = dst->src[3]; + const ggml_tensor * KQV = dst; + const ggml_tensor * Q = dst->src[0]; + const ggml_tensor * K = dst->src[1]; + const ggml_tensor * V = dst->src[2]; + const ggml_tensor * mask = dst->src[3]; + const ggml_tensor * kv_rows = dst->src[5]; // with kv_rows the kernel iterates over the mask columns - const int64_t n_kv = dst->src[5] ? dst->src[5]->ne[0] : K->ne[1]; + const int64_t n_kv = kv_rows ? kv_rows->ne[0] : K->ne[1]; float max_bias = 0.0f; memcpy(&max_bias, (const float *) KQV->op_params + 1, sizeof(float)); @@ -235,22 +236,22 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_con // On Volta the GQA optimizations aren't as impactful vs. minimizing wasted compute: if (cc == GGML_CUDA_CC_VOLTA) { if (use_gqa_opt && gqa_ratio % 8 == 0) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } if (use_gqa_opt && gqa_ratio % 4 == 0) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } if constexpr (DKQ <= 256) { if (use_gqa_opt && gqa_ratio % 2 == 0) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } else { GGML_ABORT("fatal error"); @@ -260,44 +261,45 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_con // On RDNA it is preferable to minimize wasted compute vs. duplicate I/O for the mask. if (amd_wmma_available(cc)) { if (use_gqa_opt && gqa_ratio % 8 == 0) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } if (use_gqa_opt && gqa_ratio % 4 == 0) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } if (use_gqa_opt && gqa_ratio % 2 == 0) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } } if (use_gqa_opt && gqa_ratio > 4) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } if (use_gqa_opt && gqa_ratio > 2) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } if (use_gqa_opt && gqa_ratio > 1) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); return; } if constexpr (DKQ <= 256) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ctx, dst); } else { GGML_ABORT("fatal error"); } } -static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { +template +static void ggml_cuda_flash_attn_ext_mma_f16_switch_head_size(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; const ggml_tensor * KQV = dst; const ggml_tensor * Q = dst->src[0]; @@ -308,31 +310,31 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg switch (Q->ne[0]) { case 40: GGML_ASSERT(V->ne[0] == 40); - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 40, 40>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 40, 40, type_K, type_V>(ctx, dst); break; case 64: GGML_ASSERT(V->ne[0] == 64); - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 64, 64>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 64, 64, type_K, type_V>(ctx, dst); break; case 72: GGML_ASSERT(V->ne[0] == 72); - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 72, 72>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 72, 72, type_K, type_V>(ctx, dst); break; case 80: GGML_ASSERT(V->ne[0] == 80); - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 80, 80>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 80, 80, type_K, type_V>(ctx, dst); break; case 96: GGML_ASSERT(V->ne[0] == 96); - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 96, 96>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 96, 96, type_K, type_V>(ctx, dst); break; case 112: GGML_ASSERT(V->ne[0] == 112); - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<112, 112>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<112, 112, type_K, type_V>(ctx, dst); break; case 128: GGML_ASSERT(V->ne[0] == 128); - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<128, 128>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<128, 128, type_K, type_V>(ctx, dst); break; case 192: { // MiMo-V2.5 / V2.5-Pro / V2-Flash: gqa_ratio is 8 (SWA) or 16 (full attn) @@ -344,15 +346,15 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg GGML_ASSERT(Q->ne[2] % K->ne[2] == 0); const int gqa_ratio = Q->ne[2] / K->ne[2]; if (gqa_ratio % 16 == 0) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 16>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 16, type_K, type_V>(ctx, dst); } else { GGML_ASSERT(gqa_ratio % 8 == 0); - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 8>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 8, type_K, type_V>(ctx, dst); } } break; case 256: GGML_ASSERT(V->ne[0] == 256); - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<256, 256>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<256, 256, type_K, type_V>(ctx, dst); break; case 320: // For Mistral Small 4, go straight to the ncols1 switch (ncols2=32-only build). @@ -367,12 +369,12 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg const int gqa_ratio = Q->ne[2] / K->ne[2]; GGML_ASSERT(gqa_ratio % 32 == 0); - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<320, 256, 32>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<320, 256, 32, type_K, type_V>(ctx, dst); } break; case 512: GGML_ASSERT(V->ne[0] == 512); - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<512, 512>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<512, 512, type_K, type_V>(ctx, dst); break; case 576: { // For Deepseek, go straight to the ncols1 switch to avoid compiling unnecessary kernels. @@ -386,50 +388,50 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg GGML_ASSERT(Q->ne[2] % K->ne[2] == 0); const int gqa_ratio = Q->ne[2] / K->ne[2]; if (amd_mfma_available(cc) && ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, 1, 16)) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst); } else if (gqa_ratio == 20 && GGML_CUDA_CC_IS_NVIDIA(cc)) { // GLM 4.7 Flash if (cc >= GGML_CUDA_CC_GB10) { if (Q->ne[1] <= 8) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst); break; } - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst); break; } if (cc >= GGML_CUDA_CC_BLACKWELL) { if (Q->ne[1] <= 4 && K->ne[1] >= 65536) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst); break; } - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst); break; } if (cc >= GGML_CUDA_CC_ADA_LOVELACE) { if (Q->ne[1] <= 4) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst); break; } - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst); break; } if (cc >= GGML_CUDA_CC_TURING) { if (Q->ne[1] <= 4) { if (K->ne[1] <= 16384) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst); break; } - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 32>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 32, type_K, type_V>(ctx, dst); break; } - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst); break; } // Volta: - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst); } else if (gqa_ratio % 16 == 0) { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst); } else { - ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst); + ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst); } } break; default: @@ -437,6 +439,21 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg } } +static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { + const ggml_tensor * K = dst->src[1]; + const ggml_tensor * V = dst->src[2]; + + if constexpr (GGML_CUDA_FA_F16_F16) { + if (K->type == GGML_TYPE_F16 && V->type == GGML_TYPE_F16) { + ggml_cuda_flash_attn_ext_mma_f16_switch_head_size(ctx, dst); + return; + } + } + + // Fallback: convert K and V to F16. + ggml_cuda_flash_attn_ext_mma_f16_switch_head_size(ctx, dst); +} + #define FATTN_VEC_CASE(D, type_K_case, type_V_case) \ if constexpr (GGML_CUDA_FA_##type_K_case##_##type_V_case) { \ if (head_size == (D) && type_K == GGML_TYPE_##type_K_case && type_V == GGML_TYPE_##type_V_case) { \ @@ -732,12 +749,15 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const gqa_ratio_eff *= 2; } + // the tile kernel for DKQ=576 only has the ncols2 = 4 and 16 variants + const best_fattn_kernel tile_kernel = Q->ne[0] == 576 && gqa_ratio % 4 != 0 ? BEST_FATTN_KERNEL_NONE : BEST_FATTN_KERNEL_TILE; + if (volta_mma_available(cc) && Q->ne[0] != 40 && Q->ne[0] != 72) { if (can_use_vector_kernel && Q->ne[1] * gqa_ratio_eff <= 2) { return BEST_FATTN_KERNEL_VEC; } if (Q->ne[1] * gqa_ratio_eff <= 16) { - return BEST_FATTN_KERNEL_TILE; // On Volta tensor cores are only faster for sufficiently large matrices. + return tile_kernel; // On Volta tensor cores are only faster for sufficiently large matrices. } return BEST_FATTN_KERNEL_MMA_F16; } @@ -783,7 +803,7 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const } } } - return BEST_FATTN_KERNEL_TILE; + return tile_kernel; } size_t ggml_cuda_flash_attn_ext_get_alloc_size(int device, const ggml_tensor * dst) { diff --git a/ggml/src/ggml-cuda/fp8.cu b/ggml/src/ggml-cuda/fp8.cu index 5fdec42208c8..e7bfd99d22bc 100644 --- a/ggml/src/ggml-cuda/fp8.cu +++ b/ggml/src/ggml-cuda/fp8.cu @@ -1,9 +1,11 @@ +#include "convert.cuh" #include "fp8.cuh" #if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && CUDART_VERSION >= 11080 +template struct fp8_abs_src { - const float * x; + const src_t * x; int64_t ne0; int64_t ne1; int64_t ne2; @@ -18,12 +20,13 @@ struct fp8_abs_src { i /= ne1; const int64_t i2 = i % ne2; const int64_t i3 = i / ne2; - const float value = fabsf(x[i0 + i1*s1 + i2*s2 + i3*s3]); + const float value = fabsf(ggml_cuda_cast(x[i0 + i1*s1 + i2*s2 + i3*s3])); return isfinite(value) ? value : 448.0f; } }; -static __global__ void fp8_amax_partials(fp8_abs_src src, int64_t ne, float * partials) { +template +static __global__ void fp8_amax_partials(fp8_abs_src src, int64_t ne, float * partials) { float amax = 0.0f; for (int64_t i = (int64_t) blockIdx.x*blockDim.x + threadIdx.x; i < ne; i += (int64_t) blockDim.x*gridDim.x) { amax = fmaxf(amax, src(i)); @@ -49,8 +52,9 @@ static __global__ void fp8_amax_final(const float * partials, int n, float * ama } } +template static __global__ void quantize_fp8_e4m3( - const float * __restrict__ x, uint8_t * __restrict__ y, const float * __restrict__ amax, + const src_t * __restrict__ x, uint8_t * __restrict__ y, const float * __restrict__ amax, float * __restrict__ scale, int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne, int64_t s1, int64_t s2, int64_t s3) { const int64_t i = (int64_t) blockIdx.x*blockDim.x + threadIdx.x; if (i >= ne) { @@ -65,12 +69,26 @@ static __global__ void quantize_fp8_e4m3( const int64_t i3 = tmp / ne2; const float d = *amax > 0.0f ? *amax / 448.0f : 1.0f; - y[i] = ggml_cuda_fp32_to_f8_e4m3(x[i0 + i1*s1 + i2*s2 + i3*s3] / d); + y[i] = ggml_cuda_fp32_to_f8_e4m3(ggml_cuda_cast(x[i0 + i1*s1 + i2*s2 + i3*s3]) / d); if (i == 0) { *scale = d; } } +// src1 (F32 or BF16) to FP8 with one scale for the whole tensor: amax / 448 +template +static void fp8_quantize_src1( + ggml_backend_cuda_context & ctx, const src_t * x, uint8_t * y, float * amax, float * scale, + int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne, int64_t s1, int64_t s2, int64_t s3, cudaStream_t stream) { + const fp8_abs_src abs_src = { x, ne0, ne1, ne2, s1, s2, s3 }; + const int reduce_blocks = std::min((ne + 255)/256, 1024); + ggml_cuda_pool_alloc reduce_tmp(ctx.pool(), reduce_blocks); + fp8_amax_partials<<>>(abs_src, ne, reduce_tmp.ptr); + fp8_amax_final<<<1, 256, 0, stream>>>(reduce_tmp.ptr, reduce_blocks, amax); + + quantize_fp8_e4m3<<<(ne + 255)/256, 256, 0, stream>>>(x, y, amax, scale, ne0, ne1, ne2, ne, s1, s2, s3); +} + static void fp8_set_batch(cublasLtMatrixLayout_t desc, int32_t count, int64_t stride) { CUBLAS_CHECK(cublasLtMatrixLayoutSetAttribute(desc, CUBLASLT_MATRIX_LAYOUT_BATCH_COUNT, &count, sizeof(count))); CUBLAS_CHECK(cublasLtMatrixLayoutSetAttribute(desc, CUBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, &stride, sizeof(stride))); @@ -89,9 +107,9 @@ bool ggml_cuda_mul_mat_fp8( ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, const ggml_tensor * weight_scale) { const int cc = ggml_cuda_info().devices[ctx.device].cc; - if (!fp8_mma_hardware_available(cc) || src0->type != GGML_TYPE_F8_E4M3 || src1->type != GGML_TYPE_F32 || + if (!fp8_mma_hardware_available(cc) || src0->type != GGML_TYPE_F8_E4M3 || (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_BF16) || dst->type != GGML_TYPE_F32 || !ggml_is_contiguous(dst) || src0->ne[0] % 16 != 0 || src0->ne[1] % 16 != 0 || - src0->nb[0] != sizeof(uint8_t) || src0->nb[1] != (size_t) src0->ne[0] || src1->nb[0] != sizeof(float) || + src0->nb[0] != sizeof(uint8_t) || src0->nb[1] != (size_t) src0->ne[0] || src1->nb[0] != ggml_type_size(src1->type) || !ggml_cuda_is_aligned(src0, 16) || !ggml_cuda_is_aligned(dst, 16)) { return false; } @@ -110,18 +128,17 @@ bool ggml_cuda_mul_mat_fp8( ggml_cuda_pool_alloc src1_scale(ctx.pool(), 1); ggml_cuda_pool_alloc src1_amax(ctx.pool(), 1); - const fp8_abs_src abs_src = { - (const float *) src1->data, ne10, ne11, ne12, - (int64_t) (nb11 / sizeof(float)), (int64_t) (nb12 / sizeof(float)), (int64_t) (nb13 / sizeof(float)) - }; - const int reduce_blocks = std::min((ne_src1 + 255)/256, 1024); - ggml_cuda_pool_alloc reduce_tmp(ctx.pool(), reduce_blocks); - fp8_amax_partials<<>>(abs_src, ne_src1, reduce_tmp.ptr); - fp8_amax_final<<<1, 256, 0, stream>>>(reduce_tmp.ptr, reduce_blocks, src1_amax.ptr); - - quantize_fp8_e4m3<<<(ne_src1 + 255)/256, 256, 0, stream>>>( - (const float *) src1->data, src1_fp8.ptr, src1_amax.ptr, src1_scale.ptr, ne10, ne11, ne12, ne_src1, - nb11 / sizeof(float), nb12 / sizeof(float), nb13 / sizeof(float)); + const int64_t s11 = nb11 / nb10; + const int64_t s12 = nb12 / nb10; + const int64_t s13 = nb13 / nb10; + if (src1->type == GGML_TYPE_BF16) { + fp8_quantize_src1(ctx, (const nv_bfloat16 *) src1->data, src1_fp8.ptr, src1_amax.ptr, src1_scale.ptr, + ne10, ne11, ne12, ne_src1, s11, s12, s13, stream); + } else { + GGML_ASSERT(src1->type == GGML_TYPE_F32); + fp8_quantize_src1(ctx, (const float *) src1->data, src1_fp8.ptr, src1_amax.ptr, src1_scale.ptr, + ne10, ne11, ne12, ne_src1, s11, s12, s13, stream); + } CUDA_CHECK(cudaGetLastError()); cublasLtMatmulDesc_t op_desc; diff --git a/ggml/src/ggml-cuda/fusion.cu b/ggml/src/ggml-cuda/fusion.cu new file mode 100644 index 000000000000..bbbb50b4f919 --- /dev/null +++ b/ggml/src/ggml-cuda/fusion.cu @@ -0,0 +1,2982 @@ +#include "fusion.cuh" +#include "graph.cuh" +#include "binbcast.cuh" +#include "dsv4-hc.cuh" +#include "fp8.cuh" +#include "gated_delta_net.cuh" +#include "inkling2.cuh" +#include "mmq.cuh" +#include "mmq-few.cuh" +#include "mmvf.cuh" +#include "mmvq.cuh" +#include "moe-weighted-reduction.cuh" +#include "norm.cuh" +#include "rope.cuh" +#include "snake.cuh" +#include "softcap.cuh" +#include "ssm-conv.cuh" +#include "ssm-scan.cuh" +#include "topk-moe.cuh" +#include "unary.cuh" + +#include +#include + +static bool ggml_cuda_should_fuse_mul_mat(const ggml_tensor * ffn_up, + const ggml_tensor * ffn_gate, + const ggml_tensor * glu, + const ggml_tensor * ffn_up_bias = nullptr, + const ggml_tensor * ffn_gate_bias = nullptr, + const ggml_tensor * ffn_up_scale = nullptr, + const ggml_tensor * ffn_gate_scale = nullptr) { + const bool has_bias = ffn_up_bias != nullptr || ffn_gate_bias != nullptr; + const bool has_scale = ffn_up_scale != nullptr || ffn_gate_scale != nullptr; + + if (has_bias && (!ffn_up_bias || !ffn_gate_bias)) { + return false; + } + if (has_scale && (!ffn_up_scale || !ffn_gate_scale)) { + return false; + } + + const bool is_mul_mat = ffn_up->op == GGML_OP_MUL_MAT && ffn_gate->op == GGML_OP_MUL_MAT && glu->op == GGML_OP_GLU; + const bool is_mul_mat_id = ffn_up->op == GGML_OP_MUL_MAT_ID && ffn_gate->op == GGML_OP_MUL_MAT_ID && glu->op == GGML_OP_GLU; + + GGML_ASSERT(ffn_up && ffn_gate && glu); + + if (!is_mul_mat && !is_mul_mat_id) { + return false; + } + + const ggml_op expected_bias_op = is_mul_mat ? GGML_OP_ADD : GGML_OP_ADD_ID; + const ggml_tensor * ffn_up_bias_src = has_scale ? ffn_up_scale : ffn_up; + const ggml_tensor * ffn_gate_bias_src = has_scale ? ffn_gate_scale : ffn_gate; + const ggml_tensor * ffn_up_out = has_bias ? ffn_up_bias : ffn_up_bias_src; + const ggml_tensor * ffn_gate_out = has_bias ? ffn_gate_bias : ffn_gate_bias_src; + + if (glu->src[0] != ffn_gate_out || glu->src[1] != ffn_up_out) { + return false; + } + + if (has_scale) { + if (ffn_up_scale->op != GGML_OP_MUL || ffn_gate_scale->op != GGML_OP_MUL) { + return false; + } + const bool up_has_mm = ffn_up_scale->src[0] == ffn_up || ffn_up_scale->src[1] == ffn_up; + const bool gate_has_mm = ffn_gate_scale->src[0] == ffn_gate || ffn_gate_scale->src[1] == ffn_gate; + if (!up_has_mm || !gate_has_mm) { + return false; + } + } + + if (has_bias) { + if (ffn_up_bias->op != expected_bias_op || ffn_gate_bias->op != expected_bias_op) { + return false; + } + + if (expected_bias_op == GGML_OP_ADD) { + const bool up_has_mul = ffn_up_bias->src[0] == ffn_up_bias_src || ffn_up_bias->src[1] == ffn_up_bias_src; + const bool gate_has_mul = ffn_gate_bias->src[0] == ffn_gate_bias_src || ffn_gate_bias->src[1] == ffn_gate_bias_src; + if (!up_has_mul || !gate_has_mul) { + return false; + } + } else { // GGML_OP_ADD_ID + if (ffn_up_bias->src[0] != ffn_up_bias_src || ffn_gate_bias->src[0] != ffn_gate_bias_src) { + return false; + } + if (ffn_up_bias->src[2] != ffn_up->src[2] || ffn_gate_bias->src[2] != ffn_gate->src[2]) { + return false; + } + } + } + + if (ffn_up->src[0]->type != ffn_gate->src[0]->type || !ggml_are_same_shape(ffn_up->src[0], ffn_gate->src[0]) || + !ggml_are_same_stride(ffn_up->src[0], ffn_gate->src[0])) { + return false; + } + + if (ffn_up->src[1] != ffn_gate->src[1]) { + return false; + } + + if (is_mul_mat_id && ffn_up->src[2] != ffn_gate->src[2]) { + return false; + } + + static constexpr std::array valid_glu_ops = { GGML_GLU_OP_SWIGLU, GGML_GLU_OP_GEGLU, GGML_GLU_OP_SWIGLU_OAI, GGML_GLU_OP_SWIGLU_CLAMP }; + + if (std::find(valid_glu_ops.begin(), valid_glu_ops.end(), ggml_get_glu_op(glu)) == valid_glu_ops.end()) { + return false; + } + + if (const bool swapped = ggml_get_op_params_i32(glu, 1); swapped) { + return false; + } + + return true; +} + +static bool ggml_cuda_should_fuse_mul_mat_vec_f(const ggml_tensor * tensor, const ggml_tensor * gate = nullptr) { + ggml_tensor * src0 = tensor->src[0]; + ggml_tensor * src1 = tensor->src[1]; + const ggml_tensor * dst = tensor; + + const bool is_mul_mat_id = tensor->op == GGML_OP_MUL_MAT_ID; + + bool use_mul_mat_vec_f = + (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || + src0->type == GGML_TYPE_F8_E4M3) && + (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16) && dst->type == GGML_TYPE_F32; + + const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; + const int warp_size = ggml_cuda_info().devices[ggml_cuda_get_device()].warp_size; + const int64_t ne11 = is_mul_mat_id ? src1->ne[2] : src1->ne[1]; + // a MUL_MAT_ID with an F32 src1 keeps the MUL_MAT rule here, with a BF16 src1 it takes MMVF where + // ggml_cuda_mul_mat_id does, since MMF can not read a BF16 src1 + const bool mul_mat_id_rule = is_mul_mat_id && src1->type == GGML_TYPE_BF16; + use_mul_mat_vec_f = use_mul_mat_vec_f && ggml_cuda_should_use_mmvf(src0, src1->type, cc, warp_size, ne11, mul_mat_id_rule); + + if (gate && !ggml_cuda_should_use_mmvf(gate->src[0], src1->type, cc, warp_size, ne11, mul_mat_id_rule)) { + return false; + } + + //we only support fusion for ncols_dst = 1 + if (tensor->op == GGML_OP_MUL_MAT && dst->ne[1] != 1) { + return false; + } + + if (tensor->op == GGML_OP_MUL_MAT_ID && dst->ne[2] != 1) { + return false; + } + + + return use_mul_mat_vec_f; +} + +static bool ggml_cuda_should_fuse_mul_mat_vec_q(const ggml_tensor * tensor) { + ggml_tensor * src0 = tensor->src[0]; + ggml_tensor * src1 = tensor->src[1]; + const ggml_tensor * dst = tensor; + + const bool bad_padding_clear = ggml_backend_buffer_get_usage(src0->buffer) == GGML_BACKEND_BUFFER_USAGE_COMPUTE && + ggml_nbytes(src0) != ggml_backend_buffer_get_alloc_size(src0->buffer, src0) && + src0->view_src; + + const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; + bool use_mul_mat_vec_q = ggml_cuda_should_use_mmvq(src0->type, cc, src1->ne[1]) && !bad_padding_clear && + (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16) && dst->type == GGML_TYPE_F32; + + // fusion is not universally faster on Pascal + if (cc < GGML_CUDA_CC_VOLTA) { + return false; + } + //we only support fusion for ncols_dst = 1 + if (tensor->op == GGML_OP_MUL_MAT && dst->ne[1] != 1) { + return false; + } + + if (tensor->op == GGML_OP_MUL_MAT_ID && dst->ne[2] > get_mmvq_mmid_max_batch(src0->type, cc)) { + return false; + } + + // do not fuse the matmuls that few-row MMQ takes in ggml_cuda_mul_mat_id + if (tensor->op == GGML_OP_MUL_MAT_ID && ggml_cuda_should_use_mmq_few(src0, src1, tensor->src[2], cc)) { + return false; + } + + return use_mul_mat_vec_q; +} + +static bool ggml_cuda_match_shared_expert(const ggml_cgraph * graph, int routed_idx, int shared_idx) { + if (routed_idx + 2 >= graph->n_nodes || shared_idx + 2 >= graph->n_nodes || shared_idx < routed_idx + 3) { + return false; + } + const int nodes[] = { routed_idx, routed_idx + 1, routed_idx + 2, shared_idx, shared_idx + 1, shared_idx + 2 }; + const ggml_op ops[] = { GGML_OP_MUL_MAT_ID, GGML_OP_MUL_MAT_ID, GGML_OP_GLU, + GGML_OP_MUL_MAT, GGML_OP_MUL_MAT, GGML_OP_GLU }; + const int outputs[] = { routed_idx + 2, shared_idx + 2 }; + if (!ggml_can_fuse_subgraph_ext(graph, nodes, 6, ops, outputs, 2)) { + return false; + } + + const ggml_tensor * routed = graph->nodes[routed_idx + 2]; + const ggml_tensor * shared = graph->nodes[shared_idx + 2]; + const ggml_tensor * gate = routed->src[0]; + const ggml_tensor * up = routed->src[1]; + const ggml_tensor * shared_gate = shared->src[0]; + const ggml_tensor * shared_up = shared->src[1]; + const auto is_pair = [&](const ggml_tensor * a, const ggml_tensor * b, int idx) { + return (a == graph->nodes[idx] && b == graph->nodes[idx + 1]) || + (b == graph->nodes[idx] && a == graph->nodes[idx + 1]); + }; + // only batch-size independent checks here: graph_optimize must produce the same graph topology for every ubatch + // size, otherwise ggml-alloc has to re-reserve (and the scheduler to synchronize) at runtime. + // the MMVQ batch size check is done in ggml_cuda_try_fuse + if (!is_pair(gate, up, routed_idx) || !is_pair(shared_gate, shared_up, shared_idx) || + !ggml_cuda_should_fuse_mul_mat(up, gate, routed) || + !ggml_cuda_should_fuse_mul_mat(shared_up, shared_gate, shared) || + !up->src[0]->buffer || + !ggml_is_quantized(up->src[0]->type)) { + return false; + } + const ggml_tensor * input = up->src[1]; + const ggml_tensor * weight = up->src[0]; + const ggml_tensor * shared_weight = shared_up->src[0]; + if (input->op != GGML_OP_RESHAPE || input->src[0] != shared_up->src[1] || + input->ne[1] != 1 || input->ne[3] != 1 || !ggml_is_contiguous(input) || + !ggml_is_contiguous(shared_up->src[1]) || !ggml_is_matrix(shared_up->src[1]) || + weight->type != shared_weight->type || weight->ne[0] != shared_weight->ne[0] || + weight->ne[1] != shared_weight->ne[1] || weight->nb[1] != shared_weight->nb[1] || weight->ne[3] != 1 || + !ggml_is_matrix(shared_weight) || !ggml_is_contiguous(shared_weight) || + !ggml_is_contiguous(shared_gate->src[0]) || !ggml_is_contiguous(routed) || !ggml_is_contiguous(shared)) { + return false; + } + if (shared_weight->op != GGML_OP_NONE || shared_gate->src[0]->op != GGML_OP_NONE || + ggml_get_glu_op(routed) != ggml_get_glu_op(shared) || + ggml_get_op_params_f32(routed, 3) != ggml_get_op_params_f32(shared, 3)) { + return false; + } + return true; +} + +// The weight scale that scale_node (MUL) applies to the output of mm_node (MUL_MAT), or nullptr. +// Shared by ggml_cuda_try_fuse and graph_optimize so that both accept the same patterns. +static const ggml_tensor * ggml_cuda_get_mul_mat_scale(const ggml_tensor * scale_node, const ggml_tensor * mm_node) { + const bool scale_lhs_mm = scale_node->src[0] == mm_node; + const bool scale_rhs_mm = scale_node->src[1] == mm_node; + if (!scale_lhs_mm && !scale_rhs_mm) { + return nullptr; + } + + const ggml_tensor * scale = scale_lhs_mm ? scale_node->src[1] : scale_node->src[0]; + if ((mm_node->src[0]->type != GGML_TYPE_NVFP4 && mm_node->src[0]->type != GGML_TYPE_F8_E4M3) || scale_node->type != GGML_TYPE_F32 || + scale->type != GGML_TYPE_F32 || !ggml_is_contiguous(scale) || ggml_nelements(scale) != 1 || + !ggml_are_same_shape(scale_node, mm_node)) { + return nullptr; + } + + return scale; +} + +// The same for MUL_MAT_ID with one scale per expert: RESHAPE, REPEAT and GET_ROWS (by the ids) of the scales, then the MUL. +static const ggml_tensor * ggml_cuda_get_mul_mat_id_scale(const ggml_tensor * reshape, const ggml_tensor * repeat, const ggml_tensor * getrows, + const ggml_tensor * scale_node, const ggml_tensor * mm_node) { + if (repeat->src[0] != reshape || getrows->src[0] != repeat || getrows->src[1] != mm_node->src[2]) { + return nullptr; + } + if (!((scale_node->src[0] == mm_node && scale_node->src[1] == getrows) || + (scale_node->src[0] == getrows && scale_node->src[1] == mm_node))) { + return nullptr; + } + + const ggml_tensor * scale = reshape->src[0]; + if ((mm_node->src[0]->type != GGML_TYPE_NVFP4 && mm_node->src[0]->type != GGML_TYPE_F8_E4M3) || scale_node->type != GGML_TYPE_F32 || + scale->type != GGML_TYPE_F32 || !ggml_is_contiguous(scale) || ggml_nelements(scale) != mm_node->src[0]->ne[2] || + !ggml_are_same_shape(scale_node, mm_node)) { + return nullptr; + } + + return scale; +} + +// Buffer- and batch-size independent, so graph_optimize produces the same graph topology for every ubatch size (see #29986). +// up_scale/gate_scale: the MUL nodes that apply the NVFP4 weight scales (per tensor or per expert) between the MUL_MATs and the GLU. +static bool ggml_cuda_mul_mat_q_fusion_matches(const ggml_tensor * up, const ggml_tensor * gate, const ggml_tensor * glu, const int device, + const ggml_tensor * up_scale = nullptr, const ggml_tensor * gate_scale = nullptr) { + const ggml_tensor * x_up = up->src[0]; + const ggml_tensor * y = up->src[1]; + + if ((up->op != GGML_OP_MUL_MAT && up->op != GGML_OP_MUL_MAT_ID) || !ggml_cuda_mmq_fusion_supported(x_up->type) || + (y->type != GGML_TYPE_F32 && y->type != GGML_TYPE_BF16)) { + return false; + } + + // The fused kernel is only compiled for weights whose rows fill whole tiles (no fallback). + if (ggml_cuda_mmq_needs_fallback(x_up->ne[1])) { + return false; + } + + if (!ggml_cuda_should_fuse_mul_mat(up, gate, glu, nullptr, nullptr, up_scale, gate_scale)) { + return false; + } + + // The fused kernel runs both MUL_MATs at one src1 precision, see ggml_cuda_mul_mat_q. + if (ggml_prec_get_src(up, 1) != ggml_prec_get_src(gate, 1)) { + return false; + } + + // The fused write-back applies SWIGLU_OAI with the default alpha and limit of ggml_cuda_op_swiglu_oai_single. + if (ggml_get_glu_op(glu) == GGML_GLU_OP_SWIGLU_OAI && (ggml_get_op_params_f32(glu, 2) != 1.702f || ggml_get_op_params_f32(glu, 3) != 7.0f)) { + return false; + } + + // NVIDIA only: the fused write-back relies on the MMA accumulator layout. + return turing_mma_available(ggml_cuda_info().devices[device].cc); +} + +static bool ggml_cuda_should_fuse_mul_mat_q(const ggml_tensor * up, const ggml_tensor * gate, const ggml_tensor * glu, + const ggml_tensor * up_scale = nullptr, const ggml_tensor * gate_scale = nullptr) { + // A hinted matmul can be fused, but its unfused path may be faster (e.g. FWHT for GGML_HINT_SRC0_IS_HADAMARD). + if (ggml_get_op_params_i32(up, 1) != GGML_HINT_NONE || ggml_get_op_params_i32(gate, 1) != GGML_HINT_NONE) { + return false; + } + + // The padding of a compute-buffer weight that is a view cannot be cleared, see ggml_cuda_mul_mat. + const auto bad_padding_clear = [](const ggml_tensor * x) { + return ggml_backend_buffer_get_usage(x->buffer) == GGML_BACKEND_BUFFER_USAGE_COMPUTE && + ggml_nbytes(x) != ggml_backend_buffer_get_alloc_size(x->buffer, x) && x->view_src; + }; + const int device = ggml_cuda_get_device(); + if (!ggml_cuda_mul_mat_q_fusion_matches(up, gate, glu, device, up_scale, gate_scale) || bad_padding_clear(up->src[0]) || bad_padding_clear(gate->src[0])) { + return false; + } + + // The batch size checks are done here, not in ggml_cuda_mul_mat_q_fusion_matches. + const ggml_tensor * x_up = up->src[0]; + const ggml_tensor * y = up->src[1]; + const int cc = ggml_cuda_info().devices[device].cc; + + // For MUL_MAT_ID: the MMVQ/MMQ choice of ggml_cuda_mul_mat_id, with the nominal tiles of all experts (the per-expert token counts are only known on the GPU). + const bool is_id = up->op == GGML_OP_MUL_MAT_ID; + const int64_t ncols = is_id ? y->ne[2] : y->ne[1]; + const int64_t nchannels = is_id ? x_up->ne[2] : y->ne[2]*y->ne[3]; + const bool use_mmvq = is_id ? ncols <= get_mmvq_mmid_max_batch(x_up->type, cc) : ggml_cuda_should_use_mmvq(x_up->type, cc, ncols); + // do not fuse the matmuls that few-row MMQ takes in ggml_cuda_mul_mat; for MUL_MAT_ID the fused MMQ keeps the expert gate and up + if (!is_id && ggml_cuda_should_use_mmq_few(x_up, y, nullptr, cc)) { + return false; + } + if (use_mmvq || !ggml_cuda_should_use_mmq(x_up->type, cc, ncols, /*n_experts =*/ is_id ? x_up->ne[2] : 0)) { + return false; + } + + // The fused kernel needs one block per tile (no stream-k split), so only fuse if the tiling is efficient. + return ggml_cuda_mmq_fusion_is_efficient(x_up->type, ggml_prec_get_src(up, 1), x_up->ne[1], ncols, nchannels, device); +} + +static bool ggml_cuda_should_fuse_rope_set_rows(const ggml_tensor * rope, + const ggml_tensor * view, + const ggml_tensor * set_rows) { + + if (rope->op != GGML_OP_ROPE || view->op != GGML_OP_VIEW || set_rows->op != GGML_OP_SET_ROWS) { + return false; + } + // ne3 not tested + if (rope->src[0]->ne[3] != 1) { + return false; + } + + if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16 && set_rows->type != GGML_TYPE_BF16) { + return false; + } + + // BF16 rope fuses into an F16 or BF16 cache, other ropes not into a BF16 cache + if (rope->type == GGML_TYPE_BF16 ? set_rows->type == GGML_TYPE_F32 : set_rows->type == GGML_TYPE_BF16) { + return false; + } + + if (set_rows->src[1]->type != GGML_TYPE_I64) { + return false; + } + + // The view should flatten two dims of rope into one dim + if (!ggml_is_contiguous(view) || view->ne[0] != rope->ne[0] * rope->ne[1]) { + return false; + } + + // Only norm/neox/multi shaders have the fusion code + const int mode = ((const int32_t *) rope->op_params)[2]; + if (mode != GGML_ROPE_TYPE_NORMAL && mode != GGML_ROPE_TYPE_NEOX && + mode != GGML_ROPE_TYPE_MROPE && mode != GGML_ROPE_TYPE_IMROPE) { + return false; + } + + return true; +} + +static bool ggml_cuda_should_fuse_rms_norm_mul_rope(const ggml_tensor * rms_norm, + const ggml_tensor * mul, + const ggml_tensor * rope) { + if (rms_norm->op != GGML_OP_RMS_NORM || mul->op != GGML_OP_MUL || rope->op != GGML_OP_ROPE) { + return false; + } + + if (rms_norm->src[0]->type != GGML_TYPE_F32 || rms_norm->type != GGML_TYPE_F32 || + mul->src[0]->type != GGML_TYPE_F32 || mul->src[1]->type != GGML_TYPE_F32 || + mul->type != GGML_TYPE_F32 || rope->type != GGML_TYPE_F32) { + return false; + } + + if (rope->src[0] != mul) { + 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; + } + + if (!ggml_are_same_shape(rms_norm, mul)) { + return false; + } + + //rms_norm kernel assumes contiguous rows + if (!ggml_is_contiguous_rows(rms_norm->src[0]) || + !ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) { + return false; + } + + const int mode = ((const int32_t *) rope->op_params)[2]; + if (mode != GGML_ROPE_TYPE_NORMAL && mode != GGML_ROPE_TYPE_NEOX && + mode != GGML_ROPE_TYPE_MROPE && mode != GGML_ROPE_TYPE_IMROPE) { + return false; + } + + if (mode & GGML_ROPE_TYPE_MROPE) { + int sections[4]; + memcpy(sections, (const int32_t *) rope->op_params + 11, sizeof(int) * 4); + const int sect_dims = sections[0] + sections[1] + sections[2] + sections[3]; + if ((sections[0] <= 0 && sections[1] <= 0 && sections[2] <= 0) || sect_dims <= 0) { + return false; + } + } + + const int n_dims = ((const int32_t *) rope->op_params)[1]; + if (n_dims % 2 != 0 || rope->src[0]->ne[0] % 2 != 0) { + return false; + } + + // ggml_rope_set_offset is not yet supported in the fused kernel + const int n_offs = ((const int32_t *) rope->op_params)[15]; + if (n_offs != 0) { + return false; + } + + return true; +} + +// match gated_delta_net + the strided cpy that scatters its state snapshots into the cache +// (slot i -> rollback group i, slot 0 newest), so the kernel can write them and skip the cpy. +static int ggml_cuda_try_gdn_cache_fusion( + const ggml_cgraph * cgraph, int node_idx, ggml_cuda_gated_delta_net_fused_cache & fused_state_cpy) { + const ggml_tensor * gdn = cgraph->nodes[node_idx]; + // the kernel skips the snapshot tail, so the gdn output must not be a graph output + if (gdn->op != GGML_OP_GATED_DELTA_NET || gdn->type != GGML_TYPE_F32 || + (gdn->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return 0; + } + + const ggml_tensor * src_v = gdn->src[2]; + const int64_t S_v = src_v->ne[0]; + const int64_t H = src_v->ne[1]; + const int64_t n_tokens = src_v->ne[2]; + const int64_t n_seqs = src_v->ne[3]; + const int64_t D = S_v * S_v * H; + const int64_t K = ggml_get_op_params_i32(gdn, 0); // snapshot slot count + const int64_t n_written = std::min(n_tokens, K); // newest n_written slots are written + + // snapshot tail starts right after the attention scores + const size_t tail_off = ggml_row_size(GGML_TYPE_F32, S_v * H * n_tokens * n_seqs); + + // snapshot cpy is the first real node after the gdn (skip views/no-ops) + const ggml_tensor * cpy = nullptr; + int skip = 0; + for (int j = node_idx + 1; j < cgraph->n_nodes && cpy == nullptr; ++j) { + const ggml_tensor * n = cgraph->nodes[j]; + if (ggml_cuda_is_view_or_noop(n)) { + continue; + } + if (n->op != GGML_OP_CPY || (n->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return 0; + } + cpy = n; + skip = j - node_idx; + } + if (cpy == nullptr) { + return 0; + } + + const ggml_tensor * src = cpy->src[0]; // view of the gdn snapshot tail + const ggml_tensor * dst = cpy->src[1]; // cache view the kernel writes to + + // src must be this gdn's snapshot tail (contiguous, at the tail offset) + if (src->op != GGML_OP_VIEW || src->view_src != gdn || src->view_offs != tail_off || + !ggml_is_contiguous(src)) { + return 0; + } + + // dst is the [D, n_seqs, n_written] cache view; require nb[1] == D (the per-seq stride the kernel + // assumes). ggml_cpy pins src to the same element count. + const std::array expected_ne = { D, n_seqs, n_written, 1 }; + if (dst->op != GGML_OP_VIEW || dst->type != GGML_TYPE_F32 || dst->data == nullptr || + !std::equal(expected_ne.begin(), expected_ne.end(), dst->ne) || + dst->nb[0] != ggml_type_size(GGML_TYPE_F32) || dst->nb[1] != (size_t) ggml_row_size(GGML_TYPE_F32, D)) { + return 0; + } + + 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; +} + +// match ssm_scan + the strided cpy that scatters its state snapshots into the cache, so the kernel writes them and skips the cpy +static int ggml_cuda_try_ssm_scan_cache_fusion( + const ggml_cgraph * cgraph, int node_idx, ggml_cuda_ssm_scan_fused_cache & fused_state_cpy) { + const ggml_tensor * ssm = cgraph->nodes[node_idx]; + // the kernel skips the snapshot tail, so the scan output must not be a graph output + if (ssm->op != GGML_OP_SSM_SCAN || ssm->type != GGML_TYPE_F32 || (ssm->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return 0; + } + + const int64_t K = ggml_get_op_params_i32(ssm, 0); // snapshot slot count + + const ggml_tensor * s = ssm->src[0]; + const ggml_tensor * x = ssm->src[1]; + const ggml_tensor * A = ssm->src[3]; + + const int64_t d_state = s->ne[0]; + const int64_t D = d_state * s->ne[1] * x->ne[1]; // d_state * head_dim * n_head + const int64_t n_tok = x->ne[2]; + const int64_t n_seqs = x->ne[3]; + + // only the mamba-2 kernels (group scan and SSD) write to the cache; mamba-1 still uses the cpy + if (A->nb[1] != sizeof(float) || (d_state != 96 && d_state != 128 && d_state != 256)) { + return 0; + } + + // the scan reads its input rows from the cache (picked by ids), so with more than one seq a seq can read a row that another seq writes in the same launch + if (n_seqs != 1) { + return 0; + } + + const int64_t n_written = std::min(n_tok, K); + const size_t tail_off = ggml_row_size(GGML_TYPE_F32, ggml_nelements(x)); + + // snapshot cpy is the first real node after the scan (skip views/no-ops) + const ggml_tensor * cpy = nullptr; + int skip = 0; + for (int j = node_idx + 1; j < cgraph->n_nodes && cpy == nullptr; ++j) { + const ggml_tensor * n = cgraph->nodes[j]; + if (ggml_cuda_is_view_or_noop(n)) { + continue; + } + if (n->op != GGML_OP_CPY || (n->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return 0; + } + cpy = n; + skip = j - node_idx; + } + if (cpy == nullptr) { + return 0; + } + + const ggml_tensor * src = cpy->src[0]; // view of the scan snapshot tail + const ggml_tensor * dst = cpy->src[1]; // cache view the kernel writes to + + // src must be this scan's snapshot tail (contiguous, at the tail offset) + if (src->op != GGML_OP_VIEW || src->view_src != ssm || src->view_offs != tail_off || + !ggml_is_contiguous(src)) { + return 0; + } + + // dst is the [D, n_seqs, n_written] cache view; require nb[1] == D, the per-seq stride the kernel takes from src0->nb[3] + const std::array expected_ne = { D, n_seqs, n_written, 1 }; + if (dst->op != GGML_OP_VIEW || dst->type != GGML_TYPE_F32 || dst->data == nullptr || + !std::equal(expected_ne.begin(), expected_ne.end(), dst->ne) || + dst->nb[0] != ggml_type_size(GGML_TYPE_F32) || dst->nb[1] != (size_t) ggml_row_size(GGML_TYPE_F32, D)) { + return 0; + } + + fused_state_cpy.data = (float *) dst->data; // rollback slot 0 (newest) + fused_state_cpy.slot_stride = K > 1 ? (int64_t) (dst->nb[2] / sizeof(float)) : 0; + return skip; +} + +// expert group selection from build_moe_ffn (n_expert_groups > 1) +// src0/src1 index into this table, -1 is the (biased) probs, -2 is not checked +static const struct { + ggml_op op; + int src0; + int src1; +} topk_moe_group_pattern[] = { + { GGML_OP_RESHAPE, -1, -2 }, // 0: [n_exp_per_group, n_expert_groups, n_tokens] + { GGML_OP_RESHAPE, 0, -2 }, // 1: [1, n_exp_per_group, n_expert_groups, n_tokens] + { GGML_OP_ARGSORT, 0, -2 }, // 2 + { GGML_OP_VIEW, 2, -2 }, // 3: top-2 per group + { GGML_OP_GET_ROWS, 1, 3 }, // 4 + { GGML_OP_RESHAPE, 4, -2 }, // 5 + { GGML_OP_SUM_ROWS, 5, -2 }, // 6: group scores + { GGML_OP_RESHAPE, 6, -2 }, // 7 + { GGML_OP_ARGSORT, 7, -2 }, // 8 + { GGML_OP_VIEW, 8, -2 }, // 9: top n_group_used groups + { GGML_OP_GET_ROWS, 0, 9 }, // 10 + { GGML_OP_FILL, 0, -2 }, // 11 + { GGML_OP_SET_ROWS, 10, 9 }, // 12: unused groups -> -inf + { GGML_OP_RESHAPE, 12, -2 }, // 13: [n_expert, n_tokens] +}; + +static bool ggml_cuda_topk_moe_group_fusion(const struct ggml_cgraph * cgraph, int node_idx, const ggml_tensor * selection, ggml_cuda_topk_moe_args & args) { + const int n_ops = (int) std::size(topk_moe_group_pattern); + if (node_idx + n_ops > cgraph->n_nodes) { + return false; + } + + ggml_tensor ** nodes = cgraph->nodes + node_idx; + auto src_ok = [&](const ggml_tensor * src, int idx) { + return idx == -2 || src == (idx == -1 ? selection : nodes[idx]); + }; + + for (int i = 0; i < n_ops; i++) { + const auto & p = topk_moe_group_pattern[i]; + if (nodes[i]->op != p.op || !src_ok(nodes[i]->src[0], p.src0) || !src_ok(nodes[i]->src[1], p.src1)) { + return false; + } + } + + const int n_groups = nodes[0]->ne[1]; + const int n_group_used = nodes[9]->ne[0]; + + if (nodes[3]->ne[0] != 2 || nodes[12]->src[2] != nodes[11] || ggml_get_op_params_f32(nodes[11], 0) != -INFINITY || + n_groups > WARP_SIZE) { + return false; + } + + args.n_groups = n_groups; + args.n_group_used = n_group_used; + return true; +} + +static bool ggml_cuda_topk_moe_fusion(const struct ggml_cgraph * cgraph, int node_idx, ggml_cuda_topk_moe_args & args) { + args.sigmoid = false; + args.sqrt_softplus = false; + args.softmax = false; + args.delayed_softmax = false; + args.prob_bias = false; + args.norm = false; + args.norm_bias = false; + args.n_groups = 0; + args.n_group_used = 0; + + const int n_nodes = cgraph->n_nodes; + ggml_tensor ** nodes = cgraph->nodes; + + if (nodes[node_idx]->op == GGML_OP_SOFT_MAX) { + args.softmax = true; + } + + if (nodes[node_idx]->op == GGML_OP_UNARY) { + const ggml_unary_op unary_op = ggml_get_unary_op(nodes[node_idx]); + if (unary_op == GGML_UNARY_OP_SIGMOID) { + args.sigmoid = true; + } else if (unary_op == GGML_UNARY_OP_SOFTPLUS && node_idx + 1 < n_nodes && + nodes[node_idx + 1]->op == GGML_OP_SQRT && nodes[node_idx + 1]->src[0] == nodes[node_idx]) { + // sqrt(softplus(x)) scoring (DeepSeek-V4) + args.sqrt_softplus = true; + node_idx++; + } else { + return false; + } + } + + if (nodes[node_idx]->op == GGML_OP_ARGSORT) { + args.delayed_softmax = true; + } + + node_idx++; + + if (args.sigmoid || args.sqrt_softplus || args.softmax) { + // SOFTMAX -> RESHAPE + if (node_idx >= n_nodes || nodes[node_idx]->op != GGML_OP_RESHAPE || + nodes[node_idx]->src[0] != nodes[node_idx - 1]) { + return false; + } + ggml_tensor * probs_reshaped = nodes[node_idx]; + node_idx++; + + if (node_idx >= n_nodes) { + return false; + } + + // src of bias add is the unreshaped probs (-2 instead of -1) + const ggml_tensor * selection = nodes[node_idx - 2]; + if (nodes[node_idx]->op == GGML_OP_ADD && nodes[node_idx]->src[0] == selection) { + args.prob_bias = true; + selection = nodes[node_idx]; + node_idx++; + } + + if (ggml_cuda_topk_moe_group_fusion(cgraph, node_idx, selection, args)) { + node_idx += (int) std::size(topk_moe_group_pattern); + selection = nodes[node_idx - 1]; + } + + // RESHAPE/ADD/group mask -> ARGSORT + if (node_idx >= n_nodes || nodes[node_idx]->op != GGML_OP_ARGSORT || nodes[node_idx]->src[0] != selection) { + return false; + } + + node_idx++; + + // ARGSORT-> VIEW + if (node_idx >= n_nodes || nodes[node_idx]->op != GGML_OP_VIEW || + nodes[node_idx]->src[0] != nodes[node_idx - 1]) { + return false; + } + + // kept groups must hold all used experts + if (args.n_groups > 0 && nodes[node_idx]->ne[0] > args.n_group_used * (probs_reshaped->ne[1] / args.n_groups)) { + return false; + } + node_idx++; + + if (node_idx >= n_nodes || nodes[node_idx]->op != GGML_OP_GET_ROWS) { + return false; + } + + // GET_ROWS + if (nodes[node_idx]->src[0] != probs_reshaped || nodes[node_idx]->src[1] != nodes[node_idx - 1]) { + return false; + } + node_idx++; + } else if (args.delayed_softmax) { + if (node_idx - 2 < 0) { + return false; + } + ggml_tensor * probs_reshaped = nodes[node_idx - 2]; + + // VIEW->ARGSORT + if (node_idx >= n_nodes || nodes[node_idx]->op != GGML_OP_VIEW || + nodes[node_idx]->src[0] != nodes[node_idx - 1]) { + return false; + } + node_idx++; + + // GET_ROWS + if (node_idx >= n_nodes || nodes[node_idx]->src[1] != nodes[node_idx - 1] || + nodes[node_idx]->src[0] != probs_reshaped) { + return false; + } + node_idx++; + + static const std::vector remaining_ops = { GGML_OP_RESHAPE, GGML_OP_SOFT_MAX, GGML_OP_RESHAPE }; + + for (const ggml_op op : remaining_ops) { + if (node_idx >= n_nodes || nodes[node_idx]->op != op || nodes[node_idx]->src[0] != nodes[node_idx - 1]) { + return false; + } + node_idx++; + } + } + + // At this point we can check for norm + scale. Everything is now at least valid till the norm + if (node_idx >= n_nodes) { + return true; + } + + if (nodes[node_idx]->op == GGML_OP_RESHAPE) { + //check RESHAPE->SUM_ROWS->CLAMP|SCALE->DIV->RESHAPE + static const std::vector norm_ops = { GGML_OP_RESHAPE, GGML_OP_SUM_ROWS }; + + args.norm = true; + for (const ggml_op op : norm_ops) { + if (nodes[node_idx]->op == op && nodes[node_idx]->src[0] == nodes[node_idx - 1]) { + node_idx++; + } else { + args.norm = false; + return true; + } + } + + // the sum is clamped from below, or a SCALE with scale 1 adds a bias (DeepSeek-V4.1, Inkling 2) + const ggml_tensor * denom = node_idx < n_nodes ? nodes[node_idx] : nullptr; + const bool is_clamp = denom && denom->op == GGML_OP_CLAMP; + const bool is_bias = denom && denom->op == GGML_OP_SCALE && ggml_get_op_params_f32(denom, 0) == 1.0f; + if ((!is_clamp && !is_bias) || denom->src[0] != nodes[node_idx - 1]) { + args.norm = false; + return true; + } + args.norm_bias = is_bias; + node_idx++; + + // DIV <- CLAMP|SCALE, RESHAPE + if (nodes[node_idx]->op != GGML_OP_DIV || nodes[node_idx]->src[1] != nodes[node_idx - 1] || + nodes[node_idx]->src[0] != nodes[node_idx - 3]) { + args.norm = false; + return true; + } + node_idx++; + + if (nodes[node_idx]->op != GGML_OP_RESHAPE || nodes[node_idx]->src[0] != nodes[node_idx - 1]) { + args.norm = false; + return true; + } + + node_idx++; + } + + if (nodes[node_idx]->op == GGML_OP_SCALE && nodes[node_idx]->src[0] == nodes[node_idx - 1]) { + args.scale = true; + } + + return true; +} + +// returns whether the write (out) nodes overwrite the read nodes in operation +static bool ggml_cuda_check_fusion_memory_ranges(const ggml_cgraph * cgraph, + const int node_idx, + const int node_count, + const int * out_nodes, + const int out_count, + const bool is_topk_moe = false) { + auto nodes_overlap = [&](const ggml_tensor * a, const ggml_tensor * b) { + const int64_t a_start = (int64_t) a->data; + const int64_t a_end = a_start + ggml_backend_buft_get_alloc_size(a->buffer->buft, a); + + const int64_t b_start = (int64_t) b->data; + const int64_t b_end = b_start + ggml_backend_buft_get_alloc_size(b->buffer->buft, b); + + if ((b_start <= a_start && a_start < b_end) || (a_start <= b_start && b_start < a_end)) { + return true; + } + + return false; + }; + + bool is_ok = true; + // one block reads all logits before it writes, so logits may alias the out nodes + const ggml_tensor * logits_may_alias = nullptr; + if (is_topk_moe && ggml_nrows(cgraph->nodes[node_idx]) <= TOPK_MOE_ROWS_PER_BLOCK) { + logits_may_alias = cgraph->nodes[node_idx]->src[0]; + } + + for (int i = 0; i < out_count; ++i) { + const ggml_tensor * dst = cgraph->nodes[out_nodes[i]]; + + for (int j = node_idx; j < node_idx + node_count; ++j) { + // Loop over all srcs of all nodes in the fusion. If the src overlaps + // the destination and the src is not an intermediate node that's being + // elided, then disable fusion. + + for (int src_idx = 0; src_idx < GGML_MAX_SRC; ++src_idx) { + const ggml_tensor * src = cgraph->nodes[j]->src[src_idx]; + + if (!src || src->op == GGML_OP_NONE || src == logits_may_alias) { + continue; + } + + if (nodes_overlap(dst, src)) { + bool found = false; + + for (int k = node_idx; k < j; ++k) { + if (cgraph->nodes[k] == src) { + found = true; + break; + } + } + + if (!found) { + is_ok = false; + break; + } + } + } + } + } + + return is_ok; +} + +// The long form spans 2*k + 1 nodes. ggml_can_fuse_subgraph() accepts at most +// 31 nodes, so k <= 15; larger values use the per-operation path. +static constexpr int MOE_WEIGHTED_REDUCTION_MAX_EXPERTS = 15; + +struct ggml_cuda_moe_weighted_reduction_match { + const ggml_tensor * experts = nullptr; + const ggml_tensor * expert_scale = nullptr; + const ggml_tensor * weights = nullptr; + ggml_tensor * dst = nullptr; + int node_count = 0; +}; + +static bool ggml_cuda_match_moe_weighted_reduction( + const ggml_cgraph * cgraph, + int node_idx, + ggml_cuda_moe_weighted_reduction_match & match) { + const ggml_tensor * first = cgraph->nodes[node_idx]; + if (first->op != GGML_OP_MUL || first->type != GGML_TYPE_F32 || !ggml_is_contiguous(first)) { + return false; + } + + auto split_mul = [](const ggml_tensor * mul, const ggml_tensor *& full, const ggml_tensor *& broadcast) { + auto is_weights = [mul](const ggml_tensor * tensor) { + return tensor && tensor->type == GGML_TYPE_F32 && ggml_is_contiguous(tensor) && tensor->ne[0] == 1 && + tensor->ne[1] == mul->ne[1] && tensor->ne[2] == mul->ne[2] && tensor->ne[3] == mul->ne[3]; + }; + auto is_experts = [mul](const ggml_tensor * tensor) { + return tensor && tensor->type == GGML_TYPE_F32 && ggml_is_contiguous(tensor) && + ggml_are_same_shape(tensor, mul); + }; + + if (is_experts(mul->src[0]) && is_weights(mul->src[1])) { + full = mul->src[0]; + broadcast = mul->src[1]; + return true; + } + if (is_experts(mul->src[1]) && is_weights(mul->src[0])) { + full = mul->src[1]; + broadcast = mul->src[0]; + return true; + } + return false; + }; + + const ggml_tensor * weighted = first; + const ggml_tensor * experts = nullptr; + const ggml_tensor * expert_scale = nullptr; + const ggml_tensor * weights = nullptr; + int mul_count = 1; + + // Match both structural forms: + // (experts * expert_scale) * router_weight + // experts * router_weight + // The matcher does not depend on the model or quantization type. + if (node_idx + 1 < cgraph->n_nodes) { + const ggml_tensor * second = cgraph->nodes[node_idx + 1]; + const ggml_tensor * scaled = nullptr; + const ggml_tensor * route = nullptr; + const ggml_tensor * raw = nullptr; + const ggml_tensor * scale = nullptr; + if (second->op == GGML_OP_MUL && second->type == GGML_TYPE_F32 && ggml_is_contiguous(second) && + split_mul(second, scaled, route) && scaled == first && split_mul(first, raw, scale)) { + weighted = second; + experts = raw; + expert_scale = scale; + weights = route; + mul_count = 2; + } + } + + if (experts == nullptr && !split_mul(first, experts, weights)) { + return false; + } + + const int n_expert_used = (int) weighted->ne[1]; + const int64_t n_tokens = weighted->ne[2] * weighted->ne[3]; + if (n_expert_used < 2 || n_expert_used > MOE_WEIGHTED_REDUCTION_MAX_EXPERTS) { + return false; + } + + const int node_count = 2 * n_expert_used + mul_count - 1; + if (node_idx + node_count > cgraph->n_nodes) { + return false; + } + + std::vector ops(node_count, GGML_OP_VIEW); + ops[0] = GGML_OP_MUL; + if (mul_count == 2) { + ops[1] = GGML_OP_MUL; + } + std::vector views; + views.reserve(n_expert_used); + const ggml_tensor * previous = nullptr; + int n_adds = 0; + for (int offset = mul_count; offset < node_count; ++offset) { + const ggml_tensor * candidate = cgraph->nodes[node_idx + offset]; + ops[offset] = candidate->op; + + if (candidate->op == GGML_OP_VIEW) { + const int expert = (int) views.size(); + if (expert >= n_expert_used || candidate->src[0] != weighted || candidate->view_src != weighted || + candidate->type != GGML_TYPE_F32 || candidate->ne[0] != weighted->ne[0] || + candidate->ne[1] != n_tokens || candidate->ne[2] != 1 || candidate->ne[3] != 1 || + candidate->nb[0] != weighted->nb[0] || candidate->nb[1] != weighted->nb[2] || + candidate->view_offs != (size_t) expert * weighted->nb[1]) { + return false; + } + views.push_back(candidate); + continue; + } + + if (candidate->op != GGML_OP_ADD || views.size() < 2 || n_adds + 1 >= (int) views.size()) { + return false; + } + const ggml_tensor * lhs = n_adds == 0 ? views[0] : previous; + const ggml_tensor * rhs = views[n_adds + 1]; + if (candidate->src[0] != lhs || candidate->src[1] != rhs || candidate->type != GGML_TYPE_F32) { + return false; + } + previous = candidate; + ++n_adds; + } + + if ((int) views.size() != n_expert_used || n_adds != n_expert_used - 1 || previous == nullptr) { + return false; + } + if (!ggml_is_contiguous(previous) || previous->ne[0] != weighted->ne[0] || + previous->ne[1] != n_tokens || previous->ne[2] != 1 || previous->ne[3] != 1) { + return false; + } + + const int output_idx = node_idx + node_count - 1; + if (!ggml_can_fuse_subgraph(cgraph, node_idx, node_count, ops.data(), &output_idx, 1)) { + return false; + } + + match.experts = experts; + match.expert_scale = expert_scale; + match.weights = weights; + match.dst = cgraph->nodes[output_idx]; + match.node_count = node_count; + return true; +} + + +static bool ggml_cuda_can_fuse(const struct ggml_cgraph * cgraph, + int node_idx, + std::initializer_list ops, + std::initializer_list unary_ops) { +#ifndef NDEBUG + const size_t num_unary = std::count(ops.begin(), ops.end(), GGML_OP_UNARY); + GGML_ASSERT(unary_ops.size() == num_unary); +#endif + + const auto is_equal = [](const std::initializer_list & list1, + const std::initializer_list & list2) { + return std::equal(list1.begin(), list1.end(), list2.begin(), list2.end()); + }; + + std::initializer_list mul_mat_bias_glu_ops = { GGML_OP_MUL_MAT, GGML_OP_ADD, GGML_OP_MUL_MAT, GGML_OP_ADD, GGML_OP_GLU }; + std::initializer_list mul_mat_id_bias_glu_ops = { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID, GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID, GGML_OP_GLU }; + + std::initializer_list mul_mat_id_glu_ops = { GGML_OP_MUL_MAT_ID, GGML_OP_MUL_MAT_ID, GGML_OP_GLU }; + std::initializer_list mul_mat_glu_ops = { GGML_OP_MUL_MAT, GGML_OP_MUL_MAT, GGML_OP_GLU }; + + if ((is_equal(mul_mat_bias_glu_ops, ops) || is_equal(mul_mat_id_bias_glu_ops, ops)) && + ggml_can_fuse_subgraph(cgraph, node_idx, ops, { node_idx + 4 })) { + const ggml_tensor * ffn_gate = cgraph->nodes[node_idx]; + const ggml_tensor * ffn_gate_bias = cgraph->nodes[node_idx + 1]; + const ggml_tensor * ffn_up = cgraph->nodes[node_idx + 2]; + const ggml_tensor * ffn_up_bias = cgraph->nodes[node_idx + 3]; + const ggml_tensor * glu = cgraph->nodes[node_idx + 4]; + + if (ggml_cuda_should_fuse_mul_mat(ffn_up, ffn_gate, glu, ffn_up_bias, ffn_gate_bias)) { + int out_nodes[] = { node_idx + 4 }; + return ggml_cuda_check_fusion_memory_ranges(cgraph, node_idx, (int)ops.size(), out_nodes, 1); + } + } + + if ((is_equal(mul_mat_id_glu_ops, ops) || is_equal(mul_mat_glu_ops, ops)) && + ggml_can_fuse_subgraph(cgraph, node_idx, ops, { node_idx + 2 })) { + const ggml_tensor * ffn_gate = cgraph->nodes[node_idx]; + const ggml_tensor * ffn_up = cgraph->nodes[node_idx + 1]; + const ggml_tensor * glu = cgraph->nodes[node_idx + 2]; + + if (ggml_cuda_should_fuse_mul_mat(ffn_up, ffn_gate, glu)) { + int out_nodes[] = { node_idx + 2 }; + return ggml_cuda_check_fusion_memory_ranges(cgraph, node_idx, (int)ops.size(), out_nodes, 1); + } + } + + std::initializer_list rms_norm_mul_rope_ops = { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE }; + std::initializer_list rms_norm_mul_rope_set_rows_ops = { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }; + + if (is_equal(rms_norm_mul_rope_set_rows_ops, ops) && ggml_can_fuse_subgraph(cgraph, node_idx, ops, { node_idx + 4 })) { + const ggml_tensor * rms_norm = cgraph->nodes[node_idx]; + const ggml_tensor * mul = cgraph->nodes[node_idx + 1]; + const ggml_tensor * rope = cgraph->nodes[node_idx + 2]; + const ggml_tensor * view = cgraph->nodes[node_idx + 3]; + const ggml_tensor * set_rows = cgraph->nodes[node_idx + 4]; + + if (ggml_check_edges(cgraph, node_idx, {{1, 0, 0}, {2, 0, 1}, {3, 0, 2}, {4, 0, 3}}) && + ggml_cuda_should_fuse_rms_norm_mul_rope(rms_norm, mul, rope) && + ggml_cuda_should_fuse_rope_set_rows(rope, view, set_rows)) { + int out_nodes[] = { node_idx + 4 }; + return ggml_cuda_check_fusion_memory_ranges(cgraph, node_idx, (int)ops.size(), out_nodes, 1); + } + } + + if (is_equal(rms_norm_mul_rope_ops, ops) && ggml_can_fuse(cgraph, node_idx, ops)) { + const ggml_tensor * rms_norm = cgraph->nodes[node_idx]; + const ggml_tensor * mul = cgraph->nodes[node_idx + 1]; + const ggml_tensor * rope = cgraph->nodes[node_idx + 2]; + + if (ggml_cuda_should_fuse_rms_norm_mul_rope(rms_norm, mul, rope)) { + int out_nodes[] = { node_idx + 2 }; + return ggml_cuda_check_fusion_memory_ranges(cgraph, node_idx, (int)ops.size(), out_nodes, 1); + } + return false; + } + + std::initializer_list rope_set_rows_ops = { GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }; + + if (is_equal(rope_set_rows_ops, ops) && ggml_can_fuse_subgraph(cgraph, node_idx, ops, { node_idx + 2 })) { + const ggml_tensor * rope = cgraph->nodes[node_idx]; + const ggml_tensor * view = cgraph->nodes[node_idx + 1]; + const ggml_tensor * set_rows = cgraph->nodes[node_idx + 2]; + + if (ggml_cuda_should_fuse_rope_set_rows(rope, view, set_rows)) { + int out_nodes[] = { node_idx + 2 }; + return ggml_cuda_check_fusion_memory_ranges(cgraph, node_idx, (int)ops.size(), out_nodes, 1); + } + } + + // scale_out*sigmoid(scale_in*post) as the hc_post weights (qwen4exp hc_combine) + std::initializer_list hc_post_gate_ops = { GGML_OP_SCALE, GGML_OP_UNARY, GGML_OP_SCALE, GGML_OP_DSV4_HC_POST }; + + if (is_equal(hc_post_gate_ops, ops) && ggml_can_fuse_subgraph(cgraph, node_idx, ops, { node_idx + 3 })) { + const ggml_tensor * scale_in = cgraph->nodes[node_idx]; + const ggml_tensor * sigmoid = cgraph->nodes[node_idx + 1]; + const ggml_tensor * scale_out = cgraph->nodes[node_idx + 2]; + + // the chain must feed hc_post->src[2]; a bias on either scale is not handled + if (ggml_check_edges(cgraph, node_idx, {{1, 0, 0}, {2, 0, 1}, {3, 2, 2}}) && + ggml_get_unary_op(sigmoid) == GGML_UNARY_OP_SIGMOID && + ggml_get_op_params_f32(scale_in, 1) == 0.0f && ggml_get_op_params_f32(scale_out, 1) == 0.0f && + scale_in->src[0]->type == GGML_TYPE_F32 && scale_out->type == GGML_TYPE_F32 && + ggml_are_same_shape(scale_in->src[0], scale_out)) { + int out_nodes[] = { node_idx + 3 }; + return ggml_cuda_check_fusion_memory_ranges(cgraph, node_idx, (int)ops.size(), out_nodes, 1); + } + return false; + } + + if (!ggml_can_fuse(cgraph, node_idx, ops)) { + return false; + } + + if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_NORM && ops.begin()[1] == GGML_OP_MUL) { + const ggml_tensor * norm = cgraph->nodes[node_idx]; + const ggml_tensor * mul = cgraph->nodes[node_idx + 1]; + const ggml_tensor * weight = mul->src[0] == norm ? mul->src[1] : mul->src[0]; + if (norm->src[0]->type != GGML_TYPE_F32 || norm->type != GGML_TYPE_F32 || mul->type != GGML_TYPE_F32 || + weight->type != GGML_TYPE_F32 || !ggml_is_vector(weight) || weight->ne[0] != norm->ne[0] || + !ggml_is_contiguous(weight)) { + return false; + } + if (ops.size() == 3) { + const ggml_tensor * add = cgraph->nodes[node_idx + 2]; + const ggml_tensor * bias = add->src[0] == mul ? add->src[1] : add->src[0]; + if (ops.begin()[2] != GGML_OP_ADD || add->type != GGML_TYPE_F32 || bias->type != GGML_TYPE_F32 || + !ggml_is_vector(bias) || bias->ne[0] != norm->ne[0] || !ggml_is_contiguous(bias)) { + return false; + } + } + return true; + } + + if ((ops.size() == 2 || ops.size() == 3) && 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]; + const ggml_tensor *add = nullptr; + + if (ops.size() == 3 && ops.begin()[2] == GGML_OP_ADD) { + add = cgraph->nodes[node_idx+2]; + } + + // the mul operand is a norm weight, which model files store as F32; + // the add operand is an F32 bias or a residual with the type of x + const ggml_type type = rms_norm->type; + if ((type != GGML_TYPE_F32 && type != GGML_TYPE_BF16) || rms_norm->src[0]->type != type) { + return false; + } + + const ggml_tensor * mul_src = mul->src[0] == rms_norm ? mul->src[1] : mul->src[0]; + if (mul_src->type != GGML_TYPE_F32 || mul->type != type) { + return false; + } + + if (add) { + const ggml_tensor * add_src = add->src[0] == mul ? add->src[1] : add->src[0]; + if ((add_src->type != GGML_TYPE_F32 && add_src->type != type) || add->type != type) { + 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 kernel assumes contiguous rows + if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) { + return false; + } + + if (add && (!ggml_is_contiguous(add->src[0]) || !ggml_is_contiguous_rows(add->src[1]))) { + return false; + } + + return true; + } + + if (ops.size() == 2 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_SCALE) { + const ggml_tensor * rms_norm = cgraph->nodes[node_idx]; + const ggml_tensor * scale = cgraph->nodes[node_idx+1]; + + if (rms_norm->src[0]->type != GGML_TYPE_F32 || rms_norm->type != GGML_TYPE_F32) { + return false; + } + + float bias; + memcpy(&bias, (const float *) scale->op_params + 1, sizeof(float)); + + return bias == 0.0f && scale->type == GGML_TYPE_F32; + } + + if (ops.size() == 2 && ops.begin()[0] == GGML_OP_SSM_CONV && ops.begin()[1] == GGML_OP_UNARY + && unary_ops.size() == 1 && unary_ops.begin()[0] == GGML_UNARY_OP_SILU) { + const ggml_tensor * ssm_conv = cgraph->nodes[node_idx]; + const ggml_tensor * silu = cgraph->nodes[node_idx+1]; + if (ggml_get_unary_op(silu) != unary_ops.begin()[0]) { + return false; + } + + if (ssm_conv->type != GGML_TYPE_F32 || silu->type != GGML_TYPE_F32) { + return false; + } + + return true; + } + + if (ops.size() == 3 && ops.begin()[0] == GGML_OP_SSM_CONV && ops.begin()[1] == GGML_OP_ADD + && ops.begin()[2] == GGML_OP_UNARY && unary_ops.size() == 1 && unary_ops.begin()[0] == GGML_UNARY_OP_SILU) { + const ggml_tensor * ssm_conv = cgraph->nodes[node_idx]; + const ggml_tensor * add = cgraph->nodes[node_idx+1]; + const ggml_tensor * silu = cgraph->nodes[node_idx+2]; + if (ggml_get_unary_op(silu) != unary_ops.begin()[0]) { + return false; + } + + if (ssm_conv->type != GGML_TYPE_F32 || add->type != GGML_TYPE_F32 || silu->type != GGML_TYPE_F32) { + return false; + } + + // ADD must consume ssm_conv's output and broadcast a 1-D channel-wise bias. + const ggml_tensor * bias = (add->src[0] == ssm_conv) ? add->src[1] : add->src[0]; + if (bias->type != GGML_TYPE_F32 || !ggml_is_contiguous(bias)) { + return false; + } + if (ggml_nelements(bias) != ssm_conv->ne[0] || bias->ne[0] != ssm_conv->ne[0]) { + return false; + } + + return true; + } + + if (ops.size() == 2 && ops.begin()[0] == GGML_OP_UNARY && ops.begin()[1] == GGML_OP_MUL + && unary_ops.size() == 1 && (unary_ops.begin()[0] == GGML_UNARY_OP_SILU || unary_ops.begin()[0] == GGML_UNARY_OP_SIGMOID || unary_ops.begin()[0] == GGML_UNARY_OP_SOFTPLUS)) { + const ggml_tensor * unary = cgraph->nodes[node_idx]; + const ggml_tensor * mul = cgraph->nodes[node_idx+1]; + + if (ggml_get_unary_op(unary) != unary_ops.begin()[0]) { + return false; + } + + if (unary->type != GGML_TYPE_F32 && unary->type != GGML_TYPE_F16 && unary->type != GGML_TYPE_BF16) { + return false; + } + + if (unary->type != mul->type) { + return false; + } + + const ggml_tensor * other = (mul->src[0] == unary) ? mul->src[1] : mul->src[0]; + if (other->type != unary->type) { + return false; + } + if (!ggml_is_contiguous_1(other) || !ggml_is_contiguous_1(unary->src[0]) || !ggml_are_same_shape(other, unary)) { + return false; + } + + return true; + } + + if (ops.size() == 2 && ops.begin()[0] == GGML_OP_UNARY && ops.begin()[1] == GGML_OP_SQR + && unary_ops.size() == 1 && unary_ops.begin()[0] == GGML_UNARY_OP_RELU) { + const ggml_tensor * unary = cgraph->nodes[node_idx]; + const ggml_tensor * sqr = cgraph->nodes[node_idx+1]; + + if (ggml_get_unary_op(unary) != GGML_UNARY_OP_RELU) { + return false; + } + + if (unary->type != GGML_TYPE_F32 && unary->type != GGML_TYPE_F16) { + return false; + } + + if (unary->type != sqr->type) { + return false; + } + + if (!ggml_is_contiguous(unary->src[0])) { + return false; + } + + return true; + } + + if (ops.size() == 3 && ops.begin()[0] == GGML_OP_SCALE && ops.begin()[1] == GGML_OP_UNARY && ops.begin()[2] == GGML_OP_SCALE + && unary_ops.size() == 1 && unary_ops.begin()[0] == GGML_UNARY_OP_TANH) { + const ggml_tensor *scale = cgraph->nodes[node_idx]; + const ggml_tensor *tanh = cgraph->nodes[node_idx+1]; + const ggml_tensor *scale2 = cgraph->nodes[node_idx+2]; + + // the fused softcap kernel is F32 only + if (scale->src[0]->type != GGML_TYPE_F32 || scale->type != GGML_TYPE_F32) { + return false; + } + + // TODO: make the fused softcap kernel stride aware, it reads src and writes dst as dense + if (!ggml_is_contiguous(scale->src[0]) || !ggml_is_contiguous(scale2)) { + return false; + } + + if (ggml_get_unary_op(tanh) != GGML_UNARY_OP_TANH) { + return false; + } + + // Check for bias + if (ggml_get_op_params_f32(scale, 1) != 0.0f || ggml_get_op_params_f32(scale2, 1) != 0.0f) { + return false; + } + + return true; + } + + return false; +} + +// fused op chains of the Inkling 2 graph (inkling2.cuh, ggml_cuda_op_l2_clip) + +static bool ggml_cuda_tensors_overlap(const ggml_tensor * a, const ggml_tensor * b) { + const char * a0 = (const char *) a->data; + const char * b0 = (const char *) b->data; + const char * a1 = a0 + ggml_backend_buft_get_alloc_size(a->buffer->buft, a); + const char * b1 = b0 + ggml_backend_buft_get_alloc_size(b->buffer->buft, b); + return a0 < b1 && b0 < a1; +} + +// a dimension of src broadcasts to dst if it is 1 or equal +static bool ggml_cuda_can_bcast_to(const ggml_tensor * src, const ggml_tensor * dst, int first_dim) { + for (int d = first_dim; d < GGML_MAX_DIMS; ++d) { + if (src->ne[d] != 1 && src->ne[d] != dst->ne[d]) { + return false; + } + } + return true; +} + +// [MUL by a per-column weight] -> L2_NORM -> SCALE [-> MUL by a per-channel/sample factor] +static int ggml_cuda_try_fuse_l2_clip(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) { + const ggml_tensor * node = cgraph->nodes[i]; + const bool has_w = node->op == GGML_OP_MUL; + if (!has_w && node->op != GGML_OP_L2_NORM) { + return 0; + } + + const ggml_tensor * x = node->src[0]; + const ggml_tensor * w = has_w ? node->src[1] : nullptr; + if (x->type != GGML_TYPE_F32 || x->nb[0] != sizeof(float)) { + return 0; + } + if (has_w && (!ggml_are_same_shape(x, node) || w->type != GGML_TYPE_F32 || w->nb[0] != sizeof(float) || + w->ne[0] != x->ne[0] || !ggml_cuda_can_bcast_to(w, x, 1))) { + return 0; + } + + for (const bool has_f : { true, false }) { + ggml_op ops[4]; + int n = 0; + if (has_w) { + ops[n++] = GGML_OP_MUL; + } + ops[n++] = GGML_OP_L2_NORM; + ops[n++] = GGML_OP_SCALE; + if (has_f) { + ops[n++] = GGML_OP_MUL; + } + + if (!ggml_can_fuse(cgraph, i, ops, n)) { + continue; + } + + const ggml_tensor * l2 = cgraph->nodes[i + n - (has_f ? 3 : 2)]; + const ggml_tensor * sc = cgraph->nodes[i + n - (has_f ? 2 : 1)]; + ggml_tensor * dst = cgraph->nodes[i + n - 1]; + const ggml_tensor * f = nullptr; + + if (l2->type != GGML_TYPE_F32 || sc->type != GGML_TYPE_F32 || sc->src[0] != l2 || (has_w && l2->src[0] != node) || + !ggml_is_contiguous(dst)) { + continue; + } + if (has_f) { + f = dst->src[1]; + if (dst->src[0] != sc || f->type != GGML_TYPE_F32 || f->ne[0] != 1 || f->ne[1] != 1 || !ggml_cuda_can_bcast_to(f, dst, 2)) { + continue; + } + } + + // a block reads its row before it writes it, so dst may be x itself but must not overlap it otherwise + const bool x_in_place = x->data == dst->data && ggml_is_contiguous(x); + if ((!x_in_place && ggml_cuda_tensors_overlap(x, dst)) || (w && ggml_cuda_tensors_overlap(w, dst)) || + (f && ggml_cuda_tensors_overlap(f, dst))) { + continue; + } + + ggml_cuda_op_l2_clip(*cuda_ctx, x, w, l2, sc, f, dst); + return n - 1; + } + + return 0; +} + +// situ on the halves of a merged gate_up: SCALE -> TANH -> SCALE, SIGMOID, MUL, (up view) SCALE -> TANH -> SCALE, MUL +static int ggml_cuda_try_fuse_situ(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) { + static constexpr ggml_op ops[] = { + GGML_OP_SCALE, GGML_OP_UNARY, GGML_OP_SCALE, GGML_OP_UNARY, GGML_OP_MUL, GGML_OP_VIEW, + GGML_OP_SCALE, GGML_OP_UNARY, GGML_OP_SCALE, GGML_OP_MUL, + }; + constexpr int n = sizeof(ops)/sizeof(ops[0]); + + if (i + n > cgraph->n_nodes) { + return 0; + } + for (int k = 0; k < n; ++k) { + if (cgraph->nodes[i + k]->op != ops[k]) { + return 0; + } + } + + ggml_tensor ** nd = cgraph->nodes + i; + + const ggml_tensor * gate = nd[0]->src[0]; + const ggml_tensor * up = nd[5]; + + const auto is_mul_of = [](const ggml_tensor * t, const ggml_tensor * a, const ggml_tensor * b) { + return (t->src[0] == a && t->src[1] == b) || (t->src[0] == b && t->src[1] == a); + }; + + if (ggml_get_unary_op(nd[1]) != GGML_UNARY_OP_TANH || ggml_get_unary_op(nd[3]) != GGML_UNARY_OP_SIGMOID || + ggml_get_unary_op(nd[7]) != GGML_UNARY_OP_TANH || + nd[1]->src[0] != nd[0] || nd[2]->src[0] != nd[1] || nd[3]->src[0] != gate || !is_mul_of(nd[4], nd[2], nd[3]) || + nd[6]->src[0] != up || nd[7]->src[0] != nd[6] || nd[8]->src[0] != nd[7] || !is_mul_of(nd[9], nd[4], nd[8])) { + return 0; + } + + if (gate->type != GGML_TYPE_F32 || up->type != GGML_TYPE_F32 || gate->nb[0] != sizeof(float) || up->nb[0] != sizeof(float) || + !ggml_are_same_shape(gate, up) || !ggml_are_same_shape(gate, nd[9]) || !ggml_is_contiguous(nd[9])) { + return 0; + } + for (int k = 0; k < n; ++k) { + if (nd[k]->type != GGML_TYPE_F32) { + return 0; + } + } + + // the up view is a view of a node outside the group, it is not part of the subgraph check + const int idxs[] = { i, i + 1, i + 2, i + 3, i + 4, i + 6, i + 7, i + 8, i + 9 }; + const ggml_op ops_ext[] = { ops[0], ops[1], ops[2], ops[3], ops[4], ops[6], ops[7], ops[8], ops[9] }; + const int out = i + n - 1; + if (!ggml_can_fuse_subgraph_ext(cgraph, idxs, 9, ops_ext, &out, 1) || !ggml_cuda_check_fusion_memory_ranges(cgraph, i, n, &out, 1)) { + return 0; + } + + const float s[4] = { + ggml_get_op_params_f32(nd[0], 0), ggml_get_op_params_f32(nd[2], 0), ggml_get_op_params_f32(nd[6], 0), ggml_get_op_params_f32(nd[8], 0), + }; + const float b[4] = { + ggml_get_op_params_f32(nd[0], 1), ggml_get_op_params_f32(nd[2], 1), ggml_get_op_params_f32(nd[6], 1), ggml_get_op_params_f32(nd[8], 1), + }; + + ggml_cuda_op_situ(*cuda_ctx, gate, up, s, b, nd[9]); + return n - 1; +} + +// depth mix: [RMS_NORM(cur)] -> CONCAT(stack, norm) -> [REPEAT(query)] -> MUL_MAT -> SOFT_MAX, TRANSPOSE -> CONT -> MUL_MAT +static int ggml_cuda_try_fuse_depth_mix(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) { + const ggml_tensor * node = cgraph->nodes[i]; + const bool has_norm = node->op == GGML_OP_RMS_NORM; + + const int j = i + (has_norm ? 1 : 0); + if (j + 1 >= cgraph->n_nodes) { + return 0; + } + + const ggml_tensor * cc = cgraph->nodes[j]; + if (cc->op != GGML_OP_CONCAT || ggml_get_op_params_i32(cc, 0) != 1 || (has_norm && cc->src[1] != node) || + (!has_norm && cc->src[1]->op != GGML_OP_RMS_NORM)) { + return 0; + } + + const bool has_rep = cgraph->nodes[j + 1]->op == GGML_OP_REPEAT; + + ggml_op ops[8]; + int n = 0; + if (has_norm) { + ops[n++] = GGML_OP_RMS_NORM; + } + ops[n++] = GGML_OP_CONCAT; + if (has_rep) { + ops[n++] = GGML_OP_REPEAT; + } + ops[n++] = GGML_OP_MUL_MAT; + ops[n++] = GGML_OP_SOFT_MAX; + ops[n++] = GGML_OP_TRANSPOSE; + ops[n++] = GGML_OP_CONT; + ops[n++] = GGML_OP_MUL_MAT; + + if (i + n > cgraph->n_nodes) { + return 0; + } + for (int k = 0; k < n; ++k) { + if (cgraph->nodes[i + k]->op != ops[k]) { + return 0; + } + } + + const ggml_tensor * rep = has_rep ? cgraph->nodes[j + 1] : nullptr; + const ggml_tensor * mm1 = cgraph->nodes[i + n - 5]; + const ggml_tensor * sm = cgraph->nodes[i + n - 4]; + const ggml_tensor * tr = cgraph->nodes[i + n - 3]; + const ggml_tensor * ct = cgraph->nodes[i + n - 2]; + ggml_tensor * mm2 = cgraph->nodes[i + n - 1]; + + const ggml_tensor * stack = cc->src[0]; + const ggml_tensor * cur = has_norm ? node->src[0] : cc->src[1]; + const ggml_tensor * query = has_rep ? rep->src[0] : mm1->src[1]; + + if (mm1->src[0] != cc || mm1->src[1] != (has_rep ? rep : query) || sm->src[0] != mm1 || sm->src[1] || sm->src[2] || + ggml_get_op_params_f32(sm, 1) != 0.0f || tr->src[0] != cc || ct->src[0] != tr || mm2->src[0] != sm || mm2->src[1] != ct) { + return 0; + } + + const int64_t ne = cur->ne[0]; + const int64_t T = cur->ne[2]; + const int64_t B = stack->ne[1]; + const int64_t Q = query->ne[1]; + + for (const ggml_tensor * t : std::initializer_list{ stack, cur, query, cc, mm1, sm, mm2 }) { + if (t->type != GGML_TYPE_F32) { + return 0; + } + } + if (cur->nb[0] != sizeof(float) || cur->ne[1] != 1 || cur->ne[3] != 1 || !ggml_is_contiguous(stack) || + stack->ne[0] != ne || stack->ne[2] != T || stack->ne[3] != 1 || B < 1 || B > GGML_CUDA_DEPTH_MIX_MAX_ROWS || + !ggml_is_contiguous(query) || query->ne[0] != ne || query->ne[2] != 1 || query->ne[3] != 1 || (!has_rep && T != 1) || + mm2->ne[0] != Q || mm2->ne[1] != ne || mm2->ne[2] != T || !ggml_is_contiguous(mm2)) { + return 0; + } + + const int out = i + n - 1; + if (!ggml_can_fuse_subgraph(cgraph, i, n, ops, &out, 1) || !ggml_cuda_check_fusion_memory_ranges(cgraph, i, n, &out, 1)) { + return 0; + } + + const float eps = has_norm ? ggml_get_op_params_f32(node, 0) : 0.0f; + ggml_cuda_op_depth_mix(*cuda_ctx, stack, cur, has_norm, eps, query, ggml_get_op_params_f32(sm, 0), mm2); + return n - 1; +} + +// loop controller: CONCAT(cur, msg) -> RMS_NORM -> RESHAPE -> MUL_MAT(down) -> MUL_MAT(forget) -> TANH -> MUL(cur) -> SUB(cur), +// MUL_MAT(gain) -> TANH -> MUL(msg) -> ADD +static int ggml_cuda_try_fuse_loop_ctrl(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) { + static constexpr ggml_op ops[] = { + GGML_OP_CONCAT, GGML_OP_RMS_NORM, GGML_OP_RESHAPE, GGML_OP_MUL_MAT, GGML_OP_MUL_MAT, GGML_OP_UNARY, GGML_OP_MUL, GGML_OP_SUB, + GGML_OP_MUL_MAT, GGML_OP_UNARY, GGML_OP_MUL, GGML_OP_ADD, + }; + constexpr int n = sizeof(ops)/sizeof(ops[0]); + + if (i + n > cgraph->n_nodes) { + return 0; + } + for (int k = 0; k < n; ++k) { + if (cgraph->nodes[i + k]->op != ops[k]) { + return 0; + } + } + + ggml_tensor ** nd = cgraph->nodes + i; + + const ggml_tensor * cc = nd[0]; + if (ggml_get_op_params_i32(cc, 0) != 1 || cc->src[0]->op != GGML_OP_RESHAPE || cc->src[1]->op != GGML_OP_RESHAPE) { + return 0; + } + + const ggml_tensor * cur = cc->src[0]->src[0]; + const ggml_tensor * msg = cc->src[1]->src[0]; + const ggml_tensor * down = nd[3]; + const ggml_tensor * wd = down->src[0]; + const ggml_tensor * wf = nd[4]->src[0]; + const ggml_tensor * wg = nd[8]->src[0]; + ggml_tensor * dst = nd[11]; + + if (nd[1]->src[0] != cc || nd[2]->src[0] != nd[1] || down->src[1] != nd[2] || nd[4]->src[1] != down || + ggml_get_unary_op(nd[5]) != GGML_UNARY_OP_TANH || nd[5]->src[0] != nd[4] || + nd[6]->src[0] != nd[5] || nd[6]->src[1] != cur || nd[7]->src[0] != cur || nd[7]->src[1] != nd[6] || + nd[8]->src[1] != down || ggml_get_unary_op(nd[9]) != GGML_UNARY_OP_TANH || nd[9]->src[0] != nd[8] || + nd[10]->src[0] != nd[9] || nd[10]->src[1] != msg || dst->src[0] != nd[7] || dst->src[1] != nd[10]) { + return 0; + } + + const int64_t ne = cur->ne[0]; + const int64_t T = cur->ne[1]; + const int64_t rank = wd->ne[1]; + + if (T > GGML_CUDA_LOOP_CTRL_MAX_TOKENS || !ggml_is_contiguous(cur) || !ggml_is_contiguous(msg) || !ggml_are_same_shape(cur, msg) || + cur->ne[2] != 1 || cur->ne[3] != 1 || !ggml_are_same_shape(cur, dst) || !ggml_is_contiguous(dst) || + !ggml_is_contiguous(down) || down->ne[0] != rank || down->ne[1] != T) { + return 0; + } + for (const ggml_tensor * t : std::initializer_list{ cur, msg, wd, wf, wg, down, dst }) { + if (t->type != GGML_TYPE_F32) { + return 0; + } + } + for (const ggml_tensor * w : { wd, wf, wg }) { + if (!ggml_is_contiguous(w) || w->ne[2] != 1 || w->ne[3] != 1) { + return 0; + } + } + if (wd->ne[0] != 2*ne || wf->ne[0] != rank || wg->ne[0] != rank || wf->ne[1] != ne || wg->ne[1] != ne) { + return 0; + } + + // the down product is written by the first kernel and read by the second, so the output must not overlap it + const int outs[] = { i + 3, i + n - 1 }; + if (!ggml_can_fuse_subgraph(cgraph, i, n, ops, outs, 2) || !ggml_cuda_check_fusion_memory_ranges(cgraph, i, n, outs, 2) || + ggml_cuda_tensors_overlap(dst, down)) { + return 0; + } + + ggml_cuda_op_loop_ctrl(*cuda_ctx, cur, msg, ggml_get_op_params_f32(nd[1], 0), wd, wg, wf, nd[3], dst); + return n - 1; +} + +// short conv: CONCAT(past, cur^T) -> the state store -> SSM_CONV -> RESHAPE -> [taps] -> ADD(cur) -> SCALE [-> ADD] +// each tap: VIEW(x) -> TRANSPOSE -> CONT -> RESHAPE, [RESHAPE(dyn)], VIEW(dyn) -> MUL -> RESHAPE -> ADD +static int ggml_cuda_try_fuse_short_conv(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) { + // the subgraph nodes: 5 for the concat, state store and conv, 7 per tap, 3 for the adds and the scale + constexpr int MAX_NODES = 8 + 7*GGML_CUDA_SHORT_CONV_MAX_K; + + const ggml_tensor * cc = cgraph->nodes[i]; + if (cc->op != GGML_OP_CONCAT || ggml_get_op_params_i32(cc, 0) != 0 || i + 8 > cgraph->n_nodes) { + return 0; + } + + const ggml_tensor * past = cc->src[0]; + const ggml_tensor * xin = cc->src[1]; + + if (cc->type != GGML_TYPE_F32 || past->type != GGML_TYPE_F32 || past->nb[0] != sizeof(float) || cc->ne[3] != 1 || + !ggml_is_contiguous(cc) || xin->op != GGML_OP_TRANSPOSE || xin->src[0]->op != GGML_OP_RESHAPE) { + return 0; + } + + const int64_t K1 = past->ne[0]; + const int64_t C = cc->ne[1]; + const int64_t S = cc->ne[2]; + const int64_t Ts = cc->ne[0] - K1; + const int64_t K = K1 + 1; + + const ggml_tensor * cur = xin->src[0]->src[0]; + if (K < 2 || K > GGML_CUDA_SHORT_CONV_MAX_K || Ts < 1 || past->ne[1] != C || past->ne[2] != S || xin->ne[0] != Ts || + cur->type != GGML_TYPE_F32 || !ggml_is_contiguous(cur) || cur->ne[0] != C || ggml_nelements(cur) != C*Ts*S) { + return 0; + } + + int idxs[MAX_NODES]; + ggml_op ops[MAX_NODES]; + int n_sub = 0; + auto add_node = [&](int k) { + idxs[n_sub] = k; + ops[n_sub] = cgraph->nodes[k]->op; + n_sub++; + }; + + int k = i; + add_node(k++); + + // the state store: the last K - 1 columns of x copied to the cell of each sequence (VIEW, VIEW, CPY), or with rollback + // slots the windows that end at the last kw tokens set into slots kw - 1 .. 0 (VIEW, ARANGE, SCALE, CPY, VIEW, VIEW, SET_ROWS) + const ggml_tensor * cell = nullptr; + int st_idx = -1; + int64_t kw = 1; + int64_t slot_s = 0; + int64_t ch_s = K1; + int64_t seq_s = 0; + if (cgraph->nodes[k + 1]->op == GGML_OP_ARANGE) { + if (k + 7 > cgraph->n_nodes) { + return 0; + } + const ggml_tensor * win = cgraph->nodes[k]; + const ggml_tensor * ar = cgraph->nodes[k + 1]; + const ggml_tensor * sb = cgraph->nodes[k + 2]; + const ggml_tensor * cs = cgraph->nodes[k + 3]; + const ggml_tensor * ord = cgraph->nodes[k + 4]; + const ggml_tensor * sl = cgraph->nodes[k + 5]; + const ggml_tensor * sr = cgraph->nodes[k + 6]; + + const int64_t n_slots = ar->ne[0]; + kw = ord->ne[0]; + + // the slot order {n_slots - 1, ..., 0}, its last kw entries + if (win->op != GGML_OP_VIEW || sb->op != GGML_OP_SCALE || cs->op != GGML_OP_CPY || ord->op != GGML_OP_VIEW || + sl->op != GGML_OP_VIEW || sr->op != GGML_OP_SET_ROWS || + ggml_get_op_params_f32(ar, 0) != 0.0f || ggml_get_op_params_f32(ar, 2) != 1.0f || sb->src[0] != ar || + ggml_get_op_params_f32(sb, 0) != -1.0f || ggml_get_op_params_f32(sb, 1) != (float) (n_slots - 1) || + cs->src[0] != sb || cs->type != GGML_TYPE_I32 || ord->view_src != cs || + ord->view_offs != (size_t) (n_slots - kw)*sizeof(int32_t) || kw < 1 || kw > n_slots || kw > Ts) { + return 0; + } + // window w is x[Ts - (kw - 1) + w, +K - 1) of each channel + if (win->view_src != cc || win->ne[0] != K1 || win->ne[1] != kw || win->ne[2] != C || win->ne[3] != S || + win->nb[0] != sizeof(float) || win->nb[1] != sizeof(float) || win->nb[2] != cc->nb[1] || win->nb[3] != cc->nb[2] || + win->view_offs != (size_t) (Ts - (kw - 1))*sizeof(float)) { + return 0; + } + // SET_ROWS: src[0] the rows, src[1] the indices, src[2] the destination + if (sr->src[0] != win || sr->src[1] != ord || sr->src[2] != sl || sl->type != GGML_TYPE_F32 || sl->nb[0] != sizeof(float) || + sl->ne[0] != K1 || sl->ne[1] != n_slots || sl->ne[2] != C || sl->ne[3] != S) { + return 0; + } + // the slot order is a constant the kernel does not need; the cast is its own src[1], so its uses are checked here + if (ggml_node_get_use_count(cgraph, k + 1) != 1 || ggml_node_get_use_count(cgraph, k + 2) != 1 || + ggml_node_get_use_count(cgraph, k + 3) != 1 + (cs->src[1] == cs ? 1 : 0) || ggml_node_get_use_count(cgraph, k + 4) != 1) { + return 0; + } + cell = sl; + st_idx = k + 6; + slot_s = sl->nb[1]/sizeof(float); + ch_s = sl->nb[2]/sizeof(float); + seq_s = sl->nb[3]/sizeof(float); + add_node(k); // windows + add_node(k + 6); // set_rows, the slots are a view of the state outside the group + k += 7; + } else { + const ggml_tensor * tail = cgraph->nodes[k]; + const ggml_tensor * cpy = cgraph->nodes[k + 2]; + cell = cgraph->nodes[k + 1]; + if (tail->op != GGML_OP_VIEW || cell->op != GGML_OP_VIEW || cpy->op != GGML_OP_CPY || + tail->view_src != cc || tail->view_offs != (size_t) Ts*sizeof(float) || tail->ne[0] != K1 || tail->ne[1] != C || + tail->ne[2] != S || tail->nb[1] != cc->nb[1] || tail->nb[2] != cc->nb[2] || cpy->src[0] != tail || cpy->src[1] != cell || + cell->type != GGML_TYPE_F32 || cell->nb[0] != sizeof(float) || cell->ne[0] != K1*C || ggml_nrows(cell) != S || + ggml_get_op_params_i32(cpy, 0) != 0) { + return 0; + } + st_idx = k + 2; + seq_s = cell->nb[1]/sizeof(float); + add_node(k); // tail + add_node(k + 2); // cpy, the cell is a view of the state outside the group + k += 3; + } + const int cpy_idx = st_idx; + + if (k + 4 > cgraph->n_nodes) { + return 0; + } + const ggml_tensor * conv = cgraph->nodes[k]; + const ggml_tensor * w = conv->src[1]; + const ggml_tensor * out = cgraph->nodes[k + 1]; + if (conv->op != GGML_OP_SSM_CONV || conv->src[0] != cc || w->type != GGML_TYPE_F32 || !ggml_is_contiguous(w) || + w->ne[0] != K || w->ne[1] != C || out->op != GGML_OP_RESHAPE || out->src[0] != conv || out->ne[0] != C || out->ne[1] != Ts*S) { + return 0; + } + add_node(k); + add_node(k + 1); + k += 2; + + // the input-dependent taps, one per lag + const ggml_tensor * dyn = nullptr; + int64_t n_heads = 0; + if (cgraph->nodes[k]->op == GGML_OP_VIEW && cgraph->nodes[k]->view_src == cc) { + for (int64_t lag = 0; lag < K; ++lag) { + if (k + 9 > cgraph->n_nodes) { + return 0; + } + const ggml_tensor * win = cgraph->nodes[k]; + const ggml_tensor * tr = cgraph->nodes[k + 1]; + const ggml_tensor * ct = cgraph->nodes[k + 2]; + const ggml_tensor * wr = cgraph->nodes[k + 3]; + if (win->op != GGML_OP_VIEW || tr->op != GGML_OP_TRANSPOSE || ct->op != GGML_OP_CONT || wr->op != GGML_OP_RESHAPE || + win->view_src != cc || win->view_offs != (size_t) (K1 - lag)*sizeof(float) || win->ne[0] != Ts || win->ne[1] != C || + win->ne[2] != S || win->nb[1] != cc->nb[1] || win->nb[2] != cc->nb[2] || + tr->src[0] != win || ct->src[0] != tr || wr->src[0] != ct) { + return 0; + } + for (int m = 0; m < 4; ++m) { + add_node(k + m); + } + k += 4; + + if (lag == 0) { + const ggml_tensor * d3 = cgraph->nodes[k]; + if (d3->op != GGML_OP_RESHAPE || d3->ne[0] != K || d3->ne[2] != Ts*S) { + return 0; + } + dyn = d3->src[0]; + n_heads = d3->ne[1]; + if (dyn->type != GGML_TYPE_F32 || !ggml_is_contiguous(dyn) || dyn->ne[0] != K*n_heads || n_heads < 1 || C % n_heads != 0) { + return 0; + } + k += 1; // a view of the taps input outside the group + } + + const ggml_tensor * tap = cgraph->nodes[k]; + const ggml_tensor * mul = cgraph->nodes[k + 1]; + const ggml_tensor * term = cgraph->nodes[k + 2]; + const ggml_tensor * add = cgraph->nodes[k + 3]; + if (tap->op != GGML_OP_VIEW || mul->op != GGML_OP_MUL || term->op != GGML_OP_RESHAPE || add->op != GGML_OP_ADD || + tap->view_src != dyn || tap->view_offs != dyn->view_offs + (size_t) lag*sizeof(float) || tap->ne[0] != 1 || + tap->ne[1] != n_heads || tap->nb[1] != dyn->nb[0]*K || tap->nb[2] != dyn->nb[1] || + wr->ne[0] != C/n_heads || wr->ne[1] != n_heads || + mul->src[0] != wr || mul->src[1] != tap || term->src[0] != mul || add->src[0] != out || add->src[1] != term) { + return 0; + } + add_node(k + 1); + add_node(k + 2); + add_node(k + 3); + k += 4; + out = add; + } + } + + if (k + 2 > cgraph->n_nodes) { + return 0; + } + const ggml_tensor * res_add = cgraph->nodes[k]; + ggml_tensor * sc = cgraph->nodes[k + 1]; + if (res_add->op != GGML_OP_ADD || sc->op != GGML_OP_SCALE || res_add->src[0] != cur || res_add->src[1] != out || + sc->src[0] != res_add || !ggml_is_contiguous(sc) || sc->type != GGML_TYPE_F32) { + return 0; + } + add_node(k); + add_node(k + 1); + k += 2; + + // the residual add that follows the attention and FFN output convs + ggml_tensor * dst = sc; + const ggml_tensor * resid = nullptr; + if (k < cgraph->n_nodes && cgraph->nodes[k]->op == GGML_OP_ADD && + (cgraph->nodes[k]->src[0] == sc || cgraph->nodes[k]->src[1] == sc)) { + ggml_tensor * add = cgraph->nodes[k]; + const ggml_tensor * r = add->src[0] == sc ? add->src[1] : add->src[0]; + if (r != sc && r->type == GGML_TYPE_F32 && ggml_is_contiguous(r) && ggml_are_same_shape(r, sc) && + ggml_is_contiguous(add) && add->type == GGML_TYPE_F32) { + int outs[] = { cpy_idx, k }; + add_node(k); + if (ggml_can_fuse_subgraph_ext(cgraph, idxs, n_sub, ops, outs, 2)) { + dst = add; + resid = r; + k += 1; + } else { + n_sub--; + } + } + } + + const int n = k - i; + const int outs[] = { cpy_idx, k - 1 }; + if (!ggml_can_fuse_subgraph_ext(cgraph, idxs, n_sub, ops, outs, 2)) { + return 0; + } + + // the kernel reads past, cur, w, the taps and the residual and writes the state and dst. a thread reads the residual + // and cur at a token right before it writes dst there, so dst may be either of them in place when one thread has + // the whole sequence; any other overlap is rejected + const bool cur_in_place = cur->data == dst->data; + if ((cur_in_place && Ts > 64) || (!cur_in_place && ggml_cuda_tensors_overlap(cur, dst)) || + (resid && resid->data != dst->data && ggml_cuda_tensors_overlap(resid, dst)) || + ggml_cuda_tensors_overlap(cell, dst) || (resid && ggml_cuda_tensors_overlap(resid, cell))) { + return 0; + } + for (const ggml_tensor * t : { cell, (const ggml_tensor *) dst }) { + for (const ggml_tensor * src : { past, w, dyn }) { + if (src && ggml_cuda_tensors_overlap(t, src)) { + return 0; + } + } + } + if (ggml_cuda_tensors_overlap(cell, cur)) { + return 0; + } + + ggml_cuda_short_conv_args args = {}; + args.past = (const float *) past->data; + args.past_s1 = past->nb[1]/sizeof(float); + args.past_s2 = past->nb[2]/sizeof(float); + args.cur = (const float *) cur->data; + args.w = (const float *) w->data; + args.dyn = dyn ? (const float *) dyn->data : nullptr; + args.dyn_s1 = dyn ? dyn->nb[1]/sizeof(float) : 0; + args.n_heads = n_heads; + args.res = resid ? (const float *) resid->data : nullptr; + args.dst = (float *) dst->data; + args.state = (float *) cell->data; + args.state_slot_s = slot_s; + args.state_ch_s = ch_s; + args.state_seq_s = seq_s; + args.kw = kw; + args.run = cur_in_place || Ts <= 8 ? Ts : 1; + args.C = C; + args.K = K; + args.Ts = Ts; + args.S = S; + args.scale = ggml_get_op_params_f32(sc, 0); + args.bias = ggml_get_op_params_f32(sc, 1); + + ggml_cuda_op_short_conv(*cuda_ctx, args); + return n - 1; +} + +static int ggml_cuda_try_fuse_inkling2(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) { + switch (cgraph->nodes[i]->op) { + case GGML_OP_CONCAT: + if (int n = ggml_cuda_try_fuse_short_conv(cuda_ctx, cgraph, i)) { + return n; + } + if (int n = ggml_cuda_try_fuse_loop_ctrl(cuda_ctx, cgraph, i)) { + return n; + } + return ggml_cuda_try_fuse_depth_mix(cuda_ctx, cgraph, i); + case GGML_OP_RMS_NORM: + return ggml_cuda_try_fuse_depth_mix(cuda_ctx, cgraph, i); + case GGML_OP_MUL: + case GGML_OP_L2_NORM: + return ggml_cuda_try_fuse_l2_clip(cuda_ctx, cgraph, i); + case GGML_OP_SCALE: + return ggml_cuda_try_fuse_situ(cuda_ctx, cgraph, i); + default: + return 0; + } +} + +// try and fuse nodes and return the number of nodes to skip +int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) { + if (int n = ggml_cuda_try_fuse_inkling2(cuda_ctx, cgraph, i)) { + return n; + } + + ggml_tensor * node = cgraph->nodes[i]; + + if (node->op == GGML_OP_MUL_MAT_ID && cuda_ctx->stream_context().concurrent_events.empty() && + ggml_cuda_match_shared_expert(cgraph, i, i + 3) && + ggml_cuda_should_fuse_mul_mat_vec_q(cgraph->nodes[i + 2]->src[1])) { + const int outputs[] = { i + 2, i + 5 }; + if (ggml_cuda_check_fusion_memory_ranges(cgraph, i, 6, outputs, 2)) { + ggml_tensor * routed = cgraph->nodes[i + 2]; + ggml_tensor * shared = cgraph->nodes[i + 5]; + const ggml_tensor * up = routed->src[1]; + ggml_cuda_mm_fusion_args_host fusion{}; + fusion.gate = routed->src[0]->src[0]; + fusion.glu_op = ggml_get_glu_op(routed); + fusion.glu_limit = ggml_get_op_params_f32(routed, 3); + fusion.shared_up = shared->src[1]->src[0]; + fusion.shared_gate = shared->src[0]->src[0]; + fusion.shared_dst = shared; + ggml_cuda_mul_mat_vec_q(*cuda_ctx, up->src[0], up->src[1], up->src[2], routed, &fusion); + return 5; + } + } + + if (node->op == GGML_OP_MUL) { + ggml_cuda_moe_weighted_reduction_match match; + if (ggml_cuda_match_moe_weighted_reduction(cgraph, i, match)) { + const int output_idx = i + match.node_count - 1; + if (ggml_cuda_check_fusion_memory_ranges(cgraph, i, match.node_count, &output_idx, 1)) { + ggml_cuda_op_moe_weighted_reduction( + *cuda_ctx, match.experts, match.expert_scale, match.weights, match.dst); + return match.node_count - 1; + } + } + } + + // gated_delta_net -> cpy: scatter recurrent-state snapshots into the cache + if (node->op == GGML_OP_GATED_DELTA_NET) { + ggml_cuda_gated_delta_net_fused_cache fused_state_cpy; + const int nodes_to_skip = ggml_cuda_try_gdn_cache_fusion(cgraph, i, fused_state_cpy); + if (nodes_to_skip > 0) { +#ifdef GGML_CUDA_DEBUG + GGML_LOG_INFO("%s: fused gated_delta_net snapshot copies for %s (skipped %d nodes)\n", + __func__, node->name, nodes_to_skip); +#endif + ggml_cuda_op_gated_delta_net_fused_cache(*cuda_ctx, node, fused_state_cpy); + return nodes_to_skip; + } + } + + // ssm_scan -> cpy: scatter recurrent-state snapshots into the cache + if (node->op == GGML_OP_SSM_SCAN) { + ggml_cuda_ssm_scan_fused_cache fused_state_cpy; + const int nodes_to_skip = ggml_cuda_try_ssm_scan_cache_fusion(cgraph, i, fused_state_cpy); + if (nodes_to_skip > 0) { +#ifdef GGML_CUDA_DEBUG + GGML_LOG_INFO("%s: fused ssm_scan snapshot copies for %s (skipped %d nodes)\n", + __func__, node->name, nodes_to_skip); +#endif + ggml_cuda_op_ssm_scan_fused_cache(*cuda_ctx, node, fused_state_cpy); + return nodes_to_skip; + } + } + + //topk-moe + if (cgraph->nodes[i]->op == GGML_OP_UNARY || cgraph->nodes[i]->op == GGML_OP_SOFT_MAX || + cgraph->nodes[i]->op == GGML_OP_ARGSORT) { + ggml_cuda_topk_moe_args args; + const bool can_fuse = ggml_cuda_topk_moe_fusion(cgraph, i, args); + std::vector ops; + ops.reserve(13); // max ops; avoids gcc -Wstringop-overflow false positive + + if (can_fuse) { + const ggml_tensor * logits = node->src[0]; + ggml_tensor * weights = nullptr; + ggml_tensor * ids = nullptr; + const ggml_tensor * bias = nullptr; + const ggml_tensor * denom = nullptr; + const ggml_tensor * scale = nullptr; + + if (!args.delayed_softmax) { + int out_nodes[2]; // nodes which can't be elided + + if (args.sigmoid) { + ops.insert(ops.end(), { GGML_OP_UNARY }); + } else if (args.sqrt_softplus) { + ops.insert(ops.end(), { GGML_OP_UNARY, GGML_OP_SQRT }); + } else { + ops.insert(ops.end(), { GGML_OP_SOFT_MAX }); + } + ops.push_back(GGML_OP_RESHAPE); + if (args.prob_bias) { + ops.push_back(GGML_OP_ADD); + bias = cgraph->nodes[i + ops.size() - 1]->src[1]; + } + if (args.n_groups > 0) { + for (const auto & p : topk_moe_group_pattern) { + ops.push_back(p.op); + } + } + ops.insert(ops.end(), { GGML_OP_ARGSORT, GGML_OP_VIEW, GGML_OP_GET_ROWS }); + out_nodes[0] = i + ops.size() - 2; + ids = cgraph->nodes[out_nodes[0]]; + + if (args.norm) { + ops.insert(ops.end(), { GGML_OP_RESHAPE, GGML_OP_SUM_ROWS, args.norm_bias ? GGML_OP_SCALE : GGML_OP_CLAMP, + GGML_OP_DIV, GGML_OP_RESHAPE }); + denom = cgraph->nodes[i + ops.size() - 3]; + } + if (args.scale) { + ops.insert(ops.end(), { GGML_OP_SCALE }); + scale = cgraph->nodes[i + ops.size() - 1]; + } + + weights = cgraph->nodes[i + ops.size() - 1]; + out_nodes[1] = i + ops.size() - 1; + + if (ggml_can_fuse_subgraph(cgraph, i, ops.size(), ops.data(), out_nodes, 2) && + ggml_cuda_should_use_topk_moe(node, logits, weights, ids) && + ggml_cuda_check_fusion_memory_ranges(cgraph, i, ops.size(), out_nodes, 2, /*is_topk_moe=*/true)) { + ggml_cuda_op_topk_moe(*cuda_ctx, logits, weights, ids, denom, scale, bias, args); + return ops.size() - 1; + } + } else if (!args.norm && !args.prob_bias) { + //special case gpt-oss, no norm, no bias. + ops.insert(ops.end(), { GGML_OP_ARGSORT, GGML_OP_VIEW, GGML_OP_GET_ROWS, GGML_OP_RESHAPE, + GGML_OP_SOFT_MAX, GGML_OP_RESHAPE }); + weights = cgraph->nodes[i + 5]; + ids = cgraph->nodes[i + 1]; + const ggml_tensor * softmax = cgraph->nodes[i + 4]; + + int out_nodes[2] = { i + 1, i + 5 }; + if (ggml_can_fuse_subgraph(cgraph, i, ops.size(), ops.data(), out_nodes, 2) && + ggml_cuda_should_use_topk_moe(softmax, logits, weights, ids) && + ggml_cuda_check_fusion_memory_ranges(cgraph, i, ops.size(), out_nodes, 2, /*is_topk_moe=*/true)) { + ggml_cuda_op_topk_moe(*cuda_ctx, logits, weights, ids, denom, scale, bias, args); + return ops.size() - 1; + } + } + } + } + + //RoPE + view + set-rows + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, {})) { + ggml_tensor * rope = cgraph->nodes[i]; + ggml_tensor * set_rows = cgraph->nodes[i + 2]; + + ggml_cuda_op_rope_fused(*cuda_ctx, rope, set_rows); + return 2; + } + + // Snake activation: y = x + sin(a*x)^2 * inv_b + // Naive 5-op decomposition emitted by frontends: mul -> sin -> sqr -> mul -> add + if (ggml_can_fuse_subgraph(cgraph, i, + { GGML_OP_MUL, GGML_OP_SIN, GGML_OP_SQR, GGML_OP_MUL, GGML_OP_ADD }, + { i + 4 })) { + const ggml_tensor * mul0 = cgraph->nodes[i]; + const ggml_tensor * sqr = cgraph->nodes[i + 2]; + const ggml_tensor * mul1 = cgraph->nodes[i + 3]; + ggml_tensor * add = cgraph->nodes[i + 4]; + + // x carries the full activation shape, a is the broadcast operand + const ggml_tensor * x = ggml_are_same_shape(mul0, mul0->src[0]) ? mul0->src[0] : mul0->src[1]; + const ggml_tensor * a = (x == mul0->src[0]) ? mul0->src[1] : mul0->src[0]; + + // mul1 reads sqr and inv_b in either operand order + const ggml_tensor * inv_b = (mul1->src[0] == sqr) ? mul1->src[1] : mul1->src[0]; + + // closure check: the trailing add must read the same x as the leading mul + const ggml_tensor * x_in_add = (add->src[0] == mul1) ? add->src[1] : add->src[0]; + + // Kernel iterates over total = T * C, so x and add must be 2D and + // a / inv_b must collapse to [1, C, 1, 1]. Higher dims are not handled. + const bool dim_ok = (x->ne[2] == 1 && x->ne[3] == 1) && + (add->ne[2] == 1 && add->ne[3] == 1) && + (a->ne[2] == 1 && a->ne[3] == 1); + const bool shape_ok = ggml_are_same_shape(a, inv_b) && a->ne[0] == 1 && a->ne[1] == x->ne[1]; + + // x is in the supported whitelist and every chain intermediate shares + // x's type. launch_snake reads a and inv_b as const float *, so they + // stay F32. + const ggml_tensor * sin1 = cgraph->nodes[i + 1]; + const bool types_ok = (x->type == GGML_TYPE_F32 || x->type == GGML_TYPE_F16 || x->type == GGML_TYPE_BF16) && + (a->type == GGML_TYPE_F32) && (inv_b->type == GGML_TYPE_F32) && + (mul0->type == x->type) && (sin1->type == x->type) && + (sqr->type == x->type) && (mul1->type == x->type) && + (add->type == x->type); + + // kernel reads x[idx] and a[c] / inv_b[c] linearly, so every operand is contiguous + const bool contig_ok = ggml_is_contiguous(x) && ggml_is_contiguous(add) && + ggml_is_contiguous(a) && ggml_is_contiguous(inv_b); + + if (types_ok && shape_ok && dim_ok && contig_ok && x_in_add == x) { + ggml_cuda_op_snake_fused(*cuda_ctx, x, a, inv_b, add); + return 4; + } + } + + // multi-(add or mul) + if (node->op == GGML_OP_ADD || node->op == GGML_OP_MUL) { + int n_fuse = 0; + ggml_op ops[8]; + std::fill(ops, ops + 8, node->op); + + for (; n_fuse <= 6; ++n_fuse) { + if (!ggml_can_fuse(cgraph, i + n_fuse, ops + n_fuse, 2)) { + break; + } + if (cgraph->nodes[i + n_fuse] != cgraph->nodes[i + n_fuse + 1]->src[0]) { + break; + } + if (!ggml_are_same_layout(cgraph->nodes[i + n_fuse]->src[1], cgraph->nodes[i + n_fuse + 1]->src[1])) { + break; + } + } + + n_fuse++; + + if (n_fuse > 1) { + ggml_tensor fused_node; + memcpy(&fused_node, node, sizeof(ggml_tensor)); + for (int j = 0; j < n_fuse - 1; ++j) { + fused_node.src[j + 2] = cgraph->nodes[i + j + 1]->src[1]; + } + fused_node.data = cgraph->nodes[i + n_fuse - 1]->data; + if (node->op == GGML_OP_ADD) { + ggml_cuda_op_fused_add(*cuda_ctx, &fused_node, n_fuse); + } else { + ggml_cuda_op_fused_mul(*cuda_ctx, &fused_node, n_fuse); + } + return n_fuse - 1; + } + } + + bool fused_mul_mat_vec = false; + int fused_node_count = 0; + + auto get_bias_tensor = [](const ggml_tensor * bias_node, const ggml_tensor * mul_node, ggml_op op_bias) -> const ggml_tensor * { + if (op_bias == GGML_OP_ADD) { + if (bias_node->src[0] == mul_node) { + return bias_node->src[1]; + } + if (bias_node->src[1] == mul_node) { + return bias_node->src[0]; + } + return nullptr; + } + GGML_ASSERT(op_bias == GGML_OP_ADD_ID); + GGML_ASSERT(bias_node->src[0] == mul_node); + return bias_node->src[1]; + }; + + // gate + glu + up, with optional scale/bias on both lanes. + for (ggml_op op : { GGML_OP_MUL_MAT, GGML_OP_MUL_MAT_ID }) { + const ggml_op bias_op = op == GGML_OP_MUL_MAT ? GGML_OP_ADD : GGML_OP_ADD_ID; + + if (op == GGML_OP_MUL_MAT) { + for (const bool with_bias : { false, true }) { + const int gate_idx = i; + const int gate_scale_idx = i + 1; + const int gate_bias_idx = with_bias ? i + 2 : -1; + const int up_idx = with_bias ? i + 3 : i + 2; + const int up_scale_idx = up_idx + 1; + const int up_bias_idx = with_bias ? up_idx + 2 : -1; + const int glu_idx = with_bias ? up_idx + 3 : up_idx + 2; + + const int out_nodes[] = { glu_idx }; + ggml_op ops[7]; + if (with_bias) { + ops[0] = op; + ops[1] = GGML_OP_MUL; + ops[2] = bias_op; + ops[3] = op; + ops[4] = GGML_OP_MUL; + ops[5] = bias_op; + ops[6] = GGML_OP_GLU; + } else { + ops[0] = op; + ops[1] = GGML_OP_MUL; + ops[2] = op; + ops[3] = GGML_OP_MUL; + ops[4] = GGML_OP_GLU; + } + const int n_ops = with_bias ? 7 : 5; + + if (!ggml_can_fuse_subgraph(cgraph, i, n_ops, ops, out_nodes, 1) || + !ggml_cuda_check_fusion_memory_ranges(cgraph, i, n_ops, out_nodes, 1)) { + continue; + } + + ggml_tensor * gate_n = cgraph->nodes[gate_idx]; + ggml_tensor * gate_scale_n = cgraph->nodes[gate_scale_idx]; + ggml_tensor * gate_out_n = with_bias ? cgraph->nodes[gate_bias_idx] : gate_scale_n; + ggml_tensor * up_n = cgraph->nodes[up_idx]; + ggml_tensor * up_scale_n = cgraph->nodes[up_scale_idx]; + ggml_tensor * up_out_n = with_bias ? cgraph->nodes[up_bias_idx] : up_scale_n; + const ggml_tensor * glu = cgraph->nodes[glu_idx]; + + if (!ggml_cuda_should_fuse_mul_mat(up_n, gate_n, glu, + with_bias ? up_out_n : nullptr, with_bias ? gate_out_n : nullptr, up_scale_n, gate_scale_n)) { + continue; + } + + const ggml_tensor * gate_scale = ggml_cuda_get_mul_mat_scale(gate_scale_n, gate_n); + const ggml_tensor * up_scale = ggml_cuda_get_mul_mat_scale(up_scale_n, up_n); + if (!gate_scale || !up_scale) { + continue; + } + + const ggml_tensor * up_bias = with_bias ? get_bias_tensor(up_out_n, up_scale_n, bias_op) : nullptr; + const ggml_tensor * gate_bias = with_bias ? get_bias_tensor(gate_out_n, gate_scale_n, bias_op) : nullptr; + if (with_bias && (!ggml_are_same_shape(gate_out_n->src[0], gate_out_n->src[1]) || + !ggml_are_same_shape(up_out_n->src[0], up_out_n->src[1]))) { + continue; + } + + const ggml_tensor * src0 = up_n->src[0]; + const ggml_tensor * src1 = up_n->src[1]; + const ggml_tensor * ids = up_n->src[2]; + + ggml_cuda_mm_fusion_args_host fusion_data{}; + fusion_data.gate = gate_n->src[0]; + fusion_data.x_bias = up_bias; + fusion_data.gate_bias = gate_bias; + fusion_data.x_scale = up_scale; + fusion_data.gate_scale = gate_scale; + fusion_data.glu_op = ggml_get_glu_op(glu); + fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3); + + if (ggml_cuda_should_fuse_mul_mat_vec_f(up_n, gate_n)) { + ggml_cuda_mul_mat_vec_f(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data); + fused_mul_mat_vec = true; + fused_node_count = n_ops; + break; + } + + if (ggml_cuda_should_fuse_mul_mat_vec_q(up_n)) { + ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data); + fused_mul_mat_vec = true; + fused_node_count = n_ops; + break; + } + + if (!with_bias && ggml_cuda_should_fuse_mul_mat_q(up_n, gate_n, glu, up_scale_n, gate_scale_n)) { + fusion_data.prec_src1 = ggml_prec_get_src(up_n, 1); + ggml_cuda_mul_mat_q(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data); + fused_mul_mat_vec = true; + fused_node_count = n_ops; + break; + } + } + + if (fused_mul_mat_vec) { + break; + } + } else { + for (const bool with_bias : { false, true }) { + const int gate_idx = i; + const int gate_scale_idx = i + 4; + const int gate_bias_idx = with_bias ? i + 5 : -1; + const int up_idx = with_bias ? i + 6 : i + 5; + const int up_scale_idx = up_idx + 4; + const int up_bias_idx = with_bias ? up_idx + 5 : -1; + const int glu_idx = with_bias ? up_idx + 6 : up_idx + 5; + + const int out_nodes[] = { glu_idx }; + ggml_op ops[13]; + if (with_bias) { + ops[0] = op; + ops[1] = GGML_OP_RESHAPE; + ops[2] = GGML_OP_REPEAT; + ops[3] = GGML_OP_GET_ROWS; + ops[4] = GGML_OP_MUL; + ops[5] = bias_op; + ops[6] = op; + ops[7] = GGML_OP_RESHAPE; + ops[8] = GGML_OP_REPEAT; + ops[9] = GGML_OP_GET_ROWS; + ops[10] = GGML_OP_MUL; + ops[11] = bias_op; + ops[12] = GGML_OP_GLU; + } else { + ops[0] = op; + ops[1] = GGML_OP_RESHAPE; + ops[2] = GGML_OP_REPEAT; + ops[3] = GGML_OP_GET_ROWS; + ops[4] = GGML_OP_MUL; + ops[5] = op; + ops[6] = GGML_OP_RESHAPE; + ops[7] = GGML_OP_REPEAT; + ops[8] = GGML_OP_GET_ROWS; + ops[9] = GGML_OP_MUL; + ops[10] = GGML_OP_GLU; + } + const int n_ops = with_bias ? 13 : 11; + + if (!ggml_can_fuse_subgraph(cgraph, i, n_ops, ops, out_nodes, 1) || + !ggml_cuda_check_fusion_memory_ranges(cgraph, i, n_ops, out_nodes, 1)) { + continue; + } + + ggml_tensor * gate_n = cgraph->nodes[gate_idx]; + ggml_tensor * gate_scale_n = cgraph->nodes[gate_scale_idx]; + ggml_tensor * gate_out_n = with_bias ? cgraph->nodes[gate_bias_idx] : gate_scale_n; + ggml_tensor * up_n = cgraph->nodes[up_idx]; + ggml_tensor * up_scale_n = cgraph->nodes[up_scale_idx]; + ggml_tensor * up_out_n = with_bias ? cgraph->nodes[up_bias_idx] : up_scale_n; + const ggml_tensor * glu = cgraph->nodes[glu_idx]; + + if (!ggml_cuda_should_fuse_mul_mat(up_n, gate_n, glu, + with_bias ? up_out_n : nullptr, with_bias ? gate_out_n : nullptr, up_scale_n, gate_scale_n)) { + continue; + } + + const ggml_tensor * gate_scale = ggml_cuda_get_mul_mat_id_scale(cgraph->nodes[gate_idx + 1], cgraph->nodes[gate_idx + 2], + cgraph->nodes[gate_idx + 3], gate_scale_n, gate_n); + const ggml_tensor * up_scale = ggml_cuda_get_mul_mat_id_scale(cgraph->nodes[up_idx + 1], cgraph->nodes[up_idx + 2], + cgraph->nodes[up_idx + 3], up_scale_n, up_n); + if (!gate_scale || !up_scale) { + continue; + } + + const ggml_tensor * up_bias = with_bias ? get_bias_tensor(up_out_n, up_scale_n, bias_op) : nullptr; + const ggml_tensor * gate_bias = with_bias ? get_bias_tensor(gate_out_n, gate_scale_n, bias_op) : nullptr; + + const ggml_tensor * src0 = up_n->src[0]; + const ggml_tensor * src1 = up_n->src[1]; + const ggml_tensor * ids = up_n->src[2]; + + ggml_cuda_mm_fusion_args_host fusion_data{}; + fusion_data.gate = gate_n->src[0]; + fusion_data.x_bias = up_bias; + fusion_data.gate_bias = gate_bias; + fusion_data.x_scale = up_scale; + fusion_data.gate_scale = gate_scale; + fusion_data.glu_op = ggml_get_glu_op(glu); + fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3); + + if (ggml_cuda_should_fuse_mul_mat_vec_f(up_n, gate_n)) { + ggml_cuda_mul_mat_vec_f(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data); + fused_mul_mat_vec = true; + fused_node_count = n_ops; + break; + } + + if (ggml_cuda_should_fuse_mul_mat_vec_q(up_n)) { + ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data); + fused_mul_mat_vec = true; + fused_node_count = n_ops; + break; + } + + if (!with_bias && ggml_cuda_should_fuse_mul_mat_q(up_n, gate_n, glu, up_scale_n, gate_scale_n)) { + fusion_data.prec_src1 = ggml_prec_get_src(up_n, 1); + ggml_cuda_mul_mat_q(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data); + fused_mul_mat_vec = true; + fused_node_count = n_ops; + break; + } + } + + if (fused_mul_mat_vec) { + break; + } + } + + if (ggml_cuda_can_fuse(cgraph, i, { op, bias_op, op, bias_op, GGML_OP_GLU }, {})) { + ggml_tensor * glu = cgraph->nodes[i + 4]; + ggml_tensor * gate_bias_n = glu->src[0]; + ggml_tensor * up_bias_n = glu->src[1]; + + //we don't assume the order for {gate, up}. Instead infer it from the bias tensor + ggml_tensor * gate_n = nullptr; + ggml_tensor * up_n = nullptr; + + if (gate_bias_n->src[0] == cgraph->nodes[i] || gate_bias_n->src[1] == cgraph->nodes[i]) { + gate_n = cgraph->nodes[i]; + up_n = cgraph->nodes[i + 2]; + } else if (gate_bias_n->src[0] == cgraph->nodes[i + 2] || gate_bias_n->src[1] == cgraph->nodes[i + 2]) { + gate_n = cgraph->nodes[i + 2]; + up_n = cgraph->nodes[i]; + } else { + continue; + } + + const ggml_tensor * up_bias_tensor = get_bias_tensor(up_bias_n, up_n, bias_op); + const ggml_tensor * gate_bias_tensor = get_bias_tensor(gate_bias_n, gate_n, bias_op); + + if (!up_bias_tensor || !gate_bias_tensor) { + continue; + } + + // we don't support repeating adds + if (bias_op == GGML_OP_ADD && (!ggml_are_same_shape(gate_bias_n->src[0], gate_bias_n->src[1]) || + !ggml_are_same_shape(up_bias_n->src[0], up_bias_n->src[1]))) { + continue; + } + + const ggml_tensor * src0 = up_n->src[0]; + const ggml_tensor * src1 = up_n->src[1]; + const ggml_tensor * ids = up_n->src[2]; + + if (ggml_cuda_should_fuse_mul_mat_vec_f(up_n, gate_n)) { + ggml_cuda_mm_fusion_args_host fusion_data{}; + fusion_data.gate = gate_n->src[0]; + fusion_data.x_bias = up_bias_tensor; + fusion_data.gate_bias = gate_bias_tensor; + fusion_data.glu_op = ggml_get_glu_op(glu); + fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3); + + ggml_cuda_mul_mat_vec_f(*cuda_ctx, src0, src1, ids, glu, &fusion_data); + fused_mul_mat_vec = true; + fused_node_count = 5; + break; + } + + if (ggml_cuda_should_fuse_mul_mat_vec_q(up_n)) { + ggml_cuda_mm_fusion_args_host fusion_data{}; + fusion_data.gate = gate_n->src[0]; + fusion_data.x_bias = up_bias_tensor; + fusion_data.gate_bias = gate_bias_tensor; + fusion_data.glu_op = ggml_get_glu_op(glu); + fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3); + + ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, glu, &fusion_data); + fused_mul_mat_vec = true; + fused_node_count = 5; + break; + } + } else if (ggml_cuda_can_fuse(cgraph, i, { op, op, GGML_OP_GLU }, {})) { + ggml_tensor * glu = cgraph->nodes[i + 2]; + ggml_tensor * gate = glu->src[0]; + ggml_tensor * up = glu->src[1]; + + bool ok = (gate == cgraph->nodes[i] && up == cgraph->nodes[i + 1]) || + (gate == cgraph->nodes[i + 1] && up == cgraph->nodes[i]); + + if (!ok) { + continue; + } + + const ggml_tensor * src0 = up->src[0]; + const ggml_tensor * src1 = up->src[1]; + const ggml_tensor * ids = up->src[2]; + + if (ggml_cuda_should_fuse_mul_mat_vec_f(up, gate)) { + ggml_cuda_mm_fusion_args_host fusion_data{}; + fusion_data.gate = gate->src[0]; + fusion_data.glu_op = ggml_get_glu_op(glu); + fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3); + + ggml_cuda_mul_mat_vec_f(*cuda_ctx, src0, src1, ids, glu, &fusion_data); + fused_mul_mat_vec = true; + fused_node_count = 3; + break; + } + + if (ggml_cuda_should_fuse_mul_mat_vec_q(up)) { + ggml_cuda_mm_fusion_args_host fusion_data{}; + fusion_data.gate = gate->src[0]; + fusion_data.glu_op = ggml_get_glu_op(glu); + fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3); + + ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, glu, &fusion_data); + fused_mul_mat_vec = true; + fused_node_count = 3; + break; + } + + if (ggml_cuda_should_fuse_mul_mat_q(up, gate, glu)) { + ggml_cuda_mm_fusion_args_host fusion_data{}; + fusion_data.gate = gate->src[0]; + fusion_data.glu_op = ggml_get_glu_op(glu); + fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3); + fusion_data.prec_src1 = ggml_prec_get_src(up, 1); + + ggml_cuda_mul_mat_q(*cuda_ctx, src0, src1, ids, glu, &fusion_data); + fused_mul_mat_vec = true; + fused_node_count = 3; + break; + } + } + } + + if (fused_mul_mat_vec) { + return fused_node_count - 1; + } + + fused_mul_mat_vec = false; + fused_node_count = 0; + + // mul_mat + scale + optional bias + for (ggml_op op : { GGML_OP_MUL_MAT, GGML_OP_MUL_MAT_ID }) { + const ggml_op bias_op = op == GGML_OP_MUL_MAT ? GGML_OP_ADD : GGML_OP_ADD_ID; + + for (const bool with_bias : { false, true }) { + const int n_ops = op == GGML_OP_MUL_MAT ? (with_bias ? 3 : 2) : (with_bias ? 6 : 5); + const int out_nodes[] = { i + n_ops - 1 }; + ggml_op ops[6]; + if (op == GGML_OP_MUL_MAT) { + if (with_bias) { + ops[0] = op; + ops[1] = GGML_OP_MUL; + ops[2] = bias_op; + } else { + ops[0] = op; + ops[1] = GGML_OP_MUL; + } + } else { + if (with_bias) { + ops[0] = op; + ops[1] = GGML_OP_RESHAPE; + ops[2] = GGML_OP_REPEAT; + ops[3] = GGML_OP_GET_ROWS; + ops[4] = GGML_OP_MUL; + ops[5] = bias_op; + } else { + ops[0] = op; + ops[1] = GGML_OP_RESHAPE; + ops[2] = GGML_OP_REPEAT; + ops[3] = GGML_OP_GET_ROWS; + ops[4] = GGML_OP_MUL; + } + } + + if (!ggml_can_fuse_subgraph(cgraph, i, n_ops, ops, out_nodes, 1) || + !ggml_cuda_check_fusion_memory_ranges(cgraph, i, n_ops, out_nodes, 1)) { + continue; + } + + ggml_tensor * mm_node = cgraph->nodes[i]; + ggml_tensor * scale_node = op == GGML_OP_MUL_MAT ? cgraph->nodes[i + 1] : cgraph->nodes[i + 4]; + ggml_tensor * out_node = with_bias ? cgraph->nodes[i + n_ops - 1] : scale_node; + + const ggml_tensor * scale = nullptr; + if (op == GGML_OP_MUL_MAT) { + scale = ggml_cuda_get_mul_mat_scale(scale_node, mm_node); + } else { + scale = ggml_cuda_get_mul_mat_id_scale(cgraph->nodes[i + 1], cgraph->nodes[i + 2], cgraph->nodes[i + 3], scale_node, mm_node); + } + if (!scale) { + continue; + } + + const ggml_tensor * bias = with_bias ? get_bias_tensor(out_node, scale_node, bias_op) : nullptr; + if (with_bias && !bias) { + continue; + } + if (with_bias && bias_op == GGML_OP_ADD && !ggml_are_same_shape(out_node->src[0], out_node->src[1])) { + continue; + } + if (with_bias && bias_op == GGML_OP_ADD_ID && out_node->src[2] != mm_node->src[2]) { + continue; + } + + const ggml_tensor * src0 = mm_node->src[0]; + const ggml_tensor * src1 = mm_node->src[1]; + const ggml_tensor * ids = mm_node->src[2]; + + ggml_cuda_mm_fusion_args_host fusion_data{}; + fusion_data.x_bias = bias; + fusion_data.x_scale = scale; + + if (ggml_cuda_should_fuse_mul_mat_vec_f(mm_node)) { + ggml_cuda_mul_mat_vec_f(*cuda_ctx, src0, src1, ids, out_node, &fusion_data); + fused_mul_mat_vec = true; + fused_node_count = n_ops; + break; + } + + if (op == GGML_OP_MUL_MAT && !with_bias && src0->type == GGML_TYPE_F8_E4M3 && + ggml_get_op_params_i32(mm_node, 3) != GGML_PREC_F32 && + ggml_cuda_mul_mat_fp8(*cuda_ctx, src0, src1, scale_node, scale)) { + return 1; + } + + if (!with_bias && src0->type == GGML_TYPE_NVFP4 && (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16) && + mm_node->type == GGML_TYPE_F32) { + const int cc = ggml_cuda_info().devices[cuda_ctx->device].cc; + const bool is_id = op == GGML_OP_MUL_MAT_ID; + const int64_t ncols = is_id ? src1->ne[2] : src1->ne[1]; + const bool use_mmvq = is_id ? ncols <= get_mmvq_mmid_max_batch(src0->type, cc) : + ggml_cuda_should_use_mmvq(src0->type, cc, ncols); + const bool bad_padding_clear = ggml_backend_buffer_get_usage(src0->buffer) == GGML_BACKEND_BUFFER_USAGE_COMPUTE && + ggml_nbytes(src0) != ggml_backend_buffer_get_alloc_size(src0->buffer, src0) && + src0->view_src; + if (!use_mmvq && !bad_padding_clear && + ggml_cuda_should_use_mmq(src0->type, cc, ncols, /*n_experts =*/ is_id ? src0->ne[2] : 0)) { + fusion_data.prec_src1 = ggml_prec_get_src(mm_node, 1); + ggml_cuda_mul_mat_q(*cuda_ctx, src0, src1, ids, out_node, &fusion_data); + return n_ops - 1; + } + } + + if (ggml_cuda_should_fuse_mul_mat_vec_q(mm_node)) { + ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, out_node, &fusion_data); + fused_mul_mat_vec = true; + fused_node_count = n_ops; + break; + } + } + if (fused_mul_mat_vec) { + break; + } + } + + if (fused_mul_mat_vec) { + return fused_node_count - 1; + } + + // mul_mat + add + for (ggml_op op : { GGML_OP_MUL_MAT, GGML_OP_MUL_MAT_ID }) { + const ggml_op bias_op = op == GGML_OP_MUL_MAT ? GGML_OP_ADD : GGML_OP_ADD_ID; + + if (!ggml_can_fuse(cgraph, i, { op, bias_op })) { + continue; + } + + ggml_tensor * mm_node = cgraph->nodes[i]; + ggml_tensor * bias_node = cgraph->nodes[i + 1]; + + ggml_tensor * bias_tensor = nullptr; + if (bias_op == GGML_OP_ADD) { + if (bias_node->src[0] == mm_node) { + bias_tensor = bias_node->src[1]; + } else if (bias_node->src[1] == mm_node) { + bias_tensor = bias_node->src[0]; + } else { + continue; + } + } else { + if (bias_node->src[0] != mm_node) { + continue; + } + bias_tensor = bias_node->src[1]; + } + + const ggml_tensor * src0 = mm_node->src[0]; + const ggml_tensor * src1 = mm_node->src[1]; + const ggml_tensor * ids = mm_node->src[2]; + + if (bias_op == GGML_OP_ADD_ID && bias_node->src[2] != ids) { + continue; + } + + if (bias_op == GGML_OP_ADD && !ggml_are_same_shape(bias_node->src[0], bias_node->src[1])) { + continue; + } + + ggml_cuda_mm_fusion_args_host fusion_data{}; + fusion_data.x_bias = bias_tensor; + + if (ggml_cuda_should_fuse_mul_mat_vec_f(mm_node)) { + ggml_cuda_mul_mat_vec_f(*cuda_ctx, src0, src1, ids, bias_node, &fusion_data); + fused_mul_mat_vec = true; + fused_node_count = 2; + break; + } + + if (ggml_cuda_should_fuse_mul_mat_vec_q(mm_node)) { + ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, bias_node, &fusion_data); + fused_mul_mat_vec = true; + fused_node_count = 2; + break; + } + } + + if (fused_mul_mat_vec) { + return fused_node_count - 1; + } + + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, {})) { + ggml_cuda_op_rms_norm_mul_rope_fused(*cuda_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2], cgraph->nodes[i + 4]); + return 4; + } + + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE }, {})) { + ggml_cuda_op_rms_norm_mul_rope_fused(*cuda_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2], nullptr); + return 2; + } + + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_NORM, GGML_OP_MUL, GGML_OP_ADD }, {})) { + ggml_cuda_op_norm(*cuda_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2]); + return 2; + } + + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_NORM, GGML_OP_MUL }, {})) { + ggml_cuda_op_norm(*cuda_ctx, node, cgraph->nodes[i + 1]); + return 1; + } + + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ADD }, {})) { + ggml_cuda_op_rms_norm_fused_add(*cuda_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2]); + return 2; + } + + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL }, {})) { + ggml_cuda_op_rms_norm_fused(*cuda_ctx, node, cgraph->nodes[i + 1]); + return 1; + } + + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_SCALE }, {})) { + ggml_cuda_op_rms_norm_scale_fused(*cuda_ctx, node, cgraph->nodes[i + 1]); + return 1; + } + + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_SSM_CONV, GGML_OP_ADD, GGML_OP_UNARY }, { GGML_UNARY_OP_SILU })) { + ggml_cuda_op_ssm_conv(*cuda_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2]); + return 2; + } + + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_SSM_CONV, GGML_OP_UNARY }, { GGML_UNARY_OP_SILU })) { + ggml_cuda_op_ssm_conv(*cuda_ctx, node, /*bias_add_node=*/ nullptr, cgraph->nodes[i + 1]); + return 1; + } + + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_UNARY, GGML_OP_MUL }, { GGML_UNARY_OP_SILU }) || + ggml_cuda_can_fuse(cgraph, i, { GGML_OP_UNARY, GGML_OP_MUL }, { GGML_UNARY_OP_SIGMOID }) || + ggml_cuda_can_fuse(cgraph, i, { GGML_OP_UNARY, GGML_OP_MUL }, { GGML_UNARY_OP_SOFTPLUS })) { + ggml_cuda_op_unary_mul(*cuda_ctx, node, cgraph->nodes[i + 1]); + return 1; + } + + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_UNARY, GGML_OP_SQR }, { GGML_UNARY_OP_RELU })) { + ggml_cuda_op_relu_sqr(*cuda_ctx, node, cgraph->nodes[i + 1]); + return 1; + } + + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_SCALE, GGML_OP_UNARY, GGML_OP_SCALE, GGML_OP_DSV4_HC_POST }, { GGML_UNARY_OP_SIGMOID })) { + ggml_cuda_op_dsv4_hc_post(*cuda_ctx, cgraph->nodes[i + 3], node, cgraph->nodes[i + 2]); + return 3; + } + + if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_SCALE, GGML_OP_UNARY, GGML_OP_SCALE }, { GGML_UNARY_OP_TANH })) { + ggml_cuda_op_softcap(*cuda_ctx, cgraph->nodes[i + 2], node); + return 2; + } + + return 0; +} + +void ggml_cuda_fusion_add_alloc_deps(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, ggml_backend_graph_optimize_params * params) { + auto add_alloc_deps = [&](size_t start, size_t last_node) { + + for (size_t i = start; i < last_node; ++i) { + params->add_alloc_dep(params->user_data, cgraph->nodes[i], cgraph->nodes[last_node]); + + for (int j = 0; j < GGML_MAX_SRC; ++j) { + if (cgraph->nodes[i]->src[j]) { + params->add_alloc_dep(params->user_data, cgraph->nodes[i]->src[j], cgraph->nodes[last_node]); + } + } + } + }; + + ggml_cuda_set_device(cuda_ctx->device); + for (int i = 0; i + 5 < cgraph->n_nodes; ++i) { + if (cgraph->nodes[i]->op != GGML_OP_MUL_MAT_ID) { + continue; + } + for (int j = i + 3; j + 2 < cgraph->n_nodes; ++j) { + if (cgraph->nodes[j]->op == GGML_OP_MUL_MAT_ID && cgraph->nodes[j + 1]->op == GGML_OP_MUL_MAT_ID) { + break; + } + if (cgraph->nodes[j]->op != GGML_OP_MUL_MAT || !ggml_cuda_match_shared_expert(cgraph, i, j)) { + continue; + } + // Group both outputs before allocation so the shared result cannot alias intervening nodes. + std::rotate(cgraph->nodes + i + 3, cgraph->nodes + j, cgraph->nodes + j + 3); + ggml_tensor * up = cgraph->nodes[i + 2]->src[1]; + params->add_alloc_dep(params->user_data, up->src[1], cgraph->nodes[i + 5]); + params->add_alloc_dep(params->user_data, up->src[2], cgraph->nodes[i + 5]); + i += 5; + break; + } + } + for (int i = 0; i < cgraph->n_nodes; ++i) { + // Keep the inputs of the fused gate/up/GLU MMQ kernel alive until the GLU so that they cannot alias its output (under op offload the weights are buffer copies). + if (i + 2 < cgraph->n_nodes && cgraph->nodes[i + 2]->op == GGML_OP_GLU) { + ggml_tensor * glu = cgraph->nodes[i + 2]; + ggml_tensor * gate = glu->src[0]; + ggml_tensor * up = glu->src[1]; + const bool ok = (gate == cgraph->nodes[i] && up == cgraph->nodes[i + 1]) || (gate == cgraph->nodes[i + 1] && up == cgraph->nodes[i]); + if (ok && ggml_cuda_mul_mat_q_fusion_matches(up, gate, glu, cuda_ctx->device)) { + add_alloc_deps(i, i + 2); + i += 2; + continue; + } + } + // Same with the NVFP4 scales: MUL_MAT(gate), MUL(gate scale), MUL_MAT(up), MUL(up scale), GLU. + if (i + 4 < cgraph->n_nodes && cgraph->nodes[i + 4]->op == GGML_OP_GLU) { + ggml_tensor * glu = cgraph->nodes[i + 4]; + ggml_tensor * gate_scale = cgraph->nodes[i + 1]; + ggml_tensor * up_scale = cgraph->nodes[i + 3]; + if (glu->src[0] == gate_scale && glu->src[1] == up_scale && + ggml_cuda_mul_mat_q_fusion_matches(cgraph->nodes[i + 2], cgraph->nodes[i], glu, cuda_ctx->device, up_scale, gate_scale) && + ggml_cuda_get_mul_mat_scale(gate_scale, cgraph->nodes[i]) && ggml_cuda_get_mul_mat_scale(up_scale, cgraph->nodes[i + 2])) { + add_alloc_deps(i, i + 4); + i += 4; + continue; + } + } + // Same with per-expert NVFP4 scales: MUL_MAT_ID, RESHAPE, REPEAT, GET_ROWS, MUL for gate and for up, GLU. + if (i + 10 < cgraph->n_nodes && cgraph->nodes[i + 10]->op == GGML_OP_GLU) { + ggml_tensor * glu = cgraph->nodes[i + 10]; + ggml_tensor * gate_scale = cgraph->nodes[i + 4]; + ggml_tensor * up_scale = cgraph->nodes[i + 9]; + if (glu->src[0] == gate_scale && glu->src[1] == up_scale && + ggml_cuda_mul_mat_q_fusion_matches(cgraph->nodes[i + 5], cgraph->nodes[i], glu, cuda_ctx->device, up_scale, gate_scale) && + ggml_cuda_get_mul_mat_id_scale(cgraph->nodes[i + 1], cgraph->nodes[i + 2], cgraph->nodes[i + 3], gate_scale, cgraph->nodes[i]) && + ggml_cuda_get_mul_mat_id_scale(cgraph->nodes[i + 6], cgraph->nodes[i + 7], cgraph->nodes[i + 8], up_scale, cgraph->nodes[i + 5])) { + add_alloc_deps(i, i + 10); + i += 10; + continue; + } + } + + ggml_cuda_moe_weighted_reduction_match match; + if (ggml_cuda_match_moe_weighted_reduction(cgraph, i, match)) { + params->add_alloc_dep(params->user_data, const_cast(match.experts), match.dst); + params->add_alloc_dep(params->user_data, const_cast(match.weights), match.dst); + if (match.expert_scale != nullptr) { + params->add_alloc_dep( + params->user_data, const_cast(match.expert_scale), match.dst); + } + i += match.node_count - 1; + } + + if (cgraph->nodes[i]->op == GGML_OP_UNARY || cgraph->nodes[i]->op == GGML_OP_SOFT_MAX || + cgraph->nodes[i]->op == GGML_OP_ARGSORT) { + ggml_cuda_topk_moe_args args; + const bool can_fuse = ggml_cuda_topk_moe_fusion(cgraph, i, args); + std::vector ops; + ops.reserve(13); // max ops; avoids gcc -Wstringop-overflow false positive + + const ggml_tensor * node = cgraph->nodes[i]; + + if (can_fuse) { + const ggml_tensor * logits = node->src[0]; + ggml_tensor * weights = nullptr; + ggml_tensor * ids = nullptr; + + if (!args.delayed_softmax) { + int out_nodes[2]; // nodes which can't be elided + + if (args.sigmoid) { + ops.insert(ops.end(), { GGML_OP_UNARY }); + } else if (args.sqrt_softplus) { + ops.insert(ops.end(), { GGML_OP_UNARY, GGML_OP_SQRT }); + } else { + ops.insert(ops.end(), { GGML_OP_SOFT_MAX }); + } + const int i_probs = i + (int) ops.size() - 1; // last node of the gating activation + + if (args.prob_bias) { + ops.insert(ops.end(), { GGML_OP_RESHAPE, GGML_OP_ADD, GGML_OP_ARGSORT, GGML_OP_VIEW, + GGML_OP_GET_ROWS }); + out_nodes[0] = i_probs + 4; + } else { + ops.insert(ops.end(), { GGML_OP_RESHAPE, GGML_OP_ARGSORT, GGML_OP_VIEW, GGML_OP_GET_ROWS }); + out_nodes[0] = i_probs + 3; + } + ids = cgraph->nodes[out_nodes[0]]; + + if (args.norm) { + ops.insert(ops.end(), { GGML_OP_RESHAPE, GGML_OP_SUM_ROWS, + args.norm_bias ? GGML_OP_SCALE : GGML_OP_CLAMP, GGML_OP_DIV, + GGML_OP_RESHAPE }); + } + if (args.scale) { + ops.insert(ops.end(), { GGML_OP_SCALE }); + } + + weights = cgraph->nodes[i + ops.size() - 1]; + out_nodes[1] = i + ops.size() - 1; + + if (ggml_can_fuse_subgraph(cgraph, i, ops.size(), ops.data(), out_nodes, 2) && + ggml_cuda_should_use_topk_moe(node, logits, weights, ids)) { + + add_alloc_deps(i, i + ops.size()); + i += ops.size() - 1; + } + } + } + } + } +} diff --git a/ggml/src/ggml-cuda/fusion.cuh b/ggml/src/ggml-cuda/fusion.cuh new file mode 100644 index 000000000000..38173b2f7ddb --- /dev/null +++ b/ggml/src/ggml-cuda/fusion.cuh @@ -0,0 +1,10 @@ +#pragma once + +#include "common.cuh" +#include "ggml-backend-impl.h" + +// try and fuse nodes starting at node i and return the number of nodes to skip +int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i); + +// add alloc deps for the fusions that need their inputs to stay alive (called from graph_optimize) +void ggml_cuda_fusion_add_alloc_deps(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, ggml_backend_graph_optimize_params * params); diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index c014bbe5bb24..f2b3740a520e 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -28,6 +28,7 @@ #include "ggml-cuda/diag.cuh" #include "ggml-cuda/fattn.cuh" #include "ggml-cuda/fp8.cuh" +#include "ggml-cuda/fusion.cuh" #include "ggml-cuda/fwht.cuh" #include "ggml-cuda/getrows.cuh" #include "ggml-cuda/im2col.cuh" @@ -36,7 +37,6 @@ #include "ggml-cuda/mmq-few.cuh" #include "ggml-cuda/mmvf.cuh" #include "ggml-cuda/mmvq.cuh" -#include "ggml-cuda/moe-weighted-reduction.cuh" #include "ggml-cuda/norm.cuh" #include "ggml-cuda/opt-step-adamw.cuh" #include "ggml-cuda/opt-step-sgd.cuh" @@ -49,8 +49,6 @@ #include "ggml-cuda/roll.cuh" #include "ggml-cuda/scale.cuh" #include "ggml-cuda/sleep.cuh" -#include "ggml-cuda/snake.cuh" -#include "ggml-cuda/softcap.cuh" #include "ggml-cuda/softmax.cuh" #include "ggml-cuda/ssm-conv.cuh" #include "ggml-cuda/ssm-scan.cuh" @@ -59,7 +57,6 @@ #include "ggml-cuda/top-k.cuh" #include "ggml-cuda/mean.cuh" #include "ggml-cuda/tsembd.cuh" -#include "ggml-cuda/topk-moe.cuh" #include "ggml-cuda/unary.cuh" #include "ggml-cuda/upscale.cuh" #include "ggml-cuda/wkv.cuh" @@ -2206,332 +2203,6 @@ static void ggml_cuda_mul_mat_cublas(ggml_backend_cuda_context & ctx, const ggml } } -static bool ggml_cuda_should_fuse_mul_mat(const ggml_tensor * ffn_up, - const ggml_tensor * ffn_gate, - const ggml_tensor * glu, - const ggml_tensor * ffn_up_bias = nullptr, - const ggml_tensor * ffn_gate_bias = nullptr, - const ggml_tensor * ffn_up_scale = nullptr, - const ggml_tensor * ffn_gate_scale = nullptr) { - const bool has_bias = ffn_up_bias != nullptr || ffn_gate_bias != nullptr; - const bool has_scale = ffn_up_scale != nullptr || ffn_gate_scale != nullptr; - - if (has_bias && (!ffn_up_bias || !ffn_gate_bias)) { - return false; - } - if (has_scale && (!ffn_up_scale || !ffn_gate_scale)) { - return false; - } - - const bool is_mul_mat = ffn_up->op == GGML_OP_MUL_MAT && ffn_gate->op == GGML_OP_MUL_MAT && glu->op == GGML_OP_GLU; - const bool is_mul_mat_id = ffn_up->op == GGML_OP_MUL_MAT_ID && ffn_gate->op == GGML_OP_MUL_MAT_ID && glu->op == GGML_OP_GLU; - - GGML_ASSERT(ffn_up && ffn_gate && glu); - - if (!is_mul_mat && !is_mul_mat_id) { - return false; - } - - const ggml_op expected_bias_op = is_mul_mat ? GGML_OP_ADD : GGML_OP_ADD_ID; - const ggml_tensor * ffn_up_bias_src = has_scale ? ffn_up_scale : ffn_up; - const ggml_tensor * ffn_gate_bias_src = has_scale ? ffn_gate_scale : ffn_gate; - const ggml_tensor * ffn_up_out = has_bias ? ffn_up_bias : ffn_up_bias_src; - const ggml_tensor * ffn_gate_out = has_bias ? ffn_gate_bias : ffn_gate_bias_src; - - if (glu->src[0] != ffn_gate_out || glu->src[1] != ffn_up_out) { - return false; - } - - if (has_scale) { - if (ffn_up_scale->op != GGML_OP_MUL || ffn_gate_scale->op != GGML_OP_MUL) { - return false; - } - const bool up_has_mm = ffn_up_scale->src[0] == ffn_up || ffn_up_scale->src[1] == ffn_up; - const bool gate_has_mm = ffn_gate_scale->src[0] == ffn_gate || ffn_gate_scale->src[1] == ffn_gate; - if (!up_has_mm || !gate_has_mm) { - return false; - } - } - - if (has_bias) { - if (ffn_up_bias->op != expected_bias_op || ffn_gate_bias->op != expected_bias_op) { - return false; - } - - if (expected_bias_op == GGML_OP_ADD) { - const bool up_has_mul = ffn_up_bias->src[0] == ffn_up_bias_src || ffn_up_bias->src[1] == ffn_up_bias_src; - const bool gate_has_mul = ffn_gate_bias->src[0] == ffn_gate_bias_src || ffn_gate_bias->src[1] == ffn_gate_bias_src; - if (!up_has_mul || !gate_has_mul) { - return false; - } - } else { // GGML_OP_ADD_ID - if (ffn_up_bias->src[0] != ffn_up_bias_src || ffn_gate_bias->src[0] != ffn_gate_bias_src) { - return false; - } - if (ffn_up_bias->src[2] != ffn_up->src[2] || ffn_gate_bias->src[2] != ffn_gate->src[2]) { - return false; - } - } - } - - if (ffn_up->src[0]->type != ffn_gate->src[0]->type || !ggml_are_same_shape(ffn_up->src[0], ffn_gate->src[0]) || - !ggml_are_same_stride(ffn_up->src[0], ffn_gate->src[0])) { - return false; - } - - if (ffn_up->src[1] != ffn_gate->src[1]) { - return false; - } - - if (is_mul_mat_id && ffn_up->src[2] != ffn_gate->src[2]) { - return false; - } - - static constexpr std::array valid_glu_ops = { GGML_GLU_OP_SWIGLU, GGML_GLU_OP_GEGLU, GGML_GLU_OP_SWIGLU_OAI, GGML_GLU_OP_SWIGLU_CLAMP }; - - if (std::find(valid_glu_ops.begin(), valid_glu_ops.end(), ggml_get_glu_op(glu)) == valid_glu_ops.end()) { - return false; - } - - if (const bool swapped = ggml_get_op_params_i32(glu, 1); swapped) { - return false; - } - - return true; -} - -static bool ggml_cuda_should_fuse_mul_mat_vec_f(const ggml_tensor * tensor, const ggml_tensor * gate = nullptr) { - ggml_tensor * src0 = tensor->src[0]; - ggml_tensor * src1 = tensor->src[1]; - const ggml_tensor * dst = tensor; - - const bool is_mul_mat_id = tensor->op == GGML_OP_MUL_MAT_ID; - - bool use_mul_mat_vec_f = - (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || - src0->type == GGML_TYPE_F8_E4M3) && - src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32; - - const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; - const int warp_size = ggml_cuda_info().devices[ggml_cuda_get_device()].warp_size; - use_mul_mat_vec_f = use_mul_mat_vec_f && ggml_cuda_should_use_mmvf(src0, cc, warp_size, is_mul_mat_id ? src1->ne[2] : src1->ne[1]); - - if (gate && !ggml_cuda_should_use_mmvf(gate->src[0], cc, warp_size, is_mul_mat_id ? src1->ne[2] : src1->ne[1])) { - return false; - } - - //we only support fusion for ncols_dst = 1 - if (tensor->op == GGML_OP_MUL_MAT && dst->ne[1] != 1) { - return false; - } - - if (tensor->op == GGML_OP_MUL_MAT_ID && dst->ne[2] != 1) { - return false; - } - - - return use_mul_mat_vec_f; -} - -static bool ggml_cuda_should_fuse_mul_mat_vec_q(const ggml_tensor * tensor) { - ggml_tensor * src0 = tensor->src[0]; - ggml_tensor * src1 = tensor->src[1]; - const ggml_tensor * dst = tensor; - - const bool bad_padding_clear = ggml_backend_buffer_get_usage(src0->buffer) == GGML_BACKEND_BUFFER_USAGE_COMPUTE && - ggml_nbytes(src0) != ggml_backend_buffer_get_alloc_size(src0->buffer, src0) && - src0->view_src; - - const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; - bool use_mul_mat_vec_q = ggml_cuda_should_use_mmvq(src0->type, cc, src1->ne[1]) && !bad_padding_clear && - src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32; - - // fusion is not universally faster on Pascal - if (cc < GGML_CUDA_CC_VOLTA) { - return false; - } - //we only support fusion for ncols_dst = 1 - if (tensor->op == GGML_OP_MUL_MAT && dst->ne[1] != 1) { - return false; - } - - if (tensor->op == GGML_OP_MUL_MAT_ID && dst->ne[2] > get_mmvq_mmid_max_batch(src0->type, cc)) { - return false; - } - - // do not fuse the matmuls that few-row MMQ takes in ggml_cuda_mul_mat_id - if (tensor->op == GGML_OP_MUL_MAT_ID && ggml_cuda_should_use_mmq_few(src0, src1, tensor->src[2], cc)) { - return false; - } - - return use_mul_mat_vec_q; -} - -static bool ggml_cuda_match_shared_expert(const ggml_cgraph * graph, int routed_idx, int shared_idx) { - if (routed_idx + 2 >= graph->n_nodes || shared_idx + 2 >= graph->n_nodes || shared_idx < routed_idx + 3) { - return false; - } - const int nodes[] = { routed_idx, routed_idx + 1, routed_idx + 2, shared_idx, shared_idx + 1, shared_idx + 2 }; - const ggml_op ops[] = { GGML_OP_MUL_MAT_ID, GGML_OP_MUL_MAT_ID, GGML_OP_GLU, - GGML_OP_MUL_MAT, GGML_OP_MUL_MAT, GGML_OP_GLU }; - const int outputs[] = { routed_idx + 2, shared_idx + 2 }; - if (!ggml_can_fuse_subgraph_ext(graph, nodes, 6, ops, outputs, 2)) { - return false; - } - - const ggml_tensor * routed = graph->nodes[routed_idx + 2]; - const ggml_tensor * shared = graph->nodes[shared_idx + 2]; - const ggml_tensor * gate = routed->src[0]; - const ggml_tensor * up = routed->src[1]; - const ggml_tensor * shared_gate = shared->src[0]; - const ggml_tensor * shared_up = shared->src[1]; - const auto is_pair = [&](const ggml_tensor * a, const ggml_tensor * b, int idx) { - return (a == graph->nodes[idx] && b == graph->nodes[idx + 1]) || - (b == graph->nodes[idx] && a == graph->nodes[idx + 1]); - }; - // only batch-size independent checks here: graph_optimize must produce the same graph topology for every ubatch - // size, otherwise ggml-alloc has to re-reserve (and the scheduler to synchronize) at runtime. - // the MMVQ batch size check is done in ggml_cuda_try_fuse - if (!is_pair(gate, up, routed_idx) || !is_pair(shared_gate, shared_up, shared_idx) || - !ggml_cuda_should_fuse_mul_mat(up, gate, routed) || - !ggml_cuda_should_fuse_mul_mat(shared_up, shared_gate, shared) || - !up->src[0]->buffer || - !ggml_is_quantized(up->src[0]->type)) { - return false; - } - const ggml_tensor * input = up->src[1]; - const ggml_tensor * weight = up->src[0]; - const ggml_tensor * shared_weight = shared_up->src[0]; - if (input->op != GGML_OP_RESHAPE || input->src[0] != shared_up->src[1] || - input->ne[1] != 1 || input->ne[3] != 1 || !ggml_is_contiguous(input) || - !ggml_is_contiguous(shared_up->src[1]) || !ggml_is_matrix(shared_up->src[1]) || - weight->type != shared_weight->type || weight->ne[0] != shared_weight->ne[0] || - weight->ne[1] != shared_weight->ne[1] || weight->nb[1] != shared_weight->nb[1] || weight->ne[3] != 1 || - !ggml_is_matrix(shared_weight) || !ggml_is_contiguous(shared_weight) || - !ggml_is_contiguous(shared_gate->src[0]) || !ggml_is_contiguous(routed) || !ggml_is_contiguous(shared)) { - return false; - } - if (shared_weight->op != GGML_OP_NONE || shared_gate->src[0]->op != GGML_OP_NONE || - ggml_get_glu_op(routed) != ggml_get_glu_op(shared) || - ggml_get_op_params_f32(routed, 3) != ggml_get_op_params_f32(shared, 3)) { - return false; - } - return true; -} - -// The weight scale that scale_node (MUL) applies to the output of mm_node (MUL_MAT), or nullptr. -// Shared by ggml_cuda_try_fuse and graph_optimize so that both accept the same patterns. -static const ggml_tensor * ggml_cuda_get_mul_mat_scale(const ggml_tensor * scale_node, const ggml_tensor * mm_node) { - const bool scale_lhs_mm = scale_node->src[0] == mm_node; - const bool scale_rhs_mm = scale_node->src[1] == mm_node; - if (!scale_lhs_mm && !scale_rhs_mm) { - return nullptr; - } - - const ggml_tensor * scale = scale_lhs_mm ? scale_node->src[1] : scale_node->src[0]; - if ((mm_node->src[0]->type != GGML_TYPE_NVFP4 && mm_node->src[0]->type != GGML_TYPE_F8_E4M3) || scale_node->type != GGML_TYPE_F32 || - scale->type != GGML_TYPE_F32 || !ggml_is_contiguous(scale) || ggml_nelements(scale) != 1 || - !ggml_are_same_shape(scale_node, mm_node)) { - return nullptr; - } - - return scale; -} - -// The same for MUL_MAT_ID with one scale per expert: RESHAPE, REPEAT and GET_ROWS (by the ids) of the scales, then the MUL. -static const ggml_tensor * ggml_cuda_get_mul_mat_id_scale(const ggml_tensor * reshape, const ggml_tensor * repeat, const ggml_tensor * getrows, - const ggml_tensor * scale_node, const ggml_tensor * mm_node) { - if (repeat->src[0] != reshape || getrows->src[0] != repeat || getrows->src[1] != mm_node->src[2]) { - return nullptr; - } - if (!((scale_node->src[0] == mm_node && scale_node->src[1] == getrows) || - (scale_node->src[0] == getrows && scale_node->src[1] == mm_node))) { - return nullptr; - } - - const ggml_tensor * scale = reshape->src[0]; - if ((mm_node->src[0]->type != GGML_TYPE_NVFP4 && mm_node->src[0]->type != GGML_TYPE_F8_E4M3) || scale_node->type != GGML_TYPE_F32 || - scale->type != GGML_TYPE_F32 || !ggml_is_contiguous(scale) || ggml_nelements(scale) != mm_node->src[0]->ne[2] || - !ggml_are_same_shape(scale_node, mm_node)) { - return nullptr; - } - - return scale; -} - -// Buffer- and batch-size independent, so graph_optimize produces the same graph topology for every ubatch size (see #29986). -// up_scale/gate_scale: the MUL nodes that apply the NVFP4 weight scales (per tensor or per expert) between the MUL_MATs and the GLU. -static bool ggml_cuda_mul_mat_q_fusion_matches(const ggml_tensor * up, const ggml_tensor * gate, const ggml_tensor * glu, const int device, - const ggml_tensor * up_scale = nullptr, const ggml_tensor * gate_scale = nullptr) { - const ggml_tensor * x_up = up->src[0]; - const ggml_tensor * y = up->src[1]; - - if ((up->op != GGML_OP_MUL_MAT && up->op != GGML_OP_MUL_MAT_ID) || !ggml_cuda_mmq_fusion_supported(x_up->type) || y->type != GGML_TYPE_F32) { - return false; - } - - // The fused kernel is only compiled for weights whose rows fill whole tiles (no fallback). - if (ggml_cuda_mmq_needs_fallback(x_up->ne[1])) { - return false; - } - - if (!ggml_cuda_should_fuse_mul_mat(up, gate, glu, nullptr, nullptr, up_scale, gate_scale)) { - return false; - } - - // The fused kernel runs both MUL_MATs at one src1 precision, see ggml_cuda_mul_mat_q. - if (ggml_prec_get_src(up, 1) != ggml_prec_get_src(gate, 1)) { - return false; - } - - // The fused write-back applies SWIGLU_OAI with the default alpha and limit of ggml_cuda_op_swiglu_oai_single. - if (ggml_get_glu_op(glu) == GGML_GLU_OP_SWIGLU_OAI && (ggml_get_op_params_f32(glu, 2) != 1.702f || ggml_get_op_params_f32(glu, 3) != 7.0f)) { - return false; - } - - // NVIDIA only: the fused write-back relies on the MMA accumulator layout. - return turing_mma_available(ggml_cuda_info().devices[device].cc); -} - -static bool ggml_cuda_should_fuse_mul_mat_q(const ggml_tensor * up, const ggml_tensor * gate, const ggml_tensor * glu, - const ggml_tensor * up_scale = nullptr, const ggml_tensor * gate_scale = nullptr) { - // A hinted matmul can be fused, but its unfused path may be faster (e.g. FWHT for GGML_HINT_SRC0_IS_HADAMARD). - if (ggml_get_op_params_i32(up, 1) != GGML_HINT_NONE || ggml_get_op_params_i32(gate, 1) != GGML_HINT_NONE) { - return false; - } - - // The padding of a compute-buffer weight that is a view cannot be cleared, see ggml_cuda_mul_mat. - const auto bad_padding_clear = [](const ggml_tensor * x) { - return ggml_backend_buffer_get_usage(x->buffer) == GGML_BACKEND_BUFFER_USAGE_COMPUTE && - ggml_nbytes(x) != ggml_backend_buffer_get_alloc_size(x->buffer, x) && x->view_src; - }; - const int device = ggml_cuda_get_device(); - if (!ggml_cuda_mul_mat_q_fusion_matches(up, gate, glu, device, up_scale, gate_scale) || bad_padding_clear(up->src[0]) || bad_padding_clear(gate->src[0])) { - return false; - } - - // The batch size checks are done here, not in ggml_cuda_mul_mat_q_fusion_matches. - const ggml_tensor * x_up = up->src[0]; - const ggml_tensor * y = up->src[1]; - const int cc = ggml_cuda_info().devices[device].cc; - - // For MUL_MAT_ID: the MMVQ/MMQ choice of ggml_cuda_mul_mat_id, with the nominal tiles of all experts (the per-expert token counts are only known on the GPU). - const bool is_id = up->op == GGML_OP_MUL_MAT_ID; - const int64_t ncols = is_id ? y->ne[2] : y->ne[1]; - const int64_t nchannels = is_id ? x_up->ne[2] : y->ne[2]*y->ne[3]; - const bool use_mmvq = is_id ? ncols <= get_mmvq_mmid_max_batch(x_up->type, cc) : ggml_cuda_should_use_mmvq(x_up->type, cc, ncols); - // do not fuse the matmuls that few-row MMQ takes in ggml_cuda_mul_mat; for MUL_MAT_ID the fused MMQ keeps the expert gate and up - if (!is_id && ggml_cuda_should_use_mmq_few(x_up, y, nullptr, cc)) { - return false; - } - if (use_mmvq || !ggml_cuda_should_use_mmq(x_up->type, cc, ncols, /*n_experts =*/ is_id ? x_up->ne[2] : 0)) { - return false; - } - - // The fused kernel needs one block per tile (no stream-k split), so only fuse if the tiling is efficient. - return ggml_cuda_mmq_fusion_is_efficient(x_up->type, ggml_prec_get_src(up, 1), x_up->ne[1], ncols, nchannels, device); -} - static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { GGML_TENSOR_BINARY_OP_LOCALS @@ -2544,7 +2215,8 @@ static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor // Therefore, in such cases use cuBLAS. const bool bad_padding_clear = ggml_backend_buffer_get_usage(src0->buffer) == GGML_BACKEND_BUFFER_USAGE_COMPUTE && ggml_nbytes(src0) != ggml_backend_buffer_get_alloc_size(src0->buffer, src0) && src0->view_src; - if (bad_padding_clear || src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) { + // MMVQ, MMQ and MMVF (BF16 and FP8 weights) also read a BF16 src1, MMF only an F32 src1 + if (bad_padding_clear || (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_BF16) || dst->type != GGML_TYPE_F32) { ggml_cuda_mul_mat_cublas(ctx, src0, src1, dst); return; } @@ -2552,7 +2224,7 @@ static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor const int cc = ggml_cuda_info().devices[ctx.device].cc; const int warp_size = ggml_cuda_info().devices[ctx.device].warp_size; - if (ggml_cuda_should_use_mmvf(src0, cc, warp_size, ne11)) { + if (ggml_cuda_should_use_mmvf(src0, src1->type, cc, warp_size, ne11, /*mul_mat_id =*/ false)) { // The custom vector kernel can be used over batched cuBLAS GEMM. // But this is only faster for GPUs without tensor cores or with a thin src0 matrix (particularly KQV in attention) ggml_cuda_mul_mat_vec_f(ctx, src0, src1, nullptr, dst); @@ -2562,7 +2234,7 @@ static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor if (ne01 == 1 && ne11 > MMVF_MAX_BATCH_SIZE && ne2 == 1 && ne3 == 1 && src0->type == GGML_TYPE_F32 && ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst) - && ggml_cuda_should_use_mmvf(src1, cc, warp_size, /*ne11 =*/ 1)) { + && ggml_cuda_should_use_mmvf(src1, src0->type, cc, warp_size, /*ne11 =*/ 1, /*mul_mat_id =*/ false)) { ggml_tensor dst_vec = *dst; dst_vec.ne[0] = ne11; dst_vec.ne[1] = 1; @@ -2572,7 +2244,7 @@ static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor ggml_cuda_mul_mat_vec_f(ctx, src1, src0, nullptr, &dst_vec); return; } - if (ggml_cuda_should_use_mmf(src0->type, cc, warp_size, src0->ne, src0->nb, ne11, /*mul_mat_id =*/ false)) { + if (src1->type == GGML_TYPE_F32 && ggml_cuda_should_use_mmf(src0->type, cc, warp_size, src0->ne, src0->nb, ne11, /*mul_mat_id =*/ false)) { ggml_cuda_mul_mat_f(ctx, src0, src1, nullptr, dst); return; } @@ -2603,7 +2275,7 @@ static bool ggml_cuda_mul_mat_id_needs_sync(const ggml_tensor * dst, const int c const ggml_tensor * src1 = dst->src[1]; const int warp_size = ggml_cuda_info().devices[ggml_cuda_get_device()].warp_size; - if (src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) { + if ((src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_BF16) || dst->type != GGML_TYPE_F32) { return true; } @@ -2612,10 +2284,7 @@ static bool ggml_cuda_mul_mat_id_needs_sync(const ggml_tensor * dst, const int c if (dst->ne[2] <= get_mmvq_mmid_max_batch(src0->type, cc)) { return false; } - } else if (src0->type == GGML_TYPE_F8_E4M3 && - ggml_cuda_should_use_mmvf(src0, cc, warp_size, dst->ne[2])) { - return false; - } else if (src0->type != GGML_TYPE_F8_E4M3 && GGML_CUDA_CC_IS_AMD(cc) && src0->ne[0] % 2 == 0) { + } else if (ggml_cuda_should_use_mmvf(src0, src1->type, cc, warp_size, dst->ne[2], /*mul_mat_id =*/ true)) { return false; } } @@ -2628,7 +2297,7 @@ static bool ggml_cuda_mul_mat_id_needs_sync(const ggml_tensor * dst, const int c return false; } - if (ggml_cuda_should_use_mmf(src0->type, cc, warp_size, src0->ne, src0->nb, src1->ne[2], /*mul_mat_id=*/true)) { + if (src1->type == GGML_TYPE_F32 && ggml_cuda_should_use_mmf(src0->type, cc, warp_size, src0->ne, src0->nb, src1->ne[2], /*mul_mat_id=*/true)) { return false; } @@ -2640,7 +2309,7 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * const ggml_tensor * src1 = dst->src[1]; const ggml_tensor * ids = dst->src[2]; - GGML_ASSERT(src1->type == GGML_TYPE_F32); + GGML_ASSERT(src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16); GGML_ASSERT(dst->type == GGML_TYPE_F32); GGML_TENSOR_BINARY_OP_LOCALS @@ -2649,7 +2318,7 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * const int warp_size = ggml_cuda_info().devices[ggml_cuda_get_device()].warp_size; // [TAG_MUL_MAT_ID_CUDA_GRAPHS] - if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { + if ((src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16) && dst->type == GGML_TYPE_F32) { // up to 24 tokens few-row MMQ is faster than MMQ, on DGX Spark also faster than MMVQ const bool use_mmq_few = ggml_cuda_should_use_mmq_few(src0, src1, ids, cc); @@ -2661,16 +2330,9 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * ggml_cuda_mul_mat_vec_q(ctx, src0, src1, ids, dst); return; } - } else if (src0->type == GGML_TYPE_F8_E4M3 && - ggml_cuda_should_use_mmvf(src0, cc, warp_size, ne2)) { + } else if (ggml_cuda_should_use_mmvf(src0, src1->type, cc, warp_size, ne2, /*mul_mat_id =*/ true)) { ggml_cuda_mul_mat_vec_f(ctx, src0, src1, ids, dst); return; - } else { - // MMVF reads src0 in pairs of values, so it needs an even number of columns - if (src0->type != GGML_TYPE_F8_E4M3 && GGML_CUDA_CC_IS_AMD(cc) && ne00 % 2 == 0) { - ggml_cuda_mul_mat_vec_f(ctx, src0, src1, ids, dst); - return; - } } } @@ -2684,7 +2346,7 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * return; } - if (ggml_cuda_should_use_mmf(src0->type, cc, warp_size, src0->ne, src0->nb, src1->ne[2], /*mul_mat_id=*/true)) { + if (src1->type == GGML_TYPE_F32 && ggml_cuda_should_use_mmf(src0->type, cc, warp_size, src0->ne, src0->nb, src1->ne[2], /*mul_mat_id=*/true)) { ggml_cuda_mul_mat_f(ctx, src0, src1, ids, dst); return; } @@ -3297,2076 +2959,205 @@ static bool ggml_backend_cuda_cpy_tensor_async(ggml_backend_t backend_src, ggml_ CUDA_CHECK(cudaMemcpyAsync(dst->data, src->data, ggml_nbytes(dst), cudaMemcpyDeviceToDevice, cuda_ctx_src->stream())); } return true; -} - -static void ggml_backend_cuda_synchronize(ggml_backend_t backend) { - ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *)backend->context; - - CUDA_CHECK(cudaStreamSynchronize(cuda_ctx->stream())); - - GGML_UNUSED(backend); -} - -static bool ggml_cuda_is_view_or_noop(const ggml_tensor * t) { - return ggml_is_empty(t) || t->op == GGML_OP_RESHAPE || t->op == GGML_OP_TRANSPOSE || - t->op == GGML_OP_VIEW || t->op == GGML_OP_PERMUTE || t->op == GGML_OP_NONE; -} - -#ifdef USE_CUDA_GRAPH -static bool ggml_cuda_graph_debug_enabled() { - static const bool enabled = ggml_cuda_env_flag("GGML_CUDA_GRAPH_DEBUG"); - return enabled; -} - -static bool ggml_cuda_graph_check_compability(ggml_cgraph * cgraph) { - - bool use_cuda_graph = true; - // Loop over nodes in GGML graph to obtain info needed for CUDA graph - - for (int i = 0; i < cgraph->n_nodes; i++) { - ggml_tensor * node = cgraph->nodes[i]; - - if (ggml_cuda_is_view_or_noop(node)) { - continue; - } - - // [TAG_MUL_MAT_ID_CUDA_GRAPHS] - if (node->op == GGML_OP_MUL_MAT_ID) { - const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; - if (ggml_cuda_mul_mat_id_needs_sync(node, cc)) { - // the mul_mat_id fallback path synchronizes the stream, so we cannot use CUDA graphs - // ref: https://github.com/ggml-org/llama.cpp/pull/18958 - use_cuda_graph = false; - if (ggml_cuda_graph_debug_enabled()) { - GGML_LOG_DEBUG("%s: disabling CUDA graphs due to unsupported node type\n", __func__); - } - } - } - - if (!use_cuda_graph) { - break; - } - } - - return use_cuda_graph; -} - -static const void * ggml_cuda_graph_get_key(ggml_cgraph * cgraph) { - return cgraph->nodes[0]; -} - -static bool ggml_cuda_graph_update_required(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph) { - bool res = false; - - const void * graph_key = ggml_cuda_graph_get_key(cgraph); - ggml_cuda_graph * graph = cuda_ctx->cuda_graph(graph_key); - - if (cgraph->uid != 0 && - cgraph->uid == graph->uid) { - if (ggml_cuda_graph_debug_enabled()) { - GGML_LOG_DEBUG("CUDA Graph id %zu reused\n", cgraph->uid); - } - GGML_ASSERT((int)graph->node_props.size() == cgraph->n_nodes); - return false; - } - - graph->uid = cgraph->uid; - - // Check if the graph size has changed - if ((int)graph->node_props.size() != cgraph->n_nodes) { - res = true; - graph->node_props.resize(cgraph->n_nodes); - } - - for (int i = 0; i < cgraph->n_nodes; i++) { - ggml_cuda_graph::node_properties prop = {}; - memcpy(&prop.node, cgraph->nodes[i], sizeof(ggml_tensor)); - - for (int j = 0; j < GGML_MAX_SRC; ++j) { - if (cgraph->nodes[i]->src[j]) { - prop.node_src_data_ptrs[j] = cgraph->nodes[i]->src[j]->data; - memcpy(prop.node_src_ne[j], cgraph->nodes[i]->src[j]->ne, sizeof(prop.node_src_ne[j])); - memcpy(prop.node_src_nb[j], cgraph->nodes[i]->src[j]->nb, sizeof(prop.node_src_nb[j])); - } - } - - if (res || memcmp(&graph->node_props[i], &prop, sizeof(prop)) != 0) { - graph->node_props[i] = prop; - res = true; - } - } - - return res; -} - -#ifdef USE_CUDA_GRAPH_CLUSTER_CHECK -static std::vector ggml_cuda_graph_get_clusters(cudaGraph_t cuda_graph, int device) { - std::vector clusters; - static const bool runtime_affected = [] { - int version = 0; - CUDA_CHECK(cudaRuntimeGetVersion(&version)); - // TODO: upper bound once fixed in the CUDA runtime - return version >= 11080; - }(); - if (!runtime_affected || ggml_cuda_info().devices[device].cc < GGML_CUDA_CC_HOPPER) { - return clusters; - } - size_t n_nodes = 0; - CUDA_CHECK(cudaGraphGetNodes(cuda_graph, nullptr, &n_nodes)); - std::vector nodes(n_nodes); - CUDA_CHECK(cudaGraphGetNodes(cuda_graph, nodes.data(), &n_nodes)); - for (size_t i = 0; i < n_nodes; ++i) { - cudaGraphNodeType type; - CUDA_CHECK(cudaGraphNodeGetType(nodes[i], &type)); - if (type != cudaGraphNodeTypeKernel) { - continue; - } - cudaLaunchAttributeValue val = {}; - CUDA_CHECK(cudaGraphKernelNodeGetAttribute(nodes[i], cudaLaunchAttributeClusterDimension, &val)); - if (val.clusterDim.x * val.clusterDim.y * val.clusterDim.z > 1) { - clusters.push_back({ i, val.clusterDim.x, val.clusterDim.y, val.clusterDim.z }); - } - } - return clusters; -} -#endif // USE_CUDA_GRAPH_CLUSTER_CHECK - -static void ggml_cuda_graph_update_executable(ggml_cuda_graph_instance & instance, cudaGraph_t cuda_graph, int device) { -#ifdef USE_CUDA_GRAPH_CLUSTER_CHECK - std::vector clusters = ggml_cuda_graph_get_clusters(cuda_graph, device); - if (instance.clusters != clusters) { - if (ggml_cuda_graph_debug_enabled()) { - GGML_LOG_DEBUG("%s: cluster dims changed, re-instantiating CUDA graph\n", __func__); - } - CUDA_CHECK(cudaGraphExecDestroy(instance)); - CUDA_CHECK(cudaGraphInstantiate(&instance.handle, cuda_graph, nullptr, nullptr, 0)); - instance.clusters = std::move(clusters); - return; - } -#else - GGML_UNUSED(device); -#endif // USE_CUDA_GRAPH_CLUSTER_CHECK - -#if CUDART_VERSION >= 12000 - cudaGraphExecUpdateResultInfo result_info; - cudaError_t stat = cudaGraphExecUpdate(instance, cuda_graph, &result_info); -#else - cudaGraphNode_t errorNode; - cudaGraphExecUpdateResult result_info; - cudaError_t stat = cudaGraphExecUpdate(instance, cuda_graph, &errorNode, &result_info); -#endif // CUDART_VERSION >= 12000 - - if (stat == cudaErrorGraphExecUpdateFailure) { - if (ggml_cuda_graph_debug_enabled()) { - GGML_LOG_DEBUG("%s: CUDA graph update failed\n", __func__); - } - - // The pre-existing graph exec cannot be updated due to violated constraints - // so instead clear error and re-instantiate - (void)cudaGetLastError(); - CUDA_CHECK(cudaGraphExecDestroy(instance)); - instance.handle = nullptr; - CUDA_CHECK(cudaGraphInstantiate(&instance.handle, cuda_graph, nullptr, nullptr, 0)); - } else { - GGML_ASSERT(stat == cudaSuccess); - } -} - -// number of ggml nodes per CUDA graph chunk, 0 captures the whole ggml graph as one CUDA graph -static int ggml_cuda_graph_chunk_size() { - static const int chunk_size = [] { - const char * env = getenv("GGML_CUDA_GRAPH_CHUNK_SIZE"); - return env != nullptr ? atoi(env) : 512; - }(); - return chunk_size; -} - -// end the capture of chunk `idx`, update or create its executable and launch it -static void ggml_cuda_graph_launch_chunk(ggml_backend_cuda_context * cuda_ctx, ggml_cuda_graph * graph, size_t idx) { - cudaGraph_t cuda_graph = nullptr; - CUDA_CHECK(cudaStreamEndCapture(cuda_ctx->stream(), &cuda_graph)); - - if (idx < graph->instances.size()) { - ggml_cuda_graph_update_executable(graph->instances[idx], cuda_graph, cuda_ctx->device); - } else { - GGML_ASSERT(idx == graph->instances.size()); - graph->instances.emplace_back(); - CUDA_CHECK(cudaGraphInstantiate(&graph->instances[idx].handle, cuda_graph, nullptr, nullptr, 0)); -#ifdef USE_CUDA_GRAPH_CLUSTER_CHECK - graph->instances[idx].clusters = ggml_cuda_graph_get_clusters(cuda_graph, cuda_ctx->device); -#endif // USE_CUDA_GRAPH_CLUSTER_CHECK - } - CUDA_CHECK(cudaGraphDestroy(cuda_graph)); - - CUDA_CHECK(cudaGraphLaunch(graph->instances[idx], cuda_ctx->stream())); -} -#endif // USE_CUDA_GRAPH - -static bool ggml_cuda_should_fuse_rope_set_rows(const ggml_tensor * rope, - const ggml_tensor * view, - const ggml_tensor * set_rows) { - - if (rope->op != GGML_OP_ROPE || view->op != GGML_OP_VIEW || set_rows->op != GGML_OP_SET_ROWS) { - return false; - } - // ne3 not tested - if (rope->src[0]->ne[3] != 1) { - return false; - } - - if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16 && set_rows->type != GGML_TYPE_BF16) { - return false; - } - - // BF16 rope fuses into an F16 or BF16 cache, other ropes not into a BF16 cache - if (rope->type == GGML_TYPE_BF16 ? set_rows->type == GGML_TYPE_F32 : set_rows->type == GGML_TYPE_BF16) { - return false; - } - - if (set_rows->src[1]->type != GGML_TYPE_I64) { - return false; - } - - // The view should flatten two dims of rope into one dim - if (!ggml_is_contiguous(view) || view->ne[0] != rope->ne[0] * rope->ne[1]) { - return false; - } - - // Only norm/neox/multi shaders have the fusion code - const int mode = ((const int32_t *) rope->op_params)[2]; - if (mode != GGML_ROPE_TYPE_NORMAL && mode != GGML_ROPE_TYPE_NEOX && - mode != GGML_ROPE_TYPE_MROPE && mode != GGML_ROPE_TYPE_IMROPE) { - return false; - } - - return true; -} - -static bool ggml_cuda_should_fuse_rms_norm_mul_rope(const ggml_tensor * rms_norm, - const ggml_tensor * mul, - const ggml_tensor * rope) { - if (rms_norm->op != GGML_OP_RMS_NORM || mul->op != GGML_OP_MUL || rope->op != GGML_OP_ROPE) { - return false; - } - - if (rms_norm->src[0]->type != GGML_TYPE_F32 || rms_norm->type != GGML_TYPE_F32 || - mul->src[0]->type != GGML_TYPE_F32 || mul->src[1]->type != GGML_TYPE_F32 || - mul->type != GGML_TYPE_F32 || rope->type != GGML_TYPE_F32) { - return false; - } - - if (rope->src[0] != mul) { - 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; - } - - if (!ggml_are_same_shape(rms_norm, mul)) { - return false; - } - - //rms_norm kernel assumes contiguous rows - if (!ggml_is_contiguous_rows(rms_norm->src[0]) || - !ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) { - return false; - } - - const int mode = ((const int32_t *) rope->op_params)[2]; - if (mode != GGML_ROPE_TYPE_NORMAL && mode != GGML_ROPE_TYPE_NEOX && - mode != GGML_ROPE_TYPE_MROPE && mode != GGML_ROPE_TYPE_IMROPE) { - return false; - } - - if (mode & GGML_ROPE_TYPE_MROPE) { - int sections[4]; - memcpy(sections, (const int32_t *) rope->op_params + 11, sizeof(int) * 4); - const int sect_dims = sections[0] + sections[1] + sections[2] + sections[3]; - if ((sections[0] <= 0 && sections[1] <= 0 && sections[2] <= 0) || sect_dims <= 0) { - return false; - } - } - - const int n_dims = ((const int32_t *) rope->op_params)[1]; - if (n_dims % 2 != 0 || rope->src[0]->ne[0] % 2 != 0) { - return false; - } - - // ggml_rope_set_offset is not yet supported in the fused kernel - const int n_offs = ((const int32_t *) rope->op_params)[15]; - if (n_offs != 0) { - return false; - } - - return true; -} - -// match gated_delta_net + the strided cpy that scatters its state snapshots into the cache -// (slot i -> rollback group i, slot 0 newest), so the kernel can write them and skip the cpy. -static int ggml_cuda_try_gdn_cache_fusion( - const ggml_cgraph * cgraph, int node_idx, ggml_cuda_gated_delta_net_fused_cache & fused_state_cpy) { - const ggml_tensor * gdn = cgraph->nodes[node_idx]; - // the kernel skips the snapshot tail, so the gdn output must not be a graph output - if (gdn->op != GGML_OP_GATED_DELTA_NET || gdn->type != GGML_TYPE_F32 || - (gdn->flags & GGML_TENSOR_FLAG_OUTPUT)) { - return 0; - } - - const ggml_tensor * src_v = gdn->src[2]; - const int64_t S_v = src_v->ne[0]; - const int64_t H = src_v->ne[1]; - const int64_t n_tokens = src_v->ne[2]; - const int64_t n_seqs = src_v->ne[3]; - const int64_t D = S_v * S_v * H; - const int64_t K = ggml_get_op_params_i32(gdn, 0); // snapshot slot count - const int64_t n_written = std::min(n_tokens, K); // newest n_written slots are written - - // snapshot tail starts right after the attention scores - const size_t tail_off = ggml_row_size(GGML_TYPE_F32, S_v * H * n_tokens * n_seqs); - - // snapshot cpy is the first real node after the gdn (skip views/no-ops) - const ggml_tensor * cpy = nullptr; - int skip = 0; - for (int j = node_idx + 1; j < cgraph->n_nodes && cpy == nullptr; ++j) { - const ggml_tensor * n = cgraph->nodes[j]; - if (ggml_cuda_is_view_or_noop(n)) { - continue; - } - if (n->op != GGML_OP_CPY || (n->flags & GGML_TENSOR_FLAG_OUTPUT)) { - return 0; - } - cpy = n; - skip = j - node_idx; - } - if (cpy == nullptr) { - return 0; - } - - const ggml_tensor * src = cpy->src[0]; // view of the gdn snapshot tail - const ggml_tensor * dst = cpy->src[1]; // cache view the kernel writes to - - // src must be this gdn's snapshot tail (contiguous, at the tail offset) - if (src->op != GGML_OP_VIEW || src->view_src != gdn || src->view_offs != tail_off || - !ggml_is_contiguous(src)) { - return 0; - } - - // dst is the [D, n_seqs, n_written] cache view; require nb[1] == D (the per-seq stride the kernel - // assumes). ggml_cpy pins src to the same element count. - const std::array expected_ne = { D, n_seqs, n_written, 1 }; - if (dst->op != GGML_OP_VIEW || dst->type != GGML_TYPE_F32 || dst->data == nullptr || - !std::equal(expected_ne.begin(), expected_ne.end(), dst->ne) || - dst->nb[0] != ggml_type_size(GGML_TYPE_F32) || dst->nb[1] != (size_t) ggml_row_size(GGML_TYPE_F32, D)) { - return 0; - } - - 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; -} - -// match ssm_scan + the strided cpy that scatters its state snapshots into the cache, so the kernel writes them and skips the cpy -static int ggml_cuda_try_ssm_scan_cache_fusion( - const ggml_cgraph * cgraph, int node_idx, ggml_cuda_ssm_scan_fused_cache & fused_state_cpy) { - const ggml_tensor * ssm = cgraph->nodes[node_idx]; - // the kernel skips the snapshot tail, so the scan output must not be a graph output - if (ssm->op != GGML_OP_SSM_SCAN || ssm->type != GGML_TYPE_F32 || (ssm->flags & GGML_TENSOR_FLAG_OUTPUT)) { - return 0; - } - - const int64_t K = ggml_get_op_params_i32(ssm, 0); // snapshot slot count - - const ggml_tensor * s = ssm->src[0]; - const ggml_tensor * x = ssm->src[1]; - const ggml_tensor * A = ssm->src[3]; - - const int64_t d_state = s->ne[0]; - const int64_t D = d_state * s->ne[1] * x->ne[1]; // d_state * head_dim * n_head - const int64_t n_tok = x->ne[2]; - const int64_t n_seqs = x->ne[3]; - - // only the mamba-2 kernels (group scan and SSD) write to the cache; mamba-1 still uses the cpy - if (A->nb[1] != sizeof(float) || (d_state != 96 && d_state != 128 && d_state != 256)) { - return 0; - } - - // the scan reads its input rows from the cache (picked by ids), so with more than one seq a seq can read a row that another seq writes in the same launch - if (n_seqs != 1) { - return 0; - } - - const int64_t n_written = std::min(n_tok, K); - const size_t tail_off = ggml_row_size(GGML_TYPE_F32, ggml_nelements(x)); - - // snapshot cpy is the first real node after the scan (skip views/no-ops) - const ggml_tensor * cpy = nullptr; - int skip = 0; - for (int j = node_idx + 1; j < cgraph->n_nodes && cpy == nullptr; ++j) { - const ggml_tensor * n = cgraph->nodes[j]; - if (ggml_cuda_is_view_or_noop(n)) { - continue; - } - if (n->op != GGML_OP_CPY || (n->flags & GGML_TENSOR_FLAG_OUTPUT)) { - return 0; - } - cpy = n; - skip = j - node_idx; - } - if (cpy == nullptr) { - return 0; - } - - const ggml_tensor * src = cpy->src[0]; // view of the scan snapshot tail - const ggml_tensor * dst = cpy->src[1]; // cache view the kernel writes to - - // src must be this scan's snapshot tail (contiguous, at the tail offset) - if (src->op != GGML_OP_VIEW || src->view_src != ssm || src->view_offs != tail_off || - !ggml_is_contiguous(src)) { - return 0; - } - - // dst is the [D, n_seqs, n_written] cache view; require nb[1] == D, the per-seq stride the kernel takes from src0->nb[3] - const std::array expected_ne = { D, n_seqs, n_written, 1 }; - if (dst->op != GGML_OP_VIEW || dst->type != GGML_TYPE_F32 || dst->data == nullptr || - !std::equal(expected_ne.begin(), expected_ne.end(), dst->ne) || - dst->nb[0] != ggml_type_size(GGML_TYPE_F32) || dst->nb[1] != (size_t) ggml_row_size(GGML_TYPE_F32, D)) { - return 0; - } - - fused_state_cpy.data = (float *) dst->data; // rollback slot 0 (newest) - fused_state_cpy.slot_stride = K > 1 ? (int64_t) (dst->nb[2] / sizeof(float)) : 0; - return skip; -} - -// expert group selection from build_moe_ffn (n_expert_groups > 1) -// src0/src1 index into this table, -1 is the (biased) probs, -2 is not checked -static const struct { - ggml_op op; - int src0; - int src1; -} topk_moe_group_pattern[] = { - { GGML_OP_RESHAPE, -1, -2 }, // 0: [n_exp_per_group, n_expert_groups, n_tokens] - { GGML_OP_RESHAPE, 0, -2 }, // 1: [1, n_exp_per_group, n_expert_groups, n_tokens] - { GGML_OP_ARGSORT, 0, -2 }, // 2 - { GGML_OP_VIEW, 2, -2 }, // 3: top-2 per group - { GGML_OP_GET_ROWS, 1, 3 }, // 4 - { GGML_OP_RESHAPE, 4, -2 }, // 5 - { GGML_OP_SUM_ROWS, 5, -2 }, // 6: group scores - { GGML_OP_RESHAPE, 6, -2 }, // 7 - { GGML_OP_ARGSORT, 7, -2 }, // 8 - { GGML_OP_VIEW, 8, -2 }, // 9: top n_group_used groups - { GGML_OP_GET_ROWS, 0, 9 }, // 10 - { GGML_OP_FILL, 0, -2 }, // 11 - { GGML_OP_SET_ROWS, 10, 9 }, // 12: unused groups -> -inf - { GGML_OP_RESHAPE, 12, -2 }, // 13: [n_expert, n_tokens] -}; - -static bool ggml_cuda_topk_moe_group_fusion(const struct ggml_cgraph * cgraph, int node_idx, const ggml_tensor * selection, ggml_cuda_topk_moe_args & args) { - const int n_ops = (int) std::size(topk_moe_group_pattern); - if (node_idx + n_ops > cgraph->n_nodes) { - return false; - } - - ggml_tensor ** nodes = cgraph->nodes + node_idx; - auto src_ok = [&](const ggml_tensor * src, int idx) { - return idx == -2 || src == (idx == -1 ? selection : nodes[idx]); - }; - - for (int i = 0; i < n_ops; i++) { - const auto & p = topk_moe_group_pattern[i]; - if (nodes[i]->op != p.op || !src_ok(nodes[i]->src[0], p.src0) || !src_ok(nodes[i]->src[1], p.src1)) { - return false; - } - } - - const int n_groups = nodes[0]->ne[1]; - const int n_group_used = nodes[9]->ne[0]; - - if (nodes[3]->ne[0] != 2 || nodes[12]->src[2] != nodes[11] || ggml_get_op_params_f32(nodes[11], 0) != -INFINITY || - n_groups > WARP_SIZE) { - return false; - } - - args.n_groups = n_groups; - args.n_group_used = n_group_used; - return true; -} - -static bool ggml_cuda_topk_moe_fusion(const struct ggml_cgraph * cgraph, int node_idx, ggml_cuda_topk_moe_args & args) { - args.sigmoid = false; - args.sqrt_softplus = false; - args.softmax = false; - args.delayed_softmax = false; - args.prob_bias = false; - args.norm = false; - args.n_groups = 0; - args.n_group_used = 0; - - const int n_nodes = cgraph->n_nodes; - ggml_tensor ** nodes = cgraph->nodes; - - if (nodes[node_idx]->op == GGML_OP_SOFT_MAX) { - args.softmax = true; - } - - if (nodes[node_idx]->op == GGML_OP_UNARY) { - const ggml_unary_op unary_op = ggml_get_unary_op(nodes[node_idx]); - if (unary_op == GGML_UNARY_OP_SIGMOID) { - args.sigmoid = true; - } else if (unary_op == GGML_UNARY_OP_SOFTPLUS && node_idx + 1 < n_nodes && - nodes[node_idx + 1]->op == GGML_OP_SQRT && nodes[node_idx + 1]->src[0] == nodes[node_idx]) { - // sqrt(softplus(x)) scoring (DeepSeek-V4) - args.sqrt_softplus = true; - node_idx++; - } else { - return false; - } - } - - if (nodes[node_idx]->op == GGML_OP_ARGSORT) { - args.delayed_softmax = true; - } - - node_idx++; - - if (args.sigmoid || args.sqrt_softplus || args.softmax) { - // SOFTMAX -> RESHAPE - if (node_idx >= n_nodes || nodes[node_idx]->op != GGML_OP_RESHAPE || - nodes[node_idx]->src[0] != nodes[node_idx - 1]) { - return false; - } - ggml_tensor * probs_reshaped = nodes[node_idx]; - node_idx++; - - if (node_idx >= n_nodes) { - return false; - } - - // src of bias add is the unreshaped probs (-2 instead of -1) - const ggml_tensor * selection = nodes[node_idx - 2]; - if (nodes[node_idx]->op == GGML_OP_ADD && nodes[node_idx]->src[0] == selection) { - args.prob_bias = true; - selection = nodes[node_idx]; - node_idx++; - } - - if (ggml_cuda_topk_moe_group_fusion(cgraph, node_idx, selection, args)) { - node_idx += (int) std::size(topk_moe_group_pattern); - selection = nodes[node_idx - 1]; - } - - // RESHAPE/ADD/group mask -> ARGSORT - if (node_idx >= n_nodes || nodes[node_idx]->op != GGML_OP_ARGSORT || nodes[node_idx]->src[0] != selection) { - return false; - } - - node_idx++; - - // ARGSORT-> VIEW - if (node_idx >= n_nodes || nodes[node_idx]->op != GGML_OP_VIEW || - nodes[node_idx]->src[0] != nodes[node_idx - 1]) { - return false; - } - - // kept groups must hold all used experts - if (args.n_groups > 0 && nodes[node_idx]->ne[0] > args.n_group_used * (probs_reshaped->ne[1] / args.n_groups)) { - return false; - } - node_idx++; - - if (node_idx >= n_nodes || nodes[node_idx]->op != GGML_OP_GET_ROWS) { - return false; - } - - // GET_ROWS - if (nodes[node_idx]->src[0] != probs_reshaped || nodes[node_idx]->src[1] != nodes[node_idx - 1]) { - return false; - } - node_idx++; - } else if (args.delayed_softmax) { - if (node_idx - 2 < 0) { - return false; - } - ggml_tensor * probs_reshaped = nodes[node_idx - 2]; - - // VIEW->ARGSORT - if (node_idx >= n_nodes || nodes[node_idx]->op != GGML_OP_VIEW || - nodes[node_idx]->src[0] != nodes[node_idx - 1]) { - return false; - } - node_idx++; - - // GET_ROWS - if (node_idx >= n_nodes || nodes[node_idx]->src[1] != nodes[node_idx - 1] || - nodes[node_idx]->src[0] != probs_reshaped) { - return false; - } - node_idx++; - - static const std::vector remaining_ops = { GGML_OP_RESHAPE, GGML_OP_SOFT_MAX, GGML_OP_RESHAPE }; - - for (const ggml_op op : remaining_ops) { - if (node_idx >= n_nodes || nodes[node_idx]->op != op || nodes[node_idx]->src[0] != nodes[node_idx - 1]) { - return false; - } - node_idx++; - } - } - - // At this point we can check for norm + scale. Everything is now at least valid till the norm - if (node_idx >= n_nodes) { - return true; - } - - if (nodes[node_idx]->op == GGML_OP_RESHAPE) { - //check RESHAPE->SUM_ROWS->CLAMP->DIV->RESHAPE - static const std::vector norm_ops = { GGML_OP_RESHAPE, GGML_OP_SUM_ROWS, GGML_OP_CLAMP }; - - args.norm = true; - for (const ggml_op op : norm_ops) { - if (nodes[node_idx]->op == op && nodes[node_idx]->src[0] == nodes[node_idx - 1]) { - node_idx++; - } else { - args.norm = false; - return true; - } - } - - // DIV <- CLAMP, RESHAPE - if (nodes[node_idx]->op != GGML_OP_DIV || nodes[node_idx]->src[1] != nodes[node_idx - 1] || - nodes[node_idx]->src[0] != nodes[node_idx - 3]) { - args.norm = false; - return true; - } - node_idx++; - - if (nodes[node_idx]->op != GGML_OP_RESHAPE || nodes[node_idx]->src[0] != nodes[node_idx - 1]) { - args.norm = false; - return true; - } - - node_idx++; - } - - if (nodes[node_idx]->op == GGML_OP_SCALE && nodes[node_idx]->src[0] == nodes[node_idx - 1]) { - args.scale = true; - } - - return true; -} - -// returns whether the write (out) nodes overwrite the read nodes in operation -static bool ggml_cuda_check_fusion_memory_ranges(const ggml_cgraph * cgraph, - const int node_idx, - const int node_count, - const int * out_nodes, - const int out_count, - const bool is_topk_moe = false) { - auto nodes_overlap = [&](const ggml_tensor * a, const ggml_tensor * b) { - const int64_t a_start = (int64_t) a->data; - const int64_t a_end = a_start + ggml_backend_buft_get_alloc_size(a->buffer->buft, a); - - const int64_t b_start = (int64_t) b->data; - const int64_t b_end = b_start + ggml_backend_buft_get_alloc_size(b->buffer->buft, b); - - if ((b_start <= a_start && a_start < b_end) || (a_start <= b_start && b_start < a_end)) { - return true; - } - - return false; - }; - - bool is_ok = true; - // one block reads all logits before it writes, so logits may alias the out nodes - const ggml_tensor * logits_may_alias = nullptr; - if (is_topk_moe && ggml_nrows(cgraph->nodes[node_idx]) <= TOPK_MOE_ROWS_PER_BLOCK) { - logits_may_alias = cgraph->nodes[node_idx]->src[0]; - } - - for (int i = 0; i < out_count; ++i) { - const ggml_tensor * dst = cgraph->nodes[out_nodes[i]]; - - for (int j = node_idx; j < node_idx + node_count; ++j) { - // Loop over all srcs of all nodes in the fusion. If the src overlaps - // the destination and the src is not an intermediate node that's being - // elided, then disable fusion. - - for (int src_idx = 0; src_idx < GGML_MAX_SRC; ++src_idx) { - const ggml_tensor * src = cgraph->nodes[j]->src[src_idx]; - - if (!src || src->op == GGML_OP_NONE || src == logits_may_alias) { - continue; - } - - if (nodes_overlap(dst, src)) { - bool found = false; - - for (int k = node_idx; k < j; ++k) { - if (cgraph->nodes[k] == src) { - found = true; - break; - } - } - - if (!found) { - is_ok = false; - break; - } - } - } - } - } - - return is_ok; -} - -// The long form spans 2*k + 1 nodes. ggml_can_fuse_subgraph() accepts at most -// 31 nodes, so k <= 15; larger values use the per-operation path. -static constexpr int MOE_WEIGHTED_REDUCTION_MAX_EXPERTS = 15; - -struct ggml_cuda_moe_weighted_reduction_match { - const ggml_tensor * experts = nullptr; - const ggml_tensor * expert_scale = nullptr; - const ggml_tensor * weights = nullptr; - ggml_tensor * dst = nullptr; - int node_count = 0; -}; - -static bool ggml_cuda_match_moe_weighted_reduction( - const ggml_cgraph * cgraph, - int node_idx, - ggml_cuda_moe_weighted_reduction_match & match) { - const ggml_tensor * first = cgraph->nodes[node_idx]; - if (first->op != GGML_OP_MUL || first->type != GGML_TYPE_F32 || !ggml_is_contiguous(first)) { - return false; - } - - auto split_mul = [](const ggml_tensor * mul, const ggml_tensor *& full, const ggml_tensor *& broadcast) { - auto is_weights = [mul](const ggml_tensor * tensor) { - return tensor && tensor->type == GGML_TYPE_F32 && ggml_is_contiguous(tensor) && tensor->ne[0] == 1 && - tensor->ne[1] == mul->ne[1] && tensor->ne[2] == mul->ne[2] && tensor->ne[3] == mul->ne[3]; - }; - auto is_experts = [mul](const ggml_tensor * tensor) { - return tensor && tensor->type == GGML_TYPE_F32 && ggml_is_contiguous(tensor) && - ggml_are_same_shape(tensor, mul); - }; - - if (is_experts(mul->src[0]) && is_weights(mul->src[1])) { - full = mul->src[0]; - broadcast = mul->src[1]; - return true; - } - if (is_experts(mul->src[1]) && is_weights(mul->src[0])) { - full = mul->src[1]; - broadcast = mul->src[0]; - return true; - } - return false; - }; - - const ggml_tensor * weighted = first; - const ggml_tensor * experts = nullptr; - const ggml_tensor * expert_scale = nullptr; - const ggml_tensor * weights = nullptr; - int mul_count = 1; - - // Match both structural forms: - // (experts * expert_scale) * router_weight - // experts * router_weight - // The matcher does not depend on the model or quantization type. - if (node_idx + 1 < cgraph->n_nodes) { - const ggml_tensor * second = cgraph->nodes[node_idx + 1]; - const ggml_tensor * scaled = nullptr; - const ggml_tensor * route = nullptr; - const ggml_tensor * raw = nullptr; - const ggml_tensor * scale = nullptr; - if (second->op == GGML_OP_MUL && second->type == GGML_TYPE_F32 && ggml_is_contiguous(second) && - split_mul(second, scaled, route) && scaled == first && split_mul(first, raw, scale)) { - weighted = second; - experts = raw; - expert_scale = scale; - weights = route; - mul_count = 2; - } - } - - if (experts == nullptr && !split_mul(first, experts, weights)) { - return false; - } - - const int n_expert_used = (int) weighted->ne[1]; - const int64_t n_tokens = weighted->ne[2] * weighted->ne[3]; - if (n_expert_used < 2 || n_expert_used > MOE_WEIGHTED_REDUCTION_MAX_EXPERTS) { - return false; - } - - const int node_count = 2 * n_expert_used + mul_count - 1; - if (node_idx + node_count > cgraph->n_nodes) { - return false; - } - - std::vector ops(node_count, GGML_OP_VIEW); - ops[0] = GGML_OP_MUL; - if (mul_count == 2) { - ops[1] = GGML_OP_MUL; - } - std::vector views; - views.reserve(n_expert_used); - const ggml_tensor * previous = nullptr; - int n_adds = 0; - for (int offset = mul_count; offset < node_count; ++offset) { - const ggml_tensor * candidate = cgraph->nodes[node_idx + offset]; - ops[offset] = candidate->op; - - if (candidate->op == GGML_OP_VIEW) { - const int expert = (int) views.size(); - if (expert >= n_expert_used || candidate->src[0] != weighted || candidate->view_src != weighted || - candidate->type != GGML_TYPE_F32 || candidate->ne[0] != weighted->ne[0] || - candidate->ne[1] != n_tokens || candidate->ne[2] != 1 || candidate->ne[3] != 1 || - candidate->nb[0] != weighted->nb[0] || candidate->nb[1] != weighted->nb[2] || - candidate->view_offs != (size_t) expert * weighted->nb[1]) { - return false; - } - views.push_back(candidate); - continue; - } - - if (candidate->op != GGML_OP_ADD || views.size() < 2 || n_adds + 1 >= (int) views.size()) { - return false; - } - const ggml_tensor * lhs = n_adds == 0 ? views[0] : previous; - const ggml_tensor * rhs = views[n_adds + 1]; - if (candidate->src[0] != lhs || candidate->src[1] != rhs || candidate->type != GGML_TYPE_F32) { - return false; - } - previous = candidate; - ++n_adds; - } - - if ((int) views.size() != n_expert_used || n_adds != n_expert_used - 1 || previous == nullptr) { - return false; - } - if (!ggml_is_contiguous(previous) || previous->ne[0] != weighted->ne[0] || - previous->ne[1] != n_tokens || previous->ne[2] != 1 || previous->ne[3] != 1) { - return false; - } - - const int output_idx = node_idx + node_count - 1; - if (!ggml_can_fuse_subgraph(cgraph, node_idx, node_count, ops.data(), &output_idx, 1)) { - return false; - } - - match.experts = experts; - match.expert_scale = expert_scale; - match.weights = weights; - match.dst = cgraph->nodes[output_idx]; - match.node_count = node_count; - return true; -} - - -static bool ggml_cuda_can_fuse(const struct ggml_cgraph * cgraph, - int node_idx, - std::initializer_list ops, - std::initializer_list unary_ops) { -#ifndef NDEBUG - const size_t num_unary = std::count(ops.begin(), ops.end(), GGML_OP_UNARY); - GGML_ASSERT(unary_ops.size() == num_unary); -#endif - - const auto is_equal = [](const std::initializer_list & list1, - const std::initializer_list & list2) { - return std::equal(list1.begin(), list1.end(), list2.begin(), list2.end()); - }; - - std::initializer_list mul_mat_bias_glu_ops = { GGML_OP_MUL_MAT, GGML_OP_ADD, GGML_OP_MUL_MAT, GGML_OP_ADD, GGML_OP_GLU }; - std::initializer_list mul_mat_id_bias_glu_ops = { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID, GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID, GGML_OP_GLU }; - - std::initializer_list mul_mat_id_glu_ops = { GGML_OP_MUL_MAT_ID, GGML_OP_MUL_MAT_ID, GGML_OP_GLU }; - std::initializer_list mul_mat_glu_ops = { GGML_OP_MUL_MAT, GGML_OP_MUL_MAT, GGML_OP_GLU }; - - if ((is_equal(mul_mat_bias_glu_ops, ops) || is_equal(mul_mat_id_bias_glu_ops, ops)) && - ggml_can_fuse_subgraph(cgraph, node_idx, ops, { node_idx + 4 })) { - const ggml_tensor * ffn_gate = cgraph->nodes[node_idx]; - const ggml_tensor * ffn_gate_bias = cgraph->nodes[node_idx + 1]; - const ggml_tensor * ffn_up = cgraph->nodes[node_idx + 2]; - const ggml_tensor * ffn_up_bias = cgraph->nodes[node_idx + 3]; - const ggml_tensor * glu = cgraph->nodes[node_idx + 4]; - - if (ggml_cuda_should_fuse_mul_mat(ffn_up, ffn_gate, glu, ffn_up_bias, ffn_gate_bias)) { - int out_nodes[] = { node_idx + 4 }; - return ggml_cuda_check_fusion_memory_ranges(cgraph, node_idx, (int)ops.size(), out_nodes, 1); - } - } - - if ((is_equal(mul_mat_id_glu_ops, ops) || is_equal(mul_mat_glu_ops, ops)) && - ggml_can_fuse_subgraph(cgraph, node_idx, ops, { node_idx + 2 })) { - const ggml_tensor * ffn_gate = cgraph->nodes[node_idx]; - const ggml_tensor * ffn_up = cgraph->nodes[node_idx + 1]; - const ggml_tensor * glu = cgraph->nodes[node_idx + 2]; - - if (ggml_cuda_should_fuse_mul_mat(ffn_up, ffn_gate, glu)) { - int out_nodes[] = { node_idx + 2 }; - return ggml_cuda_check_fusion_memory_ranges(cgraph, node_idx, (int)ops.size(), out_nodes, 1); - } - } - - std::initializer_list rms_norm_mul_rope_ops = { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE }; - std::initializer_list rms_norm_mul_rope_set_rows_ops = { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }; - - if (is_equal(rms_norm_mul_rope_set_rows_ops, ops) && ggml_can_fuse_subgraph(cgraph, node_idx, ops, { node_idx + 4 })) { - const ggml_tensor * rms_norm = cgraph->nodes[node_idx]; - const ggml_tensor * mul = cgraph->nodes[node_idx + 1]; - const ggml_tensor * rope = cgraph->nodes[node_idx + 2]; - const ggml_tensor * view = cgraph->nodes[node_idx + 3]; - const ggml_tensor * set_rows = cgraph->nodes[node_idx + 4]; - - if (ggml_check_edges(cgraph, node_idx, {{1, 0, 0}, {2, 0, 1}, {3, 0, 2}, {4, 0, 3}}) && - ggml_cuda_should_fuse_rms_norm_mul_rope(rms_norm, mul, rope) && - ggml_cuda_should_fuse_rope_set_rows(rope, view, set_rows)) { - int out_nodes[] = { node_idx + 4 }; - return ggml_cuda_check_fusion_memory_ranges(cgraph, node_idx, (int)ops.size(), out_nodes, 1); - } - } - - if (is_equal(rms_norm_mul_rope_ops, ops) && ggml_can_fuse(cgraph, node_idx, ops)) { - const ggml_tensor * rms_norm = cgraph->nodes[node_idx]; - const ggml_tensor * mul = cgraph->nodes[node_idx + 1]; - const ggml_tensor * rope = cgraph->nodes[node_idx + 2]; - - if (ggml_cuda_should_fuse_rms_norm_mul_rope(rms_norm, mul, rope)) { - int out_nodes[] = { node_idx + 2 }; - return ggml_cuda_check_fusion_memory_ranges(cgraph, node_idx, (int)ops.size(), out_nodes, 1); - } - return false; - } - - std::initializer_list rope_set_rows_ops = { GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }; - - if (is_equal(rope_set_rows_ops, ops) && ggml_can_fuse_subgraph(cgraph, node_idx, ops, { node_idx + 2 })) { - const ggml_tensor * rope = cgraph->nodes[node_idx]; - const ggml_tensor * view = cgraph->nodes[node_idx + 1]; - const ggml_tensor * set_rows = cgraph->nodes[node_idx + 2]; - - if (ggml_cuda_should_fuse_rope_set_rows(rope, view, set_rows)) { - int out_nodes[] = { node_idx + 2 }; - return ggml_cuda_check_fusion_memory_ranges(cgraph, node_idx, (int)ops.size(), out_nodes, 1); - } - } - - // scale_out*sigmoid(scale_in*post) as the hc_post weights (qwen4exp hc_combine) - std::initializer_list hc_post_gate_ops = { GGML_OP_SCALE, GGML_OP_UNARY, GGML_OP_SCALE, GGML_OP_DSV4_HC_POST }; - - if (is_equal(hc_post_gate_ops, ops) && ggml_can_fuse_subgraph(cgraph, node_idx, ops, { node_idx + 3 })) { - const ggml_tensor * scale_in = cgraph->nodes[node_idx]; - const ggml_tensor * sigmoid = cgraph->nodes[node_idx + 1]; - const ggml_tensor * scale_out = cgraph->nodes[node_idx + 2]; - - // the chain must feed hc_post->src[2]; a bias on either scale is not handled - if (ggml_check_edges(cgraph, node_idx, {{1, 0, 0}, {2, 0, 1}, {3, 2, 2}}) && - ggml_get_unary_op(sigmoid) == GGML_UNARY_OP_SIGMOID && - ggml_get_op_params_f32(scale_in, 1) == 0.0f && ggml_get_op_params_f32(scale_out, 1) == 0.0f && - scale_in->src[0]->type == GGML_TYPE_F32 && scale_out->type == GGML_TYPE_F32 && - ggml_are_same_shape(scale_in->src[0], scale_out)) { - int out_nodes[] = { node_idx + 3 }; - return ggml_cuda_check_fusion_memory_ranges(cgraph, node_idx, (int)ops.size(), out_nodes, 1); - } - return false; - } - - if (!ggml_can_fuse(cgraph, node_idx, ops)) { - return false; - } - - if ((ops.size() == 2 || ops.size() == 3) && ops.begin()[0] == GGML_OP_NORM && ops.begin()[1] == GGML_OP_MUL) { - const ggml_tensor * norm = cgraph->nodes[node_idx]; - const ggml_tensor * mul = cgraph->nodes[node_idx + 1]; - const ggml_tensor * weight = mul->src[0] == norm ? mul->src[1] : mul->src[0]; - if (norm->src[0]->type != GGML_TYPE_F32 || norm->type != GGML_TYPE_F32 || mul->type != GGML_TYPE_F32 || - weight->type != GGML_TYPE_F32 || !ggml_is_vector(weight) || weight->ne[0] != norm->ne[0] || - !ggml_is_contiguous(weight)) { - return false; - } - if (ops.size() == 3) { - const ggml_tensor * add = cgraph->nodes[node_idx + 2]; - const ggml_tensor * bias = add->src[0] == mul ? add->src[1] : add->src[0]; - if (ops.begin()[2] != GGML_OP_ADD || add->type != GGML_TYPE_F32 || bias->type != GGML_TYPE_F32 || - !ggml_is_vector(bias) || bias->ne[0] != norm->ne[0] || !ggml_is_contiguous(bias)) { - return false; - } - } - return true; - } - - if ((ops.size() == 2 || ops.size() == 3) && 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]; - const ggml_tensor *add = nullptr; - - if (ops.size() == 3 && ops.begin()[2] == GGML_OP_ADD) { - add = cgraph->nodes[node_idx+2]; - } - - // the mul operand is a norm weight, which model files store as F32; - // the add operand is an F32 bias or a residual with the type of x - const ggml_type type = rms_norm->type; - if ((type != GGML_TYPE_F32 && type != GGML_TYPE_BF16) || rms_norm->src[0]->type != type) { - return false; - } - - const ggml_tensor * mul_src = mul->src[0] == rms_norm ? mul->src[1] : mul->src[0]; - if (mul_src->type != GGML_TYPE_F32 || mul->type != type) { - return false; - } - - if (add) { - const ggml_tensor * add_src = add->src[0] == mul ? add->src[1] : add->src[0]; - if ((add_src->type != GGML_TYPE_F32 && add_src->type != type) || add->type != type) { - 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 kernel assumes contiguous rows - if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) { - return false; - } - - if (add && (!ggml_is_contiguous(add->src[0]) || !ggml_is_contiguous_rows(add->src[1]))) { - return false; - } - - return true; - } - - if (ops.size() == 2 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_SCALE) { - const ggml_tensor * rms_norm = cgraph->nodes[node_idx]; - const ggml_tensor * scale = cgraph->nodes[node_idx+1]; - - if (rms_norm->src[0]->type != GGML_TYPE_F32 || rms_norm->type != GGML_TYPE_F32) { - return false; - } - - float bias; - memcpy(&bias, (const float *) scale->op_params + 1, sizeof(float)); - - return bias == 0.0f && scale->type == GGML_TYPE_F32; - } - - if (ops.size() == 2 && ops.begin()[0] == GGML_OP_SSM_CONV && ops.begin()[1] == GGML_OP_UNARY - && unary_ops.size() == 1 && unary_ops.begin()[0] == GGML_UNARY_OP_SILU) { - const ggml_tensor * ssm_conv = cgraph->nodes[node_idx]; - const ggml_tensor * silu = cgraph->nodes[node_idx+1]; - if (ggml_get_unary_op(silu) != unary_ops.begin()[0]) { - return false; - } - - if (ssm_conv->type != GGML_TYPE_F32 || silu->type != GGML_TYPE_F32) { - return false; - } - - return true; - } - - if (ops.size() == 3 && ops.begin()[0] == GGML_OP_SSM_CONV && ops.begin()[1] == GGML_OP_ADD - && ops.begin()[2] == GGML_OP_UNARY && unary_ops.size() == 1 && unary_ops.begin()[0] == GGML_UNARY_OP_SILU) { - const ggml_tensor * ssm_conv = cgraph->nodes[node_idx]; - const ggml_tensor * add = cgraph->nodes[node_idx+1]; - const ggml_tensor * silu = cgraph->nodes[node_idx+2]; - if (ggml_get_unary_op(silu) != unary_ops.begin()[0]) { - return false; - } - - if (ssm_conv->type != GGML_TYPE_F32 || add->type != GGML_TYPE_F32 || silu->type != GGML_TYPE_F32) { - return false; - } - - // ADD must consume ssm_conv's output and broadcast a 1-D channel-wise bias. - const ggml_tensor * bias = (add->src[0] == ssm_conv) ? add->src[1] : add->src[0]; - if (bias->type != GGML_TYPE_F32 || !ggml_is_contiguous(bias)) { - return false; - } - if (ggml_nelements(bias) != ssm_conv->ne[0] || bias->ne[0] != ssm_conv->ne[0]) { - return false; - } - - return true; - } - - if (ops.size() == 2 && ops.begin()[0] == GGML_OP_UNARY && ops.begin()[1] == GGML_OP_MUL - && unary_ops.size() == 1 && (unary_ops.begin()[0] == GGML_UNARY_OP_SILU || unary_ops.begin()[0] == GGML_UNARY_OP_SIGMOID || unary_ops.begin()[0] == GGML_UNARY_OP_SOFTPLUS)) { - const ggml_tensor * unary = cgraph->nodes[node_idx]; - const ggml_tensor * mul = cgraph->nodes[node_idx+1]; - - if (ggml_get_unary_op(unary) != unary_ops.begin()[0]) { - return false; - } - - if (unary->type != GGML_TYPE_F32 && unary->type != GGML_TYPE_F16 && unary->type != GGML_TYPE_BF16) { - return false; - } - - if (unary->type != mul->type) { - return false; - } - - const ggml_tensor * other = (mul->src[0] == unary) ? mul->src[1] : mul->src[0]; - if (other->type != unary->type) { - return false; - } - if (!ggml_is_contiguous_1(other) || !ggml_is_contiguous_1(unary->src[0]) || !ggml_are_same_shape(other, unary)) { - return false; - } - - return true; - } - - if (ops.size() == 2 && ops.begin()[0] == GGML_OP_UNARY && ops.begin()[1] == GGML_OP_SQR - && unary_ops.size() == 1 && unary_ops.begin()[0] == GGML_UNARY_OP_RELU) { - const ggml_tensor * unary = cgraph->nodes[node_idx]; - const ggml_tensor * sqr = cgraph->nodes[node_idx+1]; - - if (ggml_get_unary_op(unary) != GGML_UNARY_OP_RELU) { - return false; - } - - if (unary->type != GGML_TYPE_F32 && unary->type != GGML_TYPE_F16) { - return false; - } - - if (unary->type != sqr->type) { - return false; - } - - if (!ggml_is_contiguous(unary->src[0])) { - return false; - } - - return true; - } - - if (ops.size() == 3 && ops.begin()[0] == GGML_OP_SCALE && ops.begin()[1] == GGML_OP_UNARY && ops.begin()[2] == GGML_OP_SCALE - && unary_ops.size() == 1 && unary_ops.begin()[0] == GGML_UNARY_OP_TANH) { - const ggml_tensor *scale = cgraph->nodes[node_idx]; - const ggml_tensor *tanh = cgraph->nodes[node_idx+1]; - const ggml_tensor *scale2 = cgraph->nodes[node_idx+2]; - - // the fused softcap kernel is F32 only - if (scale->src[0]->type != GGML_TYPE_F32 || scale->type != GGML_TYPE_F32) { - return false; - } - - // TODO: make the fused softcap kernel stride aware, it reads src and writes dst as dense - if (!ggml_is_contiguous(scale->src[0]) || !ggml_is_contiguous(scale2)) { - return false; - } - - if (ggml_get_unary_op(tanh) != GGML_UNARY_OP_TANH) { - return false; - } - - // Check for bias - if (ggml_get_op_params_f32(scale, 1) != 0.0f || ggml_get_op_params_f32(scale2, 1) != 0.0f) { - return false; - } - - return true; - } - - return false; -} - -// try and fuse nodes and return the number of nodes to skip -static int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) { - - if (ggml_cuda_fusion_disabled()) { - return 0; - } - - ggml_tensor * node = cgraph->nodes[i]; - - if (node->op == GGML_OP_MUL_MAT_ID && cuda_ctx->stream_context().concurrent_events.empty() && - ggml_cuda_match_shared_expert(cgraph, i, i + 3) && - ggml_cuda_should_fuse_mul_mat_vec_q(cgraph->nodes[i + 2]->src[1])) { - const int outputs[] = { i + 2, i + 5 }; - if (ggml_cuda_check_fusion_memory_ranges(cgraph, i, 6, outputs, 2)) { - ggml_tensor * routed = cgraph->nodes[i + 2]; - ggml_tensor * shared = cgraph->nodes[i + 5]; - const ggml_tensor * up = routed->src[1]; - ggml_cuda_mm_fusion_args_host fusion{}; - fusion.gate = routed->src[0]->src[0]; - fusion.glu_op = ggml_get_glu_op(routed); - fusion.glu_limit = ggml_get_op_params_f32(routed, 3); - fusion.shared_up = shared->src[1]->src[0]; - fusion.shared_gate = shared->src[0]->src[0]; - fusion.shared_dst = shared; - ggml_cuda_mul_mat_vec_q(*cuda_ctx, up->src[0], up->src[1], up->src[2], routed, &fusion); - return 5; - } - } - - if (node->op == GGML_OP_MUL) { - ggml_cuda_moe_weighted_reduction_match match; - if (ggml_cuda_match_moe_weighted_reduction(cgraph, i, match)) { - const int output_idx = i + match.node_count - 1; - if (ggml_cuda_check_fusion_memory_ranges(cgraph, i, match.node_count, &output_idx, 1)) { - ggml_cuda_op_moe_weighted_reduction( - *cuda_ctx, match.experts, match.expert_scale, match.weights, match.dst); - return match.node_count - 1; - } - } - } - - // gated_delta_net -> cpy: scatter recurrent-state snapshots into the cache - if (node->op == GGML_OP_GATED_DELTA_NET) { - ggml_cuda_gated_delta_net_fused_cache fused_state_cpy; - const int nodes_to_skip = ggml_cuda_try_gdn_cache_fusion(cgraph, i, fused_state_cpy); - if (nodes_to_skip > 0) { -#ifdef GGML_CUDA_DEBUG - GGML_LOG_INFO("%s: fused gated_delta_net snapshot copies for %s (skipped %d nodes)\n", - __func__, node->name, nodes_to_skip); -#endif - ggml_cuda_op_gated_delta_net_fused_cache(*cuda_ctx, node, fused_state_cpy); - return nodes_to_skip; - } - } - - // ssm_scan -> cpy: scatter recurrent-state snapshots into the cache - if (node->op == GGML_OP_SSM_SCAN) { - ggml_cuda_ssm_scan_fused_cache fused_state_cpy; - const int nodes_to_skip = ggml_cuda_try_ssm_scan_cache_fusion(cgraph, i, fused_state_cpy); - if (nodes_to_skip > 0) { -#ifdef GGML_CUDA_DEBUG - GGML_LOG_INFO("%s: fused ssm_scan snapshot copies for %s (skipped %d nodes)\n", - __func__, node->name, nodes_to_skip); -#endif - ggml_cuda_op_ssm_scan_fused_cache(*cuda_ctx, node, fused_state_cpy); - return nodes_to_skip; - } - } - - //topk-moe - if (cgraph->nodes[i]->op == GGML_OP_UNARY || cgraph->nodes[i]->op == GGML_OP_SOFT_MAX || - cgraph->nodes[i]->op == GGML_OP_ARGSORT) { - ggml_cuda_topk_moe_args args; - const bool can_fuse = ggml_cuda_topk_moe_fusion(cgraph, i, args); - std::vector ops; - ops.reserve(13); // max ops; avoids gcc -Wstringop-overflow false positive - - if (can_fuse) { - const ggml_tensor * logits = node->src[0]; - ggml_tensor * weights = nullptr; - ggml_tensor * ids = nullptr; - const ggml_tensor * bias = nullptr; - const ggml_tensor * clamp = nullptr; - const ggml_tensor * scale = nullptr; - - if (!args.delayed_softmax) { - int out_nodes[2]; // nodes which can't be elided - - if (args.sigmoid) { - ops.insert(ops.end(), { GGML_OP_UNARY }); - } else if (args.sqrt_softplus) { - ops.insert(ops.end(), { GGML_OP_UNARY, GGML_OP_SQRT }); - } else { - ops.insert(ops.end(), { GGML_OP_SOFT_MAX }); - } - ops.push_back(GGML_OP_RESHAPE); - if (args.prob_bias) { - ops.push_back(GGML_OP_ADD); - bias = cgraph->nodes[i + ops.size() - 1]->src[1]; - } - if (args.n_groups > 0) { - for (const auto & p : topk_moe_group_pattern) { - ops.push_back(p.op); - } - } - ops.insert(ops.end(), { GGML_OP_ARGSORT, GGML_OP_VIEW, GGML_OP_GET_ROWS }); - out_nodes[0] = i + ops.size() - 2; - ids = cgraph->nodes[out_nodes[0]]; - - if (args.norm) { - ops.insert(ops.end(), - { GGML_OP_RESHAPE, GGML_OP_SUM_ROWS, GGML_OP_CLAMP, GGML_OP_DIV, GGML_OP_RESHAPE }); - clamp = cgraph->nodes[i + ops.size() - 3]; - } - if (args.scale) { - ops.insert(ops.end(), { GGML_OP_SCALE }); - scale = cgraph->nodes[i + ops.size() - 1]; - } - - weights = cgraph->nodes[i + ops.size() - 1]; - out_nodes[1] = i + ops.size() - 1; - - if (ggml_can_fuse_subgraph(cgraph, i, ops.size(), ops.data(), out_nodes, 2) && - ggml_cuda_should_use_topk_moe(node, logits, weights, ids) && - ggml_cuda_check_fusion_memory_ranges(cgraph, i, ops.size(), out_nodes, 2, /*is_topk_moe=*/true)) { - ggml_cuda_op_topk_moe(*cuda_ctx, logits, weights, ids, clamp, scale, bias, args); - return ops.size() - 1; - } - } else if (!args.norm && !args.prob_bias) { - //special case gpt-oss, no norm, no bias. - ops.insert(ops.end(), { GGML_OP_ARGSORT, GGML_OP_VIEW, GGML_OP_GET_ROWS, GGML_OP_RESHAPE, - GGML_OP_SOFT_MAX, GGML_OP_RESHAPE }); - weights = cgraph->nodes[i + 5]; - ids = cgraph->nodes[i + 1]; - const ggml_tensor * softmax = cgraph->nodes[i + 4]; - - int out_nodes[2] = { i + 1, i + 5 }; - if (ggml_can_fuse_subgraph(cgraph, i, ops.size(), ops.data(), out_nodes, 2) && - ggml_cuda_should_use_topk_moe(softmax, logits, weights, ids) && - ggml_cuda_check_fusion_memory_ranges(cgraph, i, ops.size(), out_nodes, 2, /*is_topk_moe=*/true)) { - ggml_cuda_op_topk_moe(*cuda_ctx, logits, weights, ids, clamp, scale, bias, args); - return ops.size() - 1; - } - } - } - } - - //RoPE + view + set-rows - if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, {})) { - ggml_tensor * rope = cgraph->nodes[i]; - ggml_tensor * set_rows = cgraph->nodes[i + 2]; - - ggml_cuda_op_rope_fused(*cuda_ctx, rope, set_rows); - return 2; - } - - // Snake activation: y = x + sin(a*x)^2 * inv_b - // Naive 5-op decomposition emitted by frontends: mul -> sin -> sqr -> mul -> add - if (ggml_can_fuse_subgraph(cgraph, i, - { GGML_OP_MUL, GGML_OP_SIN, GGML_OP_SQR, GGML_OP_MUL, GGML_OP_ADD }, - { i + 4 })) { - const ggml_tensor * mul0 = cgraph->nodes[i]; - const ggml_tensor * sqr = cgraph->nodes[i + 2]; - const ggml_tensor * mul1 = cgraph->nodes[i + 3]; - ggml_tensor * add = cgraph->nodes[i + 4]; - - // x carries the full activation shape, a is the broadcast operand - const ggml_tensor * x = ggml_are_same_shape(mul0, mul0->src[0]) ? mul0->src[0] : mul0->src[1]; - const ggml_tensor * a = (x == mul0->src[0]) ? mul0->src[1] : mul0->src[0]; - - // mul1 reads sqr and inv_b in either operand order - const ggml_tensor * inv_b = (mul1->src[0] == sqr) ? mul1->src[1] : mul1->src[0]; - - // closure check: the trailing add must read the same x as the leading mul - const ggml_tensor * x_in_add = (add->src[0] == mul1) ? add->src[1] : add->src[0]; - - // Kernel iterates over total = T * C, so x and add must be 2D and - // a / inv_b must collapse to [1, C, 1, 1]. Higher dims are not handled. - const bool dim_ok = (x->ne[2] == 1 && x->ne[3] == 1) && - (add->ne[2] == 1 && add->ne[3] == 1) && - (a->ne[2] == 1 && a->ne[3] == 1); - const bool shape_ok = ggml_are_same_shape(a, inv_b) && a->ne[0] == 1 && a->ne[1] == x->ne[1]; - - // x is in the supported whitelist and every chain intermediate shares - // x's type. launch_snake reads a and inv_b as const float *, so they - // stay F32. - const ggml_tensor * sin1 = cgraph->nodes[i + 1]; - const bool types_ok = (x->type == GGML_TYPE_F32 || x->type == GGML_TYPE_F16 || x->type == GGML_TYPE_BF16) && - (a->type == GGML_TYPE_F32) && (inv_b->type == GGML_TYPE_F32) && - (mul0->type == x->type) && (sin1->type == x->type) && - (sqr->type == x->type) && (mul1->type == x->type) && - (add->type == x->type); - - // kernel reads x[idx] and a[c] / inv_b[c] linearly, so every operand is contiguous - const bool contig_ok = ggml_is_contiguous(x) && ggml_is_contiguous(add) && - ggml_is_contiguous(a) && ggml_is_contiguous(inv_b); - - if (types_ok && shape_ok && dim_ok && contig_ok && x_in_add == x) { - ggml_cuda_op_snake_fused(*cuda_ctx, x, a, inv_b, add); - return 4; - } - } - - // multi-(add or mul) - if (node->op == GGML_OP_ADD || node->op == GGML_OP_MUL) { - int n_fuse = 0; - ggml_op ops[8]; - std::fill(ops, ops + 8, node->op); - - for (; n_fuse <= 6; ++n_fuse) { - if (!ggml_can_fuse(cgraph, i + n_fuse, ops + n_fuse, 2)) { - break; - } - if (cgraph->nodes[i + n_fuse] != cgraph->nodes[i + n_fuse + 1]->src[0]) { - break; - } - if (!ggml_are_same_layout(cgraph->nodes[i + n_fuse]->src[1], cgraph->nodes[i + n_fuse + 1]->src[1])) { - break; - } - } - - n_fuse++; - - if (n_fuse > 1) { - ggml_tensor fused_node; - memcpy(&fused_node, node, sizeof(ggml_tensor)); - for (int j = 0; j < n_fuse - 1; ++j) { - fused_node.src[j + 2] = cgraph->nodes[i + j + 1]->src[1]; - } - fused_node.data = cgraph->nodes[i + n_fuse - 1]->data; - if (node->op == GGML_OP_ADD) { - ggml_cuda_op_fused_add(*cuda_ctx, &fused_node, n_fuse); - } else { - ggml_cuda_op_fused_mul(*cuda_ctx, &fused_node, n_fuse); - } - return n_fuse - 1; - } - } - - bool fused_mul_mat_vec = false; - int fused_node_count = 0; - - auto get_bias_tensor = [](const ggml_tensor * bias_node, const ggml_tensor * mul_node, ggml_op op_bias) -> const ggml_tensor * { - if (op_bias == GGML_OP_ADD) { - if (bias_node->src[0] == mul_node) { - return bias_node->src[1]; - } - if (bias_node->src[1] == mul_node) { - return bias_node->src[0]; - } - return nullptr; - } - GGML_ASSERT(op_bias == GGML_OP_ADD_ID); - GGML_ASSERT(bias_node->src[0] == mul_node); - return bias_node->src[1]; - }; - - // gate + glu + up, with optional scale/bias on both lanes. - for (ggml_op op : { GGML_OP_MUL_MAT, GGML_OP_MUL_MAT_ID }) { - const ggml_op bias_op = op == GGML_OP_MUL_MAT ? GGML_OP_ADD : GGML_OP_ADD_ID; - - if (op == GGML_OP_MUL_MAT) { - for (const bool with_bias : { false, true }) { - const int gate_idx = i; - const int gate_scale_idx = i + 1; - const int gate_bias_idx = with_bias ? i + 2 : -1; - const int up_idx = with_bias ? i + 3 : i + 2; - const int up_scale_idx = up_idx + 1; - const int up_bias_idx = with_bias ? up_idx + 2 : -1; - const int glu_idx = with_bias ? up_idx + 3 : up_idx + 2; - - const int out_nodes[] = { glu_idx }; - ggml_op ops[7]; - if (with_bias) { - ops[0] = op; - ops[1] = GGML_OP_MUL; - ops[2] = bias_op; - ops[3] = op; - ops[4] = GGML_OP_MUL; - ops[5] = bias_op; - ops[6] = GGML_OP_GLU; - } else { - ops[0] = op; - ops[1] = GGML_OP_MUL; - ops[2] = op; - ops[3] = GGML_OP_MUL; - ops[4] = GGML_OP_GLU; - } - const int n_ops = with_bias ? 7 : 5; - - if (!ggml_can_fuse_subgraph(cgraph, i, n_ops, ops, out_nodes, 1) || - !ggml_cuda_check_fusion_memory_ranges(cgraph, i, n_ops, out_nodes, 1)) { - continue; - } - - ggml_tensor * gate_n = cgraph->nodes[gate_idx]; - ggml_tensor * gate_scale_n = cgraph->nodes[gate_scale_idx]; - ggml_tensor * gate_out_n = with_bias ? cgraph->nodes[gate_bias_idx] : gate_scale_n; - ggml_tensor * up_n = cgraph->nodes[up_idx]; - ggml_tensor * up_scale_n = cgraph->nodes[up_scale_idx]; - ggml_tensor * up_out_n = with_bias ? cgraph->nodes[up_bias_idx] : up_scale_n; - const ggml_tensor * glu = cgraph->nodes[glu_idx]; - - if (!ggml_cuda_should_fuse_mul_mat(up_n, gate_n, glu, - with_bias ? up_out_n : nullptr, with_bias ? gate_out_n : nullptr, up_scale_n, gate_scale_n)) { - continue; - } - - const ggml_tensor * gate_scale = ggml_cuda_get_mul_mat_scale(gate_scale_n, gate_n); - const ggml_tensor * up_scale = ggml_cuda_get_mul_mat_scale(up_scale_n, up_n); - if (!gate_scale || !up_scale) { - continue; - } - - const ggml_tensor * up_bias = with_bias ? get_bias_tensor(up_out_n, up_scale_n, bias_op) : nullptr; - const ggml_tensor * gate_bias = with_bias ? get_bias_tensor(gate_out_n, gate_scale_n, bias_op) : nullptr; - if (with_bias && (!ggml_are_same_shape(gate_out_n->src[0], gate_out_n->src[1]) || - !ggml_are_same_shape(up_out_n->src[0], up_out_n->src[1]))) { - continue; - } - - const ggml_tensor * src0 = up_n->src[0]; - const ggml_tensor * src1 = up_n->src[1]; - const ggml_tensor * ids = up_n->src[2]; - - ggml_cuda_mm_fusion_args_host fusion_data{}; - fusion_data.gate = gate_n->src[0]; - fusion_data.x_bias = up_bias; - fusion_data.gate_bias = gate_bias; - fusion_data.x_scale = up_scale; - fusion_data.gate_scale = gate_scale; - fusion_data.glu_op = ggml_get_glu_op(glu); - fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3); - - if (ggml_cuda_should_fuse_mul_mat_vec_f(up_n, gate_n)) { - ggml_cuda_mul_mat_vec_f(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data); - fused_mul_mat_vec = true; - fused_node_count = n_ops; - break; - } - - if (ggml_cuda_should_fuse_mul_mat_vec_q(up_n)) { - ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data); - fused_mul_mat_vec = true; - fused_node_count = n_ops; - break; - } - - if (!with_bias && ggml_cuda_should_fuse_mul_mat_q(up_n, gate_n, glu, up_scale_n, gate_scale_n)) { - fusion_data.prec_src1 = ggml_prec_get_src(up_n, 1); - ggml_cuda_mul_mat_q(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data); - fused_mul_mat_vec = true; - fused_node_count = n_ops; - break; - } - } - - if (fused_mul_mat_vec) { - break; - } - } else { - for (const bool with_bias : { false, true }) { - const int gate_idx = i; - const int gate_scale_idx = i + 4; - const int gate_bias_idx = with_bias ? i + 5 : -1; - const int up_idx = with_bias ? i + 6 : i + 5; - const int up_scale_idx = up_idx + 4; - const int up_bias_idx = with_bias ? up_idx + 5 : -1; - const int glu_idx = with_bias ? up_idx + 6 : up_idx + 5; - - const int out_nodes[] = { glu_idx }; - ggml_op ops[13]; - if (with_bias) { - ops[0] = op; - ops[1] = GGML_OP_RESHAPE; - ops[2] = GGML_OP_REPEAT; - ops[3] = GGML_OP_GET_ROWS; - ops[4] = GGML_OP_MUL; - ops[5] = bias_op; - ops[6] = op; - ops[7] = GGML_OP_RESHAPE; - ops[8] = GGML_OP_REPEAT; - ops[9] = GGML_OP_GET_ROWS; - ops[10] = GGML_OP_MUL; - ops[11] = bias_op; - ops[12] = GGML_OP_GLU; - } else { - ops[0] = op; - ops[1] = GGML_OP_RESHAPE; - ops[2] = GGML_OP_REPEAT; - ops[3] = GGML_OP_GET_ROWS; - ops[4] = GGML_OP_MUL; - ops[5] = op; - ops[6] = GGML_OP_RESHAPE; - ops[7] = GGML_OP_REPEAT; - ops[8] = GGML_OP_GET_ROWS; - ops[9] = GGML_OP_MUL; - ops[10] = GGML_OP_GLU; - } - const int n_ops = with_bias ? 13 : 11; - - if (!ggml_can_fuse_subgraph(cgraph, i, n_ops, ops, out_nodes, 1) || - !ggml_cuda_check_fusion_memory_ranges(cgraph, i, n_ops, out_nodes, 1)) { - continue; - } - - ggml_tensor * gate_n = cgraph->nodes[gate_idx]; - ggml_tensor * gate_scale_n = cgraph->nodes[gate_scale_idx]; - ggml_tensor * gate_out_n = with_bias ? cgraph->nodes[gate_bias_idx] : gate_scale_n; - ggml_tensor * up_n = cgraph->nodes[up_idx]; - ggml_tensor * up_scale_n = cgraph->nodes[up_scale_idx]; - ggml_tensor * up_out_n = with_bias ? cgraph->nodes[up_bias_idx] : up_scale_n; - const ggml_tensor * glu = cgraph->nodes[glu_idx]; - - if (!ggml_cuda_should_fuse_mul_mat(up_n, gate_n, glu, - with_bias ? up_out_n : nullptr, with_bias ? gate_out_n : nullptr, up_scale_n, gate_scale_n)) { - continue; - } - - const ggml_tensor * gate_scale = ggml_cuda_get_mul_mat_id_scale(cgraph->nodes[gate_idx + 1], cgraph->nodes[gate_idx + 2], - cgraph->nodes[gate_idx + 3], gate_scale_n, gate_n); - const ggml_tensor * up_scale = ggml_cuda_get_mul_mat_id_scale(cgraph->nodes[up_idx + 1], cgraph->nodes[up_idx + 2], - cgraph->nodes[up_idx + 3], up_scale_n, up_n); - if (!gate_scale || !up_scale) { - continue; - } - - const ggml_tensor * up_bias = with_bias ? get_bias_tensor(up_out_n, up_scale_n, bias_op) : nullptr; - const ggml_tensor * gate_bias = with_bias ? get_bias_tensor(gate_out_n, gate_scale_n, bias_op) : nullptr; - - const ggml_tensor * src0 = up_n->src[0]; - const ggml_tensor * src1 = up_n->src[1]; - const ggml_tensor * ids = up_n->src[2]; - - ggml_cuda_mm_fusion_args_host fusion_data{}; - fusion_data.gate = gate_n->src[0]; - fusion_data.x_bias = up_bias; - fusion_data.gate_bias = gate_bias; - fusion_data.x_scale = up_scale; - fusion_data.gate_scale = gate_scale; - fusion_data.glu_op = ggml_get_glu_op(glu); - fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3); - - if (ggml_cuda_should_fuse_mul_mat_vec_f(up_n, gate_n)) { - ggml_cuda_mul_mat_vec_f(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data); - fused_mul_mat_vec = true; - fused_node_count = n_ops; - break; - } - - if (ggml_cuda_should_fuse_mul_mat_vec_q(up_n)) { - ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data); - fused_mul_mat_vec = true; - fused_node_count = n_ops; - break; - } - - if (!with_bias && ggml_cuda_should_fuse_mul_mat_q(up_n, gate_n, glu, up_scale_n, gate_scale_n)) { - fusion_data.prec_src1 = ggml_prec_get_src(up_n, 1); - ggml_cuda_mul_mat_q(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data); - fused_mul_mat_vec = true; - fused_node_count = n_ops; - break; - } - } - - if (fused_mul_mat_vec) { - break; - } - } - - if (ggml_cuda_can_fuse(cgraph, i, { op, bias_op, op, bias_op, GGML_OP_GLU }, {})) { - ggml_tensor * glu = cgraph->nodes[i + 4]; - ggml_tensor * gate_bias_n = glu->src[0]; - ggml_tensor * up_bias_n = glu->src[1]; - - //we don't assume the order for {gate, up}. Instead infer it from the bias tensor - ggml_tensor * gate_n = nullptr; - ggml_tensor * up_n = nullptr; - - if (gate_bias_n->src[0] == cgraph->nodes[i] || gate_bias_n->src[1] == cgraph->nodes[i]) { - gate_n = cgraph->nodes[i]; - up_n = cgraph->nodes[i + 2]; - } else if (gate_bias_n->src[0] == cgraph->nodes[i + 2] || gate_bias_n->src[1] == cgraph->nodes[i + 2]) { - gate_n = cgraph->nodes[i + 2]; - up_n = cgraph->nodes[i]; - } else { - continue; - } - - const ggml_tensor * up_bias_tensor = get_bias_tensor(up_bias_n, up_n, bias_op); - const ggml_tensor * gate_bias_tensor = get_bias_tensor(gate_bias_n, gate_n, bias_op); - - if (!up_bias_tensor || !gate_bias_tensor) { - continue; - } - - // we don't support repeating adds - if (bias_op == GGML_OP_ADD && (!ggml_are_same_shape(gate_bias_n->src[0], gate_bias_n->src[1]) || - !ggml_are_same_shape(up_bias_n->src[0], up_bias_n->src[1]))) { - continue; - } - - const ggml_tensor * src0 = up_n->src[0]; - const ggml_tensor * src1 = up_n->src[1]; - const ggml_tensor * ids = up_n->src[2]; - - if (ggml_cuda_should_fuse_mul_mat_vec_f(up_n, gate_n)) { - ggml_cuda_mm_fusion_args_host fusion_data{}; - fusion_data.gate = gate_n->src[0]; - fusion_data.x_bias = up_bias_tensor; - fusion_data.gate_bias = gate_bias_tensor; - fusion_data.glu_op = ggml_get_glu_op(glu); - fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3); - - ggml_cuda_mul_mat_vec_f(*cuda_ctx, src0, src1, ids, glu, &fusion_data); - fused_mul_mat_vec = true; - fused_node_count = 5; - break; - } - - if (ggml_cuda_should_fuse_mul_mat_vec_q(up_n)) { - ggml_cuda_mm_fusion_args_host fusion_data{}; - fusion_data.gate = gate_n->src[0]; - fusion_data.x_bias = up_bias_tensor; - fusion_data.gate_bias = gate_bias_tensor; - fusion_data.glu_op = ggml_get_glu_op(glu); - fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3); - - ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, glu, &fusion_data); - fused_mul_mat_vec = true; - fused_node_count = 5; - break; - } - } else if (ggml_cuda_can_fuse(cgraph, i, { op, op, GGML_OP_GLU }, {})) { - ggml_tensor * glu = cgraph->nodes[i + 2]; - ggml_tensor * gate = glu->src[0]; - ggml_tensor * up = glu->src[1]; - - bool ok = (gate == cgraph->nodes[i] && up == cgraph->nodes[i + 1]) || - (gate == cgraph->nodes[i + 1] && up == cgraph->nodes[i]); - - if (!ok) { - continue; - } - - const ggml_tensor * src0 = up->src[0]; - const ggml_tensor * src1 = up->src[1]; - const ggml_tensor * ids = up->src[2]; - - if (ggml_cuda_should_fuse_mul_mat_vec_f(up, gate)) { - ggml_cuda_mm_fusion_args_host fusion_data{}; - fusion_data.gate = gate->src[0]; - fusion_data.glu_op = ggml_get_glu_op(glu); - fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3); - - ggml_cuda_mul_mat_vec_f(*cuda_ctx, src0, src1, ids, glu, &fusion_data); - fused_mul_mat_vec = true; - fused_node_count = 3; - break; - } - - if (ggml_cuda_should_fuse_mul_mat_vec_q(up)) { - ggml_cuda_mm_fusion_args_host fusion_data{}; - fusion_data.gate = gate->src[0]; - fusion_data.glu_op = ggml_get_glu_op(glu); - fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3); - - ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, glu, &fusion_data); - fused_mul_mat_vec = true; - fused_node_count = 3; - break; - } - - if (ggml_cuda_should_fuse_mul_mat_q(up, gate, glu)) { - ggml_cuda_mm_fusion_args_host fusion_data{}; - fusion_data.gate = gate->src[0]; - fusion_data.glu_op = ggml_get_glu_op(glu); - fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3); - fusion_data.prec_src1 = ggml_prec_get_src(up, 1); - - ggml_cuda_mul_mat_q(*cuda_ctx, src0, src1, ids, glu, &fusion_data); - fused_mul_mat_vec = true; - fused_node_count = 3; - break; - } - } - } - - if (fused_mul_mat_vec) { - return fused_node_count - 1; - } - - fused_mul_mat_vec = false; - fused_node_count = 0; - - // mul_mat + scale + optional bias - for (ggml_op op : { GGML_OP_MUL_MAT, GGML_OP_MUL_MAT_ID }) { - const ggml_op bias_op = op == GGML_OP_MUL_MAT ? GGML_OP_ADD : GGML_OP_ADD_ID; - - for (const bool with_bias : { false, true }) { - const int n_ops = op == GGML_OP_MUL_MAT ? (with_bias ? 3 : 2) : (with_bias ? 6 : 5); - const int out_nodes[] = { i + n_ops - 1 }; - ggml_op ops[6]; - if (op == GGML_OP_MUL_MAT) { - if (with_bias) { - ops[0] = op; - ops[1] = GGML_OP_MUL; - ops[2] = bias_op; - } else { - ops[0] = op; - ops[1] = GGML_OP_MUL; - } - } else { - if (with_bias) { - ops[0] = op; - ops[1] = GGML_OP_RESHAPE; - ops[2] = GGML_OP_REPEAT; - ops[3] = GGML_OP_GET_ROWS; - ops[4] = GGML_OP_MUL; - ops[5] = bias_op; - } else { - ops[0] = op; - ops[1] = GGML_OP_RESHAPE; - ops[2] = GGML_OP_REPEAT; - ops[3] = GGML_OP_GET_ROWS; - ops[4] = GGML_OP_MUL; - } - } +} - if (!ggml_can_fuse_subgraph(cgraph, i, n_ops, ops, out_nodes, 1) || - !ggml_cuda_check_fusion_memory_ranges(cgraph, i, n_ops, out_nodes, 1)) { - continue; - } +static void ggml_backend_cuda_synchronize(ggml_backend_t backend) { + ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *)backend->context; - ggml_tensor * mm_node = cgraph->nodes[i]; - ggml_tensor * scale_node = op == GGML_OP_MUL_MAT ? cgraph->nodes[i + 1] : cgraph->nodes[i + 4]; - ggml_tensor * out_node = with_bias ? cgraph->nodes[i + n_ops - 1] : scale_node; + CUDA_CHECK(cudaStreamSynchronize(cuda_ctx->stream())); - const ggml_tensor * scale = nullptr; - if (op == GGML_OP_MUL_MAT) { - scale = ggml_cuda_get_mul_mat_scale(scale_node, mm_node); - } else { - scale = ggml_cuda_get_mul_mat_id_scale(cgraph->nodes[i + 1], cgraph->nodes[i + 2], cgraph->nodes[i + 3], scale_node, mm_node); - } - if (!scale) { - continue; - } + GGML_UNUSED(backend); +} - const ggml_tensor * bias = with_bias ? get_bias_tensor(out_node, scale_node, bias_op) : nullptr; - if (with_bias && !bias) { - continue; - } - if (with_bias && bias_op == GGML_OP_ADD && !ggml_are_same_shape(out_node->src[0], out_node->src[1])) { - continue; - } - if (with_bias && bias_op == GGML_OP_ADD_ID && out_node->src[2] != mm_node->src[2]) { - continue; - } +#ifdef USE_CUDA_GRAPH +static bool ggml_cuda_graph_debug_enabled() { + static const bool enabled = ggml_cuda_env_flag("GGML_CUDA_GRAPH_DEBUG"); + return enabled; +} - const ggml_tensor * src0 = mm_node->src[0]; - const ggml_tensor * src1 = mm_node->src[1]; - const ggml_tensor * ids = mm_node->src[2]; +static bool ggml_cuda_graph_check_compability(ggml_cgraph * cgraph) { - ggml_cuda_mm_fusion_args_host fusion_data{}; - fusion_data.x_bias = bias; - fusion_data.x_scale = scale; + bool use_cuda_graph = true; + // Loop over nodes in GGML graph to obtain info needed for CUDA graph - if (ggml_cuda_should_fuse_mul_mat_vec_f(mm_node)) { - ggml_cuda_mul_mat_vec_f(*cuda_ctx, src0, src1, ids, out_node, &fusion_data); - fused_mul_mat_vec = true; - fused_node_count = n_ops; - break; - } + for (int i = 0; i < cgraph->n_nodes; i++) { + ggml_tensor * node = cgraph->nodes[i]; - if (op == GGML_OP_MUL_MAT && !with_bias && src0->type == GGML_TYPE_F8_E4M3 && - ggml_get_op_params_i32(mm_node, 3) != GGML_PREC_F32 && - ggml_cuda_mul_mat_fp8(*cuda_ctx, src0, src1, scale_node, scale)) { - return 1; - } + if (ggml_cuda_is_view_or_noop(node)) { + continue; + } - if (!with_bias && src0->type == GGML_TYPE_NVFP4 && src1->type == GGML_TYPE_F32 && mm_node->type == GGML_TYPE_F32) { - const int cc = ggml_cuda_info().devices[cuda_ctx->device].cc; - const bool is_id = op == GGML_OP_MUL_MAT_ID; - const int64_t ncols = is_id ? src1->ne[2] : src1->ne[1]; - const bool use_mmvq = is_id ? ncols <= get_mmvq_mmid_max_batch(src0->type, cc) : - ggml_cuda_should_use_mmvq(src0->type, cc, ncols); - const bool bad_padding_clear = ggml_backend_buffer_get_usage(src0->buffer) == GGML_BACKEND_BUFFER_USAGE_COMPUTE && - ggml_nbytes(src0) != ggml_backend_buffer_get_alloc_size(src0->buffer, src0) && - src0->view_src; - if (!use_mmvq && !bad_padding_clear && - ggml_cuda_should_use_mmq(src0->type, cc, ncols, /*n_experts =*/ is_id ? src0->ne[2] : 0)) { - fusion_data.prec_src1 = ggml_prec_get_src(mm_node, 1); - ggml_cuda_mul_mat_q(*cuda_ctx, src0, src1, ids, out_node, &fusion_data); - return n_ops - 1; + // [TAG_MUL_MAT_ID_CUDA_GRAPHS] + if (node->op == GGML_OP_MUL_MAT_ID) { + const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc; + if (ggml_cuda_mul_mat_id_needs_sync(node, cc)) { + // the mul_mat_id fallback path synchronizes the stream, so we cannot use CUDA graphs + // ref: https://github.com/ggml-org/llama.cpp/pull/18958 + use_cuda_graph = false; + if (ggml_cuda_graph_debug_enabled()) { + GGML_LOG_DEBUG("%s: disabling CUDA graphs due to unsupported node type\n", __func__); } } - - if (ggml_cuda_should_fuse_mul_mat_vec_q(mm_node)) { - ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, out_node, &fusion_data); - fused_mul_mat_vec = true; - fused_node_count = n_ops; - break; - } } - if (fused_mul_mat_vec) { + + if (!use_cuda_graph) { break; } } - if (fused_mul_mat_vec) { - return fused_node_count - 1; - } + return use_cuda_graph; +} - // mul_mat + add - for (ggml_op op : { GGML_OP_MUL_MAT, GGML_OP_MUL_MAT_ID }) { - const ggml_op bias_op = op == GGML_OP_MUL_MAT ? GGML_OP_ADD : GGML_OP_ADD_ID; +static const void * ggml_cuda_graph_get_key(ggml_cgraph * cgraph) { + return cgraph->nodes[0]; +} - if (!ggml_can_fuse(cgraph, i, { op, bias_op })) { - continue; - } +static bool ggml_cuda_graph_update_required(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph) { + bool res = false; - ggml_tensor * mm_node = cgraph->nodes[i]; - ggml_tensor * bias_node = cgraph->nodes[i + 1]; + const void * graph_key = ggml_cuda_graph_get_key(cgraph); + ggml_cuda_graph * graph = cuda_ctx->cuda_graph(graph_key); - ggml_tensor * bias_tensor = nullptr; - if (bias_op == GGML_OP_ADD) { - if (bias_node->src[0] == mm_node) { - bias_tensor = bias_node->src[1]; - } else if (bias_node->src[1] == mm_node) { - bias_tensor = bias_node->src[0]; - } else { - continue; - } - } else { - if (bias_node->src[0] != mm_node) { - continue; - } - bias_tensor = bias_node->src[1]; + if (cgraph->uid != 0 && + cgraph->uid == graph->uid) { + if (ggml_cuda_graph_debug_enabled()) { + GGML_LOG_DEBUG("CUDA Graph id %zu reused\n", cgraph->uid); } + GGML_ASSERT((int)graph->node_props.size() == cgraph->n_nodes); + return false; + } - const ggml_tensor * src0 = mm_node->src[0]; - const ggml_tensor * src1 = mm_node->src[1]; - const ggml_tensor * ids = mm_node->src[2]; - - if (bias_op == GGML_OP_ADD_ID && bias_node->src[2] != ids) { - continue; - } + graph->uid = cgraph->uid; - if (bias_op == GGML_OP_ADD && !ggml_are_same_shape(bias_node->src[0], bias_node->src[1])) { - continue; - } + // Check if the graph size has changed + if ((int)graph->node_props.size() != cgraph->n_nodes) { + res = true; + graph->node_props.resize(cgraph->n_nodes); + } - ggml_cuda_mm_fusion_args_host fusion_data{}; - fusion_data.x_bias = bias_tensor; + for (int i = 0; i < cgraph->n_nodes; i++) { + ggml_cuda_graph::node_properties prop = {}; + memcpy(&prop.node, cgraph->nodes[i], sizeof(ggml_tensor)); - if (ggml_cuda_should_fuse_mul_mat_vec_f(mm_node)) { - ggml_cuda_mul_mat_vec_f(*cuda_ctx, src0, src1, ids, bias_node, &fusion_data); - fused_mul_mat_vec = true; - fused_node_count = 2; - break; + for (int j = 0; j < GGML_MAX_SRC; ++j) { + if (cgraph->nodes[i]->src[j]) { + prop.node_src_data_ptrs[j] = cgraph->nodes[i]->src[j]->data; + memcpy(prop.node_src_ne[j], cgraph->nodes[i]->src[j]->ne, sizeof(prop.node_src_ne[j])); + memcpy(prop.node_src_nb[j], cgraph->nodes[i]->src[j]->nb, sizeof(prop.node_src_nb[j])); + } } - if (ggml_cuda_should_fuse_mul_mat_vec_q(mm_node)) { - ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, bias_node, &fusion_data); - fused_mul_mat_vec = true; - fused_node_count = 2; - break; + if (res || memcmp(&graph->node_props[i], &prop, sizeof(prop)) != 0) { + graph->node_props[i] = prop; + res = true; } } - if (fused_mul_mat_vec) { - return fused_node_count - 1; - } - - if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE, GGML_OP_VIEW, GGML_OP_SET_ROWS }, {})) { - ggml_cuda_op_rms_norm_mul_rope_fused(*cuda_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2], cgraph->nodes[i + 4]); - return 4; - } - - if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ROPE }, {})) { - ggml_cuda_op_rms_norm_mul_rope_fused(*cuda_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2], nullptr); - return 2; - } - - if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_NORM, GGML_OP_MUL, GGML_OP_ADD }, {})) { - ggml_cuda_op_norm(*cuda_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2]); - return 2; - } - - if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_NORM, GGML_OP_MUL }, {})) { - ggml_cuda_op_norm(*cuda_ctx, node, cgraph->nodes[i + 1]); - return 1; - } + return res; +} - if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ADD }, {})) { - ggml_cuda_op_rms_norm_fused_add(*cuda_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2]); - return 2; +#ifdef USE_CUDA_GRAPH_CLUSTER_CHECK +static std::vector ggml_cuda_graph_get_clusters(cudaGraph_t cuda_graph, int device) { + std::vector clusters; + static const bool runtime_affected = [] { + int version = 0; + CUDA_CHECK(cudaRuntimeGetVersion(&version)); + // TODO: upper bound once fixed in the CUDA runtime + return version >= 11080; + }(); + if (!runtime_affected || ggml_cuda_info().devices[device].cc < GGML_CUDA_CC_HOPPER) { + return clusters; } - - if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL }, {})) { - ggml_cuda_op_rms_norm_fused(*cuda_ctx, node, cgraph->nodes[i + 1]); - return 1; + size_t n_nodes = 0; + CUDA_CHECK(cudaGraphGetNodes(cuda_graph, nullptr, &n_nodes)); + std::vector nodes(n_nodes); + CUDA_CHECK(cudaGraphGetNodes(cuda_graph, nodes.data(), &n_nodes)); + for (size_t i = 0; i < n_nodes; ++i) { + cudaGraphNodeType type; + CUDA_CHECK(cudaGraphNodeGetType(nodes[i], &type)); + if (type != cudaGraphNodeTypeKernel) { + continue; + } + cudaLaunchAttributeValue val = {}; + CUDA_CHECK(cudaGraphKernelNodeGetAttribute(nodes[i], cudaLaunchAttributeClusterDimension, &val)); + if (val.clusterDim.x * val.clusterDim.y * val.clusterDim.z > 1) { + clusters.push_back({ i, val.clusterDim.x, val.clusterDim.y, val.clusterDim.z }); + } } + return clusters; +} +#endif // USE_CUDA_GRAPH_CLUSTER_CHECK - if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_SCALE }, {})) { - ggml_cuda_op_rms_norm_scale_fused(*cuda_ctx, node, cgraph->nodes[i + 1]); - return 1; +static void ggml_cuda_graph_update_executable(ggml_cuda_graph_instance & instance, cudaGraph_t cuda_graph, int device) { +#ifdef USE_CUDA_GRAPH_CLUSTER_CHECK + std::vector clusters = ggml_cuda_graph_get_clusters(cuda_graph, device); + if (instance.clusters != clusters) { + if (ggml_cuda_graph_debug_enabled()) { + GGML_LOG_DEBUG("%s: cluster dims changed, re-instantiating CUDA graph\n", __func__); + } + CUDA_CHECK(cudaGraphExecDestroy(instance)); + CUDA_CHECK(cudaGraphInstantiate(&instance.handle, cuda_graph, nullptr, nullptr, 0)); + instance.clusters = std::move(clusters); + return; } +#else + GGML_UNUSED(device); +#endif // USE_CUDA_GRAPH_CLUSTER_CHECK - if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_SSM_CONV, GGML_OP_ADD, GGML_OP_UNARY }, { GGML_UNARY_OP_SILU })) { - ggml_cuda_op_ssm_conv(*cuda_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2]); - return 2; - } +#if CUDART_VERSION >= 12000 + cudaGraphExecUpdateResultInfo result_info; + cudaError_t stat = cudaGraphExecUpdate(instance, cuda_graph, &result_info); +#else + cudaGraphNode_t errorNode; + cudaGraphExecUpdateResult result_info; + cudaError_t stat = cudaGraphExecUpdate(instance, cuda_graph, &errorNode, &result_info); +#endif // CUDART_VERSION >= 12000 - if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_SSM_CONV, GGML_OP_UNARY }, { GGML_UNARY_OP_SILU })) { - ggml_cuda_op_ssm_conv(*cuda_ctx, node, /*bias_add_node=*/ nullptr, cgraph->nodes[i + 1]); - return 1; - } + if (stat == cudaErrorGraphExecUpdateFailure) { + if (ggml_cuda_graph_debug_enabled()) { + GGML_LOG_DEBUG("%s: CUDA graph update failed\n", __func__); + } - if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_UNARY, GGML_OP_MUL }, { GGML_UNARY_OP_SILU }) || - ggml_cuda_can_fuse(cgraph, i, { GGML_OP_UNARY, GGML_OP_MUL }, { GGML_UNARY_OP_SIGMOID }) || - ggml_cuda_can_fuse(cgraph, i, { GGML_OP_UNARY, GGML_OP_MUL }, { GGML_UNARY_OP_SOFTPLUS })) { - ggml_cuda_op_unary_mul(*cuda_ctx, node, cgraph->nodes[i + 1]); - return 1; + // The pre-existing graph exec cannot be updated due to violated constraints + // so instead clear error and re-instantiate + (void)cudaGetLastError(); + CUDA_CHECK(cudaGraphExecDestroy(instance)); + instance.handle = nullptr; + CUDA_CHECK(cudaGraphInstantiate(&instance.handle, cuda_graph, nullptr, nullptr, 0)); + } else { + GGML_ASSERT(stat == cudaSuccess); } +} - if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_UNARY, GGML_OP_SQR }, { GGML_UNARY_OP_RELU })) { - ggml_cuda_op_relu_sqr(*cuda_ctx, node, cgraph->nodes[i + 1]); - return 1; - } +// number of ggml nodes per CUDA graph chunk, 0 captures the whole ggml graph as one CUDA graph +static int ggml_cuda_graph_chunk_size() { + static const int chunk_size = [] { + const char * env = getenv("GGML_CUDA_GRAPH_CHUNK_SIZE"); + return env != nullptr ? atoi(env) : 512; + }(); + return chunk_size; +} - if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_SCALE, GGML_OP_UNARY, GGML_OP_SCALE, GGML_OP_DSV4_HC_POST }, { GGML_UNARY_OP_SIGMOID })) { - ggml_cuda_op_dsv4_hc_post(*cuda_ctx, cgraph->nodes[i + 3], node, cgraph->nodes[i + 2]); - return 3; - } +// end the capture of chunk `idx`, update or create its executable and launch it +static void ggml_cuda_graph_launch_chunk(ggml_backend_cuda_context * cuda_ctx, ggml_cuda_graph * graph, size_t idx) { + cudaGraph_t cuda_graph = nullptr; + CUDA_CHECK(cudaStreamEndCapture(cuda_ctx->stream(), &cuda_graph)); - if (ggml_cuda_can_fuse(cgraph, i, { GGML_OP_SCALE, GGML_OP_UNARY, GGML_OP_SCALE }, { GGML_UNARY_OP_TANH })) { - ggml_cuda_op_softcap(*cuda_ctx, cgraph->nodes[i + 2], node); - return 2; + if (idx < graph->instances.size()) { + ggml_cuda_graph_update_executable(graph->instances[idx], cuda_graph, cuda_ctx->device); + } else { + GGML_ASSERT(idx == graph->instances.size()); + graph->instances.emplace_back(); + CUDA_CHECK(cudaGraphInstantiate(&graph->instances[idx].handle, cuda_graph, nullptr, nullptr, 0)); +#ifdef USE_CUDA_GRAPH_CLUSTER_CHECK + graph->instances[idx].clusters = ggml_cuda_graph_get_clusters(cuda_graph, cuda_ctx->device); +#endif // USE_CUDA_GRAPH_CLUSTER_CHECK } + CUDA_CHECK(cudaGraphDestroy(cuda_graph)); - return 0; + CUDA_CHECK(cudaGraphLaunch(graph->instances[idx], cuda_ctx->stream())); } +#endif // USE_CUDA_GRAPH static void ggml_cuda_graph_evaluate_and_capture(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, const bool use_cuda_graph, const bool cuda_graph_update_required, const void * graph_key) { bool graph_evaluated_or_captured = false; @@ -5524,7 +3315,7 @@ static void ggml_cuda_graph_evaluate_and_capture(ggml_backend_cuda_context * cud continue; } - int nodes_to_skip = ggml_cuda_try_fuse(cuda_ctx, cgraph, i); + int nodes_to_skip = ggml_cuda_fusion_disabled() ? 0 : ggml_cuda_try_fuse(cuda_ctx, cgraph, i); if (nodes_to_skip != 0) { #ifdef GGML_CUDA_DEBUG @@ -5707,154 +3498,10 @@ static void ggml_backend_cuda_event_wait(ggml_backend_t backend, ggml_backend_ev static void ggml_backend_cuda_graph_optimize(ggml_backend_t backend, ggml_cgraph * cgraph, ggml_backend_graph_optimize_params * params) { ggml_backend_cuda_context * cuda_ctx = (ggml_backend_cuda_context *) backend->context; - const bool disable_fusion = ggml_cuda_fusion_disabled(); - - auto add_alloc_deps = [&](size_t start, size_t last_node) { - - for (size_t i = start; i < last_node; ++i) { - params->add_alloc_dep(params->user_data, cgraph->nodes[i], cgraph->nodes[last_node]); - - for (int j = 0; j < GGML_MAX_SRC; ++j) { - if (cgraph->nodes[i]->src[j]) { - params->add_alloc_dep(params->user_data, cgraph->nodes[i]->src[j], cgraph->nodes[last_node]); - } - } - } - }; - - if (!disable_fusion) { + if (!ggml_cuda_fusion_disabled()) { // add alloc deps for performance positive fusions. This may increase the overall compute buffer size. // TODO: consolidate fusion paths in graph_optimize and graph_compute - ggml_cuda_set_device(cuda_ctx->device); - for (int i = 0; i + 5 < cgraph->n_nodes; ++i) { - if (cgraph->nodes[i]->op != GGML_OP_MUL_MAT_ID) { - continue; - } - for (int j = i + 3; j + 2 < cgraph->n_nodes; ++j) { - if (cgraph->nodes[j]->op == GGML_OP_MUL_MAT_ID && cgraph->nodes[j + 1]->op == GGML_OP_MUL_MAT_ID) { - break; - } - if (cgraph->nodes[j]->op != GGML_OP_MUL_MAT || !ggml_cuda_match_shared_expert(cgraph, i, j)) { - continue; - } - // Group both outputs before allocation so the shared result cannot alias intervening nodes. - std::rotate(cgraph->nodes + i + 3, cgraph->nodes + j, cgraph->nodes + j + 3); - ggml_tensor * up = cgraph->nodes[i + 2]->src[1]; - params->add_alloc_dep(params->user_data, up->src[1], cgraph->nodes[i + 5]); - params->add_alloc_dep(params->user_data, up->src[2], cgraph->nodes[i + 5]); - i += 5; - break; - } - } - for (int i = 0; i < cgraph->n_nodes; ++i) { - // Keep the inputs of the fused gate/up/GLU MMQ kernel alive until the GLU so that they cannot alias its output (under op offload the weights are buffer copies). - if (i + 2 < cgraph->n_nodes && cgraph->nodes[i + 2]->op == GGML_OP_GLU) { - ggml_tensor * glu = cgraph->nodes[i + 2]; - ggml_tensor * gate = glu->src[0]; - ggml_tensor * up = glu->src[1]; - const bool ok = (gate == cgraph->nodes[i] && up == cgraph->nodes[i + 1]) || (gate == cgraph->nodes[i + 1] && up == cgraph->nodes[i]); - if (ok && ggml_cuda_mul_mat_q_fusion_matches(up, gate, glu, cuda_ctx->device)) { - add_alloc_deps(i, i + 2); - i += 2; - continue; - } - } - // Same with the NVFP4 scales: MUL_MAT(gate), MUL(gate scale), MUL_MAT(up), MUL(up scale), GLU. - if (i + 4 < cgraph->n_nodes && cgraph->nodes[i + 4]->op == GGML_OP_GLU) { - ggml_tensor * glu = cgraph->nodes[i + 4]; - ggml_tensor * gate_scale = cgraph->nodes[i + 1]; - ggml_tensor * up_scale = cgraph->nodes[i + 3]; - if (glu->src[0] == gate_scale && glu->src[1] == up_scale && - ggml_cuda_mul_mat_q_fusion_matches(cgraph->nodes[i + 2], cgraph->nodes[i], glu, cuda_ctx->device, up_scale, gate_scale) && - ggml_cuda_get_mul_mat_scale(gate_scale, cgraph->nodes[i]) && ggml_cuda_get_mul_mat_scale(up_scale, cgraph->nodes[i + 2])) { - add_alloc_deps(i, i + 4); - i += 4; - continue; - } - } - // Same with per-expert NVFP4 scales: MUL_MAT_ID, RESHAPE, REPEAT, GET_ROWS, MUL for gate and for up, GLU. - if (i + 10 < cgraph->n_nodes && cgraph->nodes[i + 10]->op == GGML_OP_GLU) { - ggml_tensor * glu = cgraph->nodes[i + 10]; - ggml_tensor * gate_scale = cgraph->nodes[i + 4]; - ggml_tensor * up_scale = cgraph->nodes[i + 9]; - if (glu->src[0] == gate_scale && glu->src[1] == up_scale && - ggml_cuda_mul_mat_q_fusion_matches(cgraph->nodes[i + 5], cgraph->nodes[i], glu, cuda_ctx->device, up_scale, gate_scale) && - ggml_cuda_get_mul_mat_id_scale(cgraph->nodes[i + 1], cgraph->nodes[i + 2], cgraph->nodes[i + 3], gate_scale, cgraph->nodes[i]) && - ggml_cuda_get_mul_mat_id_scale(cgraph->nodes[i + 6], cgraph->nodes[i + 7], cgraph->nodes[i + 8], up_scale, cgraph->nodes[i + 5])) { - add_alloc_deps(i, i + 10); - i += 10; - continue; - } - } - - ggml_cuda_moe_weighted_reduction_match match; - if (ggml_cuda_match_moe_weighted_reduction(cgraph, i, match)) { - params->add_alloc_dep(params->user_data, const_cast(match.experts), match.dst); - params->add_alloc_dep(params->user_data, const_cast(match.weights), match.dst); - if (match.expert_scale != nullptr) { - params->add_alloc_dep( - params->user_data, const_cast(match.expert_scale), match.dst); - } - i += match.node_count - 1; - } - - if (cgraph->nodes[i]->op == GGML_OP_UNARY || cgraph->nodes[i]->op == GGML_OP_SOFT_MAX || - cgraph->nodes[i]->op == GGML_OP_ARGSORT) { - ggml_cuda_topk_moe_args args; - const bool can_fuse = ggml_cuda_topk_moe_fusion(cgraph, i, args); - std::vector ops; - ops.reserve(13); // max ops; avoids gcc -Wstringop-overflow false positive - - const ggml_tensor * node = cgraph->nodes[i]; - - if (can_fuse) { - const ggml_tensor * logits = node->src[0]; - ggml_tensor * weights = nullptr; - ggml_tensor * ids = nullptr; - - if (!args.delayed_softmax) { - int out_nodes[2]; // nodes which can't be elided - - if (args.sigmoid) { - ops.insert(ops.end(), { GGML_OP_UNARY }); - } else if (args.sqrt_softplus) { - ops.insert(ops.end(), { GGML_OP_UNARY, GGML_OP_SQRT }); - } else { - ops.insert(ops.end(), { GGML_OP_SOFT_MAX }); - } - const int i_probs = i + (int) ops.size() - 1; // last node of the gating activation - - if (args.prob_bias) { - ops.insert(ops.end(), { GGML_OP_RESHAPE, GGML_OP_ADD, GGML_OP_ARGSORT, GGML_OP_VIEW, - GGML_OP_GET_ROWS }); - out_nodes[0] = i_probs + 4; - } else { - ops.insert(ops.end(), { GGML_OP_RESHAPE, GGML_OP_ARGSORT, GGML_OP_VIEW, GGML_OP_GET_ROWS }); - out_nodes[0] = i_probs + 3; - } - ids = cgraph->nodes[out_nodes[0]]; - - if (args.norm) { - ops.insert(ops.end(), - { GGML_OP_RESHAPE, GGML_OP_SUM_ROWS, GGML_OP_CLAMP, GGML_OP_DIV, GGML_OP_RESHAPE }); - } - if (args.scale) { - ops.insert(ops.end(), { GGML_OP_SCALE }); - } - - weights = cgraph->nodes[i + ops.size() - 1]; - out_nodes[1] = i + ops.size() - 1; - - if (ggml_can_fuse_subgraph(cgraph, i, ops.size(), ops.data(), out_nodes, 2) && - ggml_cuda_should_use_topk_moe(node, logits, weights, ids)) { - - add_alloc_deps(i, i + ops.size()); - i += ops.size() - 1; - } - } - } - } - } + ggml_cuda_fusion_add_alloc_deps(cuda_ctx, cgraph, params); } #ifdef USE_CUDA_GRAPH @@ -6468,12 +4115,16 @@ static bool ggml_backend_cuda_device_supports_op(ggml_backend_dev_t dev, const g if (b->type == GGML_TYPE_F16 && a->type != GGML_TYPE_F16 && !ggml_cuda_op_mul_mat_use_fwht(op)) { return false; } + if (op->op == GGML_OP_MUL_MAT_ID && b->type != GGML_TYPE_F32 && b->type != GGML_TYPE_BF16) { + return false; + } const int cc_dev = ggml_cuda_info().devices[dev_ctx->device].cc; const bool f32_src1_ok = GGML_CUDA_CC_IS_NVIDIA(cc_dev) && cc_dev < GGML_CUDA_CC_AMPERE; const enum ggml_prec prec_src1 = ggml_prec_get_src(op, 1); const bool fp8_id_mmvf = op->op == GGML_OP_MUL_MAT_ID && - a->type == GGML_TYPE_F8_E4M3 && b->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32 && - ggml_cuda_should_use_mmvf(a, cc_dev, ggml_cuda_info().devices[dev_ctx->device].warp_size, b->ne[2]); + a->type == GGML_TYPE_F8_E4M3 && (b->type == GGML_TYPE_F32 || b->type == GGML_TYPE_BF16) && op->type == GGML_TYPE_F32 && + ggml_cuda_should_use_mmvf(a, b->type, cc_dev, ggml_cuda_info().devices[dev_ctx->device].warp_size, b->ne[2], + /*mul_mat_id =*/ true); if (prec_src1 == GGML_PREC_F32 && !fp8_id_mmvf && (op->op == GGML_OP_MUL_MAT_ID || !f32_src1_ok || a->type != GGML_TYPE_F32)) { return false; } @@ -6488,7 +4139,7 @@ static bool ggml_backend_cuda_device_supports_op(ggml_backend_dev_t dev, const g return false; } if (GGML_CUDA_CC_IS_QY2(cc) && op->op == GGML_OP_MUL_MAT_ID && - a->type == GGML_TYPE_Q2_K && b->type == GGML_TYPE_F32) { + a->type == GGML_TYPE_Q2_K && (b->type == GGML_TYPE_F32 || b->type == GGML_TYPE_BF16)) { return false; } } diff --git a/ggml/src/ggml-cuda/graph.cuh b/ggml/src/ggml-cuda/graph.cuh index 7b9c277898e1..bb51ef9befc6 100644 --- a/ggml/src/ggml-cuda/graph.cuh +++ b/ggml/src/ggml-cuda/graph.cuh @@ -1,6 +1,6 @@ #pragma once -// CUDA graph capture and concurrent stream state, only needed by ggml-cuda.cu +// CUDA graph capture and concurrent stream state, only needed by ggml-cuda.cu and fusion.cu #include "common.cuh" diff --git a/ggml/src/ggml-cuda/inkling2.cu b/ggml/src/ggml-cuda/inkling2.cu new file mode 100644 index 000000000000..b96270396774 --- /dev/null +++ b/ggml/src/ggml-cuda/inkling2.cu @@ -0,0 +1,396 @@ +#include "inkling2.cuh" + +// the fused kernels keep the operation order of the unfused graph where it is cheap to do so, +// __fmul_rn/__fadd_rn stop the compiler from contracting a separate MUL and ADD into one FMA + +static __global__ void situ_f32( + const float * gate, const float * up, float * dst, const int ne0, const int ne1, const int ne2, const int64_t nrows, + const int64_t g_s1, const int64_t g_s2, const int64_t g_s3, const int64_t u_s1, const int64_t u_s2, const int64_t u_s3, + const float s0, const float b0, const float s1, const float b1, const float s2, const float b2, const float s3, const float b3) { + ggml_cuda_pdl_lc(); + const int i0 = blockIdx.x*blockDim.x + threadIdx.x; + + ggml_cuda_pdl_sync(); + if (i0 >= ne0) { + return; + } + + for (int64_t row = blockIdx.y; row < nrows; row += gridDim.y) { + const int64_t i1 = row % ne1; + const int64_t i2 = (row / ne1) % ne2; + const int64_t i3 = row / ((int64_t) ne1*ne2); + + const float g = gate[i3*g_s3 + i2*g_s2 + i1*g_s1 + i0]; + const float u = up [i3*u_s3 + i2*u_s2 + i1*u_s1 + i0]; + + const float act = s1*tanhf(s0*g + b0) + b1; + const float sig = 1.0f/(1.0f + expf(-g)); + const float lin = s3*tanhf(s2*u + b2) + b3; + + dst[row*ne0 + i0] = __fmul_rn(__fmul_rn(act, sig), lin); + } +} + +void ggml_cuda_op_situ(ggml_backend_cuda_context & ctx, const ggml_tensor * gate, const ggml_tensor * up, + const float * s, const float * b, ggml_tensor * dst) { + GGML_ASSERT(gate->type == GGML_TYPE_F32 && up->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32); + GGML_ASSERT(gate->nb[0] == sizeof(float) && up->nb[0] == sizeof(float) && ggml_is_contiguous(dst)); + GGML_ASSERT(ggml_are_same_shape(gate, up) && ggml_are_same_shape(gate, dst)); + + const int64_t ne0 = gate->ne[0]; + const int64_t nrows = ggml_nrows(gate); + + const int block_size = 256; + const dim3 grid((ne0 + block_size - 1)/block_size, std::min(nrows, 65535), 1); + + const ggml_cuda_kernel_launch_params params(grid, dim3(block_size, 1, 1), 0, ctx.stream()); + ggml_cuda_kernel_launch(situ_f32, params, + (const float *) gate->data, (const float *) up->data, (float *) dst->data, (int) ne0, (int) gate->ne[1], (int) gate->ne[2], nrows, + (int64_t) (gate->nb[1]/sizeof(float)), (int64_t) (gate->nb[2]/sizeof(float)), (int64_t) (gate->nb[3]/sizeof(float)), + (int64_t) (up->nb[1]/sizeof(float)), (int64_t) (up->nb[2]/sizeof(float)), (int64_t) (up->nb[3]/sizeof(float)), + s[0], b[0], s[1], b[1], s[2], b[2], s[3], b[3]); +} + +// one thread per (channel, run of tokens of one sequence). the last K columns of x stay in registers, right-aligned in +// M = GGML_CUDA_SHORT_CONV_MAX_K slots with zero weights in front, so K needs no template and the sums keep their order. +// a thread reads cur at a token before it writes dst there and never again, so dst may be cur itself when a thread has +// the whole sequence +template +static __global__ void short_conv_f32(const ggml_cuda_short_conv_args a) { + ggml_cuda_pdl_lc(); + constexpr int M = GGML_CUDA_SHORT_CONV_MAX_K; + + const int K = a.K; + const int K1 = K - 1; + const int c = blockIdx.x*blockDim.x + threadIdx.x; + + ggml_cuda_pdl_sync(); + if (c >= a.C) { + return; + } + + float w[M]; +#pragma unroll + for (int m = 0; m < M; ++m) { + w[m] = m >= M - K ? a.w[c*K + m - (M - K)] : 0.0f; + } + + const int n_runs = (a.Ts + a.run - 1)/a.run; + for (int r = blockIdx.y; r < a.S*n_runs; r += gridDim.y) { + const int s = r / n_runs; + const int t0 = (r - s*n_runs)*a.run; + const int t1 = min(t0 + a.run, a.Ts); + + const float * pc = a.past + c*a.past_s1 + s*a.past_s2; + const float * xc = a.cur + (int64_t) s*a.Ts*a.C + c; + + // x[M - K + k] is column ts + k of [past; cur^T] + float x[M]; +#pragma unroll + for (int m = 0; m < M - 1; ++m) { + const int j = t0 + m - (M - K); + x[m] = j < 0 ? 0.0f : j < K1 ? pc[j] : xc[(int64_t) (j - K1)*a.C]; + } + + for (int ts = t0; ts < t1; ++ts) { + const int64_t t = (int64_t) s*a.Ts + ts; + + x[M - 1] = xc[(int64_t) ts*a.C]; + + float y = 0.0f; +#pragma unroll + for (int m = 0; m < M; ++m) { + y += x[m]*w[m]; + } + + if constexpr (has_dyn) { + const float * d = a.dyn + t*a.dyn_s1 + (c / (a.C / a.n_heads))*K; +#pragma unroll + for (int lag = 0; lag < M; ++lag) { + if (lag < K) { + y = __fadd_rn(y, __fmul_rn(x[M - 1 - lag], d[lag])); + } + } + } + + float o = a.scale*__fadd_rn(x[M - 1], y) + a.bias; + if constexpr (has_res) { + o = __fadd_rn(a.res[t*a.C + c], o); + } + a.dst[t*a.C + c] = o; + +#pragma unroll + for (int m = 0; m < M - 1; ++m) { + x[m] = x[m + 1]; + } + + // x now holds the K - 1 columns that end at token ts: the conv state of slot Ts - 1 - ts, if it is kept + if (ts >= a.Ts - a.kw) { + float * st = a.state + (a.Ts - 1 - ts)*a.state_slot_s + c*a.state_ch_s + s*a.state_seq_s; +#pragma unroll + for (int m = 0; m < M - 1; ++m) { + if (m >= M - K) { + st[m - (M - K)] = x[m]; + } + } + } + } + } +} + +void ggml_cuda_op_short_conv(ggml_backend_cuda_context & ctx, const ggml_cuda_short_conv_args & a) { + GGML_ASSERT(a.K >= 2 && a.K <= GGML_CUDA_SHORT_CONV_MAX_K); + + const int block_size = 128; + const int n_runs = (a.Ts + a.run - 1)/a.run; + const dim3 grid((a.C + block_size - 1)/block_size, std::min(a.S*n_runs, 65535), 1); + + const ggml_cuda_kernel_launch_params params(grid, dim3(block_size, 1, 1), 0, ctx.stream()); + if (a.dyn) { + if (a.res) { + ggml_cuda_kernel_launch(short_conv_f32, params, a); + } else { + ggml_cuda_kernel_launch(short_conv_f32, params, a); + } + } else { + if (a.res) { + ggml_cuda_kernel_launch(short_conv_f32, params, a); + } else { + ggml_cuda_kernel_launch(short_conv_f32, params, a); + } + } +} + +// one block per (query, token): the dot products of the B stack rows and of cur with the query, the softmax over the +// B + 1 rows and the weighted sum; the norm of cur is a scale of its dot product +template +static __global__ void depth_mix_f32( + const float * stack, const float * cur, const float * query, float * dst, const int n, const int B, const int Q, + const int64_t stack_s1, const int64_t stack_s2, const int64_t cur_s1, const int64_t query_s1, + const bool norm_cur, const float eps, const float scale) { + ggml_cuda_pdl_lc(); + constexpr int MAX = GGML_CUDA_DEPTH_MIX_MAX_ROWS; + constexpr int NW = block_size/WARP_SIZE; + + const int q = blockIdx.x; + const int t = blockIdx.y; + const int tid = threadIdx.x; + const int lane = tid % WARP_SIZE; + const int warp = tid / WARP_SIZE; + + const float * qv = query + q*query_s1; + const float * st = stack + t*stack_s2; + const float * xc = cur + t*cur_s1; + + // [0, B): the stack rows, MAX: cur, MAX + 1: the sum of squares of cur + float acc[MAX + 2]; +#pragma unroll + for (int r = 0; r < MAX + 2; ++r) { + acc[r] = 0.0f; + } + + ggml_cuda_pdl_sync(); + + for (int i = tid; i < n; i += block_size) { + const float qi = qv[i]; +#pragma unroll + for (int r = 0; r < MAX; ++r) { + if (r < B) { + acc[r] += st[r*stack_s1 + i]*qi; + } + } + const float xi = xc[i]; + acc[MAX] += xi*qi; + acc[MAX + 1] += xi*xi; + } + + __shared__ float s_acc[NW][MAX + 2]; +#pragma unroll + for (int r = 0; r < MAX + 2; ++r) { + if (r < B || r >= MAX) { + acc[r] = warp_reduce_sum(acc[r]); + if (lane == 0) { + s_acc[warp][r] = acc[r]; + } + } + } + __syncthreads(); +#pragma unroll + for (int r = 0; r < MAX + 2; ++r) { + if (r < B || r >= MAX) { + acc[r] = 0.0f; +#pragma unroll + for (int w = 0; w < NW; ++w) { + acc[r] += s_acc[w][r]; + } + } + } + + const float sc = norm_cur ? rsqrtf(acc[MAX + 1]/n + eps) : 1.0f; + + float mx = scale*(sc*acc[MAX]); +#pragma unroll + for (int r = 0; r < MAX; ++r) { + if (r < B) { + acc[r] = scale*acc[r]; + mx = fmaxf(mx, acc[r]); + } + } + + float p_cur = expf(scale*(sc*acc[MAX]) - mx); + float sum = 0.0f; +#pragma unroll + for (int r = 0; r < MAX; ++r) { + if (r < B) { + acc[r] = expf(acc[r] - mx); + sum += acc[r]; + } + } + sum += p_cur; + + const float inv = 1.0f/sum; +#pragma unroll + for (int r = 0; r < MAX; ++r) { + acc[r] *= inv; + } + p_cur *= inv*sc; + + for (int i = tid; i < n; i += block_size) { + float o = 0.0f; +#pragma unroll + for (int r = 0; r < MAX; ++r) { + if (r < B) { + o += acc[r]*st[r*stack_s1 + i]; + } + } + o += p_cur*xc[i]; + dst[((int64_t) t*n + i)*Q + q] = o; + } +} + +void ggml_cuda_op_depth_mix(ggml_backend_cuda_context & ctx, const ggml_tensor * stack, const ggml_tensor * cur, + bool norm_cur, float eps, const ggml_tensor * query, float scale, ggml_tensor * dst) { + const int64_t n = cur->ne[0]; + const int64_t B = stack->ne[1]; + const int64_t T = stack->ne[2]; + const int64_t Q = query->ne[1]; + + GGML_ASSERT(B >= 1 && B <= GGML_CUDA_DEPTH_MIX_MAX_ROWS); + GGML_ASSERT(stack->nb[0] == sizeof(float) && cur->nb[0] == sizeof(float) && query->nb[0] == sizeof(float)); + GGML_ASSERT(ggml_is_contiguous(dst) && dst->ne[0] == Q && dst->ne[1] == n && dst->ne[2] == T); + GGML_ASSERT(T <= 65535 && Q <= 65535); + + const int block_size = 256; + const dim3 grid(Q, T, 1); + + const ggml_cuda_kernel_launch_params params(grid, dim3(block_size, 1, 1), 0, ctx.stream()); + ggml_cuda_kernel_launch(depth_mix_f32, params, + (const float *) stack->data, (const float *) cur->data, (const float *) query->data, (float *) dst->data, + (int) n, (int) B, (int) Q, + (int64_t) (stack->nb[1]/sizeof(float)), (int64_t) (stack->nb[2]/sizeof(float)), + (int64_t) (cur->nb[2]/sizeof(float)), (int64_t) (query->nb[1]/sizeof(float)), + norm_cur, eps, scale); +} + +// one block per (rank row, token): the sums of squares of cur and msg and their dot products with the two halves of the row +template +static __global__ void loop_ctrl_down_f32( + const float * cur, const float * msg, const float * w, float * gate, const int n, + const int64_t cur_s1, const int64_t msg_s1, const int64_t w_s1, const int64_t gate_s1, const float eps) { + ggml_cuda_pdl_lc(); + const int r = blockIdx.x; + const int t = blockIdx.y; + const int tid = threadIdx.x; + + const float * xc = cur + t*cur_s1; + const float * xm = msg + t*msg_s1; + const float * wr = w + r*w_s1; + + ggml_cuda_pdl_sync(); + + float2 ss = make_float2(0.0f, 0.0f); + float2 dd = make_float2(0.0f, 0.0f); + for (int i = tid; i < n; i += block_size) { + const float c = xc[i]; + const float m = xm[i]; + ss.x += c*c; + ss.y += m*m; + dd.x += wr[i]*c; + dd.y += wr[n + i]*m; + } + + __shared__ float2 s_ss[32]; + __shared__ float2 s_dd[32]; + ss = block_reduce(ss, s_ss); + dd = block_reduce(dd, s_dd); + + if (tid == 0) { + gate[t*gate_s1 + r] = rsqrtf(ss.x/n + eps)*dd.x + rsqrtf(ss.y/n + eps)*dd.y; + } +} + +// one warp per (output channel, token): the gain and forget dot products over the rank and the combine +static __global__ void loop_ctrl_up_f32( + const float * cur, const float * msg, const float * gate, const float * wg, const float * wf, float * dst, + const int n, const int rank, const int64_t cur_s1, const int64_t msg_s1, const int64_t gate_s1, + const int64_t wg_s1, const int64_t wf_s1, const int64_t dst_s1) { + ggml_cuda_pdl_lc(); + const int i = blockIdx.x*blockDim.y + threadIdx.y; + const int t = blockIdx.y; + const int lane = threadIdx.x; + + ggml_cuda_pdl_sync(); + if (i >= n) { + return; + } + + const float * gt = gate + t*gate_s1; + + float g = 0.0f; + float f = 0.0f; + for (int k = lane; k < rank; k += WARP_SIZE) { + const float x = gt[k]; + g += wg[i*wg_s1 + k]*x; + f += wf[i*wf_s1 + k]*x; + } + g = warp_reduce_sum(g); + f = warp_reduce_sum(f); + + if (lane == 0) { + const float c = cur[t*cur_s1 + i]; + const float m = msg[t*msg_s1 + i]; + const float a = __fsub_rn(c, __fmul_rn(tanhf(f), c)); + dst[t*dst_s1 + i] = __fadd_rn(a, __fmul_rn(tanhf(g), m)); + } +} + +void ggml_cuda_op_loop_ctrl(ggml_backend_cuda_context & ctx, const ggml_tensor * cur, const ggml_tensor * msg, float eps, + const ggml_tensor * w_down, const ggml_tensor * w_gain, const ggml_tensor * w_forget, ggml_tensor * gate, ggml_tensor * dst) { + const int64_t n = cur->ne[0]; + const int64_t T = cur->ne[1]; + const int64_t rank = w_down->ne[1]; + + GGML_ASSERT(cur->nb[0] == sizeof(float) && msg->nb[0] == sizeof(float) && gate->nb[0] == sizeof(float) && dst->nb[0] == sizeof(float)); + GGML_ASSERT(w_down->ne[0] == 2*n && w_gain->ne[0] == rank && w_forget->ne[0] == rank && w_gain->ne[1] == n && w_forget->ne[1] == n); + GGML_ASSERT(T <= GGML_CUDA_LOOP_CTRL_MAX_TOKENS); + + cudaStream_t stream = ctx.stream(); + + { + const int block_size = 256; + const ggml_cuda_kernel_launch_params params(dim3(rank, T, 1), dim3(block_size, 1, 1), 0, stream); + ggml_cuda_kernel_launch(loop_ctrl_down_f32, params, + (const float *) cur->data, (const float *) msg->data, (const float *) w_down->data, (float *) gate->data, (int) n, + (int64_t) (cur->nb[1]/sizeof(float)), (int64_t) (msg->nb[1]/sizeof(float)), + (int64_t) (w_down->nb[1]/sizeof(float)), (int64_t) (gate->nb[1]/sizeof(float)), eps); + } + { + const int rows_per_block = 8; + const ggml_cuda_kernel_launch_params params(dim3((n + rows_per_block - 1)/rows_per_block, T, 1), dim3(WARP_SIZE, rows_per_block, 1), 0, stream); + ggml_cuda_kernel_launch(loop_ctrl_up_f32, params, + (const float *) cur->data, (const float *) msg->data, (const float *) gate->data, + (const float *) w_gain->data, (const float *) w_forget->data, (float *) dst->data, (int) n, (int) rank, + (int64_t) (cur->nb[1]/sizeof(float)), (int64_t) (msg->nb[1]/sizeof(float)), (int64_t) (gate->nb[1]/sizeof(float)), + (int64_t) (w_gain->nb[1]/sizeof(float)), (int64_t) (w_forget->nb[1]/sizeof(float)), (int64_t) (dst->nb[1]/sizeof(float))); + } +} diff --git a/ggml/src/ggml-cuda/inkling2.cuh b/ggml/src/ggml-cuda/inkling2.cuh new file mode 100644 index 000000000000..dcffe3e60995 --- /dev/null +++ b/ggml/src/ggml-cuda/inkling2.cuh @@ -0,0 +1,55 @@ +#pragma once + +#include "common.cuh" + +// fused op chains of the Inkling 2 graph + +// largest conv width and stack depth the fused kernels handle +#define GGML_CUDA_SHORT_CONV_MAX_K 8 +#define GGML_CUDA_DEPTH_MIX_MAX_ROWS 16 + +// the most tokens the fused loop controller handles, larger batches use the matrix multiplications +#define GGML_CUDA_LOOP_CTRL_MAX_TOKENS 8 + +// situ(g, u) = (s1*tanh(s0*g + b0) + b1)*sigmoid(g)*(s3*tanh(s2*u + b2) + b3), with s and b of the four SCALE nodes +void ggml_cuda_op_situ(ggml_backend_cuda_context & ctx, const ggml_tensor * gate, const ggml_tensor * up, + const float * s, const float * b, ggml_tensor * dst); + +// causal short conv: x = [past; cur^T], y = conv(x, w) (+ input-dependent taps per head), dst = s*(cur + y) + b (+ res) +// the K - 1 columns of x that end at token Ts - 1 - slot are the conv state of slot, for the last kw slots (kw = 1 without rollback) +// each thread does `run` tokens of a sequence in order, run == Ts lets dst be cur +struct ggml_cuda_short_conv_args { + const float * past; // [K - 1, C, S], strides in elements + int64_t past_s1; + int64_t past_s2; + const float * cur; // [C, Ts*S], contiguous + const float * w; // [K, C], contiguous + const float * dyn; // [K*H, Ts*S] taps or nullptr + int64_t dyn_s1; + int n_heads; + const float * res; // [C, Ts*S], contiguous, or nullptr + float * dst; // [C, Ts*S], contiguous + float * state; // [K - 1, slot, C, S], strides in elements + int64_t state_slot_s; + int64_t state_ch_s; + int64_t state_seq_s; + int kw; + int run; + int C; + int K; + int Ts; + int S; + float scale; + float bias; +}; + +void ggml_cuda_op_short_conv(ggml_backend_cuda_context & ctx, const ggml_cuda_short_conv_args & args); + +// depth mix: states = [stack; rms_norm(cur)], p = softmax(scale*(states . query)), dst = p . states, written as [Q, n, T] +// norm_cur false: cur is already normalized +void ggml_cuda_op_depth_mix(ggml_backend_cuda_context & ctx, const ggml_tensor * stack, const ggml_tensor * cur, + bool norm_cur, float eps, const ggml_tensor * query, float scale, ggml_tensor * dst); + +// loop controller: gate = w_down . [rms_norm(cur); rms_norm(msg)], dst = cur - tanh(w_forget . gate)*cur + tanh(w_gain . gate)*msg +void ggml_cuda_op_loop_ctrl(ggml_backend_cuda_context & ctx, const ggml_tensor * cur, const ggml_tensor * msg, float eps, + const ggml_tensor * w_down, const ggml_tensor * w_gain, const ggml_tensor * w_forget, ggml_tensor * gate, ggml_tensor * dst); diff --git a/ggml/src/ggml-cuda/lightning-indexer.cu b/ggml/src/ggml-cuda/lightning-indexer.cu index b7939243b74b..ff6402e47540 100644 --- a/ggml/src/ggml-cuda/lightning-indexer.cu +++ b/ggml/src/ggml-cuda/lightning-indexer.cu @@ -622,6 +622,42 @@ void ggml_cuda_lightning_indexer(ggml_backend_cuda_context & ctx, ggml_tensor * LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 32, k, GGML_TYPE_F32) GGML_ABORT("fatal error"); } + } else if (n_embd == 128 && n_head == 16) { + if ((turing_mma_available(cc) || amd_mfma_available(cc) || amd_wmma_available(cc)) && k->type != GGML_TYPE_F32 && k->type != GGML_TYPE_BF16) { + constexpr int K_VECS_PER_BLOCK = 32; + constexpr int WARPS_PER_BLOCK = 4; + + dim3 block(ggml_cuda_info().devices[device].warp_size, WARPS_PER_BLOCK); + int num_kv_blocks = (n_kv + (K_VECS_PER_BLOCK) - 1) / (K_VECS_PER_BLOCK); + dim3 grid(num_kv_blocks, n_batch, n_stream); + + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_mma, 128, 16, k, GGML_TYPE_F16) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_mma, 128, 16, k, GGML_TYPE_Q4_0) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_mma, 128, 16, k, GGML_TYPE_Q4_1) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_mma, 128, 16, k, GGML_TYPE_Q5_0) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_mma, 128, 16, k, GGML_TYPE_Q5_1) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_mma, 128, 16, k, GGML_TYPE_Q8_0) + GGML_ABORT("fatal error"); + } else { + // use vector kernel + constexpr int K_VECS_PER_WARP = 8; + constexpr int WARPS_PER_BLOCK = 8; + constexpr int K_VECS_PER_BLOCK = K_VECS_PER_WARP * WARPS_PER_BLOCK; + + dim3 block(32, WARPS_PER_BLOCK); + int num_kv_blocks = (n_kv + (K_VECS_PER_BLOCK) - 1) / (K_VECS_PER_BLOCK); + dim3 grid(num_kv_blocks, n_batch, n_stream); + + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_F16) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_Q4_0) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_Q4_1) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_Q5_0) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_Q5_1) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_Q8_0) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_BF16) + LIGHTNING_INDEXER_CASE(lightning_indexer_kernel_vec, 128, 16, k, GGML_TYPE_F32) + GGML_ABORT("fatal error"); + } } else if (n_embd == 128 && n_head == 4 && n_batch >= LIGHTNING_INDEXER_TILE_TOKENS) { // too few heads for a wmma tile, the tile kernel shares the keys across the tokens constexpr int WARPS_PER_BLOCK = 8; @@ -688,7 +724,7 @@ bool ggml_cuda_lightning_indexer_supported(int device, const ggml_tensor * dst) return false; } - if (neq1 != 64 && neq1 != 32 && neq1 != 4) { + if (neq1 != 64 && neq1 != 32 && neq1 != 16 && neq1 != 4) { return false; } diff --git a/ggml/src/ggml-cuda/mmf.cuh b/ggml/src/ggml-cuda/mmf.cuh index 46a123a5c3c1..101c247fe1cd 100644 --- a/ggml/src/ggml-cuda/mmf.cuh +++ b/ggml/src/ggml-cuda/mmf.cuh @@ -98,9 +98,9 @@ static __global__ void mul_mat_f( const int sample_x = sample_dst / sample_ratio; const int sample_y = sample_dst; - x += int64_t(sample_x) *stride_sample_x + channel_x *stride_channel_x + row0*stride_row ; - y += int64_t(sample_y) *stride_sample_y + channel_y *stride_channel_y; - dst += int64_t(sample_dst)*stride_sample_dst + channel_dst*stride_channel_dst; + x += int64_t(sample_x) *stride_sample_x + int64_t(channel_x) *stride_channel_x + int64_t(row0)*stride_row; + y += int64_t(sample_y) *stride_sample_y + int64_t(channel_y) *stride_channel_y; + dst += int64_t(sample_dst)*stride_sample_dst + int64_t(channel_dst)*stride_channel_dst; [[maybe_unused]] const float2 * y2 = (const float2 *) y; @@ -290,7 +290,7 @@ static __global__ void mul_mat_f_ids( const int sample_x = sample_dst / sample_ratio; const int sample_y = sample_dst; - x += int64_t(sample_x) *stride_sample_x + channel_x *stride_channel_x + row0*stride_row; + x += int64_t(sample_x) *stride_sample_x + int64_t(channel_x) *stride_channel_x + int64_t(row0)*stride_row; y += int64_t(sample_y) *stride_sample_y; dst += int64_t(sample_dst)*stride_sample_dst; diff --git a/ggml/src/ggml-cuda/mmq-few.cu b/ggml/src/ggml-cuda/mmq-few.cu index bc7cbc6e5638..2fe47ddd25ae 100644 --- a/ggml/src/ggml-cuda/mmq-few.cu +++ b/ggml/src/ggml-cuda/mmq-few.cu @@ -799,10 +799,10 @@ static void launch_mul_mat_q_few_switch_ncg(const ggml_tensor * src0, const ggml void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst) { GGML_TENSOR_BINARY_OP_LOCALS; - GGML_ASSERT(src1->type == GGML_TYPE_F32); + GGML_ASSERT(src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16); GGML_ASSERT( dst->type == GGML_TYPE_F32); GGML_ASSERT(nb00 == ggml_type_size(src0->type)); - GGML_ASSERT(nb10 == sizeof(float)); + GGML_ASSERT(nb10 == ggml_type_size(src1->type)); GGML_ASSERT(nb0 == sizeof(float)); GGML_ASSERT(ne00 % QK_K == 0); @@ -828,14 +828,14 @@ void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor pairs.alloc(int64_t(npairs_max)*MMQ_FEW_PAIR_INTS); src1_q.alloc(int64_t(npairs_max)*nunits*MMQ_FEW_Q8_1_INT4); - quantize_mmq_few_id_q8_1_cuda((const float *) src1->data, (const int32_t *) ids->data, src1_q.get(), pairs.get(), mmq_few_ds_layout(src0->type), - ne00, nb11/sizeof(float), nb12/sizeof(float), ne11, ne02, n_expert_used, n_tokens, ids->nb[1]/sizeof(int32_t), npairs_max, stream); + quantize_mmq_few_id_q8_1_cuda(src1->data, src1->type, (const int32_t *) ids->data, src1_q.get(), pairs.get(), mmq_few_ds_layout(src0->type), + ne00, nb11/nb10, nb12/nb10, ne11, ne02, n_expert_used, n_tokens, ids->nb[1]/sizeof(int32_t), npairs_max, stream); } else { GGML_ASSERT(ne11 <= MMQ_FEW_MAX_NCG*MMQ_FEW_NCOLS); GGML_ASSERT(ne12 % ne02 == 0 && ne13 % ne03 == 0); src1_q.alloc(int64_t(ne12)*ne13*nunits*ncg*MMQ_FEW_Q8_1_INT4); - quantize_mmq_few_q8_1_cuda((const float *) src1->data, src1_q.get(), mmq_few_ds_layout(src0->type), ne10, nb11/sizeof(float), nb12/sizeof(float), nb13/sizeof(float), + quantize_mmq_few_q8_1_cuda(src1->data, src1->type, src1_q.get(), mmq_few_ds_layout(src0->type), ne10, nb11/nb10, nb12/nb10, nb13/nb10, ne11, ne12, ne13, stream); } diff --git a/ggml/src/ggml-cuda/mmq.cu b/ggml/src/ggml-cuda/mmq.cu index c9bcbc2aa3a9..9d896b32256e 100644 --- a/ggml/src/ggml-cuda/mmq.cu +++ b/ggml/src/ggml-cuda/mmq.cu @@ -164,7 +164,7 @@ static int ggml_cuda_mmq_get_J_best( void ggml_cuda_mul_mat_q( ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst, const ggml_cuda_mm_fusion_args_host * fusion) { - GGML_ASSERT( src1->type == GGML_TYPE_F32); + GGML_ASSERT( src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16); GGML_ASSERT( dst->type == GGML_TYPE_F32); GGML_ASSERT(!ids || ids->type == GGML_TYPE_I32); // Optional, used for batched GGML_MUL_MAT_ID. @@ -210,7 +210,6 @@ void ggml_cuda_mul_mat_q( GGML_ASSERT(!ids || ids->nb[0] == ggml_type_size(ids->type)); const char * src0_d = (const char *) src0->data; - const float * src1_d = (const float *) src1->data; float * dst_d = (float *) dst->data; // If src0 (or the fused gate weight) is a temporary compute buffer, clear any potential padding. @@ -284,11 +283,11 @@ void ggml_cuda_mul_mat_q( static constexpr size_t align_float8 = 32; const bool use_aligned_float8 = ggml_cuda_is_aligned(src1, align_float8); static_assert(sizeof(block_fp4_mmq) == 4 * sizeof(block_q8_1)); - quantize_mmq_fp4_cuda(src1_d, nullptr, src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10, s11, s12, s13, ne10_padded, + quantize_mmq_fp4_cuda(src1->data, src1->type, nullptr, src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10, s11, s12, s13, ne10_padded, ne11, ne12, ne13, stream); } else { - quantize_mmq_q8_1_cuda(src1_d, nullptr, src1_q8_1.get(), src0->type, ne10, s11, s12, s13, ne10_padded, + quantize_mmq_q8_1_cuda(src1->data, src1->type, nullptr, src1_q8_1.get(), src0->type, ne10, s11, s12, s13, ne10_padded, ne11, ne12, ne13, stream); } CUDA_CHECK(cudaGetLastError()); @@ -359,17 +358,17 @@ void ggml_cuda_mul_mat_q( static constexpr size_t align_float8 = 32; const bool use_aligned_float8 = ggml_cuda_is_aligned(src1, align_float8); if (dedup_bcast) { - quantize_scatter_mmq_fp4_cuda(src1_d, ids_src1.get(), src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10, + quantize_scatter_mmq_fp4_cuda(src1->data, src1->type, ids_src1.get(), src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10, /*stride_token=*/s12, ne10_padded, ne12, ne11_flat, n_expert_used, stream); } else { - quantize_mmq_fp4_cuda(src1_d, ids_src1.get(), src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10, s11, s12, s13, + quantize_mmq_fp4_cuda(src1->data, src1->type, ids_src1.get(), src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10, s11, s12, s13, ne10_padded, ne11_flat, ne12_flat, ne13_flat, stream); } } else if (dedup_bcast) { - quantize_scatter_mmq_q8_1_cuda(src1_d, ids_src1.get(), src1_q8_1.get(), src0->type, ne10, + quantize_scatter_mmq_q8_1_cuda(src1->data, src1->type, ids_src1.get(), src1_q8_1.get(), src0->type, ne10, /*stride_token=*/s12, ne10_padded, ne12, ne11_flat, n_expert_used, stream); } else { - quantize_mmq_q8_1_cuda(src1_d, ids_src1.get(), src1_q8_1.get(), src0->type, ne10, s11, s12, s13, + quantize_mmq_q8_1_cuda(src1->data, src1->type, ids_src1.get(), src1_q8_1.get(), src0->type, ne10, s11, s12, s13, ne10_padded, ne11_flat, ne12_flat, ne13_flat, stream); } CUDA_CHECK(cudaGetLastError()); diff --git a/ggml/src/ggml-cuda/mmvf.cu b/ggml/src/ggml-cuda/mmvf.cu index dbc84c2244bf..f8b03c9d97e4 100644 --- a/ggml/src/ggml-cuda/mmvf.cu +++ b/ggml/src/ggml-cuda/mmvf.cu @@ -13,15 +13,20 @@ static __device__ __forceinline__ float2 mmvf_load_fp8x2(const ggml_fp8_e4m3_t * #endif } -template +template static __global__ void mul_mat_vec_f( - const T * x_ptr, const float * y_ptr, const int32_t * ids_ptr, const ggml_cuda_mm_fusion_args_device fusion, float * dst_ptr, + const T * x_ptr, const T_y * y_ptr, const int32_t * ids_ptr, const ggml_cuda_mm_fusion_args_device fusion, float * dst_ptr, const int ncols2, const uint3 nchannels_y, const int stride_row, const int stride_col_y2, const int stride_col_dst, const uint3 channel_ratio, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst, const uint3 sample_ratio, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst, const int ids_stride) { + static_assert(std::is_same_v || (std::is_same_v && + (std::is_same_v || std::is_same_v)), "a BF16 src1 needs BF16 or FP8 weights"); + using T_y2 = std::conditional_t, nv_bfloat162, float2>; // a pair of src1 values + const T * GGML_CUDA_RESTRICT x = x_ptr; - const float * GGML_CUDA_RESTRICT y = y_ptr; + const T_y * GGML_CUDA_RESTRICT y = y_ptr; const int32_t * GGML_CUDA_RESTRICT ids = ids_ptr; float * GGML_CUDA_RESTRICT dst = dst_ptr; const int row = blockIdx.x; @@ -257,7 +262,7 @@ static __global__ void mul_mat_vec_f( #endif // FP16_AVAILABLE } } else if constexpr (std::is_same_v) { - const float2 * y2 = (const float2 *) y; + const T_y2 * y2 = (const T_y2 *) y; //TODO: add support for ggml_cuda_mad for hip_bfloat162 #if defined(GGML_USE_HIP) const int * x2 = (const int *) x; @@ -277,7 +282,7 @@ static __global__ void mul_mat_vec_f( } #pragma unroll for (int j = 0; j < ncols_dst; ++j) { - const float2 tmpy = y2[j*stride_col_y2 + col2]; + const float2 tmpy = ggml_cuda_cast(y2[j*stride_col_y2 + col2]); const float tmpx0 = ggml_cuda_cast(reinterpret_cast(&tmpx)[0]); const float tmpx1 = ggml_cuda_cast(reinterpret_cast(&tmpx)[1]); ggml_cuda_mad(sumf[j], tmpx0, tmpy.x); @@ -311,7 +316,7 @@ static __global__ void mul_mat_vec_f( } #pragma unroll for (int j = 0; j < ncols_dst; ++j) { - const float2 tmpy = y2[j*stride_col_y2 + col2]; + const float2 tmpy = ggml_cuda_cast(y2[j*stride_col_y2 + col2]); ggml_cuda_mad(sumf[j], tmpx.x, tmpy.x); ggml_cuda_mad(sumf[j], tmpx.y, tmpy.y); @@ -325,7 +330,7 @@ static __global__ void mul_mat_vec_f( } #endif } else if constexpr (std::is_same_v) { - const float2 * y2 = (const float2 *) y; + const T_y2 * y2 = (const T_y2 *) y; for (int col2 = tid; col2 < ncols2; col2 += block_size) { const float2 tmpx = mmvf_load_fp8x2(x, col2); float2 tmpx_gate = {}; @@ -336,7 +341,7 @@ static __global__ void mul_mat_vec_f( } #pragma unroll for (int j = 0; j < ncols_dst; ++j) { - const float2 tmpy = y2[j*stride_col_y2 + col2]; + const float2 tmpy = ggml_cuda_cast(y2[j*stride_col_y2 + col2]); ggml_cuda_mad(sumf[j], tmpx, tmpy); if constexpr (has_fusion) { @@ -439,9 +444,9 @@ static __global__ void mul_mat_vec_f( } } -template +template static void mul_mat_vec_f_switch_fusion( - const T * x, const float * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst, + const T * x, const T_y * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst, const int64_t ncols, const uint3 nchannels_y, const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst, const uint3 channel_ratio, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst, @@ -454,7 +459,7 @@ static void mul_mat_vec_f_switch_fusion( fusion.x_scale != nullptr || fusion.gate_scale != nullptr; if constexpr (ncols_dst == 1) { if (has_fusion) { - ggml_cuda_kernel_launch(mul_mat_vec_f, launch_params, + ggml_cuda_kernel_launch(mul_mat_vec_f, launch_params, x, y, ids, fusion, dst, ncols, nchannels_y, stride_row, stride_col_y, stride_col_dst, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, ids_stride); @@ -464,16 +469,16 @@ static void mul_mat_vec_f_switch_fusion( GGML_ASSERT(!has_fusion && "fusion only supported for ncols_dst=1"); - ggml_cuda_kernel_launch(mul_mat_vec_f, launch_params, + ggml_cuda_kernel_launch(mul_mat_vec_f, launch_params, x, y, ids, fusion, dst, ncols, nchannels_y, stride_row, stride_col_y, stride_col_dst, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, ids_stride); } -template +template void launch_mul_mat_vec_f_cuda( - const T * x, const float * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst, + const T * x, const T_y * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst, const int64_t ncols, const int64_t nrows, const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst, const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst, @@ -565,9 +570,9 @@ void launch_mul_mat_vec_f_cuda( } } -template +template static void mul_mat_vec_f_cuda_switch_ncols_dst( - const T * x, const float * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst, + const T * x, const T_y * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst, const int64_t ncols, const int64_t nrows, const int64_t ncols_dst, const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst, const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst, @@ -661,9 +666,9 @@ static void mul_mat_vec_f_cuda_switch_ncols_dst( } } -template +template static void mul_mat_vec_f_cuda( - const T * x, const float * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst, + const T * x, const T_y * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst, const int64_t ncols, const int64_t nrows, const int64_t ncols_dst, const int64_t stride_row, const int64_t stride_col_y, const int stride_col_dst, const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst, @@ -688,7 +693,9 @@ static void mul_mat_vec_f_cuda( void ggml_cuda_mul_mat_vec_f(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst, const ggml_cuda_mm_fusion_args_host * fusion) { - GGML_ASSERT( src1->type == GGML_TYPE_F32); + // a BF16 src1 only for BF16 and FP8 weights + GGML_ASSERT( src1->type == GGML_TYPE_F32 || + (src1->type == GGML_TYPE_BF16 && (src0->type == GGML_TYPE_BF16 || src0->type == GGML_TYPE_F8_E4M3))); GGML_ASSERT(!ids || ids->type == GGML_TYPE_I32); GGML_ASSERT( dst->type == GGML_TYPE_F32); @@ -790,12 +797,24 @@ void ggml_cuda_mul_mat_vec_f(ggml_backend_cuda_context & ctx, const ggml_tensor } break; case GGML_TYPE_BF16: { const nv_bfloat16 * src0_d = (const nv_bfloat16 *) src0->data; + if (src1->type == GGML_TYPE_BF16) { + mul_mat_vec_f_cuda(src0_d, (const nv_bfloat16 *) src1->data, ids_d, fusion_local, dst_d, ne00, ne01, ncols_dst, s01, + stride_col_y, stride_col_dst, ne02, nchannels_y, nchannels_dst, s02, stride_channel_y, stride_channel_dst, + ne03, ne3, s03, s13, s3, ids_stride, prec, ctx.stream()); + break; + } mul_mat_vec_f_cuda(src0_d, src1_d, ids_d, fusion_local, dst_d, ne00, ne01, ncols_dst, s01, stride_col_y, stride_col_dst, ne02, nchannels_y, nchannels_dst, s02, stride_channel_y, stride_channel_dst, ne03, ne3, s03, s13, s3, ids_stride, prec, ctx.stream()); } break; case GGML_TYPE_F8_E4M3: { const ggml_fp8_e4m3_t * src0_d = (const ggml_fp8_e4m3_t *) src0->data; + if (src1->type == GGML_TYPE_BF16) { + mul_mat_vec_f_cuda(src0_d, (const nv_bfloat16 *) src1->data, ids_d, fusion_local, dst_d, ne00, ne01, ncols_dst, s01, + stride_col_y, stride_col_dst, ne02, nchannels_y, nchannels_dst, s02, stride_channel_y, stride_channel_dst, + ne03, ne3, s03, s13, s3, ids_stride, prec, ctx.stream()); + break; + } mul_mat_vec_f_cuda(src0_d, src1_d, ids_d, fusion_local, dst_d, ne00, ne01, ncols_dst, s01, stride_col_y, stride_col_dst, ne02, nchannels_y, nchannels_dst, s02, stride_channel_y, stride_channel_dst, ne03, ne3, s03, s13, s3, ids_stride, prec, ctx.stream()); @@ -866,8 +885,8 @@ void ggml_cuda_op_mul_mat_vec_f( GGML_UNUSED_VARS(ctx, src1, dst, src1_ddq_i, src1_ncols, src1_padded_row_size); } -bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size, int64_t ne11) { - const ggml_type type = src0->type; +bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, ggml_type type_src1, int cc, int warp_size, int64_t ne11, bool mul_mat_id) { + const ggml_type type_src0 = src0->type; const int64_t * src0_ne = src0->ne; const size_t * src0_nb = src0->nb; @@ -875,7 +894,7 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size, return false; } - const size_t ts = ggml_type_size(type); + const size_t ts = ggml_type_size(type_src0); if (src0_nb[0] != ts) { return false; } @@ -884,7 +903,27 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size, return false; } - switch (type) { + // MMVF reads a BF16 src1 only for BF16 and FP8 weights + if (type_src1 == GGML_TYPE_BF16 && type_src0 != GGML_TYPE_BF16 && type_src0 != GGML_TYPE_F8_E4M3) { + return false; + } + + if (mul_mat_id) { + // FP8 experts on all GPUs, F32/F16/BF16 experts on AMD, and BF16 experts with a BF16 src1, which MMF can not read + // (with an F32 src1 NVIDIA takes MMF where it supports the experts, otherwise the sorted fallback) + switch (type_src0) { + case GGML_TYPE_F32: + case GGML_TYPE_F16: + case GGML_TYPE_BF16: + return ne11 <= MMVF_MAX_BATCH_SIZE && (GGML_CUDA_CC_IS_AMD(cc) || type_src1 == GGML_TYPE_BF16); + case GGML_TYPE_F8_E4M3: + return ne11 <= MMVF_MAX_BATCH_SIZE; + default: + return false; + } + } + + switch (type_src0) { case GGML_TYPE_F32: if (GGML_CUDA_CC_IS_NVIDIA(cc)) { if (ampere_mma_available(cc)) { @@ -905,7 +944,7 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size, if (GGML_CUDA_CC_IS_NVIDIA(cc)) { const bool src0_small = (src0_ne[1] <= 512 || src0_ne[2]*src0_ne[3] == 1); // MMF needs full row tiles, for other row counts MMVF still beats cuBLAS at small batch size - if (src0_small && !ggml_cuda_should_use_mmf(type, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) { + if (src0_small && !ggml_cuda_should_use_mmf(type_src0, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) { return ne11 <= MMVF_MAX_BATCH_SIZE; } if (ampere_mma_available(cc)) { @@ -919,7 +958,7 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size, } return ne11 <= MMVF_MAX_BATCH_SIZE; } else if (GGML_CUDA_CC_IS_AMD(cc)) { - if (GGML_CUDA_CC_IS_RDNA(cc) && !ggml_cuda_should_use_mmf(type, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) { + if (GGML_CUDA_CC_IS_RDNA(cc) && !ggml_cuda_should_use_mmf(type_src0, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) { return ne11 <= MMVF_MAX_BATCH_SIZE; } if (fp16_mma_hardware_available(cc)) { @@ -938,7 +977,7 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size, if (GGML_CUDA_CC_IS_NVIDIA(cc)) { const bool src0_small = (src0_ne[1] <= 512 || src0_ne[2]*src0_ne[3] == 1); // MMF needs full row tiles, for other row counts MMVF still beats cuBLAS at small batch size - if (src0_small && !ggml_cuda_should_use_mmf(type, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) { + if (src0_small && !ggml_cuda_should_use_mmf(type_src0, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) { return ne11 <= MMVF_MAX_BATCH_SIZE; } // MMF tiles 32 rows per block, so a matrix of few rows leaves most SMs idle while MMVF runs a block @@ -964,7 +1003,7 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size, } return ne11 <= MMVF_MAX_BATCH_SIZE; } else if (GGML_CUDA_CC_IS_AMD(cc)) { - if (GGML_CUDA_CC_IS_RDNA(cc) && !ggml_cuda_should_use_mmf(type, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) { + if (GGML_CUDA_CC_IS_RDNA(cc) && !ggml_cuda_should_use_mmf(type_src0, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) { return ne11 <= MMVF_MAX_BATCH_SIZE; } if (bf16_mma_hardware_available(cc)) { diff --git a/ggml/src/ggml-cuda/mmvf.cuh b/ggml/src/ggml-cuda/mmvf.cuh index 5a2477b079b2..c57c265ae6b9 100644 --- a/ggml/src/ggml-cuda/mmvf.cuh +++ b/ggml/src/ggml-cuda/mmvf.cuh @@ -11,4 +11,4 @@ void ggml_cuda_op_mul_mat_vec_f( const char * src1_ddq_i, float * dst_dd_i, const int64_t row_low, const int64_t row_high, const int64_t src1_ncols, const int64_t src1_padded_row_size, cudaStream_t stream); -bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size, int64_t ne11); +bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, ggml_type type_src1, int cc, int warp_size, int64_t ne11, bool mul_mat_id); diff --git a/ggml/src/ggml-cuda/mmvq.cu b/ggml/src/ggml-cuda/mmvq.cu index 3549fbe3215a..5fa37ae77d6a 100644 --- a/ggml/src/ggml-cuda/mmvq.cu +++ b/ggml/src/ggml-cuda/mmvq.cu @@ -1538,7 +1538,7 @@ static void mul_mat_vec_q_switch_type( void ggml_cuda_mul_mat_vec_q( ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst, const ggml_cuda_mm_fusion_args_host * fusion) { - GGML_ASSERT( src1->type == GGML_TYPE_F32); + GGML_ASSERT( src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16); GGML_ASSERT( dst->type == GGML_TYPE_F32); GGML_ASSERT(!ids || ids->type == GGML_TYPE_I32); // Optional, used for batched GGML_MUL_MAT_ID. @@ -1557,7 +1557,6 @@ void ggml_cuda_mul_mat_vec_q( GGML_ASSERT(!ids || ne12 <= MMVQ_MAX_BATCH_SIZE); - const float * src1_d = (const float *) src1->data; const int32_t * ids_d = ids ? (const int32_t *) ids->data : nullptr; float * dst_d = (float *) dst->data; @@ -1637,7 +1636,7 @@ void ggml_cuda_mul_mat_vec_q( const int64_t s11 = src1->nb[1] / ts_src1; const int64_t s12 = src1->nb[2] / ts_src1; const int64_t s13 = src1->nb[3] / ts_src1; - quantize_row_q8_1_cuda(src1_d, src1_q8_1.get(), ne10, s11, s12, s13, ne10_padded, ne11, ne12, ne13, stream); + quantize_row_q8_1_cuda(src1->data, src1->type, src1_q8_1.get(), ne10, s11, s12, s13, ne10_padded, ne11, ne12, ne13, stream); } const int64_t s01 = src0->nb[1] / ts_src0; diff --git a/ggml/src/ggml-cuda/norm.cu b/ggml/src/ggml-cuda/norm.cu index 95c3b0a0e941..02cca5afdc7e 100644 --- a/ggml/src/ggml-cuda/norm.cu +++ b/ggml/src/ggml-cuda/norm.cu @@ -399,6 +399,54 @@ static __global__ void l2_norm_f32( } } +// l2_norm with an optional per-column weight before it and SCALE (+ an optional MUL by a per-channel/sample factor) after it, +// with the reduction of l2_norm_f32 +template +static __global__ void l2_clip_f32( + const float * x, const float * w, const float * f, float * dst, const int ncols, const int nchannels, const int nsamples, + const int64_t stride_row, const int64_t stride_channel, const int64_t stride_sample, + const int64_t w_stride_row, const int64_t w_stride_channel, const int64_t w_stride_sample, + const int64_t f_stride_channel, const int64_t f_stride_sample, const float eps, const float scale, const float bias) { + ggml_cuda_pdl_lc(); + const int nrows = gridDim.x; + const int row = blockIdx.x; + const int tid = threadIdx.x; + + extern __shared__ float s_sum[]; + + ggml_cuda_pdl_sync(); + + for (int sample = blockIdx.z; sample < nsamples; sample += gridDim.z) { + for (int channel = blockIdx.y; channel < nchannels; channel += gridDim.y) { + const float * xc = x + sample*stride_sample + channel*stride_channel + row*stride_row; + const float * wc = has_w ? w + sample*w_stride_sample + channel*w_stride_channel + row*w_stride_row : nullptr; + float * dstc = dst + ((sample*nchannels + channel)*nrows + row)*ncols; + + float tmp = 0.0f; + + for (int col = tid; col < ncols; col += block_size) { + const float xi = has_w ? xc[col]*wc[col] : xc[col]; + tmp += xi * xi; + } + + tmp = block_reduce(tmp, s_sum); + + const float l2 = rsqrtf(fmaxf(tmp, eps * eps)); + const float fc = has_f ? f[sample*f_stride_sample + channel*f_stride_channel] : 1.0f; + + for (int col = tid; col < ncols; col += block_size) { + const float xi = has_w ? xc[col]*wc[col] : xc[col]; + const float yi = scale*(l2*xi) + bias; + dstc[col] = has_f ? yi*fc : yi; + } + + if constexpr (block_size > WARP_SIZE) { + __syncthreads(); + } + } + } +} + template static void norm_f32_cuda(const float * x, float * dst, @@ -623,6 +671,71 @@ static void l2_norm_f32_cuda( } } +template +static void l2_clip_f32_cuda( + const float * x, const float * w, const float * f, float * dst, const int ncols, const int nrows, const int nchannels, const int nsamples, + const int64_t stride_row, const int64_t stride_channel, const int64_t stride_sample, + const int64_t w_stride_row, const int64_t w_stride_channel, const int64_t w_stride_sample, + const int64_t f_stride_channel, const int64_t f_stride_sample, const float eps, const float scale, const float bias, cudaStream_t stream) { + const dim3 blocks_num(nrows, MIN(nchannels, UINT16_MAX), MIN(nsamples, UINT16_MAX)); + if (ncols < 1024) { + const ggml_cuda_kernel_launch_params params(blocks_num, dim3(WARP_SIZE, 1, 1), 0, stream); + ggml_cuda_kernel_launch(l2_clip_f32, params, x, w, f, dst, ncols, nchannels, nsamples, + stride_row, stride_channel, stride_sample, w_stride_row, w_stride_channel, w_stride_sample, + f_stride_channel, f_stride_sample, eps, scale, bias); + } else { + const ggml_cuda_kernel_launch_params params(blocks_num, dim3(1024, 1, 1), 32 * sizeof(float), stream); + ggml_cuda_kernel_launch(l2_clip_f32<1024, has_w, has_f>, params, x, w, f, dst, ncols, nchannels, nsamples, + stride_row, stride_channel, stride_sample, w_stride_row, w_stride_channel, w_stride_sample, + f_stride_channel, f_stride_sample, eps, scale, bias); + } +} + +void ggml_cuda_op_l2_clip(ggml_backend_cuda_context & ctx, const ggml_tensor * x, const ggml_tensor * w, const ggml_tensor * l2_norm, + const ggml_tensor * scale, const ggml_tensor * f, ggml_tensor * dst) { + GGML_ASSERT(x->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32 && x->nb[0] == sizeof(float)); + GGML_ASSERT(ggml_is_contiguous(dst) && ggml_are_same_shape(x, dst)); + + GGML_TENSOR_LOCALS(int64_t, ne0, x, ne); + GGML_TENSOR_LOCALS(size_t, nb0, x, nb); + + // broadcast dimensions of w and f have a stride of 0 + auto bcast_stride = [](const ggml_tensor * t, int dim) -> int64_t { + return t->ne[dim] == 1 ? 0 : (int64_t) (t->nb[dim]/sizeof(float)); + }; + + const int64_t ws1 = w ? bcast_stride(w, 1) : 0; + const int64_t ws2 = w ? bcast_stride(w, 2) : 0; + const int64_t ws3 = w ? bcast_stride(w, 3) : 0; + const int64_t fs2 = f ? bcast_stride(f, 2) : 0; + const int64_t fs3 = f ? bcast_stride(f, 3) : 0; + + const float * x_d = (const float *) x->data; + const float * w_d = w ? (const float *) w->data : nullptr; + const float * f_d = f ? (const float *) f->data : nullptr; + float * d_d = (float *) dst->data; + + const float eps = ggml_get_op_params_f32(l2_norm, 0); + const float s = ggml_get_op_params_f32(scale, 0); + const float b = ggml_get_op_params_f32(scale, 1); + + const int64_t s01 = nb01/sizeof(float); + const int64_t s02 = nb02/sizeof(float); + const int64_t s03 = nb03/sizeof(float); + + cudaStream_t stream = ctx.stream(); + + if (w && f) { + l2_clip_f32_cuda(x_d, w_d, f_d, d_d, ne00, ne01, ne02, ne03, s01, s02, s03, ws1, ws2, ws3, fs2, fs3, eps, s, b, stream); + } else if (w) { + l2_clip_f32_cuda(x_d, w_d, f_d, d_d, ne00, ne01, ne02, ne03, s01, s02, s03, ws1, ws2, ws3, fs2, fs3, eps, s, b, stream); + } else if (f) { + l2_clip_f32_cuda(x_d, w_d, f_d, d_d, ne00, ne01, ne02, ne03, s01, s02, s03, ws1, ws2, ws3, fs2, fs3, eps, s, b, stream); + } else { + l2_clip_f32_cuda(x_d, w_d, f_d, d_d, ne00, ne01, ne02, ne03, s01, s02, s03, ws1, ws2, ws3, fs2, fs3, eps, s, b, stream); + } +} + void ggml_cuda_op_norm(ggml_backend_cuda_context & ctx, ggml_tensor * dst, ggml_tensor * mul, ggml_tensor * add) { const ggml_tensor * src0 = dst->src[0]; const float * src0_d = (const float *) src0->data; diff --git a/ggml/src/ggml-cuda/norm.cuh b/ggml/src/ggml-cuda/norm.cuh index 741a1d1ae6a9..786fd1b644f6 100644 --- a/ggml/src/ggml-cuda/norm.cuh +++ b/ggml/src/ggml-cuda/norm.cuh @@ -21,3 +21,7 @@ void ggml_cuda_op_rms_norm_fused_add(ggml_backend_cuda_context & ctx, void ggml_cuda_op_rms_norm_back(ggml_backend_cuda_context & ctx, ggml_tensor * dst); void ggml_cuda_op_l2_norm(ggml_backend_cuda_context & ctx, ggml_tensor * dst); + +// [MUL by w ->] L2_NORM -> SCALE [-> MUL by f], w broadcasts over the rows, f is one value per channel/sample +void ggml_cuda_op_l2_clip(ggml_backend_cuda_context & ctx, const ggml_tensor * x, const ggml_tensor * w, const ggml_tensor * l2_norm, + const ggml_tensor * scale, const ggml_tensor * f, ggml_tensor * dst); diff --git a/ggml/src/ggml-cuda/quantize.cu b/ggml/src/ggml-cuda/quantize.cu index 23936c305610..5f4d767503ce 100644 --- a/ggml/src/ggml-cuda/quantize.cu +++ b/ggml/src/ggml-cuda/quantize.cu @@ -1,6 +1,21 @@ #include "quantize.cuh" +#include "convert.cuh" #include +// 4 consecutive values of x as float4, x + 4*i is aligned to 4 values +template +static __device__ __forceinline__ float4 quantize_load4(const src_t * x, const int64_t i) { + if constexpr (std::is_same_v) { + __align__(8) nv_bfloat162 v[2]; + ggml_cuda_memcpy_1(v, x + 4*i); + const float2 lo = ggml_cuda_cast(v[0]); + const float2 hi = ggml_cuda_cast(v[1]); + return make_float4(lo.x, lo.y, hi.x, hi.y); + } else { + return ((const float4 *) x)[i]; + } +} + #if defined(BLACKWELL_MMA_AVAILABLE) // this maps to 256-bit loads in PTX on supported devices, // and otherwise falls back to 2 128-bit loads @@ -9,6 +24,23 @@ struct __builtin_align__(32) float8 { float p; float q; float r; float s; }; +// 8 consecutive values of x as float8, x is aligned to 8 values +// for float it returns a reference like a direct load, a copy changes the register allocation of the kernels +template +static __device__ __forceinline__ decltype(auto) quantize_load8(const src_t * x) { + if constexpr (std::is_same_v) { + __align__(16) nv_bfloat162 v[4]; + ggml_cuda_memcpy_1(v, x); + const float2 a = ggml_cuda_cast(v[0]); + const float2 b = ggml_cuda_cast(v[1]); + const float2 c = ggml_cuda_cast(v[2]); + const float2 d = ggml_cuda_cast(v[3]); + return float8{a.x, a.y, b.x, b.y, c.x, c.y, d.x, d.y}; + } else { + return reinterpret_cast(x)[0]; + } +} + #if CUDART_VERSION >= 12080 static __device__ __forceinline__ float nvfp4_native_scale_error( const float vals[QK_NVFP4_SUB], const float inv_col_scale, const float inv_scale, const float scale) { @@ -50,13 +82,14 @@ static __device__ __forceinline__ float nvfp4_native_scale_error( #endif // CUDART_VERSION >= 12080 #endif // defined(BLACKWELL_MMA_AVAILABLE) +template __launch_bounds__(CUDA_QUANTIZE_BLOCK_SIZE, 1) static __global__ void quantize_q8_1( - const float * x_ptr, void * vy_ptr, + const src_t * x_ptr, void * vy_ptr, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03, const int64_t ne0, const uint32_t ne1, const uint3 ne2) { ggml_cuda_pdl_lc(); - const float * GGML_CUDA_RESTRICT x = x_ptr; + const src_t * GGML_CUDA_RESTRICT x = x_ptr; void * GGML_CUDA_RESTRICT vy = vy_ptr; const int64_t i0 = (int64_t)blockDim.x*blockIdx.x + threadIdx.x; @@ -81,7 +114,7 @@ static __global__ void quantize_q8_1( const int64_t iqs = i_cont % QK8_1; // quant index ggml_cuda_pdl_sync(); - const float xi = i0 < ne00 ? x[i03*s03 + i02*s02 + i01*s01 + i00] : 0.0f; + const float xi = i0 < ne00 ? ggml_cuda_cast(x[i03*s03 + i02*s02 + i01*s01 + i00]) : 0.0f; float amax = fabsf(xi); amax = warp_reduce_max(amax); @@ -124,9 +157,9 @@ __device__ __forceinline__ uint8_t compute_e8m0_scale(float amax) { } // scatter: grid over tokens, quantize once, write to all the token's compact rows -template +template static __global__ void quantize_mmq_nvfp4( - const float * __restrict__ x, const int32_t * __restrict__ ids, void * __restrict__ vy, float * __restrict__ scale, + const src_t * __restrict__ x, const int32_t * __restrict__ ids, void * __restrict__ vy, float * __restrict__ scale, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03, const int64_t ne0, const int64_t ne1, const int64_t ne2, const int n_expert_used) { #if defined(BLACKWELL_MMA_AVAILABLE) @@ -140,13 +173,12 @@ static __global__ void quantize_mmq_nvfp4( const int64_t i01 = ids ? ids[blockIdx.x] : blockIdx.x; base_idx = i3 * s03 + i2 * s02 + i01 * s01; } - const float * __restrict__ x_row = x + base_idx; + const src_t * __restrict__ x_row = x + base_idx; float amax = 0.0f; if constexpr (use_aligned_float8) { for (int64_t i0 = 8 * threadIdx.x; i0 < ne00; i0 += 8 * blockDim.x) { - const float * x_base = x_row + i0; - const float8 v = reinterpret_cast(x_base)[0]; + const float8 v = quantize_load8(x_row + i0); amax = fmaxf(amax, fabsf(v.x)); amax = fmaxf(amax, fabsf(v.y)); amax = fmaxf(amax, fabsf(v.z)); @@ -158,7 +190,7 @@ static __global__ void quantize_mmq_nvfp4( } } else { for (int64_t i0 = threadIdx.x; i0 < ne00; i0 += blockDim.x) { - amax = fmaxf(amax, fabsf(x_row[i0])); + amax = fmaxf(amax, fabsf(ggml_cuda_cast(x_row[i0]))); } } @@ -204,9 +236,9 @@ static __global__ void quantize_mmq_nvfp4( float vals[QK_NVFP4_SUB]; if constexpr (use_aligned_float8) { - const float * x_base = x_row + i0_base; - const float8 v0 = i0_base + 7 < ne00 ? reinterpret_cast(x_base)[0] : float8{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; - const float8 v1 = i0_base + 15 < ne00 ? reinterpret_cast(x_base + 8)[0] : float8{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; + const src_t * x_base = x_row + i0_base; + const float8 v0 = i0_base + 7 < ne00 ? quantize_load8(x_base) : float8{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; + const float8 v1 = i0_base + 15 < ne00 ? quantize_load8(x_base + 8) : float8{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; vals[0] = v0.x; vals[1] = v0.y; vals[2] = v0.z; vals[3] = v0.w; vals[4] = v0.p; vals[5] = v0.q; vals[6] = v0.r; vals[7] = v0.s; vals[8] = v1.x; vals[9] = v1.y; vals[10] = v1.z; vals[11] = v1.w; @@ -215,7 +247,7 @@ static __global__ void quantize_mmq_nvfp4( #pragma unroll for (int k = 0; k < QK_NVFP4_SUB; ++k) { const int64_t i00 = i0_base + k; - vals[k] = i00 < ne00 ? x_row[i00] : 0.0f; + vals[k] = i00 < ne00 ? ggml_cuda_cast(x_row[i00]) : 0.0f; } } @@ -333,8 +365,8 @@ static __global__ void quantize_mmq_nvfp4( // quantize values in the format mxfp4 is stored which is interleaved nibbles // i.e. a block a0-a31 is represented as a0a16,a1a17 ...a15a31 // scatter: grid over tokens, quantize once, write to all the token's compact rows -template -static __global__ void quantize_mmq_mxfp4(const float * __restrict__ x, +template +static __global__ void quantize_mmq_mxfp4(const src_t * __restrict__ x, const int32_t * __restrict__ ids, void * __restrict__ vy, const int64_t ne00, @@ -384,7 +416,7 @@ static __global__ void quantize_mmq_mxfp4(const float * __restrict__ x, #pragma unroll for (int b = 0; b < 2; ++b) { const int64_t i0 = warp_start_offset + b * vals_per_scale + lane_id_32; - const float xi = (i0 < ne00) ? x[base_pos + i0] : 0.0f; + const float xi = (i0 < ne00) ? ggml_cuda_cast(x[base_pos + i0]) : 0.0f; float amax = fabsf(xi); #pragma unroll @@ -453,9 +485,9 @@ static __global__ void quantize_mmq_mxfp4(const float * __restrict__ x, } // scatter: grid over tokens, quantize once, write to all the token's compact rows -template +template static __global__ void quantize_mmq_q8_1( - const float * __restrict__ x, const int32_t * __restrict__ ids, void * __restrict__ vy, + const src_t * __restrict__ x, const int32_t * __restrict__ ids, void * __restrict__ vy, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03, const int64_t ne0, const int ne1, const int ne2, const int n_expert_used) { @@ -481,14 +513,13 @@ static __global__ void quantize_mmq_q8_1( base_idx = i3*s03 + i2*s02 + i01*s01; } - const float4 * x4 = (const float4 *) x; block_q8_1_mmq * y = (block_q8_1_mmq *) vy; const int64_t k_block = i0 / QK8_1_MMQ; // column block in the channel const int64_t iqs = i0 % QK8_1_MMQ; // quant index in block // Load 4 floats per thread and calculate max. abs. value between them: - const float4 xi = i0 < ne00 ? x4[(base_idx + i00)/4] : make_float4(0.0f, 0.0f, 0.0f, 0.0f); + const float4 xi = i0 < ne00 ? quantize_load4(x, (base_idx + i00)/4) : make_float4(0.0f, 0.0f, 0.0f, 0.0f); float amax = fabsf(xi.x); amax = fmaxf(amax, fabsf(xi.y)); amax = fmaxf(amax, fabsf(xi.z)); @@ -556,8 +587,20 @@ static __global__ void quantize_mmq_q8_1( GGML_UNUSED(n_expert_used); } -void quantize_row_q8_1_cuda( - const float * x, void * vy, +// calls launch with x as const float * or const nv_bfloat16 *, the src1 types that the quantize kernels read +template +static void quantize_launch_typed(const void * x, const ggml_type type_src1, const F & launch) { + if (type_src1 == GGML_TYPE_BF16) { + launch((const nv_bfloat16 *) x); + } else { + GGML_ASSERT(type_src1 == GGML_TYPE_F32); + launch((const float *) x); + } +} + +template +static void quantize_row_q8_1_cuda( + const src_t * x, void * vy, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03, const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) { GGML_ASSERT(ne0 % QK8_1 == 0); @@ -568,11 +611,21 @@ void quantize_row_q8_1_cuda( const dim3 num_blocks(block_num_x, ne1, ne2*ne3); const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE, 1, 1); const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(num_blocks, block_size, 0, stream); - ggml_cuda_kernel_launch(quantize_q8_1, launch_params, x, vy, ne00, s01, s02, s03, ne0, ne1, ne2_fastdiv); + ggml_cuda_kernel_launch(quantize_q8_1, launch_params, x, vy, ne00, s01, s02, s03, ne0, ne1, ne2_fastdiv); } -void quantize_mmq_q8_1_cuda( - const float * x, const int32_t * ids, void * vy, const ggml_type type_src0, +void quantize_row_q8_1_cuda( + const void * x, const ggml_type type_src1, void * vy, + const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03, + const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) { + quantize_launch_typed(x, type_src1, [&](auto * x_t) { + quantize_row_q8_1_cuda(x_t, vy, ne00, s01, s02, s03, ne0, ne1, ne2, ne3, stream); + }); +} + +template +static void quantize_mmq_q8_1_cuda( + const src_t * x, const int32_t * ids, void * vy, const ggml_type type_src0, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03, const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) { GGML_ASSERT(ne00 % 4 == 0); @@ -584,15 +637,15 @@ void quantize_mmq_q8_1_cuda( const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1); switch (mmq_get_q8_1_ds_layout(type_src0)) { case MMQ_Q8_1_DS_LAYOUT_D4: - quantize_mmq_q8_1 + quantize_mmq_q8_1 <<>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0); break; case MMQ_Q8_1_DS_LAYOUT_DS4: - quantize_mmq_q8_1 + quantize_mmq_q8_1 <<>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0); break; case MMQ_Q8_1_DS_LAYOUT_D2S6: - quantize_mmq_q8_1 + quantize_mmq_q8_1 <<>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0); break; default: @@ -600,6 +653,15 @@ void quantize_mmq_q8_1_cuda( } } +void quantize_mmq_q8_1_cuda( + const void * x, const ggml_type type_src1, const int32_t * ids, void * vy, const ggml_type type_src0, + const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03, + const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) { + quantize_launch_typed(x, type_src1, [&](auto * x_t) { + quantize_mmq_q8_1_cuda(x_t, ids, vy, type_src0, ne00, s01, s02, s03, ne0, ne1, ne2, ne3, stream); + }); +} + // Stores the 4 values xi of a thread, values [iu, iu + 4) of column g in a unit of 256 values, in the column group yg of the unit, see quantize.cuh for the layout. template static __device__ __forceinline__ void quantize_mmq_few_store(const float4 xi, int4 * yg, const int iu, const int g) { @@ -635,12 +697,12 @@ static __device__ __forceinline__ void quantize_mmq_few_store(const float4 xi, i } // Each thread quantizes 4 values of one column, see quantize.cuh for the layout. -template +template static __global__ void quantize_mmq_few_q8_1( - const float * x_ptr, void * vy_ptr, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03, + const src_t * x_ptr, void * vy_ptr, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03, const int ne1, const int ne2) { ggml_cuda_pdl_lc(); - const float * GGML_CUDA_RESTRICT x = x_ptr; + const src_t * GGML_CUDA_RESTRICT x = x_ptr; int4 * GGML_CUDA_RESTRICT vy = (int4 *) vy_ptr; const int64_t i0 = ((int64_t)blockDim.x*blockIdx.y + threadIdx.x)*4; @@ -651,7 +713,7 @@ static __global__ void quantize_mmq_few_q8_1( const int64_t i2 = blockIdx.z % ne2; const int64_t i3 = blockIdx.z / ne2; - const float4 xi = (int) blockIdx.x < ne1 ? *(const float4 *) (x + i3*s03 + i2*s02 + blockIdx.x*s01 + i0) : make_float4(0.0f, 0.0f, 0.0f, 0.0f); + const float4 xi = (int) blockIdx.x < ne1 ? quantize_load4(x + i3*s03 + i2*s02 + blockIdx.x*s01 + i0, 0) : make_float4(0.0f, 0.0f, 0.0f, 0.0f); const int g = blockIdx.x % MMQ_FEW_NCOLS; // column in group int4 * yg = vy + ((blockIdx.z*(ne00/QK_K) + i0/QK_K)*(gridDim.x/MMQ_FEW_NCOLS) + blockIdx.x/MMQ_FEW_NCOLS)*MMQ_FEW_Q8_1_INT4; @@ -660,9 +722,9 @@ static __global__ void quantize_mmq_few_q8_1( // MUL_MAT_ID: block x is the (token, slot) entry, ids are as in mm_ids_helper. Each block finds the pair of its entry in shared memory, block (0, 0) also writes all pairs. // Entry rank r = number of earlier tokens with the same expert, pair = first pair of the expert + r/MMQ_FEW_NCOLS, column = r % MMQ_FEW_NCOLS. -template +template static __global__ void quantize_mmq_few_id_q8_1( - const float * x_ptr, const int32_t * ids, void * vy_ptr, int * pairs, const int64_t ne00, const int64_t s11, const int64_t s12, + const src_t * x_ptr, const int32_t * ids, void * vy_ptr, int * pairs, const int64_t ne00, const int64_t s11, const int64_t s12, const int ne11, const int n_experts, const int n_expert_used, const int64_t si1, const int npairs_max) { // per expert: bit t set if token t uses it and the index of its first pair; then the total number of pairs extern __shared__ unsigned int data_mmq_few_id[]; @@ -671,7 +733,7 @@ static __global__ void quantize_mmq_few_id_q8_1( int & npairs = pair0[n_experts]; ggml_cuda_pdl_lc(); - const float * GGML_CUDA_RESTRICT x = x_ptr; + const src_t * GGML_CUDA_RESTRICT x = x_ptr; int4 * GGML_CUDA_RESTRICT vy = (int4 *) vy_ptr; ggml_cuda_pdl_sync(); @@ -741,15 +803,16 @@ static __global__ void quantize_mmq_few_id_q8_1( } const int it = blockIdx.x / n_expert_used; const int is = blockIdx.x % n_expert_used; - const float4 xi = *(const float4 *) (x + it*s12 + (is % ne11)*s11 + i0); + const float4 xi = quantize_load4(x + it*s12 + (is % ne11)*s11 + i0, 0); const int r = rank(blockIdx.x, e); int4 * yg = vy + (int64_t(pair0[e] + r/MMQ_FEW_NCOLS)*(ne00/QK_K) + i0/QK_K)*MMQ_FEW_Q8_1_INT4; quantize_mmq_few_store(xi, yg, i0 % QK_K, r % MMQ_FEW_NCOLS); } -void quantize_mmq_few_q8_1_cuda( - const float * x, void * vy, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03, +template +static void quantize_mmq_few_q8_1_cuda( + const src_t * x, void * vy, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) { GGML_ASSERT(ne00 % QK_K == 0); @@ -759,11 +822,11 @@ void quantize_mmq_few_q8_1_cuda( const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(num_blocks, block_size, 0, stream); switch (ds_layout) { case MMQ_Q8_1_DS_LAYOUT_D4: - ggml_cuda_kernel_launch(quantize_mmq_few_q8_1, launch_params, + ggml_cuda_kernel_launch(quantize_mmq_few_q8_1, launch_params, x, vy, ne00, s01, s02, s03, (int) ne1, (int) ne2); break; case MMQ_Q8_1_DS_LAYOUT_DS4: - ggml_cuda_kernel_launch(quantize_mmq_few_q8_1, launch_params, + ggml_cuda_kernel_launch(quantize_mmq_few_q8_1, launch_params, x, vy, ne00, s01, s02, s03, (int) ne1, (int) ne2); break; default: @@ -771,8 +834,17 @@ void quantize_mmq_few_q8_1_cuda( } } -void quantize_mmq_few_id_q8_1_cuda( - const float * x, const int32_t * ids, void * vy, int * pairs, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s11, const int64_t s12, +void quantize_mmq_few_q8_1_cuda( + const void * x, const ggml_type type_src1, void * vy, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03, + const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) { + quantize_launch_typed(x, type_src1, [&](auto * x_t) { + quantize_mmq_few_q8_1_cuda(x_t, vy, ds_layout, ne00, s01, s02, s03, ne1, ne2, ne3, stream); + }); +} + +template +static void quantize_mmq_few_id_q8_1_cuda( + const src_t * x, const int32_t * ids, void * vy, int * pairs, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s11, const int64_t s12, const int64_t ne11, const int64_t n_experts, const int64_t n_expert_used, const int64_t n_tokens, const int64_t si1, const int64_t npairs_max, cudaStream_t stream) { GGML_ASSERT(ne00 % QK_K == 0); GGML_ASSERT(n_tokens <= 32); // one bit per token @@ -785,11 +857,11 @@ void quantize_mmq_few_id_q8_1_cuda( const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(num_blocks, block_size, nbytes_shared, stream); switch (ds_layout) { case MMQ_Q8_1_DS_LAYOUT_D4: - ggml_cuda_kernel_launch(quantize_mmq_few_id_q8_1, launch_params, + ggml_cuda_kernel_launch(quantize_mmq_few_id_q8_1, launch_params, x, ids, vy, pairs, ne00, s11, s12, (int) ne11, (int) n_experts, (int) n_expert_used, si1, (int) npairs_max); break; case MMQ_Q8_1_DS_LAYOUT_DS4: - ggml_cuda_kernel_launch(quantize_mmq_few_id_q8_1, launch_params, + ggml_cuda_kernel_launch(quantize_mmq_few_id_q8_1, launch_params, x, ids, vy, pairs, ne00, s11, s12, (int) ne11, (int) n_experts, (int) n_expert_used, si1, (int) npairs_max); break; default: @@ -797,9 +869,18 @@ void quantize_mmq_few_id_q8_1_cuda( } } +void quantize_mmq_few_id_q8_1_cuda( + const void * x, const ggml_type type_src1, const int32_t * ids, void * vy, int * pairs, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s11, const int64_t s12, + const int64_t ne11, const int64_t n_experts, const int64_t n_expert_used, const int64_t n_tokens, const int64_t si1, const int64_t npairs_max, cudaStream_t stream) { + quantize_launch_typed(x, type_src1, [&](auto * x_t) { + quantize_mmq_few_id_q8_1_cuda(x_t, ids, vy, pairs, ds_layout, ne00, s11, s12, ne11, n_experts, n_expert_used, n_tokens, si1, npairs_max, stream); + }); +} + // scatter=true reuses the quant kernel: grid over tokens, ids = inverse map (token slot -> compact row) -void quantize_scatter_mmq_q8_1_cuda( - const float * x, const int32_t * ids_src1_inv, void * vy, const ggml_type type_src0, +template +static void quantize_scatter_mmq_q8_1_cuda( + const src_t * x, const int32_t * ids_src1_inv, void * vy, const ggml_type type_src0, const int64_t ne00, const int64_t stride_token, const int64_t ne0, const int64_t n_tokens, const int64_t nrows_dst, const int n_expert_used, cudaStream_t stream) { GGML_ASSERT(ne00 % 4 == 0); @@ -810,15 +891,15 @@ void quantize_scatter_mmq_q8_1_cuda( const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1); switch (mmq_get_q8_1_ds_layout(type_src0)) { case MMQ_Q8_1_DS_LAYOUT_D4: - quantize_mmq_q8_1<<>>( + quantize_mmq_q8_1<<>>( x, ids_src1_inv, vy, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/(int) nrows_dst, /*ne2=*/1, n_expert_used); break; case MMQ_Q8_1_DS_LAYOUT_DS4: - quantize_mmq_q8_1<<>>( + quantize_mmq_q8_1<<>>( x, ids_src1_inv, vy, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/(int) nrows_dst, /*ne2=*/1, n_expert_used); break; case MMQ_Q8_1_DS_LAYOUT_D2S6: - quantize_mmq_q8_1<<>>( + quantize_mmq_q8_1<<>>( x, ids_src1_inv, vy, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/(int) nrows_dst, /*ne2=*/1, n_expert_used); break; default: @@ -826,9 +907,19 @@ void quantize_scatter_mmq_q8_1_cuda( } } +void quantize_scatter_mmq_q8_1_cuda( + const void * x, const ggml_type type_src1, const int32_t * ids_src1_inv, void * vy, const ggml_type type_src0, + const int64_t ne00, const int64_t stride_token, const int64_t ne0, + const int64_t n_tokens, const int64_t nrows_dst, const int n_expert_used, cudaStream_t stream) { + quantize_launch_typed(x, type_src1, [&](auto * x_t) { + quantize_scatter_mmq_q8_1_cuda(x_t, ids_src1_inv, vy, type_src0, ne00, stride_token, ne0, n_tokens, nrows_dst, n_expert_used, stream); + }); +} + // scatter=true reuses the quant kernels: grid over tokens, ids = inverse map (token slot -> compact row) -void quantize_scatter_mmq_fp4_cuda( - const float * x, const int32_t * ids_src1_inv, void * vy, float * scale, const ggml_type type_src0, const bool use_aligned_float8, +template +static void quantize_scatter_mmq_fp4_cuda( + const src_t * x, const int32_t * ids_src1_inv, void * vy, float * scale, const ggml_type type_src0, const bool use_aligned_float8, const int64_t ne00, const int64_t stride_token, const int64_t ne0, const int64_t n_tokens, const int64_t nrows_dst, const int n_expert_used, cudaStream_t stream) { GGML_ASSERT(ne0 > 0); @@ -838,10 +929,10 @@ void quantize_scatter_mmq_fp4_cuda( const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1); const dim3 num_blocks(n_tokens, 1, 1); if (use_aligned_float8) { - quantize_mmq_nvfp4<<>>( + quantize_mmq_nvfp4<<>>( x, ids_src1_inv, vy, scale, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/nrows_dst, /*ne2=*/1, n_expert_used); } else { - quantize_mmq_nvfp4<<>>( + quantize_mmq_nvfp4<<>>( x, ids_src1_inv, vy, scale, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/nrows_dst, /*ne2=*/1, n_expert_used); } } else { @@ -851,13 +942,24 @@ void quantize_scatter_mmq_fp4_cuda( const int64_t block_num_y = (ne0 + vals_per_block - 1) / vals_per_block; const dim3 block_size(WARP_SIZE, nwarps, 1); const dim3 num_blocks(n_tokens, block_num_y, 1); - quantize_mmq_mxfp4<<>>( + quantize_mmq_mxfp4<<>>( x, ids_src1_inv, vy, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/(int) nrows_dst, /*ne2=*/1, n_expert_used); } } -void quantize_mmq_fp4_cuda( - const float * x, const int32_t * ids, void * vy, float * scale, const ggml_type type_src0, const bool use_aligned_float8, +void quantize_scatter_mmq_fp4_cuda( + const void * x, const ggml_type type_src1, const int32_t * ids_src1_inv, void * vy, float * scale, const ggml_type type_src0, + const bool use_aligned_float8, const int64_t ne00, const int64_t stride_token, const int64_t ne0, + const int64_t n_tokens, const int64_t nrows_dst, const int n_expert_used, cudaStream_t stream) { + quantize_launch_typed(x, type_src1, [&](auto * x_t) { + quantize_scatter_mmq_fp4_cuda(x_t, ids_src1_inv, vy, scale, type_src0, use_aligned_float8, ne00, stride_token, ne0, + n_tokens, nrows_dst, n_expert_used, stream); + }); +} + +template +static void quantize_mmq_fp4_cuda( + const src_t * x, const int32_t * ids, void * vy, float * scale, const ggml_type type_src0, const bool use_aligned_float8, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03, const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) { GGML_ASSERT(type_src0 == GGML_TYPE_MXFP4 || type_src0 == GGML_TYPE_NVFP4); @@ -869,10 +971,10 @@ void quantize_mmq_fp4_cuda( const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1); const dim3 num_blocks(ne1, ne2 * ne3, 1); if (use_aligned_float8) { - quantize_mmq_nvfp4<<>>( + quantize_mmq_nvfp4<<>>( x, ids, vy, scale, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0); } else { - quantize_mmq_nvfp4<<>>( + quantize_mmq_nvfp4<<>>( x, ids, vy, scale, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0); } } else { @@ -886,6 +988,15 @@ void quantize_mmq_fp4_cuda( const dim3 num_blocks(ne1, block_num_y, ne2 * ne3); const dim3 block_size(WARP_SIZE, nwarps, 1); - quantize_mmq_mxfp4<<>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0); + quantize_mmq_mxfp4<<>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0); } } + +void quantize_mmq_fp4_cuda( + const void * x, const ggml_type type_src1, const int32_t * ids, void * vy, float * scale, const ggml_type type_src0, + const bool use_aligned_float8, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03, + const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) { + quantize_launch_typed(x, type_src1, [&](auto * x_t) { + quantize_mmq_fp4_cuda(x_t, ids, vy, scale, type_src0, use_aligned_float8, ne00, s01, s02, s03, ne0, ne1, ne2, ne3, stream); + }); +} diff --git a/ggml/src/ggml-cuda/quantize.cuh b/ggml/src/ggml-cuda/quantize.cuh index 0613cf367f72..c8b39acbfea1 100644 --- a/ggml/src/ggml-cuda/quantize.cuh +++ b/ggml/src/ggml-cuda/quantize.cuh @@ -11,13 +11,15 @@ static_assert(MATRIX_ROW_PADDING % CUDA_QUANTIZE_BLOCK_SIZE == 0, "Risk of out-of-bounds access."); static_assert(MATRIX_ROW_PADDING % (4*CUDA_QUANTIZE_BLOCK_SIZE_MMQ) == 0, "Risk of out-of-bounds access."); +// x holds the src1 values, type_src1 is GGML_TYPE_F32 or GGML_TYPE_BF16 + void quantize_row_q8_1_cuda( - const float * x, void * vy, + const void * x, ggml_type type_src1, void * vy, int64_t ne00, int64_t s01, int64_t s02, int64_t s03, int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3, cudaStream_t stream); void quantize_mmq_q8_1_cuda( - const float * x, const int32_t * ids, void * vy, + const void * x, ggml_type type_src1, const int32_t * ids, void * vy, ggml_type type_src0, int64_t ne00, int64_t s01, int64_t s02, int64_t s03, int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3, cudaStream_t stream); @@ -29,7 +31,7 @@ static constexpr int MMQ_FEW_NCOLS = 8; // src1 columns per column group static constexpr int MMQ_FEW_Q8_1_INT4 = 4*WARP_SIZE + 4*4; // int4 per 256 values and column group void quantize_mmq_few_q8_1_cuda( - const float * x, void * vy, mmq_q8_1_ds_layout ds_layout, int64_t ne00, int64_t s01, int64_t s02, int64_t s03, + const void * x, ggml_type type_src1, void * vy, mmq_q8_1_ds_layout ds_layout, int64_t ne00, int64_t s01, int64_t s02, int64_t s03, int64_t ne1, int64_t ne2, int64_t ne3, cudaStream_t stream); // MUL_MAT_ID: a pair is an expert and one column group of up to MMQ_FEW_NCOLS of its (token, slot) entries. The src1 of pair p is channel p above, its columns past the entries are not written. @@ -37,10 +39,11 @@ void quantize_mmq_few_q8_1_cuda( static constexpr int MMQ_FEW_PAIR_INTS = 2 + MMQ_FEW_NCOLS; void quantize_mmq_few_id_q8_1_cuda( - const float * x, const int32_t * ids, void * vy, int * pairs, mmq_q8_1_ds_layout ds_layout, int64_t ne00, int64_t s11, int64_t s12, + const void * x, ggml_type type_src1, const int32_t * ids, void * vy, int * pairs, mmq_q8_1_ds_layout ds_layout, int64_t ne00, int64_t s11, int64_t s12, int64_t ne11, int64_t n_experts, int64_t n_expert_used, int64_t n_tokens, int64_t si1, int64_t npairs_max, cudaStream_t stream); -void quantize_mmq_fp4_cuda(const float * x, +void quantize_mmq_fp4_cuda(const void * x, + ggml_type type_src1, const int32_t * ids, void * vy, float * scale, @@ -57,7 +60,8 @@ void quantize_mmq_fp4_cuda(const float * x, cudaStream_t stream); // quantize each token once and scatter the block to its compact rows (via the inverse map) -void quantize_scatter_mmq_fp4_cuda(const float * x, +void quantize_scatter_mmq_fp4_cuda(const void * x, + ggml_type type_src1, const int32_t * ids_src1_inv, void * vy, float * scale, @@ -71,7 +75,8 @@ void quantize_scatter_mmq_fp4_cuda(const float * x, int n_expert_used, cudaStream_t stream); -void quantize_scatter_mmq_q8_1_cuda(const float * x, +void quantize_scatter_mmq_q8_1_cuda(const void * x, + ggml_type type_src1, const int32_t * ids_src1_inv, void * vy, ggml_type type_src0, diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_16.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_16.cu new file mode 100644 index 000000000000..fcf4114149c6 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_16.cu @@ -0,0 +1,6 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(192, 128, 1, 16, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(576, 512, 1, 16, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_32.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_32.cu new file mode 100644 index 000000000000..083f5d1b8342 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_32.cu @@ -0,0 +1,6 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(320, 256, 1, 32, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(576, 512, 1, 32, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_8.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_8.cu new file mode 100644 index 000000000000..6adcac083f40 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_1-ncols2_8.cu @@ -0,0 +1,14 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(40, 40, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(64, 64, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(72, 72, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(80, 80, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(96, 96, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(112, 112, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(128, 128, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(192, 128, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(256, 256, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(512, 512, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_1.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_1.cu new file mode 100644 index 000000000000..a7ed494a8cb7 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_1.cu @@ -0,0 +1,12 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(40, 40, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(64, 64, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(72, 72, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(80, 80, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(96, 96, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(112, 112, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(128, 128, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(256, 256, 16, 1, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_2.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_2.cu new file mode 100644 index 000000000000..e8b55046a23f --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_2.cu @@ -0,0 +1,13 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(40, 40, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(64, 64, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(72, 72, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(80, 80, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(96, 96, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(112, 112, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(128, 128, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(256, 256, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(512, 512, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_4.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_4.cu new file mode 100644 index 000000000000..53cf952b1108 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_16-ncols2_4.cu @@ -0,0 +1,14 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(40, 40, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(64, 64, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(72, 72, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(80, 80, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(96, 96, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(112, 112, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(128, 128, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(256, 256, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(512, 512, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(576, 512, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_16.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_16.cu new file mode 100644 index 000000000000..23f4a9a5be25 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_16.cu @@ -0,0 +1,6 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(192, 128, 2, 16, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(576, 512, 2, 16, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_32.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_32.cu new file mode 100644 index 000000000000..040a3224e434 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_32.cu @@ -0,0 +1,6 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(320, 256, 2, 32, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(576, 512, 2, 32, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_4.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_4.cu new file mode 100644 index 000000000000..ffb774fe866f --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_4.cu @@ -0,0 +1,14 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(40, 40, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(64, 64, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(72, 72, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(80, 80, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(96, 96, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(112, 112, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(128, 128, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(256, 256, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(512, 512, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(576, 512, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_8.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_8.cu new file mode 100644 index 000000000000..02e48cc4043e --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_2-ncols2_8.cu @@ -0,0 +1,14 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(40, 40, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(64, 64, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(72, 72, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(80, 80, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(96, 96, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(112, 112, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(128, 128, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(192, 128, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(256, 256, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(512, 512, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_32-ncols2_1.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_32-ncols2_1.cu new file mode 100644 index 000000000000..68e71304d060 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_32-ncols2_1.cu @@ -0,0 +1,12 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(40, 40, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(64, 64, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(72, 72, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(80, 80, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(96, 96, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(112, 112, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(128, 128, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(256, 256, 32, 1, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_32-ncols2_2.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_32-ncols2_2.cu new file mode 100644 index 000000000000..857ccd4207b2 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_32-ncols2_2.cu @@ -0,0 +1,13 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(40, 40, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(64, 64, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(72, 72, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(80, 80, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(96, 96, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(112, 112, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(128, 128, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(256, 256, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(512, 512, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_16.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_16.cu new file mode 100644 index 000000000000..c7125f78aad1 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_16.cu @@ -0,0 +1,6 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(192, 128, 4, 16, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(576, 512, 4, 16, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_2.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_2.cu new file mode 100644 index 000000000000..d88c45377e48 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_2.cu @@ -0,0 +1,13 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(40, 40, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(64, 64, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(72, 72, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(80, 80, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(96, 96, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(112, 112, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(128, 128, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(256, 256, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(512, 512, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_4.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_4.cu new file mode 100644 index 000000000000..bbd1dd361aad --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_4.cu @@ -0,0 +1,14 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(40, 40, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(64, 64, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(72, 72, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(80, 80, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(96, 96, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(112, 112, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(128, 128, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(256, 256, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(512, 512, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(576, 512, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_8.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_8.cu new file mode 100644 index 000000000000..8c233b5f12e7 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_4-ncols2_8.cu @@ -0,0 +1,14 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(40, 40, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(64, 64, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(72, 72, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(80, 80, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(96, 96, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(112, 112, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(128, 128, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(192, 128, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(256, 256, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(512, 512, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_64-ncols2_1.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_64-ncols2_1.cu new file mode 100644 index 000000000000..daf4ca890257 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_64-ncols2_1.cu @@ -0,0 +1,12 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(40, 40, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(64, 64, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(72, 72, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(80, 80, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(96, 96, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(112, 112, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(128, 128, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(256, 256, 64, 1, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_1.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_1.cu new file mode 100644 index 000000000000..1459810148c9 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_1.cu @@ -0,0 +1,12 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(40, 40, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(64, 64, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(72, 72, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(80, 80, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(96, 96, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(112, 112, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(128, 128, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(256, 256, 8, 1, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_2.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_2.cu new file mode 100644 index 000000000000..4ec32c1347a5 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_2.cu @@ -0,0 +1,13 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(40, 40, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(64, 64, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(72, 72, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(80, 80, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(96, 96, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(112, 112, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(128, 128, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(256, 256, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(512, 512, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_4.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_4.cu new file mode 100644 index 000000000000..415ecfa9fc6c --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_4.cu @@ -0,0 +1,14 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(40, 40, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(64, 64, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(72, 72, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(80, 80, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(96, 96, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(112, 112, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(128, 128, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(256, 256, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(512, 512, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(576, 512, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_8.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_8.cu new file mode 100644 index 000000000000..ed37e9d38e80 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-f16-f16-ncols1_8-ncols2_8.cu @@ -0,0 +1,14 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-mma-f16.cuh" + +DECL_FATTN_MMA_F16_CASE(40, 40, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(64, 64, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(72, 72, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(80, 80, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(96, 96, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(112, 112, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(128, 128, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(192, 128, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(256, 256, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16); +DECL_FATTN_MMA_F16_CASE(512, 512, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_16.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_16.cu deleted file mode 100644 index b2661b931624..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_16.cu +++ /dev/null @@ -1,6 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(192, 128, 1, 16); -DECL_FATTN_MMA_F16_CASE(576, 512, 1, 16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_32.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_32.cu deleted file mode 100644 index 8fc3b17976e7..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_32.cu +++ /dev/null @@ -1,6 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(320, 256, 1, 32); -DECL_FATTN_MMA_F16_CASE(576, 512, 1, 32); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_8.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_8.cu deleted file mode 100644 index 3c861c2c0912..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_1-ncols2_8.cu +++ /dev/null @@ -1,14 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(40, 40, 1, 8); -DECL_FATTN_MMA_F16_CASE(64, 64, 1, 8); -DECL_FATTN_MMA_F16_CASE(72, 72, 1, 8); -DECL_FATTN_MMA_F16_CASE(80, 80, 1, 8); -DECL_FATTN_MMA_F16_CASE(96, 96, 1, 8); -DECL_FATTN_MMA_F16_CASE(112, 112, 1, 8); -DECL_FATTN_MMA_F16_CASE(128, 128, 1, 8); -DECL_FATTN_MMA_F16_CASE(192, 128, 1, 8); -DECL_FATTN_MMA_F16_CASE(256, 256, 1, 8); -DECL_FATTN_MMA_F16_CASE(512, 512, 1, 8); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_1.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_1.cu deleted file mode 100644 index 86501536489e..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_1.cu +++ /dev/null @@ -1,12 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(40, 40, 16, 1); -DECL_FATTN_MMA_F16_CASE(64, 64, 16, 1); -DECL_FATTN_MMA_F16_CASE(72, 72, 16, 1); -DECL_FATTN_MMA_F16_CASE(80, 80, 16, 1); -DECL_FATTN_MMA_F16_CASE(96, 96, 16, 1); -DECL_FATTN_MMA_F16_CASE(112, 112, 16, 1); -DECL_FATTN_MMA_F16_CASE(128, 128, 16, 1); -DECL_FATTN_MMA_F16_CASE(256, 256, 16, 1); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_2.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_2.cu deleted file mode 100644 index 8cf304825901..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_2.cu +++ /dev/null @@ -1,13 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(40, 40, 16, 2); -DECL_FATTN_MMA_F16_CASE(64, 64, 16, 2); -DECL_FATTN_MMA_F16_CASE(72, 72, 16, 2); -DECL_FATTN_MMA_F16_CASE(80, 80, 16, 2); -DECL_FATTN_MMA_F16_CASE(96, 96, 16, 2); -DECL_FATTN_MMA_F16_CASE(112, 112, 16, 2); -DECL_FATTN_MMA_F16_CASE(128, 128, 16, 2); -DECL_FATTN_MMA_F16_CASE(256, 256, 16, 2); -DECL_FATTN_MMA_F16_CASE(512, 512, 16, 2); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_4.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_4.cu deleted file mode 100644 index 51c91c2044b6..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_16-ncols2_4.cu +++ /dev/null @@ -1,14 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(40, 40, 16, 4); -DECL_FATTN_MMA_F16_CASE(64, 64, 16, 4); -DECL_FATTN_MMA_F16_CASE(72, 72, 16, 4); -DECL_FATTN_MMA_F16_CASE(80, 80, 16, 4); -DECL_FATTN_MMA_F16_CASE(96, 96, 16, 4); -DECL_FATTN_MMA_F16_CASE(112, 112, 16, 4); -DECL_FATTN_MMA_F16_CASE(128, 128, 16, 4); -DECL_FATTN_MMA_F16_CASE(256, 256, 16, 4); -DECL_FATTN_MMA_F16_CASE(512, 512, 16, 4); -DECL_FATTN_MMA_F16_CASE(576, 512, 16, 4); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_16.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_16.cu deleted file mode 100644 index fd41e71b1421..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_16.cu +++ /dev/null @@ -1,6 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(192, 128, 2, 16); -DECL_FATTN_MMA_F16_CASE(576, 512, 2, 16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_32.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_32.cu deleted file mode 100644 index abd2b21ce044..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_32.cu +++ /dev/null @@ -1,6 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(320, 256, 2, 32); -DECL_FATTN_MMA_F16_CASE(576, 512, 2, 32); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_4.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_4.cu deleted file mode 100644 index b6f99eb72e52..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_4.cu +++ /dev/null @@ -1,14 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(40, 40, 2, 4); -DECL_FATTN_MMA_F16_CASE(64, 64, 2, 4); -DECL_FATTN_MMA_F16_CASE(72, 72, 2, 4); -DECL_FATTN_MMA_F16_CASE(80, 80, 2, 4); -DECL_FATTN_MMA_F16_CASE(96, 96, 2, 4); -DECL_FATTN_MMA_F16_CASE(112, 112, 2, 4); -DECL_FATTN_MMA_F16_CASE(128, 128, 2, 4); -DECL_FATTN_MMA_F16_CASE(256, 256, 2, 4); -DECL_FATTN_MMA_F16_CASE(512, 512, 2, 4); -DECL_FATTN_MMA_F16_CASE(576, 512, 2, 4); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_8.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_8.cu deleted file mode 100644 index 14c120243035..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_2-ncols2_8.cu +++ /dev/null @@ -1,14 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(40, 40, 2, 8); -DECL_FATTN_MMA_F16_CASE(64, 64, 2, 8); -DECL_FATTN_MMA_F16_CASE(72, 72, 2, 8); -DECL_FATTN_MMA_F16_CASE(80, 80, 2, 8); -DECL_FATTN_MMA_F16_CASE(96, 96, 2, 8); -DECL_FATTN_MMA_F16_CASE(112, 112, 2, 8); -DECL_FATTN_MMA_F16_CASE(128, 128, 2, 8); -DECL_FATTN_MMA_F16_CASE(192, 128, 2, 8); -DECL_FATTN_MMA_F16_CASE(256, 256, 2, 8); -DECL_FATTN_MMA_F16_CASE(512, 512, 2, 8); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_32-ncols2_1.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_32-ncols2_1.cu deleted file mode 100644 index dbc58be55e54..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_32-ncols2_1.cu +++ /dev/null @@ -1,12 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(40, 40, 32, 1); -DECL_FATTN_MMA_F16_CASE(64, 64, 32, 1); -DECL_FATTN_MMA_F16_CASE(72, 72, 32, 1); -DECL_FATTN_MMA_F16_CASE(80, 80, 32, 1); -DECL_FATTN_MMA_F16_CASE(96, 96, 32, 1); -DECL_FATTN_MMA_F16_CASE(112, 112, 32, 1); -DECL_FATTN_MMA_F16_CASE(128, 128, 32, 1); -DECL_FATTN_MMA_F16_CASE(256, 256, 32, 1); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_32-ncols2_2.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_32-ncols2_2.cu deleted file mode 100644 index 784a1f919506..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_32-ncols2_2.cu +++ /dev/null @@ -1,13 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(40, 40, 32, 2); -DECL_FATTN_MMA_F16_CASE(64, 64, 32, 2); -DECL_FATTN_MMA_F16_CASE(72, 72, 32, 2); -DECL_FATTN_MMA_F16_CASE(80, 80, 32, 2); -DECL_FATTN_MMA_F16_CASE(96, 96, 32, 2); -DECL_FATTN_MMA_F16_CASE(112, 112, 32, 2); -DECL_FATTN_MMA_F16_CASE(128, 128, 32, 2); -DECL_FATTN_MMA_F16_CASE(256, 256, 32, 2); -DECL_FATTN_MMA_F16_CASE(512, 512, 32, 2); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_16.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_16.cu deleted file mode 100644 index cc41fa52f135..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_16.cu +++ /dev/null @@ -1,6 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(192, 128, 4, 16); -DECL_FATTN_MMA_F16_CASE(576, 512, 4, 16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_2.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_2.cu deleted file mode 100644 index 7ace51905334..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_2.cu +++ /dev/null @@ -1,13 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(40, 40, 4, 2); -DECL_FATTN_MMA_F16_CASE(64, 64, 4, 2); -DECL_FATTN_MMA_F16_CASE(72, 72, 4, 2); -DECL_FATTN_MMA_F16_CASE(80, 80, 4, 2); -DECL_FATTN_MMA_F16_CASE(96, 96, 4, 2); -DECL_FATTN_MMA_F16_CASE(112, 112, 4, 2); -DECL_FATTN_MMA_F16_CASE(128, 128, 4, 2); -DECL_FATTN_MMA_F16_CASE(256, 256, 4, 2); -DECL_FATTN_MMA_F16_CASE(512, 512, 4, 2); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_4.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_4.cu deleted file mode 100644 index f27640e84efc..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_4.cu +++ /dev/null @@ -1,14 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(40, 40, 4, 4); -DECL_FATTN_MMA_F16_CASE(64, 64, 4, 4); -DECL_FATTN_MMA_F16_CASE(72, 72, 4, 4); -DECL_FATTN_MMA_F16_CASE(80, 80, 4, 4); -DECL_FATTN_MMA_F16_CASE(96, 96, 4, 4); -DECL_FATTN_MMA_F16_CASE(112, 112, 4, 4); -DECL_FATTN_MMA_F16_CASE(128, 128, 4, 4); -DECL_FATTN_MMA_F16_CASE(256, 256, 4, 4); -DECL_FATTN_MMA_F16_CASE(512, 512, 4, 4); -DECL_FATTN_MMA_F16_CASE(576, 512, 4, 4); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_8.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_8.cu deleted file mode 100644 index 28a961b6b9b9..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_4-ncols2_8.cu +++ /dev/null @@ -1,14 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(40, 40, 4, 8); -DECL_FATTN_MMA_F16_CASE(64, 64, 4, 8); -DECL_FATTN_MMA_F16_CASE(72, 72, 4, 8); -DECL_FATTN_MMA_F16_CASE(80, 80, 4, 8); -DECL_FATTN_MMA_F16_CASE(96, 96, 4, 8); -DECL_FATTN_MMA_F16_CASE(112, 112, 4, 8); -DECL_FATTN_MMA_F16_CASE(128, 128, 4, 8); -DECL_FATTN_MMA_F16_CASE(192, 128, 4, 8); -DECL_FATTN_MMA_F16_CASE(256, 256, 4, 8); -DECL_FATTN_MMA_F16_CASE(512, 512, 4, 8); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_64-ncols2_1.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_64-ncols2_1.cu deleted file mode 100644 index 1ad67c0d8f3f..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_64-ncols2_1.cu +++ /dev/null @@ -1,12 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(40, 40, 64, 1); -DECL_FATTN_MMA_F16_CASE(64, 64, 64, 1); -DECL_FATTN_MMA_F16_CASE(72, 72, 64, 1); -DECL_FATTN_MMA_F16_CASE(80, 80, 64, 1); -DECL_FATTN_MMA_F16_CASE(96, 96, 64, 1); -DECL_FATTN_MMA_F16_CASE(112, 112, 64, 1); -DECL_FATTN_MMA_F16_CASE(128, 128, 64, 1); -DECL_FATTN_MMA_F16_CASE(256, 256, 64, 1); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_1.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_1.cu deleted file mode 100644 index 695782ca4be0..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_1.cu +++ /dev/null @@ -1,12 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(40, 40, 8, 1); -DECL_FATTN_MMA_F16_CASE(64, 64, 8, 1); -DECL_FATTN_MMA_F16_CASE(72, 72, 8, 1); -DECL_FATTN_MMA_F16_CASE(80, 80, 8, 1); -DECL_FATTN_MMA_F16_CASE(96, 96, 8, 1); -DECL_FATTN_MMA_F16_CASE(112, 112, 8, 1); -DECL_FATTN_MMA_F16_CASE(128, 128, 8, 1); -DECL_FATTN_MMA_F16_CASE(256, 256, 8, 1); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_2.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_2.cu deleted file mode 100644 index de265981544e..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_2.cu +++ /dev/null @@ -1,13 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(40, 40, 8, 2); -DECL_FATTN_MMA_F16_CASE(64, 64, 8, 2); -DECL_FATTN_MMA_F16_CASE(72, 72, 8, 2); -DECL_FATTN_MMA_F16_CASE(80, 80, 8, 2); -DECL_FATTN_MMA_F16_CASE(96, 96, 8, 2); -DECL_FATTN_MMA_F16_CASE(112, 112, 8, 2); -DECL_FATTN_MMA_F16_CASE(128, 128, 8, 2); -DECL_FATTN_MMA_F16_CASE(256, 256, 8, 2); -DECL_FATTN_MMA_F16_CASE(512, 512, 8, 2); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_4.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_4.cu deleted file mode 100644 index 9d9c748aef71..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_4.cu +++ /dev/null @@ -1,14 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(40, 40, 8, 4); -DECL_FATTN_MMA_F16_CASE(64, 64, 8, 4); -DECL_FATTN_MMA_F16_CASE(72, 72, 8, 4); -DECL_FATTN_MMA_F16_CASE(80, 80, 8, 4); -DECL_FATTN_MMA_F16_CASE(96, 96, 8, 4); -DECL_FATTN_MMA_F16_CASE(112, 112, 8, 4); -DECL_FATTN_MMA_F16_CASE(128, 128, 8, 4); -DECL_FATTN_MMA_F16_CASE(256, 256, 8, 4); -DECL_FATTN_MMA_F16_CASE(512, 512, 8, 4); -DECL_FATTN_MMA_F16_CASE(576, 512, 8, 4); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_8.cu b/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_8.cu deleted file mode 100644 index 50f17f2f8d0d..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-mma-f16-instance-ncols1_8-ncols2_8.cu +++ /dev/null @@ -1,14 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-mma-f16.cuh" - -DECL_FATTN_MMA_F16_CASE(40, 40, 8, 8); -DECL_FATTN_MMA_F16_CASE(64, 64, 8, 8); -DECL_FATTN_MMA_F16_CASE(72, 72, 8, 8); -DECL_FATTN_MMA_F16_CASE(80, 80, 8, 8); -DECL_FATTN_MMA_F16_CASE(96, 96, 8, 8); -DECL_FATTN_MMA_F16_CASE(112, 112, 8, 8); -DECL_FATTN_MMA_F16_CASE(128, 128, 8, 8); -DECL_FATTN_MMA_F16_CASE(192, 128, 8, 8); -DECL_FATTN_MMA_F16_CASE(256, 256, 8, 8); -DECL_FATTN_MMA_F16_CASE(512, 512, 8, 8); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq320-dv256.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq320-dv256.cu deleted file mode 100644 index c91f508079d5..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq320-dv256.cu +++ /dev/null @@ -1,5 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-tile.cuh" - -DECL_FATTN_TILE_CASE(320, 256); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq40-dv40.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq40-dv40.cu deleted file mode 100644 index 10b330fa6c03..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq40-dv40.cu +++ /dev/null @@ -1,5 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-tile.cuh" - -DECL_FATTN_TILE_CASE(40, 40); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq512-dv512.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq512-dv512.cu deleted file mode 100644 index 7c61d8d2ecdb..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq512-dv512.cu +++ /dev/null @@ -1,5 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-tile.cuh" - -DECL_FATTN_TILE_CASE(512, 512); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq576-dv512.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq576-dv512.cu deleted file mode 100644 index 254b7d2e1dc2..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq576-dv512.cu +++ /dev/null @@ -1,5 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-tile.cuh" - -DECL_FATTN_TILE_CASE(576, 512); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq64-dv64.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq64-dv64.cu deleted file mode 100644 index 5caffac0467d..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq64-dv64.cu +++ /dev/null @@ -1,5 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-tile.cuh" - -DECL_FATTN_TILE_CASE(64, 64); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq72-dv72.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq72-dv72.cu deleted file mode 100644 index 8f9d5315f2ac..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq72-dv72.cu +++ /dev/null @@ -1,5 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-tile.cuh" - -DECL_FATTN_TILE_CASE(72, 72); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq80-dv80.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq80-dv80.cu deleted file mode 100644 index 90abb3b18626..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq80-dv80.cu +++ /dev/null @@ -1,5 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-tile.cuh" - -DECL_FATTN_TILE_CASE(80, 80); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq96-dv96.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq96-dv96.cu deleted file mode 100644 index 7292c0aab8f9..000000000000 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq96-dv96.cu +++ /dev/null @@ -1,5 +0,0 @@ -// This file has been autogenerated by generate_cu_files.py, do not edit manually. - -#include "../fattn-tile.cuh" - -DECL_FATTN_TILE_CASE(96, 96); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq112-dv112.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq112-dv112.cu new file mode 100644 index 000000000000..ba680fa3c1ec --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq112-dv112.cu @@ -0,0 +1,5 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-tile.cuh" + +DECL_FATTN_TILE_CASE(112, 112, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq128-dv128.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq128-dv128.cu new file mode 100644 index 000000000000..640f4b034cf4 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq128-dv128.cu @@ -0,0 +1,5 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-tile.cuh" + +DECL_FATTN_TILE_CASE(128, 128, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq192-dv128.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq192-dv128.cu new file mode 100644 index 000000000000..425987914cee --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq192-dv128.cu @@ -0,0 +1,5 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-tile.cuh" + +DECL_FATTN_TILE_CASE(192, 128, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq256-dv256.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq256-dv256.cu new file mode 100644 index 000000000000..a828dc7e37ce --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq256-dv256.cu @@ -0,0 +1,5 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-tile.cuh" + +DECL_FATTN_TILE_CASE(256, 256, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq320-dv256.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq320-dv256.cu new file mode 100644 index 000000000000..138f7808468f --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq320-dv256.cu @@ -0,0 +1,5 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-tile.cuh" + +DECL_FATTN_TILE_CASE(320, 256, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq112-dv112.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq40-dv40.cu similarity index 65% rename from ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq112-dv112.cu rename to ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq40-dv40.cu index a8b15ad72a91..1346495d84f9 100644 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq112-dv112.cu +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq40-dv40.cu @@ -2,4 +2,4 @@ #include "../fattn-tile.cuh" -DECL_FATTN_TILE_CASE(112, 112); +DECL_FATTN_TILE_CASE(40, 40, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq512-dv512.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq512-dv512.cu new file mode 100644 index 000000000000..79d63707614a --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq512-dv512.cu @@ -0,0 +1,5 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-tile.cuh" + +DECL_FATTN_TILE_CASE(512, 512, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq576-dv512.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq576-dv512.cu new file mode 100644 index 000000000000..2fa684e1d2bd --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq576-dv512.cu @@ -0,0 +1,5 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-tile.cuh" + +DECL_FATTN_TILE_CASE(576, 512, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq128-dv128.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq64-dv64.cu similarity index 65% rename from ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq128-dv128.cu rename to ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq64-dv64.cu index 1da18105508a..f070f7b578a8 100644 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq128-dv128.cu +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq64-dv64.cu @@ -2,4 +2,4 @@ #include "../fattn-tile.cuh" -DECL_FATTN_TILE_CASE(128, 128); +DECL_FATTN_TILE_CASE(64, 64, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq192-dv128.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq72-dv72.cu similarity index 65% rename from ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq192-dv128.cu rename to ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq72-dv72.cu index b571cca0df23..881236ecd564 100644 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq192-dv128.cu +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq72-dv72.cu @@ -2,4 +2,4 @@ #include "../fattn-tile.cuh" -DECL_FATTN_TILE_CASE(192, 128); +DECL_FATTN_TILE_CASE(72, 72, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq256-dv256.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq80-dv80.cu similarity index 65% rename from ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq256-dv256.cu rename to ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq80-dv80.cu index bc65c723eca9..0a21116421e3 100644 --- a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-dkq256-dv256.cu +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq80-dv80.cu @@ -2,4 +2,4 @@ #include "../fattn-tile.cuh" -DECL_FATTN_TILE_CASE(256, 256); +DECL_FATTN_TILE_CASE(80, 80, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq96-dv96.cu b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq96-dv96.cu new file mode 100644 index 000000000000..05d4bd1712f7 --- /dev/null +++ b/ggml/src/ggml-cuda/template-instances/fattn-tile-instance-f16-f16-dkq96-dv96.cu @@ -0,0 +1,5 @@ +// This file has been autogenerated by generate_cu_files.py, do not edit manually. + +#include "../fattn-tile.cuh" + +DECL_FATTN_TILE_CASE(96, 96, GGML_TYPE_F16, GGML_TYPE_F16); diff --git a/ggml/src/ggml-cuda/template-instances/generate_cu_files.py b/ggml/src/ggml-cuda/template-instances/generate_cu_files.py index f49a015ae1f5..eeabf416328d 100755 --- a/ggml/src/ggml-cuda/template-instances/generate_cu_files.py +++ b/ggml/src/ggml-cuda/template-instances/generate_cu_files.py @@ -10,11 +10,13 @@ TYPES_KV = ["GGML_TYPE_F16", "GGML_TYPE_Q4_0", "GGML_TYPE_Q4_1", "GGML_TYPE_Q5_0", "GGML_TYPE_Q5_1", "GGML_TYPE_Q8_0", "GGML_TYPE_BF16", "GGML_TYPE_F8_E4M3"] +TYPES_KV_TILE_MMA = ["GGML_TYPE_F16"] + SOURCE_FATTN_TILE = """// This file has been autogenerated by generate_cu_files.py, do not edit manually. #include "../fattn-tile.cuh" -DECL_FATTN_TILE_CASE({head_size_kq}, {head_size_v}); +DECL_FATTN_TILE_CASE({head_size_kq}, {head_size_v}, {type_k}, {type_v}); """ SOURCE_FATTN_VEC = """// This file has been autogenerated by generate_cu_files.py, do not edit manually. @@ -32,7 +34,7 @@ """ -SOURCE_FATTN_MMA_CASE = "DECL_FATTN_MMA_F16_CASE({head_size_kq}, {head_size_v}, {ncols1}, {ncols2});\n" +SOURCE_FATTN_MMA_CASE = "DECL_FATTN_MMA_F16_CASE({head_size_kq}, {head_size_v}, {ncols1}, {ncols2}, {type_k}, {type_v});\n" TYPES_MMQ = [ "GGML_TYPE_Q1_0", @@ -71,38 +73,45 @@ def get_short_name(long_quant_name): for filename in glob("*.cu"): os.remove(filename) -for head_size_kq in HEAD_SIZES_KQ: - head_size_v = HEAD_SIZES_V_OVERRIDE.get(head_size_kq, head_size_kq) - with open(f"fattn-tile-instance-dkq{head_size_kq}-dv{head_size_v}.cu", "w") as f: - f.write(SOURCE_FATTN_TILE.format(head_size_kq=head_size_kq, head_size_v=head_size_v)) +for type_k in TYPES_KV_TILE_MMA: + for type_v in TYPES_KV_TILE_MMA: + for head_size_kq in HEAD_SIZES_KQ: + head_size_v = HEAD_SIZES_V_OVERRIDE.get(head_size_kq, head_size_kq) + with open(f"fattn-tile-instance-{get_short_name(type_k)}-{get_short_name(type_v)}-dkq{head_size_kq}-dv{head_size_v}.cu", "w") as f: + f.write(SOURCE_FATTN_TILE.format( + head_size_kq=head_size_kq, head_size_v=head_size_v, type_k=type_k, type_v=type_v)) for type_k in TYPES_KV: for type_v in TYPES_KV: with open(f"fattn-vec-instance-{get_short_name(type_k)}-{get_short_name(type_v)}.cu", "w") as f: f.write(SOURCE_FATTN_VEC.format(type_k=type_k, type_v=type_v)) -for ncols in [8, 16, 32, 64]: - for ncols2 in [1, 2, 4, 8, 16, 32]: - if ncols2 > ncols: - continue - ncols1 = ncols // ncols2 - with open(f"fattn-mma-f16-instance-ncols1_{ncols1}-ncols2_{ncols2}.cu", "w") as f: - f.write(SOURCE_FATTN_MMA_START) - - for head_size_kq in HEAD_SIZES_KQ: - # Skip compilation of unused ncols2 values for niche head sizes: - if head_size_kq == 192 and ncols2 not in (8, 16): # MiMo-V2.5 - continue - if head_size_kq == 320 and ncols2 != 32: # Mistral Small 4 - continue - if head_size_kq == 512 and ncols2 not in (2, 4, 8): # Gemma 4 (+ MTP) - continue - if head_size_kq == 576 and ncols2 not in (4, 16, 32): # Deepseek, GLM 4.7 Flash - continue - if head_size_kq not in (192, 320, 576) and ncols2 in (16, 32): +for type_k in TYPES_KV_TILE_MMA: + for type_v in TYPES_KV_TILE_MMA: + for ncols in [8, 16, 32, 64]: + for ncols2 in [1, 2, 4, 8, 16, 32]: + if ncols2 > ncols: continue - head_size_v = HEAD_SIZES_V_OVERRIDE.get(head_size_kq, head_size_kq) - f.write(SOURCE_FATTN_MMA_CASE.format(ncols1=ncols1, ncols2=ncols2, head_size_kq=head_size_kq, head_size_v=head_size_v)) + ncols1 = ncols // ncols2 + with open(f"fattn-mma-f16-instance-{get_short_name(type_k)}-{get_short_name(type_v)}-ncols1_{ncols1}-ncols2_{ncols2}.cu", "w") as f: + f.write(SOURCE_FATTN_MMA_START) + + for head_size_kq in HEAD_SIZES_KQ: + # Skip compilation of unused ncols2 values for niche head sizes: + if head_size_kq == 192 and ncols2 not in (8, 16): # MiMo-V2.5 + continue + if head_size_kq == 320 and ncols2 != 32: # Mistral Small 4 + continue + if head_size_kq == 512 and ncols2 not in (2, 4, 8): # Gemma 4 (+ MTP) + continue + if head_size_kq == 576 and ncols2 not in (4, 16, 32): # Deepseek, GLM 4.7 Flash + continue + if head_size_kq not in (192, 320, 576) and ncols2 in (16, 32): + continue + head_size_v = HEAD_SIZES_V_OVERRIDE.get(head_size_kq, head_size_kq) + f.write(SOURCE_FATTN_MMA_CASE.format( + ncols1=ncols1, ncols2=ncols2, head_size_kq=head_size_kq, head_size_v=head_size_v, + type_k=type_k, type_v=type_v)) for type in TYPES_MMQ: with open(f"mmq-instance-{get_short_name(type)}.cu", "w") as f: diff --git a/ggml/src/ggml-cuda/topk-moe.cu b/ggml/src/ggml-cuda/topk-moe.cu index d6481baafb5a..0bb65f306d46 100644 --- a/ggml/src/ggml-cuda/topk-moe.cu +++ b/ggml/src/ggml-cuda/topk-moe.cu @@ -7,12 +7,13 @@ // Kernel config struct - passed by value to CUDA kernel struct topk_moe_config { - bool use_sigmoid; - bool use_sqrt_softplus; - bool with_norm; - bool delayed_softmax; - int n_groups; - int n_group_used; + bool use_sigmoid; + bool use_sqrt_softplus; + bool with_norm; + bool delayed_softmax; + int n_groups; + int n_group_used; + float norm_bias; }; // Warp-local softmax used for both the pre-top-k logits and the post-top-k delayed path. @@ -334,7 +335,7 @@ __global__ void topk_moe_cuda(const float * logits, if (config.with_norm) { wt_sum = warp_reduce_sum(wt_sum); - wt_sum = max(wt_sum, clamp_val); + wt_sum = max(wt_sum, clamp_val) + config.norm_bias; const float inv_sum = 1.0f / wt_sum; for (int i = 0; i < experts_per_thread; i++) { @@ -438,7 +439,7 @@ void ggml_cuda_op_topk_moe(ggml_backend_cuda_context & ctx, const ggml_tensor * logits, ggml_tensor * weights, ggml_tensor * ids, - const ggml_tensor * clamp, + const ggml_tensor * denom, const ggml_tensor * scale, const ggml_tensor * bias, const ggml_cuda_topk_moe_args & args) { @@ -460,11 +461,15 @@ void ggml_cuda_op_topk_moe(ggml_backend_cuda_context & ctx, const int n_expert_used = weights->ne[1]; - const bool with_norm = clamp != nullptr; + const bool with_norm = denom != nullptr; + // the sum is clamped from below (CLAMP) or gets an additive bias (SCALE with scale 1) float clamp_val = -INFINITY; - if (clamp) { - clamp_val = ggml_get_op_params_f32(clamp, 0); + float norm_bias = 0.0f; + if (denom && denom->op == GGML_OP_SCALE) { + norm_bias = ggml_get_op_params_f32(denom, 1); + } else if (denom) { + clamp_val = ggml_get_op_params_f32(denom, 0); } topk_moe_config config; @@ -474,6 +479,7 @@ void ggml_cuda_op_topk_moe(ggml_backend_cuda_context & ctx, config.delayed_softmax = args.delayed_softmax; config.n_groups = args.n_groups; config.n_group_used = args.n_group_used; + config.norm_bias = norm_bias; if (bias) { launch_topk_moe_cuda(ctx, logits_d, weights_d, ids_d, bias_d, n_rows, n_experts, n_expert_used, clamp_val, diff --git a/ggml/src/ggml-cuda/topk-moe.cuh b/ggml/src/ggml-cuda/topk-moe.cuh index 3637500ff99d..082153e6e1d2 100644 --- a/ggml/src/ggml-cuda/topk-moe.cuh +++ b/ggml/src/ggml-cuda/topk-moe.cuh @@ -13,6 +13,7 @@ struct ggml_cuda_topk_moe_args { bool delayed_softmax{}; bool prob_bias{}; bool norm{}; + bool norm_bias{}; // the weight sum gets SCALE (sum + bias) instead of CLAMP bool scale{}; int n_groups{}; // > 0: pick experts only from the top n_group_used expert groups int n_group_used{}; @@ -22,7 +23,7 @@ void ggml_cuda_op_topk_moe(ggml_backend_cuda_context & ctx, const ggml_tensor * logits, ggml_tensor * weights, ggml_tensor * ids, - const ggml_tensor * clamp, + const ggml_tensor * denom, const ggml_tensor * scale, const ggml_tensor * bias, const ggml_cuda_topk_moe_args & args); diff --git a/ggml/src/ggml-hexagon/CMakeLists.txt b/ggml/src/ggml-hexagon/CMakeLists.txt index fea5770c197f..f388e3335c4b 100644 --- a/ggml/src/ggml-hexagon/CMakeLists.txt +++ b/ggml/src/ggml-hexagon/CMakeLists.txt @@ -59,6 +59,8 @@ ggml_add_backend_library(${TARGET_NAME} htp-opnode.h htp-fusion.cpp htp-fusion.h + htp-lower.cpp + htp-lower.h htp-repack.cpp htp-repack.h htp-drv.cpp diff --git a/ggml/src/ggml-hexagon/ggml-hexagon.cpp b/ggml/src/ggml-hexagon/ggml-hexagon.cpp index aa6e6d9a01a1..966219e52422 100644 --- a/ggml/src/ggml-hexagon/ggml-hexagon.cpp +++ b/ggml/src/ggml-hexagon/ggml-hexagon.cpp @@ -56,12 +56,14 @@ #include "ggml-quants.h" #include "htp-opnode.h" #include "htp/htp-ops.h" +#include "htp/htp-vtcm.h" #include "htp_iface.h" #include "htp-drv.h" #include "htp-repack.h" #include "htp-common.h" #include "htp-kparams.h" #include "htp-fusion.h" +#include "htp-lower.h" using intvec = std::vector; using uintvec = std::vector; @@ -132,8 +134,8 @@ size_t opt_mbuf_dyn = 512ul * 1024 * 1024; // max dynamic (compute) buff size_t opt_mbuf_static = 1ul * 1024 * 1024 * 1024; // max static (weight/KV) buffer size size_t opt_mbuf_total = 0; // total buffer space limit (0 = unconstrained) -int opt_mm_select = 2; // 2 = HMX -> HVX -> CPU, 1 = HVX -> CPU, 0 = CPU (unsupported) -int opt_fa_select = 2; // 2 = HMX -> HVX -> CPU, 1 = HVX -> CPU, 0 = CPU (unsupported) +int opt_mm_select = 3; // 4 = pure W8A8, 3 = hybrid W8A8 + FP16 post-GLU (default), 2 = FP16 HMX -> HVX -> CPU, 1 = HVX -> CPU, 0 = CPU +int opt_fa_select = 3; // 3 = INT HMX W8A8 (default) -> FP16 HMX -> HVX -> CPU, 2 = FP16 HMX -> HVX -> CPU, 1 = HVX -> CPU, 0 = CPU int opt_fa_split = 1; // 1 = head-split + team-split when n_kv_heads < N_cores (default), 0 = off int opt_li_select = 2; // 2 = HMX -> HVX, 1 = HVX, 0 = CPU (unsupported) int opt_gdn_select = 2; // 2 = HMX -> HVX, 1 = HVX, 0 = CPU (unsupported) @@ -151,6 +153,7 @@ int opt_opqueue = 8; // max number of pending batches int opt_optrace = 0; // trace buffer size per thread (0 means default) int opt_oppoll = 0; // polling for batch completions int opt_opfusion = 1; // enable/disable op fusion +int opt_oplower = 1; // lower internal F32 ops to F16 (0: off, 1: on) int opt_rt_repack = 1; // runtime repacking: 0 = disabled, 1 = all tileable weights (default) static std::regex* opt_opfilter = NULL; // regex of ops to not claim @@ -362,7 +365,7 @@ struct ggml_hexagon_session { std::unordered_map cpy_fence_slots; void enqueue_mdev_group(); - void enqueue_op(const htp_opnode & node); + void enqueue_op(const htp_opnode & node, bool allow_fuse = true); void enqueue_cpy(const ggml_tensor * src, ggml_tensor * dst, const ggml_tensor * sync_tensor = nullptr, uint32_t fence_seq = 0); void enqueue_fence(const ggml_tensor * sync_tensor, uint32_t fence_seq = 0, bool wait = true); void enqueue_allreduce(const ggml_tensor * dst, const std::vector & src_tensors, @@ -391,7 +394,7 @@ struct ggml_hexagon_session { }; const char * htp_session_name(const struct ggml_hexagon_session * sess) { return sess->c_name(); } -size_t htp_session_vtcm_size(const struct ggml_hexagon_session * sess) { return sess->vtcm_size; } +size_t htp_session_vtcm_size(const struct ggml_hexagon_session * sess) { return htp_vtcm_usable_size(sess->vtcm_size); } uint32_t htp_session_n_hvx(const struct ggml_hexagon_session * sess) { return sess->n_hvx; } uint32_t htp_session_n_hmx(const struct ggml_hexagon_session * sess) { return sess->n_hmx; } uint32_t htp_session_mdev_count(const struct ggml_hexagon_session * sess) { return sess->mdev.count; } @@ -697,6 +700,11 @@ static void ggml_backend_hexagon_buffer_set_tensor(ggml_backend_buffer_t buffer, HEX_VERBOSE("ggml-hex: %s set-tensor %s : data %p offset %zu size %zu usage %d flags 0x%x\n", sess->c_name(), tensor->name, data, offset, size, (int) buffer->usage, ggml_hexagon_tensor_get_flags(tensor)); + if (htp_tensor_is_stored_f16(tensor)) { + htp_pack_tensor_lowered_f16(tensor, data, offset, size); + return; + } + memcpy((char *) tensor->data + offset, data, size); } @@ -712,12 +720,16 @@ static void ggml_backend_hexagon_buffer_get_tensor(ggml_backend_buffer_t buffer, HEX_VERBOSE("ggml-hex: %s get-tensor %s : data %p offset %zu size %zu usage %d flags 0x%x\n", sess->c_name(), tensor->name, data, offset, size, (int) buffer->usage, flags); - if ((flags & HTP_TENSOR_TILED) == 0) { - memcpy(data, (const char *) tensor->data + offset, size); + if (flags & HTP_TENSOR_TILED) { + htp_unpack_tensor_tiled(data, tensor, offset, size); + return; + } + if (htp_tensor_is_stored_f16(tensor)) { + htp_unpack_tensor_lowered_f16(data, tensor, offset, size); return; } - htp_unpack_tensor_tiled(data, tensor, offset, size); + memcpy(data, (const char *) tensor->data + offset, size); } static bool ggml_backend_hexagon_buffer_cpy_tensor(ggml_backend_buffer_t buffer, @@ -751,6 +763,13 @@ static void ggml_backend_hexagon_buffer_set_tensor_2d(ggml_backend_buffer_t buff HEX_VERBOSE("ggml-hex: %s set-tensor-2d %s : data %p offset %zu size %zu n_copies %zu stride_tensor %zu stride_data %zu usage %d flags 0x%x\n", sess->c_name(), tensor->name, data, offset, size, n_copies, stride_tensor, stride_data, (int) buffer->usage, ggml_hexagon_tensor_get_flags(tensor)); + if (htp_tensor_is_stored_f16(tensor)) { + for (size_t i = 0; i < n_copies; i++) { + htp_pack_tensor_lowered_f16(tensor, (const uint8_t *) data + i * stride_data, offset + i * stride_tensor, size); + } + return; + } + for (size_t i = 0; i < n_copies; i++) { memcpy((uint8_t *) tensor->data + offset + i * stride_tensor, (const uint8_t *) data + i * stride_data, size); } @@ -772,6 +791,12 @@ static void ggml_backend_hexagon_buffer_get_tensor_2d(ggml_backend_buffer_t buff sess->c_name(), tensor->name, data, offset, size, n_copies, stride_tensor, stride_data, (int) buffer->usage); if ((flags & HTP_TENSOR_TILED) == 0) { + if (htp_tensor_is_stored_f16(tensor)) { + for (size_t i = 0; i < n_copies; i++) { + htp_unpack_tensor_lowered_f16((uint8_t *) data + i * stride_data, tensor, offset + i * stride_tensor, size); + } + return; + } for (size_t i = 0; i < n_copies; i++) { memcpy((uint8_t *)data + i * stride_data, (const uint8_t *)tensor->data + offset + i * stride_tensor, size); } @@ -814,6 +839,10 @@ static void ggml_backend_hexagon_buffer_set_tensor_n(ggml_backend_buffer_t buffe if (is_weights) { ggml_hexagon_tensor_set_flags(tensors[i], HTP_TENSOR_WEIGHT); } + if (htp_tensor_is_stored_f16(tensors[i])) { + htp_pack_tensor_lowered_f16(tensors[i], data[i], offsets[i], sizes[i]); + continue; + } memcpy((char *) tensors[i]->data + offsets[i], data[i], sizes[i]); } } @@ -854,6 +883,11 @@ static void ggml_backend_hexagon_host_buffer_set_tensor(ggml_backend_buffer_t bu sess->flush_sync(); + if (htp_tensor_is_stored_f16(tensor)) { + htp_pack_tensor_lowered_f16(tensor, data, offset, size); + return; + } + memcpy((char *) tensor->data + offset, data, size); } @@ -862,6 +896,10 @@ static void ggml_backend_hexagon_host_buffer_get_tensor(ggml_backend_buffer_t bu void * data, size_t offset, size_t size) { + if (htp_tensor_is_stored_f16(tensor)) { + htp_unpack_tensor_lowered_f16(data, tensor, offset, size); + return; + } memcpy(data, (const char *) tensor->data + offset, size); GGML_UNUSED(buffer); } @@ -881,6 +919,10 @@ static void ggml_backend_hexagon_host_buffer_set_tensor_n(ggml_backend_buffer_t if (sizes[i] == 0) { continue; } + if (htp_tensor_is_stored_f16(tensors[i])) { + htp_pack_tensor_lowered_f16(tensors[i], data[i], offsets[i], sizes[i]); + continue; + } memcpy((char *) tensors[i]->data + offsets[i], data[i], sizes[i]); } } @@ -1247,6 +1289,58 @@ static bool ggml_backend_buffer_is_hexagon(const struct ggml_backend_buffer * b) return b->buft->iface.get_alignment == ggml_backend_hexagon_buffer_type_get_alignment; } +struct ggml_hexagon_tensor_map { + struct slot { + uint64_t key; + uint32_t gen; + int32_t val; + }; + + std::vector slots; + uint32_t mask = 0; + uint32_t gen = 1; + + void init(size_t max_entries) { + size_t cap = 64; + while (cap < max_entries * 2) { + cap <<= 1; + } + slots.assign(cap, { 0, 0, 0 }); + mask = (uint32_t) (cap - 1); + gen = 1; + } + + void clear() { + if (++gen == 0) { + for (auto & s : slots) { s.gen = 0; } + gen = 1; + } + } + + bool contains(uint64_t key) const { + uint32_t i = (uint32_t) key & mask; + while (slots[i].gen == gen) { + if (slots[i].key == key) { return true; } + i = (i + 1) & mask; + } + return false; + } + + int find_or_insert(uint64_t key, int new_val, bool & inserted) { + uint32_t i = (uint32_t) key & mask; + while (slots[i].gen == gen) { + if (slots[i].key == key) { + inserted = false; + return slots[i].val; + } + i = (i + 1) & mask; + } + slots[i] = { key, gen, new_val }; + inserted = true; + return new_val; + } +}; + struct ggml_hexagon_opbatch { ggml_hexagon_session* sess; @@ -1255,12 +1349,13 @@ struct ggml_hexagon_opbatch { std::vector h_tens; // htp tensor descriptors std::vector h_ops; // htp op descriptors - std::unordered_map t_map; // tensor hash to index + ggml_hexagon_tensor_map t_map; // tensor hash to index unsigned int n_bufs; // num buffers in the batch unsigned int n_tens; // num tensors ... unsigned int n_ops; // num ops ... size_t b_vmem; // sum of non-extended buffer sizes + bool last_op_fusable; unsigned int n_bufs_max; unsigned int n_tens_max; @@ -1272,9 +1367,9 @@ struct ggml_hexagon_opbatch { n_tens = 0; n_ops = 0; b_vmem = 0; + last_op_fusable = false; t_map.clear(); - ops.resize(n_ops_max); } ggml_hexagon_opbatch(ggml_hexagon_session *sess, size_t batch_size, size_t max_vmem) { @@ -1292,7 +1387,7 @@ struct ggml_hexagon_opbatch { h_tens.resize(n_tens_max); h_ops.resize(n_ops_max); - t_map.reserve(n_tens_max); + t_map.init(n_tens_max); GGML_LOG_INFO("ggml-hex: %s op batching: n-bufs %u n-tensors %u n-ops %u vmem %zu\n", sess->c_name(), n_bufs_max, n_tens_max, n_ops_max, b_vmem_max); @@ -1371,20 +1466,16 @@ struct ggml_hexagon_opbatch { } static uint64_t hash_tensor(const ggml_tensor * t, const htp_tensor & shape) { - uint64_t hash = 1469598103934665603ull; - auto hash_value = [&hash](uint64_t value) { - hash ^= value; - hash *= 1099511628211ull; - }; - - hash_value((uintptr_t) t->data); - hash_value(shape.type); - hash_value(shape.size); - hash_value(shape.flags); - for (int i = 0; i < GGML_MAX_DIMS; ++i) { - hash_value(shape.ne[i]); - hash_value(shape.nb[i]); - } + uint64_t h1 = (uintptr_t) t->data ^ ((uint64_t) shape.type << 48) ^ ((uint64_t) shape.flags << 32) ^ shape.size; + uint64_t h2 = (uint64_t) shape.ne[0] + ^ ((uint64_t) shape.ne[1] * 0x9e3779b97f4a7c15ull) + ^ ((uint64_t) shape.ne[2] * 0xbf58476d1ce4e5b9ull) + ^ ((uint64_t) shape.ne[3] * 0x94d049bb133111ebull); + uint64_t h3 = (uint64_t) shape.nb[0] + ^ ((uint64_t) shape.nb[1] * 0x9e3779b97f4a7c15ull) + ^ ((uint64_t) shape.nb[2] * 0xbf58476d1ce4e5b9ull) + ^ ((uint64_t) shape.nb[3] * 0x94d049bb133111ebull); + uint64_t hash = (h1 * 0xff51afd7ed558ccdull) ^ (h2 * 0xc4ceb9fe1a85ec53ull) ^ h3; // avalanche high bits down to low bits for power-of-two table indexing hash ^= hash >> 33; @@ -1400,19 +1491,16 @@ struct ggml_hexagon_opbatch { init_tensor_shape(shape, t); const uint64_t hash = hash_tensor(t, shape); - auto it = t_map.find(hash); - if (it != t_map.end()) { - return it->second; + bool inserted = false; + int ti = t_map.find_or_insert(hash, (int) n_tens, inserted); + if (!inserted) { + return ti; } - auto sbuf = static_cast(t->buffer->context); - - // Add new tensor to the batch - int ti = n_tens++; + n_tens++; GGML_ASSERT(n_tens <= n_tens_max); - t_map[hash] = ti; - + auto sbuf = static_cast(t->buffer->context); uint64_t t_offset = (uint8_t *) t->data - sbuf->base(); htp_tensor & h = h_tens[ti]; @@ -1445,7 +1533,7 @@ struct ggml_hexagon_opbatch { if (check_tens) { htp_tensor shape {}; init_tensor_shape(shape, t); - if (t_map.count(hash_tensor(t, shape))) return; + if (t_map.contains(hash_tensor(t, shape))) return; extra_tens++; } @@ -1479,8 +1567,7 @@ struct ggml_hexagon_opbatch { return true; } - void sync_op_desc(unsigned int n) { - const htp_opnode & node = ops[n]; + void sync_op_desc(unsigned int n, const htp_opnode & node) { htp_op_desc & o = h_ops[n]; memcpy(o.params, node.params, sizeof(o.params)); @@ -1499,24 +1586,29 @@ struct ggml_hexagon_opbatch { } // caller must ensure the op fits - void add_op(const htp_opnode & node) { + void add_op(const htp_opnode & node, bool save_op = true) { unsigned int n = n_ops++; GGML_ASSERT(n_ops <= n_ops_max); - ops[n] = node; + if (save_op) { + ops[n] = node; + } + last_op_fusable = save_op; h_ops[n].flags = 0; - ggml_hexagon_dump_op_exec(sess->c_name(), ops[n], h_ops[n].flags); - sync_op_desc(n); + if (opt_verbose) { + ggml_hexagon_dump_op_exec(sess->c_name(), node, h_ops[n].flags); + } + sync_op_desc(n, node); } void sort_buffers() { if (n_bufs <= 1) return; - std::vector order(n_bufs); + int order[HTP_OP_MAX_BUFS]; for (unsigned int i = 0; i < n_bufs; i++) { order[i] = (int) i; } - std::stable_sort(order.begin(), order.end(), [&](int a, int b) { + std::stable_sort(order, order + n_bufs, [&](int a, int b) { return h_bufs[a].size > h_bufs[b].size; }); @@ -1529,8 +1621,8 @@ struct ggml_hexagon_opbatch { } if (already_sorted) return; - std::vector remap(n_bufs); - std::vector sorted_bufs(n_bufs); + uint16_t remap[HTP_OP_MAX_BUFS]; + htp_buf_desc sorted_bufs[HTP_OP_MAX_BUFS]; for (unsigned int new_bi = 0; new_bi < n_bufs; new_bi++) { int old_bi = order[new_bi]; remap[old_bi] = (uint16_t) new_bi; @@ -1553,7 +1645,7 @@ struct ggml_hexagon_opbatch { } bool try_fuse(const htp_opnode & node) { - if (n_ops == 0) { + if (n_ops == 0 || !last_op_fusable) { return false; } @@ -1562,7 +1654,8 @@ struct ggml_hexagon_opbatch { return false; } - sync_op_desc(n_ops - 1); + htp_lower_opnode(sess, last_node); + sync_op_desc(n_ops - 1, last_node); HEX_VERBOSE("ggml-hex: %s fused %s (N=%zu, #%u)\n", sess->c_name(), last_node.name().c_str(), last_node.fused.size() + 1, n_ops - 1); return true; @@ -1776,12 +1869,20 @@ void ggml_hexagon_session::flush_pending(bool all) { struct dspqueue_buffer dbuf; uint32_t n_dbufs; - // Read response packet from queue - const uint32_t timeo = opt_oppoll ? 0 : DSPQUEUE_TIMEOUT; + // opt_oppoll: 0 = block, 1 = poll, >1 = hybrid poll budget in ms + const auto poll_deadline = opt_oppoll > 1 + ? std::chrono::steady_clock::now() + std::chrono::milliseconds(opt_oppoll) + : std::chrono::steady_clock::time_point::max(); - int err = dspqueue_read(this->queue, &flags, 1, &n_dbufs, &dbuf, sizeof(rsp), &rsp_size, (uint8_t *) &rsp, timeo); - if (err == AEE_EEXPIRED || err == AEE_EWOULDBLOCK) { - continue; + int err = 0; + for (;;) { + const uint32_t timeo = (opt_oppoll == 1 || (opt_oppoll > 1 && std::chrono::steady_clock::now() < poll_deadline)) + ? 0 : DSPQUEUE_TIMEOUT; + + err = dspqueue_read(this->queue, &flags, 1, &n_dbufs, &dbuf, sizeof(rsp), &rsp_size, (uint8_t *) &rsp, timeo); + if (err != AEE_EEXPIRED && err != AEE_EWOULDBLOCK) { + break; + } } if (err != 0) { @@ -1869,10 +1970,13 @@ void ggml_hexagon_session::flush_batch(size_t min_ops) { op_batch->reset(); } -void ggml_hexagon_session::enqueue_op(const htp_opnode & node) { +void ggml_hexagon_session::enqueue_op(const htp_opnode & node, bool allow_fuse) { auto register_tensor = [&](const ggml_tensor * t) { if (!t) return; auto * sbuf = static_cast(t->buffer->context); + if (sbuf->sess == this && sbuf->mapped && this->mdev.sessions.empty()) { + return; + } if (ggml_backend_buffer_get_usage(t->buffer) == GGML_BACKEND_BUFFER_USAGE_WEIGHTS) { sbuf->extended = opt_dma64; } @@ -1896,7 +2000,7 @@ void ggml_hexagon_session::enqueue_op(const htp_opnode & node) { } const bool fits_tensors = op_batch->fit_tensors(node); - if (opt_opfusion && fits_tensors && op_batch->try_fuse(node)) { + if (opt_opfusion && allow_fuse && fits_tensors && op_batch->try_fuse(node)) { return; } @@ -1911,7 +2015,7 @@ void ggml_hexagon_session::enqueue_op(const htp_opnode & node) { } } - op_batch->add_op(node); + op_batch->add_op(node, opt_profile || (opt_opfusion && allow_fuse)); } void ggml_hexagon_session::enqueue_mdev_group() { @@ -2299,6 +2403,7 @@ void ggml_hexagon_session::allocate(const ggml_hexagon_device_config & config) n this->n_hmx = (opt_nhmx != 0) ? 1 : 0; this->vtcm_size = opt_vtcm_size > 0 ? opt_vtcm_size : 8 * 1024 * 1024; } + GGML_ASSERT(this->n_hvx > 0 && this->vtcm_size >= 2 * HTP_VTCM_GUARD_SIZE); } // Enable FastRPC QoS mode @@ -2533,18 +2638,16 @@ static ggml_status ggml_backend_hexagon_graph_compute(ggml_backend_t backend, gg HEX_VERBOSE("ggml-hex: %s graph-compute n_nodes %d\n", sess->c_name(), graph->n_nodes); - const std::vector * nodes_ptr = nullptr; - std::vector computed_nodes; - - bool cache_hit = (graph->uid != 0 && sess->cached_uid == graph->uid); - if (cache_hit) { - nodes_ptr = &sess->cached_nodes; - } else { + const bool cache_hit = graph->uid != 0 && sess->cached_uid == graph->uid; + if (!cache_hit) { ggml_hexagon_graph_repack(graph, sess); + htp_lower_reset_graph(graph); htp_fusion_tag_graph(graph); - computed_nodes.reserve(graph->n_nodes); + auto & nodes = sess->cached_nodes; + nodes.clear(); + nodes.reserve(graph->n_nodes); for (int i = 0; i < graph->n_nodes; ++i) { ggml_tensor * n = graph->nodes[i]; @@ -2559,21 +2662,22 @@ static ggml_status ggml_backend_hexagon_graph_compute(ggml_backend_t backend, gg htp_opnode node(opcode, n); GGML_ASSERT(htp_kparams_solve(sess, node)); - - computed_nodes.push_back(std::move(node)); + if (nodes.empty() || !opt_opfusion || !htp_fusion_try_fuse(sess, nodes.back(), node)) { + nodes.push_back(std::move(node)); + } } - if (graph->uid != 0) { - sess->cached_uid = graph->uid; - sess->cached_nodes = std::move(computed_nodes); - nodes_ptr = &sess->cached_nodes; - } else { - nodes_ptr = &computed_nodes; + if (opt_opfusion) { + htp_fusion_optimize_nodes(sess, graph, nodes); } + + htp_lower_graph(sess, graph, nodes); + + sess->cached_uid = graph->uid; } - for (const auto & node : *nodes_ptr) { - sess->enqueue_op(node); + for (const auto & node : sess->cached_nodes) { + sess->enqueue_op(node, false); } if (sess->last_error > HTP_STATUS_OK) { @@ -2737,7 +2841,7 @@ static std::vector ggml_hexagon_graph_optimize_reorder(const std::vector stack; stack.push_back(i0); @@ -3536,6 +3640,7 @@ static void ggml_hexagon_init(ggml_backend_reg * reg) { const char * str_opqueue = getenv("GGML_HEXAGON_OPQUEUE"); const char * str_oppoll = getenv("GGML_HEXAGON_OPPOLL"); const char * str_opfusion = getenv("GGML_HEXAGON_OPFUSION"); + const char * str_oplower = getenv("GGML_HEXAGON_OPLOWER"); const char * str_rt_repack = getenv("GGML_HEXAGON_RT_REPACK"); const char * str_opfilter = getenv("GGML_HEXAGON_OPFILTER"); const char * str_profile = getenv("GGML_HEXAGON_PROFILE"); @@ -3561,12 +3666,14 @@ static void ggml_hexagon_init(ggml_backend_reg * reg) { const char * str_power_mode = getenv("GGML_HEXAGON_POWER_MODE"); // Init Arch first since it affects other defaults + int hw_arch = 0; + int arch_err = htpdrv_get_arch(CDSP_DOMAIN_ID, &hw_arch); if (!str_arch) { - int err = htpdrv_get_arch(CDSP_DOMAIN_ID, &opt_arch); - if (err != 0) { - GGML_LOG_ERROR("ggml-hex: failed to query HTP version (err %d) defaulting to v73\n", err); + if (arch_err != 0) { + GGML_LOG_ERROR("ggml-hex: failed to query HTP version (err %d) defaulting to v73\n", arch_err); opt_arch = 73; } else { + opt_arch = hw_arch; if (opt_arch < 73) { GGML_LOG_WARN("ggml-hex: Hexagon arch v%d is under supported range, capping at v73\n", opt_arch); opt_arch = 73; @@ -3581,6 +3688,9 @@ static void ggml_hexagon_init(ggml_backend_reg * reg) { } opt_arch = strtoul(str_arch, NULL, 0); } + if (arch_err != 0) { + hw_arch = opt_arch; + } size_t MiB = 1024 * 1024; @@ -3595,8 +3705,9 @@ static void ggml_hexagon_init(ggml_backend_reg * reg) { opt_opbatch = str_opbatch ? strtoul(str_opbatch, NULL, 0) : opt_opbatch; opt_opqueue = str_opqueue ? strtoul(str_opqueue, NULL, 0) : opt_opqueue; opt_optrace = str_optrace ? strtoul(str_optrace, NULL, 0) : (opt_opbatch * HTP_TRACE_MAX_EVENTS + 131072); - opt_oppoll = str_oppoll ? strtoul(str_oppoll, NULL, 0) : opt_oppoll; + opt_oppoll = str_oppoll ? strtoul(str_oppoll, NULL, 0) : (htpdrv_has_read_noblock() ? 50 : 0); opt_opfusion = str_opfusion ? atoi(str_opfusion) : opt_opfusion; + opt_oplower = str_oplower ? (atoi(str_oplower) != 0 ? 1 : 0) : opt_oplower; opt_rt_repack = str_rt_repack ? atoi(str_rt_repack) : opt_rt_repack; opt_profile = str_profile ? atoi(str_profile) : 0; opt_etm = str_etm ? atoi(str_etm) : 0; @@ -3835,6 +3946,19 @@ static void ggml_hexagon_init(ggml_backend_reg * reg) { // Resolve domain info for all configured devices ggml_hexagon_discover_devices(); + size_t total_sessions = opt_ndev; + for (size_t i = 0; i < opt_ndev; i++) { + total_sessions += opt_device_configs[i].mdev_group.size(); + } + if (!str_mm_select && hw_arch == 73 && total_sessions > 1) { + opt_mm_select = 2; + GGML_LOG_INFO("ggml-hex: defaulting MM_SELECT=2 on multi-session v73 hardware\n"); + } + if (!str_fa_select && hw_arch == 73 && total_sessions > 1) { + opt_fa_select = 2; + GGML_LOG_INFO("ggml-hex: defaulting FA_SELECT=2 on multi-session v73 hardware\n"); + } + if (str_profile) { opt_pmu_evt = [&]() -> std::vector { auto v = str_to_vec(str_profile); diff --git a/ggml/src/ggml-hexagon/htp-common.h b/ggml/src/ggml-hexagon/htp-common.h index 235b99c13ad8..5b76b97bd51c 100644 --- a/ggml/src/ggml-hexagon/htp-common.h +++ b/ggml/src/ggml-hexagon/htp-common.h @@ -34,6 +34,7 @@ extern int opt_opqueue; extern int opt_optrace; extern int opt_oppoll; extern int opt_opfusion; +extern int opt_oplower; extern int opt_rt_repack; #ifndef HEX_VERBOSE @@ -61,10 +62,66 @@ static inline bool ggml_hexagon_tensor_is_tiled(const struct ggml_tensor * t) { return (ggml_hexagon_tensor_get_flags(t) & HTP_TENSOR_TILED) != 0; } +static inline const struct ggml_tensor * htp_tensor_root(const struct ggml_tensor * t) { + while (t && t->view_src) { + t = t->view_src; + } + return t; +} + +static inline void ggml_hexagon_tensor_clear_lowered(struct ggml_tensor * t) { + for (; t != nullptr; t = t->view_src) { + ggml_hexagon_tensor_clear_flags(t, HTP_TENSOR_LOWERED_F16); + } +} + +static inline bool ggml_hexagon_tensor_is_lowered_f16(const struct ggml_tensor * t) { + return t && (ggml_hexagon_tensor_get_flags(t) & HTP_TENSOR_LOWERED_F16) != 0; +} + +static inline bool htp_tensor_is_stored_f16(const struct ggml_tensor * t) { + return t && t->type == GGML_TYPE_F32 && + (ggml_hexagon_tensor_is_lowered_f16(t) || ggml_hexagon_tensor_is_lowered_f16(htp_tensor_root(t))); +} + +static inline enum ggml_type htp_effective_type(const struct ggml_tensor * t) { + return ggml_hexagon_tensor_is_lowered_f16(t) ? GGML_TYPE_F16 : t->type; +} + +static inline uint8_t * htp_tensor_data_ptr(const struct ggml_tensor * t) { + if (!ggml_hexagon_tensor_is_lowered_f16(t) || !t->view_src) { + return (uint8_t *) t->data; + } + const struct ggml_tensor * root = htp_tensor_root(t); + return (uint8_t *) root->data + ((const uint8_t *) t->data - (const uint8_t *) root->data) / 2; +} + +static inline size_t htp_tensor_nbytes(const struct ggml_tensor * t) { + return ggml_hexagon_tensor_is_lowered_f16(t) ? (ggml_nbytes(t) / 2) : ggml_nbytes(t); +} + +// Lower a tagged F32 tensor to F16 on the stack and clear HTP_TENSOR_LOWERED_F16 so lowering is idempotent. +static inline struct ggml_tensor htp_tensor_lower_f16(const struct ggml_tensor * t) { + struct ggml_tensor m = *t; + if (ggml_hexagon_tensor_is_lowered_f16(t)) { + m.type = GGML_TYPE_F16; + for (int d = 0; d < GGML_MAX_DIMS; ++d) { + m.nb[d] /= 2; + } + m.view_offs /= 2; + m.data = htp_tensor_data_ptr(t); + m.extra = (void *) (uintptr_t) (ggml_hexagon_tensor_get_flags(t) & ~HTP_TENSOR_LOWERED_F16); + } + return m; +} + static inline bool ggml_hexagon_tensor_can_tile(const struct ggml_tensor * t) { if (opt_rt_repack == 0) { return false; } + if (!ggml_op_is_empty(t->op)) { + return false; + } if (t->buffer) { if (ggml_backend_buft_is_host(t->buffer->buft) || ggml_backend_buffer_get_usage(t->buffer) == GGML_BACKEND_BUFFER_USAGE_COMPUTE) { @@ -79,38 +136,14 @@ static inline bool ggml_hexagon_tensor_will_tile(const struct ggml_tensor * t) { } static inline bool htp_tensors_overlap(const struct ggml_tensor * a, const struct ggml_tensor * b) { - const uintptr_t a0 = (uintptr_t) a->data; - const uintptr_t b0 = (uintptr_t) b->data; - const uintptr_t a1 = a0 + ggml_nbytes(a); - const uintptr_t b1 = b0 + ggml_nbytes(b); + const uintptr_t a0 = (uintptr_t) htp_tensor_data_ptr(a); + const uintptr_t b0 = (uintptr_t) htp_tensor_data_ptr(b); + const uintptr_t a1 = a0 + htp_tensor_nbytes(a); + const uintptr_t b1 = b0 + htp_tensor_nbytes(b); return a0 < b1 && b0 < a1; } -static inline bool htp_can_row_partition(const struct ggml_tensor * t) { - if (t->ne[1] > 1 && (t->nb[1] & 127) != 0) return false; - if (t->ne[2] > 1 && (t->nb[2] & 127) != 0) return false; - if (t->ne[3] > 1 && (t->nb[3] & 127) != 0) return false; - return true; -} - -static inline uint32_t htp_mdev_rows_per_chunk(const struct ggml_tensor * t) { - if ((t->data && ((uintptr_t) t->data & 127) != 0) || (t->view_offs & 127) != 0) return 0; - const size_t elem_size = ggml_type_size(t->type); - if (t->ne[0] != 1 && t->nb[0] != elem_size) return 0; - if (ggml_is_permuted(t)) return 0; - if (t->ne[2] > 1 && (t->nb[2] & 127) != 0) return 0; - if (t->ne[3] > 1 && (t->nb[3] & 127) != 0) return 0; - if (t->ne[1] > 1 && (t->nb[1] & 127) == 0) return 1; - const size_t row_size = (size_t) t->ne[0] * elem_size; - if (t->nb[1] == row_size && - (t->ne[2] <= 1 || t->nb[2] == t->nb[1] * (size_t) t->ne[1]) && - (t->ne[3] <= 1 || t->nb[3] == t->nb[2] * (size_t) t->ne[2])) { - return (row_size > 0) ? (HEX_L2_LINE_SIZE / hex_gcd_u32((uint32_t) row_size, HEX_L2_LINE_SIZE)) : 1; - } - return 0; -} - struct ggml_hexagon_session; const char * htp_session_name(const struct ggml_hexagon_session * sess); diff --git a/ggml/src/ggml-hexagon/htp-drv.cpp b/ggml/src/ggml-hexagon/htp-drv.cpp index 9ae4ea7275ac..224e3e432b91 100644 --- a/ggml/src/ggml-hexagon/htp-drv.cpp +++ b/ggml/src/ggml-hexagon/htp-drv.cpp @@ -174,6 +174,10 @@ AEEResult dspqueue_write(dspqueue_t queue, return dspqueue_write_pfn(queue, flags, num_buffers, buffers, message_length, message, timeout_us); } +bool htpdrv_has_read_noblock(void) { + return dspqueue_read_noblock_pfn != nullptr; +} + AEEResult dspqueue_read(dspqueue_t queue, uint32_t * flags, uint32_t max_buffers, @@ -183,12 +187,10 @@ AEEResult dspqueue_read(dspqueue_t queue, uint32_t * message_length, uint8_t * message, uint32_t timeout_us) { -#ifdef _WIN32 - if (timeout_us == 0) { + if (timeout_us == 0 && dspqueue_read_noblock_pfn != nullptr) { return dspqueue_read_noblock_pfn(queue, flags, max_buffers, num_buffers, buffers, max_message_length, - message_length, message); + message_length, message); } -#endif return dspqueue_read_pfn(queue, flags, max_buffers, num_buffers, buffers, max_message_length, message_length, message, timeout_us); } @@ -378,7 +380,7 @@ int htpdrv_init() { dlsym(handle.get(), dspqueue_export_pfn_t, dspqueue_export_pfn, dspqueue_export, false); dlsym(handle.get(), dspqueue_write_pfn_t, dspqueue_write_pfn, dspqueue_write, false); dlsym(handle.get(), dspqueue_read_pfn_t, dspqueue_read_pfn, dspqueue_read, false); - dlsym(handle.get(), dspqueue_read_noblock_pfn_t, dspqueue_read_noblock_pfn, dspqueue_read_noblock, false); + dlsym(handle.get(), dspqueue_read_noblock_pfn_t, dspqueue_read_noblock_pfn, dspqueue_read_noblock, true); dlsym(handle.get(), remote_handle64_open_pfn_t, remote_handle64_open_pfn, remote_handle64_open, false); dlsym(handle.get(), remote_handle64_invoke_pfn_t, remote_handle64_invoke_pfn, remote_handle64_invoke, false); dlsym(handle.get(), remote_handle_control_pfn_t, remote_handle_control_pfn, remote_handle_control, false); diff --git a/ggml/src/ggml-hexagon/htp-drv.h b/ggml/src/ggml-hexagon/htp-drv.h index c88a72940adb..4aa34a21f5a4 100644 --- a/ggml/src/ggml-hexagon/htp-drv.h +++ b/ggml/src/ggml-hexagon/htp-drv.h @@ -117,6 +117,7 @@ HTPDRV_API domain * htpdrv_get_domain(int domain_id); HTPDRV_API int htpdrv_get_arch(int domain, int * arch); HTPDRV_API int remote_system_request(system_req_payload * req); +HTPDRV_API bool htpdrv_has_read_noblock(void); #ifdef __cplusplus } diff --git a/ggml/src/ggml-hexagon/htp-fusion.cpp b/ggml/src/ggml-hexagon/htp-fusion.cpp index eb08626692f4..35972964f275 100644 --- a/ggml/src/ggml-hexagon/htp-fusion.cpp +++ b/ggml/src/ggml-hexagon/htp-fusion.cpp @@ -51,14 +51,15 @@ static inline bool htp_match_consumer( static bool is_supported_mul_mat_nx_kernel(const ggml_tensor * src0, const struct htp_mm_kernel_params * kparams) { if (kparams->n_hmx) { - return kparams->kernel_type == HTP_MM_KERNEL_HMX_2D; + return htp_mm_kernel_is_hmx_2d(kparams->kernel_type); } - return ggml_hexagon_tensor_is_tiled(src0) && (kparams->kernel_type == HTP_MM_KERNEL_HVX_QUANT_ROW); + return ggml_hexagon_tensor_is_tiled(src0) && + (kparams->kernel_type == HTP_MM_KERNEL_HVX_QUANT_ROW || kparams->kernel_type == HTP_MM_KERNEL_HVX_QUANT_BLOCK); } static bool is_supported_mul_mat_id_nx_kernel(const ggml_tensor * src0, const struct htp_mm_kernel_params * kparams) { if (kparams->n_hmx) { - return kparams->kernel_type == HTP_MM_KERNEL_HMX_2D; + return htp_mm_kernel_is_hmx_2d(kparams->kernel_type); } return ggml_hexagon_tensor_is_tiled(src0) && (kparams->kernel_type == HTP_MM_KERNEL_HVX_QUANT_ROW || kparams->kernel_type == HTP_MM_KERNEL_HVX_QUANT_BLOCK); @@ -76,21 +77,23 @@ static bool fuse_allreduce_add(const ggml_hexagon_session * sess, htp_opnode & p const ggml_tensor * ar_local = prev.inputs[rank]; if (!ggml_hexagon_tensor_is_fuseable(ar_local)) return false; + if (cur.inputs.size() < 2) return false; + const ggml_tensor * cur_src0 = cur.inputs[0]; + const ggml_tensor * cur_src1 = cur.inputs[1]; const ggml_tensor * add_dst = cur.dst(); const ggml_tensor * res_tensor = nullptr; - if (htp_same_tensor_data(cur.src0(), ar_local)) { - res_tensor = cur.src1(); - } else if (htp_same_tensor_data(cur.src1(), ar_local)) { - res_tensor = cur.src0(); + if (htp_same_tensor_data(cur_src0, ar_local)) { + res_tensor = cur_src1; + } else if (htp_same_tensor_data(cur_src1, ar_local)) { + res_tensor = cur_src0; } else { return false; } - if (ar_local->type != res_tensor->type) return false; + if (ar_local->type != res_tensor->type || ar_local->type != add_dst->type) return false; const bool is_same_shape = ggml_are_same_shape(ar_local, res_tensor); - const bool is_row_bcast = !is_same_shape && (ar_local->ne[0] == res_tensor->ne[0] && - res_tensor->ne[1] == 1 && res_tensor->ne[2] == 1 && res_tensor->ne[3] == 1); + const bool is_row_bcast = !is_same_shape && (ar_local->ne[0] == res_tensor->ne[0] && ggml_is_vector(res_tensor)); if (!is_same_shape && !is_row_bcast) return false; if (is_same_shape && !ggml_are_same_stride(ar_local, res_tensor)) { @@ -135,12 +138,15 @@ static bool fuse_rms_norm_mul(const ggml_hexagon_session * sess, htp_opnode & pr const ggml_tensor * src0 = prev.src0(); const ggml_tensor * dst = cur.dst(); - if (src0->type != GGML_TYPE_F32 || src0->ne[0] != weight->ne[0] || !htp_same_shape_and_contiguity(prev.dst(), dst)) return false; + if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || + (weight->type != GGML_TYPE_F32 && weight->type != GGML_TYPE_F16) || + src0->ne[0] != weight->ne[0] || !htp_same_shape_and_contiguity(prev.dst(), dst)) return false; if (htp_inputs_overlap_unsafe(prev, dst, weight)) return false; - const bool is_row_bcast = (weight->ne[1] == 1 && weight->ne[2] == 1 && weight->ne[3] == 1); + const bool is_row_bcast = ggml_is_vector(weight); + const bool is_dim1_bcast = (weight->ne[1] == src0->ne[1] && ggml_is_matrix(weight)); const bool is_same_shape = ggml_are_same_shape(src0, weight); - if (!is_row_bcast && !is_same_shape) return false; + if (!is_row_bcast && !is_dim1_bcast && !is_same_shape) return false; struct htp_unary_kernel_params kparams; if (!htp_kparams_solve_rms_norm_mul(sess, src0, weight, dst, &kparams)) { @@ -167,11 +173,13 @@ static bool fuse_rms_norm_mul_add(const ggml_hexagon_session * sess, htp_opnode const ggml_tensor * src0 = prev.src0(); const ggml_tensor * weight = prev.inputs[1]; const ggml_tensor * dst = cur.dst(); - if (!ggml_are_same_layout(src0, r)) return false; + if ((r->type != GGML_TYPE_F32 && r->type != GGML_TYPE_F16) || + (weight->type != GGML_TYPE_F32 && weight->type != GGML_TYPE_F16)) return false; + if (!ggml_are_same_shape(src0, r) || (ggml_is_contiguous(src0) != ggml_is_contiguous(r))) return false; if (htp_inputs_overlap_unsafe(prev, dst, r)) return false; struct htp_unary_kernel_params kparams; - if (!htp_kparams_solve_rms_norm_mul_add(sess, src0, weight, dst, &kparams)) return false; + if (!htp_kparams_solve_rms_norm_mul_add(sess, src0, weight, r, dst, &kparams)) return false; prev.opcode = HTP_OP_RMS_NORM_MUL_ADD; prev.inputs.push_back(r); @@ -188,7 +196,7 @@ static bool fuse_rms_norm_scale(const ggml_hexagon_session * sess, htp_opnode & const ggml_tensor * src0 = prev.src0(); const ggml_tensor * dst = cur.dst(); - if (src0->type != GGML_TYPE_F32 || !htp_same_shape_and_contiguity(prev.dst(), dst)) return false; + if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || !htp_same_shape_and_contiguity(prev.dst(), dst)) return false; if (htp_inputs_overlap_unsafe(prev, dst)) return false; float scale = 0.0f; @@ -214,13 +222,27 @@ static bool fuse_mul_mat_add(const ggml_hexagon_session * sess, htp_opnode & pre const ggml_tensor * src2 = nullptr; if (!htp_match_consumer(prev, cur, /*commutative=*/ true, &src2)) return false; - if (src2->type != GGML_TYPE_F32) return false; + if ((src2->type != GGML_TYPE_F32 && src2->type != GGML_TYPE_F16) || + !ggml_is_contiguous_to_2(src2)) { + return false; + } const ggml_tensor * src0 = prev.node->src[0]; const ggml_tensor * src1 = prev.node->src[1]; const ggml_tensor * dst = cur.node; if (!ggml_are_same_shape(prev.node, dst)) return false; + // Require matching ne[0], valid broadcast dims (1 or equal), and no unsafe overlap. + if (src2->ne[0] != dst->ne[0] || + (src2->ne[1] != 1 && src2->ne[1] != dst->ne[1]) || + (src2->ne[2] != 1 && src2->ne[2] != dst->ne[2]) || + (src2->ne[3] != 1 && src2->ne[3] != dst->ne[3])) { + return false; + } + if (htp_tensors_overlap(dst, src0) || htp_tensors_overlap(dst, src1) || htp_inplace_overlap_unsafe(dst, src2)) { + return false; + } + const bool prev_collapsed = htp_matmul_can_collapse(src0, src1, prev.node); const bool cur_collapsed = htp_matmul_add_can_collapse(src0, src1, src2, dst); if (prev_collapsed != cur_collapsed) { @@ -233,12 +255,12 @@ static bool fuse_mul_mat_add(const ggml_hexagon_session * sess, htp_opnode & pre return false; } - const int src1_nrows = src1->ne[1] * src1->ne[2] * src1->ne[3]; - if (kparams.n_hmx == 0 && src1_nrows != 1) return false; + const int src1_nrows = (int) ggml_nrows(src1); + const bool is_batched = (!ggml_is_matrix(src0) || !ggml_is_matrix(src1)); + if (kparams.n_hmx == 0 && (src1_nrows != 1 || is_batched)) return false; if (kparams.n_hmx > 0 && orig_kparams->n_hmx > 0) { if (kparams.m_chunk < orig_kparams->m_chunk || - kparams.n_chunk < orig_kparams->n_chunk || kparams.n_act_hvx < orig_kparams->n_act_hvx) { HEX_VERBOSE("ggml-hex: %s skip MUL_MAT_ADD fusion: HMX efficiency reduced (m %d->%d, n %d->%d, hvx %d->%d)\n", htp_session_name(sess), orig_kparams->m_chunk, kparams.m_chunk, @@ -251,7 +273,6 @@ static bool fuse_mul_mat_add(const ggml_hexagon_session * sess, htp_opnode & pre prev.opcode = HTP_OP_MUL_MAT_ADD; prev.inputs = { src0, src1, src2 }; prev.outputs = { dst }; - htp_opnode_collapse(sess, prev); prev.fused.push_back(cur.node); prev.set_kparams(kparams); return true; @@ -273,21 +294,36 @@ static bool fuse_mul_mat_nx(const ggml_hexagon_session * sess, htp_opnode & prev const auto * cur_kparams = cur.kparams(); if (x_in != x_orig || w_in->type != w0->type || w_in->ne[0] != w0->ne[0] || - w0->ne[2] != 1 || w0->ne[3] != 1 || w_in->ne[2] != 1 || w_in->ne[3] != 1 || + !ggml_is_matrix(w0) || !ggml_is_matrix(w_in) || ggml_hexagon_tensor_is_tiled(w_in) != ggml_hexagon_tensor_is_tiled(w0) || - orig_kparams->n_hmx != cur_kparams->n_hmx) { + orig_kparams->n_hmx != cur_kparams->n_hmx || + orig_kparams->kernel_type != cur_kparams->kernel_type) { return false; } const bool collapse = htp_matmul_can_collapse(w0, x_orig, prev.node) && htp_matmul_can_collapse(w_in, x_in, d_in); - if ((x_orig->ne[2] > 1 || x_orig->ne[3] > 1) && !collapse) return false; + if (!ggml_is_matrix(x_orig) && !collapse) return false; + + const ggml_tensor * prev_w = prev.inputs[0]; + ggml_type prev_dst_type = prev.outputs[0]->type; + for (size_t i = 1; i < curr_n; ++i) { + if (prev.inputs[i]->ne[1] > prev_w->ne[1]) prev_w = prev.inputs[i]; + if (ggml_type_size(prev.outputs[i]->type) > ggml_type_size(prev_dst_type)) { + prev_dst_type = prev.outputs[i]->type; + } + } + const ggml_tensor * w_for_solve = (w_in->ne[1] > prev_w->ne[1]) ? w_in : prev_w; + const ggml_type max_dst_type = (ggml_type_size(d_in->type) > ggml_type_size(prev_dst_type)) ? d_in->type : prev_dst_type; - if (prev.opcode == HTP_OP_MUL_MAT_NX) { + if (prev.opcode == HTP_OP_MUL_MAT_NX && w_for_solve == prev_w && + ggml_type_size(max_dst_type) == ggml_type_size(prev_dst_type)) { orig_kparams->n_weights = curr_n + 1; } else { struct htp_mm_kernel_params kparams; const ggml_tensor x_collapsed = collapse ? htp_tensor_collapse_rows(x_orig) : *x_orig; - if (!htp_kparams_solve_mmnx(sess, w0, &x_collapsed, curr_n + 1, &kparams)) return false; + ggml_tensor d_collapsed = collapse ? htp_tensor_collapse_rows(prev.outputs[0]) : *prev.outputs[0]; + d_collapsed.type = max_dst_type; + if (!htp_kparams_solve_mmnx(sess, w_for_solve, &x_collapsed, &d_collapsed, curr_n + 1, &kparams)) return false; if (!is_supported_mul_mat_nx_kernel(w0, &kparams)) return false; prev.set_kparams(kparams); @@ -295,8 +331,98 @@ static bool fuse_mul_mat_nx(const ggml_hexagon_session * sess, htp_opnode & prev } prev.inputs.insert(prev.inputs.begin() + curr_n, w_in); - prev.outputs.push_back(collapse ? prev.add_dummy(htp_tensor_collapse_rows(d_in)) : d_in); + prev.outputs.push_back(d_in); + prev.fused.push_back(cur.node); + return true; +} + +static bool htp_is_fuseable_mmnx_glu_op(uint32_t op) { + return op == HTP_OP_GLU_SWIGLU || op == HTP_OP_GLU_GEGLU || + op == HTP_OP_GLU_GEGLU_QUICK || op == HTP_OP_GLU_REGLU; +} + +static bool fuse_mul_mat_nx_glu(const ggml_hexagon_session * sess, htp_opnode & prev, const htp_opnode & cur) { + if (prev.opcode != HTP_OP_MUL_MAT_NX || prev.outputs.size() != 2 || prev.inputs.size() != 3) { + return false; + } + if (!htp_is_fuseable_mmnx_glu_op(cur.opcode) || cur.inputs.size() != 2 || cur.outputs.size() != 1 || !cur.src1()) { + return false; + } + if (prev.fused.size() + 1 + cur.fused.size() > HTP_OP_MAX_FUSED) { + return false; + } + + const auto * orig_kparams = prev.kparams(); + if (!orig_kparams->n_hmx || !htp_mm_kernel_is_hmx_2d(orig_kparams->kernel_type)) { + return false; + } + + const ggml_tensor * out0 = prev.outputs[0]; + const ggml_tensor * out1 = prev.outputs[1]; + if (!ggml_hexagon_tensor_is_fuseable(out0) || !ggml_hexagon_tensor_is_fuseable(out1) || + (out0->flags & GGML_TENSOR_FLAG_OUTPUT) || (out1->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return false; + } + if (ggml_prec_get_acc(out0) == GGML_PREC_F32 || ggml_prec_get_acc(out1) == GGML_PREC_F32) { + return false; + } + + const ggml_tensor * w_gate = nullptr; + const ggml_tensor * w_up = nullptr; + const ggml_tensor * out_gate = nullptr; + const ggml_tensor * out_up = nullptr; + if (htp_same_tensor_data(cur.src0(), out0) && htp_same_tensor_data(cur.src1(), out1)) { + w_gate = prev.inputs[0]; + w_up = prev.inputs[1]; + out_gate = out0; + out_up = out1; + } else if (htp_same_tensor_data(cur.src0(), out1) && htp_same_tensor_data(cur.src1(), out0)) { + w_gate = prev.inputs[1]; + w_up = prev.inputs[0]; + out_gate = out1; + out_up = out0; + } else { + return false; + } + + const ggml_tensor * act = prev.inputs[2]; + const ggml_tensor * dst = cur.dst(); + if (w_gate->ne[1] != w_up->ne[1] || w_gate->ne[0] != w_up->ne[0] || + !ggml_is_contiguous(out_gate) || !ggml_is_contiguous(out_up) || !ggml_is_contiguous(dst) || + out_gate->type != cur.src0()->type || out_up->type != cur.src1()->type || + !ggml_are_same_shape(out_gate, cur.src0()) || !ggml_are_same_stride(out_gate, cur.src0()) || + !ggml_are_same_shape(out_up, cur.src1()) || !ggml_are_same_stride(out_up, cur.src1()) || + !ggml_are_same_shape(out_gate, dst)) { + return false; + } + if (dst->type != GGML_TYPE_F16 && dst->type != GGML_TYPE_F32) { + return false; + } + if (htp_tensors_overlap(dst, w_gate) || htp_tensors_overlap(dst, w_up) || htp_tensors_overlap(dst, act)) { + return false; + } + + const bool collapse = htp_matmul_can_collapse(w_gate, act, dst) && htp_matmul_can_collapse(w_up, act, dst); + if (!ggml_is_matrix(act) && !collapse) { + return false; + } + + const ggml_tensor x_collapsed = collapse ? htp_tensor_collapse_rows(act) : *act; + const ggml_tensor d_collapsed = collapse ? htp_tensor_collapse_rows(dst) : *dst; + + struct htp_mm_kernel_params kparams; + if (!htp_kparams_solve_mmnx_glu(sess, w_gate, w_up, &x_collapsed, &d_collapsed, (uint8_t) cur.opcode, &kparams)) { + return false; + } + + prev.opcode = HTP_OP_MUL_MAT_NX_GLU; + prev.inputs = { w_gate, w_up, act }; + prev.outputs = { dst }; prev.fused.push_back(cur.node); + for (const ggml_tensor * f : cur.fused) { + prev.fused.push_back(f); + } + prev.set_kparams(kparams); return true; } @@ -380,7 +506,6 @@ static bool fuse_gdn_cpy(const ggml_hexagon_session * sess, htp_opnode & prev, c } static bool fuse_ssm_conv_silu(const ggml_hexagon_session * sess, htp_opnode & prev, const htp_opnode & cur) { - GGML_UNUSED(sess); if (prev.opcode != HTP_OP_SSM_CONV) return false; auto * kparams = prev.kparams(); @@ -389,12 +514,17 @@ static bool fuse_ssm_conv_silu(const ggml_hexagon_session * sess, htp_opnode & p const ggml_tensor * conv_dst = prev.dst(); const ggml_tensor * dst = cur.dst(); - if (!ggml_are_same_layout(conv_dst, dst)) return false; + if (!ggml_are_same_shape(conv_dst, cur.src0()) || !ggml_are_same_stride(conv_dst, cur.src0())) return false; + if (!ggml_are_same_shape(conv_dst, dst)) return false; if (htp_tensors_overlap(dst, prev.src0()) || htp_tensors_overlap(dst, prev.src1())) return false; - kparams->silu = 1; - prev.outputs[0] = dst; - prev.fused.push_back(cur.node); + htp_opnode cand = prev; + cand.outputs[0] = dst; + cand.fused.push_back(cur.node); + cand.kparams()->silu = 1; + if (!htp_kparams_solve(sess, cand)) return false; + + prev = std::move(cand); return true; } @@ -421,6 +551,97 @@ static bool fuse_repeat_get_rows(const ggml_hexagon_session * sess, htp_opnode & return true; } +static inline bool htp_is_scale_bias_unary(uint32_t opcode) { + switch (opcode) { + case HTP_OP_UNARY_EXP: + case HTP_OP_UNARY_SIGMOID: + case HTP_OP_UNARY_SILU: + case HTP_OP_UNARY_GELU: + case HTP_OP_UNARY_GELU_QUICK: + case HTP_OP_UNARY_GELU_ERF: + case HTP_OP_UNARY_SOFTPLUS: + case HTP_OP_UNARY_TANH: + return true; + default: + return false; + } +} + +static bool fuse_scale_unary(const ggml_hexagon_session * sess, htp_opnode & prev, const htp_opnode & cur) { + if (prev.opcode != HTP_OP_SCALE || !prev.fused.empty() || !htp_is_scale_bias_unary(cur.opcode)) return false; + if (cur.kparams()->has_scale_bias) return false; + if (!htp_match_consumer(prev, cur, /*commutative=*/ false)) return false; + + const ggml_tensor * src0 = prev.src0(); + const ggml_tensor * dst = cur.dst(); + if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || + dst->type != src0->type || !htp_same_shape_and_contiguity(prev.dst(), dst)) { + return false; + } + if (htp_inputs_overlap_unsafe(prev, dst)) return false; + + float in_scale = 0.0f; + float in_bias = 0.0f; + memcpy(&in_scale, (const float *) prev.params + 0, sizeof(float)); + memcpy(&in_bias, (const float *) prev.params + 1, sizeof(float)); + + htp_opnode cand = prev; + cand.opcode = cur.opcode; + cand.outputs = { dst }; + memcpy(cand.params, cur.params, sizeof(cand.params)); + + auto * kp = cand.kparams(); + kp->has_scale_bias = 1; + kp->in_scale = in_scale; + kp->in_bias = in_bias; + kp->out_scale = 1.0f; + kp->out_bias = 0.0f; + if (!htp_kparams_solve(sess, cand)) return false; + + prev = std::move(cand); + prev.fused.push_back(cur.node); + return true; +} + +static bool fuse_unary_scale(const ggml_hexagon_session * sess, htp_opnode & prev, const htp_opnode & cur) { + if (!htp_is_scale_bias_unary(prev.opcode) || prev.fused.size() >= HTP_OP_MAX_FUSED) return false; + if (!htp_match_consumer(prev, cur, /*commutative=*/ false)) return false; + + const ggml_tensor * src0 = prev.src0(); + const ggml_tensor * dst = cur.dst(); + if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || + dst->type != src0->type || !htp_same_shape_and_contiguity(prev.dst(), dst)) { + return false; + } + if (htp_inputs_overlap_unsafe(prev, dst)) return false; + + float s_out = 0.0f; + float b_out = 0.0f; + memcpy(&s_out, (const float *) cur.params + 0, sizeof(float)); + memcpy(&b_out, (const float *) cur.params + 1, sizeof(float)); + + const auto * prev_kp = prev.kparams(); + const float in_scale = prev_kp->has_scale_bias ? prev_kp->in_scale : 1.0f; + const float in_bias = prev_kp->has_scale_bias ? prev_kp->in_bias : 0.0f; + const float out_scale = (prev_kp->has_scale_bias ? prev_kp->out_scale : 1.0f) * s_out; + const float out_bias = (prev_kp->has_scale_bias ? prev_kp->out_bias : 0.0f) * s_out + b_out; + + htp_opnode cand = prev; + cand.outputs = { dst }; + + auto * kp = cand.kparams(); + kp->has_scale_bias = 1; + kp->in_scale = in_scale; + kp->in_bias = in_bias; + kp->out_scale = out_scale; + kp->out_bias = out_bias; + if (!htp_kparams_solve(sess, cand)) return false; + + prev = std::move(cand); + prev.fused.push_back(cur.node); + return true; +} + static bool fuse_unary_mul_glu(const ggml_hexagon_session * sess, htp_opnode & prev, const htp_opnode & cur) { htp_op_code glu_op = HTP_OP_INVALID; switch (prev.opcode) { @@ -432,6 +653,7 @@ static bool fuse_unary_mul_glu(const ggml_hexagon_session * sess, htp_opnode & p case HTP_OP_UNARY_SIGMOID: glu_op = HTP_OP_GLU_SIGMOID; break; default: return false; } + if (prev.kparams()->has_scale_bias) return false; const ggml_tensor * up = nullptr; if (!htp_match_consumer(prev, cur, /*commutative=*/ true, &up)) return false; @@ -440,11 +662,13 @@ static bool fuse_unary_mul_glu(const ggml_hexagon_session * sess, htp_opnode & p const ggml_tensor * dst = cur.dst(); if (htp_inputs_overlap_unsafe(prev, dst, up)) return false; - prev.opcode = glu_op; - prev.inputs = { gate, up }; - prev.outputs = { dst }; - if (!htp_kparams_solve(sess, prev)) return false; + htp_opnode cand = prev; + cand.opcode = glu_op; + cand.inputs = { gate, up }; + cand.outputs = { dst }; + if (!htp_kparams_solve(sess, cand)) return false; + prev = std::move(cand); prev.fused.push_back(cur.node); memset(prev.params, 0, sizeof(prev.params)); return true; @@ -463,6 +687,7 @@ static bool fuse_mul_mul_scalar(const ggml_hexagon_session * sess, htp_opnode & const ggml_tensor * src1 = prev.src1(); const ggml_tensor * dst = cur.dst(); + if (prev.src0()->type != src1->type || prev.dst()->type != src1->type || src2->type != src1->type || dst->type != src1->type) return false; if (!ggml_are_same_shape(src1, src2) || !htp_same_shape_and_contiguity(prev.dst(), dst)) return false; if (htp_inputs_overlap_unsafe(prev, dst, src2)) return false; @@ -506,6 +731,10 @@ static bool fuse_binary_nx(const ggml_hexagon_session * sess, htp_opnode & prev, const ggml_tensor * src0 = prev.inputs[0]; const ggml_tensor * dst = cur.dst(); + if (prev.dst()->type != src0->type || new_src->type != src0->type || dst->type != src0->type) return false; + for (const auto * in : prev.inputs) { + if (in->type != src0->type) return false; + } if (!ggml_are_same_shape(src0, prev.inputs[1]) || !ggml_are_same_shape(src0, new_src) || !htp_same_shape_and_contiguity(prev.dst(), dst)) { @@ -547,7 +776,7 @@ static bool fuse_binary_nx(const ggml_hexagon_session * sess, htp_opnode & prev, const uint32_t total_elems = (uint32_t) ggml_nelements(src0); const uint32_t elem_size = (uint32_t) ggml_type_size(src0->type); const uint32_t max_hvx = htp_session_n_hvx(sess); - if (!htp_binary_solve_chunked(&L, &kparams, total_elems, elem_size, max_hvx, n_srcs, false, vtcm_size)) { + if (!htp_binary_solve_chunked(&L, &kparams, total_elems, elem_size, elem_size, elem_size, max_hvx, n_srcs, false, vtcm_size)) { return false; } } @@ -569,7 +798,8 @@ bool htp_fusion_can_stack(const struct ggml_tensor * a) { if (!htp_fusion_enabled(HTP_FUSE_MUL_MAT_NX)) return false; if (htp_is_hadamard(a)) return false; if (a->src[0]->ne[2] != 1 || a->src[0]->ne[3] != 1) return false; - return ggml_is_quantized(a->src[0]->type); + return ggml_is_quantized(a->src[0]->type) || + (a->src[0]->type == GGML_TYPE_F16 && a->src[0]->ne[0] % 32 == 0); case GGML_OP_MUL_MAT_ID: if (!htp_fusion_enabled(HTP_FUSE_MUL_MAT_ID_NX)) return false; return a->src[2] != nullptr && ggml_is_quantized(a->src[0]->type); @@ -639,6 +869,7 @@ void htp_fusion_tag_graph(struct ggml_cgraph * graph) { bool htp_fusion_try_fuse(const struct ggml_hexagon_session * sess, struct htp_opnode & prev, const struct htp_opnode & cur) { if (!opt_opfusion) return false; + if (!cur.fused.empty()) return false; switch (cur.opcode) { case HTP_OP_ADD: @@ -655,9 +886,19 @@ bool htp_fusion_try_fuse(const struct ggml_hexagon_session * sess, struct htp_op case HTP_OP_DIV: return htp_fusion_enabled(HTP_FUSE_BINARY_NX) && fuse_binary_nx(sess, prev, cur); case HTP_OP_SCALE: - return htp_fusion_enabled(HTP_FUSE_RMS_NORM_SCALE) && fuse_rms_norm_scale(sess, prev, cur); + return (htp_fusion_enabled(HTP_FUSE_RMS_NORM_SCALE) && fuse_rms_norm_scale(sess, prev, cur)) || + (htp_fusion_enabled(HTP_FUSE_UNARY_SCALE) && fuse_unary_scale(sess, prev, cur)); case HTP_OP_UNARY_SILU: - return htp_fusion_enabled(HTP_FUSE_SSM_CONV_SILU) && fuse_ssm_conv_silu(sess, prev, cur); + return (htp_fusion_enabled(HTP_FUSE_SSM_CONV_SILU) && fuse_ssm_conv_silu(sess, prev, cur)) || + (htp_fusion_enabled(HTP_FUSE_UNARY_SCALE) && fuse_scale_unary(sess, prev, cur)); + case HTP_OP_UNARY_EXP: + case HTP_OP_UNARY_SIGMOID: + case HTP_OP_UNARY_GELU: + case HTP_OP_UNARY_GELU_QUICK: + case HTP_OP_UNARY_GELU_ERF: + case HTP_OP_UNARY_SOFTPLUS: + case HTP_OP_UNARY_TANH: + return htp_fusion_enabled(HTP_FUSE_UNARY_SCALE) && fuse_scale_unary(sess, prev, cur); case HTP_OP_GET_ROWS: return htp_fusion_enabled(HTP_FUSE_REPEAT_GET_ROWS) && fuse_repeat_get_rows(sess, prev, cur); case HTP_OP_CPY: @@ -666,7 +907,396 @@ bool htp_fusion_try_fuse(const struct ggml_hexagon_session * sess, struct htp_op return htp_fusion_enabled(HTP_FUSE_MUL_MAT_NX) && fuse_mul_mat_nx(sess, prev, cur); case HTP_OP_MUL_MAT_ID: return htp_fusion_enabled(HTP_FUSE_MUL_MAT_ID_NX) && fuse_mul_mat_id_nx(sess, prev, cur); + case HTP_OP_GLU_SWIGLU: + case HTP_OP_GLU_GEGLU: + case HTP_OP_GLU_GEGLU_QUICK: + case HTP_OP_GLU_REGLU: + return htp_fusion_enabled(HTP_FUSE_MUL_MAT_NX_GLU) && fuse_mul_mat_nx_glu(sess, prev, cur); default: return false; } } + +static void htp_fuse_gdn_state(const struct ggml_hexagon_session * sess, std::vector & nodes) { + for (size_t c = 0; c < nodes.size(); ++c) { + if (nodes[c].opcode != HTP_OP_GATED_DELTA_NET || nodes[c].inputs.size() != 6 || + nodes[c].fused.size() >= HTP_OP_MAX_FUSED) { + continue; + } + const ggml_tensor * v = nodes[c].inputs[2]; + const ggml_tensor * s = nodes[c].inputs[5]; + + const ggml_tensor * base_s = s; + while (base_s->view_src && + (base_s->op == GGML_OP_RESHAPE || (base_s->op == GGML_OP_VIEW && base_s->view_offs == 0)) && + ggml_is_contiguous(base_s)) { + base_s = base_s->view_src; + } + if (base_s->flags & GGML_TENSOR_FLAG_OUTPUT) continue; + + size_t p = c; + for (size_t i = 0; i < c; ++i) { + if (nodes[i].opcode == HTP_OP_GET_ROWS && nodes[i].fused.empty() && + nodes[i].outputs.size() == 1 && nodes[i].dst() == base_s) { + p = i; + break; + } + } + if (p == c) continue; + + const ggml_tensor * gr_src0 = nodes[p].src0(); + const ggml_tensor * gr_src1 = nodes[p].src1(); + const int64_t n_seqs = v->ne[3]; + if (htp_tensors_overlap(nodes[c].outputs[0], gr_src0) || htp_tensors_overlap(nodes[c].outputs[0], gr_src1)) { + continue; + } + if (nodes[c].outputs.size() > 1 && nodes[c].outputs[1]) { + const ggml_tensor * dst_cache = nodes[c].outputs[1]; + if (htp_tensors_overlap(dst_cache, gr_src1)) continue; + if (htp_tensors_overlap(gr_src0, dst_cache)) { + const uintptr_t src0_ptr = (uintptr_t) htp_tensor_data_ptr(gr_src0); + const uintptr_t dst_ptr = (uintptr_t) htp_tensor_data_ptr(dst_cache); + const bool slot_aligned = (n_seqs == 1) && + (dst_cache->type == gr_src0->type) && + (dst_ptr >= src0_ptr) && + (gr_src0->nb[1] > 0) && + ((dst_ptr - src0_ptr) % gr_src0->nb[1] == 0) && + (dst_cache->ne[2] == 1 || gr_src0->nb[1] == dst_cache->nb[2]); + if (!slot_aligned) continue; + } + } + + bool safe = true; + for (size_t k = 0; k < nodes.size() && safe; ++k) { + if (k == p) continue; + if (k != c) { + for (const ggml_tensor * in : nodes[k].inputs) { + for (const ggml_tensor * t = in; t != nullptr; t = t->view_src) { + if (t == base_s) { safe = false; break; } + } + if (!safe) break; + } + } + if (k > p && k < c) { + for (const ggml_tensor * out : nodes[k].outputs) { + if (out && (htp_tensors_overlap(out, gr_src0) || htp_tensors_overlap(out, gr_src1) || + htp_tensors_overlap(out, base_s))) { + safe = false; + break; + } + } + } + } + if (!safe) continue; + + htp_opnode cand = nodes[c]; + cand.inputs[5] = gr_src0; + cand.inputs.push_back(gr_src1); + cand.fused.insert(cand.fused.begin(), nodes[p].node); + if (!htp_kparams_solve(sess, cand)) continue; + + nodes[c] = std::move(cand); + nodes.erase(nodes.begin() + (ptrdiff_t) p); + --c; + } +} + +static bool htp_unwrap_transpose_01(const ggml_tensor * t, const ggml_tensor ** out_src) { + if (!t || !t->view_src || t->view_offs != 0) { + return false; + } + if (t->op == GGML_OP_TRANSPOSE) { + *out_src = t->view_src; + return true; + } + if (t->op == GGML_OP_PERMUTE) { + if (ggml_get_op_params_i32(t, 0) == 1 && + ggml_get_op_params_i32(t, 1) == 0 && + ggml_get_op_params_i32(t, 2) == 2 && + ggml_get_op_params_i32(t, 3) == 3) { + *out_src = t->view_src; + return true; + } + } + return false; +} + +static bool htp_tensor_is_view_of(const ggml_tensor * in, const ggml_tensor * target) { + if (!in || !target) { + return false; + } + for (const ggml_tensor * t = in; t != nullptr; t = t->view_src) { + if (t == target) { + return true; + } + } + return false; +} + +static bool htp_tensor_reads_from(const ggml_tensor * in, const ggml_tensor * target) { + if (!in || !target) { + return false; + } + if (htp_tensor_is_view_of(in, target)) { + return true; + } + return htp_tensors_overlap(in, target); +} + +static void htp_fuse_concat_ssm_conv(const struct ggml_hexagon_session * sess, std::vector & nodes) { + for (size_t c = 0; c < nodes.size(); ++c) { + if (nodes[c].opcode != HTP_OP_SSM_CONV || nodes[c].inputs.size() != 2 || + nodes[c].outputs.size() != 1 || nodes[c].fused.size() >= HTP_OP_MAX_FUSED) { + continue; + } + + const ggml_tensor * conv_x = nodes[c].src0(); + const ggml_tensor * conv_weight = nodes[c].src1(); + const ggml_tensor * conv_dst = nodes[c].dst(); + if (conv_x->flags & GGML_TENSOR_FLAG_OUTPUT) { + continue; + } + + size_t p = c; + for (size_t i = 0; i < c; ++i) { + if (nodes[i].opcode == HTP_OP_CONCAT && nodes[i].fused.empty() && + nodes[i].outputs.size() == 1 && nodes[i].dst() == conv_x && + ggml_get_op_params_i32(nodes[i].node, 0) == 0) { + p = i; + break; + } + } + if (p == c) { + continue; + } + + const ggml_tensor * cat_state = nodes[p].src0(); + const ggml_tensor * cat_xT = nodes[p].src1(); + const ggml_tensor * cat_x = nullptr; + if (!htp_unwrap_transpose_01(cat_xT, &cat_x)) { + continue; + } + + const int64_t d_conv = conv_weight->ne[0]; + const int64_t d_inner = conv_weight->ne[1]; + const int64_t n_t = conv_dst->ne[1]; + const int64_t n_s = conv_dst->ne[2]; + const int64_t S = d_conv - 1; + + size_t q = nodes.size(); + size_t n_other = 0; + for (size_t k = 0; k < nodes.size(); ++k) { + if (k == p || k == c) { + continue; + } + bool uses_conv_x = false; + for (const ggml_tensor * in : nodes[k].inputs) { + if (htp_tensor_is_view_of(in, conv_x)) { + uses_conv_x = true; + break; + } + } + if (uses_conv_x) { + q = k; + ++n_other; + } + } + if (n_other > 1) { + continue; + } + + const bool has_cpy = (n_other == 1); + const ggml_tensor * cpy_dst = nullptr; + if (has_cpy) { + if (q <= p || nodes[q].opcode != HTP_OP_CPY || !nodes[q].fused.empty() || + nodes[q].outputs.size() != 1 || (nodes[q].node->flags & GGML_TENSOR_FLAG_OUTPUT)) { + continue; + } + if (nodes[c].fused.size() + 2 > HTP_OP_MAX_FUSED) { + continue; + } + const ggml_tensor * cpy_src = nodes[q].src0(); + cpy_dst = nodes[q].dst(); + const size_t conv_x_es = ggml_type_size(conv_x->type); + if (cpy_src->op != GGML_OP_VIEW || + !htp_same_tensor_data(cpy_src->view_src, conv_x) || + cpy_src->ne[0] != S || cpy_src->ne[1] != d_inner || cpy_src->ne[2] != n_s || cpy_src->ne[3] != 1 || + cpy_src->nb[0] != conv_x_es || cpy_src->nb[1] != conv_x->nb[1] || + (n_s > 1 && cpy_src->nb[2] != conv_x->nb[2]) || + cpy_src->view_offs != (size_t) n_t * conv_x_es) { + continue; + } + } + + const bool inplace_x_dst = htp_same_tensor_data(conv_dst, cat_x) && + conv_dst->type == cat_x->type && + ggml_are_same_shape(conv_dst, cat_x) && + ggml_are_same_stride(conv_dst, cat_x); + if (htp_tensors_overlap(conv_dst, cat_state) || + (htp_tensors_overlap(conv_dst, cat_x) && !inplace_x_dst) || + htp_tensors_overlap(conv_dst, conv_weight)) { + continue; + } + if (has_cpy) { + if (htp_tensors_overlap(conv_dst, cpy_dst) || + htp_tensors_overlap(cpy_dst, cat_x) || + htp_tensors_overlap(cpy_dst, conv_weight)) { + continue; + } + if (htp_tensors_overlap(cpy_dst, cat_state)) { + const bool inplace_state = (n_s == 1) && + htp_same_tensor_data(cpy_dst, cat_state) && + cpy_dst->type == cat_state->type; + if (!inplace_state) { + continue; + } + } + } + + bool safe = true; + for (size_t k = p + 1; k < c && safe; ++k) { + if (has_cpy && k == q) { + continue; + } + for (const ggml_tensor * out : nodes[k].outputs) { + if (!out) { + continue; + } + if (htp_tensors_overlap(out, cat_state) || + htp_tensors_overlap(out, cat_x) || + htp_tensors_overlap(out, conv_x) || + htp_tensors_overlap(out, conv_weight) || + (has_cpy && htp_tensors_overlap(out, cpy_dst))) { + safe = false; + break; + } + } + } + if (has_cpy && safe) { + const size_t lo = (q < c) ? (q + 1) : (c + 1); + const size_t hi = (q < c) ? c : q; + for (size_t k = lo; k < hi && safe; ++k) { + for (const ggml_tensor * in : nodes[k].inputs) { + if (htp_tensor_reads_from(in, cpy_dst)) { + safe = false; + break; + } + } + for (const ggml_tensor * out : nodes[k].outputs) { + if (out && (htp_tensors_overlap(out, cpy_dst) || (q > c && htp_tensors_overlap(out, conv_x)))) { + safe = false; + break; + } + } + } + } + if (!safe) { + continue; + } + + htp_opnode cand = nodes[c]; + cand.inputs = { cat_state, conv_weight, cat_x }; + if (has_cpy) { + cand.outputs = { conv_dst, cpy_dst }; + cand.fused.insert(cand.fused.begin(), nodes[q].node); + } + cand.fused.insert(cand.fused.begin(), nodes[p].node); + if (!htp_kparams_solve(sess, cand)) { + continue; + } + + nodes[c] = std::move(cand); + if (has_cpy) { + nodes.erase(nodes.begin() + (ptrdiff_t) q); + if (q < c) { + --c; + } + } + nodes.erase(nodes.begin() + (ptrdiff_t) p); + --c; + } +} + +static void htp_fuse_mul_mat_nx_glu(const struct ggml_hexagon_session * sess, std::vector & nodes) { + for (size_t c = 0; c < nodes.size(); ++c) { + if (!htp_is_fuseable_mmnx_glu_op(nodes[c].opcode) || nodes[c].inputs.size() != 2 || + nodes[c].outputs.size() != 1 || !nodes[c].src1()) { + continue; + } + + const ggml_tensor * s0 = nodes[c].src0(); + const ggml_tensor * s1 = nodes[c].src1(); + + size_t p = c; + for (size_t i = 0; i < c; ++i) { + if (nodes[i].opcode != HTP_OP_MUL_MAT_NX || nodes[i].outputs.size() != 2 || nodes[i].inputs.size() != 3) { + continue; + } + const ggml_tensor * o0 = nodes[i].outputs[0]; + const ggml_tensor * o1 = nodes[i].outputs[1]; + if ((htp_same_tensor_data(s0, o0) && htp_same_tensor_data(s1, o1)) || + (htp_same_tensor_data(s0, o1) && htp_same_tensor_data(s1, o0))) { + p = i; + break; + } + } + if (p == c) { + continue; + } + + const ggml_tensor * w0 = nodes[p].inputs[0]; + const ggml_tensor * w1 = nodes[p].inputs[1]; + const ggml_tensor * act = nodes[p].inputs[2]; + const ggml_tensor * o0 = nodes[p].outputs[0]; + const ggml_tensor * o1 = nodes[p].outputs[1]; + + bool safe = true; + for (size_t k = 0; k < nodes.size() && safe; ++k) { + if (k == p || k == c) { + continue; + } + for (const ggml_tensor * in : nodes[k].inputs) { + if (htp_tensor_reads_from(in, o0) || htp_tensor_reads_from(in, o1)) { + safe = false; + break; + } + } + if (safe && k > p && k < c) { + for (const ggml_tensor * out : nodes[k].outputs) { + if (out && (htp_tensors_overlap(out, w0) || htp_tensors_overlap(out, w1) || + htp_tensors_overlap(out, act) || htp_tensors_overlap(out, o0) || + htp_tensors_overlap(out, o1))) { + safe = false; + break; + } + } + } + } + if (!safe) { + continue; + } + + htp_opnode cand = nodes[p]; + if (!fuse_mul_mat_nx_glu(sess, cand, nodes[c])) { + continue; + } + + nodes[c] = std::move(cand); + nodes.erase(nodes.begin() + (ptrdiff_t) p); + --c; + } +} + +void htp_fusion_optimize_nodes(const struct ggml_hexagon_session * sess, const struct ggml_cgraph * graph, std::vector & nodes) { + GGML_UNUSED(graph); + + if (htp_fusion_enabled(HTP_FUSE_MUL_MAT_NX_GLU)) { + htp_fuse_mul_mat_nx_glu(sess, nodes); + } + if (htp_fusion_enabled(HTP_FUSE_GDN_STATE)) { + htp_fuse_gdn_state(sess, nodes); + } + if (htp_fusion_enabled(HTP_FUSE_CONCAT_SSM_CONV)) { + htp_fuse_concat_ssm_conv(sess, nodes); + } +} diff --git a/ggml/src/ggml-hexagon/htp-fusion.h b/ggml/src/ggml-hexagon/htp-fusion.h index e4f711c872f5..6a2b391967f0 100644 --- a/ggml/src/ggml-hexagon/htp-fusion.h +++ b/ggml/src/ggml-hexagon/htp-fusion.h @@ -15,8 +15,12 @@ enum htp_fusion_flags { HTP_FUSE_MUL_MUL_SCALAR = (1 << 9), // 512 HTP_FUSE_BINARY_NX = (1 << 10), // 1024 HTP_FUSE_RMS_NORM_SCALE = (1 << 11), // 2048 - HTP_FUSE_SSM_CONV_SILU = (1 << 12), // 4096 + HTP_FUSE_SSM_CONV_SILU = (1 << 12), // 4096 HTP_FUSE_RMS_NORM_MUL_ADD = (1 << 13), // 8192 + HTP_FUSE_UNARY_SCALE = (1 << 14), // 16384 + HTP_FUSE_GDN_STATE = (1 << 15), // 32768 + HTP_FUSE_CONCAT_SSM_CONV = (1 << 16), // 65536 + HTP_FUSE_MUL_MAT_NX_GLU = (1 << 17), // 131072 }; static inline bool htp_fusion_enabled(int flag) { @@ -30,5 +34,6 @@ bool htp_fusion_can_stack(const struct ggml_tensor * a, const struct ggml_tensor int htp_fusion_max(const struct ggml_cgraph * graph, int idx); void htp_fusion_tag_graph(struct ggml_cgraph * graph); bool htp_fusion_try_fuse(const struct ggml_hexagon_session * sess, struct htp_opnode & prev, const struct htp_opnode & cur); +void htp_fusion_optimize_nodes(const struct ggml_hexagon_session * sess, const struct ggml_cgraph * graph, std::vector & nodes); #endif // HTP_FUSION_H diff --git a/ggml/src/ggml-hexagon/htp-kparams.cpp b/ggml/src/ggml-hexagon/htp-kparams.cpp index 122d6aee878b..97ca56e3f854 100644 --- a/ggml/src/ggml-hexagon/htp-kparams.cpp +++ b/ggml/src/ggml-hexagon/htp-kparams.cpp @@ -108,39 +108,6 @@ htp_op_code htp_op_remap(const struct ggml_tensor * t) { return HTP_OP_INVALID; } -bool htp_rows_stride(const int64_t * ne, const size_t * nb, size_t * stride) { - size_t s = 0, next = 0; - for (int i = 1; i < GGML_MAX_DIMS; i++) { - if (ne[i] == 1) continue; - if (s == 0) { s = nb[i]; next = s * ne[i]; continue; } - if (nb[i] != next) return false; - next *= ne[i]; - } - *stride = s ? s : nb[1]; - return true; -} - -bool htp_matmul_can_collapse(const struct ggml_tensor * src0, const struct ggml_tensor * src1, const struct ggml_tensor * dst) { - size_t s1, sd; - return (dst->op == GGML_OP_MUL_MAT || dst->op == GGML_OP_ADD) && - src0->ne[2] == 1 && src0->ne[3] == 1 && src1->ne[2] * src1->ne[3] > 1 && - src1->nb[0] == ggml_type_size(src1->type) && htp_rows_stride(src1->ne, src1->nb, &s1) && - dst->nb[0] == ggml_type_size(dst->type) && htp_rows_stride(dst->ne, dst->nb, &sd); -} - -ggml_tensor htp_tensor_collapse_rows(const struct ggml_tensor * t) { - size_t stride = 0; - htp_rows_stride(t->ne, t->nb, &stride); - ggml_tensor c = *t; - c.ne[1] = t->ne[1] * t->ne[2] * t->ne[3]; - c.ne[2] = 1; - c.ne[3] = 1; - c.nb[1] = stride; - c.nb[2] = c.nb[1] * c.ne[1]; - c.nb[3] = c.nb[2]; - return c; -} - bool htp_kparams_solve_allreduce( const struct ggml_hexagon_session * sess, const struct ggml_tensor * dst, @@ -164,7 +131,7 @@ bool htp_kparams_solve_allreduce( const bool is_contiguous = ggml_is_contiguous(dst); const uint32_t ne0 = (uint32_t) dst->ne[0]; - const uint32_t ne1 = (uint32_t) (dst->ne[1] * dst->ne[2] * dst->ne[3]); + const uint32_t ne1 = (uint32_t) ggml_nrows(dst); kparams->ne0 = (int32_t) ne0; kparams->ne1 = (int32_t) ne1; @@ -306,7 +273,7 @@ static bool htp_flash_attn_is_hmx_eligible( GGML_UNUSED(sinks); - if (opt_fa_select > 2) { + if (opt_fa_select >= 4) { return true; } @@ -322,7 +289,16 @@ static bool htp_flash_attn_is_hmx_eligible( const uint32_t S = k->ne[1]; const uint32_t total_threads = n_hvx * htp_session_mdev_count(sess); - if (DK > 256 || (DK == 256 && (DV > 256 || n_kv_heads < total_threads))) { + if (DK > 256 || DV > 256) { + return true; + } + + // W8A8 HMX pads M=1 decode rows to 64, so HVX is much faster for Q8_0 KV decode. + if (k->type == GGML_TYPE_Q8_0 || v->type == GGML_TYPE_Q8_0) { + return false; + } + + if (DK == 256 && n_kv_heads < total_threads) { return true; } @@ -431,14 +407,33 @@ static bool htp_kparams_solve_flash_attn( kparams->n_head_log2 = 1u << (uint32_t) std::floor(std::log2(n_head)); kparams->m0 = std::pow(2.0f, -(max_bias) / kparams->n_head_log2); kparams->m1 = std::pow(2.0f, -(max_bias / 2.0f) / kparams->n_head_log2); + kparams->broadcast_rk2 = init_fastdiv_values(q->ne[2] / k->ne[2]); + kparams->broadcast_rk3 = init_fastdiv_values(q->ne[3] / k->ne[3]); + kparams->broadcast_rv2 = init_fastdiv_values(q->ne[2] / v->ne[2]); + kparams->broadcast_rv3 = init_fastdiv_values(q->ne[3] / v->ne[3]); if (htp_flash_attn_is_hmx_eligible(sess, q, k, v, sinks)) { const uint32_t DK_pad = hex_round_up(DK, 64); const uint32_t DV_pad = hex_round_up(DV, 64); - size_t Br = 0, Bc = 0; - int ret = hmx_fa_find_chunk_size(&Br, &Bc, G, DK_pad, DV_pad, neq1, nek1, vtcm_size, n_hvx, (q->type == GGML_TYPE_F32), sinks != nullptr, n_head, fa_team_size); - if (ret == 0) { - kparams->kernel_type = HTP_FA_KERNEL_HMX; + const bool use_w8a8 = (opt_fa_select >= 3 && k->type == GGML_TYPE_Q8_0 && v->type == GGML_TYPE_Q8_0 && + DK % 32 == 0 && DV % 32 == 0 && DK <= 768); + const bool has_mask = (mask != nullptr); + const bool mask_broadcast = (has_mask && mask->ne[2] == 1); + + struct hmx_fa_layout_params lp = {}; + lp.kernel_type = use_w8a8 ? HTP_FA_KERNEL_HMX_W8A8 : HTP_FA_KERNEL_HMX_F16; + lp.q_type = q->type; + lp.gqa_factor = G; + lp.DK = DK_pad; + lp.DV = DV_pad; + lp.n_hvx = n_hvx; + lp.n_heads = n_head; + lp.has_mask = has_mask; + lp.mask_broadcast = mask_broadcast; + lp.has_sinks = (sinks != nullptr); + + if (hmx_fa_find_chunk_size(&lp, neq1, nek1, vtcm_size, fa_team_size) == 0) { + kparams->kernel_type = lp.kernel_type; if (logit_softcap == 0.0f) { kparams->scale = scale * (float) M_LOG2E; kparams->logit_softcap = 0.0f; @@ -446,15 +441,18 @@ static bool htp_kparams_solve_flash_attn( kparams->scale = scale; kparams->logit_softcap = logit_softcap * (float) M_LOG2E; } - kparams->Br = Br; - kparams->Bc = Bc; - kparams->n_kv_blocks = (nek1 + Bc - 1) / Bc; - kparams->n_hvx = (kparams->n_kv_blocks >= 3 && n_hvx >= 2) ? n_hvx : 1; - kparams->u.hmx.g_br = hex_align_up(G * Br, 32); - kparams->u.hmx.pipeline = (kparams->n_kv_blocks >= 3 && n_hvx >= 2) ? 1 : 0; - kparams->vtcm_size = hmx_fa_compute_vtcm_usage(G, DK_pad, DV_pad, Br, Bc, kparams->n_hvx, kparams->u.hmx.pipeline != 0, (q->type == GGML_TYPE_F32), sinks != nullptr, n_head); - kparams->u.hmx.mask_broadcast = (mask != nullptr && mask->ne[2] == 1) ? 1 : 0; - kparams->u.hmx.div_G = init_fastdiv_values(G); + kparams->Br = lp.Br; + kparams->Bc = lp.Bc; + kparams->n_kv_blocks = (nek1 + lp.Bc - 1) / lp.Bc; + kparams->n_hvx = (kparams->n_kv_blocks >= 3 && n_hvx >= 2) ? n_hvx : 1; + kparams->u.hmx.g_br = hex_align_up(G * lp.Br, use_w8a8 ? HMX_W8A8_ACT_TILE_N_ROWS : HMX_FP16_TILE_N_ROWS); + kparams->u.hmx.mask_broadcast = mask_broadcast ? 1 : 0; + // vtcm_mask_buf is single-buffered for non-broadcast masks, so disable block pipelining. + kparams->u.hmx.pipeline = (kparams->n_kv_blocks >= 3 && n_hvx >= 2 && (!has_mask || mask_broadcast)) ? 1 : 0; + lp.n_hvx = kparams->n_hvx; + lp.pipeline = (kparams->u.hmx.pipeline != 0); + kparams->vtcm_size = hmx_fa_compute_vtcm_usage(&lp); + kparams->u.hmx.div_G = init_fastdiv_values(G); if (mask) { kparams->src3_div2 = init_fastdiv_values(mask->ne[2]); kparams->src3_div3 = init_fastdiv_values(mask->ne[3]); @@ -469,11 +467,20 @@ static bool htp_kparams_solve_flash_attn( kparams->n_kv_blocks = (k->ne[1] + 64 - 1) / 64; kparams->n_hvx = n_hvx; - const size_t size_q_row_padded = hex_round_up(q->ne[0] * ((q->type == GGML_TYPE_F32) ? 4 : 2), 128); + const size_t size_q_row_padded = hex_round_up(htp_tensor_get_row_size(q->type, q->ne[0]), 128); const size_t size_k_row_padded = hex_round_up(k->ne[0] * 2, 128); const size_t size_v_row_padded = hex_round_up(v->ne[0] * 2, 128); - kparams->vtcm_size = hvx_fa_compute_vtcm_usage(DK, DV, (q->type == GGML_TYPE_F32), mask != nullptr, sinks != nullptr, n_head, n_hvx); + struct hvx_fa_layout_params hvx_lp = {}; + hvx_lp.q_type = q->type; + hvx_lp.DK = DK; + hvx_lp.DV = DV; + hvx_lp.n_heads = n_head; + hvx_lp.n_hvx = n_hvx; + hvx_lp.has_mask = (mask != nullptr); + hvx_lp.has_sinks = (sinks != nullptr); + + kparams->vtcm_size = hvx_fa_compute_vtcm_usage(&hvx_lp); if ((size_t) kparams->vtcm_size > vtcm_size) { HEX_VERBOSE("ggml-hex: skip flash_attn_ext because VTCM needed (%d) > budget (%zu)\n", kparams->vtcm_size, vtcm_size); @@ -500,6 +507,7 @@ static bool htp_kparams_solve_flash_attn( static bool htp_kparams_solve_gated_delta_net( const struct ggml_hexagon_session * sess, const struct ggml_tensor * op, + const struct ggml_tensor * dst_cache, struct htp_gdn_kernel_params * kparams ) { if (opt_gdn_select < 1) { @@ -514,21 +522,33 @@ 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 bool has_ids = op->src[6] != nullptr && op->src[7] == nullptr && + (op->src[6]->type == GGML_TYPE_I32 || op->src[6]->type == GGML_TYPE_I64); + const struct ggml_tensor * ids = has_ids ? op->src[6] : nullptr; + const struct ggml_tensor * pend_k = has_ids ? nullptr : 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 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 || - dst->type != GGML_TYPE_F32) { + auto is_act_type = [](ggml_type t) { + return t == GGML_TYPE_F32 || t == GGML_TYPE_F16; + }; + + if (!is_act_type(q->type) || !is_act_type(k->type) || !is_act_type(v->type) || + g->type != GGML_TYPE_F32 || beta->type != GGML_TYPE_F32 || state->type != GGML_TYPE_F32) { + return false; + } + if (dst_cache && (dst_cache->type != GGML_TYPE_F32 || !ggml_is_contiguous(dst_cache))) { + return false; + } + if (dst->type != GGML_TYPE_F32 && !(dst_cache != nullptr && dst->type == GGML_TYPE_F16)) { return false; } if (!ggml_is_contiguous_rows(q) || !ggml_is_contiguous_rows(k) || !ggml_is_contiguous_rows(v) || - !ggml_is_contiguous(g) || !ggml_is_contiguous(beta) || !ggml_is_contiguous(state) || + !ggml_is_contiguous(g) || !ggml_is_contiguous(beta) || (!ids && !ggml_is_contiguous(state)) || !ggml_is_contiguous(dst)) { return false; } @@ -550,11 +570,19 @@ static bool htp_kparams_solve_gated_delta_net( if ((g->ne[0] != 1 && g->ne[0] != S_v) || beta->ne[0] != 1) { return false; } - if (state->ne[0] != S_v || state->ne[1] != S_v || state->ne[2] != H || state->ne[3] != n_seqs) { + if (ids) { + if ((ids->type != GGML_TYPE_I32 && ids->type != GGML_TYPE_I64) || + !ggml_is_contiguous_rows(ids) || + ids->ne[0] < n_seqs || !ggml_is_vector(ids) || + state->ne[0] != S_v * S_v * H || !ggml_is_contiguous_rows(state) || + (state->nb[1] % sizeof(float)) != 0 || !ggml_is_matrix(state)) { + return false; + } + } else if (state->ne[0] != S_v || state->ne[1] != S_v || state->ne[2] != H || state->ne[3] != n_seqs) { return false; } if (dst->ne[0] != S_v * H || dst->ne[1] != n_tokens * n_seqs + S_v * n_seqs * K || - dst->ne[2] != 1 || dst->ne[3] != 1) { + !ggml_is_matrix(dst)) { return false; } if ((pend_v != nullptr) != replay || (pend_gb != nullptr) != replay || (n_rep != nullptr) != replay) { @@ -591,9 +619,8 @@ static bool htp_kparams_solve_gated_delta_net( struct htp_gdn_vtcm_layout hvx_layout; uint32_t n_heads_batch = 1; - if (can_use_hmx && htp_gdn_hmx_solve_layout(&hmx_layout, (uint32_t) S_v, HTP_GDN_CHUNK_SIZE, total_rows, vtcm_size, n_hvx, true, &n_heads_batch)) { + if (can_use_hmx && htp_gdn_hmx_solve_layout(&hmx_layout, (uint32_t) S_v, HTP_GDN_CHUNK_SIZE, total_rows, vtcm_size, n_hvx, &n_heads_batch)) { kparams->kernel_type = HTP_GDN_KERNEL_HMX_CHUNKED; - kparams->pipeline = hmx_layout.pipeline ? 1 : 0; kparams->chunk_size = HTP_GDN_CHUNK_SIZE; kparams->n_chunks = ((uint32_t) n_tokens + HTP_GDN_CHUNK_SIZE - 1) / HTP_GDN_CHUNK_SIZE; kparams->n_heads_batch = (uint16_t) n_heads_batch; @@ -604,7 +631,6 @@ static bool htp_kparams_solve_gated_delta_net( return false; } kparams->kernel_type = HTP_GDN_KERNEL_HVX_RECURRENT; - kparams->pipeline = 0; kparams->n_heads_batch = 1; kparams->vtcm_size = (uint32_t) hvx_layout.total_bytes; } @@ -617,7 +643,7 @@ static bool htp_kparams_solve_gated_delta_net( kparams->K = (uint32_t) K; kparams->total_rows = total_rows; kparams->kda = (g->ne[0] == S_v) ? 1 : 0; - kparams->state_seq_stride = (uint32_t) (state->nb[3] / sizeof(float)); + kparams->state_seq_stride = (uint32_t) ((ids ? state->nb[1] : state->nb[3]) / sizeof(float)); kparams->state_size_per_snap = (uint32_t) (S_v * S_v * H * n_seqs); kparams->scale = 1.0f / sqrtf((float) S_v); @@ -638,7 +664,7 @@ static bool htp_matmul_is_hmx_eligible( ) { GGML_UNUSED(dst); - if (src1->type != GGML_TYPE_F32 && (src1->type != GGML_TYPE_F16 || is_matmul_id)) { + if (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) { return false; } @@ -668,7 +694,7 @@ static bool htp_matmul_is_hmx_eligible( return false; } - if (src0->nb[0] > src0->nb[1] || src1->nb[0] > src1->nb[1]) { + if (ggml_is_transposed(src0) || ggml_is_transposed(src1)) { return false; } @@ -680,10 +706,34 @@ static bool htp_matmul_is_hmx_eligible( return true; } +// Post-GLU/gated projections (e.g. ffn_down, gated attn_output) have sharp channel outliers +// that degrade W8A8 activation quantization; route them to FP16 HMX under MM_SELECT=3. +static bool htp_mm_is_post_glu(const struct ggml_tensor * act) { + while (act && (act->op == GGML_OP_VIEW || act->op == GGML_OP_RESHAPE || act->op == GGML_OP_CONT || act->op == GGML_OP_CPY)) { + act = act->view_src ? act->view_src : act->src[0]; + } + if (!act) { + return false; + } + if (act->op == GGML_OP_GLU) { + return true; + } + if (act->op == GGML_OP_MUL) { + const struct ggml_tensor * a0 = act->src[0]; + const struct ggml_tensor * a1 = act->src[1]; + if ((a0 && (a0->op == GGML_OP_UNARY || a0->op == GGML_OP_GLU)) || + (a1 && (a1->op == GGML_OP_UNARY || a1->op == GGML_OP_GLU))) { + return true; + } + } + return false; +} + static bool htp_kparams_solve_hmx_mm( const struct ggml_hexagon_session * sess, const struct ggml_tensor * src0, const struct ggml_tensor * act, + const struct ggml_tensor * bias, const struct ggml_tensor * dst, int wtype, int ne00_padded, @@ -694,28 +744,24 @@ static bool htp_kparams_solve_hmx_mm( int ne11_padded, bool is_matmul_id, bool is_batched, - size_t src2_size, size_t vtcm_budget, - struct htp_mm_kernel_params * kparams + struct htp_mm_kernel_params * kparams, + bool is_glu = false ) { + const bool bias_is_2d = bias && (bias->ne[1] > 1); + const bool bias_batched = bias && (bias->ne[2] > 1 || bias->ne[3] > 1); const bool is_tiled = ggml_hexagon_tensor_will_tile(src0); const int aligned_tile_size = is_tiled ? htp_tensor_get_tile_padded_size(wtype) : 0; const int n_hvx = (int) htp_session_n_hvx(sess); const uint32_t mdev_count = htp_session_mdev_count(sess); - const int ne10 = act->ne[0]; int m_for_solver = ne11; int m_for_solver_padded = ne11_padded; if (!is_matmul_id && mdev_count > 1 && ((uint32_t) ne11 >= mdev_count)) { - const uint32_t rows_per_chunk = dst ? htp_mdev_rows_per_chunk(dst) : 1; - const uint32_t total_chunks = rows_per_chunk ? ((uint32_t) ne11 / rows_per_chunk) : 0; - if (total_chunks >= mdev_count) { - const uint32_t chunks_per_mdev = (total_chunks + mdev_count - 1) / mdev_count; - const uint32_t m_dev0 = chunks_per_mdev * rows_per_chunk; - const uint32_t m_last = (uint32_t) ne11 > (mdev_count - 1) * m_dev0 ? (uint32_t) ne11 - (mdev_count - 1) * m_dev0 : 0; - m_for_solver = (int) std::max(m_dev0, m_last); - m_for_solver_padded = hex_round_up(std::max(m_for_solver, 32), 32); - } + const uint32_t m_dev0 = ((uint32_t) ne11 + mdev_count - 1) / mdev_count; + const uint32_t m_last = (uint32_t) ne11 > (mdev_count - 1) * m_dev0 ? (uint32_t) ne11 - (mdev_count - 1) * m_dev0 : 0; + m_for_solver = (int) std::max(m_dev0, m_last); + m_for_solver_padded = hex_round_up(std::max(m_for_solver, 32), 32); } const bool pipeline = is_matmul_id ? false : htp_mm_hmx_pipeline(m_for_solver); const bool is_batched_val = is_matmul_id ? false : is_batched; @@ -727,30 +773,79 @@ static bool htp_kparams_solve_hmx_mm( bool use_grouped = false; int act_hvx_selected = 0; - if (is_batched_val && wtype == GGML_TYPE_F16 && !is_tiled && group_size > 1) { - if (htp_mm_hmx_solve_batched_params(wtype, ne00_padded, ne01_padded, m_for_solver, group_size, n_hvx, pipeline, src2_size, vtcm_budget, &m_chunk, &n_chunk, &act_hvx_selected, &vtcm_size)) { + const uint8_t fp16_kernel_type = (is_batched && !is_matmul_id) ? HTP_MM_KERNEL_HMX_BATCHED : HTP_MM_KERNEL_HMX_2D; + uint8_t kernel_type = fp16_kernel_type; + const uint32_t min_k = htp_int_hmx_min_k((int) wtype); + const bool allow_w8a8 = (opt_mm_select >= 4) || + (opt_mm_select == 3 && !htp_mm_is_post_glu(act) && + (!dst || ggml_prec_get_acc(dst) != GGML_PREC_F32)); + if (is_tiled && htp_is_int_hmx_weight_type((int) wtype) && allow_w8a8 && + ne00_padded >= (int) min_k && (ne00_padded % min_k) == 0) { + kernel_type = (is_batched && !is_matmul_id) ? HTP_MM_KERNEL_HMX_W8A8_BATCHED : HTP_MM_KERNEL_HMX_W8A8_2D; + } + + if (is_glu && !htp_mm_kernel_is_hmx_2d(kernel_type)) { + return false; + } + + size_t bias_size = bias ? hex_round_up(ggml_nbytes(bias), 128) : 0; + const size_t res_out_elem_size = dst ? ggml_type_size(dst->type) : sizeof(float); + if (!is_glu && is_batched_val && wtype == GGML_TYPE_F16 && !is_tiled && group_size > 1 && !bias_batched) { + if (htp_mm_hmx_solve_batched_params(wtype, ne00_padded, ne01_padded, m_for_solver, group_size, n_hvx, pipeline, bias_size, res_out_elem_size, vtcm_budget, &m_chunk, &n_chunk, &act_hvx_selected, &vtcm_size)) { use_grouped = true; } } if (!use_grouped) { + // HMX 2D DMA-writes output slices per (mc, nc) chunk and streams 2D residual slices when pipelined. + const size_t res_in_elem_size = (pipeline && !is_matmul_id && bias_is_2d) ? ggml_type_size(bias->type) : 0; + if (res_in_elem_size > 0) { + bias_size = 0; + } + int m_id_rows = 0; if (dst && is_matmul_id) { const int n_experts = ne02 > 0 ? ne02 : 1; const size_t total_expert_rows = (size_t) dst->ne[1] * dst->ne[2]; int m_per_expert = (int) ((total_expert_rows + n_experts - 1) / n_experts); - if (mdev_count > 1 && htp_can_row_partition(dst)) { + if (mdev_count > 1) { m_per_expert = (m_per_expert + (int) mdev_count - 1) / (int) mdev_count; } m_id_rows = hex_round_up(std::max(m_per_expert, 32), 32); } const uint32_t cost_m = is_matmul_id ? (uint32_t) m_id_rows : (uint32_t) m_for_solver; - if (!htp_mm_hmx_solve_2d_params(wtype, ne00_padded, m_id_rows, ne01_padded, m_for_solver_padded, cost_m, n_hvx, pipeline, is_matmul_id, aligned_tile_size, src2_size, vtcm_budget, &m_chunk, &n_chunk, &act_hvx_selected, &vtcm_size)) { - return false; + // Non-grouped HMX_BATCHED dispatches to hmx_mm_2d_f32 (full 2D layout, not grouped-batched layout). + const uint8_t solve_ktype = htp_mm_kernel_is_hmx_int(kernel_type) ? kernel_type : HTP_MM_KERNEL_HMX_2D; + if (is_glu) { + if (!htp_mm_hmx_solve_2d_params_glu(solve_ktype, wtype, ne00_padded, ne01_padded, m_for_solver_padded, cost_m, n_hvx, pipeline, aligned_tile_size, res_out_elem_size, vtcm_budget, &m_chunk, &n_chunk, &act_hvx_selected, &vtcm_size)) { + if (htp_mm_kernel_is_hmx_int(kernel_type)) { + kernel_type = HTP_MM_KERNEL_HMX_2D; + if (!htp_mm_hmx_solve_2d_params_glu(HTP_MM_KERNEL_HMX_2D, wtype, ne00_padded, ne01_padded, m_for_solver_padded, cost_m, n_hvx, pipeline, aligned_tile_size, res_out_elem_size, vtcm_budget, &m_chunk, &n_chunk, &act_hvx_selected, &vtcm_size)) { + return false; + } + } else { + return false; + } + } + } else if (!htp_mm_hmx_solve_2d_params_ex(solve_ktype, wtype, ne00_padded, m_id_rows, ne01_padded, m_for_solver_padded, cost_m, n_hvx, pipeline, is_matmul_id, aligned_tile_size, bias_size, res_in_elem_size, res_out_elem_size, vtcm_budget, &m_chunk, &n_chunk, &act_hvx_selected, &vtcm_size)) { + if (htp_mm_kernel_is_hmx_int(kernel_type)) { + kernel_type = fp16_kernel_type; + if (!htp_mm_hmx_solve_2d_params_ex(HTP_MM_KERNEL_HMX_2D, wtype, ne00_padded, m_id_rows, ne01_padded, m_for_solver_padded, cost_m, n_hvx, pipeline, is_matmul_id, aligned_tile_size, bias_size, res_in_elem_size, res_out_elem_size, vtcm_budget, &m_chunk, &n_chunk, &act_hvx_selected, &vtcm_size)) { + return false; + } + } else { + return false; + } } } + const uint32_t hmx_n_groups = htp_mm_kernel_is_hmx_int(kernel_type) + ? (((uint32_t) ne00_padded + HTP_MM_HMX_W8A8_KGROUP - 1u) / HTP_MM_HMX_W8A8_KGROUP) + : 1u; + const uint32_t n_k_tiles = std::max(1, ne00_padded / 32); + kparams->n_hmx = 1; + kparams->hmx_n_groups = (int32_t) hmx_n_groups; kparams->pipeline = pipeline ? 1 : 0; kparams->m_chunk = m_chunk; kparams->n_chunk = n_chunk; @@ -758,12 +853,13 @@ static bool htp_kparams_solve_hmx_mm( kparams->n_act_hvx = act_hvx_selected; kparams->tile_size = is_tiled ? htp_tensor_get_tile_size(wtype) : 0; kparams->aligned_tile_size = aligned_tile_size; - kparams->act_row_size = htp_mm_tiled_act_row_size(wtype, ne10); kparams->vtcm_size = vtcm_size; kparams->div_n_act_hvx = init_fastdiv_values(act_hvx_selected); kparams->div_ne00_padded = init_fastdiv_values(ne00_padded); - kparams->vtcm_bias_size = (int32_t) src2_size; - kparams->kernel_type = (is_batched && !is_matmul_id) ? HTP_MM_KERNEL_HMX_BATCHED : HTP_MM_KERNEL_HMX_2D; + kparams->div_hmx_n_groups = init_fastdiv_values(hmx_n_groups); + kparams->div_n_k_tiles = init_fastdiv_values(n_k_tiles); + kparams->vtcm_bias_size = (int32_t) bias_size; + kparams->kernel_type = kernel_type; return true; } @@ -781,7 +877,7 @@ static void htp_kparams_solve_hvx_mm( int ne12, int ne13, bool is_matmul_id, - const size_t src2_row_size, + const size_t bias_row_size, size_t vtcm_budget, struct htp_mm_kernel_params * kparams ) { @@ -798,6 +894,8 @@ static void htp_kparams_solve_hvx_mm( GGML_UNUSED(ne03); const int src1_nrows = ne11 * ne12 * ne13; + const size_t act_elem_size = ggml_type_size(src1->type); + const size_t dst_row_size = dst ? (size_t) dst->ne[0] * sizeof(float) : 0; if (is_tiled) { kparams->tile_size = htp_tensor_get_tile_size(wtype); @@ -816,7 +914,7 @@ static void htp_kparams_solve_hvx_mm( for (uint32_t d = max_prefetch; d >= 2; d /= 2) { htp_mm_hvx_vtcm_layout_build( &L, kparams->kernel_type, wtype, ne10, src1_nrows, n_hvx, - 0, src0->nb[1], kparams->act_row_size, 0, d, true, false + dst_row_size, src0->nb[1], act_elem_size, 0, d, true, false ); if (L.total_bytes <= vtcm_budget) { best_n_prefetch = d; @@ -843,7 +941,7 @@ static void htp_kparams_solve_hvx_mm( for (uint32_t d = max_prefetch; d >= 2; d /= 2) { htp_mm_hvx_vtcm_layout_build( &L, kparams->kernel_type, wtype, ne10, src1_nrows, n_hvx, - dst->nb[1], src0->nb[1], src1->nb[1], src2_row_size, d, false, false + dst_row_size, src0->nb[1], act_elem_size, bias_row_size, d, false, false ); if (L.total_bytes <= vtcm_budget) { best_n_prefetch = d; @@ -854,7 +952,7 @@ static void htp_kparams_solve_hvx_mm( uint32_t m_chunk = 0; if (htp_mm_hvx_solve_vtcm_params( kparams->kernel_type, wtype, ne10, src1_nrows, n_hvx, - dst->nb[1], src0->nb[1], src1->nb[1], src2_row_size, best_n_prefetch, vtcm_budget, + dst_row_size, src0->nb[1], act_elem_size, bias_row_size, best_n_prefetch, vtcm_budget, &L, &m_chunk)) { kparams->n_prefetch = best_n_prefetch; kparams->m_chunk = (m_chunk < (uint32_t) src1_nrows) ? m_chunk : 0; @@ -884,7 +982,7 @@ static void htp_kparams_solve_hvx_mm( uint32_t m_chunk = 0; if (htp_mm_hvx_solve_vtcm_params( ktype, wtype, ne10, src1_nrows, n_hvx, - dst->nb[1], src0->nb[1], src1->nb[1], src2_row_size, 16, vtcm_budget, + dst_row_size, src0->nb[1], act_elem_size, bias_row_size, 16, vtcm_budget, &L, &m_chunk)) { kparams->kernel_type = ktype; kparams->m_chunk = (m_chunk < (uint32_t) src1_nrows) ? m_chunk : 0; @@ -903,9 +1001,8 @@ static bool htp_kparams_solve_matmul_impl( const struct ggml_hexagon_session * sess, const struct ggml_tensor * src0, const struct ggml_tensor * src1, + const struct ggml_tensor * bias, const struct ggml_tensor * dst, - const size_t src2_row_size, - const size_t src2_size, struct htp_mm_kernel_params * kparams ) { memset(kparams, 0, sizeof(*kparams)); @@ -932,12 +1029,12 @@ static bool htp_kparams_solve_matmul_impl( const bool hmx_enabled = (htp_session_n_hmx(sess) > 0) && (opt_mm_select >= 2); if (hmx_enabled && htp_matmul_is_hmx_eligible(src0, src1, dst, is_matmul_id, is_batched)) { - if (htp_kparams_solve_hmx_mm(sess, src0, src1, dst, wtype, ne00_padded, ne01_tiled, ne02, ne11, ne12, ne11_padded, is_matmul_id, is_batched, src2_size, vtcm_budget, kparams)) { + if (htp_kparams_solve_hmx_mm(sess, src0, src1, bias, dst, wtype, ne00_padded, ne01_tiled, ne02, ne11, ne12, ne11_padded, is_matmul_id, is_batched, vtcm_budget, kparams)) { goto finalize; } } - htp_kparams_solve_hvx_mm(sess, src0, src1, dst, wtype, is_tiled, ne02, ne03, ne10, ne11, ne12, ne13, is_matmul_id, src2_row_size, vtcm_budget, kparams); + htp_kparams_solve_hvx_mm(sess, src0, src1, dst, wtype, is_tiled, ne02, ne03, ne10, ne11, ne12, ne13, is_matmul_id, bias ? bias->nb[1] : 0, vtcm_budget, kparams); finalize: kparams->div_ne12_ne1 = init_fastdiv_values(ne12 * ne11); @@ -961,7 +1058,7 @@ static bool htp_matmul_check_types( ) { const bool is_matmul_id = (dst->op == GGML_OP_MUL_MAT_ID); - if (dst->type != GGML_TYPE_F32) { + if (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) { return false; } @@ -971,7 +1068,8 @@ static bool htp_matmul_check_types( if (is_matmul_id) { const struct ggml_tensor * src2 = dst->src[2]; - if (src1->type != GGML_TYPE_F32 || !src2 || src2->type != GGML_TYPE_I32) { + const bool src1_ok = (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); + if (!src1_ok || !src2 || src2->type != GGML_TYPE_I32) { return false; } switch (src0->type) { @@ -1043,11 +1141,6 @@ static bool htp_matmul_check_types( return src0->ne[0] % ggml_blck_size(src0->type) == 0; case GGML_TYPE_F32: - if (src1->type != GGML_TYPE_F32) { - return false; - } - return src0->nb[1] >= src0->nb[0]; - case GGML_TYPE_F16: case GGML_TYPE_BF16: return src0->nb[1] >= src0->nb[0]; @@ -1072,59 +1165,36 @@ static bool htp_kparams_solve_matmul( if (htp_matmul_can_collapse(src0, src1, dst)) { const ggml_tensor src1_collapsed = htp_tensor_collapse_rows(src1); const ggml_tensor dst_collapsed = htp_tensor_collapse_rows(dst); - return htp_kparams_solve_matmul_impl(sess, src0, &src1_collapsed, &dst_collapsed, 0, 0, kparams); + return htp_kparams_solve_matmul_impl(sess, src0, &src1_collapsed, nullptr, &dst_collapsed, kparams); } - return htp_kparams_solve_matmul_impl(sess, src0, src1, dst, 0, 0, kparams); -} - -bool htp_matmul_add_can_collapse( - const struct ggml_tensor * src0, - const struct ggml_tensor * src1, - const struct ggml_tensor * src2, - const struct ggml_tensor * dst -) { - if (!htp_matmul_can_collapse(src0, src1, dst)) { - return false; - } - if (!src2) { - return true; - } - const int64_t src2_nrows = src2->ne[1] * src2->ne[2] * src2->ne[3]; - if (src2_nrows == 1) { - return true; - } - size_t s2; - return src2->nb[0] == ggml_type_size(src2->type) && - ggml_are_same_shape(src2, dst) && - htp_rows_stride(src2->ne, src2->nb, &s2); + return htp_kparams_solve_matmul_impl(sess, src0, src1, nullptr, dst, kparams); } bool htp_kparams_solve_matmul_add( const struct ggml_hexagon_session * sess, const struct ggml_tensor * src0, const struct ggml_tensor * src1, - const struct ggml_tensor * src2, + const struct ggml_tensor * bias, const struct ggml_tensor * dst, struct htp_mm_kernel_params * kparams ) { - if (htp_matmul_add_can_collapse(src0, src1, src2, dst)) { + if (htp_matmul_add_can_collapse(src0, src1, bias, dst)) { const ggml_tensor src1_collapsed = htp_tensor_collapse_rows(src1); const ggml_tensor dst_collapsed = htp_tensor_collapse_rows(dst); - const ggml_tensor src2_collapsed = (src2 && (src2->ne[1] * src2->ne[2] * src2->ne[3] > 1)) - ? htp_tensor_collapse_rows(src2) - : (src2 ? *src2 : ggml_tensor{}); - const struct ggml_tensor * p_src2 = src2 ? &src2_collapsed : nullptr; - const size_t src2_size = p_src2 ? hex_round_up(ggml_nbytes(p_src2), 128) : 0; - return htp_kparams_solve_matmul_impl(sess, src0, &src1_collapsed, &dst_collapsed, p_src2 ? p_src2->nb[1] : 0, src2_size, kparams); - } - const size_t src2_size = src2 ? hex_round_up(ggml_nbytes(src2), 128) : 0; - return htp_kparams_solve_matmul_impl(sess, src0, src1, dst, src2 ? src2->nb[1] : 0, src2_size, kparams); + const ggml_tensor bias_collapsed = (bias && (ggml_nrows(bias) > 1)) + ? htp_tensor_collapse_rows(bias) + : (bias ? *bias : ggml_tensor{}); + const struct ggml_tensor * p_bias = bias ? &bias_collapsed : nullptr; + return htp_kparams_solve_matmul_impl(sess, src0, &src1_collapsed, p_bias, &dst_collapsed, kparams); + } + return htp_kparams_solve_matmul_impl(sess, src0, src1, bias, dst, kparams); } bool htp_kparams_solve_mmnx( const struct ggml_hexagon_session * sess, const struct ggml_tensor * src0, const struct ggml_tensor * act, + const struct ggml_tensor * dst, int32_t n_weights, struct htp_mm_kernel_params * kparams ) { @@ -1147,36 +1217,40 @@ bool htp_kparams_solve_mmnx( const bool is_tiled = ggml_hexagon_tensor_will_tile(src0); const int wtype = (is_tiled && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_BF16)) ? GGML_TYPE_F16 : src0->type; - const int ne00_padded = is_tiled ? hex_round_up(ne00, 32) : ne00; + const int ne00_padded = is_tiled ? hex_round_up(ne00, htp_tensor_get_tile_k(wtype)) : ne00; const int ne11_padded = hex_round_up(ne11, 32); const int ne01_tiled = hex_round_up(ne01, 32); const bool is_batched = (ne02 * ne03 > 1 || ne12 * ne13 > 1); const bool hmx_enabled = (n_hmx > 0) && (opt_mm_select >= 2); - if (hmx_enabled && htp_matmul_is_hmx_eligible(src0, act, nullptr, false, is_batched)) { - if (htp_kparams_solve_hmx_mm(sess, src0, act, nullptr, wtype, ne00_padded, ne01_tiled, ne02, ne11, ne12, ne11_padded, false, is_batched, 0, vtcm_budget, kparams)) { + if (hmx_enabled && htp_matmul_is_hmx_eligible(src0, act, dst, false, is_batched)) { + if (htp_kparams_solve_hmx_mm(sess, src0, act, nullptr, dst, wtype, ne00_padded, ne01_tiled, ne02, ne11, ne12, ne11_padded, false, is_batched, vtcm_budget, kparams)) { kparams->n_weights = n_weights; goto finalize; } } - if (!is_tiled || act->type != GGML_TYPE_F32 || ne10 % 32 != 0) { + if (!is_tiled || (act->type != GGML_TYPE_F32 && act->type != GGML_TYPE_F16) || ne10 % 32 != 0) { kparams->kernel_type = HTP_MM_KERNEL_UNSUPPORTED; return false; } { - const int act_nrows = ne11 * ne12 * ne13; - const size_t act_row_size = htp_mm_tiled_act_row_size(wtype, ne10); - const size_t src0_row_size = src0->nb[1]; + const int act_nrows = ne11 * ne12 * ne13; + const int32_t hvx_ktype = (act_nrows < (int) n_hvx) + ? HTP_MM_KERNEL_HVX_QUANT_BLOCK : HTP_MM_KERNEL_HVX_QUANT_ROW; + const size_t act_row_size = htp_mm_tiled_act_row_size(wtype, ne10); + const size_t act_elem_size = ggml_type_size(act->type); + const size_t src0_row_size = src0->nb[1]; + const size_t dst_row_size = (size_t) src0->ne[1] * sizeof(float); const uint32_t max_prefetch = (act_nrows > HTP_MM_HMX_MIN_NROWS) ? 2 : 16; uint32_t best_n_prefetch = 2; for (uint32_t d = max_prefetch; d >= 2; d /= 2) { struct htp_mm_hvx_vtcm_layout L; htp_mm_hvx_vtcm_layout_build( - &L, HTP_MM_KERNEL_HVX_QUANT_ROW, wtype, ne10, act_nrows, n_hvx, - 0, src0_row_size, act_row_size, 0, d, false, true + &L, hvx_ktype, wtype, ne10, act_nrows, n_hvx, + dst_row_size, src0_row_size, act_elem_size, 0, d, false, true ); if (L.total_bytes <= vtcm_budget) { best_n_prefetch = d; @@ -1186,12 +1260,12 @@ bool htp_kparams_solve_mmnx( struct htp_mm_hvx_vtcm_layout L; htp_mm_hvx_vtcm_layout_build( - &L, HTP_MM_KERNEL_HVX_QUANT_ROW, wtype, ne10, act_nrows, n_hvx, - 0, src0_row_size, act_row_size, 0, best_n_prefetch, false, true + &L, hvx_ktype, wtype, ne10, act_nrows, n_hvx, + dst_row_size, src0_row_size, act_elem_size, 0, best_n_prefetch, false, true ); if (opt_mm_select >= 1 && L.total_bytes <= vtcm_budget) { - kparams->kernel_type = HTP_MM_KERNEL_HVX_QUANT_ROW; + kparams->kernel_type = hvx_ktype; kparams->tile_size = htp_tensor_get_tile_size(wtype); kparams->aligned_tile_size = htp_tensor_get_tile_padded_size(wtype); kparams->act_row_size = act_row_size; @@ -1214,6 +1288,67 @@ bool htp_kparams_solve_mmnx( return (size_t) kparams->vtcm_size <= vtcm_budget; } +bool htp_kparams_solve_mmnx_glu( + const struct ggml_hexagon_session * sess, + const struct ggml_tensor * w_gate, + const struct ggml_tensor * w_up, + const struct ggml_tensor * act, + const struct ggml_tensor * dst, + uint8_t glu_op, + struct htp_mm_kernel_params * kparams +) { + if (htp_session_n_hmx(sess) == 0 || opt_mm_select < 2) { + return false; + } + if (w_gate->type != w_up->type || w_gate->ne[0] != w_up->ne[0] || w_gate->ne[1] != w_up->ne[1] || + !ggml_is_matrix(w_gate) || !ggml_is_matrix(w_up) || + !ggml_is_contiguous(w_up) || w_gate->nb[1] != w_up->nb[1] || + ggml_hexagon_tensor_will_tile(w_gate) != ggml_hexagon_tensor_will_tile(w_up)) { + return false; + } + if (!htp_matmul_check_types(w_gate, act, dst) || !htp_matmul_check_types(w_up, act, dst)) { + return false; + } + + const size_t vtcm_budget = htp_session_vtcm_size(sess); + memset(kparams, 0, sizeof(*kparams)); + kparams->n_hvx = htp_session_n_hvx(sess); + + const int ne00 = w_gate->ne[0]; + const int ne01 = w_gate->ne[1]; + const int ne02 = w_gate->ne[2]; + const int ne03 = w_gate->ne[3]; + const int ne11 = act->ne[1]; + const int ne12 = act->ne[2]; + const int ne13 = act->ne[3]; + + const bool is_tiled = ggml_hexagon_tensor_will_tile(w_gate); + const int wtype = (is_tiled && (w_gate->type == GGML_TYPE_F32 || w_gate->type == GGML_TYPE_BF16)) ? GGML_TYPE_F16 : w_gate->type; + const int tile_k = htp_tensor_get_tile_k(wtype); + const int ne00_padded = is_tiled ? hex_round_up(ne00, tile_k) : ne00; + const int ne11_padded = hex_round_up(ne11, 32); + const int ne01_tiled = hex_round_up(ne01, 32); + const bool is_batched = (ne02 * ne03 > 1 || ne12 * ne13 > 1); + + const bool k_ok = is_tiled ? (tile_k > 0 && (ne00 % tile_k) == 0) : ((ne00 & 31) == 0); + if (is_batched || !k_ok || + !htp_matmul_is_hmx_eligible(w_gate, act, dst, false, false)) { + return false; + } + if (!htp_kparams_solve_hmx_mm(sess, w_gate, act, nullptr, dst, wtype, ne00_padded, ne01_tiled, ne02, ne11, ne12, ne11_padded, false, false, vtcm_budget, kparams, /*is_glu=*/ true)) { + return false; + } + + kparams->n_weights = 2; + kparams->glu_op = glu_op; + kparams->div_ne12_ne1 = init_fastdiv_values(ne12 * ne11); + kparams->div_ne1 = init_fastdiv_values(ne11); + kparams->div_r2 = init_fastdiv_values(ne02 > 0 ? ne12 / ne02 : 1); + kparams->div_r3 = init_fastdiv_values(ne03 > 0 ? ne13 / ne03 : 1); + kparams->div_ne12 = init_fastdiv_values(ne12); + return kparams->n_hmx == 1 && htp_mm_kernel_is_hmx_2d(kparams->kernel_type) && (size_t) kparams->vtcm_size <= vtcm_budget; +} + bool htp_kparams_solve_mmidnx( const struct ggml_hexagon_session * sess, const struct ggml_tensor * src0, @@ -1222,7 +1357,7 @@ bool htp_kparams_solve_mmidnx( int32_t n_weights, struct htp_mm_kernel_params * kparams ) { - const bool ok = htp_kparams_solve_matmul_impl(sess, src0, act, dst, 0, 0, kparams); + const bool ok = htp_kparams_solve_matmul_impl(sess, src0, act, nullptr, dst, kparams); kparams->n_weights = n_weights; return ok; } @@ -1240,12 +1375,15 @@ static bool htp_kparams_solve_binary( const struct ggml_tensor * src2 = (op == HTP_OP_ADD_ID) ? op_tensor->src[2] : nullptr; const struct ggml_tensor * dst = op_tensor; + if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || + (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) || + (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) { + return false; + } + const bool is_add_id = (op == HTP_OP_ADD_ID); if (is_add_id) { - if (!src2) { - return false; - } - if (src0->type != GGML_TYPE_F32 || src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 || src2->type != GGML_TYPE_I32) { + if (src2->type != GGML_TYPE_I32) { return false; } if (!ggml_are_same_shape(src0, dst)) { @@ -1257,24 +1395,24 @@ static bool htp_kparams_solve_binary( if (src2->ne[0] != src0->ne[1] || src2->ne[1] != src0->ne[2]) { return false; } - if (src0->nb[0] != sizeof(float) || src1->nb[0] != sizeof(float) || dst->nb[0] != sizeof(float) || src2->nb[0] != sizeof(int32_t)) { + if (!ggml_is_contiguous_rows(src0) || !ggml_is_contiguous_rows(src1) || + !ggml_is_contiguous_rows(dst) || !ggml_is_contiguous_rows(src2)) { return false; } if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1) || !ggml_is_contiguous(dst)) { return false; } - if (src2->nb[1] < src2->ne[0] * sizeof(int32_t)) { + if (src2->nb[1] < ggml_row_size(src2->type, src2->ne[0])) { return false; } } else { - if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || - src1->type != src0->type || dst->type != src0->type) { + if (ggml_is_permuted(src0) || ggml_is_permuted(dst) || !ggml_are_same_shape(src0, dst)) { return false; } - if (ggml_is_permuted(src0) || ggml_is_permuted(dst) || !ggml_are_same_shape(src0, dst)) { + if (!ggml_can_repeat(src1, src0)) { return false; } - if (!ggml_can_repeat(src1, src0) || ggml_is_permuted(src1)) { + if (!ggml_is_contiguous_rows(src1) && !ggml_is_permuted(src1)) { return false; } } @@ -1282,25 +1420,32 @@ static bool htp_kparams_solve_binary( const uint32_t max_hvx_sess = htp_session_n_hvx(sess); const size_t vtcm_size = htp_session_vtcm_size(sess); - const size_t elem_size = ggml_type_size(src0->type); - const size_t src0_row_size = src0->ne[0] * elem_size; - const size_t src1_row_size = src1->ne[0] * elem_size; - const size_t dst_row_size = dst->ne[0] * elem_size; + const size_t src0_elem_size = ggml_type_size(src0->type); + const size_t src1_elem_size = ggml_type_size(src1->type); + const size_t dst_elem_size = ggml_type_size(dst->type); + const size_t src0_row_size = src0->ne[0] * src0_elem_size; + const size_t src1_row_size = src1->ne[0] * src1_elem_size; + const size_t dst_row_size = dst->ne[0] * dst_elem_size; const size_t src0_row_size_aligned = hex_round_up(src0_row_size, 128); const size_t src1_row_size_aligned = hex_round_up(src1_row_size, 128); const size_t dst_row_size_aligned = hex_round_up(dst_row_size, 128); - if (!htp_binary_strides_safe(src0, src1, dst, elem_size)) { + if (!htp_binary_strides_safe(src0, src1, dst, src0_elem_size, src1_elem_size, dst_elem_size)) { return false; } + kparams->src0_elem_size = (uint8_t) src0_elem_size; + kparams->src1_elem_size = (uint8_t) src1_elem_size; + kparams->dst_elem_size = (uint8_t) dst_elem_size; + const bool is_scalar = !is_add_id && src1->ne[0] == 1; const bool is_row_bcast = !is_add_id && !is_scalar && src1->ne[0] == src0->ne[0] && - (src0->ne[1] > 1 || src0->ne[2] > 1 || src0->ne[3] > 1) && - src1->ne[1] == 1 && src1->ne[2] == 1 && src1->ne[3] == 1; + ggml_nrows(src0) > 1 && + ggml_is_vector(src1); const bool is_same_shape = !is_add_id && !is_scalar && + src1->nb[0] == src1_elem_size && src1->ne[0] == src0->ne[0] && src1->ne[1] == src0->ne[1] && (src1->ne[2] == src0->ne[2] || src1->ne[2] == 1) && @@ -1310,35 +1455,13 @@ static bool htp_kparams_solve_binary( const bool is_scalar_broadcast = !is_add_id && (ggml_nelements(src1) == 1); if (!is_add_id && is_contig && (ggml_are_same_shape(src0, src1) || is_scalar_broadcast)) { - const uint32_t total_elems = (uint32_t) ggml_nelements(src0); - const uint32_t max_chunk_elems = 32768 / elem_size; - const uint32_t min_chunk_elems = 256; - const uint32_t target_chunk_elems = hex_round_up((total_elems + (2 * max_hvx_sess) - 1) / (2 * max_hvx_sess), 32); - const uint32_t chunk_size = (std::min)(max_chunk_elems, (std::max)(target_chunk_elems, min_chunk_elems)); - const uint32_t chunk_bytes = hex_round_up(chunk_size * elem_size, 128); - const uint32_t total_chunks = (total_elems + chunk_size - 1) / chunk_size; - const uint32_t n_hvx = (total_chunks >= 2) ? (std::min)(max_hvx_sess, total_chunks) : 1; - - kparams->kernel_type = HTP_BINARY_KERNEL_CHUNKED; - kparams->n_hvx = n_hvx; - kparams->n_srcs = 2; - kparams->rows_per_buffer = 1; kparams->src0_row_size_aligned = src0_row_size_aligned; - kparams->src1_row_size_aligned = is_scalar_broadcast ? 0 : src1_row_size_aligned; + kparams->src1_row_size_aligned = src1_row_size_aligned; kparams->dst_row_size_aligned = dst_row_size_aligned; - kparams->src1_size = 0; - kparams->chunk_size = chunk_size; - kparams->chunk_bytes = chunk_bytes; - kparams->is_scalar = is_scalar_broadcast ? 1 : 0; - struct htp_binary_vtcm_layout L; - htp_binary_vtcm_layout_build(&L, kparams, vtcm_size); - if (L.total_bytes == 0 || L.total_bytes > vtcm_size) { - return false; - } - - kparams->vtcm_size = L.total_bytes; - return true; + return htp_binary_solve_chunked(&L, kparams, (uint32_t) ggml_nelements(src0), + (uint32_t) src0_elem_size, (uint32_t) src1_elem_size, (uint32_t) dst_elem_size, + max_hvx_sess, 2, is_scalar_broadcast, vtcm_size); } enum htp_binary_kernel_type kernel_type; @@ -1354,9 +1477,10 @@ static bool htp_kparams_solve_binary( } } else if (is_row_bcast) { kernel_type = HTP_BINARY_KERNEL_ROW_BCAST; - src1_size = src1_row_size_aligned; + src1_size = hex_round_up(src1->ne[0] * ((src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) ? sizeof(ggml_fp16_t) : sizeof(float)), 128); + kparams->src1_strided = src1->nb[0] != src1_elem_size ? 1 : 0; } else if (is_scalar) { - src1_size = hex_round_up(ggml_nelements(src1) * elem_size, 128); + src1_size = hex_round_up(ggml_nelements(src1) * ((src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) ? sizeof(ggml_fp16_t) : sizeof(float)), 128); if (src1_size > vtcm_size) { return false; } @@ -1365,14 +1489,14 @@ static bool htp_kparams_solve_binary( } else if (is_same_shape) { kernel_type = HTP_BINARY_KERNEL_SAME_SHAPE; } else if (is_complex) { - src1_size = hex_round_up(ggml_nelements(src1) * elem_size + 128, 128); + src1_size = hex_round_up(ggml_nelements(src1) * src1_elem_size + 128, 128); if (src1_size > vtcm_size) { return false; } kernel_type = HTP_BINARY_KERNEL_COMPLEX; kparams->src1_strided = !ggml_is_contiguous(src1) ? 1 : 0; } else { - src1_size = hex_round_up(ggml_nelements(src1) * elem_size + 128, 128); + src1_size = hex_round_up(ggml_nelements(src1) * src1_elem_size + 128, 128); if (src1_size > vtcm_size) { return false; } @@ -1380,7 +1504,7 @@ static bool htp_kparams_solve_binary( kparams->src1_strided = !ggml_is_contiguous(src1) ? 1 : 0; } - const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3]; + const uint32_t src0_nrows = ggml_nrows(src0); const uint32_t min_rows_per_hvx = (uint32_t) (std::max(1, (128 + dst_row_size - 1) / dst_row_size)); const uint32_t max_hvx = (std::max)(1u, src0_nrows / min_rows_per_hvx); @@ -1437,7 +1561,8 @@ static bool htp_kparams_solve_binary( if (L.rows_per_buffer == 0 || L.total_bytes > vtcm_size) { if (!is_add_id && is_contig && (ggml_are_same_shape(src0, src1) || is_scalar_broadcast)) { const uint32_t total_elems = (uint32_t) ggml_nelements(src0); - return htp_binary_solve_chunked(&L, kparams, total_elems, (uint32_t) elem_size, + return htp_binary_solve_chunked(&L, kparams, total_elems, + (uint32_t) src0_elem_size, (uint32_t) src1_elem_size, (uint32_t) dst_elem_size, max_hvx_sess, 2, is_scalar_broadcast, vtcm_size); } return false; @@ -1449,106 +1574,106 @@ static bool htp_kparams_solve_binary( return true; } -// collapse contiguous dims of elementwise ops so that rows fill at least one HVX vector -static void htp_collapse_dims(struct ggml_tensor ** tensors, size_t n_tensors, size_t elem_size, uint32_t n_hvx) { - if (n_tensors == 0 || !tensors[0]) { - return; - } - for (size_t t = 0; t < n_tensors; t++) { - if (!tensors[t] || tensors[t]->nb[0] != elem_size) { - return; - } - if (t > 0 && !ggml_are_same_shape(tensors[0], tensors[t])) { - return; - } +static bool htp_kparams_solve_binary_nx( + const struct ggml_hexagon_session * sess, + const htp_opnode & node, + struct htp_binary_kernel_params * kparams +) { + const uint32_t n_srcs = (uint32_t) node.inputs.size(); + if (n_srcs <= 2 || n_srcs > HTP_OP_MAX_INPUTS || node.outputs.size() != 1) { + return false; } - struct ggml_tensor * t0 = tensors[0]; + const struct ggml_tensor * src0 = node.inputs[0]; + const struct ggml_tensor * src1 = node.inputs[1]; + const struct ggml_tensor * dst = node.outputs[0]; - while (t0->ne[1] > 1 || t0->ne[2] > 1 || t0->ne[3] > 1) { - const size_t row_size = (size_t) t0->ne[0] * elem_size; - bool rows_contig = true; - for (size_t t = 0; t < n_tensors; t++) { - if (tensors[t]->nb[1] != (size_t) tensors[t]->ne[0] * elem_size) { - rows_contig = false; - break; - } - } - bool all_ne1_one = true; - for (size_t t = 0; t < n_tensors; t++) { - if (tensors[t]->ne[1] != 1) { - all_ne1_one = false; - break; - } - } - const bool can_merge = all_ne1_one || - (rows_contig && (t0->ne[0] == 1 || (row_size < 128 && row_size * t0->ne[1] <= 2048))); - if (!can_merge) { - break; + if (src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) { + return false; + } + if (dst->type != src0->type || ggml_is_permuted(dst) || !ggml_are_same_shape(src0, dst)) { + return false; + } + + const size_t elem_size = ggml_type_size(src0->type); + bool all_contig = ggml_is_contiguous(dst); + for (uint32_t s = 0; s < n_srcs; ++s) { + const struct ggml_tensor * in = node.inputs[s]; + if (in->type != src0->type || ggml_is_permuted(in) || !ggml_are_same_shape(src0, in)) { + return false; } - for (size_t t = 0; t < n_tensors; t++) { - tensors[t]->ne[0] *= tensors[t]->ne[1]; - tensors[t]->ne[1] = tensors[t]->ne[2]; - tensors[t]->ne[2] = tensors[t]->ne[3]; - tensors[t]->ne[3] = 1; - tensors[t]->nb[1] = tensors[t]->nb[2]; - tensors[t]->nb[2] = tensors[t]->nb[3]; - tensors[t]->nb[3] = tensors[t]->nb[2] * tensors[t]->ne[2]; + if (!htp_binary_strides_safe(src0, in, dst, elem_size, elem_size, elem_size) || + !htp_binary_strides_safe(in, src0, dst, elem_size, elem_size, elem_size)) { + return false; } + all_contig = all_contig && ggml_is_contiguous(in); + } + if (!all_contig && src0->ne[0] <= 1) { + return false; } - // ne1 too big to merge in full: merge it in chunks of k rows (k divides ne1) - const size_t row_size = (size_t) t0->ne[0] * elem_size; - bool rows_contig = true; - for (size_t t = 0; t < n_tensors; t++) { - if (tensors[t]->nb[1] != row_size) { - rows_contig = false; - break; - } + memset(kparams, 0, sizeof(*kparams)); + + const uint32_t max_hvx_sess = htp_session_n_hvx(sess); + const size_t vtcm_size = htp_session_vtcm_size(sess); + const size_t row_size = src0->ne[0] * elem_size; + const size_t row_size_aligned = hex_round_up(row_size, 128); + + kparams->src0_elem_size = (uint8_t) elem_size; + kparams->src1_elem_size = (uint8_t) elem_size; + kparams->dst_elem_size = (uint8_t) elem_size; + kparams->src0_row_size_aligned = (uint32_t) row_size_aligned; + kparams->src1_row_size_aligned = (uint32_t) row_size_aligned; + kparams->dst_row_size_aligned = (uint32_t) row_size_aligned; + + if (all_contig) { + struct htp_binary_vtcm_layout L; + return htp_binary_solve_chunked(&L, kparams, (uint32_t) ggml_nelements(src0), + (uint32_t) elem_size, (uint32_t) elem_size, (uint32_t) elem_size, + max_hvx_sess, n_srcs, false, vtcm_size); } - if (t0->ne[1] > 1 && row_size < 128 && rows_contig) { - int64_t k = 2048 / row_size; - while (k > 1 && t0->ne[1] % k != 0) { - k--; + + const uint32_t src0_nrows = ggml_nrows(src0); + const uint32_t min_rows_per_hvx = (uint32_t) (std::max(1, (128 + row_size - 1) / row_size)); + const uint32_t max_hvx = (std::max)(1u, src0_nrows / min_rows_per_hvx); + + kparams->kernel_type = HTP_BINARY_KERNEL_SAME_SHAPE; + kparams->n_hvx = (std::min)(max_hvx_sess, max_hvx); + kparams->n_srcs = (uint8_t) n_srcs; + + for (uint32_t s = 0; s < n_srcs; ++s) { + const struct ggml_tensor * in = node.inputs[s]; + if (src0->ne[2] > 1 && in->nb[2] != in->ne[1] * in->nb[1]) { + kparams->split_at_ne01 = 1; } - if (k > 1) { - for (size_t t = 0; t < n_tensors; t++) { - tensors[t]->ne[0] *= k; - tensors[t]->ne[1] /= k; - tensors[t]->nb[1] *= k; - tensors[t]->nb[2] = tensors[t]->nb[1] * tensors[t]->ne[1]; - tensors[t]->nb[3] = tensors[t]->nb[2] * tensors[t]->ne[2]; - } + if (src0->ne[3] > 1 && in->nb[3] != in->ne[2] * in->nb[2]) { + kparams->split_at_ne02 = 1; } } - - // nrows too small to saturate threads: split ne0 into k rows (k divides ne0) - const size_t row_size_curr = (size_t) t0->ne[0] * elem_size; - const uint32_t nrows = (uint32_t) (t0->ne[1] * t0->ne[2] * t0->ne[3]); - rows_contig = true; - for (size_t t = 0; t < n_tensors; t++) { - if (tensors[t]->ne[1] != 1 && tensors[t]->nb[1] != row_size_curr) { - rows_contig = false; - break; - } + if (src0->ne[2] > 1 && dst->nb[2] != dst->ne[1] * dst->nb[1]) { + kparams->split_at_ne01 = 1; } - if (nrows < n_hvx && rows_contig && row_size_curr >= 4096) { - const size_t vec_elems = 128 / elem_size; - int64_t k = std::max(row_size_curr / 16384, (n_hvx * 4 + nrows - 1) / nrows); - k = std::min(k, row_size_curr / 2048); - while (k > 1 && t0->ne[0] % (k * vec_elems) != 0) { - k--; - } - if (k > 1) { - for (size_t t = 0; t < n_tensors; t++) { - tensors[t]->ne[0] /= k; - tensors[t]->ne[1] *= k; - tensors[t]->nb[1] = tensors[t]->ne[0] * elem_size; - tensors[t]->nb[2] = tensors[t]->nb[1] * tensors[t]->ne[1]; - tensors[t]->nb[3] = tensors[t]->nb[2] * tensors[t]->ne[2]; - } - } + if (src0->ne[3] > 1 && dst->nb[3] != dst->ne[2] * dst->nb[2]) { + kparams->split_at_ne02 = 1; } + + kparams->div_ne01 = init_fastdiv_values((uint32_t) src0->ne[1]); + kparams->div_ne02 = init_fastdiv_values((uint32_t) src0->ne[2]); + kparams->div_ne012 = init_fastdiv_values((uint32_t) (src0->ne[1] * src0->ne[2])); + kparams->div_ne11 = init_fastdiv_values((uint32_t) src1->ne[1]); + kparams->div_ne12 = init_fastdiv_values((uint32_t) src1->ne[2]); + kparams->div_ne13 = init_fastdiv_values((uint32_t) src1->ne[3]); + + struct htp_binary_vtcm_layout L; + htp_binary_vtcm_layout_build(&L, kparams, vtcm_size); + if (L.rows_per_buffer == 0 || L.total_bytes > vtcm_size) { + return false; + } + + kparams->rows_per_buffer = L.rows_per_buffer; + kparams->vtcm_size = (uint32_t) L.total_bytes; + + return true; } static bool htp_kparams_solve_unary_impl( @@ -1556,6 +1681,7 @@ static bool htp_kparams_solve_unary_impl( uint32_t op, const struct ggml_tensor * src0, const struct ggml_tensor * src1, + const struct ggml_tensor * src2, const struct ggml_tensor * dst, struct htp_unary_kernel_params * kparams ) { @@ -1565,15 +1691,34 @@ static bool htp_kparams_solve_unary_impl( return false; } + const bool is_rms_norm = (op == HTP_OP_RMS_NORM || op == HTP_OP_RMS_NORM_MUL || op == HTP_OP_RMS_NORM_MUL_ADD); + if (op == HTP_OP_HADAMARD) { const int64_t n = src0->ne[0]; if (n < 32 || (n & (n - 1)) != 0) { return false; } - if (!dst->src[0] || dst->src[0]->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 || + if (dst->src[0]->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 || (src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16)) { return false; } + } else if (is_rms_norm) { + if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || + (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) { + return false; + } + if (op == HTP_OP_RMS_NORM_MUL || op == HTP_OP_RMS_NORM_MUL_ADD) { + if ((src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) || + !ggml_is_contiguous_rows(src1) || src1->ne[0] != src0->ne[0]) { + return false; + } + } + if (op == HTP_OP_RMS_NORM_MUL_ADD) { + if ((src2->type != GGML_TYPE_F32 && src2->type != GGML_TYPE_F16) || + !ggml_is_contiguous_rows(src2) || !ggml_are_same_shape(src0, src2)) { + return false; + } + } } else { if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || dst->type != src0->type) { return false; @@ -1584,14 +1729,24 @@ static bool htp_kparams_solve_unary_impl( if (src0->type == GGML_TYPE_F16) { switch (op) { case HTP_OP_NORM: - case HTP_OP_RMS_NORM: case HTP_OP_L2_NORM: case HTP_OP_SCALE: case HTP_OP_CLAMP: + case HTP_OP_LEAKY_RELU: case HTP_OP_SQR: case HTP_OP_SQRT: + case HTP_OP_UNARY_NEG: + case HTP_OP_UNARY_EXP: + case HTP_OP_UNARY_SIGMOID: + case HTP_OP_UNARY_SILU: + case HTP_OP_UNARY_GELU: + case HTP_OP_UNARY_GELU_QUICK: + case HTP_OP_UNARY_GELU_ERF: + case HTP_OP_UNARY_SOFTPLUS: + case HTP_OP_UNARY_TANH: case HTP_OP_UNARY_LOG: case HTP_OP_UNARY_ABS: + case HTP_OP_UNARY_RELU: case HTP_OP_UNARY_STEP: case HTP_OP_UNARY_CEIL: case HTP_OP_UNARY_SGN: @@ -1606,11 +1761,12 @@ static bool htp_kparams_solve_unary_impl( return false; } - const size_t elem_size = ggml_type_size(src0->type); + const size_t src0_elem_size = ggml_type_size(src0->type); + const size_t dst_elem_size = ggml_type_size(dst->type); - const size_t dst_data_row_size = dst->ne[0] * ggml_type_size(dst->type); + const size_t dst_data_row_size = dst->ne[0] * dst_elem_size; - const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3]; + const uint32_t src0_nrows = (uint32_t) ggml_nrows(src0); const uint32_t min_rows_per_hvx = (uint32_t) (std::max(1, (128 + dst_data_row_size - 1) / dst_data_row_size)); const uint32_t max_hvx = (std::max)(1u, src0_nrows / min_rows_per_hvx); const uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx); @@ -1618,32 +1774,57 @@ static bool htp_kparams_solve_unary_impl( kparams->n_hvx = n_hvx; - const bool has_weight = (op == HTP_OP_RMS_NORM_MUL || op == HTP_OP_RMS_NORM_MUL_ADD); - const bool broadcast_weight = has_weight && (src1->ne[1] * src1->ne[2] * src1->ne[3] == 1); - if (op == HTP_OP_RMS_NORM_MUL_ADD && !broadcast_weight) { - return false; + const bool has_src1_mul = (op == HTP_OP_RMS_NORM_MUL || op == HTP_OP_RMS_NORM_MUL_ADD); + const bool has_src2_add = (op == HTP_OP_RMS_NORM_MUL_ADD); + const bool is_row_bcast = has_src1_mul && ggml_is_vector(src1); + bool broadcast_src1 = false; + if (op == HTP_OP_RMS_NORM_MUL) { + const bool is_dim1_bcast = (src1->ne[1] == src0->ne[1] && ggml_is_matrix(src1) && !ggml_is_matrix(src0)); + if (!is_row_bcast && !is_dim1_bcast && !ggml_are_same_shape(src0, src1)) { + return false; + } + broadcast_src1 = is_row_bcast || is_dim1_bcast; + } else if (op == HTP_OP_RMS_NORM_MUL_ADD) { + if (!is_row_bcast && !(src1->ne[1] == src0->ne[1] && ggml_is_matrix(src1))) { + return false; + } + broadcast_src1 = true; } - kparams->broadcast_weight = broadcast_weight; + const uint32_t src1_nrows = broadcast_src1 ? (uint32_t) src1->ne[1] : 0; + kparams->broadcast_src1 = broadcast_src1; - const bool src0_contig = ggml_is_contiguous_1(src0); - const bool src1_contig = (has_weight && !broadcast_weight) ? ggml_is_contiguous_1(src1) : true; + const size_t src0_data_row_size = (size_t) src0->ne[0] * src0_elem_size; + const uint32_t ne01 = (uint32_t) src0->ne[1]; + const bool src0_contig = ggml_is_contiguous_1(src0) && (!has_src2_add || ggml_is_contiguous_1(src2)); + const bool src1_contig = (has_src1_mul && !broadcast_src1) ? ggml_is_contiguous_1(src1) : true; + const bool src0_slice_dma = !src0_contig && !has_src2_add && (!has_src1_mul || broadcast_src1) && + ne01 > 1 && src0->ne[2] > 1 && src0->ne[3] == 1 && + src0->nb[1] == src0_data_row_size && (src0_data_row_size & 127) == 0; const uint32_t src0_nrows_per_hvx = (src0_nrows + n_hvx - 1) / n_hvx; const uint32_t min_block_rows = (uint32_t) (std::max(1, 2048 / dst_data_row_size)); - uint32_t max_block = (src0_contig && src1_contig) ? src0_nrows : (uint32_t) src0->ne[1]; + uint32_t max_block = ((src0_contig && src1_contig) || src0_slice_dma) ? src0_nrows : ne01; if (src0_nrows_per_hvx >= 2 * min_block_rows) { max_block = (std::min)(max_block, (std::max)(min_block_rows, src0_nrows_per_hvx / 4)); } + if (src0_slice_dma && max_block > ne01) { + max_block = (max_block / ne01) * ne01; + } - kparams->src0_contig = src0_contig ? 1 : 0; - kparams->src1_contig = src1_contig ? 1 : 0; + kparams->src0_contig = src0_contig ? 1 : 0; + kparams->src1_contig = src1_contig ? 1 : 0; + kparams->src0_slice_dma = src0_slice_dma ? 1 : 0; + + const size_t src1_elem_size = has_src1_mul ? ggml_type_size(src1->type) : sizeof(float); + const size_t src2_elem_size = has_src2_add ? ggml_type_size(src2->type) : sizeof(float); struct htp_unary_vtcm_layout L; uint32_t col_tile = 0; uint32_t vtcm_row_per_hvx = 0; htp_unary_solve_layout(&L, op, src0->ne[0], dst->ne[0], - has_weight ? src1->ne[0] : 0, - max_block, broadcast_weight, n_hvx, vtcm_size, elem_size, + has_src1_mul ? src1->ne[0] : 0, + max_block, broadcast_src1, src1_nrows, n_hvx, vtcm_size, + src0_elem_size, dst_elem_size, src1_elem_size, src2_elem_size, &col_tile, &vtcm_row_per_hvx); kparams->col_tile = col_tile; @@ -1660,17 +1841,6 @@ static bool htp_kparams_solve_unary_impl( return (col_tile > 0 || vtcm_row_per_hvx > 0) && L.total_bytes <= vtcm_size; } -static bool htp_kparams_solve_unary( - const struct ggml_hexagon_session * sess, - const struct ggml_tensor * op, - struct htp_unary_kernel_params * kparams -) { - const htp_op_code opcode = htp_op_remap(op); - const struct ggml_tensor * src0 = (opcode == HTP_OP_HADAMARD) ? op->src[1] : op->src[0]; - const struct ggml_tensor * src1 = (opcode == HTP_OP_HADAMARD) ? nullptr : op->src[1]; - return htp_kparams_solve_unary_impl(sess, opcode, src0, src1, op, kparams); -} - bool htp_kparams_solve_rms_norm_mul( const struct ggml_hexagon_session * sess, const struct ggml_tensor * src0, @@ -1678,17 +1848,18 @@ bool htp_kparams_solve_rms_norm_mul( const struct ggml_tensor * dst, struct htp_unary_kernel_params * kparams ) { - return htp_kparams_solve_unary_impl(sess, HTP_OP_RMS_NORM_MUL, src0, src1, dst, kparams); + return htp_kparams_solve_unary_impl(sess, HTP_OP_RMS_NORM_MUL, src0, src1, nullptr, dst, kparams); } bool htp_kparams_solve_rms_norm_mul_add( const struct ggml_hexagon_session * sess, const struct ggml_tensor * src0, const struct ggml_tensor * src1, + const struct ggml_tensor * src2, const struct ggml_tensor * dst, struct htp_unary_kernel_params * kparams ) { - return htp_kparams_solve_unary_impl(sess, HTP_OP_RMS_NORM_MUL_ADD, src0, src1, dst, kparams); + return htp_kparams_solve_unary_impl(sess, HTP_OP_RMS_NORM_MUL_ADD, src0, src1, src2, dst, kparams); } bool htp_kparams_solve_repeat_get_rows( @@ -1714,13 +1885,13 @@ bool htp_kparams_solve_repeat_get_rows( return false; } - if (src0->type == dst->type) { - if (src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_I32 && src0->type != GGML_TYPE_F16) { + const bool tiled = ggml_hexagon_tensor_is_tiled(src0); + + if (src0->type == GGML_TYPE_I32) { + if (dst->type != GGML_TYPE_I32 || tiled) { return false; } - } else if (src0->type == GGML_TYPE_I32) { - return false; - } else if (dst->type != GGML_TYPE_F32) { + } else if (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) { return false; } @@ -1733,8 +1904,7 @@ bool htp_kparams_solve_repeat_get_rows( const uint32_t ne12 = src1->ne[2]; const uint32_t nr = ne10 * ne11 * ne12; - const bool tiled = ggml_hexagon_tensor_is_tiled(src0); - const int wtype = (tiled && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_BF16)) ? GGML_TYPE_F16 : src0->type; + const int wtype = (tiled && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_BF16)) ? GGML_TYPE_F16 : src0->type; if (tiled) { kparams->kernel_type = HTP_GET_ROWS_KERNEL_TILED; @@ -1753,7 +1923,7 @@ bool htp_kparams_solve_repeat_get_rows( struct htp_get_rows_vtcm_layout vtcm_layout = {}; while (kparams->n_hvx > 0) { - htp_get_rows_vtcm_layout_build(&vtcm_layout, kparams->kernel_type, wtype, ne00, total_tasks, src1->type, kparams->n_hvx); + htp_get_rows_vtcm_layout_build(&vtcm_layout, kparams->kernel_type, wtype, dst->type, ne00, kparams->n_hvx); if (vtcm_layout.total_bytes <= vtcm_size) { break; } @@ -1761,7 +1931,7 @@ bool htp_kparams_solve_repeat_get_rows( } if (kparams->n_hvx == 0 && total_tasks > 0) { - htp_get_rows_vtcm_layout_build(&vtcm_layout, kparams->kernel_type, wtype, ne00, total_tasks, src1->type, 1); + htp_get_rows_vtcm_layout_build(&vtcm_layout, kparams->kernel_type, wtype, dst->type, ne00, 1); } kparams->vtcm_size = (total_tasks == 0) ? 0 : vtcm_layout.total_bytes; @@ -1800,7 +1970,7 @@ static bool htp_kparams_solve_set_rows( if (dst->type == GGML_TYPE_Q8_0 && src0->ne[0] < 32) { return false; } - if (src0->type != GGML_TYPE_F32) { + if (src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) { return false; } if (src1->type != GGML_TYPE_I32 && src1->type != GGML_TYPE_I64) { @@ -1816,7 +1986,7 @@ static bool htp_kparams_solve_set_rows( kparams->total_tasks = nr; struct htp_set_rows_vtcm_layout vtcm_layout; - htp_set_rows_vtcm_layout_build(&vtcm_layout, dst->type, src0->ne[0], kparams->n_hvx); + htp_set_rows_vtcm_layout_build(&vtcm_layout, src0->type, dst->type, src0->ne[0], kparams->n_hvx); kparams->vtcm_size = vtcm_layout.total_bytes; return vtcm_layout.total_bytes <= htp_session_vtcm_size(sess); @@ -1834,10 +2004,11 @@ static bool htp_kparams_solve_softmax( const struct ggml_tensor * src2 = op->src[2]; const struct ggml_tensor * dst = op; - if (src2) { + if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || + (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) { return false; } - if (src0->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 || src0->ne[2] > 512) { + if (src0->ne[2] > 512) { return false; } if (src1) { @@ -1848,11 +2019,19 @@ static bool htp_kparams_solve_softmax( return false; } } + if (src2) { + if (src2->type != GGML_TYPE_F32 || + src2->ne[0] != src0->ne[2] || + src2->ne[1] != 1 || src2->ne[2] != 1 || src2->ne[3] != 1 || + !ggml_is_contiguous(src2)) { + return false; + } + } if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(dst)) { return false; } - const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3]; + const uint32_t src0_nrows = ggml_nrows(src0); const size_t dst_data_row_size = op->ne[0] * ggml_type_size(op->type); const uint32_t min_rows_per_hvx = (uint32_t) (std::max(1, (128 + dst_data_row_size - 1) / dst_data_row_size)); const uint32_t max_hvx = (std::max)(1u, src0_nrows / min_rows_per_hvx); @@ -1879,14 +2058,26 @@ static bool htp_kparams_solve_softmax( kparams->m1 = 1.0f; } + kparams->src0_f16 = (src0->type == GGML_TYPE_F16) ? 1 : 0; + kparams->dst_f16 = (dst->type == GGML_TYPE_F16) ? 1 : 0; kparams->use_src1 = (src1 != nullptr) ? 1 : 0; kparams->use_f16 = (src1 != nullptr && src1->type == GGML_TYPE_F16) ? 1 : 0; + kparams->use_src2 = (src2 != nullptr) ? 1 : 0; const uint32_t ne00 = src0->ne[0]; const uint32_t ne10 = src1 ? src1->ne[0] : 1; struct htp_softmax_vtcm_layout layout; - htp_softmax_vtcm_layout_build(&layout, ne00, ne10, kparams->use_src1 != 0, kparams->use_f16 != 0, n_hvx); + htp_softmax_vtcm_layout_build(&layout, + ne00, + ne10, + n_head, + kparams->src0_f16 != 0, + kparams->dst_f16 != 0, + kparams->use_src1 != 0, + kparams->use_f16 != 0, + kparams->use_src2 != 0, + n_hvx); if (layout.total_bytes > htp_session_vtcm_size(sess)) { return false; } @@ -1894,12 +2085,22 @@ static bool htp_kparams_solve_softmax( kparams->n_hvx = n_hvx; kparams->vtcm_size = (uint32_t) layout.total_bytes; - if (!kparams->use_src1) { - kparams->kernel_type = HTP_SOFTMAX_KERNEL_NOMASK; - } else if (kparams->use_f16) { - kparams->kernel_type = HTP_SOFTMAX_KERNEL_MASK_F16; + if (kparams->src0_f16) { + if (!kparams->use_src1) { + kparams->kernel_type = HTP_SOFTMAX_KERNEL_SRC16_NOMASK; + } else if (kparams->use_f16) { + kparams->kernel_type = HTP_SOFTMAX_KERNEL_SRC16_MASK_F16; + } else { + kparams->kernel_type = HTP_SOFTMAX_KERNEL_SRC16_MASK_F32; + } } else { - kparams->kernel_type = HTP_SOFTMAX_KERNEL_MASK_F32; + if (!kparams->use_src1) { + kparams->kernel_type = HTP_SOFTMAX_KERNEL_NOMASK; + } else if (kparams->use_f16) { + kparams->kernel_type = HTP_SOFTMAX_KERNEL_MASK_F16; + } else { + kparams->kernel_type = HTP_SOFTMAX_KERNEL_MASK_F32; + } } if (src0->ne[1] > 0) kparams->div_ne01 = init_fastdiv_values(src0->ne[1]); @@ -1931,14 +2132,16 @@ static bool htp_kparams_solve_rope( if (!ggml_are_same_shape(src0, dst)) { return false; } - if (src0->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 || src1->type != GGML_TYPE_I32) { + const bool is_f32 = (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32); + const bool is_f16 = (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16); + if ((!is_f32 && !is_f16) || src1->type != GGML_TYPE_I32) { return false; } if (src0->ne[0] <= 0) { return false; } - const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3]; + const uint32_t src0_nrows = ggml_nrows(src0); if (src0_nrows == 0) { return false; } @@ -1992,8 +2195,9 @@ static bool htp_kparams_solve_rope( } } - if (src0->nb[0] != sizeof(float) || dst->nb[0] != sizeof(float) || - src0->nb[1] < src0->ne[0] * sizeof(float) || dst->nb[1] < dst->ne[0] * sizeof(float)) { + const size_t elem_size = is_f16 ? sizeof(ggml_fp16_t) : sizeof(float); + if (src0->nb[0] != elem_size || dst->nb[0] != elem_size || + src0->nb[1] < src0->ne[0] * elem_size || dst->nb[1] < dst->ne[0] * elem_size) { return false; } @@ -2001,15 +2205,29 @@ static bool htp_kparams_solve_rope( const uint32_t n_freq_factors = src2 ? (uint32_t) src2->ne[0] : 0; struct htp_rope_vtcm_layout layout; - htp_rope_vtcm_layout_build(&layout, src0->ne[0], n_hvx, n_freq_factors); + htp_rope_vtcm_layout_build(&layout, src0->ne[0], elem_size, n_hvx, n_freq_factors); if (layout.total_bytes > htp_session_vtcm_size(sess)) { return false; } - kparams->n_hvx = n_hvx; - kparams->vtcm_size = (uint32_t) layout.total_bytes; - kparams->div_ne2_ne1 = init_fastdiv_values(dst->ne[2] * dst->ne[1]); - kparams->div_ne1 = init_fastdiv_values(dst->ne[1]); + const int n_ctx_orig = op_params[4]; + float beta_fast, beta_slow; + memcpy(&beta_fast, op_params + 9, sizeof(float)); + memcpy(&beta_slow, op_params + 10, sizeof(float)); + + kparams->n_hvx = n_hvx; + kparams->vtcm_size = (uint32_t) layout.total_bytes; + kparams->theta_scale = (n_dims > 0) ? std::pow(freq_base, -2.0f / n_dims) : 0.0f; + kparams->theta_scale_32 = (n_dims > 0) ? std::pow(freq_base, -64.0f / n_dims) : 0.0f; + { + const float inv_2log_fb = 1.0f / (2.0f * std::log(freq_base)); + const float start = std::floor(n_dims * std::log(n_ctx_orig / (beta_fast * 2.0f * (float) M_PI)) * inv_2log_fb); + const float end = std::ceil(n_dims * std::log(n_ctx_orig / (beta_slow * 2.0f * (float) M_PI)) * inv_2log_fb); + kparams->corr_dims[0] = std::max(0.0f, start); + kparams->corr_dims[1] = std::min((float) (n_dims - 1), end); + } + kparams->div_ne2_ne1 = init_fastdiv_values(dst->ne[2] * dst->ne[1]); + kparams->div_ne1 = init_fastdiv_values(dst->ne[1]); return true; } @@ -2024,42 +2242,173 @@ static bool htp_kparams_solve_sum_rows( const struct ggml_tensor * src0 = op->src[0]; const struct ggml_tensor * dst = op; - if (src0->type != GGML_TYPE_F32) { + const uint32_t ne00 = src0->ne[0]; + const uint32_t src0_nrows = ggml_nrows(src0); + const uint32_t max_hvx_sess = htp_session_n_hvx(sess); + + if (op->op == GGML_OP_SUM_ROWS) { + if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || + (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) { + return false; + } + if (dst->ne[0] != 1 || + dst->ne[1] != src0->ne[1] || + dst->ne[2] != src0->ne[2] || + dst->ne[3] != src0->ne[3]) { + return false; + } + if (!ggml_is_contiguous_rows(src0) || !ggml_is_contiguous(dst)) { + return false; + } + + const size_t src0_elem_size = ggml_type_size(src0->type); + const size_t dst_elem_size = ggml_type_size(dst->type); + const size_t src0_data_row_size = (size_t) ne00 * src0_elem_size; + const size_t src0_row_size_aligned = hex_round_up(src0_data_row_size, 128); + const size_t vtcm_size = htp_session_vtcm_size(sess); + + const uint32_t min_rpt = (src0_data_row_size < 1024) ? 32 : 1; + const uint32_t max_hvx = (std::max)(1u, src0_nrows / min_rpt); + uint32_t n_hvx = (std::min)(max_hvx_sess, max_hvx); + + while (n_hvx > 1 && 2 * (src0_row_size_aligned + 128) * n_hvx > vtcm_size) { + n_hvx--; + } + if (n_hvx == 0 || 2 * (src0_row_size_aligned + 128) * n_hvx > vtcm_size) { + return false; + } + + const bool can_2d_dma = (src0_nrows > 1) && + (src0->nb[1] >= src0_data_row_size); + const bool src0_contig = can_2d_dma && ggml_is_contiguous_1(src0); + + const uint32_t src0_nrows_per_hvx = (src0_nrows + n_hvx - 1) / n_hvx; + const uint32_t min_block_rows = (uint32_t) (std::max(1, 2048 / src0_data_row_size)); + uint32_t max_block = !can_2d_dma ? 1u : (src0_contig ? src0_nrows : (uint32_t) src0->ne[1]); + if (max_block > 1 && src0_nrows_per_hvx >= 2 * min_block_rows) { + max_block = (std::min)(max_block, (std::max)(min_block_rows, src0_nrows_per_hvx / 4)); + } + max_block = (std::min)(max_block, 512u); + max_block = (std::max)(max_block, 1u); + + const size_t per_hvx_budget = vtcm_size / (2 * n_hvx); + uint32_t block = (per_hvx_budget > 128) + ? (uint32_t) ((per_hvx_budget - 128) / (src0_row_size_aligned + dst_elem_size)) + : 1u; + block = (std::min)(block, max_block); + block = (std::max)(block, 1u); + + struct htp_sum_rows_vtcm_layout L; + htp_sum_rows_vtcm_layout_build(&L, src0_data_row_size, dst_elem_size, block, n_hvx); + while (block > 1 && L.total_bytes > vtcm_size) { + block--; + htp_sum_rows_vtcm_layout_build(&L, src0_data_row_size, dst_elem_size, block, n_hvx); + } + if (L.total_bytes > vtcm_size) { + return false; + } + + kparams->n_hvx = n_hvx; + kparams->block = block; + kparams->src0_contig = src0_contig ? 1 : 0; + kparams->vtcm_size = (uint32_t) L.total_bytes; + kparams->div_ne01 = init_fastdiv_values((uint32_t) src0->ne[1]); + kparams->div_ne02 = init_fastdiv_values((uint32_t) src0->ne[2]); + kparams->div_ne012 = init_fastdiv_values((uint32_t) (src0->ne[1] * src0->ne[2])); + + return true; + } + + if (src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) { return false; } if (op->op == GGML_OP_ARGMAX) { if (dst->type != GGML_TYPE_I32) { return false; } - } else if (dst->type != GGML_TYPE_F32) { + } else if (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16) { return false; } if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(dst)) { return false; } - const uint32_t ne00 = src0->ne[0]; - const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3]; - const uint32_t max_hvx_sess = htp_session_n_hvx(sess); + const size_t vtcm_size = htp_session_vtcm_size(sess); + const size_t src0_elem_size = ggml_type_size(src0->type); + const uint32_t elems_per_vec = (uint32_t) (128 / src0_elem_size); if (op->op == GGML_OP_SUM) { const uint32_t total_elems = (uint32_t) ggml_nelements(src0); - const uint32_t n_hvx = (total_elems >= 1024) ? max_hvx_sess : 1; - const uint32_t raw_chunk = (total_elems + n_hvx - 1) / n_hvx; + uint32_t n_hvx = (total_elems >= 1024) ? max_hvx_sess : 1; + uint32_t chunk_elems = (std::min)(4096u, (uint32_t) hex_round_up((std::max)(1u, total_elems), elems_per_vec)); + + struct htp_sum_vtcm_layout L; + htp_sum_vtcm_layout_build(&L, chunk_elems, src0_elem_size, n_hvx); + while (L.total_bytes > vtcm_size && chunk_elems > elems_per_vec) { + chunk_elems = (std::max)(elems_per_vec, (chunk_elems / 2) & ~(elems_per_vec - 1)); + htp_sum_vtcm_layout_build(&L, chunk_elems, src0_elem_size, n_hvx); + } + while (L.total_bytes > vtcm_size && n_hvx > 1) { + n_hvx--; + htp_sum_vtcm_layout_build(&L, chunk_elems, src0_elem_size, n_hvx); + } + if (L.total_bytes > vtcm_size) { + return false; + } + + const uint32_t raw_chunk = (total_elems + n_hvx - 1) / n_hvx; kparams->n_hvx = n_hvx; - kparams->elems_per_hvx = hex_round_up(raw_chunk, 32); + kparams->elems_per_hvx = hex_round_up(raw_chunk, elems_per_vec); + kparams->chunk_elems = chunk_elems; + kparams->vtcm_size = (uint32_t) L.total_bytes; } else if (op->op == GGML_OP_ARGMAX && src0_nrows <= 1) { - const uint32_t n_hvx = (ne00 >= 1024) ? max_hvx_sess : 1; + uint32_t n_hvx = (ne00 >= 1024) ? max_hvx_sess : 1; + uint32_t chunk_elems = (std::min)(4096u, (uint32_t) hex_round_up((std::max)(1u, ne00), elems_per_vec)); + + struct htp_sum_vtcm_layout L; + htp_sum_vtcm_layout_build(&L, chunk_elems, src0_elem_size, n_hvx); + while (L.total_bytes > vtcm_size && chunk_elems > elems_per_vec) { + chunk_elems = (std::max)(elems_per_vec, (chunk_elems / 2) & ~(elems_per_vec - 1)); + htp_sum_vtcm_layout_build(&L, chunk_elems, src0_elem_size, n_hvx); + } + while (L.total_bytes > vtcm_size && n_hvx > 1) { + n_hvx--; + htp_sum_vtcm_layout_build(&L, chunk_elems, src0_elem_size, n_hvx); + } + if (L.total_bytes > vtcm_size) { + return false; + } + const uint32_t raw_chunk = (ne00 + n_hvx - 1) / n_hvx; kparams->n_hvx = n_hvx; - kparams->elems_per_hvx = hex_round_up(raw_chunk, 32); + kparams->elems_per_hvx = hex_round_up(raw_chunk, elems_per_vec); + kparams->chunk_elems = chunk_elems; + kparams->vtcm_size = (uint32_t) L.total_bytes; } else { - const uint32_t min_rpt = (src0->nb[1] < 1024) ? 32 : 1; - const uint32_t max_hvx = (std::max)(1u, src0_nrows / min_rpt); + const uint32_t min_rpt = (src0->nb[1] < 1024) ? 32 : 1; + const uint32_t max_hvx = (std::max)(1u, src0_nrows / min_rpt); + uint32_t n_hvx = (std::min)(max_hvx_sess, max_hvx); + uint32_t chunk_elems = (std::min)(4096u, (uint32_t) hex_round_up((std::max)(1u, ne00), elems_per_vec)); + + struct htp_sum_vtcm_layout L; + htp_sum_vtcm_layout_build(&L, chunk_elems, src0_elem_size, n_hvx); + while (L.total_bytes > vtcm_size && chunk_elems > elems_per_vec) { + chunk_elems = (std::max)(elems_per_vec, (chunk_elems / 2) & ~(elems_per_vec - 1)); + htp_sum_vtcm_layout_build(&L, chunk_elems, src0_elem_size, n_hvx); + } + while (L.total_bytes > vtcm_size && n_hvx > 1) { + n_hvx--; + htp_sum_vtcm_layout_build(&L, chunk_elems, src0_elem_size, n_hvx); + } + if (L.total_bytes > vtcm_size) { + return false; + } - kparams->n_hvx = (std::min)(max_hvx_sess, max_hvx); + kparams->n_hvx = n_hvx; + kparams->chunk_elems = chunk_elems; + kparams->vtcm_size = (uint32_t) L.total_bytes; } return true; @@ -2099,7 +2448,7 @@ bool htp_kparams_solve_unary_mul_glu( } const size_t dst_row_size = dst->ne[0] * elem_size; - const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3]; + const uint32_t src0_nrows = ggml_nrows(src0); const uint32_t min_rows_per_hvx = (uint32_t) (std::max(1, (128 + dst_row_size - 1) / dst_row_size)); const uint32_t max_hvx = (std::max)(1u, src0_nrows / min_rows_per_hvx); const uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx); @@ -2127,14 +2476,6 @@ bool htp_kparams_solve_unary_mul_glu( return true; } -static bool htp_kparams_solve_glu( - const struct ggml_hexagon_session * sess, - const struct ggml_tensor * op, - struct htp_glu_kernel_params * kparams -) { - return htp_kparams_solve_unary_mul_glu(sess, htp_op_remap(op), op->src[0], op->src[1], op, kparams); -} - static bool htp_kparams_solve_repeat( const struct ggml_hexagon_session * sess, const struct ggml_tensor * op, @@ -2145,24 +2486,97 @@ static bool htp_kparams_solve_repeat( const struct ggml_tensor * src0 = op->src[0]; const struct ggml_tensor * dst = op; - if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || src0->type != dst->type) { + if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || + (dst->type != src0->type && !(src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16))) { return false; } + const size_t src_elem_size = ggml_type_size(src0->type); + const size_t dst_elem_size = ggml_type_size(dst->type); + if (!ggml_can_repeat(src0, dst) || ggml_is_transposed(src0) || ggml_is_transposed(dst)) { return false; } + if (src0->nb[0] != src_elem_size || dst->nb[0] != dst_elem_size) { + return false; + } - const uint32_t total_dst_rows = dst->ne[1] * dst->ne[2] * dst->ne[3]; - const size_t dst_row_size = dst->ne[0] * ggml_type_size(dst->type); + const uint32_t ne00 = (uint32_t) src0->ne[0]; + const uint32_t nr0 = (uint32_t) (dst->ne[0] / src0->ne[0]); + const uint32_t total_dst_rows = (uint32_t) ggml_nrows(dst); + const size_t src_row_size = (size_t) ne00 * src_elem_size; + const size_t dst_row_size = (size_t) dst->ne[0] * dst_elem_size; const uint32_t min_rows_per_hvx = (uint32_t) (std::max(1, (128 + dst_row_size - 1) / dst_row_size)); const uint32_t max_hvx = (std::max)(1u, total_dst_rows / min_rows_per_hvx); - const uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx); + const uint32_t orig_n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx); + const size_t vtcm_size = htp_session_vtcm_size(sess); - kparams->n_hvx = n_hvx; - kparams->nr0 = dst->ne[0] / src0->ne[0]; - kparams->nr1 = dst->ne[1] / src0->ne[1]; - kparams->nr2 = dst->ne[2] / src0->ne[2]; - kparams->nr3 = dst->ne[3] / src0->ne[3]; + uint32_t n_hvx = orig_n_hvx; + uint32_t tile_elems = ne00; + uint32_t dst_reps = nr0; + uint32_t pipelined = 1; + + struct htp_repeat_vtcm_layout L; + htp_repeat_vtcm_layout_build(&L, src_row_size, dst_row_size, 2, n_hvx); + while (L.total_bytes > vtcm_size && n_hvx > 1) { + n_hvx--; + htp_repeat_vtcm_layout_build(&L, src_row_size, dst_row_size, 2, n_hvx); + } + + if (L.total_bytes > vtcm_size) { + // Fallback to single-buffered row or column-tiled DMA + pipelined = 0; + n_hvx = orig_n_hvx; + const size_t dst_unit_bytes = (size_t) ne00 * dst_elem_size; + + htp_repeat_vtcm_layout_build(&L, src_row_size, dst_unit_bytes, 1, n_hvx); + while (L.total_bytes > vtcm_size && n_hvx > 1) { + n_hvx--; + htp_repeat_vtcm_layout_build(&L, src_row_size, dst_unit_bytes, 1, n_hvx); + } + + if (L.total_bytes <= vtcm_size) { + tile_elems = ne00; + const size_t per_hvx_budget = vtcm_size / n_hvx; + const size_t dst_budget = per_hvx_budget > L.src_buf_bytes ? (per_hvx_budget - L.src_buf_bytes) : dst_unit_bytes; + dst_reps = (uint32_t) (std::min(nr0, (std::max(1, dst_budget / dst_unit_bytes)))); + htp_repeat_vtcm_layout_build(&L, src_row_size, (size_t) dst_reps * dst_unit_bytes, 1, n_hvx); + while (L.total_bytes > vtcm_size && dst_reps > 1) { + dst_reps = (std::max)(1u, dst_reps / 2); + htp_repeat_vtcm_layout_build(&L, src_row_size, (size_t) dst_reps * dst_unit_bytes, 1, n_hvx); + } + } else { + // Single src row exceeds VTCM: column-tile along dim0 + dst_reps = 1; + n_hvx = orig_n_hvx; + tile_elems = (std::min)(ne00, 4096u); + if (tile_elems > 64) { + tile_elems = (tile_elems / 64) * 64; + } + htp_repeat_vtcm_layout_build(&L, (size_t) tile_elems * src_elem_size, (size_t) tile_elems * dst_elem_size, 1, n_hvx); + while (L.total_bytes > vtcm_size && tile_elems > 64) { + tile_elems = (std::max)(64u, ((tile_elems / 2) / 64) * 64); + htp_repeat_vtcm_layout_build(&L, (size_t) tile_elems * src_elem_size, (size_t) tile_elems * dst_elem_size, 1, n_hvx); + } + while (L.total_bytes > vtcm_size && n_hvx > 1) { + n_hvx--; + htp_repeat_vtcm_layout_build(&L, (size_t) tile_elems * src_elem_size, (size_t) tile_elems * dst_elem_size, 1, n_hvx); + } + } + } + + if (L.total_bytes > vtcm_size) { + return false; + } + + kparams->n_hvx = n_hvx; + kparams->nr0 = nr0; + kparams->nr1 = dst->ne[1] / src0->ne[1]; + kparams->nr2 = dst->ne[2] / src0->ne[2]; + kparams->nr3 = dst->ne[3] / src0->ne[3]; + kparams->tile_elems = tile_elems; + kparams->dst_reps = dst_reps; + kparams->pipelined = pipelined; + kparams->vtcm_size = (uint32_t) L.total_bytes; kparams->div_ne1 = init_fastdiv_values(dst->ne[1]); kparams->div_ne12 = init_fastdiv_values(dst->ne[1] * dst->ne[2]); @@ -2175,16 +2589,17 @@ static bool htp_kparams_solve_repeat( static bool htp_kparams_solve_ssm_conv( const struct ggml_hexagon_session * sess, - const struct ggml_tensor * op, + const struct ggml_tensor * src0, + const struct ggml_tensor * src1, + const struct ggml_tensor * dst, struct htp_ssm_conv_kernel_params * kparams ) { memset(kparams, 0, sizeof(*kparams)); - const struct ggml_tensor * src0 = op->src[0]; - const struct ggml_tensor * src1 = op->src[1]; - const struct ggml_tensor * dst = op; - - if (src0->type != GGML_TYPE_F32 || src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) { + const auto is_valid_type = [](ggml_type t) { + return t == GGML_TYPE_F32 || t == GGML_TYPE_F16; + }; + if (!is_valid_type(src0->type) || !is_valid_type(src1->type) || !is_valid_type(dst->type)) { return false; } if (src0->ne[3] != 1 || src1->ne[2] != 1 || src1->ne[3] != 1 || dst->ne[3] != 1) { @@ -2208,10 +2623,23 @@ static bool htp_kparams_solve_ssm_conv( if (dst->ne[0] != d_inner_64 || dst->ne[1] != n_t_64 || dst->ne[2] != n_s_64) { return false; } - if (src0->nb[0] != sizeof(float) || src1->nb[0] != sizeof(float) || dst->nb[0] != sizeof(float)) { + + const size_t src0_elem_size = ggml_type_size(src0->type); + const size_t src1_elem_size = ggml_type_size(src1->type); + const size_t dst_elem_size = ggml_type_size(dst->type); + + if (src0->nb[0] != src0_elem_size || src1->nb[0] != src1_elem_size || dst->nb[0] != dst_elem_size) { return false; } - if (src0->nb[1] != src0->ne[0] * sizeof(float) || src1->nb[1] != src1->ne[0] * sizeof(float)) { + if (src1->nb[1] != (size_t) src1->ne[0] * src1_elem_size) { + return false; + } + if ((d_inner_64 > 1 && src0->nb[1] < (size_t) src0->ne[0] * src0_elem_size) || + (n_s_64 > 1 && src0->nb[2] < (size_t) d_inner_64 * src0->nb[1])) { + return false; + } + if ((n_t_64 > 1 && dst->nb[1] < (size_t) d_inner_64 * dst_elem_size) || + (n_s_64 > 1 && dst->nb[2] < (size_t) n_t_64 * dst->nb[1])) { return false; } @@ -2240,7 +2668,7 @@ static bool htp_kparams_solve_ssm_conv( const uint32_t src1_T_bytes = hex_round_up(d_conv * d_inner_per_hvx * sizeof(float), 128); const uint32_t vtcm_src1_per_hvx = src1_raw_bytes + src1_T_bytes; - const size_t vtcm_budget = (vtcm_size > 0 ? vtcm_size / n_hvx : (1024 * 1024)); + const size_t vtcm_budget = vtcm_size / n_hvx; const uint32_t src0_block_T = hex_round_up(ncs * 32 * sizeof(float), 128); const size_t fixed_bytes = vtcm_src1_per_hvx + src0_block_T; const size_t avail_for_tiles = vtcm_budget > fixed_bytes ? vtcm_budget - fixed_bytes : (128 * 1024); @@ -2249,7 +2677,7 @@ static bool htp_kparams_solve_ssm_conv( target_max_tile = (std::max)(target_max_tile, 32u); target_max_tile = (std::min)(target_max_tile, 128u); - const size_t raw_stride_bytes = ncs * sizeof(float) + sizeof(float); + const size_t raw_stride_bytes = htp_ssm_conv_raw_stride_bytes(ncs, src0_elem_size); uint32_t d_inner_tile = (uint32_t) (avail_for_tiles / (2 * (raw_stride_bytes + n_t * sizeof(float)))); d_inner_tile = (d_inner_tile / 32) * 32; if (d_inner_tile == 0) { @@ -2265,7 +2693,7 @@ static bool htp_kparams_solve_ssm_conv( } struct htp_ssm_conv_vtcm_layout L; - htp_ssm_conv_vtcm_layout_build(&L, d_inner_per_hvx, d_conv, n_t, kparams->d_inner_tile, n_hvx); + htp_ssm_conv_vtcm_layout_build(&L, d_inner_per_hvx, d_conv, n_t, kparams->d_inner_tile, n_hvx, src0_elem_size); kparams->vtcm_size = (uint32_t) L.total_bytes; kparams->div_d_inner_tile = init_fastdiv_values(kparams->d_inner_tile); @@ -2273,6 +2701,131 @@ static bool htp_kparams_solve_ssm_conv( return L.total_bytes <= vtcm_size; } +static bool htp_kparams_solve_ssm_conv_token_major( + const struct ggml_hexagon_session * sess, + const struct ggml_tensor * state, + const struct ggml_tensor * weight, + const struct ggml_tensor * x, + const struct ggml_tensor * dst, + const struct ggml_tensor * dst_state, + struct htp_ssm_conv_kernel_params * kparams +) { + memset(kparams, 0, sizeof(*kparams)); + + const auto is_valid_type = [](ggml_type t) { + return t == GGML_TYPE_F32 || t == GGML_TYPE_F16; + }; + if (!is_valid_type(state->type) || !is_valid_type(weight->type) || + !is_valid_type(x->type) || !is_valid_type(dst->type)) { + return false; + } + if (dst_state && !is_valid_type(dst_state->type)) { + return false; + } + if (state->ne[3] != 1 || weight->ne[2] != 1 || weight->ne[3] != 1 || + x->ne[3] != 1 || dst->ne[3] != 1) { + return false; + } + + const int64_t d_conv_64 = weight->ne[0]; + const int64_t d_inner_64 = weight->ne[1]; + const int64_t n_t_64 = dst->ne[1]; + const int64_t n_s_64 = dst->ne[2]; + const int64_t S_64 = d_conv_64 - 1; + + if (d_conv_64 < 2 || d_conv_64 > 32 || d_inner_64 <= 0 || n_t_64 <= 0 || n_s_64 <= 0) { + return false; + } + if (state->ne[0] != S_64 || state->ne[1] != d_inner_64 || state->ne[2] != n_s_64) { + return false; + } + if (x->ne[0] != d_inner_64 || x->ne[1] != n_t_64 || x->ne[2] != n_s_64) { + return false; + } + if (dst->ne[0] != d_inner_64) { + return false; + } + + const size_t state_elem_size = ggml_type_size(state->type); + const size_t weight_elem_size = ggml_type_size(weight->type); + const size_t x_elem_size = ggml_type_size(x->type); + const size_t dst_elem_size = ggml_type_size(dst->type); + + if (state->nb[0] != state_elem_size || weight->nb[0] != weight_elem_size || + x->nb[0] != x_elem_size || dst->nb[0] != dst_elem_size) { + return false; + } + if (weight->nb[1] != (size_t) d_conv_64 * weight_elem_size) { + return false; + } + if ((d_inner_64 > 1 && state->nb[1] != (size_t) S_64 * state_elem_size) || + (n_s_64 > 1 && state->nb[2] < (size_t) d_inner_64 * state->nb[1])) { + return false; + } + if ((n_t_64 > 1 && x->nb[1] < (size_t) d_inner_64 * x_elem_size) || + (n_s_64 > 1 && x->nb[2] < (size_t) n_t_64 * x->nb[1])) { + return false; + } + if ((n_t_64 > 1 && dst->nb[1] < (size_t) d_inner_64 * dst_elem_size) || + (n_s_64 > 1 && dst->nb[2] < (size_t) n_t_64 * dst->nb[1])) { + return false; + } + + if (dst_state) { + const size_t dst_state_elem_size = ggml_type_size(dst_state->type); + if (dst_state->ne[0] != S_64 * d_inner_64 || dst_state->ne[1] != n_s_64 || + dst_state->ne[2] != 1 || dst_state->ne[3] != 1 || + dst_state->nb[0] != dst_state_elem_size || + (n_s_64 > 1 && dst_state->nb[1] < (size_t) S_64 * d_inner_64 * dst_state_elem_size)) { + return false; + } + } + + const uint32_t d_conv = (uint32_t) d_conv_64; + const uint32_t d_inner = (uint32_t) d_inner_64; + const uint32_t n_t = (uint32_t) n_t_64; + const uint32_t n_s = (uint32_t) n_s_64; + + const uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), (d_inner + 31) / 32); + const size_t vtcm_size = htp_session_vtcm_size(sess); + + const uint32_t raw_rpt = (d_inner + n_hvx - 1) / n_hvx; + const uint32_t d_inner_per_hvx = hex_round_up(raw_rpt, 32); + + uint32_t d_inner_tile = hex_round_up(d_inner_per_hvx, 64); + uint32_t n_t_tile = (std::min)(n_t, 64u); + + struct htp_ssm_conv_vtcm_layout L; + while (true) { + htp_ssm_conv_token_vtcm_layout_build(&L, d_inner_per_hvx, d_conv, n_t_tile, d_inner_tile, n_hvx, x_elem_size, dst_elem_size); + if (L.total_bytes <= vtcm_size) { + break; + } + if (n_t_tile > 8) { + n_t_tile /= 2; + } else if (d_inner_tile > 64) { + d_inner_tile = hex_round_up(d_inner_tile / 2, 64); + } else if (n_t_tile > 1) { + n_t_tile /= 2; + } else { + return false; + } + } + + kparams->n_hvx = n_hvx; + kparams->d_conv = d_conv; + kparams->d_inner = d_inner; + kparams->n_t = n_t; + kparams->n_s = n_s; + kparams->d_inner_tile = d_inner_tile; + kparams->vtcm_size = (uint32_t) L.total_bytes; + kparams->token_major = 1; + kparams->n_t_tile = n_t_tile; + kparams->n_t_blocks = (n_t + n_t_tile - 1) / n_t_tile; + + return true; +} + static bool htp_kparams_solve_ssm_scan( const struct ggml_hexagon_session * sess, const struct ggml_tensor * op, @@ -2430,15 +2983,15 @@ static bool htp_kparams_solve_sort( const struct ggml_tensor * dst = op; const bool is_top_k = (op->op == GGML_OP_TOP_K); - if (src0->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_I32) { + if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || dst->type != GGML_TYPE_I32) { return false; } - const uint32_t total_rows = src0->ne[1] * src0->ne[2] * src0->ne[3]; + const uint32_t total_rows = ggml_nrows(src0); const uint32_t ne00 = src0->ne[0]; const uint32_t k = dst->ne[0]; - const uint32_t n_hvx_max = htp_session_n_hvx(sess) > 0 ? htp_session_n_hvx(sess) : 4; - const size_t vtcm_budget = htp_session_vtcm_size(sess) > 0 ? htp_session_vtcm_size(sess) : (8 * 1024 * 1024); + const uint32_t n_hvx_max = htp_session_n_hvx(sess); + const size_t vtcm_budget = htp_session_vtcm_size(sess); int32_t order = GGML_SORT_ORDER_DESC; if (!is_top_k) { @@ -2524,12 +3077,10 @@ static bool htp_kparams_solve_pool_2d( const uint32_t src_y = is_pool_1d ? 1 : (uint32_t) src0->ne[1]; const uint32_t dst_x = (uint32_t) dst->ne[0]; const uint32_t dst_y = is_pool_1d ? 1 : (uint32_t) dst->ne[1]; - const uint32_t dst_plane_bytes = dst_x * dst_y * sizeof(float); const uint32_t planes = (uint32_t) (is_pool_1d ? (uint64_t) src0->ne[1] * (uint64_t) src0->ne[2] * (uint64_t) src0->ne[3] : (uint64_t) src0->ne[2] * (uint64_t) src0->ne[3]); const uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), planes > 0 ? planes : 1); - const uint32_t planes_per_chunk = (dst_plane_bytes > 0) ? (HEX_L2_LINE_SIZE / hex_gcd_u32(dst_plane_bytes, HEX_L2_LINE_SIZE)) : 1; struct htp_pool_vtcm_layout layout; if (!htp_pool_solve_layout(&layout, src_x, src_y, dst_x, dst_y, n_hvx, htp_session_vtcm_size(sess))) { @@ -2548,7 +3099,6 @@ static bool htp_kparams_solve_pool_2d( kparams->pad_y = pad_y; kparams->n_hvx = n_hvx; kparams->planes = planes; - kparams->planes_per_chunk = planes_per_chunk; kparams->pool_op = (uint32_t) params[0]; const bool exact_tiling = (kparams->pad_x == 0 && kparams->pad_y == 0 && @@ -2613,8 +3163,7 @@ bool htp_kparams_solve_upscale( const bool is_src_contig_row = (src0->nb[0] == sizeof(float)); const bool is_src_strided_2d = (src0->nb[0] > sizeof(float)) && (src0->nb[0] % sizeof(float) == 0) && - (src0->nb[1] == (size_t) src_x * src0->nb[0]) && - ((size_t) src_x * src_y <= 0xFFFFu); + (src0->nb[1] == (size_t) src_x * src0->nb[0]); if ((!is_src_contig_row && !is_src_strided_2d) || dst->nb[0] != sizeof(float)) { return false; @@ -2693,24 +3242,6 @@ bool htp_kparams_solve_upscale( n_hvx = (std::min)(n_hvx, total_chunks > 0 ? total_chunks : 1); htp_upscale_vtcm_layout_build(&layout, src_x, src_y, dst_x, dst_y, dst_nrows_per_chunk, inv_sf1, filter_radius1, n_hvx); - const uint32_t slice_dst_bytes = dst_x * dst_y * sizeof(float); - const uint32_t chunk_dst_bytes = dst_x * dst_nrows_per_chunk * sizeof(float); - const bool dst_contig = (dst->nb[1] == (size_t) dst_x * sizeof(float)) && - (dst_z <= 1 || dst->nb[2] == (size_t) dst_y * dst->nb[1]) && - (dst_w <= 1 || dst->nb[3] == (size_t) dst_z * dst->nb[2]); - - uint32_t chunks_per_group = 0; - if (dst_contig) { - const uint32_t slices_per_group = (slice_dst_bytes > 0) - ? (HEX_L2_LINE_SIZE / hex_gcd_u32(slice_dst_bytes, HEX_L2_LINE_SIZE)) - : 1; - if (slices_per_group == 1 && (chunk_dst_bytes % HEX_L2_LINE_SIZE == 0)) { - chunks_per_group = 1; - } else { - chunks_per_group = slices_per_group * chunks_per_slice; - } - } - uint8_t kernel_type = HTP_UPSCALE_KERNEL_BILINEAR; if (mode_raw == HTP_UPSCALE_MODE_NEAREST) { if (dst_x == 2 * src_x && dst_y == 2 * src_y && !align_corners) { @@ -2747,7 +3278,6 @@ bool htp_kparams_solve_upscale( kparams->invscale1 = invscale1; kparams->n_hvx = n_hvx; - kparams->chunks_per_group = chunks_per_group; kparams->dst_nrows_per_chunk = dst_nrows_per_chunk; kparams->chunks_per_slice = chunks_per_slice; @@ -2772,24 +3302,26 @@ static bool htp_kparams_solve_concat( const struct ggml_tensor * src1 = op->src[1]; const struct ggml_tensor * dst = op; - if (!src0 || !src1 || !dst) { - return false; - } - int dim = ((const int32_t *) op->op_params)[0]; if (dim < 0 || dim >= GGML_MAX_DIMS) { return false; } kparams->dim = dim; - if (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16 && dst->type != GGML_TYPE_I32) { - return false; - } - if (src0->type != dst->type || src1->type != dst->type) { + const bool all_same = (src0->type == dst->type && src1->type == dst->type); + if (dst->type == GGML_TYPE_I32) { + if (!all_same) { + return false; + } + } else if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || + (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) || + (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) { return false; } - const uint32_t type_size = ggml_type_size(dst->type); + const uint32_t src0_es = ggml_type_size(src0->type); + const uint32_t src1_es = ggml_type_size(src1->type); + const uint32_t dst_es = ggml_type_size(dst->type); const uint32_t n_hvx = htp_session_n_hvx(sess); const uint32_t mdev_count = htp_session_mdev_count(sess); const size_t vtcm_size = htp_session_vtcm_size(sess); @@ -2801,30 +3333,30 @@ static bool htp_kparams_solve_concat( } } - const uint32_t max_gather_ne0 = 128 / type_size; - const uint32_t total_rows = (uint32_t) (dst->ne[1] * dst->ne[2] * dst->ne[3]); - const bool b_dense = (src1->nb[0] == type_size); + const uint32_t max_gather_ne0 = 128 / dst_es; + const uint32_t total_rows = (uint32_t) ggml_nrows(dst); + const bool b_dense = (src1->nb[0] == src1_es); const bool gather_strides_ok = - src0->nb[1] >= (size_t) src0->ne[0] * type_size && - (b_dense ? src1->nb[1] >= (size_t) src1->ne[0] * type_size - : src1->nb[0] >= (size_t) src1->ne[1] * type_size); + src0->nb[1] >= (size_t) src0->ne[0] * src0_es && + (b_dense ? src1->nb[1] >= (size_t) src1->ne[0] * src1_es + : src1->nb[0] >= (size_t) src1->ne[1] * src1_es); if (dim == 0 && (dst->type == GGML_TYPE_F32 || dst->type == GGML_TYPE_F16) && dst->ne[0] <= max_gather_ne0 && - dst->nb[0] == type_size && dst->nb[1] == (size_t) dst->ne[0] * type_size && - src0->nb[0] == type_size && - (src1->nb[0] == type_size || src1->nb[1] == type_size) && + dst->nb[0] == dst_es && dst->nb[1] == (size_t) dst->ne[0] * dst_es && + src0->nb[0] == src0_es && + (src1->nb[0] == src1_es || src1->nb[1] == src1_es) && gather_strides_ok && htp_gather_rows_tensor_outer_contiguous(dst) && htp_gather_rows_tensor_outer_contiguous(src0) && htp_gather_rows_tensor_outer_contiguous(src1)) { - if (htp_gather_rows_solve_layout(&kparams->u.gather, - (uint32_t) src0->ne[0], (uint32_t) src0->nb[1], - (uint32_t) src1->ne[0], (uint32_t) src1->nb[1], b_dense, - type_size, total_rows, - n_hvx, mdev_count, vtcm_size)) { + if (htp_concat_gather_rows_solve_layout(&kparams->u.gather, + (uint32_t) src0->ne[0], (uint32_t) src0->nb[1], + (uint32_t) src1->ne[0], (uint32_t) src1->nb[1], b_dense, + src0_es, src1_es, dst_es, total_rows, + n_hvx, mdev_count, vtcm_size)) { kparams->kernel_type = HTP_CONCAT_KERNEL_GATHER_ROWS; kparams->n_hvx = (uint8_t) n_hvx; kparams->vtcm_size = kparams->u.gather.slice * n_hvx; @@ -2832,31 +3364,67 @@ static bool htp_kparams_solve_concat( } } - const bool dma_strides_ok = (src0->nb[0] == type_size && src1->nb[0] == type_size && dst->nb[0] == type_size); + const bool dma_strides_ok = (src0->nb[0] == src0_es && src1->nb[0] == src1_es && dst->nb[0] == dst_es); if (dma_strides_ok) { kparams->kernel_type = HTP_CONCAT_KERNEL_REGULAR; - kparams->n_hvx = 1; + if (all_same) { + kparams->n_hvx = 1; + kparams->vtcm_size = 0; + } else { + const uint32_t req_vt = n_hvx * 4 * HTP_CONCAT_REG_BLK_BYTES; + if (req_vt > vtcm_size) { + return false; + } + kparams->n_hvx = (uint8_t) n_hvx; + kparams->vtcm_size = req_vt; + kparams->u.regular.div_ne01 = init_fastdiv_values((uint32_t) src0->ne[1]); + kparams->u.regular.div_ne02_ne01 = init_fastdiv_values((uint32_t) (src0->ne[1] * src0->ne[2])); + kparams->u.regular.div_ne11 = init_fastdiv_values((uint32_t) src1->ne[1]); + kparams->u.regular.div_ne12_ne11 = init_fastdiv_values((uint32_t) (src1->ne[1] * src1->ne[2])); + } return true; } - const bool is_src1_transposed = (src1->nb[0] > src1->nb[1]); - const bool is_src0_transposed = (src0->nb[0] > src0->nb[1]); - const bool transposed_rows_ok = (src0->nb[0] == type_size && src1->nb[1] == type_size && dst->nb[0] == type_size); + const bool is_src1_transposed = ggml_is_transposed(src1); + const bool is_src0_transposed = ggml_is_transposed(src0); + const bool src0_trans_ok = is_src0_transposed ? (src0->nb[1] == src0_es) : (src0->nb[0] == src0_es); + const bool src1_trans_ok = is_src1_transposed ? (src1->nb[1] == src1_es) : (src1->nb[0] == src1_es); - if (dim == 0 && is_src1_transposed && !is_src0_transposed && transposed_rows_ok && + if (dim == 0 && (is_src0_transposed || is_src1_transposed) && + src0_trans_ok && src1_trans_ok && dst->nb[0] == dst_es && (dst->type == GGML_TYPE_F32 || dst->type == GGML_TYPE_F16)) { - const uint32_t nth = n_hvx > 0 ? n_hvx : 8; - struct htp_concat_transposed_vtcm_layout layout; - htp_concat_transposed_vtcm_layout_build(&layout, (uint32_t) src0->ne[0], (uint32_t) src1->ne[0], type_size, nth); + uint32_t req_vtcm = 0; - if (vtcm_size > 0 && layout.total_bytes > vtcm_size) { + if (!is_src0_transposed && is_src1_transposed) { + struct htp_concat_transposed_vtcm_layout layout; + htp_concat_transposed_vtcm_layout_build(&layout, (uint32_t) src0->ne[0], (uint32_t) src1->ne[0], src0_es, src1_es, dst_es, n_hvx); + req_vtcm = layout.total_bytes; + } else { + struct htp_concat_transposed_vtcm_layout layout0; + htp_concat_transposed_vtcm_layout_build(&layout0, 0, (uint32_t) src0->ne[0], dst_es, src0_es, dst_es, n_hvx); + req_vtcm = layout0.total_bytes; + if (is_src1_transposed) { + struct htp_concat_transposed_vtcm_layout layout1; + htp_concat_transposed_vtcm_layout_build(&layout1, 0, (uint32_t) src1->ne[0], dst_es, src1_es, dst_es, n_hvx); + if (layout1.total_bytes > req_vtcm) { + req_vtcm = layout1.total_bytes; + } + } else if (src1_es != dst_es) { + const uint32_t reg_vtcm = n_hvx * 4 * HTP_CONCAT_REG_BLK_BYTES; + if (reg_vtcm > req_vtcm) { + req_vtcm = reg_vtcm; + } + } + } + + if (req_vtcm > vtcm_size) { return false; } kparams->kernel_type = HTP_CONCAT_KERNEL_TRANSPOSED; - kparams->n_hvx = nth; - kparams->vtcm_size = layout.total_bytes; + kparams->n_hvx = (uint8_t) n_hvx; + kparams->vtcm_size = req_vtcm; kparams->u.transposed.div_ne2 = init_fastdiv_values((uint32_t) dst->ne[2]); return true; } @@ -3045,9 +3613,9 @@ static bool htp_kparams_solve_cpy( const bool sametype = (src0->type == dst->type); const bool same_extents = ggml_are_same_shape(src0, dst); - const bool transposed = (src0->nb[0] > src0->nb[1]) || (dst->nb[0] > dst->nb[1]) || + const bool transposed = ggml_is_transposed(src0) || ggml_is_transposed(dst) || (src0->nb[0] != src_type_size) || (dst->nb[0] != dst_type_size) || - (src0->nb[1] < (size_t) src0->ne[0] * src_type_size) || (dst->nb[1] < (size_t) dst->ne[0] * dst_type_size); + (src0->nb[1] < ggml_row_size(src0->type, src0->ne[0])) || (dst->nb[1] < ggml_row_size(dst->type, dst->ne[0])); const bool sameshape = same_extents && !transposed; const bool src_is_contiguous = ggml_is_contiguous(src0); @@ -3057,45 +3625,46 @@ static bool htp_kparams_solve_cpy( const uint32_t mdev_count = htp_session_mdev_count(sess); const size_t vtcm_size = htp_session_vtcm_size(sess); - if (sametype) { - if (src_is_contiguous && dst_is_contiguous) { - kparams->kernel_type = HTP_COPY_KERNEL_1D_CONTIG; - return true; - } + if (sametype && src_is_contiguous && dst_is_contiguous) { + kparams->kernel_type = HTP_COPY_KERNEL_1D_CONTIG; + return true; + } - const uint32_t max_gather_ne0 = 128 / src_type_size; - const uint32_t total_rows = (uint32_t) (src0->ne[1] * src0->ne[2] * src0->ne[3]); - if ((src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16) && - dst_is_contiguous && !src_is_contiguous && - src0->nb[0] == src_type_size && src0->ne[0] <= max_gather_ne0 && - src0->nb[1] >= (size_t) src0->ne[0] * src_type_size && - total_rows > 1 && - htp_gather_rows_tensor_outer_contiguous(src0)) { - - if (htp_gather_rows_solve_layout(&kparams->u.gather, - (uint32_t) src0->ne[0], (uint32_t) src0->nb[1], - 0, 0, false, - src_type_size, total_rows, - n_hvx, mdev_count, vtcm_size)) { - kparams->kernel_type = HTP_COPY_KERNEL_GATHER_ROWS; - kparams->n_hvx = (uint8_t) n_hvx; - kparams->vtcm_size = kparams->u.gather.slice * n_hvx; - return true; - } + const uint32_t max_gather_ne0 = 128 / src_type_size; + const uint32_t total_rows = (uint32_t) ggml_nrows(src0); + if ((src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16) && + (dst->type == GGML_TYPE_F32 || dst->type == GGML_TYPE_F16) && + dst_is_contiguous && !src_is_contiguous && + src0->nb[0] == src_type_size && src0->ne[0] <= max_gather_ne0 && + src0->nb[1] >= (size_t) src0->ne[0] * src_type_size && + total_rows > 1 && + htp_gather_rows_tensor_outer_contiguous(src0)) { + + if (htp_gather_rows_solve_layout(&kparams->u.gather, + (uint32_t) src0->ne[0], (uint32_t) src0->nb[1], + 0, 0, false, + src_type_size, dst_type_size, total_rows, + n_hvx, mdev_count, vtcm_size)) { + kparams->kernel_type = HTP_COPY_KERNEL_GATHER_ROWS; + kparams->n_hvx = (uint8_t) n_hvx; + kparams->vtcm_size = kparams->u.gather.slice * n_hvx; + return true; } + } + if (sametype) { if (htp_kparams_solve_cpy_transpose(sess, src0, dst, src_type_size, kparams)) { return true; } if (sameshape) { kparams->kernel_type = HTP_COPY_KERNEL_SAMESHAPE_SAMETYPE; - kparams->total_rows = (uint32_t) (src0->ne[1] * src0->ne[2] * src0->ne[3]); + kparams->total_rows = (uint32_t) ggml_nrows(src0); return true; } kparams->kernel_type = HTP_COPY_KERNEL_RESHAPE; - kparams->n_hvx = n_hvx > 0 ? (uint8_t) n_hvx : 4; + kparams->n_hvx = (uint8_t) n_hvx; kparams->u.reshape.div_ne0 = init_fastdiv_values((uint32_t) dst->ne[0]); kparams->u.reshape.div_ne1_ne0 = init_fastdiv_values((uint32_t) (dst->ne[1] * dst->ne[0])); kparams->u.reshape.div_ne2_ne1_ne0 = init_fastdiv_values((uint32_t) (dst->ne[2] * dst->ne[1] * dst->ne[0])); @@ -3117,17 +3686,16 @@ static bool htp_kparams_solve_cpy( return false; } - const uint32_t nth = n_hvx > 0 ? n_hvx : 4; struct htp_copy_convert_vtcm_layout layout; - htp_copy_convert_solve_layout(&layout, (uint32_t) src0->ne[0], (uint32_t) src0->ne[1], src_type_size, dst_type_size, nth); + htp_copy_convert_solve_layout(&layout, (uint32_t) src0->ne[0], (uint32_t) src0->ne[1], src_type_size, dst_type_size, n_hvx); - if (vtcm_size > 0 && layout.total_bytes > vtcm_size) { + if (layout.total_bytes > vtcm_size) { return false; } kparams->kernel_type = HTP_COPY_KERNEL_SAMESHAPE_CONVERT; - kparams->total_rows = (uint32_t) (src0->ne[1] * src0->ne[2] * src0->ne[3]); - kparams->n_hvx = (uint8_t) nth; + kparams->total_rows = (uint32_t) ggml_nrows(src0); + kparams->n_hvx = (uint8_t) n_hvx; kparams->vtcm_size = (uint32_t) layout.total_bytes; kparams->u.convert.blk_rows = layout.blk_rows; kparams->u.convert.div_ne01 = init_fastdiv_values((uint32_t) src0->ne[1]); @@ -3227,11 +3795,9 @@ static bool htp_kparams_solve_im2col( is_patchembed = is_patchembed && (s1 == (int32_t) KH && p1 == 0 && d1 == 1); } - const uint32_t max_hvx = (sess && htp_session_n_hvx(sess) > 0) ? htp_session_n_hvx(sess) : 8; + const uint32_t max_hvx = htp_session_n_hvx(sess); const uint32_t n_hvx = (total_rows < max_hvx) ? total_rows : max_hvx; - const uint32_t vtcm_size = (sess && htp_session_vtcm_size(sess) > 0) ? (uint32_t) htp_session_vtcm_size(sess) : 0; - const uint32_t row_size = (uint32_t) dst->nb[2]; - const uint32_t rows_per_chunk = (row_size > 0) ? (HEX_L2_LINE_SIZE / hex_gcd_u32(row_size, HEX_L2_LINE_SIZE)) : 1; + const size_t vtcm_size = htp_session_vtcm_size(sess); if (is_patchembed) { const uint64_t src_row_bytes_raw = (uint64_t) IC * KH * IW * sizeof(float); @@ -3244,7 +3810,7 @@ static bool htp_kparams_solve_im2col( htp_im2col_vtcm_layout_build(&layout, src_row_bytes, dst_row_bytes, n_hvx, htp_im2col_scratch_bytes(HTP_IM2COL_KERNEL_PATCHEMBED_DMA, KH, patch_stride)); - if (vtcm_size == 0 || layout.total_bytes <= vtcm_size) { + if (layout.total_bytes <= vtcm_size) { kparams->kernel_type = HTP_IM2COL_KERNEL_PATCHEMBED_DMA; kparams->n_hvx = (uint8_t) n_hvx; kparams->vtcm_size = (uint32_t) layout.total_bytes; @@ -3266,7 +3832,6 @@ static bool htp_kparams_solve_im2col( kparams->OW = OW; kparams->patch_stride = patch_stride; kparams->total_rows = total_rows; - kparams->rows_per_chunk = rows_per_chunk; kparams->div_OH = init_fastdiv_values(OH); kparams->div_OD = init_fastdiv_values(1); return true; @@ -3300,7 +3865,7 @@ static bool htp_kparams_solve_im2col( htp_im2col_vtcm_layout_build(&layout, src_row_bytes, dst_row_bytes, blk_threads, htp_im2col_scratch_bytes(HTP_IM2COL_KERNEL_BLOCKED_DMA, KH, patch_stride)); - if (vtcm_size == 0 || layout.total_bytes <= vtcm_size) { + if (layout.total_bytes <= vtcm_size) { kparams->kernel_type = HTP_IM2COL_KERNEL_BLOCKED_DMA; kparams->n_hvx = (uint8_t) blk_threads; kparams->vtcm_size = (uint32_t) layout.total_bytes; @@ -3322,7 +3887,6 @@ static bool htp_kparams_solve_im2col( kparams->OW = OW; kparams->patch_stride = patch_stride; kparams->total_rows = total_rows; - kparams->rows_per_chunk = rows_per_chunk; kparams->div_OH = init_fastdiv_values(OH); kparams->div_OD = init_fastdiv_values(1); kparams->div_nbpr = init_fastdiv_values(nbpr); @@ -3413,11 +3977,9 @@ static bool htp_kparams_solve_im2col_3d( p0 == 0 && p1 == 0 && p2 == 0 && d0 == 1 && d1 == 1 && d2 == 1); - const uint32_t max_hvx = (sess && htp_session_n_hvx(sess) > 0) ? htp_session_n_hvx(sess) : 8; + const uint32_t max_hvx = htp_session_n_hvx(sess); const uint32_t n_hvx = (total_rows < max_hvx) ? total_rows : max_hvx; - const uint32_t vtcm_size = (sess && htp_session_vtcm_size(sess) > 0) ? (uint32_t) htp_session_vtcm_size(sess) : 0; - const uint32_t row_size = (uint32_t) dst->nb[2]; - const uint32_t rows_per_chunk = (row_size > 0) ? (HEX_L2_LINE_SIZE / hex_gcd_u32(row_size, HEX_L2_LINE_SIZE)) : 1; + const size_t vtcm_size = htp_session_vtcm_size(sess); if (is_patchembed) { const uint64_t src_row_bytes_raw = (uint64_t) IC * KD * KH * IW * sizeof(float); @@ -3429,7 +3991,7 @@ static bool htp_kparams_solve_im2col_3d( struct htp_im2col_vtcm_layout layout; htp_im2col_vtcm_layout_build(&layout, src_row_bytes, dst_row_bytes, n_hvx, 256); - if (vtcm_size == 0 || layout.total_bytes <= vtcm_size) { + if (layout.total_bytes <= vtcm_size) { kparams->kernel_type = HTP_IM2COL_KERNEL_PATCHEMBED_DMA; kparams->n_hvx = (uint8_t) n_hvx; kparams->vtcm_size = (uint32_t) layout.total_bytes; @@ -3451,7 +4013,6 @@ static bool htp_kparams_solve_im2col_3d( kparams->OW = OW; kparams->patch_stride = patch_stride; kparams->total_rows = total_rows; - kparams->rows_per_chunk = rows_per_chunk; kparams->div_OH = init_fastdiv_values(OH); kparams->div_OD = init_fastdiv_values(OD); return true; @@ -3479,7 +4040,7 @@ static bool htp_kparams_solve_im2col_3d( struct htp_im2col_vtcm_layout layout; htp_im2col_vtcm_layout_build(&layout, src_row_bytes, dst_row_bytes, n_hvx, 256); - if (vtcm_size == 0 || layout.total_bytes <= vtcm_size) { + if (layout.total_bytes <= vtcm_size) { kparams->kernel_type = HTP_IM2COL_KERNEL_BLOCKED_DMA; kparams->n_hvx = (uint8_t) n_hvx; kparams->vtcm_size = (uint32_t) layout.total_bytes; @@ -3501,7 +4062,6 @@ static bool htp_kparams_solve_im2col_3d( kparams->OW = OW; kparams->patch_stride = patch_stride; kparams->total_rows = total_rows; - kparams->rows_per_chunk = rows_per_chunk; kparams->div_OH = init_fastdiv_values(OH); kparams->div_OD = init_fastdiv_values(OD); return true; @@ -3522,7 +4082,7 @@ static bool htp_kparams_solve_pad( const struct ggml_tensor * src0 = op->src[0]; const struct ggml_tensor * dst = op; - if (src0->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) { + if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || dst->type != src0->type) { return false; } @@ -3535,32 +4095,41 @@ static bool htp_kparams_solve_pad( } const uint32_t type_size = (uint32_t) ggml_type_size(src0->type); - const uint32_t total_dst_rows = (uint32_t) (dst->ne[1] * dst->ne[2] * dst->ne[3]); - const uint32_t max_hvx = (std::max)(1u, total_dst_rows); - const uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx); - - struct htp_pad_vtcm_layout layout; - htp_pad_vtcm_layout_build(&layout, (uint32_t) src0->ne[0] * type_size, (uint32_t) dst->ne[0] * type_size, n_hvx); + if (src0->nb[0] != type_size || dst->nb[0] != type_size) { + return false; + } - const bool use_dma = (src0->nb[0] == type_size) && (src0->ne[0] >= 512) && - (htp_session_vtcm_size(sess) >= layout.total_bytes); + const uint32_t total_dst_rows = (uint32_t) ggml_nrows(dst); + const uint32_t max_hvx = (std::max)(1u, total_dst_rows); + uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx); + const size_t vtcm_size = htp_session_vtcm_size(sess); + const uint32_t elems_per_vec = 128u / type_size; + const uint32_t row_elems_aligned = (uint32_t) hex_round_up((std::max)(1u, (uint32_t) dst->ne[0]), elems_per_vec); - kparams->n_hvx = n_hvx; - kparams->total_rows = total_dst_rows; - kparams->use_dma = use_dma ? 1 : 0; - kparams->elem_size = type_size; - kparams->vtcm_size = use_dma ? (uint32_t) layout.total_bytes : 0; - - if (circular && use_dma) { - kparams->kernel_type = HTP_PAD_KERNEL_HVX_CIRCULAR_DMA; - } else if (circular) { - kparams->kernel_type = HTP_PAD_KERNEL_HVX_CIRCULAR; - } else if (use_dma) { - kparams->kernel_type = HTP_PAD_KERNEL_HVX_DMA; - } else { - kparams->kernel_type = HTP_PAD_KERNEL_HVX; + uint32_t chunk_elems = row_elems_aligned; + struct htp_pad_vtcm_layout layout; + while (true) { + const size_t max_chunk_bytes = (vtcm_size / (4 * n_hvx)) & ~(size_t) 127; + if (max_chunk_bytes >= 128) { + chunk_elems = (std::min)(row_elems_aligned, (uint32_t) (max_chunk_bytes / type_size)); + htp_pad_vtcm_layout_build(&layout, (size_t) chunk_elems * type_size, n_hvx); + if (layout.total_bytes <= vtcm_size) { + break; + } + } + if (n_hvx == 1) { + return false; + } + n_hvx--; } + kparams->n_hvx = n_hvx; + kparams->total_rows = total_dst_rows; + kparams->chunk_elems = chunk_elems; + kparams->elem_size = type_size; + kparams->vtcm_size = (uint32_t) layout.total_bytes; + kparams->kernel_type = circular ? HTP_PAD_KERNEL_HVX_CIRCULAR : HTP_PAD_KERNEL_HVX; + kparams->div_ne1 = init_fastdiv_values((uint32_t) dst->ne[1]); kparams->div_ne1_ne2 = init_fastdiv_values((uint32_t) (dst->ne[1] * dst->ne[2])); kparams->div_ne01 = init_fastdiv_values((uint32_t) src0->ne[1]); @@ -3580,26 +4149,44 @@ static bool htp_kparams_solve_cumsum( const struct ggml_tensor * src0 = op->src[0]; const struct ggml_tensor * dst = op; - if (src0->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) { + if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || + (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) { return false; } if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(dst)) { return false; } - const uint32_t total_rows = (uint32_t) (src0->ne[1] * src0->ne[2] * src0->ne[3]); - const uint32_t max_hvx = (std::max)(1u, total_rows); - const uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx); + const size_t src_elem_size = ggml_type_size(src0->type); + const size_t dst_elem_size = ggml_type_size(dst->type); + const uint32_t align_elems = (src0->type == GGML_TYPE_F16 || dst->type == GGML_TYPE_F16) ? 64u : 32u; + const uint32_t total_rows = (uint32_t) ggml_nrows(src0); + const uint32_t max_hvx = (std::max)(1u, total_rows); + uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx); + const size_t vtcm_size = htp_session_vtcm_size(sess); + const uint32_t row_elems_aligned = (uint32_t) hex_round_up((std::max)(1u, (uint32_t) src0->ne[0]), align_elems); + uint32_t chunk_elems = row_elems_aligned; struct htp_cumsum_vtcm_layout layout; - htp_cumsum_vtcm_layout_build(&layout, (uint32_t) src0->nb[1], (uint32_t) dst->nb[1], n_hvx); - - const bool use_dma = (htp_session_vtcm_size(sess) >= layout.total_bytes); + while (true) { + const size_t max_elems = (vtcm_size / (2 * n_hvx * (src_elem_size + dst_elem_size))) & ~(size_t) (align_elems - 1); + if (max_elems >= align_elems) { + chunk_elems = (std::min)(row_elems_aligned, (uint32_t) max_elems); + htp_cumsum_vtcm_layout_build(&layout, (size_t) chunk_elems * src_elem_size, (size_t) chunk_elems * dst_elem_size, n_hvx); + if (layout.total_bytes <= vtcm_size) { + break; + } + } + if (n_hvx == 1) { + return false; + } + n_hvx--; + } - kparams->n_hvx = n_hvx; - kparams->total_rows = total_rows; - kparams->use_dma = use_dma ? 1 : 0; - kparams->vtcm_size = use_dma ? (uint32_t) layout.total_bytes : 0; + kparams->n_hvx = n_hvx; + kparams->total_rows = total_rows; + kparams->chunk_elems = chunk_elems; + kparams->vtcm_size = (uint32_t) layout.total_bytes; return true; } @@ -3811,19 +4398,37 @@ static bool htp_kparams_solve_fill( const uint32_t ne1 = (uint32_t) dst->ne[1]; const uint32_t ne2 = (uint32_t) dst->ne[2]; const uint32_t ne3 = (uint32_t) dst->ne[3]; - const uint32_t nb1 = (uint32_t) dst->nb[1]; const uint32_t total_rows = ne1 * ne2 * ne3; const uint32_t max_hvx = (std::max)(1u, total_rows); - const uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx); + uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx); const uint32_t elem_size = (uint32_t) ggml_type_size(dst->type); - const uint32_t rows_per_chunk = (nb1 > 0) ? (HEX_L2_LINE_SIZE / hex_gcd_u32(nb1, HEX_L2_LINE_SIZE)) : 1; + const size_t vtcm_size = htp_session_vtcm_size(sess); + const bool is_contig = ggml_is_contiguous(dst); + const size_t row_bytes = (size_t) dst->ne[0] * elem_size; + const size_t max_bytes = is_contig ? ((size_t) ((total_rows + n_hvx - 1) / n_hvx) * row_bytes) : row_bytes; + size_t tile_bytes = (std::min)(16384u, hex_round_up((std::max)(128u, max_bytes), 128)); + + struct htp_fill_vtcm_layout L; + htp_fill_vtcm_layout_build(&L, tile_bytes, n_hvx); + while (L.total_bytes > vtcm_size && tile_bytes > 128) { + tile_bytes = (std::max)(128u, (tile_bytes / 2) & ~(size_t) 127); + htp_fill_vtcm_layout_build(&L, tile_bytes, n_hvx); + } + while (L.total_bytes > vtcm_size && n_hvx > 1) { + n_hvx--; + htp_fill_vtcm_layout_build(&L, tile_bytes, n_hvx); + } + if (L.total_bytes > vtcm_size) { + return false; + } kparams->n_hvx = n_hvx; kparams->total_rows = total_rows; kparams->elem_size = elem_size; - kparams->kernel_type = ggml_is_contiguous(dst) ? HTP_FILL_KERNEL_CONTIGUOUS : HTP_FILL_KERNEL_STRIDED; - kparams->rows_per_chunk = rows_per_chunk; + kparams->kernel_type = is_contig ? HTP_FILL_KERNEL_CONTIGUOUS : HTP_FILL_KERNEL_STRIDED; + kparams->tile_bytes = (uint32_t) L.tile_bytes; + kparams->vtcm_size = (uint32_t) L.total_bytes; kparams->div_ne1 = init_fastdiv_values(ne1); kparams->div_ne1_ne2 = init_fastdiv_values(ne1 * ne2); @@ -3928,7 +4533,7 @@ static bool htp_kparams_solve_roll( const struct ggml_tensor * src0 = op->src[0]; const struct ggml_tensor * dst = op; - if (src0->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) { + if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || dst->type != src0->type) { return false; } if (!ggml_are_same_shape(src0, dst)) { @@ -3938,6 +4543,7 @@ static bool htp_kparams_solve_roll( return false; } + const uint32_t elem_size = (uint32_t) ggml_type_size(src0->type); const uint32_t ne0 = (uint32_t) dst->ne[0]; const uint32_t ne1 = (uint32_t) dst->ne[1]; const uint32_t ne2 = (uint32_t) dst->ne[2]; @@ -3955,12 +4561,13 @@ static bool htp_kparams_solve_roll( const uint32_t total_rows = ne1 * ne2 * ne3; const uint32_t max_hvx = (std::max)(1u, total_rows); - const uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx); + uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx); + const size_t vtcm_size = htp_session_vtcm_size(sess); - kparams->n_hvx = n_hvx; kparams->total_rows = total_rows; kparams->i0_src0 = i0_src0; kparams->n0 = ne0 - i0_src0; + kparams->elem_size = elem_size; if (htp_session_mdev_count(sess) <= 1) { if (ggml_is_contiguous(src0) && ggml_is_contiguous(dst)) { @@ -3968,10 +4575,20 @@ static bool htp_kparams_solve_roll( } else { kparams->kernel_type = HTP_ROLL_KERNEL_DMA_STRIDED; } + kparams->vtcm_size = 0; } else { kparams->kernel_type = HTP_ROLL_KERNEL_HVX; + struct htp_roll_vtcm_layout L; + htp_roll_vtcm_layout_build(&L, (size_t) ne0 * elem_size, n_hvx); + while (L.total_bytes > vtcm_size && n_hvx > 1) { + n_hvx--; + htp_roll_vtcm_layout_build(&L, (size_t) ne0 * elem_size, n_hvx); + } + kparams->vtcm_size = (L.total_bytes <= vtcm_size) ? (uint32_t) L.total_bytes : 0; } + kparams->n_hvx = n_hvx; + kparams->div_ne1 = init_fastdiv_values(ne1); kparams->div_ne2_ne1 = init_fastdiv_values(ne2 * ne1); @@ -3988,7 +4605,7 @@ static bool htp_kparams_solve_diag( const struct ggml_tensor * src0 = op->src[0]; const struct ggml_tensor * dst = op; - if (src0->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) { + if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || dst->type != src0->type) { return false; } if (src0->ne[1] != 1 || dst->ne[0] != dst->ne[1] || dst->ne[0] != src0->ne[0]) { @@ -3999,39 +4616,37 @@ static bool htp_kparams_solve_diag( return false; } + const uint32_t elem_size = (uint32_t) ggml_type_size(src0->type); + const uint32_t elems_per_vec = 128u / elem_size; const uint32_t total_batches = (uint32_t) (src0->ne[2] * src0->ne[3]); const uint32_t max_hvx = (std::max)(1u, total_batches); const uint32_t n_hvx = (std::min)(htp_session_n_hvx(sess), max_hvx); - const uint32_t dst_batch_size = (uint32_t) (dst->ne[1] * dst->nb[1]); - - bool can_split = (dst->ne[0] == 1 || dst->nb[0] == sizeof(float)) && !ggml_is_permuted(dst); - uint32_t batches_per_chunk = 1; - if (can_split) { - if (dst->ne[2] > 1 && (dst->nb[2] & (HEX_L2_LINE_SIZE - 1)) == 0 && - (dst->ne[3] <= 1 || (dst->nb[3] & (HEX_L2_LINE_SIZE - 1)) == 0)) { - batches_per_chunk = 1; - } else if (dst->nb[2] == dst_batch_size && - (dst->ne[3] <= 1 || dst->nb[3] == dst->nb[2] * dst->ne[2])) { - batches_per_chunk = (dst_batch_size > 0) ? (HEX_L2_LINE_SIZE / hex_gcd_u32(dst_batch_size, HEX_L2_LINE_SIZE)) : 1; - } else { - can_split = false; - } - } - - const uint32_t src_batch_size = (uint32_t) (src0->ne[0] * sizeof(float)); - const uint32_t dst_row_size = (uint32_t) (dst->ne[0] * sizeof(float)); + const size_t vtcm_size = htp_session_vtcm_size(sess); + const uint32_t row_elems_aligned = (uint32_t) hex_round_up((std::max)(1u, (uint32_t) dst->ne[0]), elems_per_vec); + uint32_t diag_n_hvx = n_hvx; + uint32_t chunk_elems = row_elems_aligned; struct htp_diag_vtcm_layout layout; - htp_diag_vtcm_layout_build(&layout, src_batch_size, dst_row_size, n_hvx); - - const bool use_dma = (htp_session_vtcm_size(sess) >= layout.total_bytes); + while (true) { + const size_t per_hvx = vtcm_size / diag_n_hvx; + if (per_hvx >= 512) { + const size_t max_chunk_bytes = ((per_hvx - 256) / 2) & ~(size_t) 127; + chunk_elems = (std::min)(row_elems_aligned, (uint32_t) (max_chunk_bytes / elem_size)); + htp_diag_vtcm_layout_build(&layout, (size_t) chunk_elems * elem_size, diag_n_hvx); + if (layout.total_bytes <= vtcm_size) { + break; + } + } + if (diag_n_hvx == 1) { + return false; + } + diag_n_hvx--; + } - kparams->n_hvx = n_hvx; + kparams->n_hvx = diag_n_hvx; kparams->total_batches = total_batches; - kparams->use_dma = use_dma ? 1 : 0; - kparams->can_split = can_split ? 1 : 0; - kparams->batches_per_chunk = batches_per_chunk; - kparams->vtcm_size = use_dma ? (uint32_t) layout.total_bytes : 0; + kparams->chunk_elems = chunk_elems; + kparams->vtcm_size = (uint32_t) layout.total_bytes; kparams->div_ne02 = init_fastdiv_values((uint32_t) src0->ne[2]); return true; @@ -4048,7 +4663,9 @@ static bool htp_kparams_solve_solve_tri( const struct ggml_tensor * src1 = op->src[1]; const struct ggml_tensor * dst = op; - if (src0->type != GGML_TYPE_F32 || src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) { + if ((src0->type != GGML_TYPE_F32 && src0->type != GGML_TYPE_F16) || + (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) || + (dst->type != GGML_TYPE_F32 && dst->type != GGML_TYPE_F16)) { return false; } if (src0->ne[0] != src0->ne[1] || src0->ne[1] != src1->ne[1] || @@ -4056,8 +4673,14 @@ static bool htp_kparams_solve_solve_tri( !ggml_are_same_shape(src1, dst)) { return false; } + if (src0->nb[0] != ggml_type_size(src0->type) || + src1->nb[0] != ggml_type_size(src1->type) || + dst->nb[0] != ggml_type_size(dst->type)) { + return false; + } const uint32_t max_hvx_sess = htp_session_n_hvx(sess); + const uint32_t n = (uint32_t) src0->ne[0]; const uint32_t k = (uint32_t) src1->ne[0]; const uint32_t col_block = 32; const uint32_t k_chunks = (k + col_block - 1) / col_block; @@ -4065,9 +4688,23 @@ static bool htp_kparams_solve_solve_tri( const bool batched = total_batches >= max_hvx_sess; const uint32_t total_jobs = batched ? total_batches : (total_batches * k_chunks); const uint32_t max_hvx = (std::max)(1u, total_jobs); - const uint32_t n_hvx = (std::min)(max_hvx_sess, max_hvx); - const uint32_t batch_size = (uint32_t) dst->nb[2]; - const uint32_t batches_per_chunk = (batch_size > 0) ? (HEX_L2_LINE_SIZE / hex_gcd_u32(batch_size, HEX_L2_LINE_SIZE)) : 1; + uint32_t n_hvx = (std::min)(max_hvx_sess, max_hvx); + const size_t vtcm_size = htp_session_vtcm_size(sess); + + uint32_t a_full = 1; + struct htp_solve_tri_vtcm_layout L; + htp_solve_tri_vtcm_layout_build(&L, n, a_full, n_hvx); + if (L.total_bytes > vtcm_size) { + a_full = 0; + htp_solve_tri_vtcm_layout_build(&L, n, a_full, n_hvx); + while (L.total_bytes > vtcm_size && n_hvx > 1) { + n_hvx--; + htp_solve_tri_vtcm_layout_build(&L, n, a_full, n_hvx); + } + } + if (L.total_bytes > vtcm_size) { + return false; + } kparams->n_hvx = n_hvx; kparams->total_batches = total_batches; @@ -4075,7 +4712,8 @@ static bool htp_kparams_solve_solve_tri( kparams->k_chunks = k_chunks; kparams->col_block = col_block; kparams->batched = batched ? 1 : 0; - kparams->batches_per_chunk = batches_per_chunk; + kparams->a_full = a_full; + kparams->vtcm_size = (uint32_t) L.total_bytes; kparams->div_ne02 = init_fastdiv_values((uint32_t) src0->ne[2]); kparams->div_k_chunks = init_fastdiv_values(k_chunks > 0 ? k_chunks : 1); @@ -4570,7 +5208,7 @@ static bool htp_kparams_solve_conv2d_unchecked( ) { memset(kparams, 0, sizeof(*kparams)); - const uint32_t total_rows = (uint32_t) (dst->ne[1] * dst->ne[2] * dst->ne[3]); + const uint32_t total_rows = (uint32_t) ggml_nrows(dst); kparams->total_rows = total_rows; kparams->n_hvx = total_rows == 0 ? 1 : (std::min)((uint32_t) htp_session_n_hvx(sess), total_rows); @@ -4710,10 +5348,7 @@ static bool htp_kparams_solve_conv2d_dw( const uint32_t pad_rows = fast_k3x3 ? 4 : 0; const uint32_t pad_top_stride = fast_k3x3 ? w : 0; - const size_t vtcm_budget = (sess && htp_session_vtcm_size(sess) > 0) ? htp_session_vtcm_size(sess) : 0; - if (vtcm_budget == 0) { - return false; - } + const size_t vtcm_budget = htp_session_vtcm_size(sess); const uint32_t w_size = (uint32_t) (kw * kh * c * ggml_type_size(src0->type)); @@ -4823,14 +5458,11 @@ static bool htp_kparams_solve_conv3d( } } - const size_t es = ggml_type_size(src0->type); - const bool w_rows = src0->nb[0] == es && src0->nb[1] == src0->ne[0] * es && src0->nb[2] == src0->ne[1] * src0->nb[1] && - ((int64_t) IC * OC == 1 || src0->nb[3] == src0->ne[2] * src0->nb[2]); - if (!w_rows || src1->nb[0] != sizeof(float) || dst->nb[2] != dst->ne[1] * dst->nb[1]) { + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous_rows(src1) || dst->nb[2] != dst->ne[1] * dst->nb[1]) { return false; } - const int64_t total_rows = dst->ne[1] * dst->ne[2] * dst->ne[3]; + const int64_t total_rows = ggml_nrows(dst); if (total_rows > UINT32_MAX) { return false; } @@ -4840,90 +5472,6 @@ static bool htp_kparams_solve_conv3d( return htp_kparams_conv2d_tiled(sess, op, kparams); } -static bool htp_dsv4_hc_pre_can_collapse( - const struct ggml_tensor * x, - const struct ggml_tensor * weights, - const struct ggml_tensor * dst -) { - if (!x || !weights || !dst) { - return false; - } - if (x->type != GGML_TYPE_F32 || weights->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) { - return false; - } - if (x->nb[0] != sizeof(float) || weights->nb[0] != sizeof(float) || dst->nb[0] != sizeof(float)) { - return false; - } - if (x->ne[1] != 4 || dst->ne[0] != x->ne[0]) { - return false; - } - - const bool gated = ggml_get_op_params_i32(dst, 1) != 0; - const int64_t x_tokens = x->ne[2] * x->ne[3]; - const int64_t d_tokens = dst->ne[1] * dst->ne[2] * dst->ne[3]; - const int64_t w_tokens = gated ? (weights->ne[2] * weights->ne[3]) : (weights->ne[1] * weights->ne[2] * weights->ne[3]); - - if (x_tokens != d_tokens || x_tokens != w_tokens) { - return false; - } - - if (x->ne[3] == 1 && dst->ne[2] == 1 && dst->ne[3] == 1 && - (gated ? (weights->ne[3] == 1) : (weights->ne[2] == 1 && weights->ne[3] == 1))) { - return false; - } - - if (x->ne[3] > 1 && x->nb[3] != x->ne[2] * x->nb[2]) return false; - - if (dst->ne[2] > 1 && dst->nb[2] != dst->ne[1] * dst->nb[1]) return false; - if (dst->ne[3] > 1 && dst->nb[3] != dst->ne[2] * dst->nb[2]) return false; - - if (gated) { - if (weights->ne[3] > 1 && weights->nb[3] != weights->ne[2] * weights->nb[2]) return false; - } else { - if (weights->ne[2] > 1 && weights->nb[2] != weights->ne[1] * weights->nb[1]) return false; - if (weights->ne[3] > 1 && weights->nb[3] != weights->ne[2] * weights->nb[2]) return false; - } - - return true; -} - -static void htp_dsv4_hc_pre_collapse_tensors( - const struct ggml_tensor * x, - const struct ggml_tensor * weights, - const struct ggml_tensor * dst, - struct ggml_tensor * x_c, - struct ggml_tensor * w_c, - struct ggml_tensor * d_c -) { - const int64_t n_tokens = x->ne[2] * x->ne[3]; - const bool gated = ggml_get_op_params_i32(dst, 1) != 0; - - *x_c = *x; - x_c->ne[2] = n_tokens; - x_c->ne[3] = 1; - x_c->nb[3] = x_c->ne[2] * x_c->nb[2]; - - *d_c = *dst; - d_c->ne[1] = n_tokens; - d_c->ne[2] = 1; - d_c->ne[3] = 1; - d_c->nb[2] = d_c->ne[1] * d_c->nb[1]; - d_c->nb[3] = d_c->nb[2]; - - *w_c = *weights; - if (gated) { - w_c->ne[2] = n_tokens; - w_c->ne[3] = 1; - w_c->nb[3] = w_c->ne[2] * w_c->nb[2]; - } else { - w_c->ne[1] = n_tokens; - w_c->ne[2] = 1; - w_c->ne[3] = 1; - w_c->nb[2] = w_c->ne[1] * w_c->nb[1]; - w_c->nb[3] = w_c->nb[2]; - } -} - static bool htp_kparams_solve_dsv4_hc_pre_impl( const struct ggml_hexagon_session * sess, const struct ggml_tensor * x, @@ -4933,7 +5481,10 @@ static bool htp_kparams_solve_dsv4_hc_pre_impl( ) { memset(kparams, 0, sizeof(*kparams)); - if (x->type != GGML_TYPE_F32 || weights->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) { + const auto is_valid_type = [](const ggml_tensor * t) { + return (t->type == GGML_TYPE_F32 || t->type == GGML_TYPE_F16) && t->nb[0] == ggml_type_size(t->type); + }; + if (!is_valid_type(x) || !is_valid_type(weights) || !is_valid_type(dst)) { return false; } if (x->ne[1] != 4 || x->ne[3] != 1) { @@ -4945,9 +5496,6 @@ static bool htp_kparams_solve_dsv4_hc_pre_impl( if (dst->ne[0] != x->ne[0] || dst->ne[1] != x->ne[2] || dst->ne[2] != 1 || dst->ne[3] != 1) { return false; } - if (x->nb[0] != sizeof(float) || weights->nb[0] != sizeof(float) || dst->nb[0] != sizeof(float)) { - return false; - } if (ggml_is_permuted(x) || ggml_is_permuted(weights) || ggml_is_permuted(dst)) { return false; } @@ -4974,11 +5522,16 @@ static bool htp_kparams_solve_dsv4_hc_pre_impl( kparams->n_hvx = (std::min)(htp_session_n_hvx(sess), kparams->total_jobs); kparams->jobs_per_hvx = (kparams->total_jobs + kparams->n_hvx - 1) / kparams->n_hvx; + const uint32_t x_es = (uint32_t) ggml_type_size(x->type); + const uint32_t w_es = (uint32_t) ggml_type_size(weights->type); + const uint32_t dst_es = (uint32_t) ggml_type_size(dst->type); + const uint32_t max_es = gated ? std::max({ x_es, w_es, dst_es }) : std::max(x_es, dst_es); + const size_t vtcm_budget = htp_session_vtcm_size(sess); const uint32_t n_rows = gated ? HTP_DSV4_HC_PRE_GATED_ROWS : HTP_DSV4_HC_PRE_PLAIN_ROWS; uint32_t block_chunks = (std::min)((uint32_t) HTP_DSV4_HC_MAX_CHUNKS, kparams->n_chunks); while (block_chunks > 16) { - const uint32_t stride = block_chunks * 128; + const uint32_t stride = std::max(128, GGML_PAD(block_chunks * HTP_DSV4_HC_CHUNK_ELEMS * max_es, 128)); const uint32_t buf_sz = n_rows * stride; if (2 * buf_sz * kparams->n_hvx <= vtcm_budget) { break; @@ -4987,7 +5540,7 @@ static bool htp_kparams_solve_dsv4_hc_pre_impl( } kparams->dma_block_chunks = block_chunks; - kparams->dma_row_stride = block_chunks * 128; + kparams->dma_row_stride = std::max(128, GGML_PAD(block_chunks * HTP_DSV4_HC_CHUNK_ELEMS * max_es, 128)); kparams->dma_buffer_size = n_rows * kparams->dma_row_stride; kparams->vtcm_size = 2 * kparams->dma_buffer_size * kparams->n_hvx; if (kparams->vtcm_size > vtcm_budget) { @@ -5013,114 +5566,6 @@ static inline bool htp_kparams_solve_dsv4_hc_pre( return htp_kparams_solve_dsv4_hc_pre_impl(sess, op->src[0], op->src[1], op, kparams); } -static bool htp_dsv4_hc_post_can_collapse( - const struct ggml_tensor * x, - const struct ggml_tensor * residual, - const struct ggml_tensor * post, - const struct ggml_tensor * comb, - const struct ggml_tensor * dst -) { - if (!x || !residual || !post || !dst) { - return false; - } - if (x->type != GGML_TYPE_F32 || residual->type != GGML_TYPE_F32 || post->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) { - return false; - } - if (comb && comb->type != GGML_TYPE_F32) { - return false; - } - if (x->nb[0] != sizeof(float) || residual->nb[0] != sizeof(float) || post->nb[0] != sizeof(float) || dst->nb[0] != sizeof(float)) { - return false; - } - if (comb && comb->nb[0] != sizeof(float)) { - return false; - } - if (residual->ne[0] != x->ne[0] || residual->ne[1] != 4 || dst->ne[0] != x->ne[0] || dst->ne[1] != 4 || post->ne[0] != 4) { - return false; - } - if (comb && (comb->ne[0] != 4 || comb->ne[1] != 4)) { - return false; - } - - const int64_t x_tokens = x->ne[1] * x->ne[2] * x->ne[3]; - const int64_t r_tokens = residual->ne[2] * residual->ne[3]; - const int64_t p_tokens = post->ne[1] * post->ne[2] * post->ne[3]; - const int64_t d_tokens = dst->ne[2] * dst->ne[3]; - if (x_tokens != r_tokens || x_tokens != p_tokens || x_tokens != d_tokens) { - return false; - } - if (comb && (comb->ne[2] * comb->ne[3] != x_tokens)) { - return false; - } - - if (x->ne[2] == 1 && x->ne[3] == 1 && - residual->ne[3] == 1 && - post->ne[2] == 1 && post->ne[3] == 1 && - dst->ne[3] == 1 && - (!comb || comb->ne[3] == 1)) { - return false; - } - - if (x->ne[2] > 1 && x->nb[2] != x->ne[1] * x->nb[1]) return false; - if (x->ne[3] > 1 && x->nb[3] != x->ne[2] * x->nb[2]) return false; - - if (residual->ne[3] > 1 && residual->nb[3] != residual->ne[2] * residual->nb[2]) return false; - if (dst->ne[3] > 1 && dst->nb[3] != dst->ne[2] * dst->nb[2]) return false; - - if (post->ne[2] > 1 && post->nb[2] != post->ne[1] * post->nb[1]) return false; - if (post->ne[3] > 1 && post->nb[3] != post->ne[2] * post->nb[2]) return false; - - if (comb && comb->ne[3] > 1 && comb->nb[3] != comb->ne[2] * comb->nb[2]) return false; - - return true; -} - -static void htp_dsv4_hc_post_collapse_tensors( - const struct ggml_tensor * x, - const struct ggml_tensor * residual, - const struct ggml_tensor * post, - const struct ggml_tensor * comb, - const struct ggml_tensor * dst, - struct ggml_tensor * x_c, - struct ggml_tensor * r_c, - struct ggml_tensor * p_c, - struct ggml_tensor * c_c, - struct ggml_tensor * d_c -) { - const int64_t n_tokens = x->ne[1] * x->ne[2] * x->ne[3]; - - *x_c = *x; - x_c->ne[1] = n_tokens; - x_c->ne[2] = 1; - x_c->ne[3] = 1; - x_c->nb[2] = x_c->ne[1] * x_c->nb[1]; - x_c->nb[3] = x_c->nb[2]; - - *r_c = *residual; - r_c->ne[2] = n_tokens; - r_c->ne[3] = 1; - r_c->nb[3] = r_c->ne[2] * r_c->nb[2]; - - *d_c = *dst; - d_c->ne[2] = n_tokens; - d_c->ne[3] = 1; - d_c->nb[3] = d_c->ne[2] * d_c->nb[2]; - - *p_c = *post; - p_c->ne[1] = n_tokens; - p_c->ne[2] = 1; - p_c->ne[3] = 1; - p_c->nb[2] = p_c->ne[1] * p_c->nb[1]; - p_c->nb[3] = p_c->nb[2]; - - if (comb && c_c) { - *c_c = *comb; - c_c->ne[2] = n_tokens; - c_c->ne[3] = 1; - c_c->nb[3] = c_c->ne[2] * c_c->nb[2]; - } -} - static bool htp_kparams_solve_dsv4_hc_post_impl( const struct ggml_hexagon_session * sess, const struct ggml_tensor * x, @@ -5132,10 +5577,13 @@ static bool htp_kparams_solve_dsv4_hc_post_impl( ) { memset(kparams, 0, sizeof(*kparams)); - if (x->type != GGML_TYPE_F32 || residual->type != GGML_TYPE_F32 || post->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) { + const auto is_valid_type = [](const ggml_tensor * t) { + return (t->type == GGML_TYPE_F32 || t->type == GGML_TYPE_F16) && t->nb[0] == ggml_type_size(t->type); + }; + if (!is_valid_type(x) || !is_valid_type(residual) || !is_valid_type(post) || !is_valid_type(dst)) { return false; } - if (comb && comb->type != GGML_TYPE_F32) { + if (comb && !is_valid_type(comb)) { return false; } if (x->ne[2] != 1 || x->ne[3] != 1) { @@ -5156,12 +5604,6 @@ static bool htp_kparams_solve_dsv4_hc_post_impl( if (dst->ne[0] != x->ne[0] || dst->ne[1] != 4 || dst->ne[2] != x->ne[1] || dst->ne[3] != 1) { return false; } - if (x->nb[0] != sizeof(float) || residual->nb[0] != sizeof(float) || post->nb[0] != sizeof(float) || dst->nb[0] != sizeof(float)) { - return false; - } - if (comb && comb->nb[0] != sizeof(float)) { - return false; - } if (ggml_is_permuted(x) || ggml_is_permuted(residual) || ggml_is_permuted(post) || ggml_is_permuted(dst) || (comb && ggml_is_permuted(comb))) { return false; } @@ -5178,10 +5620,15 @@ static bool htp_kparams_solve_dsv4_hc_post_impl( kparams->n_hvx = (std::min)(htp_session_n_hvx(sess), kparams->total_jobs); kparams->jobs_per_hvx = (kparams->total_jobs + kparams->n_hvx - 1) / kparams->n_hvx; + const uint32_t x_es = (uint32_t) ggml_type_size(x->type); + const uint32_t r_es = (uint32_t) ggml_type_size(residual->type); + const uint32_t dst_es = (uint32_t) ggml_type_size(dst->type); + const uint32_t max_es = std::max({ x_es, r_es, dst_es }); + const size_t vtcm_budget = htp_session_vtcm_size(sess); uint32_t block_chunks = (std::min)((uint32_t) HTP_DSV4_HC_MAX_CHUNKS, kparams->n_chunks); while (block_chunks > 16) { - const uint32_t stride = block_chunks * 128; + const uint32_t stride = std::max(256, GGML_PAD(block_chunks * HTP_DSV4_HC_CHUNK_ELEMS * max_es, 128)); const uint32_t buf_sz = HTP_DSV4_HC_POST_ROWS * stride; if (2 * buf_sz * kparams->n_hvx <= vtcm_budget) { break; @@ -5190,7 +5637,7 @@ static bool htp_kparams_solve_dsv4_hc_post_impl( } kparams->dma_block_chunks = block_chunks; - kparams->dma_row_stride = block_chunks * 128; + kparams->dma_row_stride = std::max(256, GGML_PAD(block_chunks * HTP_DSV4_HC_CHUNK_ELEMS * max_es, 128)); kparams->dma_buffer_size = HTP_DSV4_HC_POST_ROWS * kparams->dma_row_stride; kparams->vtcm_size = 2 * kparams->dma_buffer_size * kparams->n_hvx; if (kparams->vtcm_size > vtcm_budget) { @@ -5216,92 +5663,6 @@ static inline bool htp_kparams_solve_dsv4_hc_post( return htp_kparams_solve_dsv4_hc_post_impl(sess, op->src[0], op->src[1], op->src[2], op->src[3], op, kparams); } -static bool htp_lightning_indexer_can_collapse( - const struct ggml_tensor * q, - const struct ggml_tensor * k, - const struct ggml_tensor * w, - const struct ggml_tensor * m, - const struct ggml_tensor * dst -) { - if (!q || !k || !w || !m || !dst) { - return false; - } - - // 2D K normalization: ne[1] is n_kv, ne[2] is 1 - const bool can_collapse_k = (k->ne[1] > 1 && k->ne[2] == 1); - - // Stream-to-token collapse across q, w, dst (and m) - bool can_collapse_stream = false; - if (q->ne[3] > 1 && k->ne[3] == 1) { - const bool q_ok = (q->nb[3] == (size_t) q->ne[2] * q->nb[2]); - const bool dst_ok = (dst->ne[3] == q->ne[3] && dst->ne[2] == 1 && dst->ne[1] == q->ne[2] && - dst->nb[3] == (size_t) dst->ne[1] * dst->nb[1]); - const bool w_ok = (w->ne[3] == q->ne[3] && w->ne[2] == 1 && w->ne[1] == q->ne[2] && - w->nb[3] == (size_t) w->ne[1] * w->nb[1]) || - (w->ne[3] == 1 && w->ne[1] == q->ne[2] * q->ne[3]); - const bool m_ok = (m->ne[3] == q->ne[3] && m->ne[2] == 1 && m->ne[1] == q->ne[2] && - m->nb[3] == (size_t) m->ne[1] * m->nb[1]) || - (m->ne[3] == 1 && m->ne[1] == q->ne[2] * q->ne[3]); - can_collapse_stream = q_ok && dst_ok && w_ok && m_ok; - } - - return can_collapse_k || can_collapse_stream; -} - -static void htp_lightning_indexer_collapse_tensors( - const struct ggml_tensor * q, - const struct ggml_tensor * k, - const struct ggml_tensor * w, - const struct ggml_tensor * m, - const struct ggml_tensor * dst, - struct ggml_tensor * q_c, - struct ggml_tensor * k_c, - struct ggml_tensor * w_c, - struct ggml_tensor * m_c, - struct ggml_tensor * dst_c -) { - *q_c = *q; - *k_c = *k; - *w_c = *w; - *m_c = *m; - *dst_c = *dst; - - if (k->ne[1] > 1 && k->ne[2] == 1) { - k_c->ne[2] = k->ne[1]; - k_c->ne[1] = 1; - k_c->nb[1] = k->nb[1]; - k_c->nb[2] = k->nb[1]; - k_c->nb[3] = k->nb[2]; - } - - if (q->ne[3] > 1 && k->ne[3] == 1) { - const int64_t n_tokens_collapsed = (int64_t) q->ne[2] * q->ne[3]; - - q_c->ne[2] = n_tokens_collapsed; - q_c->ne[3] = 1; - q_c->nb[3] = (size_t) q_c->ne[2] * q_c->nb[2]; - - if (w->ne[3] == q->ne[3]) { - w_c->ne[1] = n_tokens_collapsed; - w_c->ne[3] = 1; - w_c->nb[2] = (size_t) w_c->ne[1] * w_c->nb[1]; - w_c->nb[3] = w_c->nb[2]; - } - - dst_c->ne[1] = n_tokens_collapsed; - dst_c->ne[3] = 1; - dst_c->nb[2] = (size_t) dst_c->ne[1] * dst_c->nb[1]; - dst_c->nb[3] = dst_c->nb[2]; - - if (m->ne[3] == q->ne[3] && m->ne[1] == q->ne[2]) { - m_c->ne[1] = n_tokens_collapsed; - m_c->ne[3] = 1; - m_c->nb[2] = (size_t) m_c->ne[1] * m_c->nb[1]; - m_c->nb[3] = m_c->nb[2]; - } - } -} - static bool htp_kparams_solve_lightning_indexer_impl( const struct ggml_hexagon_session * sess, const struct ggml_tensor * q, @@ -5315,7 +5676,11 @@ static bool htp_kparams_solve_lightning_indexer_impl( return false; } - if (k->type != GGML_TYPE_F32 && k->type != GGML_TYPE_F16 && k->type != GGML_TYPE_Q8_0 && k->type != GGML_TYPE_Q4_0) { + if ((q->type != GGML_TYPE_F32 && q->type != GGML_TYPE_F16) || + (k->type != GGML_TYPE_F32 && k->type != GGML_TYPE_F16 && k->type != GGML_TYPE_Q8_0 && k->type != GGML_TYPE_Q4_0) || + (w->type != GGML_TYPE_F32 && w->type != GGML_TYPE_F16) || + m->type != GGML_TYPE_F16 || + op->type != GGML_TYPE_F32) { return false; } @@ -5365,7 +5730,7 @@ static bool htp_kparams_solve_lightning_indexer_impl( while (nt2 > 32 && vtcm_usage(nt2, 64, 2) > htp_session_vtcm_size(sess)) { nt2 /= 2; } - const size_t q_bytes = (size_t) nt2 * n_head * D * sizeof(float); + const size_t q_bytes = (size_t) nt2 * n_head * ggml_row_size(q->type, D); const size_t k_bytes = (size_t) k->ne[2] * ggml_row_size(k->type, D); if (vtcm_usage(nt2, 64, 2) <= htp_session_vtcm_size(sess) && q_bytes >= k_bytes) { n_tok = nt2; @@ -5454,217 +5819,207 @@ static inline bool htp_kparams_invoke( return SolveFn(sess, op, kparams ? (KParams *) kparams : &tmp); } -void htp_opnode_collapse(const struct ggml_hexagon_session * sess, htp_opnode & node) { - const uint32_t n_hvx = htp_session_n_hvx(sess); +bool htp_kparams_solve( + const struct ggml_hexagon_session * sess, + htp_opnode & node +) { + ggml_tensor scratch[HTP_OP_MAX_INPUTS + HTP_OP_MAX_OUTPUTS]; + htp_opnode tmp = node; + htp_lower_opnode(sess, tmp, scratch); - if (htp_op_is_unary(node.opcode) && htp_unary_is_elementwise(node.opcode)) { - if (node.inputs.empty() || !node.inputs[0] || node.outputs.empty() || !node.outputs[0]) { - return; - } - if (!ggml_are_same_shape(node.inputs[0], node.outputs[0])) { - return; - } - const size_t elem_size = ggml_type_size(node.inputs[0]->type); - struct ggml_tensor src0_c = *node.inputs[0]; - struct ggml_tensor dst_c = *node.outputs[0]; - struct ggml_tensor * tensors[2] = { &src0_c, &dst_c }; - htp_collapse_dims(tensors, 2, elem_size, n_hvx); - if (src0_c.ne[0] != node.inputs[0]->ne[0] || src0_c.ne[1] != node.inputs[0]->ne[1]) { - node.inputs[0] = node.add_dummy(src0_c); - node.outputs[0] = node.add_dummy(dst_c); - } - return; - } + const ggml_tensor * src0 = tmp.inputs.empty() ? nullptr : tmp.inputs[0]; + const ggml_tensor * src1 = tmp.inputs.size() > 1 ? tmp.inputs[1] : nullptr; + const ggml_tensor * dst = tmp.dst(); - if (htp_op_is_glu(node.opcode)) { - if (node.inputs.size() < 2 || !node.inputs[0] || !node.inputs[1] || node.outputs.empty() || !node.outputs[0]) { - return; - } - if (!ggml_are_same_shape(node.inputs[0], node.outputs[0]) || - !ggml_are_same_shape(node.inputs[1], node.outputs[0])) { - return; + auto commit = [&](bool ok) { + if (ok) { + memcpy(node.kernel_params, tmp.kernel_params, sizeof(node.kernel_params)); } - const size_t elem_size = ggml_type_size(node.inputs[0]->type); - struct ggml_tensor src0_c = *node.inputs[0]; - struct ggml_tensor src1_c = *node.inputs[1]; - struct ggml_tensor dst_c = *node.outputs[0]; - struct ggml_tensor * tensors[3] = { &src0_c, &src1_c, &dst_c }; - htp_collapse_dims(tensors, 3, elem_size, n_hvx); - if (src0_c.ne[0] != node.inputs[0]->ne[0] || src0_c.ne[1] != node.inputs[0]->ne[1]) { - node.inputs[0] = node.add_dummy(src0_c); - node.inputs[1] = node.add_dummy(src1_c); - node.outputs[0] = node.add_dummy(dst_c); + return ok; + }; + + if (htp_op_is_unary(tmp.opcode)) { + auto * kp = tmp.kparams(); + const uint32_t has_scale_bias = kp->has_scale_bias; + const float in_scale = kp->in_scale; + const float in_bias = kp->in_bias; + const float out_scale = kp->out_scale; + const float out_bias = kp->out_bias; + const ggml_tensor * src2 = tmp.inputs.size() > 2 ? tmp.inputs[2] : nullptr; + const bool ok = htp_kparams_solve_unary_impl(sess, tmp.opcode, src0, src1, src2, dst, kp); + if (has_scale_bias) { + kp->has_scale_bias = has_scale_bias; + kp->in_scale = in_scale; + kp->in_bias = in_bias; + kp->out_scale = out_scale; + kp->out_bias = out_bias; + } + return commit(ok); + } + if (htp_op_is_glu(tmp.opcode)) { + return commit(htp_kparams_solve_unary_mul_glu(sess, tmp.opcode, src0, src1, dst, tmp.kparams())); + } + if (tmp.opcode == HTP_OP_MUL_MAT || tmp.opcode == HTP_OP_MUL_MAT_ID) { + if (!htp_matmul_check_types(src0, src1, dst)) { + return false; } - return; + return commit(htp_kparams_solve_matmul_impl(sess, src0, src1, nullptr, dst, tmp.kparams())); } - - if (node.opcode == HTP_OP_MUL_MAT) { - if (node.inputs.size() < 2 || !node.inputs[0] || !node.inputs[1] || node.outputs.empty() || !node.outputs[0]) { - return; + if (tmp.opcode == HTP_OP_MUL_MAT_ADD) { + if (tmp.inputs.size() != 3) { + return false; } - const struct ggml_tensor * src0 = node.inputs[0]; - const struct ggml_tensor * src1 = node.inputs[1]; - const struct ggml_tensor * dst = node.outputs[0]; - if (htp_matmul_can_collapse(src0, src1, dst)) { - node.inputs[1] = node.add_dummy(htp_tensor_collapse_rows(src1)); - node.outputs[0] = node.add_dummy(htp_tensor_collapse_rows(dst)); + const ggml_tensor * bias = tmp.inputs[2]; + if ((bias->type != GGML_TYPE_F32 && bias->type != GGML_TYPE_F16) || + bias->nb[0] != ggml_type_size(bias->type) || + !htp_matmul_check_types(src0, src1, dst)) { + return false; } - return; + return commit(htp_kparams_solve_matmul_impl(sess, src0, src1, bias, dst, tmp.kparams())); } - - if (node.opcode == HTP_OP_MUL_MAT_ADD) { - if (node.inputs.size() < 2 || !node.inputs[0] || !node.inputs[1] || node.outputs.empty() || !node.outputs[0]) { - return; + if (tmp.opcode == HTP_OP_MUL_MAT_NX) { + const size_t n_w = tmp.outputs.size(); + if (n_w == 0 || tmp.inputs.size() != n_w + 1) { + return false; } - const struct ggml_tensor * src0 = node.inputs[0]; - const struct ggml_tensor * src1 = node.inputs[1]; - const struct ggml_tensor * src2 = node.inputs.size() > 2 ? node.inputs[2] : nullptr; - const struct ggml_tensor * dst = node.outputs[0]; - if (htp_matmul_add_can_collapse(src0, src1, src2, dst)) { - node.inputs[1] = node.add_dummy(htp_tensor_collapse_rows(src1)); - node.outputs[0] = node.add_dummy(htp_tensor_collapse_rows(dst)); - if (src2 && (src2->ne[1] * src2->ne[2] * src2->ne[3] > 1)) { - node.inputs[2] = node.add_dummy(htp_tensor_collapse_rows(src2)); + const ggml_tensor * act = tmp.inputs[n_w]; + const ggml_tensor * w_for_solve = tmp.inputs[0]; + const ggml_tensor * dst_for_solve = tmp.outputs[0]; + ggml_type max_dst_type = tmp.outputs[0]->type; + for (size_t i = 0; i < n_w; ++i) { + if (!htp_matmul_check_types(tmp.inputs[i], act, tmp.outputs[i])) { + return false; + } + if (tmp.inputs[i]->ne[1] > w_for_solve->ne[1]) { + w_for_solve = tmp.inputs[i]; + } + if (ggml_type_size(tmp.outputs[i]->type) > ggml_type_size(max_dst_type)) { + max_dst_type = tmp.outputs[i]->type; } } - return; - } - - if (node.opcode == HTP_OP_UPSCALE) { - if (node.inputs.empty() || !node.inputs[0] || node.outputs.empty() || !node.outputs[0]) { - return; - } - const struct ggml_tensor * src0 = node.inputs[0]; - const struct ggml_tensor * dst = node.outputs[0]; - - if ((src0->ne[3] > 1 || dst->ne[3] > 1) && - src0->ne[2] == dst->ne[2] && src0->ne[3] == dst->ne[3] && - src0->nb[3] == (size_t) src0->ne[2] * src0->nb[2] && - dst->nb[3] == (size_t) dst->ne[2] * dst->nb[2]) { - struct ggml_tensor src0_c = *src0; - struct ggml_tensor dst_c = *dst; - src0_c.ne[2] *= src0_c.ne[3]; - src0_c.ne[3] = 1; - src0_c.nb[3] = (size_t) src0_c.ne[2] * src0_c.nb[2]; - dst_c.ne[2] *= dst_c.ne[3]; - dst_c.ne[3] = 1; - dst_c.nb[3] = (size_t) dst_c.ne[2] * dst_c.nb[2]; - node.inputs[0] = node.add_dummy(src0_c); - node.outputs[0] = node.add_dummy(dst_c); + ggml_tensor d_for_solve = *dst_for_solve; + d_for_solve.type = max_dst_type; + if (!htp_kparams_solve_mmnx(sess, w_for_solve, act, &d_for_solve, (int32_t) n_w, tmp.kparams())) { + return false; } - return; + const auto * kp = tmp.kparams(); + const bool ok = kp->n_hmx ? htp_mm_kernel_is_hmx_2d(kp->kernel_type) + : (ggml_hexagon_tensor_is_tiled(tmp.inputs[0]) && + (kp->kernel_type == HTP_MM_KERNEL_HVX_QUANT_ROW || kp->kernel_type == HTP_MM_KERNEL_HVX_QUANT_BLOCK)); + return commit(ok); } - - if (node.opcode == HTP_OP_DSV4_HC_PRE) { - if (node.inputs.size() < 2 || !node.inputs[0] || !node.inputs[1] || node.outputs.empty() || !node.outputs[0]) { - return; - } - const struct ggml_tensor * x = node.inputs[0]; - const struct ggml_tensor * weights = node.inputs[1]; - const struct ggml_tensor * dst = node.outputs[0]; - - if (htp_dsv4_hc_pre_can_collapse(x, weights, dst)) { - struct ggml_tensor x_c, w_c, d_c; - htp_dsv4_hc_pre_collapse_tensors(x, weights, dst, &x_c, &w_c, &d_c); - node.inputs[0] = node.add_dummy(x_c); - node.inputs[1] = node.add_dummy(w_c); - node.outputs[0] = node.add_dummy(d_c); + if (tmp.opcode == HTP_OP_MUL_MAT_NX_GLU) { + if (tmp.inputs.size() != 3 || tmp.outputs.size() != 1) { + return false; } - return; + const uint8_t glu_op = tmp.kparams()->glu_op; + return commit(htp_kparams_solve_mmnx_glu(sess, tmp.inputs[0], tmp.inputs[1], tmp.inputs[2], tmp.outputs[0], glu_op, tmp.kparams())); } - - if (node.opcode == HTP_OP_DSV4_HC_POST) { - if (node.inputs.size() < 3 || !node.inputs[0] || !node.inputs[1] || !node.inputs[2] || node.outputs.empty() || !node.outputs[0]) { - return; + if (tmp.opcode == HTP_OP_MUL_MAT_ID_NX) { + const size_t n_w = tmp.outputs.size(); + if (n_w == 0 || tmp.inputs.size() != n_w + 2) { + return false; } - const struct ggml_tensor * x = node.inputs[0]; - const struct ggml_tensor * residual = node.inputs[1]; - const struct ggml_tensor * post = node.inputs[2]; - const struct ggml_tensor * comb = node.inputs.size() > 3 ? node.inputs[3] : nullptr; - const struct ggml_tensor * dst = node.outputs[0]; - - if (htp_dsv4_hc_post_can_collapse(x, residual, post, comb, dst)) { - struct ggml_tensor x_c, r_c, p_c, c_c, d_c; - htp_dsv4_hc_post_collapse_tensors(x, residual, post, comb, dst, &x_c, &r_c, &p_c, comb ? &c_c : nullptr, &d_c); - node.inputs[0] = node.add_dummy(x_c); - node.inputs[1] = node.add_dummy(r_c); - node.inputs[2] = node.add_dummy(p_c); - if (comb) { - node.inputs[3] = node.add_dummy(c_c); + const ggml_tensor * act = tmp.inputs[n_w]; + const ggml_tensor * w_for_solve = tmp.inputs[0]; + const ggml_tensor * dst_for_solve = tmp.outputs[0]; + ggml_type max_dst_type = tmp.outputs[0]->type; + for (size_t i = 0; i < n_w; ++i) { + if (!htp_matmul_check_types(tmp.inputs[i], act, tmp.outputs[i])) { + return false; + } + if (tmp.inputs[i]->ne[1] > w_for_solve->ne[1]) { + w_for_solve = tmp.inputs[i]; + } + if (ggml_type_size(tmp.outputs[i]->type) > ggml_type_size(max_dst_type)) { + max_dst_type = tmp.outputs[i]->type; } - node.outputs[0] = node.add_dummy(d_c); } - return; - } - - if (node.opcode == HTP_OP_LIGHTNING_INDEXER) { - if (node.inputs.size() < 4 || !node.inputs[0] || !node.inputs[1] || !node.inputs[2] || !node.inputs[3] || node.outputs.empty() || !node.outputs[0]) { - return; + ggml_tensor d_for_solve = *dst_for_solve; + d_for_solve.type = max_dst_type; + if (!htp_kparams_solve_mmidnx(sess, w_for_solve, act, &d_for_solve, (int32_t) n_w, tmp.kparams())) { + return false; + } + const auto * kp = tmp.kparams(); + const bool ok = kp->n_hmx ? htp_mm_kernel_is_hmx_2d(kp->kernel_type) + : (ggml_hexagon_tensor_is_tiled(tmp.inputs[0]) && + (kp->kernel_type == HTP_MM_KERNEL_HVX_QUANT_ROW || kp->kernel_type == HTP_MM_KERNEL_HVX_QUANT_BLOCK)); + return commit(ok); + } + if (tmp.opcode == HTP_OP_UPSCALE) { + return commit(htp_kparams_solve_upscale(sess, src0, dst, tmp.kparams())); + } + if (tmp.opcode == HTP_OP_DSV4_HC_PRE) { + return commit(htp_kparams_solve_dsv4_hc_pre_impl(sess, src0, src1, dst, tmp.kparams())); + } + if (tmp.opcode == HTP_OP_DSV4_HC_POST) { + const ggml_tensor * src2 = tmp.inputs.size() > 2 ? tmp.inputs[2] : nullptr; + const ggml_tensor * src3 = tmp.inputs.size() > 3 ? tmp.inputs[3] : nullptr; + return commit(htp_kparams_solve_dsv4_hc_post_impl(sess, src0, src1, src2, src3, dst, tmp.kparams())); + } + if (tmp.opcode == HTP_OP_LIGHTNING_INDEXER) { + const ggml_tensor * src2 = tmp.inputs.size() > 2 ? tmp.inputs[2] : nullptr; + const ggml_tensor * src3 = tmp.inputs.size() > 3 ? tmp.inputs[3] : nullptr; + return commit(htp_kparams_solve_lightning_indexer_impl(sess, src0, src1, src2, src3, dst, tmp.kparams())); + } + if (tmp.opcode == HTP_OP_GET_ROWS) { + return commit(htp_kparams_solve_repeat_get_rows(sess, src0, src1, dst, tmp.kparams())); + } + if (tmp.opcode == HTP_OP_SSM_CONV) { + auto * kp = tmp.kparams(); + const uint32_t silu = kp->silu; + bool ok = false; + if (tmp.inputs.size() == 3 && !tmp.outputs.empty() && tmp.outputs.size() <= 2) { + const ggml_tensor * dst_state = (tmp.outputs.size() == 2) ? tmp.outputs[1] : nullptr; + ok = htp_kparams_solve_ssm_conv_token_major(sess, src0, src1, tmp.inputs[2], tmp.outputs[0], dst_state, kp); + } else if (tmp.inputs.size() == 2 && tmp.outputs.size() == 1) { + ok = htp_kparams_solve_ssm_conv(sess, src0, src1, dst, kp); + } + kp->silu = silu; + return commit(ok); + } + if (tmp.opcode == HTP_OP_GATED_DELTA_NET) { + if ((tmp.inputs.size() != 6 && tmp.inputs.size() != 7 && tmp.inputs.size() != 10) || + tmp.outputs.empty() || tmp.outputs.size() > 2) { + return false; } - const struct ggml_tensor * q = node.inputs[0]; - const struct ggml_tensor * k = node.inputs[1]; - const struct ggml_tensor * w = node.inputs[2]; - const struct ggml_tensor * m = node.inputs[3]; - const struct ggml_tensor * dst = node.outputs[0]; - - if (htp_lightning_indexer_can_collapse(q, k, w, m, dst)) { - struct ggml_tensor q_c, k_c, w_c, m_c, d_c; - htp_lightning_indexer_collapse_tensors(q, k, w, m, dst, &q_c, &k_c, &w_c, &m_c, &d_c); - node.inputs[0] = node.add_dummy(q_c); - node.inputs[1] = node.add_dummy(k_c); - node.inputs[2] = node.add_dummy(w_c); - node.inputs[3] = node.add_dummy(m_c); - node.outputs[0] = node.add_dummy(d_c); + ggml_tensor op_view = *tmp.outputs[0]; + op_view.op = tmp.node->op; + op_view.flags = tmp.node->flags; + memcpy(op_view.op_params, tmp.params, sizeof(op_view.op_params)); + for (size_t i = 6; i < GGML_MAX_SRC; ++i) { + op_view.src[i] = nullptr; } - return; + for (size_t i = 0; i < tmp.inputs.size(); ++i) { + op_view.src[i] = const_cast(tmp.inputs[i]); + } + const ggml_tensor * dst_cache = (tmp.outputs.size() == 2) ? tmp.outputs[1] : nullptr; + return commit(htp_kparams_solve_gated_delta_net(sess, &op_view, dst_cache, tmp.kparams())); } -} - -bool htp_kparams_solve( - const struct ggml_hexagon_session * sess, - htp_opnode & node -) { - htp_opnode_collapse(sess, node); - - const ggml_tensor * src0 = node.inputs.empty() ? nullptr : node.inputs[0]; - const ggml_tensor * src1 = node.inputs.size() > 1 ? node.inputs[1] : nullptr; - const ggml_tensor * dst = node.dst(); - if (htp_op_is_unary(node.opcode)) { - return htp_kparams_solve_unary_impl(sess, node.opcode, src0, src1, dst, node.kparams()); - } - if (htp_op_is_glu(node.opcode)) { - return htp_kparams_solve_unary_mul_glu(sess, node.opcode, src0, src1, dst, node.kparams()); - } - if (node.opcode == HTP_OP_MUL_MAT) { - if (!htp_matmul_check_types(src0, src1, dst)) { - return false; + if (!tmp.fused.empty() && + (tmp.opcode == HTP_OP_ADD || tmp.opcode == HTP_OP_SUB || + tmp.opcode == HTP_OP_MUL || tmp.opcode == HTP_OP_DIV)) { + auto * kp = tmp.kparams(); + if (kp->kernel_type != HTP_BINARY_KERNEL_SCALAR && kp->n_srcs > 2 && + tmp.inputs.size() == kp->n_srcs && tmp.outputs.size() == 1) { + return commit(htp_kparams_solve_binary_nx(sess, tmp, kp)); } - return htp_kparams_solve_matmul_impl(sess, src0, src1, dst, 0, 0, node.kparams()); - } - if (node.opcode == HTP_OP_MUL_MAT_ADD) { - const ggml_tensor * src2 = node.inputs.size() > 2 ? node.inputs[2] : nullptr; - const size_t src2_size = src2 ? hex_round_up(ggml_nbytes(src2), 128) : 0; - return htp_kparams_solve_matmul_impl(sess, src0, src1, dst, src2 ? src2->nb[1] : 0, src2_size, node.kparams()); - } - if (node.opcode == HTP_OP_UPSCALE) { - return htp_kparams_solve_upscale(sess, src0, dst, node.kparams()); } - if (node.opcode == HTP_OP_DSV4_HC_PRE) { - return htp_kparams_solve_dsv4_hc_pre_impl(sess, src0, src1, dst, node.kparams()); - } - if (node.opcode == HTP_OP_DSV4_HC_POST) { - const ggml_tensor * src2 = node.inputs.size() > 2 ? node.inputs[2] : nullptr; - const ggml_tensor * src3 = node.inputs.size() > 3 ? node.inputs[3] : nullptr; - return htp_kparams_solve_dsv4_hc_post_impl(sess, src0, src1, src2, src3, dst, node.kparams()); + + if (!tmp.fused.empty()) { + return false; } - if (node.opcode == HTP_OP_LIGHTNING_INDEXER) { - const ggml_tensor * src2 = node.inputs.size() > 2 ? node.inputs[2] : nullptr; - const ggml_tensor * src3 = node.inputs.size() > 3 ? node.inputs[3] : nullptr; - return htp_kparams_solve_lightning_indexer_impl(sess, src0, src1, src2, src3, dst, node.kparams()); + + ggml_tensor op_view = *tmp.dst(); + op_view.op = tmp.node->op; + op_view.flags = tmp.node->flags; + memcpy(op_view.op_params, tmp.params, sizeof(op_view.op_params)); + for (size_t i = 0; i < tmp.inputs.size(); ++i) { + op_view.src[i] = const_cast(tmp.inputs[i]); } - return htp_kparams_solve(sess, node.node, node.kernel_params); + return commit(htp_kparams_solve(sess, &op_view, tmp.kernel_params)); } bool htp_kparams_solve( @@ -5709,7 +6064,11 @@ bool htp_kparams_solve( return htp_kparams_invoke(sess, op, kparams); case HTP_OP_SSM_CONV: - return htp_kparams_invoke(sess, op, kparams); + { + struct htp_ssm_conv_kernel_params tmp; + return htp_kparams_solve_ssm_conv(sess, op->src[0], op->src[1], op, + kparams ? (struct htp_ssm_conv_kernel_params *) kparams : &tmp); + } case HTP_OP_SSM_SCAN: return htp_kparams_invoke(sess, op, kparams); @@ -5718,7 +6077,11 @@ bool htp_kparams_solve( return htp_kparams_invoke(sess, op, kparams); case HTP_OP_GATED_DELTA_NET: - return htp_kparams_invoke(sess, op, kparams); + { + struct htp_gdn_kernel_params tmp; + return htp_kparams_solve_gated_delta_net(sess, op, nullptr, + kparams ? (struct htp_gdn_kernel_params *) kparams : &tmp); + } case HTP_OP_ARGSORT: case HTP_OP_TOP_K: @@ -5792,12 +6155,6 @@ bool htp_kparams_solve( return htp_kparams_invoke(sess, op, kparams); default: - if (htp_op_is_unary(opcode)) { - return htp_kparams_invoke(sess, op, kparams); - } - if (htp_op_is_glu(opcode)) { - return htp_kparams_invoke(sess, op, kparams); - } return false; } } diff --git a/ggml/src/ggml-hexagon/htp-kparams.h b/ggml/src/ggml-hexagon/htp-kparams.h index bae41ef1bbea..1927c7d7bc66 100644 --- a/ggml/src/ggml-hexagon/htp-kparams.h +++ b/ggml/src/ggml-hexagon/htp-kparams.h @@ -2,6 +2,7 @@ #define HTP_KPARAMS_H #include "htp-common.h" +#include "htp-lower.h" #include "htp/allreduce-ops.h" #include "htp/argsort-ops.h" @@ -39,11 +40,6 @@ #include #include -bool htp_rows_stride(const int64_t * ne, const size_t * nb, size_t * stride); -bool htp_matmul_can_collapse(const struct ggml_tensor * src0, const struct ggml_tensor * src1, const struct ggml_tensor * dst); -bool htp_matmul_add_can_collapse(const struct ggml_tensor * src0, const struct ggml_tensor * src1, const struct ggml_tensor * src2, const struct ggml_tensor * dst); -ggml_tensor htp_tensor_collapse_rows(const struct ggml_tensor * t); - template auto htp_kparams_type(bool (*)(Args...)) -> std::remove_pointer_t(), ...))>>; @@ -60,11 +56,6 @@ bool htp_kparams_solve( struct htp_opnode & node ); -void htp_opnode_collapse( - const struct ggml_hexagon_session * sess, - struct htp_opnode & node -); - bool htp_kparams_solve( const struct ggml_hexagon_session * sess, const struct ggml_tensor * op, @@ -101,6 +92,7 @@ bool htp_kparams_solve_rms_norm_mul_add( const struct ggml_hexagon_session * sess, const struct ggml_tensor * src0, const struct ggml_tensor * src1, + const struct ggml_tensor * src2, const struct ggml_tensor * dst, struct htp_unary_kernel_params * kparams ); @@ -109,7 +101,7 @@ bool htp_kparams_solve_matmul_add( const struct ggml_hexagon_session * sess, const struct ggml_tensor * src0, const struct ggml_tensor * src1, - const struct ggml_tensor * src2, + const struct ggml_tensor * bias, const struct ggml_tensor * dst, struct htp_mm_kernel_params * kparams ); @@ -118,10 +110,21 @@ bool htp_kparams_solve_mmnx( const struct ggml_hexagon_session * sess, const struct ggml_tensor * src0, const struct ggml_tensor * act, + const struct ggml_tensor * dst, int32_t n_weights, struct htp_mm_kernel_params * kparams ); +bool htp_kparams_solve_mmnx_glu( + const struct ggml_hexagon_session * sess, + const struct ggml_tensor * w_gate, + const struct ggml_tensor * w_up, + const struct ggml_tensor * act, + const struct ggml_tensor * dst, + uint8_t glu_op, + struct htp_mm_kernel_params * kparams +); + bool htp_kparams_solve_mmidnx( const struct ggml_hexagon_session * sess, const struct ggml_tensor * src0, diff --git a/ggml/src/ggml-hexagon/htp-lower.cpp b/ggml/src/ggml-hexagon/htp-lower.cpp new file mode 100644 index 000000000000..372bccb26b22 --- /dev/null +++ b/ggml/src/ggml-hexagon/htp-lower.cpp @@ -0,0 +1,1260 @@ +#include "htp-lower.h" + +#include "htp-common.h" +#include "htp-kparams.h" +#include "htp-opnode.h" + +#include +#include +#include +#include + +bool htp_rows_stride(const int64_t * ne, const size_t * nb, size_t * stride) { + size_t s = 0, next = 0; + for (int i = 1; i < GGML_MAX_DIMS; i++) { + if (ne[i] == 1) continue; + if (s == 0) { s = nb[i]; next = s * ne[i]; continue; } + if (nb[i] != next) return false; + next *= ne[i]; + } + *stride = s ? s : nb[1]; + return true; +} + +bool htp_matmul_can_collapse(const struct ggml_tensor * src0, const struct ggml_tensor * src1, const struct ggml_tensor * dst) { + size_t s1, sd; + return (dst->op == GGML_OP_MUL_MAT || dst->op == GGML_OP_ADD) && + src0->ne[2] == 1 && src0->ne[3] == 1 && src1->ne[2] * src1->ne[3] > 1 && + src1->nb[0] == ggml_type_size(src1->type) && htp_rows_stride(src1->ne, src1->nb, &s1) && + dst->nb[0] == ggml_type_size(dst->type) && htp_rows_stride(dst->ne, dst->nb, &sd); +} + +bool htp_matmul_add_can_collapse( + const struct ggml_tensor * src0, + const struct ggml_tensor * src1, + const struct ggml_tensor * src2, + const struct ggml_tensor * dst +) { + if (!htp_matmul_can_collapse(src0, src1, dst)) { + return false; + } + if (!src2) { + return true; + } + const int64_t src2_nrows = src2->ne[1] * src2->ne[2] * src2->ne[3]; + if (src2_nrows == 1) { + return true; + } + size_t s2; + return src2->nb[0] == ggml_type_size(src2->type) && + ggml_are_same_shape(src2, dst) && + htp_rows_stride(src2->ne, src2->nb, &s2); +} + +ggml_tensor htp_tensor_collapse_rows(const struct ggml_tensor * t) { + size_t stride = 0; + htp_rows_stride(t->ne, t->nb, &stride); + ggml_tensor c = *t; + c.ne[1] = t->ne[1] * t->ne[2] * t->ne[3]; + c.ne[2] = 1; + c.ne[3] = 1; + c.nb[1] = stride; + c.nb[2] = c.nb[1] * c.ne[1]; + c.nb[3] = c.nb[2]; + return c; +} + +// Collapse contiguous dims of elementwise ops so that rows fill at least one HVX vector +static void htp_collapse_dims(struct ggml_tensor ** tensors, size_t n_tensors, size_t elem_size, uint32_t n_hvx) { + if (n_tensors == 0 || !tensors[0]) { + return; + } + for (size_t t = 0; t < n_tensors; t++) { + if (!tensors[t] || tensors[t]->nb[0] != elem_size) { + return; + } + if (t > 0 && !ggml_are_same_shape(tensors[0], tensors[t])) { + return; + } + } + + struct ggml_tensor * t0 = tensors[0]; + + while (t0->ne[1] > 1 || t0->ne[2] > 1 || t0->ne[3] > 1) { + const size_t row_size = (size_t) t0->ne[0] * elem_size; + bool rows_contig = true; + for (size_t t = 0; t < n_tensors; t++) { + if (tensors[t]->nb[1] != (size_t) tensors[t]->ne[0] * elem_size) { + rows_contig = false; + break; + } + } + bool all_ne1_one = true; + for (size_t t = 0; t < n_tensors; t++) { + if (tensors[t]->ne[1] != 1) { + all_ne1_one = false; + break; + } + } + const bool can_merge = all_ne1_one || + (rows_contig && (t0->ne[0] == 1 || (row_size < 128 && row_size * t0->ne[1] <= 2048))); + if (!can_merge) { + break; + } + for (size_t t = 0; t < n_tensors; t++) { + tensors[t]->ne[0] *= tensors[t]->ne[1]; + tensors[t]->ne[1] = tensors[t]->ne[2]; + tensors[t]->ne[2] = tensors[t]->ne[3]; + tensors[t]->ne[3] = 1; + tensors[t]->nb[1] = tensors[t]->nb[2]; + tensors[t]->nb[2] = tensors[t]->nb[3]; + tensors[t]->nb[3] = tensors[t]->nb[2] * tensors[t]->ne[2]; + } + } + + // ne1 too big to merge in full: merge it in chunks of k rows (k divides ne1) + const size_t row_size = (size_t) t0->ne[0] * elem_size; + bool rows_contig = true; + for (size_t t = 0; t < n_tensors; t++) { + if (tensors[t]->nb[1] != row_size) { + rows_contig = false; + break; + } + } + if (t0->ne[1] > 1 && row_size < 128 && rows_contig) { + int64_t k = 2048 / row_size; + while (k > 1 && t0->ne[1] % k != 0) { + k--; + } + if (k > 1) { + for (size_t t = 0; t < n_tensors; t++) { + tensors[t]->ne[0] *= k; + tensors[t]->ne[1] /= k; + tensors[t]->nb[1] *= k; + } + } + } + + // nrows too small to saturate HVX units: split ne0 into k rows (k divides ne0) + const size_t row_size_curr = (size_t) t0->ne[0] * elem_size; + const uint32_t nrows = (uint32_t) (t0->ne[1] * t0->ne[2] * t0->ne[3]); + rows_contig = true; + for (size_t t = 0; t < n_tensors; t++) { + if (tensors[t]->ne[1] != 1 && tensors[t]->nb[1] != row_size_curr) { + rows_contig = false; + break; + } + } + if (nrows < n_hvx && rows_contig && row_size_curr >= 4096) { + const size_t vec_elems = 128 / elem_size; + int64_t k = std::max(row_size_curr / 16384, (n_hvx * 4 + nrows - 1) / nrows); + k = std::min(k, row_size_curr / 2048); + while (k > 1 && t0->ne[0] % (k * vec_elems) != 0) { + k--; + } + if (k > 1) { + for (size_t t = 0; t < n_tensors; t++) { + tensors[t]->ne[0] /= k; + tensors[t]->ne[1] *= k; + tensors[t]->nb[1] = tensors[t]->ne[0] * elem_size; + } + } + } +} + +bool htp_dsv4_hc_pre_can_collapse( + const struct ggml_tensor * x, + const struct ggml_tensor * weights, + const struct ggml_tensor * dst +) { + const auto is_valid_type = [](const ggml_tensor * t) { + return (t->type == GGML_TYPE_F32 || t->type == GGML_TYPE_F16) && t->nb[0] == ggml_type_size(t->type); + }; + if (!is_valid_type(x) || !is_valid_type(weights) || !is_valid_type(dst)) { + return false; + } + if (x->ne[1] != 4 || dst->ne[0] != x->ne[0]) { + return false; + } + + const bool gated = ggml_get_op_params_i32(dst, 1) != 0; + const int64_t x_tokens = x->ne[2] * x->ne[3]; + const int64_t d_tokens = dst->ne[1] * dst->ne[2] * dst->ne[3]; + const int64_t w_tokens = gated ? (weights->ne[2] * weights->ne[3]) : (weights->ne[1] * weights->ne[2] * weights->ne[3]); + + if (x_tokens != d_tokens || x_tokens != w_tokens) { + return false; + } + + if (x->ne[3] == 1 && dst->ne[2] == 1 && dst->ne[3] == 1 && + (gated ? (weights->ne[3] == 1) : (weights->ne[2] == 1 && weights->ne[3] == 1))) { + return false; + } + + if (x->ne[3] > 1 && x->nb[3] != x->ne[2] * x->nb[2]) return false; + + if (dst->ne[2] > 1 && dst->nb[2] != dst->ne[1] * dst->nb[1]) return false; + if (dst->ne[3] > 1 && dst->nb[3] != dst->ne[2] * dst->nb[2]) return false; + + if (gated) { + if (weights->ne[3] > 1 && weights->nb[3] != weights->ne[2] * weights->nb[2]) return false; + } else { + if (weights->ne[2] > 1 && weights->nb[2] != weights->ne[1] * weights->nb[1]) return false; + if (weights->ne[3] > 1 && weights->nb[3] != weights->ne[2] * weights->nb[2]) return false; + } + + return true; +} + +void htp_dsv4_hc_pre_collapse_tensors( + const struct ggml_tensor * x, + const struct ggml_tensor * weights, + const struct ggml_tensor * dst, + struct ggml_tensor * x_c, + struct ggml_tensor * w_c, + struct ggml_tensor * d_c +) { + const int64_t n_tokens = x->ne[2] * x->ne[3]; + const bool gated = ggml_get_op_params_i32(dst, 1) != 0; + + *x_c = *x; + x_c->ne[2] = n_tokens; + x_c->ne[3] = 1; + x_c->nb[3] = x_c->ne[2] * x_c->nb[2]; + + *d_c = *dst; + d_c->ne[1] = n_tokens; + d_c->ne[2] = 1; + d_c->ne[3] = 1; + d_c->nb[2] = d_c->ne[1] * d_c->nb[1]; + d_c->nb[3] = d_c->nb[2]; + + *w_c = *weights; + if (gated) { + w_c->ne[2] = n_tokens; + w_c->ne[3] = 1; + w_c->nb[3] = w_c->ne[2] * w_c->nb[2]; + } else { + w_c->ne[1] = n_tokens; + w_c->ne[2] = 1; + w_c->ne[3] = 1; + w_c->nb[2] = w_c->ne[1] * w_c->nb[1]; + w_c->nb[3] = w_c->nb[2]; + } +} + +bool htp_dsv4_hc_post_can_collapse( + const struct ggml_tensor * x, + const struct ggml_tensor * residual, + const struct ggml_tensor * post, + const struct ggml_tensor * comb, + const struct ggml_tensor * dst +) { + const auto is_valid_type = [](const ggml_tensor * t) { + return (t->type == GGML_TYPE_F32 || t->type == GGML_TYPE_F16) && t->nb[0] == ggml_type_size(t->type); + }; + if (!is_valid_type(x) || !is_valid_type(residual) || !is_valid_type(post) || !is_valid_type(dst)) { + return false; + } + if (comb && !is_valid_type(comb)) { + return false; + } + if (residual->ne[0] != x->ne[0] || residual->ne[1] != 4 || dst->ne[0] != x->ne[0] || dst->ne[1] != 4 || post->ne[0] != 4) { + return false; + } + if (comb && (comb->ne[0] != 4 || comb->ne[1] != 4)) { + return false; + } + + const int64_t x_tokens = x->ne[1] * x->ne[2] * x->ne[3]; + const int64_t r_tokens = residual->ne[2] * residual->ne[3]; + const int64_t p_tokens = post->ne[1] * post->ne[2] * post->ne[3]; + const int64_t d_tokens = dst->ne[2] * dst->ne[3]; + if (x_tokens != r_tokens || x_tokens != p_tokens || x_tokens != d_tokens) { + return false; + } + if (comb && (comb->ne[2] * comb->ne[3] != x_tokens)) { + return false; + } + + if (x->ne[2] == 1 && x->ne[3] == 1 && + residual->ne[3] == 1 && + post->ne[2] == 1 && post->ne[3] == 1 && + dst->ne[3] == 1 && + (!comb || comb->ne[3] == 1)) { + return false; + } + + if (x->ne[2] > 1 && x->nb[2] != x->ne[1] * x->nb[1]) return false; + if (x->ne[3] > 1 && x->nb[3] != x->ne[2] * x->nb[2]) return false; + + if (residual->ne[3] > 1 && residual->nb[3] != residual->ne[2] * residual->nb[2]) return false; + if (dst->ne[3] > 1 && dst->nb[3] != dst->ne[2] * dst->nb[2]) return false; + + if (post->ne[2] > 1 && post->nb[2] != post->ne[1] * post->nb[1]) return false; + if (post->ne[3] > 1 && post->nb[3] != post->ne[2] * post->nb[2]) return false; + + if (comb && comb->ne[3] > 1 && comb->nb[3] != comb->ne[2] * comb->nb[2]) return false; + + return true; +} + +void htp_dsv4_hc_post_collapse_tensors( + const struct ggml_tensor * x, + const struct ggml_tensor * residual, + const struct ggml_tensor * post, + const struct ggml_tensor * comb, + const struct ggml_tensor * dst, + struct ggml_tensor * x_c, + struct ggml_tensor * r_c, + struct ggml_tensor * p_c, + struct ggml_tensor * c_c, + struct ggml_tensor * d_c +) { + const int64_t n_tokens = x->ne[1] * x->ne[2] * x->ne[3]; + + *x_c = *x; + x_c->ne[1] = n_tokens; + x_c->ne[2] = 1; + x_c->ne[3] = 1; + x_c->nb[2] = x_c->ne[1] * x_c->nb[1]; + x_c->nb[3] = x_c->nb[2]; + + *r_c = *residual; + r_c->ne[2] = n_tokens; + r_c->ne[3] = 1; + r_c->nb[3] = r_c->ne[2] * r_c->nb[2]; + + *d_c = *dst; + d_c->ne[2] = n_tokens; + d_c->ne[3] = 1; + d_c->nb[3] = d_c->ne[2] * d_c->nb[2]; + + *p_c = *post; + p_c->ne[1] = n_tokens; + p_c->ne[2] = 1; + p_c->ne[3] = 1; + p_c->nb[2] = p_c->ne[1] * p_c->nb[1]; + p_c->nb[3] = p_c->nb[2]; + + if (comb && c_c) { + *c_c = *comb; + c_c->ne[2] = n_tokens; + c_c->ne[3] = 1; + c_c->nb[3] = c_c->ne[2] * c_c->nb[2]; + } +} + +bool htp_lightning_indexer_can_collapse( + const struct ggml_tensor * q, + const struct ggml_tensor * k, + const struct ggml_tensor * w, + const struct ggml_tensor * m, + const struct ggml_tensor * dst +) { + // 2D K normalization: ne[1] is n_kv, ne[2] is 1 + const bool can_collapse_k = (k->ne[1] > 1 && k->ne[2] == 1); + + // Stream-to-token collapse across q, w, dst (and m) + bool can_collapse_stream = false; + if (q->ne[3] > 1 && k->ne[3] == 1) { + const bool q_ok = (q->nb[3] == (size_t) q->ne[2] * q->nb[2]); + const bool dst_ok = (dst->ne[3] == q->ne[3] && dst->ne[2] == 1 && dst->ne[1] == q->ne[2] && + dst->nb[3] == (size_t) dst->ne[1] * dst->nb[1]); + const bool w_ok = (w->ne[3] == q->ne[3] && w->ne[2] == 1 && w->ne[1] == q->ne[2] && + w->nb[3] == (size_t) w->ne[1] * w->nb[1]) || + (w->ne[3] == 1 && w->ne[1] == q->ne[2] * q->ne[3]); + const bool m_ok = (m->ne[3] == q->ne[3] && m->ne[2] == 1 && m->ne[1] == q->ne[2] && + m->nb[3] == (size_t) m->ne[1] * m->nb[1]) || + (m->ne[3] == 1 && m->ne[1] == q->ne[2] * q->ne[3]); + can_collapse_stream = q_ok && dst_ok && w_ok && m_ok; + } + + return can_collapse_k || can_collapse_stream; +} + +void htp_lightning_indexer_collapse_tensors( + const struct ggml_tensor * q, + const struct ggml_tensor * k, + const struct ggml_tensor * w, + const struct ggml_tensor * m, + const struct ggml_tensor * dst, + struct ggml_tensor * q_c, + struct ggml_tensor * k_c, + struct ggml_tensor * w_c, + struct ggml_tensor * m_c, + struct ggml_tensor * dst_c +) { + *q_c = *q; + *k_c = *k; + *w_c = *w; + *m_c = *m; + *dst_c = *dst; + + if (k->ne[1] > 1 && k->ne[2] == 1) { + k_c->ne[2] = k->ne[1]; + k_c->ne[1] = 1; + k_c->nb[1] = k->nb[1]; + k_c->nb[2] = k->nb[1]; + k_c->nb[3] = k->nb[2]; + } + + if (q->ne[3] > 1 && k->ne[3] == 1) { + const int64_t n_tokens_collapsed = (int64_t) q->ne[2] * q->ne[3]; + + q_c->ne[2] = n_tokens_collapsed; + q_c->ne[3] = 1; + q_c->nb[3] = (size_t) q_c->ne[2] * q_c->nb[2]; + + if (w->ne[3] == q->ne[3]) { + w_c->ne[1] = n_tokens_collapsed; + w_c->ne[3] = 1; + w_c->nb[2] = (size_t) w_c->ne[1] * w_c->nb[1]; + w_c->nb[3] = w_c->nb[2]; + } + + dst_c->ne[1] = n_tokens_collapsed; + dst_c->ne[3] = 1; + dst_c->nb[2] = (size_t) dst_c->ne[1] * dst_c->nb[1]; + dst_c->nb[3] = dst_c->nb[2]; + + if (m->ne[3] == q->ne[3] && m->ne[1] == q->ne[2]) { + m_c->ne[1] = n_tokens_collapsed; + m_c->ne[3] = 1; + m_c->nb[2] = (size_t) m_c->ne[1] * m_c->nb[1]; + m_c->nb[3] = m_c->nb[2]; + } + } +} + +void htp_lower_opnode(const struct ggml_hexagon_session * sess, htp_opnode & node, struct ggml_tensor * scratch) { + const uint32_t n_hvx = htp_session_n_hvx(sess); + const size_t n_in = node.inputs.size(); + const size_t n_out = node.outputs.size(); + + ggml_tensor in_mat[HTP_OP_MAX_INPUTS] = {}; + ggml_tensor out_mat[HTP_OP_MAX_OUTPUTS] = {}; + bool in_dirty[HTP_OP_MAX_INPUTS] = {}; + bool out_dirty[HTP_OP_MAX_OUTPUTS] = {}; + + for (size_t i = 0; i < n_in; ++i) { + if (node.inputs[i]) { + in_dirty[i] = ggml_hexagon_tensor_is_lowered_f16(node.inputs[i]); + in_mat[i] = htp_tensor_lower_f16(node.inputs[i]); + } + } + for (size_t i = 0; i < n_out; ++i) { + out_dirty[i] = ggml_hexagon_tensor_is_lowered_f16(node.outputs[i]); + out_mat[i] = htp_tensor_lower_f16(node.outputs[i]); + } + + if (htp_op_is_unary(node.opcode) && htp_unary_is_elementwise(node.opcode)) { + if (n_in >= 1 && n_out >= 1 && + ggml_are_same_shape(&in_mat[0], &out_mat[0])) { + const int64_t old_ne0 = in_mat[0].ne[0]; + const int64_t old_ne1 = in_mat[0].ne[1]; + const size_t elem_size = ggml_type_size(in_mat[0].type); + struct ggml_tensor * tensors[2] = { &in_mat[0], &out_mat[0] }; + htp_collapse_dims(tensors, 2, elem_size, n_hvx); + if (in_mat[0].ne[0] != old_ne0 || in_mat[0].ne[1] != old_ne1) { + in_dirty[0] = true; + out_dirty[0] = true; + } + } + } else if (htp_op_is_glu(node.opcode)) { + if (n_in >= 2 && n_out >= 1 && + ggml_are_same_shape(&in_mat[0], &out_mat[0]) && + ggml_are_same_shape(&in_mat[1], &out_mat[0])) { + const int64_t old_ne0 = in_mat[0].ne[0]; + const int64_t old_ne1 = in_mat[0].ne[1]; + const size_t elem_size = ggml_type_size(in_mat[0].type); + struct ggml_tensor * tensors[3] = { &in_mat[0], &in_mat[1], &out_mat[0] }; + htp_collapse_dims(tensors, 3, elem_size, n_hvx); + if (in_mat[0].ne[0] != old_ne0 || in_mat[0].ne[1] != old_ne1) { + in_dirty[0] = true; + in_dirty[1] = true; + out_dirty[0] = true; + } + } + } else if (node.opcode == HTP_OP_MUL_MAT) { + if (n_in >= 2 && n_out >= 1 && + htp_matmul_can_collapse(&in_mat[0], &in_mat[1], &out_mat[0])) { + in_mat[1] = htp_tensor_collapse_rows(&in_mat[1]); + out_mat[0] = htp_tensor_collapse_rows(&out_mat[0]); + in_dirty[1] = true; + out_dirty[0] = true; + } + } else if (node.opcode == HTP_OP_MUL_MAT_ADD) { + if (n_in >= 3 && n_out >= 1 && + htp_matmul_add_can_collapse(&in_mat[0], &in_mat[1], &in_mat[2], &out_mat[0])) { + in_mat[1] = htp_tensor_collapse_rows(&in_mat[1]); + out_mat[0] = htp_tensor_collapse_rows(&out_mat[0]); + in_dirty[1] = true; + out_dirty[0] = true; + if (in_mat[2].ne[1] * in_mat[2].ne[2] * in_mat[2].ne[3] > 1) { + in_mat[2] = htp_tensor_collapse_rows(&in_mat[2]); + in_dirty[2] = true; + } + } + } else if (node.opcode == HTP_OP_MUL_MAT_NX) { + const size_t n_w = n_out; + if (n_w > 0 && n_in == n_w + 1) { + bool can_collapse = true; + for (size_t i = 0; i < n_w; ++i) { + if (!htp_matmul_can_collapse(&in_mat[i], &in_mat[n_w], &out_mat[i])) { + can_collapse = false; + break; + } + } + if (can_collapse) { + in_mat[n_w] = htp_tensor_collapse_rows(&in_mat[n_w]); + in_dirty[n_w] = true; + for (size_t i = 0; i < n_w; ++i) { + out_mat[i] = htp_tensor_collapse_rows(&out_mat[i]); + out_dirty[i] = true; + } + } + } + } else if (node.opcode == HTP_OP_MUL_MAT_NX_GLU) { + if (n_in == 3 && n_out == 1 && + htp_matmul_can_collapse(&in_mat[0], &in_mat[2], &out_mat[0]) && + htp_matmul_can_collapse(&in_mat[1], &in_mat[2], &out_mat[0])) { + in_mat[2] = htp_tensor_collapse_rows(&in_mat[2]); + in_dirty[2] = true; + out_mat[0] = htp_tensor_collapse_rows(&out_mat[0]); + out_dirty[0] = true; + } + } else if (node.opcode == HTP_OP_UPSCALE) { + if (n_in >= 1 && n_out >= 1) { + if ((in_mat[0].ne[3] > 1 || out_mat[0].ne[3] > 1) && + in_mat[0].ne[2] == out_mat[0].ne[2] && in_mat[0].ne[3] == out_mat[0].ne[3] && + in_mat[0].nb[3] == (size_t) in_mat[0].ne[2] * in_mat[0].nb[2] && + out_mat[0].nb[3] == (size_t) out_mat[0].ne[2] * out_mat[0].nb[2]) { + in_mat[0].ne[2] *= in_mat[0].ne[3]; + in_mat[0].ne[3] = 1; + in_mat[0].nb[3] = (size_t) in_mat[0].ne[2] * in_mat[0].nb[2]; + out_mat[0].ne[2] *= out_mat[0].ne[3]; + out_mat[0].ne[3] = 1; + out_mat[0].nb[3] = (size_t) out_mat[0].ne[2] * out_mat[0].nb[2]; + in_dirty[0] = true; + out_dirty[0] = true; + } + } + } else if (node.opcode == HTP_OP_DSV4_HC_PRE) { + if (n_in >= 2 && n_out >= 1 && + htp_dsv4_hc_pre_can_collapse(&in_mat[0], &in_mat[1], &out_mat[0])) { + struct ggml_tensor x_c, w_c, d_c; + htp_dsv4_hc_pre_collapse_tensors(&in_mat[0], &in_mat[1], &out_mat[0], &x_c, &w_c, &d_c); + in_mat[0] = x_c; + in_mat[1] = w_c; + out_mat[0] = d_c; + in_dirty[0] = true; + in_dirty[1] = true; + out_dirty[0] = true; + } + } else if (node.opcode == HTP_OP_DSV4_HC_POST) { + if (n_in >= 3 && n_out >= 1) { + const struct ggml_tensor * comb = (n_in > 3 && node.inputs[3]) ? &in_mat[3] : nullptr; + if (htp_dsv4_hc_post_can_collapse(&in_mat[0], &in_mat[1], &in_mat[2], comb, &out_mat[0])) { + struct ggml_tensor x_c, r_c, p_c, c_c, d_c; + htp_dsv4_hc_post_collapse_tensors(&in_mat[0], &in_mat[1], &in_mat[2], comb, &out_mat[0], + &x_c, &r_c, &p_c, comb ? &c_c : nullptr, &d_c); + in_mat[0] = x_c; + in_mat[1] = r_c; + in_mat[2] = p_c; + out_mat[0] = d_c; + in_dirty[0] = true; + in_dirty[1] = true; + in_dirty[2] = true; + out_dirty[0] = true; + if (comb) { + in_mat[3] = c_c; + in_dirty[3] = true; + } + } + } + } else if (node.opcode == HTP_OP_LIGHTNING_INDEXER) { + if (n_in >= 4 && n_out >= 1 && + htp_lightning_indexer_can_collapse(&in_mat[0], &in_mat[1], &in_mat[2], &in_mat[3], &out_mat[0])) { + struct ggml_tensor q_c, k_c, w_c, m_c, d_c; + htp_lightning_indexer_collapse_tensors(&in_mat[0], &in_mat[1], &in_mat[2], &in_mat[3], &out_mat[0], + &q_c, &k_c, &w_c, &m_c, &d_c); + in_mat[0] = q_c; + in_mat[1] = k_c; + in_mat[2] = w_c; + in_mat[3] = m_c; + out_mat[0] = d_c; + in_dirty[0] = true; + in_dirty[1] = true; + in_dirty[2] = true; + in_dirty[3] = true; + out_dirty[0] = true; + } + } + + size_t n_scratch = 0; + auto commit_tensor = [&](const ggml_tensor & m) -> const ggml_tensor * { + if (scratch) { + scratch[n_scratch] = m; + return &scratch[n_scratch++]; + } + return node.add_dummy(m); + }; + + const ggml_tensor * orig_in[HTP_OP_MAX_INPUTS] = {}; + for (size_t i = 0; i < n_in; ++i) { + orig_in[i] = node.inputs[i]; + if (in_dirty[i]) { + node.inputs[i] = commit_tensor(in_mat[i]); + } + } + for (size_t j = 0; j < n_out; ++j) { + if (!out_dirty[j]) { + continue; + } + const ggml_tensor * reused = nullptr; + for (size_t i = 0; i < n_in; ++i) { + if (orig_in[i] == node.outputs[j] && in_dirty[i] && + in_mat[i].type == out_mat[j].type && + ggml_are_same_shape(&in_mat[i], &out_mat[j]) && + ggml_are_same_stride(&in_mat[i], &out_mat[j])) { + reused = node.inputs[i]; + break; + } + } + node.outputs[j] = reused ? reused : commit_tensor(out_mat[j]); + } +} + +static bool htp_lower_is_view(const ggml_tensor * tensor) { + return tensor->op == GGML_OP_VIEW || tensor->op == GGML_OP_RESHAPE || tensor->op == GGML_OP_PERMUTE || tensor->op == GGML_OP_TRANSPOSE; +} + +static bool htp_lower_is_root_candidate(const ggml_tensor * root, const std::unordered_set & produced) { + return produced.count(root) && root->type == GGML_TYPE_F32 && root->buffer && + !ggml_backend_buffer_is_host(root->buffer) && + ggml_backend_buffer_get_usage(root->buffer) != GGML_BACKEND_BUFFER_USAGE_WEIGHTS && + (root->flags & (GGML_TENSOR_FLAG_INPUT | GGML_TENSOR_FLAG_OUTPUT | GGML_TENSOR_FLAG_PARAM)) == 0; +} + +static bool htp_lower_is_partial_write(const ggml_tensor * tensor) { + if (tensor->op == GGML_OP_SET || tensor->op == GGML_OP_SET_ROWS) { + return true; + } + return tensor->op == GGML_OP_CPY && !ggml_is_contiguous(tensor); +} + +static bool htp_lower_safe_class( + const ggml_cgraph * graph, + const ggml_tensor * root, + const std::vector & tensors, + const std::unordered_map & node_idx, + const std::unordered_map & internal_uses +) { + int total_internal_uses = 0; + for (const ggml_tensor * tensor : tensors) { + if (tensor->type != GGML_TYPE_F32) { + return false; + } + if (tensor != root && !htp_lower_is_view(tensor)) { + return false; + } + const ptrdiff_t offset = (const uint8_t *) tensor->data - (const uint8_t *) root->data; + if (offset % 4 != 0 || (tensor->flags & GGML_TENSOR_FLAG_OUTPUT)) { + return false; + } + for (int d = 0; d < GGML_MAX_DIMS; ++d) { + if (tensor->nb[d] % 4 != 0) { + return false; + } + } + auto it = node_idx.find(tensor); + if (it == node_idx.end() || htp_lower_is_partial_write(tensor)) { + return false; + } + const int total_uses = ggml_node_get_use_count(graph, it->second); + auto uit = internal_uses.find(tensor); + const int uses = (uit != internal_uses.end()) ? uit->second : 0; + if (uses != total_uses) { + return false; + } + total_internal_uses += uses; + } + return total_internal_uses >= 1; +} + +static bool htp_lower_inplace_types_ok(const htp_opnode & node) { + for (const ggml_tensor * inp : node.inputs) { + if (!inp) { + continue; + } + const ggml_type inp_type = htp_effective_type(inp); + if (inp_type != GGML_TYPE_F32 && inp_type != GGML_TYPE_F16) { + continue; + } + for (const ggml_tensor * out : node.outputs) { + if (!out) { + continue; + } + const ggml_type out_type = htp_effective_type(out); + if (out_type != GGML_TYPE_F32 && out_type != GGML_TYPE_F16) { + continue; + } + if (inp_type != out_type && htp_tensors_overlap(inp, out)) { + return false; + } + } + } + return true; +} + +static bool htp_lower_is_mm_opcode(uint32_t opcode) { + return opcode == HTP_OP_MUL_MAT || opcode == HTP_OP_MUL_MAT_ADD || + opcode == HTP_OP_MUL_MAT_ID || opcode == HTP_OP_MUL_MAT_NX || + opcode == HTP_OP_MUL_MAT_NX_GLU || opcode == HTP_OP_MUL_MAT_ID_NX; +} + +static const ggml_tensor * htp_lower_orig_mm_for_output(const htp_opnode & node, const ggml_tensor * tensor) { + if (!htp_lower_is_mm_opcode(node.opcode)) { + return nullptr; + } + if (node.opcode == HTP_OP_MUL_MAT_NX || node.opcode == HTP_OP_MUL_MAT_ID_NX) { + for (size_t p = 0; p < node.outputs.size(); ++p) { + if (node.outputs[p] == tensor) { + if (p == 0) { + return node.node; + } + return (p - 1 < node.fused.size()) ? node.fused[p - 1] : nullptr; + } + } + return nullptr; + } + return node.node; +} + +static bool htp_lower_mm_blocks_output_f16(const ggml_tensor * orig_mm) { + if (!orig_mm) { + return false; + } + if (ggml_prec_get_acc(orig_mm) == GGML_PREC_F32) { + return true; + } + const ggml_prec src1_prec = ggml_prec_get_src(orig_mm, 1); + return src1_prec == GGML_PREC_BF16 || src1_prec == GGML_PREC_F32; +} + +static bool htp_lower_respect_prec_hints( + const htp_opnode & owner, + const ggml_tensor * r, + const std::vector & cls, + const std::vector & nodes, + const std::unordered_map & owner_idx, + const std::unordered_map> & root_users +) { + if (htp_lower_is_mm_opcode(owner.opcode)) { + const ggml_tensor * orig_mm = htp_lower_orig_mm_for_output(owner, r); + if (htp_lower_mm_blocks_output_f16(orig_mm)) { + return false; + } + if (owner.opcode == HTP_OP_MUL_MAT_NX_GLU) { + for (const ggml_tensor * f : owner.fused) { + if (f && f->op == GGML_OP_MUL_MAT && htp_lower_mm_blocks_output_f16(f)) { + return false; + } + } + } + } + if (owner.opcode == HTP_OP_SOFTMAX && !owner.inputs.empty() && owner.inputs[0]) { + const ggml_tensor * in_root = htp_tensor_root(owner.inputs[0]); + auto oit = owner_idx.find(in_root); + if (oit != owner_idx.end()) { + const htp_opnode & node = nodes[oit->second]; + if (htp_lower_is_mm_opcode(node.opcode) && + htp_lower_mm_blocks_output_f16(htp_lower_orig_mm_for_output(node, in_root))) { + return false; + } + } + } + auto uit = root_users.find(r); + if (uit == root_users.end()) { + return true; + } + for (size_t idx : uit->second) { + const htp_opnode & node = nodes[idx]; + if (!htp_lower_is_mm_opcode(node.opcode)) { + continue; + } + const size_t act_idx = (node.opcode == HTP_OP_MUL_MAT_NX || node.opcode == HTP_OP_MUL_MAT_ID_NX) + ? node.outputs.size() + : (node.opcode == HTP_OP_MUL_MAT_NX_GLU ? 2 : 1); + if (act_idx >= node.inputs.size()) { + continue; + } + const ggml_tensor * act = node.inputs[act_idx]; + bool uses_cls = false; + for (const ggml_tensor * tensor : cls) { + if (act == tensor) { + uses_cls = true; + break; + } + } + if (!uses_cls && (!act || htp_tensor_root(act) != r)) { + continue; + } + auto blocks_src1 = [](const ggml_tensor * orig_mm) -> bool { + if (!orig_mm) { + return false; + } + const ggml_prec src1_prec = ggml_prec_get_src(orig_mm, 1); + return src1_prec == GGML_PREC_BF16 || src1_prec == GGML_PREC_F32; + }; + if (blocks_src1(node.node)) { + return false; + } + if (node.opcode == HTP_OP_MUL_MAT_NX || node.opcode == HTP_OP_MUL_MAT_NX_GLU || node.opcode == HTP_OP_MUL_MAT_ID_NX) { + for (const ggml_tensor * f : node.fused) { + if (f && (f->op == GGML_OP_MUL_MAT || f->op == GGML_OP_MUL_MAT_ID) && blocks_src1(f)) { + return false; + } + } + } + } + return true; +} + +static bool htp_lower_is_mm_root( + const std::vector & nodes, + const std::unordered_map & owner_idx, + const ggml_tensor * root +) { + auto it = owner_idx.find(root); + return it != owner_idx.end() && htp_lower_is_mm_opcode(nodes[it->second].opcode); +} + +static bool htp_lower_is_fa_root( + const std::vector & nodes, + const std::unordered_map & owner_idx, + const ggml_tensor * root +) { + auto it = owner_idx.find(root); + return it != owner_idx.end() && nodes[it->second].opcode == HTP_OP_FLASH_ATTN_EXT; +} + +static bool htp_lower_is_rms_root( + const std::vector & nodes, + const std::unordered_map & owner_idx, + const ggml_tensor * root +) { + auto it = owner_idx.find(root); + if (it == owner_idx.end()) { + return false; + } + const uint32_t opcode = nodes[it->second].opcode; + return opcode == HTP_OP_RMS_NORM || opcode == HTP_OP_RMS_NORM_MUL || + opcode == HTP_OP_RMS_NORM_MUL_ADD; +} + +static bool htp_lower_is_ssm_conv_root( + const std::vector & nodes, + const std::unordered_map & owner_idx, + const ggml_tensor * root +) { + auto it = owner_idx.find(root); + return it != owner_idx.end() && nodes[it->second].opcode == HTP_OP_SSM_CONV && + !nodes[it->second].outputs.empty() && nodes[it->second].outputs[0] == root; +} + +static bool htp_lower_is_get_rows_root( + const std::vector & nodes, + const std::unordered_map & owner_idx, + const ggml_tensor * root +) { + auto it = owner_idx.find(root); + if (it == owner_idx.end()) { + return false; + } + const htp_opnode & owner = nodes[it->second]; + return owner.opcode == HTP_OP_GET_ROWS && !owner.inputs.empty() && owner.inputs[0] && + (owner.inputs[0]->type != GGML_TYPE_F32 || ggml_hexagon_tensor_is_tiled(owner.inputs[0])); +} + +static bool htp_lower_is_repeat_root( + const std::vector & nodes, + const std::unordered_map & owner_idx, + const ggml_tensor * root +) { + auto it = owner_idx.find(root); + return it != owner_idx.end() && nodes[it->second].opcode == HTP_OP_REPEAT; +} + +static bool htp_lower_safe_gdn_output( + const htp_opnode & owner, + const ggml_tensor * root, + const std::vector & nodes, + const std::unordered_map> & root_users +) { + if (owner.outputs.size() != 2 || root != owner.outputs[0] || owner.inputs.size() < 3) { + return false; + } + auto uit = root_users.find(root); + if (uit == root_users.end()) { + return false; + } + const ggml_tensor * v = owner.inputs[2]; + const size_t tail_off = (size_t) v->ne[0] * v->ne[1] * v->ne[2] * v->ne[3] * sizeof(float); + bool has_consumer = false; + for (size_t idx : uit->second) { + const htp_opnode & node = nodes[idx]; + for (const ggml_tensor * input : node.inputs) { + if (!input || htp_tensor_root(input) != root) { + continue; + } + const ptrdiff_t offset = (const uint8_t *) input->data - (const uint8_t *) root->data; + if (offset < 0 || (size_t) offset + ggml_nbytes(input) > tail_off) { + return false; + } + has_consumer = true; + } + } + return has_consumer; +} + +void htp_lower_reset_graph(const struct ggml_cgraph * graph) { + for (int i = 0; i < graph->n_nodes; ++i) { + ggml_tensor * node = graph->nodes[i]; + for (int j = 0; j < GGML_MAX_SRC; ++j) { + ggml_hexagon_tensor_clear_lowered(node->src[j]); + } + ggml_hexagon_tensor_clear_lowered(node); + } +} + +void htp_pack_tensor_lowered_f16(struct ggml_tensor * t, const void * src, size_t offset, size_t size) { + if (size == 0) { + return; + } + GGML_ASSERT(t->type == GGML_TYPE_F32); + GGML_ASSERT(offset % sizeof(float) == 0 && size % sizeof(float) == 0); + const struct ggml_tensor * root = htp_tensor_root(t); + uint8_t * base = (uint8_t *) root->data + ((const uint8_t *) t->data - (const uint8_t *) root->data) / 2; + ggml_fp16_t * dst = (ggml_fp16_t *) (base + offset / 2); + const int64_t n = (int64_t) (size / sizeof(float)); + if ((uintptr_t) src % alignof(float) == 0) { + ggml_fp32_to_fp16_row((const float *) src, dst, n); + } else { + std::vector tmp((size_t) n); + memcpy(tmp.data(), src, size); + ggml_fp32_to_fp16_row(tmp.data(), dst, n); + } +} + +void htp_unpack_tensor_lowered_f16(void * dst, const struct ggml_tensor * t, size_t offset, size_t size) { + if (size == 0) { + return; + } + GGML_ASSERT(t->type == GGML_TYPE_F32); + GGML_ASSERT(offset % sizeof(float) == 0 && size % sizeof(float) == 0); + const struct ggml_tensor * root = htp_tensor_root(t); + const uint8_t * base = (const uint8_t *) root->data + ((const uint8_t *) t->data - (const uint8_t *) root->data) / 2; + const ggml_fp16_t * src = (const ggml_fp16_t *) (base + offset / 2); + const int64_t n = (int64_t) (size / sizeof(float)); + if ((uintptr_t) dst % alignof(float) == 0) { + ggml_fp16_to_fp32_row(src, (float *) dst, n); + } else { + std::vector tmp((size_t) n); + ggml_fp16_to_fp32_row(src, tmp.data(), n); + memcpy(dst, tmp.data(), size); + } +} + +void htp_lower_graph(const struct ggml_hexagon_session * sess, const struct ggml_cgraph * graph, std::vector & nodes) { + if (opt_oplower <= 0) { + for (htp_opnode & node : nodes) { + htp_lower_opnode(sess, node); + } + return; + } + + std::vector roots; + std::unordered_map> classes; + std::unordered_set seen; + std::unordered_map node_idx; + std::unordered_map internal_uses; + std::unordered_set produced; + + auto add_to_class = [&](const ggml_tensor * tensor) { + if (!tensor || !seen.insert(tensor).second) { + return; + } + ggml_hexagon_tensor_clear_flags(const_cast(tensor), HTP_TENSOR_LOWERED_F16); + const ggml_tensor * root = htp_tensor_root(tensor); + auto & cls = classes[root]; + if (cls.empty()) { + roots.push_back(root); + } + cls.push_back(tensor); + }; + + for (int i = 0; i < graph->n_nodes; ++i) { + const ggml_tensor * tensor = graph->nodes[i]; + node_idx[tensor] = i; + produced.insert(tensor); + for (int j = 0; j < GGML_MAX_SRC; ++j) { + if (tensor->src[j]) { + ++internal_uses[tensor->src[j]]; + } + add_to_class(tensor->src[j]); + } + add_to_class(tensor); + } + + std::unordered_map owner_idx; + std::unordered_map> root_users; + + for (size_t idx = 0; idx < nodes.size(); ++idx) { + const htp_opnode & node = nodes[idx]; + auto add_user = [&](const ggml_tensor * t) { + if (!t) { + return; + } + auto & vec = root_users[htp_tensor_root(t)]; + if (vec.empty() || vec.back() != idx) { + vec.push_back(idx); + } + }; + for (const ggml_tensor * inp : node.inputs) { + add_user(inp); + } + for (const ggml_tensor * out : node.outputs) { + if (out) { + owner_idx.emplace(out, idx); + add_user(out); + } + } + } + + size_t n_candidates = 0; + size_t n_lowered_roots = 0; + size_t n_lowered_mm = 0; + size_t bytes_saved = 0; + + auto find_owner = [&](const ggml_tensor * r) -> htp_opnode * { + auto it = owner_idx.find(r); + return (it != owner_idx.end()) ? &nodes[it->second] : nullptr; + }; + + std::unordered_map root_safe_class; + for (const ggml_tensor * root : roots) { + auto it = classes.find(root); + const bool safe = it != classes.end() && + htp_lower_is_root_candidate(root, produced) && + htp_lower_safe_class(graph, root, it->second, node_idx, internal_uses); + root_safe_class[root] = safe; + if (safe && find_owner(root)) { + ++n_candidates; + } + } + + auto is_f16_tensor = [&](const ggml_tensor * t) -> bool { + return t && (htp_effective_type(t) == GGML_TYPE_F16 || ggml_hexagon_tensor_is_lowered_f16(htp_tensor_root(t))); + }; + + auto can_lower = [&](const ggml_tensor * r) -> bool { + auto it = classes.find(r); + if (it == classes.end() || ggml_hexagon_tensor_is_lowered_f16(r)) { + return false; + } + auto sit = root_safe_class.find(r); + if (sit == root_safe_class.end() || !sit->second) { + return false; + } + htp_opnode * owner = find_owner(r); + if (!owner) { + return false; + } + if (!htp_lower_respect_prec_hints(*owner, r, it->second, nodes, owner_idx, root_users)) { + return false; + } + if (owner->opcode == HTP_OP_GATED_DELTA_NET && !htp_lower_safe_gdn_output(*owner, r, nodes, root_users)) { + return false; + } + if (owner->opcode == HTP_OP_SSM_CONV && (owner->outputs.empty() || r != owner->outputs[0])) { + return false; + } + return true; + }; + + auto is_selected_root = [&](const ggml_tensor * r) -> bool { + if (htp_lower_is_mm_root(nodes, owner_idx, r) || htp_lower_is_fa_root(nodes, owner_idx, r) || + htp_lower_is_rms_root(nodes, owner_idx, r) || htp_lower_is_ssm_conv_root(nodes, owner_idx, r) || + htp_lower_is_get_rows_root(nodes, owner_idx, r) || htp_lower_is_repeat_root(nodes, owner_idx, r)) { + return true; + } + for (const ggml_tensor * tensor : classes[r]) { + auto oit = owner_idx.find(tensor); + if (oit != owner_idx.end()) { + for (const ggml_tensor * input : nodes[oit->second].inputs) { + if (is_f16_tensor(input)) { + return true; + } + } + } + } + return false; + }; + + auto has_real_inputs = [](const htp_opnode & node) -> bool { + for (const ggml_tensor * inp : node.inputs) { + if (inp && inp->type != GGML_TYPE_I32 && inp->type != GGML_TYPE_I64) { + return true; + } + } + return false; + }; + + auto is_f16_consumer_seed = [&](const ggml_tensor * r) -> bool { + const htp_opnode * owner = find_owner(r); + if (!owner || has_real_inputs(*owner)) { + return false; + } + auto uit = root_users.find(r); + if (uit == root_users.end()) { + return false; + } + for (size_t idx : uit->second) { + const htp_opnode & user = nodes[idx]; + if (&user == owner) { + continue; + } + for (const ggml_tensor * out : user.outputs) { + if (is_f16_tensor(out)) { + return true; + } + } + } + return false; + }; + + struct saved_node { + size_t idx; + htp_opnode * node; + bool dirty; + int32_t kernel_params[HTP_OP_MAX_KERN_PARAMS]; + }; + + std::vector touched_pos(nodes.size(), -1); + + auto try_lower_root = [&](const ggml_tensor * root) { + std::vector tx_roots; + std::vector touched; + + auto apply_root = [&](const ggml_tensor * r) -> bool { + if (ggml_hexagon_tensor_is_lowered_f16(r)) { + return false; + } + tx_roots.push_back(r); + for (const ggml_tensor * tensor : classes[r]) { + ggml_hexagon_tensor_set_flags(const_cast(tensor), HTP_TENSOR_LOWERED_F16); + } + + auto uit = root_users.find(r); + if (uit != root_users.end()) { + for (size_t idx : uit->second) { + const int pos = touched_pos[idx]; + if (pos < 0) { + touched_pos[idx] = (int) touched.size(); + saved_node s; + s.idx = idx; + s.node = &nodes[idx]; + s.dirty = true; + memcpy(s.kernel_params, nodes[idx].kernel_params, sizeof(s.kernel_params)); + touched.push_back(s); + } else { + touched[pos].dirty = true; + } + } + } + return true; + }; + + apply_root(root); + + bool solved = false; + while (true) { + solved = true; + bool expanded = false; + for (size_t i = 0; i < touched.size(); ++i) { + if (!touched[i].dirty) { + continue; + } + htp_opnode * tnode = touched[i].node; + if (htp_lower_inplace_types_ok(*tnode) && htp_kparams_solve(sess, *tnode)) { + touched[i].dirty = false; + continue; + } + solved = false; + for (const ggml_tensor * out : tnode->outputs) { + const ggml_tensor * out_root = out ? htp_tensor_root(out) : nullptr; + if (out_root && can_lower(out_root) && apply_root(out_root)) { + expanded = true; + } + } + for (const ggml_tensor * inp : tnode->inputs) { + const ggml_tensor * inp_root = inp ? htp_tensor_root(inp) : nullptr; + if (inp_root && can_lower(inp_root) && is_selected_root(inp_root) && apply_root(inp_root)) { + expanded = true; + } + } + if (expanded) { + break; + } + } + if (solved || !expanded) { + break; + } + } + + for (const saved_node & s : touched) { + touched_pos[s.idx] = -1; + } + + if (!solved) { + for (const ggml_tensor * r : tx_roots) { + for (const ggml_tensor * tensor : classes[r]) { + ggml_hexagon_tensor_clear_flags(const_cast(tensor), HTP_TENSOR_LOWERED_F16); + } + } + for (saved_node & s : touched) { + memcpy(s.node->kernel_params, s.kernel_params, sizeof(s.kernel_params)); + } + return; + } + + for (const ggml_tensor * r : tx_roots) { + ++n_lowered_roots; + bytes_saved += ggml_nbytes(r) / 2; + if (htp_lower_is_mm_root(nodes, owner_idx, r)) { + ++n_lowered_mm; + } + } + }; + + for (const ggml_tensor * root : roots) { + if (can_lower(root) && is_selected_root(root)) { + try_lower_root(root); + } + } + + for (const ggml_tensor * root : roots) { + if (can_lower(root) && is_f16_consumer_seed(root)) { + try_lower_root(root); + } + } + + for (htp_opnode & node : nodes) { + htp_lower_opnode(sess, node); + } + + HEX_VERBOSE("ggml-hex: %s lower oplower=%d roots=%zu/%zu mm_out=%zu saved=%zuB\n", + htp_session_name(sess), opt_oplower, n_lowered_roots, n_candidates, n_lowered_mm, bytes_saved); +} diff --git a/ggml/src/ggml-hexagon/htp-lower.h b/ggml/src/ggml-hexagon/htp-lower.h new file mode 100644 index 000000000000..becb5532e812 --- /dev/null +++ b/ggml/src/ggml-hexagon/htp-lower.h @@ -0,0 +1,37 @@ +#ifndef HTP_LOWER_H +#define HTP_LOWER_H + +#include "ggml.h" + +#include +#include +#include + +struct ggml_cgraph; +struct ggml_hexagon_session; +struct htp_opnode; + +bool htp_rows_stride(const int64_t * ne, const size_t * nb, size_t * stride); +bool htp_matmul_can_collapse(const struct ggml_tensor * src0, const struct ggml_tensor * src1, const struct ggml_tensor * dst); +bool htp_matmul_add_can_collapse(const struct ggml_tensor * src0, const struct ggml_tensor * src1, const struct ggml_tensor * src2, const struct ggml_tensor * dst); +ggml_tensor htp_tensor_collapse_rows(const struct ggml_tensor * t); + +bool htp_dsv4_hc_pre_can_collapse(const struct ggml_tensor * x, const struct ggml_tensor * weights, const struct ggml_tensor * dst); +void htp_dsv4_hc_pre_collapse_tensors(const struct ggml_tensor * x, const struct ggml_tensor * weights, const struct ggml_tensor * dst, + struct ggml_tensor * x_c, struct ggml_tensor * w_c, struct ggml_tensor * d_c); + +bool htp_dsv4_hc_post_can_collapse(const struct ggml_tensor * x, const struct ggml_tensor * residual, const struct ggml_tensor * post, const struct ggml_tensor * comb, const struct ggml_tensor * dst); +void htp_dsv4_hc_post_collapse_tensors(const struct ggml_tensor * x, const struct ggml_tensor * residual, const struct ggml_tensor * post, const struct ggml_tensor * comb, const struct ggml_tensor * dst, + struct ggml_tensor * x_c, struct ggml_tensor * r_c, struct ggml_tensor * p_c, struct ggml_tensor * c_c, struct ggml_tensor * d_c); + +bool htp_lightning_indexer_can_collapse(const struct ggml_tensor * q, const struct ggml_tensor * k, const struct ggml_tensor * w, const struct ggml_tensor * m, const struct ggml_tensor * dst); +void htp_lightning_indexer_collapse_tensors(const struct ggml_tensor * q, const struct ggml_tensor * k, const struct ggml_tensor * w, const struct ggml_tensor * m, const struct ggml_tensor * dst, + struct ggml_tensor * q_c, struct ggml_tensor * k_c, struct ggml_tensor * w_c, struct ggml_tensor * m_c, struct ggml_tensor * dst_c); + +void htp_lower_opnode(const struct ggml_hexagon_session * sess, htp_opnode & node, struct ggml_tensor * scratch = nullptr); +void htp_lower_graph(const struct ggml_hexagon_session * sess, const struct ggml_cgraph * graph, std::vector & nodes); +void htp_lower_reset_graph(const struct ggml_cgraph * graph); +void htp_pack_tensor_lowered_f16(struct ggml_tensor * t, const void * src, size_t offset, size_t size); +void htp_unpack_tensor_lowered_f16(void * dst, const struct ggml_tensor * t, size_t offset, size_t size); + +#endif // HTP_LOWER_H diff --git a/ggml/src/ggml-hexagon/htp-opnode.cpp b/ggml/src/ggml-hexagon/htp-opnode.cpp index b7be0cea23c6..f9b98cdbf363 100644 --- a/ggml/src/ggml-hexagon/htp-opnode.cpp +++ b/ggml/src/ggml-hexagon/htp-opnode.cpp @@ -36,8 +36,18 @@ std::string htp_opnode::name() const { case HTP_OP_ALLREDUCE: return "ALLREDUCE"; case HTP_OP_ALLREDUCE_ADD: return "ALLREDUCE+ADD"; case HTP_OP_HADAMARD: return "MUL_MAT_HADAMARD"; - case HTP_OP_MUL_MAT_NX: return "MUL_MAT_NX"; - case HTP_OP_MUL_MAT_ID_NX: return "MUL_MAT_ID_NX"; + case HTP_OP_MUL_MAT_NX: return "MUL_MAT_NX"; + case HTP_OP_MUL_MAT_NX_GLU: { + const auto * kp = kparams(); + switch (kp->glu_op) { + case HTP_OP_GLU_SWIGLU: return "MUL_MAT_NX_SWIGLU"; + case HTP_OP_GLU_GEGLU: return "MUL_MAT_NX_GEGLU"; + case HTP_OP_GLU_GEGLU_QUICK: return "MUL_MAT_NX_GEGLU_QUICK"; + case HTP_OP_GLU_REGLU: return "MUL_MAT_NX_REGLU"; + default: return "MUL_MAT_NX_GLU"; + } + } + case HTP_OP_MUL_MAT_ID_NX: return "MUL_MAT_ID_NX"; case HTP_OP_ADD: case HTP_OP_SUB: case HTP_OP_MUL: @@ -146,26 +156,32 @@ static std::string format_kernel_params(const htp_opnode & node) { const size_t max_size = sizeof(str); if (node.opcode == HTP_OP_MUL_MAT || node.opcode == HTP_OP_MUL_MAT_ID || - node.opcode == HTP_OP_MUL_MAT_NX || node.opcode == HTP_OP_MUL_MAT_ID_NX || - node.opcode == HTP_OP_MUL_MAT_ADD) { + node.opcode == HTP_OP_MUL_MAT_NX || node.opcode == HTP_OP_MUL_MAT_NX_GLU || + node.opcode == HTP_OP_MUL_MAT_ID_NX || node.opcode == HTP_OP_MUL_MAT_ADD) { const auto * kparams = node.kparams(); - const char * path = "unknown"; int32_t type = kparams->kernel_type; - if (type == HTP_MM_KERNEL_HMX_2D || type == HTP_MM_KERNEL_HMX_BATCHED) { - path = (kparams->tile_size > 0) ? "hmx-tiled" : "hmx-flat"; - } else if (type == HTP_MM_KERNEL_HVX_F16_F16_VTCM || type == HTP_MM_KERNEL_HVX_F32_F32_VTCM || - type == HTP_MM_KERNEL_HVX_BF16_F32_VTCM) { - path = "hvx-flat"; - } else if (type == HTP_MM_KERNEL_HVX_QUANT_ROW || type == HTP_MM_KERNEL_HVX_QUANT_BLOCK) { - path = "hvx-tiled"; + if (htp_mm_kernel_is_hmx_w8a8(type)) { + snprintf(str, max_size, "hmx-w8a8 nhvx %u vtcm %u", (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size); + } else { + const char * path = "unknown"; + if (type == HTP_MM_KERNEL_HMX_2D || type == HTP_MM_KERNEL_HMX_BATCHED) { + path = (kparams->tile_size > 0) ? "hmx-tiled" : "hmx-flat"; + } else if (type == HTP_MM_KERNEL_HVX_F16_F16_VTCM || type == HTP_MM_KERNEL_HVX_F32_F32_VTCM || + type == HTP_MM_KERNEL_HVX_BF16_F32_VTCM) { + path = "hvx-flat"; + } else if (type == HTP_MM_KERNEL_HVX_QUANT_ROW || type == HTP_MM_KERNEL_HVX_QUANT_BLOCK) { + path = "hvx-tiled"; + } + snprintf(str, max_size, "%s nhvx %u vtcm %u", path, (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size); } - snprintf(str, max_size, "%s nhvx %u vtcm %u", path, (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size); } else if (node.opcode == HTP_OP_FLASH_ATTN_EXT) { const auto * kparams = node.kparams(); const char * path = "unknown"; int32_t type = kparams->kernel_type; - if (type == HTP_FA_KERNEL_HMX) { - path = kparams->u.hmx.pipeline ? "hmx-pipe" : "hmx-seq"; + if (type == HTP_FA_KERNEL_HMX_F16) { + path = kparams->u.hmx.pipeline ? "hmx-f16-pipe" : "hmx-f16-seq"; + } else if (type == HTP_FA_KERNEL_HMX_W8A8) { + path = kparams->u.hmx.pipeline ? "hmx-w8a8-pipe" : "hmx-w8a8-seq"; } else if (type == HTP_FA_KERNEL_HVX) { path = "hvx"; } @@ -182,7 +198,10 @@ static std::string format_kernel_params(const htp_opnode & node) { snprintf(str, max_size, "seq 0x%x -> 0x%x", (uint32_t) node.node->op_params[0], (uint32_t) node.node->op_params[1]); } else if (node.opcode == HTP_OP_SSM_CONV) { const auto * kparams = node.kparams(); - snprintf(str, max_size, "%s nhvx %u vtcm %u", kparams->n_t == 1 ? "decode" : "prefill", + const char * mode = kparams->token_major + ? (kparams->n_t == 1 ? "tok-decode" : "tok-prefill") + : (kparams->n_t == 1 ? "decode" : "prefill"); + snprintf(str, max_size, "%s nhvx %u vtcm %u", mode, (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size); } else if (node.opcode == HTP_OP_SSM_SCAN) { const auto * kparams = node.kparams(); @@ -240,10 +259,10 @@ static std::string format_kernel_params(const htp_opnode & node) { snprintf(str, max_size, "nhvx %u vtcm %u", (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size); } else if (node.opcode == HTP_OP_PAD) { const auto * kparams = node.kparams(); - snprintf(str, max_size, "k%d nhvx %u vtcm %u", (int) kparams->kernel_type, (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size); + snprintf(str, max_size, "k%d nhvx %u chunk %u vtcm %u", (int) kparams->kernel_type, (unsigned int) kparams->n_hvx, (unsigned int) kparams->chunk_elems, (unsigned int) kparams->vtcm_size); } else if (node.opcode == HTP_OP_CUMSUM) { const auto * kparams = node.kparams(); - snprintf(str, max_size, "%s nhvx %u vtcm %u", kparams->use_dma ? "dma" : "hvx", (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size); + snprintf(str, max_size, "nhvx %u chunk %u vtcm %u", (unsigned int) kparams->n_hvx, (unsigned int) kparams->chunk_elems, (unsigned int) kparams->vtcm_size); } else if (node.opcode == HTP_OP_TOP_K_MASK) { const auto * kparams = node.kparams(); const char * ktype_str = "?"; @@ -260,7 +279,7 @@ static std::string format_kernel_params(const htp_opnode & node) { snprintf(str, max_size, "k%d nhvx %u", (int) kparams->kernel_type, (unsigned int) kparams->n_hvx); } else if (node.opcode == HTP_OP_DIAG) { const auto * kparams = node.kparams(); - snprintf(str, max_size, "%s nhvx %u vtcm %u", kparams->use_dma ? "dma" : "hvx", (unsigned int) kparams->n_hvx, (unsigned int) kparams->vtcm_size); + snprintf(str, max_size, "nhvx %u chunk %u vtcm %u", (unsigned int) kparams->n_hvx, (unsigned int) kparams->chunk_elems, (unsigned int) kparams->vtcm_size); } else if (node.opcode == HTP_OP_SOLVE_TRI) { const auto * kparams = node.kparams(); snprintf(str, max_size, "%s nhvx %u", kparams->batched ? "batched" : "chunked", (unsigned int) kparams->n_hvx); diff --git a/ggml/src/ggml-hexagon/htp-opnode.h b/ggml/src/ggml-hexagon/htp-opnode.h index a30c5b600bcb..904c9f5a92cf 100644 --- a/ggml/src/ggml-hexagon/htp-opnode.h +++ b/ggml/src/ggml-hexagon/htp-opnode.h @@ -91,7 +91,7 @@ struct htp_opnode { // Build inputs (preserving optional nullptrs) if (htp_is_hadamard(this->node)) { this->inputs.push_back(this->node->src[1]); - } else { + } else if (this->node->op != GGML_OP_FILL) { int n_inputs = n_active_src(this->node); for (int i = 0; i < n_inputs; i++) { this->inputs.push_back(this->node->src[i]); diff --git a/ggml/src/ggml-hexagon/htp-repack.cpp b/ggml/src/ggml-hexagon/htp-repack.cpp index b60c1da63f89..57c3363efbae 100644 --- a/ggml/src/ggml-hexagon/htp-repack.cpp +++ b/ggml/src/ggml-hexagon/htp-repack.cpp @@ -15,169 +15,67 @@ # include #endif -// --- 4-bit block-32 nibble helpers (shared by Q4_0, IQ4_NL, Q4_1, Q5_0, Q5_1, MXFP4) --- - -static inline void unpack_nibbles_32(uint8_t * dst, const uint8_t * qs) { - for (unsigned int i = 0; i < 16; ++i) { - dst[i + 0] = qs[i] & 0x0F; - dst[i + 16] = qs[i] >> 4; - } -} - -static inline void pack_nibbles_32(uint8_t * qs, const uint8_t * src) { - for (unsigned int i = 0; i < 16; ++i) { - qs[i] = src[i + 0] | (src[i + 16] << 4); - } -} - -static inline void transpose_nibbles_to_tile(uint8_t * tile_dst, const uint8_t tile_quants[32][32]) { - for (int cp = 0; cp < 16; cp++) { - for (int row = 0; row < 32; row++) { - tile_dst[cp * 32 + row] = (tile_quants[row][2 * cp + 1] << 4) | tile_quants[row][2 * cp]; - } - } -} - -static inline void transpose_tile_to_nibbles(uint8_t tile_quants[32][32], const uint8_t * tile_src) { - for (int cp = 0; cp < 16; cp++) { - for (int row = 0; row < 32; row++) { - const uint8_t val = tile_src[cp * 32 + row]; - tile_quants[row][2 * cp + 0] = val & 0x0F; - tile_quants[row][2 * cp + 1] = val >> 4; - } - } -} - -// 5th-bit plane of one row (qh bit k = quant k), same bit layout as the Q5_K plane +// 5th-bit plane of one row (qh bit k = quant k), 4-K-grouped layout matching wb planes static inline void pack_q5_plane(uint8_t * plane, int row, uint32_t qh) { - for (int c = 0; c < 4; c++) { + for (int j = 0; j < 4; j++) { uint32_t v = 0; - for (int i = 0; i < 4; i++) { - v |= ((qh >> (8 * i + 2 * c)) & 3) << (2 * i); + for (int g = 0; g < 8; g++) { + v |= ((qh >> (4 * g + j)) & 1u) << g; } - plane[c * 32 + row] = (uint8_t) v; + plane[row * 4 + j] = (uint8_t) v; } } static inline uint32_t unpack_q5_plane(const uint8_t * plane, int row) { uint32_t qh = 0; - for (int c = 0; c < 4; c++) { - const uint32_t v = plane[c * 32 + row]; - for (int i = 0; i < 4; i++) { - qh |= ((v >> (2 * i)) & 3) << (8 * i + 2 * c); + for (int j = 0; j < 4; j++) { + const uint32_t v = plane[row * 4 + j]; + for (int g = 0; g < 8; g++) { + qh |= ((v >> g) & 1u) << (4 * g + j); } } return qh; } #if defined(__ARM_NEON) || defined(__aarch64__) -static void repack_neon_transpose8x8(const uint8x8_t rows[8], uint8x8_t columns[8]) { - const uint8x8x2_t t0 = vtrn_u8(rows[0], rows[1]); - const uint8x8x2_t t1 = vtrn_u8(rows[2], rows[3]); - const uint8x8x2_t t2 = vtrn_u8(rows[4], rows[5]); - const uint8x8x2_t t3 = vtrn_u8(rows[6], rows[7]); - const uint16x4x2_t t4 = vtrn_u16(vreinterpret_u16_u8(t0.val[0]), vreinterpret_u16_u8(t1.val[0])); - const uint16x4x2_t t5 = vtrn_u16(vreinterpret_u16_u8(t0.val[1]), vreinterpret_u16_u8(t1.val[1])); - const uint16x4x2_t t6 = vtrn_u16(vreinterpret_u16_u8(t2.val[0]), vreinterpret_u16_u8(t3.val[0])); - const uint16x4x2_t t7 = vtrn_u16(vreinterpret_u16_u8(t2.val[1]), vreinterpret_u16_u8(t3.val[1])); - const uint32x2x2_t t8 = vtrn_u32(vreinterpret_u32_u16(t4.val[0]), vreinterpret_u32_u16(t6.val[0])); - const uint32x2x2_t t9 = vtrn_u32(vreinterpret_u32_u16(t4.val[1]), vreinterpret_u32_u16(t6.val[1])); - const uint32x2x2_t ta = vtrn_u32(vreinterpret_u32_u16(t5.val[0]), vreinterpret_u32_u16(t7.val[0])); - const uint32x2x2_t tb = vtrn_u32(vreinterpret_u32_u16(t5.val[1]), vreinterpret_u32_u16(t7.val[1])); - columns[0] = vreinterpret_u8_u32(t8.val[0]); - columns[1] = vreinterpret_u8_u32(ta.val[0]); - columns[2] = vreinterpret_u8_u32(t9.val[0]); - columns[3] = vreinterpret_u8_u32(tb.val[0]); - columns[4] = vreinterpret_u8_u32(t8.val[1]); - columns[5] = vreinterpret_u8_u32(ta.val[1]); - columns[6] = vreinterpret_u8_u32(t9.val[1]); - columns[7] = vreinterpret_u8_u32(tb.val[1]); -} - -static uint8x8_t repack_neon_pack_4bit_pairs(uint8x8_t first, uint8x8_t second, bool high) { - const uint8x8x2_t separated = vuzp_u8(first, second); - const uint8x8_t mask = vdup_n_u8(0x0F); - uint8x8_t even = separated.val[0]; - uint8x8_t odd = separated.val[1]; - - if (high) { - even = vshr_n_u8(even, 4); - odd = vshr_n_u8(odd, 4); - } - - even = vand_u8(even, mask); - odd = vand_u8(odd, mask); - return vorr_u8(vshl_n_u8(odd, 4), even); -} - -static void repack_neon_4bit_rows(const uint8_t * qs[8], uint8_t * tile_dst, int row0) { - uint8x8_t low_rows[8]; - uint8x8_t high_rows[8]; - uint8x8_t columns[8]; - - for (int rr = 0; rr < 8; ++rr) { - const uint8x16_t packed = vld1q_u8(qs[rr]); - const uint8x8_t first = vget_low_u8(packed); - const uint8x8_t second = vget_high_u8(packed); - low_rows[rr] = repack_neon_pack_4bit_pairs(first, second, false); - high_rows[rr] = repack_neon_pack_4bit_pairs(first, second, true); - } - - repack_neon_transpose8x8(low_rows, columns); - for (int cp = 0; cp < 8; ++cp) { - vst1_u8(tile_dst + cp * 32 + row0, columns[cp]); - } - - repack_neon_transpose8x8(high_rows, columns); - for (int cp = 0; cp < 8; ++cp) { - vst1_u8(tile_dst + (cp + 8) * 32 + row0, columns[cp]); - } -} - -static void repack_neon_k4_rows(const uint8_t * qs[8], uint8_t * tile_dst, int row0, bool high) { - uint8x8_t first_rows[8]; - uint8x8_t second_rows[8]; - uint8x8_t columns[8]; - - for (int rr = 0; rr < 8; ++rr) { - first_rows[rr] = repack_neon_pack_4bit_pairs(vld1_u8(qs[rr]), vld1_u8(qs[rr] + 8), high); - second_rows[rr] = repack_neon_pack_4bit_pairs(vld1_u8(qs[rr] + 16), vld1_u8(qs[rr] + 24), high); - } - - repack_neon_transpose8x8(first_rows, columns); - for (int cp = 0; cp < 8; ++cp) { - vst1_u8(tile_dst + cp * 32 + row0, columns[cp]); - } - - repack_neon_transpose8x8(second_rows, columns); - for (int cp = 0; cp < 8; ++cp) { - vst1_u8(tile_dst + (cp + 8) * 32 + row0, columns[cp]); - } -} - -static void repack_neon_q8_rows(const uint8_t * qs[8], uint8_t * tile_dst, int row0) { - uint8x8_t rows[8]; - uint8x8_t columns[8]; - - for (int cp = 0; cp < 16; cp += 4) { - for (int rr = 0; rr < 8; ++rr) { - rows[rr] = vld1_u8(qs[rr] + 2 * cp); - } - repack_neon_transpose8x8(rows, columns); - - for (int pair = 0; pair < 4; ++pair) { - const uint8x8x2_t interleaved = vzip_u8(columns[2 * pair], columns[2 * pair + 1]); - uint8_t * dst = tile_dst + (cp + pair) * 64 + 2 * row0; - vst1_u8(dst, interleaved.val[0]); - vst1_u8(dst + 8, interleaved.val[1]); - } - } -} - static inline void repack_store_u32(uint8_t * dst, uint32_t v) { memcpy(dst, &v, sizeof(v)); } +static inline void repack_neon_4bit_wb_row(const uint8_t * qs, uint8_t * tile_dst, int row) { + const uint32x4_t w = vreinterpretq_u32_u8(vld1q_u8(qs)); + const uint32x2x2_t u = vuzp_u32(vget_low_u32(w), vget_high_u32(w)); + const uint8x8_t even = vreinterpret_u8_u32(u.val[0]); + const uint8x8_t odd = vreinterpret_u8_u32(u.val[1]); + const uint32x2_t lo = vreinterpret_u32_u8(vorr_u8(vand_u8(even, vdup_n_u8(0x0F)), vshl_n_u8(odd, 4))); + const uint32x2_t hi = vreinterpret_u32_u8(vorr_u8(vshr_n_u8(even, 4), vand_u8(odd, vdup_n_u8(0xF0)))); + repack_store_u32(tile_dst + 0 * 128 + row * 4, vget_lane_u32(lo, 0)); + repack_store_u32(tile_dst + 1 * 128 + row * 4, vget_lane_u32(lo, 1)); + repack_store_u32(tile_dst + 2 * 128 + row * 4, vget_lane_u32(hi, 0)); + repack_store_u32(tile_dst + 3 * 128 + row * 4, vget_lane_u32(hi, 1)); +} + +static inline void repack_neon_k4_wb_row(const uint8_t * qs_sub, uint8_t * tile_dst, int row, bool high) { + const uint32x4_t w0 = vreinterpretq_u32_u8(vld1q_u8(qs_sub)); + const uint32x4_t w1 = vreinterpretq_u32_u8(vld1q_u8(qs_sub + 16)); + const uint32x2x2_t u0 = vuzp_u32(vget_low_u32(w0), vget_high_u32(w0)); + const uint32x2x2_t u1 = vuzp_u32(vget_low_u32(w1), vget_high_u32(w1)); + const uint8x8_t even0 = vreinterpret_u8_u32(u0.val[0]); + const uint8x8_t odd0 = vreinterpret_u8_u32(u0.val[1]); + const uint8x8_t even1 = vreinterpret_u8_u32(u1.val[0]); + const uint8x8_t odd1 = vreinterpret_u8_u32(u1.val[1]); + const uint32x2_t p01 = vreinterpret_u32_u8(high + ? vorr_u8(vshr_n_u8(even0, 4), vand_u8(odd0, vdup_n_u8(0xF0))) + : vorr_u8(vand_u8(even0, vdup_n_u8(0x0F)), vshl_n_u8(odd0, 4))); + const uint32x2_t p23 = vreinterpret_u32_u8(high + ? vorr_u8(vshr_n_u8(even1, 4), vand_u8(odd1, vdup_n_u8(0xF0))) + : vorr_u8(vand_u8(even1, vdup_n_u8(0x0F)), vshl_n_u8(odd1, 4))); + repack_store_u32(tile_dst + 0 * 128 + row * 4, vget_lane_u32(p01, 0)); + repack_store_u32(tile_dst + 1 * 128 + row * 4, vget_lane_u32(p01, 1)); + repack_store_u32(tile_dst + 2 * 128 + row * 4, vget_lane_u32(p23, 0)); + repack_store_u32(tile_dst + 3 * 128 + row * 4, vget_lane_u32(p23, 1)); +} + static inline uint32x4_t repack_neon_transpose_2bit_4x4(uint32x4_t w) { uint32x4_t t = vandq_u32(veorq_u32(w, vshrq_n_u32(w, 6)), vdupq_n_u32(0x00CC00CCu)); w = veorq_u32(w, veorq_u32(t, vshlq_n_u32(t, 6))); @@ -262,19 +160,16 @@ static inline void repack_neon_q6_k(const block_q6_K * b, int kt_local, uint8_t } static inline void repack_neon_q5_k_qh(const uint8_t * qh, uint8_t hbit, uint8_t * plane, int row) { - static const uint8_t mask_bytes[16] = { 1, 2, 1, 2, 1, 2, 1, 2, 4, 8, 4, 8, 4, 8, 4, 8 }; - const uint8x16_t m0 = vld1q_u8(mask_bytes); + static const uint32_t mask_words[4] = { 0x01010101u, 0x02020202u, 0x04040404u, 0x08080808u }; + const uint8x16_t m0 = vreinterpretq_u8_u32(vld1q_u32(mask_words)); const uint8x16_t m1 = vshlq_n_u8(m0, 4); const uint8x16_t vbit = vdupq_n_u8(hbit); const uint8x16_t b0 = vandq_u8(vtstq_u8(vld1q_u8(qh + 0), vbit), m0); const uint8x16_t b1 = vandq_u8(vtstq_u8(vld1q_u8(qh + 16), vbit), m1); - const uint8x16_t b01 = vorrq_u8(b0, b1); - const uint8x8_t fold = vorr_u8(vget_low_u8(b01), vget_high_u8(b01)); - const uint8x8_t out = vpadd_u8(fold, fold); - plane[0 * 32 + row] = vget_lane_u8(out, 0); - plane[1 * 32 + row] = vget_lane_u8(out, 1); - plane[2 * 32 + row] = vget_lane_u8(out, 2); - plane[3 * 32 + row] = vget_lane_u8(out, 3); + const uint32x4_t b01 = vreinterpretq_u32_u8(vorrq_u8(b0, b1)); + const uint32x2_t f0 = vorr_u32(vget_low_u32(b01), vget_high_u32(b01)); + const uint32x2_t f1 = vpadd_u32(f0, f0); + repack_store_u32(plane + row * 4, vget_lane_u32(f1, 0)); } static inline uint16x8_t repack_neon_load_f16x8(const uint16_t * src) { @@ -457,53 +352,62 @@ static void unpack_from_tiled_grid_32(void * data, const ggml_tensor * t, size_t // --- Block-32 Quantized Types (Q4_0, IQ4_NL, Q4_1, Q5_0, Q5_1, Q8_0, MXFP4) --- +static inline void repack_4bit_wb_row(const uint8_t * qs, uint8_t * tile_dst, int row) { +#if defined(__ARM_NEON) || defined(__aarch64__) + repack_neon_4bit_wb_row(qs, tile_dst, row); +#else + for (int j = 0; j < 4; ++j) { + tile_dst[0 * 128 + row * 4 + j] = (uint8_t) (((qs[4 + j] & 0x0F) << 4) | (qs[0 + j] & 0x0F)); + tile_dst[1 * 128 + row * 4 + j] = (uint8_t) (((qs[12 + j] & 0x0F) << 4) | (qs[8 + j] & 0x0F)); + tile_dst[2 * 128 + row * 4 + j] = (uint8_t) ((qs[4 + j] & 0xF0) | (qs[0 + j] >> 4)); + tile_dst[3 * 128 + row * 4 + j] = (uint8_t) ((qs[12 + j] & 0xF0) | (qs[8 + j] >> 4)); + } +#endif +} + +static inline void unpack_4bit_wb_row(uint8_t * qs, const uint8_t * tile_src, int row) { + for (int j = 0; j < 4; ++j) { + const uint8_t p0 = tile_src[0 * 128 + row * 4 + j]; + const uint8_t p1 = tile_src[1 * 128 + row * 4 + j]; + const uint8_t p2 = tile_src[2 * 128 + row * 4 + j]; + const uint8_t p3 = tile_src[3 * 128 + row * 4 + j]; + qs[0 + j] = (uint8_t) ((p0 & 0x0F) | ((p2 & 0x0F) << 4)); + qs[4 + j] = (uint8_t) ((p0 >> 4) | (p2 & 0xF0)); + qs[8 + j] = (uint8_t) ((p1 & 0x0F) | ((p3 & 0x0F) << 4)); + qs[12 + j] = (uint8_t) ((p1 >> 4) | (p3 & 0xF0)); + } +} + static void repack_q4_0_tiled(ggml_tensor * t, const void * data, size_t offset, size_t size) { repack_to_tiled_grid_32(t, data, offset, size, HTP_TENSOR_TILE_SIZE_Q4_0, [](uint8_t * tile_dst, const block_q4_0 * src_slice, int64_t ne0, int64_t ne1, int64_t row_stride, int ct, int kt) { ggml_half * scale_dst = (ggml_half *) (tile_dst + 512); -#if defined(__ARM_NEON) || defined(__aarch64__) - if (ct * 32 + 32 <= ne1 && kt < ne0 / 32) { - for (int row0 = 0; row0 < 32; row0 += 8) { - const uint8_t * qs[8]; - for (int rr = 0; rr < 8; ++rr) { - qs[rr] = src_slice[(ct * 32 + row0 + rr) * row_stride + kt].qs; - } - repack_neon_4bit_rows(qs, tile_dst, row0); - } - - for (int row = 0; row < 32; ++row) { - scale_dst[row] = src_slice[(ct * 32 + row) * row_stride + kt].d; - } - return; - } -#endif - uint8_t tile_quants[32][32]; + const bool valid_kt = kt < ne0 / 32; for (int row = 0; row < 32; row++) { const int64_t r = ct * 32 + row; - if (r < ne1 && kt < ne0 / 32) { + if (r < ne1 && valid_kt) { const block_q4_0 & b = src_slice[r * row_stride + kt]; - unpack_nibbles_32(tile_quants[row], b.qs); + repack_4bit_wb_row(b.qs, tile_dst, row); scale_dst[row] = b.d; } else { - memset(tile_quants[row], 8, 32); + for (int i = 0; i < 4; ++i) { + memset(tile_dst + i * 128 + row * 4, 0x88, 4); + } scale_dst[row] = 0; } } - transpose_nibbles_to_tile(tile_dst, tile_quants); }); } static void repack_tiled_q4_0(void * data, const ggml_tensor * t, size_t offset, size_t size) { unpack_from_tiled_grid_32(data, t, offset, size, HTP_TENSOR_TILE_SIZE_Q4_0, [](block_q4_0 * dst_slice, const uint8_t * tile_src, int64_t ne0, int64_t start_row, int64_t end_row, int64_t row_stride, int ct, int kt) { - uint8_t tile_quants[32][32]; - transpose_tile_to_nibbles(tile_quants, tile_src); const ggml_half * scale_src = (const ggml_half *) (tile_src + 512); for (int row = 0; row < 32; row++) { const int64_t r = ct * 32 + row; if (r >= start_row && r < end_row && kt < ne0 / 32) { block_q4_0 & b = dst_slice[(r - start_row) * row_stride + kt]; - pack_nibbles_32(b.qs, tile_quants[row]); + unpack_4bit_wb_row(b.qs, tile_src, row); b.d = scale_src[row]; } } @@ -514,53 +418,34 @@ static void repack_q4_1_tiled(ggml_tensor * t, const void * data, size_t offset, repack_to_tiled_grid_32(t, data, offset, size, HTP_TENSOR_TILE_SIZE_Q4_1, [](uint8_t * tile_dst, const block_q4_1 * src_slice, int64_t ne0, int64_t ne1, int64_t row_stride, int ct, int kt) { ggml_half * scale_dst = (ggml_half *) (tile_dst + 512); -#if defined(__ARM_NEON) || defined(__aarch64__) - if (ct * 32 + 32 <= ne1 && kt < ne0 / 32) { - for (int row0 = 0; row0 < 32; row0 += 8) { - const uint8_t * qs[8]; - for (int rr = 0; rr < 8; ++rr) { - qs[rr] = src_slice[(ct * 32 + row0 + rr) * row_stride + kt].qs; - } - repack_neon_4bit_rows(qs, tile_dst, row0); - } - - for (int row = 0; row < 32; ++row) { - const block_q4_1 & src_block = src_slice[(ct * 32 + row) * row_stride + kt]; - scale_dst[2 * row + 0] = src_block.d; - scale_dst[2 * row + 1] = src_block.m; - } - return; - } -#endif - uint8_t tile_quants[32][32]; + const bool valid_kt = kt < ne0 / 32; for (int row = 0; row < 32; row++) { const int64_t r = ct * 32 + row; - if (r < ne1 && kt < ne0 / 32) { + if (r < ne1 && valid_kt) { const block_q4_1 & b = src_slice[r * row_stride + kt]; - unpack_nibbles_32(tile_quants[row], b.qs); + repack_4bit_wb_row(b.qs, tile_dst, row); scale_dst[2 * row + 0] = b.d; scale_dst[2 * row + 1] = b.m; } else { - memset(tile_quants[row], 0, 32); + for (int i = 0; i < 4; ++i) { + memset(tile_dst + i * 128 + row * 4, 0, 4); + } scale_dst[2 * row + 0] = 0; scale_dst[2 * row + 1] = 0; } } - transpose_nibbles_to_tile(tile_dst, tile_quants); }); } static void repack_tiled_q4_1(void * data, const ggml_tensor * t, size_t offset, size_t size) { unpack_from_tiled_grid_32(data, t, offset, size, HTP_TENSOR_TILE_SIZE_Q4_1, [](block_q4_1 * dst_slice, const uint8_t * tile_src, int64_t ne0, int64_t start_row, int64_t end_row, int64_t row_stride, int ct, int kt) { - uint8_t tile_quants[32][32]; - transpose_tile_to_nibbles(tile_quants, tile_src); const ggml_half * scale_src = (const ggml_half *) (tile_src + 512); for (int row = 0; row < 32; row++) { const int64_t r = ct * 32 + row; if (r >= start_row && r < end_row && kt < ne0 / 32) { block_q4_1 & b = dst_slice[(r - start_row) * row_stride + kt]; - pack_nibbles_32(b.qs, tile_quants[row]); + unpack_4bit_wb_row(b.qs, tile_src, row); b.d = scale_src[2 * row + 0]; b.m = scale_src[2 * row + 1]; } @@ -573,58 +458,37 @@ static void repack_q5_0_tiled(ggml_tensor * t, const void * data, size_t offset, [](uint8_t * tile_dst, const block_q5_0 * src_slice, int64_t ne0, int64_t ne1, int64_t row_stride, int ct, int kt) { uint8_t * plane_dst = tile_dst + 512; ggml_half * scale_dst = (ggml_half *) (tile_dst + 640); -#if defined(__ARM_NEON) || defined(__aarch64__) - if (ct * 32 + 32 <= ne1 && kt < ne0 / 32) { - for (int row0 = 0; row0 < 32; row0 += 8) { - const uint8_t * qs[8]; - for (int rr = 0; rr < 8; ++rr) { - qs[rr] = src_slice[(ct * 32 + row0 + rr) * row_stride + kt].qs; - } - repack_neon_4bit_rows(qs, tile_dst, row0); - } - - for (int row = 0; row < 32; ++row) { - const block_q5_0 & src_block = src_slice[(ct * 32 + row) * row_stride + kt]; - uint32_t qh; - memcpy(&qh, src_block.qh, sizeof(qh)); - pack_q5_plane(plane_dst, row, ~qh); - scale_dst[row] = src_block.d; - } - return; - } -#endif - uint8_t tile_quants[32][32]; + const bool valid_kt = kt < ne0 / 32; for (int row = 0; row < 32; row++) { const int64_t r = ct * 32 + row; - if (r < ne1 && kt < ne0 / 32) { + if (r < ne1 && valid_kt) { const block_q5_0 & b = src_slice[r * row_stride + kt]; - unpack_nibbles_32(tile_quants[row], b.qs); + repack_4bit_wb_row(b.qs, tile_dst, row); uint32_t qh; memcpy(&qh, b.qh, sizeof(qh)); pack_q5_plane(plane_dst, row, ~qh); scale_dst[row] = b.d; } else { - memset(tile_quants[row], 0, 32); - pack_q5_plane(plane_dst, row, 0); + for (int i = 0; i < 4; ++i) { + memset(tile_dst + i * 128 + row * 4, 0, 4); + } + memset(plane_dst + row * 4, 0, 4); scale_dst[row] = 0; } } - transpose_nibbles_to_tile(tile_dst, tile_quants); }); } static void repack_tiled_q5_0(void * data, const ggml_tensor * t, size_t offset, size_t size) { unpack_from_tiled_grid_32(data, t, offset, size, HTP_TENSOR_TILE_SIZE_Q5_0, [](block_q5_0 * dst_slice, const uint8_t * tile_src, int64_t ne0, int64_t start_row, int64_t end_row, int64_t row_stride, int ct, int kt) { - uint8_t tile_quants[32][32]; - transpose_tile_to_nibbles(tile_quants, tile_src); const uint8_t * plane_src = tile_src + 512; const ggml_half * scale_src = (const ggml_half *) (tile_src + 640); for (int row = 0; row < 32; row++) { const int64_t r = ct * 32 + row; if (r >= start_row && r < end_row && kt < ne0 / 32) { block_q5_0 & b = dst_slice[(r - start_row) * row_stride + kt]; - pack_nibbles_32(b.qs, tile_quants[row]); + unpack_4bit_wb_row(b.qs, tile_src, row); const uint32_t qh = ~unpack_q5_plane(plane_src, row); memcpy(b.qh, &qh, sizeof(qh)); b.d = scale_src[row]; @@ -639,61 +503,39 @@ static void repack_q5_1_tiled(ggml_tensor * t, const void * data, size_t offset, [](uint8_t * tile_dst, const block_q5_1 * src_slice, int64_t ne0, int64_t ne1, int64_t row_stride, int ct, int kt) { ggml_half * scale_dst = (ggml_half *) (tile_dst + 512); uint8_t * plane_dst = tile_dst + 640; -#if defined(__ARM_NEON) || defined(__aarch64__) - if (ct * 32 + 32 <= ne1 && kt < ne0 / 32) { - for (int row0 = 0; row0 < 32; row0 += 8) { - const uint8_t * qs[8]; - for (int rr = 0; rr < 8; ++rr) { - qs[rr] = src_slice[(ct * 32 + row0 + rr) * row_stride + kt].qs; - } - repack_neon_4bit_rows(qs, tile_dst, row0); - } - - for (int row = 0; row < 32; ++row) { - const block_q5_1 & src_block = src_slice[(ct * 32 + row) * row_stride + kt]; - uint32_t qh; - memcpy(&qh, src_block.qh, sizeof(qh)); - pack_q5_plane(plane_dst, row, qh); - scale_dst[2 * row + 0] = src_block.d; - scale_dst[2 * row + 1] = src_block.m; - } - return; - } -#endif - uint8_t tile_quants[32][32]; + const bool valid_kt = kt < ne0 / 32; for (int row = 0; row < 32; row++) { const int64_t r = ct * 32 + row; - if (r < ne1 && kt < ne0 / 32) { + if (r < ne1 && valid_kt) { const block_q5_1 & b = src_slice[r * row_stride + kt]; - unpack_nibbles_32(tile_quants[row], b.qs); + repack_4bit_wb_row(b.qs, tile_dst, row); uint32_t qh; memcpy(&qh, b.qh, sizeof(qh)); pack_q5_plane(plane_dst, row, qh); scale_dst[2 * row + 0] = b.d; scale_dst[2 * row + 1] = b.m; } else { - memset(tile_quants[row], 0, 32); - pack_q5_plane(plane_dst, row, 0); + for (int i = 0; i < 4; ++i) { + memset(tile_dst + i * 128 + row * 4, 0, 4); + } + memset(plane_dst + row * 4, 0, 4); scale_dst[2 * row + 0] = 0; scale_dst[2 * row + 1] = 0; } } - transpose_nibbles_to_tile(tile_dst, tile_quants); }); } static void repack_tiled_q5_1(void * data, const ggml_tensor * t, size_t offset, size_t size) { unpack_from_tiled_grid_32(data, t, offset, size, HTP_TENSOR_TILE_SIZE_Q5_1, [](block_q5_1 * dst_slice, const uint8_t * tile_src, int64_t ne0, int64_t start_row, int64_t end_row, int64_t row_stride, int ct, int kt) { - uint8_t tile_quants[32][32]; - transpose_tile_to_nibbles(tile_quants, tile_src); const ggml_half * scale_src = (const ggml_half *) (tile_src + 512); const uint8_t * plane_src = tile_src + 640; for (int row = 0; row < 32; row++) { const int64_t r = ct * 32 + row; if (r >= start_row && r < end_row && kt < ne0 / 32) { block_q5_1 & b = dst_slice[(r - start_row) * row_stride + kt]; - pack_nibbles_32(b.qs, tile_quants[row]); + unpack_4bit_wb_row(b.qs, tile_src, row); const uint32_t qh = unpack_q5_plane(plane_src, row); memcpy(b.qh, &qh, sizeof(qh)); b.d = scale_src[2 * row + 0]; @@ -706,50 +548,33 @@ static void repack_tiled_q5_1(void * data, const ggml_tensor * t, size_t offset, static void repack_mxfp4_tiled(ggml_tensor * t, const void * data, size_t offset, size_t size) { repack_to_tiled_grid_32(t, data, offset, size, HTP_TENSOR_TILE_SIZE_MXFP4, [](uint8_t * tile_dst, const block_mxfp4 * src_slice, int64_t ne0, int64_t ne1, int64_t row_stride, int ct, int kt) { - uint8_t * scale_dst = tile_dst + 512; -#if defined(__ARM_NEON) || defined(__aarch64__) - if (ct * 32 + 32 <= ne1 && kt < ne0 / 32) { - for (int row0 = 0; row0 < 32; row0 += 8) { - const uint8_t * qs[8]; - for (int rr = 0; rr < 8; ++rr) { - qs[rr] = src_slice[(ct * 32 + row0 + rr) * row_stride + kt].qs; - } - repack_neon_4bit_rows(qs, tile_dst, row0); - } - - for (int row = 0; row < 32; ++row) { - scale_dst[row] = src_slice[(ct * 32 + row) * row_stride + kt].e; - } - return; - } -#endif - uint8_t tile_quants[32][32]; + uint8_t * scale_dst = tile_dst + 512; + const bool valid_kt = kt < ne0 / 32; for (int row = 0; row < 32; row++) { const int64_t r = ct * 32 + row; - if (r < ne1 && kt < ne0 / 32) { + if (r < ne1 && valid_kt) { const block_mxfp4 & b = src_slice[r * row_stride + kt]; - unpack_nibbles_32(tile_quants[row], b.qs); + repack_4bit_wb_row(b.qs, tile_dst, row); scale_dst[row] = b.e; } else { - memset(tile_quants[row], 0, 32); + for (int i = 0; i < 4; ++i) { + memset(tile_dst + i * 128 + row * 4, 0, 4); + } scale_dst[row] = 0; } } - transpose_nibbles_to_tile(tile_dst, tile_quants); }); } static void repack_tiled_mxfp4(void * data, const ggml_tensor * t, size_t offset, size_t size) { unpack_from_tiled_grid_32(data, t, offset, size, HTP_TENSOR_TILE_SIZE_MXFP4, [](block_mxfp4 * dst_slice, const uint8_t * tile_src, int64_t ne0, int64_t start_row, int64_t end_row, int64_t row_stride, int ct, int kt) { - uint8_t tile_quants[32][32]; - transpose_tile_to_nibbles(tile_quants, tile_src); const uint8_t * scale_src = tile_src + 512; for (int row = 0; row < 32; row++) { const int64_t r = ct * 32 + row; if (r >= start_row && r < end_row && kt < ne0 / 32) { block_mxfp4 & b = dst_slice[(r - start_row) * row_stride + kt]; - pack_nibbles_32(b.qs, tile_quants[row]); + unpack_4bit_wb_row(b.qs, tile_src, row); b.e = scale_src[row]; } } @@ -760,35 +585,21 @@ static void repack_q8_0_tiled(ggml_tensor * t, const void * data, size_t offset, repack_to_tiled_grid_32(t, data, offset, size, HTP_TENSOR_TILE_SIZE_Q8_0, [](uint8_t * tile_dst, const block_q8_0 * src_slice, int64_t ne0, int64_t ne1, int64_t row_stride, int ct, int kt) { ggml_half * scale_dst = (ggml_half *) (tile_dst + 1024); -#if defined(__ARM_NEON) || defined(__aarch64__) - if (ct * 32 + 32 <= ne1 && kt < ne0 / 32) { - for (int row0 = 0; row0 < 32; row0 += 8) { - const uint8_t * qs[8]; - for (int rr = 0; rr < 8; ++rr) { - qs[rr] = (const uint8_t *) src_slice[(ct * 32 + row0 + rr) * row_stride + kt].qs; - } - repack_neon_q8_rows(qs, tile_dst, row0); - } - - for (int row = 0; row < 32; ++row) { - scale_dst[row] = src_slice[(ct * 32 + row) * row_stride + kt].d; - } - return; - } -#endif - for (int cp = 0; cp < 16; cp++) { - const int col0 = cp * 2; - const int col1 = col0 + 1; - for (int row = 0; row < 32; row++) { - const int64_t r = ct * 32 + row; - const block_q8_0 * b = (r < ne1 && kt < ne0 / 32) ? &src_slice[r * row_stride + kt] : nullptr; - tile_dst[cp * 64 + 2 * row + 0] = b ? b->qs[col0] : 0; - tile_dst[cp * 64 + 2 * row + 1] = b ? b->qs[col1] : 0; - } - } + const bool valid_kt = kt < ne0 / 32; for (int row = 0; row < 32; row++) { const int64_t r = ct * 32 + row; - scale_dst[row] = (r < ne1 && kt < ne0 / 32) ? src_slice[r * row_stride + kt].d : 0; + if (r < ne1 && valid_kt) { + const block_q8_0 & b = src_slice[r * row_stride + kt]; + for (int p = 0; p < 8; ++p) { + memcpy(tile_dst + p * 128 + row * 4, b.qs + p * 4, 4); + } + scale_dst[row] = b.d; + } else { + for (int p = 0; p < 8; ++p) { + memset(tile_dst + p * 128 + row * 4, 0, 4); + } + scale_dst[row] = 0; + } } }); } @@ -796,23 +607,15 @@ static void repack_q8_0_tiled(ggml_tensor * t, const void * data, size_t offset, static void repack_tiled_q8_0(void * data, const ggml_tensor * t, size_t offset, size_t size) { unpack_from_tiled_grid_32(data, t, offset, size, HTP_TENSOR_TILE_SIZE_Q8_0, [](block_q8_0 * dst_slice, const uint8_t * tile_src, int64_t ne0, int64_t start_row, int64_t end_row, int64_t row_stride, int ct, int kt) { - for (int cp = 0; cp < 16; cp++) { - const int col0 = cp * 2; - const int col1 = col0 + 1; - for (int row = 0; row < 32; row++) { - const int64_t r = ct * 32 + row; - if (r >= start_row && r < end_row && kt < ne0 / 32) { - block_q8_0 & b = dst_slice[(r - start_row) * row_stride + kt]; - b.qs[col0] = tile_src[cp * 64 + 2 * row + 0]; - b.qs[col1] = tile_src[cp * 64 + 2 * row + 1]; - } - } - } const ggml_half * scale_src = (const ggml_half *) (tile_src + 1024); for (int row = 0; row < 32; row++) { const int64_t r = ct * 32 + row; if (r >= start_row && r < end_row && kt < ne0 / 32) { - dst_slice[(r - start_row) * row_stride + kt].d = scale_src[row]; + block_q8_0 & b = dst_slice[(r - start_row) * row_stride + kt]; + for (int p = 0; p < 8; ++p) { + memcpy(b.qs + p * 4, tile_src + p * 128 + row * 4, 4); + } + b.d = scale_src[row]; } } }); @@ -1414,46 +1217,42 @@ static inline void pack_k4_scales_mins(uint8_t * scales, ggml_half * d, ggml_hal } } -template -static inline void repack_k4_quants(uint8_t * tile_dst, const BlockT * b, int row, int kt_local, - int64_t sb_per_row, bool use_neon) { +static inline void repack_k4_wb_row(const uint8_t * qs_sub, uint8_t * tile_dst, int row, bool high) { #if defined(__ARM_NEON) || defined(__aarch64__) - if (use_neon) { - if ((row & 7) == 0) { - const uint8_t * qs[8]; - for (int rr = 0; rr < 8; ++rr) { - qs[rr] = b[rr * sb_per_row].qs + (kt_local / 2) * 32; - } - repack_neon_k4_rows(qs, tile_dst, row, (kt_local & 1) != 0); + repack_neon_k4_wb_row(qs_sub, tile_dst, row, high); +#else + const int shift = high ? 4 : 0; + for (int p = 0; p < 4; ++p) { + for (int j = 0; j < 4; ++j) { + const uint8_t lo = (qs_sub[p * 8 + j] >> shift) & 0x0F; + const uint8_t hi = (qs_sub[p * 8 + 4 + j] >> shift) & 0x0F; + tile_dst[p * 128 + row * 4 + j] = (uint8_t) ((hi << 4) | lo); } - return; } -#else - GGML_UNUSED(sb_per_row); - GGML_UNUSED(use_neon); #endif - const uint8_t * qs_sub = b->qs + (kt_local / 2) * 32; - const int shift = (kt_local & 1) ? 4 : 0; +} - for (int cp = 0; cp < 16; cp++) { - const uint8_t q0 = (qs_sub[2 * cp + 0] >> shift) & 0x0F; - const uint8_t q1 = (qs_sub[2 * cp + 1] >> shift) & 0x0F; - tile_dst[cp * 32 + row] = (uint8_t) ((q1 << 4) | q0); +static inline void unpack_k4_wb_row(uint8_t * qs_sub, const uint8_t * tile_src, int row, bool high) { + const int shift = high ? 4 : 0; + for (int p = 0; p < 4; ++p) { + for (int j = 0; j < 4; ++j) { + const uint8_t val = tile_src[p * 128 + row * 4 + j]; + qs_sub[p * 8 + j] |= (uint8_t) ((val & 0x0F) << shift); + qs_sub[p * 8 + 4 + j] |= (uint8_t) ((val >> 4) << shift); + } } } static void repack_q4_K_tiled(ggml_tensor * t, const void * data, size_t offset, size_t size) { - const int64_t sb_per_row = t->ne[0] / QK_K; - const bool use_neon = (t->ne[1] % 8 == 0); repack_kquant_to_tiled_grid(t, data, offset, size, HTP_TENSOR_TILE_SIZE_Q4_K, - [sb_per_row, use_neon](uint8_t * tile_dst, const block_q4_K * b, int row, int kt_local) { + [](uint8_t * tile_dst, const block_q4_K * b, int row, int kt_local) { const float d = GGML_FP16_TO_FP32(b->d); const float dmin = GGML_FP16_TO_FP32(b->dmin); uint8_t sc, m; get_scale_min_k4(kt_local, b->scales, &sc, &m); - repack_k4_quants(tile_dst, b, row, kt_local, sb_per_row, use_neon); + repack_k4_wb_row(b->qs + (kt_local / 2) * 32, tile_dst, row, (kt_local & 1) != 0); ggml_half * scale_dst = (ggml_half *) (tile_dst + 512); scale_dst[2 * row + 0] = GGML_FP32_TO_FP16(d * (float) sc); @@ -1471,14 +1270,7 @@ static void repack_tiled_q4_K(void * data, const ggml_tensor * t, size_t offset, const uint8_t * tile_src = sb_tiles + kt_local * tile_size; const ggml_half * scale_src = (const ggml_half *) (tile_src + 512); - uint8_t * qs_sub = b->qs + (kt_local / 2) * 32; - const int shift = (kt_local & 1) ? 4 : 0; - - for (int cp = 0; cp < 16; cp++) { - const uint8_t val = tile_src[cp * 32 + row]; - qs_sub[2 * cp + 0] |= (uint8_t) ((val & 0x0F) << shift); - qs_sub[2 * cp + 1] |= (uint8_t) ((val >> 4) << shift); - } + unpack_k4_wb_row(b->qs + (kt_local / 2) * 32, tile_src, row, (kt_local & 1) != 0); const float D = GGML_FP16_TO_FP32(scale_src[2 * row + 0]); const float M = GGML_FP16_TO_FP32(scale_src[2 * row + 1]); @@ -1491,10 +1283,8 @@ static void repack_tiled_q4_K(void * data, const ggml_tensor * t, size_t offset, } static void repack_q5_K_tiled(ggml_tensor * t, const void * data, size_t offset, size_t size) { - const int64_t sb_per_row = t->ne[0] / QK_K; - const bool use_neon = (t->ne[1] % 8 == 0); repack_kquant_to_tiled_grid(t, data, offset, size, HTP_TENSOR_TILE_SIZE_Q5_K, - [sb_per_row, use_neon](uint8_t * tile_dst, const block_q5_K * b, int row, int kt_local) { + [](uint8_t * tile_dst, const block_q5_K * b, int row, int kt_local) { const float d = GGML_FP16_TO_FP32(b->d); const float dmin = GGML_FP16_TO_FP32(b->dmin); uint8_t * plane = tile_dst + 640; @@ -1502,21 +1292,20 @@ static void repack_q5_K_tiled(ggml_tensor * t, const void * data, size_t offset, uint8_t sc, m; get_scale_min_k4(kt_local, b->scales, &sc, &m); - repack_k4_quants(tile_dst, b, row, kt_local, sb_per_row, use_neon); + repack_k4_wb_row(b->qs + (kt_local / 2) * 32, tile_dst, row, (kt_local & 1) != 0); const uint8_t hbit = (uint8_t) (1 << kt_local); #if defined(__ARM_NEON) || defined(__aarch64__) repack_neon_q5_k_qh(b->qh, hbit, plane, row); #else - for (int cp = 0; cp < 16; cp++) { - const int i = cp / 4; - const int lane = (cp % 4) * 32 + row; - if (b->qh[2 * cp + 0] & hbit) { - plane[lane] |= (uint8_t) (1 << (2 * i)); - } - if (b->qh[2 * cp + 1] & hbit) { - plane[lane] |= (uint8_t) (1 << (2 * i + 1)); + for (int j = 0; j < 4; ++j) { + uint8_t v = 0; + for (int g = 0; g < 8; ++g) { + if (b->qh[4 * g + j] & hbit) { + v |= (uint8_t) (1u << g); + } } + plane[row * 4 + j] = v; } #endif @@ -1537,22 +1326,15 @@ static void repack_tiled_q5_K(void * data, const ggml_tensor * t, size_t offset, const uint8_t * plane = tile_src + 640; const ggml_half * scale_src = (const ggml_half *) (tile_src + 512); - uint8_t * qs_sub = b->qs + (kt_local / 2) * 32; - const int shift = (kt_local & 1) ? 4 : 0; - const uint8_t hbit = (uint8_t) (1 << kt_local); - - for (int cp = 0; cp < 16; cp++) { - const uint8_t val = tile_src[cp * 32 + row]; - qs_sub[2 * cp + 0] |= (uint8_t) ((val & 0x0F) << shift); - qs_sub[2 * cp + 1] |= (uint8_t) ((val >> 4) << shift); + unpack_k4_wb_row(b->qs + (kt_local / 2) * 32, tile_src, row, (kt_local & 1) != 0); - const int i = cp / 4; - const int lane = (cp % 4) * 32 + row; - if (plane[lane] & (1 << (2 * i))) { - b->qh[2 * cp + 0] |= hbit; - } - if (plane[lane] & (1 << (2 * i + 1))) { - b->qh[2 * cp + 1] |= hbit; + const uint8_t hbit = (uint8_t) (1 << kt_local); + for (int j = 0; j < 4; ++j) { + const uint8_t v = plane[row * 4 + j]; + for (int g = 0; g < 8; ++g) { + if (v & (1u << g)) { + b->qh[4 * g + j] |= hbit; + } } } @@ -1714,25 +1496,32 @@ static void repack_tiled_iq2_xxs(void * data, const ggml_tensor * t, size_t offs }); } -// --- NVFP4 (576 B tile: Q4_0-style nibble transpose + 2 UE4M3 scales per row, one block-64 = 2 k-tiles) --- +// --- NVFP4 (576 B tile: 4-K-grouped wb nibbles + 2 UE4M3 scales per row, one block-64 = 2 k-tiles) --- #define NVFP4_TILE_NIBBLE_BYTES 512 #define NVFP4_KT_PER_BLOCK (QK_NVFP4 / 32) #define NVFP4_SUB_PER_KT (32 / QK_NVFP4_SUB) -// element e (0..31) of k-tile kt_half lives in sub-block 2*kt_half + e/16, low nibble if (e%16) < 8 -static inline uint8_t nvfp4_get_nibble(const block_nvfp4 & b, int kt_half, int e) { - const int sub = kt_half * NVFP4_SUB_PER_KT + e / QK_NVFP4_SUB; - const int j = e % (QK_NVFP4_SUB / 2); - const uint8_t q = b.qs[sub * (QK_NVFP4_SUB / 2) + j]; - return (e % QK_NVFP4_SUB) < QK_NVFP4_SUB / 2 ? (q & 0x0F) : (q >> 4); +static inline void repack_nvfp4_wb_row(const uint8_t * qs, uint8_t * tile_dst, int row) { + for (int u = 0; u < NVFP4_SUB_PER_KT; ++u) { + const uint8_t * qs_sub = qs + u * (QK_NVFP4_SUB / 2); + for (int j = 0; j < 4; ++j) { + tile_dst[(2 * u + 0) * 128 + row * 4 + j] = (uint8_t) (((qs_sub[4 + j] & 0x0F) << 4) | (qs_sub[j] & 0x0F)); + tile_dst[(2 * u + 1) * 128 + row * 4 + j] = (uint8_t) ((qs_sub[4 + j] & 0xF0) | (qs_sub[j] >> 4)); + } + } } -static inline void nvfp4_set_nibble(block_nvfp4 & b, int kt_half, int e, uint8_t v) { - const int sub = kt_half * NVFP4_SUB_PER_KT + e / QK_NVFP4_SUB; - const int j = e % (QK_NVFP4_SUB / 2); - uint8_t & q = b.qs[sub * (QK_NVFP4_SUB / 2) + j]; - q |= (e % QK_NVFP4_SUB) < QK_NVFP4_SUB / 2 ? v : (uint8_t) (v << 4); +static inline void unpack_nvfp4_wb_row(uint8_t * qs, const uint8_t * tile_src, int row) { + for (int u = 0; u < NVFP4_SUB_PER_KT; ++u) { + uint8_t * qs_sub = qs + u * (QK_NVFP4_SUB / 2); + for (int j = 0; j < 4; ++j) { + const uint8_t p0 = tile_src[(2 * u + 0) * 128 + row * 4 + j]; + const uint8_t p1 = tile_src[(2 * u + 1) * 128 + row * 4 + j]; + qs_sub[j] = (uint8_t) ((p0 & 0x0F) | ((p1 & 0x0F) << 4)); + qs_sub[4 + j] = (uint8_t) ((p0 >> 4) | (p1 & 0xF0)); + } + } } static void repack_nvfp4_tiled(ggml_tensor * t, const void * data, size_t offset, size_t size) { @@ -1752,7 +1541,7 @@ static void repack_nvfp4_tiled(ggml_tensor * t, const void * data, size_t offset uint8_t * dst_slice = (uint8_t *) t->data + slice * matrix_size; repack_parallel_for_ct(matrix_size, (int) n_col_tiles, [&](int ct0, int ct1) { - // Padding rows and OR-ed nibbles require zeroed tiles + // Padding rows require zeroed tiles memset(dst_slice + (size_t) ct0 * ct_bytes, 0, (size_t) (ct1 - ct0) * ct_bytes); const int64_t r0 = (int64_t) ct0 * 32; @@ -1764,9 +1553,7 @@ static void repack_nvfp4_tiled(ggml_tensor * t, const void * data, size_t offset const block_nvfp4 & b = src_slice[r * blocks_per_row + blk]; for (int h = 0; h < NVFP4_KT_PER_BLOCK; ++h) { uint8_t * tile = dst_slice + (ct * n_k_tiles + blk * NVFP4_KT_PER_BLOCK + h) * HTP_TENSOR_TILE_SIZE_NVFP4; - for (int e = 0; e < 32; ++e) { - tile[(e / 2) * 32 + row] |= (uint8_t) (nvfp4_get_nibble(b, h, e) << (4 * (e & 1))); - } + repack_nvfp4_wb_row(b.qs + h * 16, tile, row); for (int u = 0; u < NVFP4_SUB_PER_KT; ++u) { tile[NVFP4_TILE_NIBBLE_BYTES + u * 32 + row] = b.d[h * NVFP4_SUB_PER_KT + u]; } @@ -1802,9 +1589,7 @@ static void repack_tiled_nvfp4(void * data, const ggml_tensor * t, size_t offset for (int h = 0; h < NVFP4_KT_PER_BLOCK; ++h) { const uint8_t * tile = (const uint8_t *) t->data + slice * matrix_size + (ct * n_k_tiles + blk * NVFP4_KT_PER_BLOCK + h) * HTP_TENSOR_TILE_SIZE_NVFP4; - for (int e = 0; e < 32; ++e) { - nvfp4_set_nibble(b, h, e, (tile[(e / 2) * 32 + row] >> (4 * (e & 1))) & 0x0F); - } + unpack_nvfp4_wb_row(b.qs + h * 16, tile, row); for (int u = 0; u < NVFP4_SUB_PER_KT; ++u) { b.d[h * NVFP4_SUB_PER_KT + u] = tile[NVFP4_TILE_NIBBLE_BYTES + u * 32 + row]; } diff --git a/ggml/src/ggml-hexagon/htp/CMakeLists.txt b/ggml/src/ggml-hexagon/htp/CMakeLists.txt index 029f9df99010..409adae2b29d 100644 --- a/ggml/src/ggml-hexagon/htp/CMakeLists.txt +++ b/ggml/src/ggml-hexagon/htp/CMakeLists.txt @@ -19,8 +19,9 @@ add_library(${HTP_LIB} SHARED htp_iface_skel.c work-queue.c dma-queue.c + dma-proxy.c hmx-queue.c - htp-dcache.c + htp-tensor.c matmul-ops.c flash-attn-ops.c gated-delta-net-ops.c diff --git a/ggml/src/ggml-hexagon/htp/allreduce-ops.c b/ggml/src/ggml-hexagon/htp/allreduce-ops.c index 1b95917ae0e7..8af3b1e8fca3 100644 --- a/ggml/src/ggml-hexagon/htp/allreduce-ops.c +++ b/ggml/src/ggml-hexagon/htp/allreduce-ops.c @@ -1,7 +1,3 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include #include diff --git a/ggml/src/ggml-hexagon/htp/argsort-ops.c b/ggml/src/ggml-hexagon/htp/argsort-ops.c index af260595494b..d8560e5aec95 100644 --- a/ggml/src/ggml-hexagon/htp/argsort-ops.c +++ b/ggml/src/ggml-hexagon/htp/argsort-ops.c @@ -92,273 +92,518 @@ static void quicksort_values_indices_desc(float * values, int32_t * indices, int } } -static inline uint32_t top_k_max_value_index(const float * values, uint32_t n, float * value) { - int32_t max_idx = 0; - hvx_argmax_f32(values, n, 0, value, &max_idx); - return (uint32_t) max_idx; -} - static const int32_t argsort_ramp_lut[32] __attribute__((aligned(VLEN))) = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 }; +static const uint32_t top_k_bit_lut[32] __attribute__((aligned(VLEN))) = { + 1u << 0, 1u << 1, 1u << 2, 1u << 3, 1u << 4, 1u << 5, 1u << 6, 1u << 7, + 1u << 8, 1u << 9, 1u << 10, 1u << 11, 1u << 12, 1u << 13, 1u << 14, 1u << 15, + 1u << 16, 1u << 17, 1u << 18, 1u << 19, 1u << 20, 1u << 21, 1u << 22, 1u << 23, + 1u << 24, 1u << 25, 1u << 26, 1u << 27, 1u << 28, 1u << 29, 1u << 30, 1u << 31 +}; + static inline void init_indices_ramp(int32_t * indices_buf, uint32_t count, uint32_t base) { const HVX_Vector ind_init_vec = Q6_Vw_vadd_VwVw(*(const HVX_Vector *) argsort_ramp_lut, Q6_V_vsplat_R(base)); const HVX_Vector ind_diff_vec = Q6_V_vsplat_R(32); HVX_Vector * indices_buf_vec = (HVX_Vector *) indices_buf; - uint32_t num_vecs = count / 32; + uint32_t num_vecs = count >> 5; HVX_Vector curr_ind_vec = ind_init_vec; for (uint32_t j = 0; j < num_vecs; j++) { indices_buf_vec[j] = curr_ind_vec; curr_ind_vec = Q6_Vw_vadd_VwVw(curr_ind_vec, ind_diff_vec); } - uint32_t rem = count % 32; + uint32_t rem = count & 31u; if (rem > 0) { hvx_vec_store_a((void *) &indices_buf_vec[num_vecs], rem * sizeof(int32_t), curr_ind_vec); } } +// Map IEEE-754 float lanes to signed int32 keys preserving +INF > finite > -INF (0x807fffff) > NaN (0x80000001) > pad (0x80000000). +__attribute__((always_inline)) +static inline HVX_Vector float_to_ord_key_vec(HVX_Vector vf) { + const HVX_Vector v_abs = Q6_V_vand_VV(vf, Q6_V_vsplat_R(0x7fffffff)); + const HVX_VectorPred q_nan = Q6_Q_vcmp_gt_VwVw(v_abs, Q6_V_vsplat_R(0x7f800000)); + const HVX_Vector v_sign = Q6_Vw_vasr_VwR(vf, 31); + const HVX_Vector v_flip = Q6_Vuw_vlsr_VuwR(v_sign, 1); + const HVX_Vector v_key = Q6_V_vxor_VV(vf, v_flip); + return Q6_V_vmux_QVV(q_nan, Q6_V_vsplat_R((int32_t) 0x80000001u), v_key); +} + +static inline float ord_key_to_float(int32_t key) { + const uint32_t u = ((uint32_t) key == 0x80000001u) + ? 0x7fc00000u + : ((key < 0) ? ((uint32_t) key ^ 0x7fffffffu) : (uint32_t) key); + union { uint32_t u; float f; } conv = { .u = u }; + return conv.f; +} + +__attribute__((always_inline)) +static inline uint32_t hvx_pred_i32_to_bits(HVX_VectorPred q, HVX_Vector v_bit_lut) { + HVX_Vector m = Q6_V_vand_QV(q, v_bit_lut); + m = Q6_V_vor_VV(m, Q6_V_vror_VR(m, 64)); + m = Q6_V_vor_VV(m, Q6_V_vror_VR(m, 32)); + m = Q6_V_vor_VV(m, Q6_V_vror_VR(m, 16)); + m = Q6_V_vor_VV(m, Q6_V_vror_VR(m, 8)); + m = Q6_V_vor_VV(m, Q6_V_vror_VR(m, 4)); + return (uint32_t) Q6_R_vextract_VR(m, 0); +} + +__attribute__((noinline)) +static int32_t top_k_argmax_hvx(const float * restrict vals, uint32_t n, uint32_t idx_base, float * restrict out_val) { + const HVX_Vector * restrict vvals = (const HVX_Vector *) vals; + const uint32_t n_full = n >> 5; + const uint32_t rem = n & 31u; + const HVX_Vector v_step = Q6_V_vsplat_R(32); + const HVX_Vector v_pad = Q6_V_vsplat_R((int32_t) 0x80000000u); + + HVX_Vector v_idx = Q6_Vw_vadd_VwVw(*(const HVX_Vector *) argsort_ramp_lut, Q6_V_vsplat_R((int32_t) idx_base)); + HVX_Vector v_best_key = v_pad; + HVX_Vector v_best_idx = v_idx; + + for (uint32_t v = 0; v < n_full; v++) { + const HVX_Vector vk = float_to_ord_key_vec(vvals[v]); + const HVX_VectorPred q = Q6_Q_vcmp_gt_VwVw(vk, v_best_key); + v_best_key = Q6_V_vmux_QVV(q, vk, v_best_key); + v_best_idx = Q6_V_vmux_QVV(q, v_idx, v_best_idx); + v_idx = Q6_Vw_vadd_VwVw(v_idx, v_step); + } + if (rem > 0) { + const HVX_VectorPred q_tail = Q6_Q_vsetq2_R(rem * sizeof(int32_t)); + const HVX_Vector vk = Q6_V_vmux_QVV(q_tail, float_to_ord_key_vec(vvals[n_full]), v_pad); + const HVX_VectorPred q = Q6_Q_vcmp_gt_VwVw(vk, v_best_key); + v_best_key = Q6_V_vmux_QVV(q, vk, v_best_key); + v_best_idx = Q6_V_vmux_QVV(q, v_idx, v_best_idx); + } + + #pragma clang loop unroll(full) + for (int shift = 64; shift >= 4; shift >>= 1) { + const HVX_Vector rk = Q6_V_vror_VR(v_best_key, shift); + const HVX_Vector ri = Q6_V_vror_VR(v_best_idx, shift); + const HVX_VectorPred q_gt = Q6_Q_vcmp_gt_VwVw(rk, v_best_key); + const HVX_VectorPred q_eq = Q6_Q_vcmp_eq_VwVw(rk, v_best_key); + const HVX_VectorPred q_idx = Q6_Q_vcmp_gt_VwVw(v_best_idx, ri); + const HVX_VectorPred q_win = Q6_Q_or_QQ(q_gt, Q6_Q_and_QQ(q_eq, q_idx)); + v_best_key = Q6_V_vmux_QVV(q_win, rk, v_best_key); + v_best_idx = Q6_V_vmux_QVV(q_win, ri, v_best_idx); + } + + if (out_val) { + *out_val = ord_key_to_float((int32_t) Q6_R_vextract_VR(v_best_key, 0)); + } + return (int32_t) Q6_R_vextract_VR(v_best_idx, 0); +} + __attribute__((always_inline)) static inline void vec_cas(HVX_Vector * X_val, HVX_Vector * X_idx, HVX_Vector * Y_val, HVX_Vector * Y_idx, bool asc) { - HVX_VectorPred pred = asc ? Q6_Q_vcmp_gt_VsfVsf(*X_val, *Y_val) - : Q6_Q_vcmp_gt_VsfVsf(*Y_val, *X_val); - HVX_Vector next_X_val = Q6_V_vmux_QVV(pred, *Y_val, *X_val); - HVX_Vector next_Y_val = Q6_V_vmux_QVV(pred, *X_val, *Y_val); - HVX_Vector next_X_idx = Q6_V_vmux_QVV(pred, *Y_idx, *X_idx); - HVX_Vector Y_tmp_idx = Q6_V_vmux_QVV(pred, *X_idx, *Y_idx); + asm volatile("" : "+v"(*X_val), "+v"(*X_idx), "+v"(*Y_val), "+v"(*Y_idx)); + const HVX_Vector lhs = asc ? *X_val : *Y_val; + const HVX_Vector rhs = asc ? *Y_val : *X_val; + const HVX_VectorPred pred = Q6_Q_vcmp_gt_VsfVsf(lhs, rhs); + const HVX_Vector next_X_val = Q6_V_vmux_QVV(pred, *Y_val, *X_val); + const HVX_Vector next_Y_val = Q6_V_vmux_QVV(pred, *X_val, *Y_val); + const HVX_Vector next_X_idx = Q6_V_vmux_QVV(pred, *Y_idx, *X_idx); + const HVX_Vector next_Y_idx = Q6_V_vmux_QVV(pred, *X_idx, *Y_idx); *X_val = next_X_val; *Y_val = next_Y_val; *X_idx = next_X_idx; - *Y_idx = Y_tmp_idx; + *Y_idx = next_Y_idx; + asm volatile("" : "+v"(*X_val), "+v"(*X_idx), "+v"(*Y_val), "+v"(*Y_idx)); } __attribute__((always_inline)) -static inline void bitonic_cas_32(HVX_Vector * V, HVX_Vector * I, int d, HVX_VectorPred dir_mask, HVX_Vector idx_vec, HVX_Vector zero_vec) { - HVX_VectorPred mask_left; - HVX_Vector V_rot_left, V_rot_right; - HVX_Vector I_rot_left, I_rot_right; - - if (d == 1) { - mask_left = Q6_Q_vcmp_eq_VwVw(Q6_V_vand_VV(idx_vec, Q6_V_vsplat_R(1)), zero_vec); - V_rot_left = Q6_V_vror_VR(*V, 4); - V_rot_right = Q6_V_vror_VR(*V, 124); - I_rot_left = Q6_V_vror_VR(*I, 4); - I_rot_right = Q6_V_vror_VR(*I, 124); - } else if (d == 2) { - mask_left = Q6_Q_vcmp_eq_VwVw(Q6_V_vand_VV(idx_vec, Q6_V_vsplat_R(2)), zero_vec); - V_rot_left = Q6_V_vror_VR(*V, 8); - V_rot_right = Q6_V_vror_VR(*V, 120); - I_rot_left = Q6_V_vror_VR(*I, 8); - I_rot_right = Q6_V_vror_VR(*I, 120); - } else if (d == 4) { - mask_left = Q6_Q_vcmp_eq_VwVw(Q6_V_vand_VV(idx_vec, Q6_V_vsplat_R(4)), zero_vec); - V_rot_left = Q6_V_vror_VR(*V, 16); - V_rot_right = Q6_V_vror_VR(*V, 112); - I_rot_left = Q6_V_vror_VR(*I, 16); - I_rot_right = Q6_V_vror_VR(*I, 112); - } else if (d == 8) { - mask_left = Q6_Q_vcmp_eq_VwVw(Q6_V_vand_VV(idx_vec, Q6_V_vsplat_R(8)), zero_vec); - V_rot_left = Q6_V_vror_VR(*V, 32); - V_rot_right = Q6_V_vror_VR(*V, 96); - I_rot_left = Q6_V_vror_VR(*I, 32); - I_rot_right = Q6_V_vror_VR(*I, 96); - } else { - mask_left = Q6_Q_vcmp_eq_VwVw(Q6_V_vand_VV(idx_vec, Q6_V_vsplat_R(16)), zero_vec); - V_rot_left = Q6_V_vror_VR(*V, 64); - V_rot_right = Q6_V_vror_VR(*V, 64); - I_rot_left = Q6_V_vror_VR(*I, 64); - I_rot_right = Q6_V_vror_VR(*I, 64); - } - - HVX_Vector V_paired = Q6_V_vmux_QVV(mask_left, V_rot_left, V_rot_right); - HVX_Vector I_paired = Q6_V_vmux_QVV(mask_left, I_rot_left, I_rot_right); - - HVX_VectorPred V_gt_Vpaired = Q6_Q_vcmp_gt_VsfVsf(*V, V_paired); - HVX_VectorPred Vpaired_gt_V = Q6_Q_vcmp_gt_VsfVsf(V_paired, *V); - HVX_VectorPred mask_right = Q6_Q_not_Q(mask_left); - HVX_VectorPred Q_asc = Q6_Q_or_QQ( - Q6_Q_and_QQ(mask_left, V_gt_Vpaired), - Q6_Q_and_QQ(Vpaired_gt_V, mask_right) - ); - HVX_VectorPred Q_swap = Q6_Q_or_QQ( - Q6_Q_and_QQ(dir_mask, Q_asc), - Q6_Q_and_QQ(Q6_Q_not_Q(dir_mask), Q6_Q_not_Q(Q_asc)) +static inline void bitonic_cas_32(HVX_Vector * V, HVX_Vector * I, int d, int s, int stage_d, bool asc, HVX_Vector idx_vec, HVX_Vector zero_vec) { + HVX_Vector idx = idx_vec; + int flip = asc ? 0 : d; + asm volatile("" : "+v"(*V), "+v"(*I), "+v"(idx), "+r"(d), "+r"(flip)); + + const HVX_Vector v_ctrl = Q6_Vb_vsplat_R(d << 2); + const HVX_Vector V_paired = Q6_V_vdelta_VV(*V, v_ctrl); + const HVX_Vector I_paired = Q6_V_vdelta_VV(*I, v_ctrl); + + const HVX_Vector v_rhs = (s < 5) ? Q6_Vuw_vlsr_VuwR(idx, s - stage_d) : Q6_V_vsplat_R(flip); + const HVX_Vector v_lane_x = Q6_V_vxor_VV(idx, v_rhs); + const HVX_VectorPred want_max = Q6_Q_vcmp_gt_VwVw(Q6_V_vand_VV(v_lane_x, Q6_V_vsplat_R(d)), zero_vec); + const HVX_VectorPred V_gt_P = Q6_Q_vcmp_gt_VsfVsf(*V, V_paired); + const HVX_VectorPred P_gt_V = Q6_Q_vcmp_gt_VsfVsf(V_paired, *V); + const HVX_VectorPred Q_swap = Q6_Q_or_QQ( + Q6_Q_and_QQ(want_max, P_gt_V), + Q6_Q_and_QQn(V_gt_P, want_max) ); *V = Q6_V_vmux_QVV(Q_swap, V_paired, *V); *I = Q6_V_vmux_QVV(Q_swap, I_paired, *I); + asm volatile("" : "+v"(*V), "+v"(*I)); } __attribute__((always_inline)) static inline void bitonic_sort_generic_hvx(uint8_t * values, uint8_t * indices, int K, bool asc_order) { - HVX_Vector V[32]; - HVX_Vector I[32]; + HVX_Vector V[8]; + HVX_Vector I[8]; - HVX_Vector zero_vec = Q6_V_vzero(); - HVX_Vector idx_vec = *(const HVX_Vector *) argsort_ramp_lut; + const HVX_Vector zero_vec = Q6_V_vzero(); + const HVX_Vector idx_vec = *(const HVX_Vector *) argsort_ramp_lut; + #pragma clang loop unroll(full) for (int v = 0; v < K; v++) { V[v] = *(HVX_Vector *)(values + v * 128); I[v] = Q6_Vw_vadd_VwVw(idx_vec, Q6_V_vsplat_R(v * 32)); } - HVX_VectorPred pred_all_1s = Q6_Q_vcmp_eq_VwVw(zero_vec, zero_vec); - HVX_VectorPred pred_all_0s = Q6_Q_not_Q(pred_all_1s); - int M = 5; - while ((1 << (M - 5)) < K) M++; + while ((1 << (M - 5)) < K) { + M++; + } + #pragma clang loop unroll(full) for (int s = 1; s <= M; s++) { + #pragma clang loop unroll(full) for (int stage_d = s - 1; stage_d >= 0; stage_d--) { - int d = 1 << stage_d; + const int d = 1 << stage_d; if (d >= 32) { - int v_dist = d / 32; + const int v_dist = d >> 5; + #pragma clang loop unroll(full) for (int v1 = 0; v1 < K; v1++) { if ((v1 & v_dist) == 0) { - int v2 = v1 + v_dist; - bool asc = (s < M) ? ((((v1 * 32) >> s) % 2) == 0) : asc_order; + const int v2 = v1 + v_dist; + const bool asc = (s < M) ? ((((v1 * 32) >> s) & 1) == 0) : asc_order; vec_cas(&V[v1], &I[v1], &V[v2], &I[v2], asc); } } } else { - if (s < 5) { - HVX_VectorPred dir_mask = Q6_Q_vcmp_eq_VwVw(Q6_V_vand_VV(idx_vec, Q6_V_vsplat_R(1 << s)), zero_vec); - for (int v = 0; v < K; v++) { - bitonic_cas_32(&V[v], &I[v], d, dir_mask, idx_vec, zero_vec); - } - } else { - for (int v = 0; v < K; v++) { - bool asc = (s < M) ? ((((v * 32) >> s) % 2) == 0) : asc_order; - HVX_VectorPred dir_mask = asc ? pred_all_1s : pred_all_0s; - bitonic_cas_32(&V[v], &I[v], d, dir_mask, idx_vec, zero_vec); - } + #pragma clang loop unroll(full) + for (int v = 0; v < K; v++) { + const bool asc = (s < M) ? ((((v * 32) >> s) & 1) == 0) : asc_order; + bitonic_cas_32(&V[v], &I[v], d, s, stage_d, asc, idx_vec, zero_vec); } } } } + #pragma clang loop unroll(full) for (int v = 0; v < K; v++) { *(HVX_Vector *)(values + v * 128) = V[v]; *(HVX_Vector *)(indices + v * 128) = I[v]; } } -static void bitonic_sort_vtcm_desc(uint8_t * values, uint8_t * indices, uint32_t n_vec, bool init_indices) { - HVX_Vector zero_vec = Q6_V_vzero(); - HVX_Vector idx_vec = *(const HVX_Vector *) argsort_ramp_lut; +__attribute__((always_inline)) +static inline void vec_cas_i32(HVX_Vector * X_val, HVX_Vector * X_idx, HVX_Vector * Y_val, HVX_Vector * Y_idx, bool asc) { + asm volatile("" : "+v"(*X_val), "+v"(*X_idx), "+v"(*Y_val), "+v"(*Y_idx)); + const HVX_Vector lhs = asc ? *X_val : *Y_val; + const HVX_Vector rhs = asc ? *Y_val : *X_val; + const HVX_VectorPred pred = Q6_Q_vcmp_gt_VwVw(lhs, rhs); + const HVX_Vector next_X_val = Q6_V_vmux_QVV(pred, *Y_val, *X_val); + const HVX_Vector next_Y_val = Q6_V_vmux_QVV(pred, *X_val, *Y_val); + const HVX_Vector next_X_idx = Q6_V_vmux_QVV(pred, *Y_idx, *X_idx); + const HVX_Vector next_Y_idx = Q6_V_vmux_QVV(pred, *X_idx, *Y_idx); + *X_val = next_X_val; + *Y_val = next_Y_val; + *X_idx = next_X_idx; + *Y_idx = next_Y_idx; + asm volatile("" : "+v"(*X_val), "+v"(*X_idx), "+v"(*Y_val), "+v"(*Y_idx)); +} - HVX_VectorPred pred_all_1s = Q6_Q_vcmp_eq_VwVw(zero_vec, zero_vec); - HVX_VectorPred pred_all_0s = Q6_Q_not_Q(pred_all_1s); +__attribute__((always_inline)) +static inline void bitonic_cas_32_i32(HVX_Vector * V, HVX_Vector * I, int d, int s, int stage_d, bool asc, HVX_Vector idx_vec, HVX_Vector zero_vec) { + HVX_Vector idx = idx_vec; + int flip = asc ? 0 : d; + asm volatile("" : "+v"(*V), "+v"(*I), "+v"(idx), "+r"(d), "+r"(flip)); + + const HVX_Vector v_ctrl = Q6_Vb_vsplat_R(d << 2); + const HVX_Vector V_paired = Q6_V_vdelta_VV(*V, v_ctrl); + const HVX_Vector I_paired = Q6_V_vdelta_VV(*I, v_ctrl); + + const HVX_Vector v_rhs = (s < 5) ? Q6_Vuw_vlsr_VuwR(idx, s - stage_d) : Q6_V_vsplat_R(flip); + const HVX_Vector v_lane_x = Q6_V_vxor_VV(idx, v_rhs); + const HVX_VectorPred want_max = Q6_Q_vcmp_gt_VwVw(Q6_V_vand_VV(v_lane_x, Q6_V_vsplat_R(d)), zero_vec); + const HVX_VectorPred V_gt_P = Q6_Q_vcmp_gt_VwVw(*V, V_paired); + const HVX_VectorPred P_gt_V = Q6_Q_vcmp_gt_VwVw(V_paired, *V); + const HVX_VectorPred Q_swap = Q6_Q_or_QQ( + Q6_Q_and_QQ(want_max, P_gt_V), + Q6_Q_and_QQn(V_gt_P, want_max) + ); - if (init_indices) { - for (uint32_t v = 0; v < n_vec; v++) { - HVX_Vector idx = Q6_Vw_vadd_VwVw(idx_vec, Q6_V_vsplat_R(v * 32)); - *(HVX_Vector *)(indices + v * 128) = idx; + *V = Q6_V_vmux_QVV(Q_swap, V_paired, *V); + *I = Q6_V_vmux_QVV(Q_swap, I_paired, *I); + asm volatile("" : "+v"(*V), "+v"(*I)); +} + +__attribute__((always_inline)) +static inline void bitonic_sort_top_k_hvx(const float * restrict values, int32_t * restrict indices, uint32_t n, uint32_t k, int K) { + HVX_Vector V[8]; + HVX_Vector I[8]; + + const HVX_Vector * restrict vvals = (const HVX_Vector *) values; + const HVX_Vector zero_vec = Q6_V_vzero(); + const HVX_Vector idx_vec = *(const HVX_Vector *) argsort_ramp_lut; + const HVX_Vector v_pad = Q6_V_vsplat_R((int32_t) 0x80000000u); + const uint32_t n_full = n >> 5; + const uint32_t rem = n & 31u; + + #pragma clang loop unroll(full) + for (int v = 0; v < K; v++) { + if ((uint32_t) v < n_full) { + V[v] = float_to_ord_key_vec(vvals[v]); + } else if ((uint32_t) v == n_full && rem > 0u) { + const HVX_VectorPred q_tail = Q6_Q_vsetq2_R(rem * sizeof(int32_t)); + V[v] = Q6_V_vmux_QVV(q_tail, float_to_ord_key_vec(vvals[v]), v_pad); + } else { + V[v] = v_pad; } + I[v] = Q6_Vw_vadd_VwVw(idx_vec, Q6_V_vsplat_R(v * 32)); } int M = 5; - while ((1u << (M - 5)) < n_vec) M++; + while ((1 << (M - 5)) < K) { + M++; + } + #pragma clang loop unroll(full) for (int s = 1; s <= M; s++) { + #pragma clang loop unroll(full) for (int stage_d = s - 1; stage_d >= 0; stage_d--) { - int d = 1 << stage_d; + const int d = 1 << stage_d; if (d >= 32) { - uint32_t v_dist = d / 32; - for (uint32_t v1 = 0; v1 < n_vec; v1++) { + const int v_dist = d >> 5; + #pragma clang loop unroll(full) + for (int v1 = 0; v1 < K; v1++) { if ((v1 & v_dist) == 0) { - uint32_t v2 = v1 + v_dist; - bool asc = (s < M) ? ((((v1 * 32) >> s) % 2) == 0) : false; + const int v2 = v1 + v_dist; + const bool asc = (s < M) ? ((((v1 * 32) >> s) & 1) == 0) : false; + vec_cas_i32(&V[v1], &I[v1], &V[v2], &I[v2], asc); + } + } + } else { + #pragma clang loop unroll(full) + for (int v = 0; v < K; v++) { + const bool asc = (s < M) ? ((((v * 32) >> s) & 1) == 0) : false; + bitonic_cas_32_i32(&V[v], &I[v], d, s, stage_d, asc, idx_vec, zero_vec); + } + } + } + } + + HVX_Vector * restrict vout = (HVX_Vector *) indices; + const uint32_t k_vecs = (k + 31u) >> 5; + #pragma clang loop unroll(full) + for (int v = 0; v < K; v++) { + if ((uint32_t) v < k_vecs) { + vout[v] = I[v]; + } + } +} + +__attribute__((noinline)) +static void sort32_top_k_hvx(const float * restrict values, int32_t * restrict indices, uint32_t n, uint32_t k) { + bitonic_sort_top_k_hvx(values, indices, n, k, 1); +} - HVX_Vector Vv1 = *(HVX_Vector *)(values + v1 * 128); - HVX_Vector Iv1 = *(HVX_Vector *)(indices + v1 * 128); - HVX_Vector Vv2 = *(HVX_Vector *)(values + v2 * 128); - HVX_Vector Iv2 = *(HVX_Vector *)(indices + v2 * 128); +__attribute__((noinline)) +static void sort64_top_k_hvx(const float * restrict values, int32_t * restrict indices, uint32_t n, uint32_t k) { + bitonic_sort_top_k_hvx(values, indices, n, k, 2); +} - vec_cas(&Vv1, &Iv1, &Vv2, &Iv2, asc); +__attribute__((noinline)) +static void sort128_top_k_hvx(const float * restrict values, int32_t * restrict indices, uint32_t n, uint32_t k) { + bitonic_sort_top_k_hvx(values, indices, n, k, 4); +} - *(HVX_Vector *)(values + v1 * 128) = Vv1; - *(HVX_Vector *)(indices + v1 * 128) = Iv1; - *(HVX_Vector *)(values + v2 * 128) = Vv2; - *(HVX_Vector *)(indices + v2 * 128) = Iv2; - } - } +__attribute__((noinline)) +static void sort256_top_k_hvx(const float * restrict values, int32_t * restrict indices, uint32_t n, uint32_t k) { + bitonic_sort_top_k_hvx(values, indices, n, k, 8); +} + +__attribute__((noinline)) +static void sort64_i32_desc(int32_t * restrict keys, int32_t * restrict indices) { + HVX_Vector * restrict vk = (HVX_Vector *) keys; + HVX_Vector * restrict vi = (HVX_Vector *) indices; + HVX_Vector V[2] = { vk[0], vk[1] }; + HVX_Vector I[2] = { vi[0], vi[1] }; + + const HVX_Vector zero_vec = Q6_V_vzero(); + const HVX_Vector idx_vec = *(const HVX_Vector *) argsort_ramp_lut; + + #pragma clang loop unroll(full) + for (int s = 1; s <= 6; s++) { + #pragma clang loop unroll(full) + for (int stage_d = s - 1; stage_d >= 0; stage_d--) { + const int d = 1 << stage_d; + if (d >= 32) { + vec_cas_i32(&V[0], &I[0], &V[1], &I[1], false); } else { - if (s < 5) { - HVX_VectorPred dir_mask = Q6_Q_vcmp_eq_VwVw(Q6_V_vand_VV(idx_vec, Q6_V_vsplat_R(1 << s)), zero_vec); - for (uint32_t v = 0; v < n_vec; v++) { - HVX_Vector Vv = *(HVX_Vector *)(values + v * 128); - HVX_Vector Iv = *(HVX_Vector *)(indices + v * 128); + #pragma clang loop unroll(full) + for (int v = 0; v < 2; v++) { + const bool asc = (s < 6) ? (v == 0) : false; + bitonic_cas_32_i32(&V[v], &I[v], d, s, stage_d, asc, idx_vec, zero_vec); + } + } + } + } - bitonic_cas_32(&Vv, &Iv, d, dir_mask, idx_vec, zero_vec); + vk[0] = V[0]; + vk[1] = V[1]; + vi[0] = I[0]; + vi[1] = I[1]; +} - *(HVX_Vector *)(values + v * 128) = Vv; - *(HVX_Vector *)(indices + v * 128) = Iv; - } - } else { - for (uint32_t v = 0; v < n_vec; v++) { - bool asc = (s < M) ? ((((v * 32) >> s) % 2) == 0) : false; - HVX_VectorPred dir_mask = asc ? pred_all_1s : pred_all_0s; +__attribute__((noinline)) +static void bitonic_sort_vtcm(uint8_t * restrict values, uint8_t * restrict indices, uint32_t n_vec, bool init_indices, bool asc_order) { + const HVX_Vector zero_vec = Q6_V_vzero(); + const HVX_Vector idx_vec = *(const HVX_Vector *) argsort_ramp_lut; - HVX_Vector Vv = *(HVX_Vector *)(values + v * 128); - HVX_Vector Iv = *(HVX_Vector *)(indices + v * 128); + if (init_indices) { + for (uint32_t v = 0; v < n_vec; v++) { + *(HVX_Vector *)(indices + v * 128) = Q6_Vw_vadd_VwVw(idx_vec, Q6_V_vsplat_R(v * 32)); + } + } - bitonic_cas_32(&Vv, &Iv, d, dir_mask, idx_vec, zero_vec); + int M = 5; + while ((1u << (M - 5)) < n_vec) { + M++; + } - *(HVX_Vector *)(values + v * 128) = Vv; - *(HVX_Vector *)(indices + v * 128) = Iv; - } + for (int s = 1; s <= M; s++) { + for (int stage_d = s - 1; stage_d >= 5; stage_d--) { + const uint32_t v_dist = 1u << (stage_d - 5); + for (uint32_t v1 = 0; v1 < n_vec; v1++) { + if ((v1 & v_dist) == 0u) { + const uint32_t v2 = v1 + v_dist; + const bool asc = (s < M) ? ((((v1 * 32u) >> s) & 1u) == 0u) : asc_order; + + HVX_Vector Vv1 = *(HVX_Vector *)(values + v1 * 128); + HVX_Vector Iv1 = *(HVX_Vector *)(indices + v1 * 128); + HVX_Vector Vv2 = *(HVX_Vector *)(values + v2 * 128); + HVX_Vector Iv2 = *(HVX_Vector *)(indices + v2 * 128); + + vec_cas(&Vv1, &Iv1, &Vv2, &Iv2, asc); + + *(HVX_Vector *)(values + v1 * 128) = Vv1; + *(HVX_Vector *)(indices + v1 * 128) = Iv1; + *(HVX_Vector *)(values + v2 * 128) = Vv2; + *(HVX_Vector *)(indices + v2 * 128) = Iv2; } } } + + // Fuse intra-vector butterfly stages d = 16, 8, 4, 2, 1 into one VTCM load/store per vector. + for (uint32_t v = 0; v < n_vec; v++) { + HVX_Vector Vv = *(HVX_Vector *)(values + v * 128); + HVX_Vector Iv = *(HVX_Vector *)(indices + v * 128); + const bool asc = (s < M) ? ((((v * 32u) >> s) & 1u) == 0u) : asc_order; + + if (s >= 5) { + bitonic_cas_32(&Vv, &Iv, 16, s, 4, asc, idx_vec, zero_vec); + } + if (s >= 4) { + bitonic_cas_32(&Vv, &Iv, 8, s, 3, asc, idx_vec, zero_vec); + } + if (s >= 3) { + bitonic_cas_32(&Vv, &Iv, 4, s, 2, asc, idx_vec, zero_vec); + } + if (s >= 2) { + bitonic_cas_32(&Vv, &Iv, 2, s, 1, asc, idx_vec, zero_vec); + } + bitonic_cas_32(&Vv, &Iv, 1, s, 0, asc, idx_vec, zero_vec); + + *(HVX_Vector *)(values + v * 128) = Vv; + *(HVX_Vector *)(indices + v * 128) = Iv; + } } } -// top-k of one row held in VTCM, k <= 64. Keeps a sorted list of the k best, rejects 256-float blocks with one max-reduce. -// Writes k values and k indices (ties: first seen wins). Slots with no finite value get -INF and index 0. -static void top_k_scan(const float * vals, uint32_t n, uint32_t k, float * out_v, int32_t * out_i) { - float best_v[64]; - int32_t best_i[64]; +__attribute__((noinline)) +static void top_k_scan(const float * restrict vals, uint32_t n, uint32_t k, float * restrict out_v, int32_t * restrict out_i) { + float best_v[64]; + int32_t best_i[64]; uint32_t cnt = 0; float thr = -INFINITY; - const uint32_t blk = 256; + const HVX_Vector v_one = Q6_V_vsplat_R(1); + const HVX_Vector v_bit_lut = *(const HVX_Vector *) top_k_bit_lut; + const HVX_Vector v_ninf = hvx_vec_splat_f32(-INFINITY); + + const uint32_t blk = 256u; for (uint32_t off = 0; off < n; off += blk) { const uint32_t bn = MIN(blk, n - off); - if (hvx_reduce_max_f32((const uint8_t *) (vals + off), bn) <= thr) { + const HVX_Vector v_thr_blk = hvx_vec_splat_f32(thr); + HVX_Vector v_any = Q6_V_vzero(); + + for (uint32_t vi = 0; vi < bn; vi += 32u) { + const uint32_t vn = MIN(32u, bn - vi); + HVX_Vector vv = *(const HVX_Vector *)(vals + off + vi); + if (vn < 32u) { + const HVX_VectorPred q_tail = Q6_Q_vsetq2_R(vn * sizeof(float)); + vv = Q6_V_vmux_QVV(q_tail, vv, v_ninf); + } + const HVX_VectorPred q_gt = Q6_Q_vcmp_gt_VsfVsf(vv, v_thr_blk); + v_any = Q6_V_vor_VV(v_any, Q6_V_vand_QV(q_gt, v_one)); + } + v_any = Q6_V_vor_VV(v_any, Q6_V_vror_VR(v_any, 64)); + v_any = Q6_V_vor_VV(v_any, Q6_V_vror_VR(v_any, 32)); + v_any = Q6_V_vor_VV(v_any, Q6_V_vror_VR(v_any, 16)); + v_any = Q6_V_vor_VV(v_any, Q6_V_vror_VR(v_any, 8)); + v_any = Q6_V_vor_VV(v_any, Q6_V_vror_VR(v_any, 4)); + if (Q6_R_vextract_VR(v_any, 0) == 0) { continue; } - for (uint32_t vi = 0; vi < bn; vi += 32) { - const uint32_t vn = MIN(32, bn - vi); - HVX_VectorAlias v_local; - v_local.v = hvx_vmem(vals + off + vi); - for (uint32_t i = 0; i < vn; i++) { - const float v = v_local.fp32[i]; - if (!(v > thr)) continue; - uint32_t pos = cnt < k ? cnt++ : k - 1; - while (pos > 0 && best_v[pos - 1] < v) { - best_v[pos] = best_v[pos - 1]; - best_i[pos] = best_i[pos - 1]; + + for (uint32_t vi = 0; vi < bn; vi += 32u) { + const uint32_t vn = MIN(32u, bn - vi); + HVX_Vector vv = *(const HVX_Vector *)(vals + off + vi); + if (vn < 32u) { + const HVX_VectorPred q_tail = Q6_Q_vsetq2_R(vn * sizeof(float)); + vv = Q6_V_vmux_QVV(q_tail, vv, v_ninf); + } + const HVX_VectorPred q_gt = Q6_Q_vcmp_gt_VsfVsf(vv, hvx_vec_splat_f32(thr)); + uint32_t mask = hvx_pred_i32_to_bits(q_gt, v_bit_lut); + while (mask != 0u) { + const uint32_t bit = (uint32_t) __builtin_ctz(mask); + mask &= mask - 1u; + union { int32_t i; float f; } u = { .i = Q6_R_vextract_VR(vv, (int) (bit * 4u)) }; + const float v = u.f; + if (!(v > thr)) { + continue; + } + uint32_t pos = cnt < k ? cnt++ : k - 1u; + while (pos > 0u && best_v[pos - 1u] < v) { + best_v[pos] = best_v[pos - 1u]; + best_i[pos] = best_i[pos - 1u]; pos--; } best_v[pos] = v; - best_i[pos] = (int32_t) (off + vi + i); - if (cnt == k) thr = best_v[k - 1]; + best_i[pos] = (int32_t) (off + vi + bit); + if (cnt == k) { + thr = best_v[k - 1u]; + } } } } - // fewer than k values above -INF: take -INF or NaN elements, then pad with index 0 - for (uint32_t off = 0; off < n && cnt < k; off += 32) { - const uint32_t vn = MIN(32, n - off); - HVX_VectorAlias v_local; - v_local.v = hvx_vmem(vals + off); - for (uint32_t j = 0; j < vn && cnt < k; j++) { - if (!(v_local.fp32[j] > -INFINITY)) { - best_v[cnt] = -INFINITY; - best_i[cnt] = (int32_t) (off + j); - cnt++; + if (cnt < k) { + for (uint32_t off = 0; off < n && cnt < k; off += 32u) { + const uint32_t vn = MIN(32u, n - off); + const HVX_Vector vv = *(const HVX_Vector *)(vals + off); + for (uint32_t j = 0; j < vn && cnt < k; j++) { + union { int32_t i; float f; } u = { .i = Q6_R_vextract_VR(vv, (int) (j * 4u)) }; + if (u.f == -INFINITY) { + best_v[cnt] = -INFINITY; + best_i[cnt] = (int32_t) (off + j); + cnt++; + } + } + } + for (uint32_t off = 0; off < n && cnt < k; off += 32u) { + const uint32_t vn = MIN(32u, n - off); + const HVX_Vector vv = *(const HVX_Vector *)(vals + off); + for (uint32_t j = 0; j < vn && cnt < k; j++) { + union { int32_t i; float f; } u = { .i = Q6_R_vextract_VR(vv, (int) (j * 4u)) }; + if (isnan(u.f)) { + best_v[cnt] = u.f; + best_i[cnt] = (int32_t) (off + j); + cnt++; + } } } } @@ -368,41 +613,300 @@ static void top_k_scan(const float * vals, uint32_t n, uint32_t k, float * out_v } for (uint32_t j = 0; j < k; j++) { - out_v[j] = best_v[j]; + if (out_v) { + out_v[j] = best_v[j]; + } out_i[j] = best_i[j]; } } -__attribute__((always_inline)) -static inline void sort32_f32_hvx(uint8_t * values, uint8_t * indices, enum ggml_sort_order order) { +// O(N) HVX radix-narrowed top-k selection in-place over VTCM float buffer. +__attribute__((noinline)) +static void top_k_select_hvx( + float * restrict buf, + int32_t * restrict out_idx, + float * restrict out_val, + int32_t * restrict cand_scratch, + uint32_t n, + uint32_t k, + uint32_t idx_base +) { + const int32_t KEY_PAD = (int32_t) 0x80000000u; + const int32_t KEY_NINF = (int32_t) 0x807fffffu; + const int32_t KEY_MAX = (int32_t) 0x7fffffffu; + + HVX_Vector * restrict vbuf = (HVX_Vector *) buf; + const uint32_t n_full = n >> 5; + const uint32_t rem = n & 31u; + const uint32_t n_vec = (n + 31u) >> 5; + + const HVX_Vector v_pad = Q6_V_vsplat_R(KEY_PAD); + const HVX_Vector v_ninf = Q6_V_vsplat_R(KEY_NINF); + const HVX_Vector v_max = Q6_V_vsplat_R(KEY_MAX); + const HVX_Vector v_one = Q6_V_vsplat_R(1); + + HVX_Vector v_min_all = v_max; + HVX_Vector v_max_all = v_pad; + HVX_Vector v_min_fin = v_max; + HVX_Vector v_cnt_fin = Q6_V_vzero(); + + for (uint32_t v = 0; v < n_full; v++) { + const HVX_Vector vk = float_to_ord_key_vec(vbuf[v]); + vbuf[v] = vk; + v_min_all = Q6_Vw_vmin_VwVw(v_min_all, vk); + v_max_all = Q6_Vw_vmax_VwVw(v_max_all, vk); + const HVX_VectorPred q_fin = Q6_Q_vcmp_gt_VwVw(vk, v_ninf); + v_cnt_fin = Q6_Vw_vadd_VwVw(v_cnt_fin, Q6_V_vand_QV(q_fin, v_one)); + v_min_fin = Q6_Vw_vmin_VwVw(v_min_fin, Q6_V_vmux_QVV(q_fin, vk, v_max)); + } + if (rem > 0u) { + const HVX_VectorPred q_tail = Q6_Q_vsetq2_R(rem * sizeof(int32_t)); + const HVX_Vector vk_raw = float_to_ord_key_vec(vbuf[n_full]); + const HVX_Vector vk = Q6_V_vmux_QVV(q_tail, vk_raw, v_pad); + vbuf[n_full] = vk; + v_min_all = Q6_Vw_vmin_VwVw(v_min_all, Q6_V_vmux_QVV(q_tail, vk_raw, v_max)); + v_max_all = Q6_Vw_vmax_VwVw(v_max_all, vk); + const HVX_VectorPred q_fin = Q6_Q_vcmp_gt_VwVw(vk, v_ninf); + v_cnt_fin = Q6_Vw_vadd_VwVw(v_cnt_fin, Q6_V_vand_QV(q_fin, v_one)); + v_min_fin = Q6_Vw_vmin_VwVw(v_min_fin, Q6_V_vmux_QVV(q_fin, vk, v_max)); + } + + #pragma clang loop unroll(full) + for (int shift = 64; shift >= 4; shift >>= 1) { + v_min_all = Q6_Vw_vmin_VwVw(v_min_all, Q6_V_vror_VR(v_min_all, shift)); + v_max_all = Q6_Vw_vmax_VwVw(v_max_all, Q6_V_vror_VR(v_max_all, shift)); + v_min_fin = Q6_Vw_vmin_VwVw(v_min_fin, Q6_V_vror_VR(v_min_fin, shift)); + v_cnt_fin = Q6_Vw_vadd_VwVw(v_cnt_fin, Q6_V_vror_VR(v_cnt_fin, shift)); + } + + const int32_t min_key = (int32_t) Q6_R_vextract_VR(v_min_all, 0); + const int32_t max_key = (int32_t) Q6_R_vextract_VR(v_max_all, 0); + const int32_t min_fin_key = (int32_t) Q6_R_vextract_VR(v_min_fin, 0); + const uint32_t n_gt_ninf = (uint32_t) Q6_R_vextract_VR(v_cnt_fin, 0); + + if (min_key == max_key) { + init_indices_ramp(out_idx, k, idx_base); + if (out_val) { + const float fv = ord_key_to_float(max_key); + for (uint32_t j = 0; j < k; j++) { + out_val[j] = fv; + } + } + return; + } + + int32_t lo = min_key - 1; + uint32_t cnt_lo = n; + int32_t hi = max_key; + uint32_t cnt_hi = 0; + + if (n_gt_ninf > k) { + lo = min_fin_key - 1; + cnt_lo = n_gt_ninf; + } else { + hi = KEY_NINF; + cnt_hi = n_gt_ninf; + if (min_key >= KEY_NINF) { + lo = KEY_NINF - 1; + } + } + + while ((uint32_t) hi - (uint32_t) lo > 1u && (cnt_lo - cnt_hi) > 64u && cnt_hi < k) { + const uint32_t span = (uint32_t) hi - (uint32_t) lo; + int32_t p[7]; + #pragma clang loop unroll(full) + for (int m = 0; m < 7; m++) { + uint32_t step = (uint32_t) (((uint64_t) span * (uint32_t) (m + 1)) >> 3); + if (step == 0u) { + step = 1u; + } else if (step >= span) { + step = span - 1u; + } + p[m] = (int32_t) ((uint32_t) lo + step); + } + + const HVX_Vector vp0 = Q6_V_vsplat_R(p[0]); + const HVX_Vector vp1 = Q6_V_vsplat_R(p[1]); + const HVX_Vector vp2 = Q6_V_vsplat_R(p[2]); + const HVX_Vector vp3 = Q6_V_vsplat_R(p[3]); + const HVX_Vector vp4 = Q6_V_vsplat_R(p[4]); + const HVX_Vector vp5 = Q6_V_vsplat_R(p[5]); + const HVX_Vector vp6 = Q6_V_vsplat_R(p[6]); + + HVX_Vector vc0 = Q6_V_vzero(); + HVX_Vector vc1 = Q6_V_vzero(); + HVX_Vector vc2 = Q6_V_vzero(); + HVX_Vector vc3 = Q6_V_vzero(); + HVX_Vector vc4 = Q6_V_vzero(); + HVX_Vector vc5 = Q6_V_vzero(); + HVX_Vector vc6 = Q6_V_vzero(); + + for (uint32_t v = 0; v < n_vec; v++) { + const HVX_Vector vk = vbuf[v]; + vc0 = Q6_Vw_vadd_VwVw(vc0, Q6_V_vand_QV(Q6_Q_vcmp_gt_VwVw(vk, vp0), v_one)); + vc1 = Q6_Vw_vadd_VwVw(vc1, Q6_V_vand_QV(Q6_Q_vcmp_gt_VwVw(vk, vp1), v_one)); + vc2 = Q6_Vw_vadd_VwVw(vc2, Q6_V_vand_QV(Q6_Q_vcmp_gt_VwVw(vk, vp2), v_one)); + vc3 = Q6_Vw_vadd_VwVw(vc3, Q6_V_vand_QV(Q6_Q_vcmp_gt_VwVw(vk, vp3), v_one)); + vc4 = Q6_Vw_vadd_VwVw(vc4, Q6_V_vand_QV(Q6_Q_vcmp_gt_VwVw(vk, vp4), v_one)); + vc5 = Q6_Vw_vadd_VwVw(vc5, Q6_V_vand_QV(Q6_Q_vcmp_gt_VwVw(vk, vp5), v_one)); + vc6 = Q6_Vw_vadd_VwVw(vc6, Q6_V_vand_QV(Q6_Q_vcmp_gt_VwVw(vk, vp6), v_one)); + } + + #pragma clang loop unroll(full) + for (int shift = 64; shift >= 4; shift >>= 1) { + vc0 = Q6_Vw_vadd_VwVw(vc0, Q6_V_vror_VR(vc0, shift)); + vc1 = Q6_Vw_vadd_VwVw(vc1, Q6_V_vror_VR(vc1, shift)); + vc2 = Q6_Vw_vadd_VwVw(vc2, Q6_V_vror_VR(vc2, shift)); + vc3 = Q6_Vw_vadd_VwVw(vc3, Q6_V_vror_VR(vc3, shift)); + vc4 = Q6_Vw_vadd_VwVw(vc4, Q6_V_vror_VR(vc4, shift)); + vc5 = Q6_Vw_vadd_VwVw(vc5, Q6_V_vror_VR(vc5, shift)); + vc6 = Q6_Vw_vadd_VwVw(vc6, Q6_V_vror_VR(vc6, shift)); + } + + const uint32_t c[7] = { + (uint32_t) Q6_R_vextract_VR(vc0, 0), + (uint32_t) Q6_R_vextract_VR(vc1, 0), + (uint32_t) Q6_R_vextract_VR(vc2, 0), + (uint32_t) Q6_R_vextract_VR(vc3, 0), + (uint32_t) Q6_R_vextract_VR(vc4, 0), + (uint32_t) Q6_R_vextract_VR(vc5, 0), + (uint32_t) Q6_R_vextract_VR(vc6, 0), + }; + + #pragma clang loop unroll(full) + for (int m = 0; m < 7; m++) { + if (c[m] >= k) { + lo = p[m]; + cnt_lo = c[m]; + } else if (p[m] < hi) { + hi = p[m]; + cnt_hi = c[m]; + } + } + } + + const HVX_Vector v_bit_lut = *(const HVX_Vector *) top_k_bit_lut; + const HVX_Vector v_hi = Q6_V_vsplat_R(hi); + uint32_t out_cnt = 0; + uint32_t rem_k = k - cnt_hi; + + if (rem_k == 0u) { + for (uint32_t v = 0; v < n_vec && out_cnt < k; v++) { + const HVX_Vector vk = vbuf[v]; + uint32_t mask = hvx_pred_i32_to_bits(Q6_Q_vcmp_gt_VwVw(vk, v_hi), v_bit_lut); + const uint32_t base = idx_base + (v << 5); + while (mask != 0u && out_cnt < k) { + const uint32_t bit = (uint32_t) __builtin_ctz(mask); + mask &= mask - 1u; + if (out_val) { + out_val[out_cnt] = ord_key_to_float((int32_t) Q6_R_vextract_VR(vk, (int) (bit * 4u))); + } + out_idx[out_cnt] = (int32_t) (base + bit); + out_cnt++; + } + } + return; + } + + if ((uint32_t) hi - (uint32_t) lo == 1u) { + const float hi_f = out_val ? ord_key_to_float(hi) : 0.0f; + for (uint32_t v = 0; v < n_vec && out_cnt < k; v++) { + const HVX_Vector vk = vbuf[v]; + const HVX_VectorPred q_gt = Q6_Q_vcmp_gt_VwVw(vk, v_hi); + const HVX_VectorPred q_eq = Q6_Q_vcmp_eq_VwVw(vk, v_hi); + uint32_t mask_gt = hvx_pred_i32_to_bits(q_gt, v_bit_lut); + uint32_t mask_eq = (rem_k > 0u) ? hvx_pred_i32_to_bits(q_eq, v_bit_lut) : 0u; + const uint32_t base = idx_base + (v << 5); + while (mask_gt != 0u) { + const uint32_t bit = (uint32_t) __builtin_ctz(mask_gt); + mask_gt &= mask_gt - 1u; + if (out_val) { + out_val[out_cnt] = ord_key_to_float((int32_t) Q6_R_vextract_VR(vk, (int) (bit * 4u))); + } + out_idx[out_cnt] = (int32_t) (base + bit); + out_cnt++; + } + while (mask_eq != 0u && rem_k > 0u) { + const uint32_t bit = (uint32_t) __builtin_ctz(mask_eq); + mask_eq &= mask_eq - 1u; + if (out_val) { + out_val[out_cnt] = hi_f; + } + out_idx[out_cnt] = (int32_t) (base + bit); + out_cnt++; + rem_k--; + } + } + return; + } + + const HVX_Vector v_lo = Q6_V_vsplat_R(lo); + int32_t * restrict cand_k = cand_scratch; + int32_t * restrict cand_i = cand_scratch + 64; + uint32_t m_cnt = 0; + + for (uint32_t v = 0; v < n_vec; v++) { + const HVX_Vector vk = vbuf[v]; + const HVX_VectorPred q_gt_hi = Q6_Q_vcmp_gt_VwVw(vk, v_hi); + const HVX_VectorPred q_gt_lo = Q6_Q_vcmp_gt_VwVw(vk, v_lo); + const HVX_VectorPred q_mid = Q6_Q_and_QQn(q_gt_lo, q_gt_hi); + uint32_t mask_gt = hvx_pred_i32_to_bits(q_gt_hi, v_bit_lut); + uint32_t mask_mid = hvx_pred_i32_to_bits(q_mid, v_bit_lut); + const uint32_t base = idx_base + (v << 5); + while (mask_gt != 0u) { + const uint32_t bit = (uint32_t) __builtin_ctz(mask_gt); + mask_gt &= mask_gt - 1u; + if (out_val) { + out_val[out_cnt] = ord_key_to_float((int32_t) Q6_R_vextract_VR(vk, (int) (bit * 4u))); + } + out_idx[out_cnt] = (int32_t) (base + bit); + out_cnt++; + } + while (mask_mid != 0u && m_cnt < 64u) { + const uint32_t bit = (uint32_t) __builtin_ctz(mask_mid); + mask_mid &= mask_mid - 1u; + cand_k[m_cnt] = (int32_t) Q6_R_vextract_VR(vk, (int) (bit * 4u)); + cand_i[m_cnt] = (int32_t) (base + bit); + m_cnt++; + } + } + + for (uint32_t j = m_cnt; j < 64u; j++) { + cand_k[j] = KEY_PAD; + cand_i[j] = 0; + } + + sort64_i32_desc(cand_k, cand_i); + + for (uint32_t j = 0; j < rem_k && out_cnt < k; j++) { + if (out_val) { + out_val[out_cnt] = ord_key_to_float(cand_k[j]); + } + out_idx[out_cnt] = cand_i[j]; + out_cnt++; + } +} + +__attribute__((noinline)) +static void sort32_f32_hvx(uint8_t * values, uint8_t * indices, enum ggml_sort_order order) { bitonic_sort_generic_hvx(values, indices, 1, order == GGML_SORT_ORDER_ASC); } -__attribute__((always_inline)) -static inline void sort64_f32_hvx(uint8_t * values, uint8_t * indices, enum ggml_sort_order order) { +__attribute__((noinline)) +static void sort64_f32_hvx(uint8_t * values, uint8_t * indices, enum ggml_sort_order order) { bitonic_sort_generic_hvx(values, indices, 2, order == GGML_SORT_ORDER_ASC); } -__attribute__((always_inline)) -static inline void sort128_f32_hvx(uint8_t * values, uint8_t * indices, enum ggml_sort_order order) { +__attribute__((noinline)) +static void sort128_f32_hvx(uint8_t * values, uint8_t * indices, enum ggml_sort_order order) { bitonic_sort_generic_hvx(values, indices, 4, order == GGML_SORT_ORDER_ASC); } -__attribute__((always_inline)) -static inline void sort256_f32_hvx(uint8_t * values, uint8_t * indices, enum ggml_sort_order order) { +__attribute__((noinline)) +static void sort256_f32_hvx(uint8_t * values, uint8_t * indices, enum ggml_sort_order order) { bitonic_sort_generic_hvx(values, indices, 8, order == GGML_SORT_ORDER_ASC); } -__attribute__((always_inline)) -static inline void sort512_f32_hvx(uint8_t * values, uint8_t * indices, enum ggml_sort_order order) { - bitonic_sort_generic_hvx(values, indices, 16, order == GGML_SORT_ORDER_ASC); -} - -__attribute__((always_inline)) -static inline void sort1024_f32_hvx(uint8_t * values, uint8_t * indices, enum ggml_sort_order order) { - bitonic_sort_generic_hvx(values, indices, 32, order == GGML_SORT_ORDER_ASC); -} - static void merge_runs( const float * restrict in_val0, const int32_t * restrict in_idx0, uint32_t n0, const float * restrict in_val1, const int32_t * restrict in_idx1, uint32_t n1, @@ -456,14 +960,33 @@ static void merge_runs( } } +// Expand fp16 values in-place to fp32 backwards from the last vector so lower fp16 vectors are read before overwrite. +__attribute__((noinline)) +static void sort_unpack_f16_to_f32_inplace(float * restrict values, uint32_t count) { + const HVX_Vector * vsrc = (const HVX_Vector *) values; + HVX_Vector * vdst = (HVX_Vector *) values; + const uint32_t n_vec_f32 = (count + 31) / 32; + const uint32_t n_vec_f16 = (n_vec_f32 + 1) / 2; + + for (int32_t v = (int32_t) n_vec_f16 - 1; v >= 0; v--) { + const HVX_VectorPair p = hvx_vec_f16_to_f32(vsrc[v]); + if ((uint32_t) (2 * v + 1) < n_vec_f32) { + vdst[2 * v + 1] = Q6_V_hi_W(p); + } + vdst[2 * v] = Q6_V_lo_W(p); + } +} + struct htp_sort_chunk_ctx { struct htp_ops_context * octx; const struct htp_sort_kernel_params * kparams; uint8_t * phase1_base; size_t phase1_slot_size; + size_t off_cand; float * merge_values; int32_t * merge_indices; uint32_t real_count[HTP_OP_MAX_NHVX]; + uint32_t cand_count[HTP_OP_MAX_NHVX]; }; static void htp_sort_chunk_job(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { @@ -488,63 +1011,55 @@ static void htp_sort_chunk_job(const htp_thread_t * th, unsigned int n, unsigned int32_t * merge_indices = cctx->merge_indices; struct htp_thread_trace * tr = th->trace; - const dma_addr_t src_addr = src0->data + (size_t) chunk_base * sizeof(float); + const bool src0_f16 = (src0->type == HTP_TYPE_F16); + const size_t src_elem_size = src0_f16 ? sizeof(__fp16) : sizeof(float); + const dma_addr_t src_addr = src0->data + (size_t) chunk_base * src_elem_size; if (kparams->is_top_k) { - uint32_t k = dst->ne[0]; - uint32_t local_k = MIN(k, chunk_elems); + const uint32_t k = dst->ne[0]; + const uint32_t local_k = MIN(k, chunk_elems); + const uint32_t take_k = MIN(local_k, real_count); + cctx->cand_count[i] = take_k; - if (real_count == 0) { - for (uint32_t j = 0; j < local_k; j++) { - merge_values[i * local_k + j] = -INFINITY; - merge_indices[i * local_k + j] = 0; - } + if (take_k == 0u) { return; } - if (local_k == 1 && ne00 >= 128*1024) { - dma_sync_read(th->dma_q, values_buf, src_addr, real_count * sizeof(float)); + float * out_val = &merge_values[i * local_k]; + int32_t * out_idx = &merge_indices[i * local_k]; + int32_t * cand_scratch = (int32_t *) (spad + cctx->off_cand); - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i); - float max_value; - uint32_t max_index = top_k_max_value_index(values_buf, real_count, &max_value); - merge_values[i] = max_value; - merge_indices[i] = (int32_t) (max_index + chunk_base); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i); - return; - } - - if (local_k > 1 && local_k <= 64 && chunk_elems > 1024) { - dma_sync_read(th->dma_q, values_buf, src_addr, real_count * sizeof(float)); - - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i); - top_k_scan(values_buf, real_count, local_k, &merge_values[i * local_k], &merge_indices[i * local_k]); - for (uint32_t j = 0; j < local_k; j++) { - merge_indices[i * local_k + j] += (int32_t) chunk_base; - } - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i); - return; - } - - dma_sync_read(th->dma_q, values_buf, src_addr, real_count * sizeof(float)); + dma_sync_read(th->dma_q, values_buf, src_addr, real_count * src_elem_size); htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i); - if (chunk_elems > real_count) { - hvx_splat_f32_u((uint8_t *)(values_buf + real_count), -INFINITY, chunk_elems - real_count); + if (src0_f16) { + sort_unpack_f16_to_f32_inplace(values_buf, real_count); } - bitonic_sort_vtcm_desc((uint8_t *) values_buf, (uint8_t *) indices_buf, chunk_elems / 32, true); - - for (uint32_t j = 0; j < local_k; j++) { - merge_values[i * local_k + j] = values_buf[j]; - merge_indices[i * local_k + j] = indices_buf[j] + (int32_t) chunk_base; + if (take_k == real_count) { + for (uint32_t j = 0; j < take_k; j++) { + out_val[j] = values_buf[j]; + out_idx[j] = (int32_t) (chunk_base + j); + } + } else if (take_k == 1u) { + out_idx[0] = top_k_argmax_hvx(values_buf, real_count, chunk_base, &out_val[0]); + } else if (take_k <= 64u && chunk_elems > 1024u) { + top_k_scan(values_buf, real_count, take_k, out_val, out_idx); + for (uint32_t j = 0; j < take_k; j++) { + out_idx[j] += (int32_t) chunk_base; + } + } else { + top_k_select_hvx(values_buf, out_idx, out_val, cand_scratch, real_count, take_k, chunk_base); } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i); } else { if (real_count > 0) { - dma_sync_read(th->dma_q, values_buf, src_addr, real_count * sizeof(float)); + dma_sync_read(th->dma_q, values_buf, src_addr, real_count * src_elem_size); htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i); + if (src0_f16) { + sort_unpack_f16_to_f32_inplace(values_buf, real_count); + } init_indices_ramp(indices_buf, real_count, chunk_base); if (kparams->order == GGML_SORT_ORDER_ASC) { @@ -630,6 +1145,10 @@ struct htp_sort_multi_row_ctx { const struct htp_sort_kernel_params * kparams; uint8_t * phase1_base; size_t phase1_slot_size; + size_t row_values_size; + size_t row_indices_size; + size_t off_cand; + uint32_t batch_rows; uint32_t row_start; uint32_t row_end; uint32_t nrows_per_hvx; @@ -673,49 +1192,50 @@ static inline size_t coord_offset(struct htp_tensor_row_coord c, size_t nb1, siz } static inline void compute_row_sort( - float * cur_values, - int32_t * cur_indices, - uint32_t ne00, - uint32_t chunk_elems, - bool is_top_k, + float * restrict cur_values, + int32_t * restrict cur_indices, + int32_t * restrict cand_scratch, + uint32_t ne00, + uint32_t chunk_elems, + bool src0_f16, + bool is_top_k, enum ggml_sort_order order, - uint32_t k + uint32_t k ) { + if (src0_f16) { + sort_unpack_f16_to_f32_inplace(cur_values, ne00); + } if (is_top_k) { - if (k > 1 && k <= 64 && ne00 > 1024) { - float out_v[64]; - top_k_scan(cur_values, ne00, k, out_v, cur_indices); - } else if (ne00 == 32 || ne00 == 64 || ne00 == 128 || ne00 == 256 || ne00 == 512 || ne00 == 1024) { - switch (ne00) { - case 32: sort32_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, GGML_SORT_ORDER_DESC); break; - case 64: sort64_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, GGML_SORT_ORDER_DESC); break; - case 128: sort128_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, GGML_SORT_ORDER_DESC); break; - case 256: sort256_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, GGML_SORT_ORDER_DESC); break; - case 512: sort512_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, GGML_SORT_ORDER_DESC); break; - case 1024: sort1024_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, GGML_SORT_ORDER_DESC); break; + if (k == 1u) { + cur_indices[0] = top_k_argmax_hvx(cur_values, ne00, 0, NULL); + } else if (ne00 <= 256u) { + switch (chunk_elems) { + case 32: sort32_top_k_hvx(cur_values, cur_indices, ne00, k); break; + case 64: sort64_top_k_hvx(cur_values, cur_indices, ne00, k); break; + case 128: sort128_top_k_hvx(cur_values, cur_indices, ne00, k); break; + default: sort256_top_k_hvx(cur_values, cur_indices, ne00, k); break; } + } else if (k <= 64u && ne00 > 1024u) { + top_k_scan(cur_values, ne00, k, NULL, cur_indices); } else { - if (chunk_elems > ne00) { - hvx_splat_f32_u((uint8_t *)(cur_values + ne00), -INFINITY, chunk_elems - ne00); - } - bitonic_sort_vtcm_desc((uint8_t *) cur_values, (uint8_t *) cur_indices, chunk_elems / 32, true); + top_k_select_hvx(cur_values, cur_indices, NULL, cand_scratch, ne00, k, 0); } } else { - if (ne00 == 32 || ne00 == 64 || ne00 == 128 || ne00 == 256 || ne00 == 512 || ne00 == 1024) { + if (ne00 == 32u || ne00 == 64u || ne00 == 128u || ne00 == 256u) { switch (ne00) { - case 32: sort32_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, order); break; - case 64: sort64_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, order); break; - case 128: sort128_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, order); break; - case 256: sort256_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, order); break; - case 512: sort512_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, order); break; - case 1024: sort1024_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, order); break; + case 32: sort32_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, order); break; + case 64: sort64_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, order); break; + case 128: sort128_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, order); break; + case 256: sort256_f32_hvx((uint8_t *) cur_values, (uint8_t *) cur_indices, order); break; } + } else if (ne00 == 512u || ne00 == 1024u) { + bitonic_sort_vtcm((uint8_t *) cur_values, (uint8_t *) cur_indices, ne00 >> 5, true, order == GGML_SORT_ORDER_ASC); } else { init_indices_ramp(cur_indices, ne00, 0); if (order == GGML_SORT_ORDER_ASC) { - quicksort_values_indices_asc(cur_values, cur_indices, 0, ne00 - 1); + quicksort_values_indices_asc(cur_values, cur_indices, 0, (int) ne00 - 1); } else { - quicksort_values_indices_desc(cur_values, cur_indices, 0, ne00 - 1); + quicksort_values_indices_desc(cur_values, cur_indices, 0, (int) ne00 - 1); } } } @@ -745,123 +1265,209 @@ static void htp_sort_multi_row_job(const htp_thread_t * th, unsigned int n, unsi uint32_t r_start = row_start + ith * mctx->nrows_per_hvx; uint32_t r_end = MIN(r_start + mctx->nrows_per_hvx, row_end); - if (r_start >= r_end) return; + if (r_start >= r_end) { + return; + } + + const size_t slot_size = mctx->phase1_slot_size; + const size_t row_values_size = mctx->row_values_size; + const size_t row_indices_size = mctx->row_indices_size; + const size_t off_cand = mctx->off_cand; + const uint32_t batch_rows = mctx->batch_rows; + const size_t values_area_size = row_values_size * (size_t) batch_rows; - size_t slot_size = mctx->phase1_slot_size; - size_t spad_offset = ith * slot_size * (size_t) kparams->n_slots; + const size_t spad_offset = ith * slot_size * (size_t) kparams->n_slots; uint8_t * hvx_spad = mctx->phase1_base + spad_offset; - uint32_t chunk_elems = (uint32_t) kparams->chunk_elems; - float * values_buf = (float *) hvx_spad; - int32_t * indices_buf = (int32_t *) (hvx_spad + chunk_elems * sizeof(float)); - + const uint32_t chunk_elems = (uint32_t) kparams->chunk_elems; dma_queue * dma_q = th->dma_q; struct htp_thread_trace * tr = th->trace; - bool is_top_k = kparams->is_top_k != 0; - uint32_t k = dst->ne[0]; - enum ggml_sort_order order = (enum ggml_sort_order) kparams->order; + const bool src0_f16 = (src0->type == HTP_TYPE_F16); + const bool is_top_k = kparams->is_top_k != 0; + const uint32_t k = dst->ne[0]; + const enum ggml_sort_order order = (enum ggml_sort_order) kparams->order; - const uint32_t src_bytes = ne00 * sizeof(float); + const uint32_t src_bytes = ne00 * (src0_f16 ? sizeof(__fp16) : sizeof(float)); const uint32_t dst_bytes = (is_top_k ? k : ne00) * sizeof(int32_t); if (kparams->n_slots == 2) { - struct htp_tensor_row_coord prime_coord = init_row_coord(r_start, ne01, ne02, &kparams->div_ne01, &kparams->div_ne01_ne02); - for (uint32_t r = r_start, spad_idx = 0; r < r_end && spad_idx < 2; r++, spad_idx++) { - uint8_t * cur_spad = hvx_spad + spad_idx * slot_size; - float * cur_values = (float *) cur_spad; - int32_t * cur_indices = (int32_t *) (cur_spad + chunk_elems * sizeof(float)); - - dma_addr_t dst_addr = dst->data + coord_offset(prime_coord, nb1, nb2, nb3); - dma_addr_t src_addr = src0->data + coord_offset(prime_coord, nb01, nb02, nb03); - - // Dummy dst writeback to establish queue ordering - dma_queue_push(dma_q, dma_make_data(dst_addr, cur_indices), - dst_bytes, dst_bytes, dst_bytes, 0); - - // Prefetch input row - dma_queue_push(dma_q, dma_make_data(cur_values, src_addr), - src_bytes, src_bytes, src_bytes, 1); - - step_row_coord(&prime_coord, ne01, ne02); + struct htp_tensor_row_coord next_coord = init_row_coord(r_start, ne01, ne02, &kparams->div_ne01, &kparams->div_ne01_ne02); + struct htp_tensor_row_coord slot_coord[2]; + uint32_t slot_cnt[2] = { 0, 0 }; + uint32_t slot_r[2] = { 0, 0 }; + uint32_t next_r = r_start; + + for (uint32_t s = 0; s < 2 && next_r < r_end; s++) { + const uint32_t b_cnt = MIN(batch_rows, MIN(r_end - next_r, ne01 - next_coord.i01)); + uint8_t * cur_spad = hvx_spad + s * slot_size; + float * cur_values_base = (float *) cur_spad; + int32_t * cur_indices_base = (int32_t *) (cur_spad + values_area_size); + + const dma_addr_t dst_addr = dst->data + coord_offset(next_coord, nb1, nb2, nb3); + const dma_addr_t src_addr = src0->data + coord_offset(next_coord, nb01, nb02, nb03); + + dma_queue_push(dma_q, dma_make_data(dst_addr, cur_indices_base), + nb1, row_indices_size, dst_bytes, 0); + dma_queue_push(dma_q, dma_make_data(cur_values_base, src_addr), + row_values_size, nb01, src_bytes, b_cnt); + + slot_cnt[s] = b_cnt; + slot_r[s] = next_r; + slot_coord[s] = next_coord; + + next_r += b_cnt; + for (uint32_t b = 0; b < b_cnt; b++) { + step_row_coord(&next_coord, ne01, ne02); + } } - struct htp_tensor_row_coord dst_coord = init_row_coord(r_start, ne01, ne02, &kparams->div_ne01, &kparams->div_ne01_ne02); - struct htp_tensor_row_coord next_src_coord = init_row_coord(r_start + 2, ne01, ne02, &kparams->div_ne01, &kparams->div_ne01_ne02); - - for (uint32_t r = r_start; r < r_end; r++) { - uint32_t cur_slot = (r - r_start) & 1; - uint8_t * cur_spad = hvx_spad + cur_slot * slot_size; - float * cur_values = (float *) cur_spad; - int32_t * cur_indices = (int32_t *) (cur_spad + chunk_elems * sizeof(float)); + uint32_t cur_slot = 0; + while (slot_cnt[cur_slot] > 0) { + const uint32_t b_cnt = slot_cnt[cur_slot]; + const uint32_t base_r = slot_r[cur_slot]; + uint8_t * cur_spad = hvx_spad + cur_slot * slot_size; + float * cur_values_base = (float *) cur_spad; + int32_t * cur_indices_base = (int32_t *) (cur_spad + values_area_size); + int32_t * cand_scratch = (int32_t *) (cur_spad + off_cand); - // Wait for previous writeback of this slot to complete dma_queue_pop(dma_q); - - // Wait for input row DMA read into this slot to complete dma_queue_pop(dma_q); - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r); - compute_row_sort(cur_values, cur_indices, ne00, chunk_elems, is_top_k, order, k); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r); - - // Push writeback of current slot - dma_addr_t dst_addr = dst->data + coord_offset(dst_coord, nb1, nb2, nb3); - dma_queue_push(dma_q, dma_make_data(dst_addr, cur_indices), - dst_bytes, dst_bytes, dst_bytes, 1); - step_row_coord(&dst_coord, ne01, ne02); - - // Prefetch next row into this slot - const uint32_t next_row = r + 2; - if (next_row < r_end) { - dma_addr_t next_src_addr = src0->data + coord_offset(next_src_coord, nb01, nb02, nb03); - dma_queue_push(dma_q, dma_make_data(cur_values, next_src_addr), - src_bytes, src_bytes, src_bytes, 1); - step_row_coord(&next_src_coord, ne01, ne02); + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) base_r); + for (uint32_t b = 0; b < b_cnt; b++) { + float * row_val = (float *) (cur_spad + (size_t) b * row_values_size); + int32_t * row_idx = (int32_t *) (cur_spad + values_area_size + (size_t) b * row_indices_size); + compute_row_sort(row_val, row_idx, cand_scratch, ne00, chunk_elems, src0_f16, is_top_k, order, k); } + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) base_r); + + const dma_addr_t dst_addr = dst->data + coord_offset(slot_coord[cur_slot], nb1, nb2, nb3); + dma_queue_push(dma_q, dma_make_data(dst_addr, cur_indices_base), + nb1, row_indices_size, dst_bytes, b_cnt); + + if (next_r < r_end) { + const uint32_t next_b = MIN(batch_rows, MIN(r_end - next_r, ne01 - next_coord.i01)); + const dma_addr_t next_src_addr = src0->data + coord_offset(next_coord, nb01, nb02, nb03); + dma_queue_push(dma_q, dma_make_data(cur_values_base, next_src_addr), + row_values_size, nb01, src_bytes, next_b); + slot_cnt[cur_slot] = next_b; + slot_r[cur_slot] = next_r; + slot_coord[cur_slot] = next_coord; + + next_r += next_b; + for (uint32_t b = 0; b < next_b; b++) { + step_row_coord(&next_coord, ne01, ne02); + } + } else { + slot_cnt[cur_slot] = 0; + } + + cur_slot ^= 1u; } dma_queue_flush(dma_q); } else { struct htp_tensor_row_coord coord = init_row_coord(r_start, ne01, ne02, &kparams->div_ne01, &kparams->div_ne01_ne02); - for (uint32_t r = r_start; r < r_end; r++) { - dma_addr_t src_addr = src0->data + coord_offset(coord, nb01, nb02, nb03); - dma_addr_t dst_addr = dst->data + coord_offset(coord, nb1, nb2, nb3); + int32_t * cand_scratch = (int32_t *) (hvx_spad + off_cand); + for (uint32_t r = r_start; r < r_end; ) { + const uint32_t b_cnt = MIN(batch_rows, MIN(r_end - r, ne01 - coord.i01)); + const dma_addr_t src_addr = src0->data + coord_offset(coord, nb01, nb02, nb03); + const dma_addr_t dst_addr = dst->data + coord_offset(coord, nb1, nb2, nb3); - dma_sync_read(dma_q, values_buf, src_addr, src_bytes); + dma_queue_push(dma_q, dma_make_data(hvx_spad, src_addr), + row_values_size, nb01, src_bytes, b_cnt); + dma_queue_flush(dma_q); htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r); - compute_row_sort(values_buf, indices_buf, ne00, chunk_elems, is_top_k, order, k); + for (uint32_t b = 0; b < b_cnt; b++) { + float * row_val = (float *) (hvx_spad + (size_t) b * row_values_size); + int32_t * row_idx = (int32_t *) (hvx_spad + values_area_size + (size_t) b * row_indices_size); + compute_row_sort(row_val, row_idx, cand_scratch, ne00, chunk_elems, src0_f16, is_top_k, order, k); + } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r); - dma_sync_write(dma_q, dst_addr, indices_buf, dst_bytes); + dma_queue_push(dma_q, dma_make_data(dst_addr, hvx_spad + values_area_size), + nb1, row_indices_size, dst_bytes, b_cnt); + dma_queue_flush(dma_q); + + r += b_cnt; + for (uint32_t b = 0; b < b_cnt; b++) { + step_row_coord(&coord, ne01, ne02); + } + } + } +} + +struct htp_top_k_identity_ctx { + struct htp_ops_context * octx; + const struct htp_sort_kernel_params * kparams; + uint8_t * phase1_base; + size_t row_indices_size; + uint32_t batch_rows; + uint32_t row_start; + uint32_t row_end; + uint32_t nrows_per_hvx; +}; + +static void htp_top_k_identity_job(const htp_thread_t * th, unsigned int n, unsigned int ith, void * data) { + const struct htp_top_k_identity_ctx * ictx = (const struct htp_top_k_identity_ctx *) data; + const struct htp_ops_context * octx = ictx->octx; + const struct htp_sort_kernel_params * kparams = ictx->kparams; + const struct htp_tensor * src0 = octx->src[0]; + const struct htp_tensor * dst = octx->dst; + + const uint32_t ne01 = src0->ne[1]; + const uint32_t ne02 = src0->ne[2]; + const uint32_t nb1 = dst->nb[1]; + const uint32_t nb2 = dst->nb[2]; + const uint32_t nb3 = dst->nb[3]; + + const uint32_t r_start = ictx->row_start + ith * ictx->nrows_per_hvx; + const uint32_t r_end = MIN(r_start + ictx->nrows_per_hvx, ictx->row_end); + if (r_start >= r_end) { + return; + } + + const uint32_t dst_bytes = dst->ne[0] * sizeof(int32_t); + const size_t row_stride = ictx->row_indices_size; + const uint32_t batch_rows = ictx->batch_rows; + dma_queue * dma_q = th->dma_q; + + struct htp_tensor_row_coord coord = init_row_coord(r_start, ne01, ne02, &kparams->div_ne01, &kparams->div_ne01_ne02); + for (uint32_t r = r_start; r < r_end; ) { + const uint32_t b_cnt = MIN(batch_rows, MIN(r_end - r, ne01 - coord.i01)); + const dma_addr_t dst_addr = dst->data + coord_offset(coord, nb1, nb2, nb3); + + if (dma_ring_depth(dma_q->ring0) >= 8u) { + dma_queue_pop(dma_q); + } + dma_queue_push(dma_q, dma_make_data(dst_addr, ictx->phase1_base), + nb1, row_stride, dst_bytes, b_cnt); + + r += b_cnt; + for (uint32_t b = 0; b < b_cnt; b++) { step_row_coord(&coord, ne01, ne02); } } + dma_queue_flush(dma_q); } static int op_sort_common(struct htp_ops_context * octx, bool is_top_k) { - if (octx->src[0]->type != HTP_TYPE_F32) { + if (octx->src[0]->type != HTP_TYPE_F32 && octx->src[0]->type != HTP_TYPE_F16) { return HTP_STATUS_NO_SUPPORT; } const struct htp_tensor * src0 = octx->src[0]; const struct htp_tensor * dst = octx->dst; - if (htp_tensor_is_extended(src0) || htp_tensor_is_extended(dst)) { - return HTP_STATUS_NO_SUPPORT; - } - const uint32_t total_rows = src0->ne[1] * src0->ne[2] * src0->ne[3]; - const size_t dst_row_size = dst->ne[0] * sizeof(int32_t); uint32_t row_start = 0; uint32_t row_end = total_rows; if (octx->ctx->mdev.count > 1) { - uint32_t rows_per_chunk = 0; - htp_tensor_mdev_rows_per_chunk(dst, sizeof(int32_t), (uint32_t) dst_row_size, &rows_per_chunk); const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( - total_rows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + total_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); row_start = range.start; row_end = range.start + range.count; } @@ -882,12 +1488,15 @@ static int op_sort_common(struct htp_ops_context * octx, bool is_top_k) { struct htp_sort_vtcm_layout layout; htp_sort_vtcm_layout_build(&layout, + ne00, total_rows, (uint32_t) kparams->chunk_elems, (uint32_t) kparams->n_chunks, (uint32_t) kparams->merge_elems, (uint32_t) kparams->n_hvx, - (uint32_t) kparams->n_slots); + (uint32_t) kparams->n_slots, + k, + is_top_k); if (octx->ctx->vtcm_size < layout.total_bytes) { FARF(ERROR, "sort: VTCM size too small. Needed %zu, have %zu", layout.total_bytes, octx->ctx->vtcm_size); @@ -899,55 +1508,101 @@ static int op_sort_common(struct htp_ops_context * octx, bool is_top_k) { float * merge_values = VTCM_LAYOUT_PTR(float, vtcm_base, layout.off_merge_values); int32_t * merge_indices = VTCM_LAYOUT_PTR(int32_t, vtcm_base, layout.off_merge_indices); + if (is_top_k && k >= ne00) { + init_indices_ramp((int32_t *) phase1_base, k, 0); + const uint32_t n_idx_vecs = (uint32_t) (layout.row_indices_size >> 7); + const HVX_Vector * restrict vsrc0 = (const HVX_Vector *) phase1_base; + for (uint32_t b = 1; b < layout.batch_rows; b++) { + HVX_Vector * restrict vdst_b = (HVX_Vector *) (phase1_base + (size_t) b * layout.row_indices_size); + for (uint32_t v = 0; v < n_idx_vecs; v++) { + vdst_b[v] = vsrc0[v]; + } + } + + const uint32_t dr = fastdiv(nrows + octx->n_hvx - 1, &octx->n_hvx_div); + + struct htp_top_k_identity_ctx ictx; + ictx.octx = octx; + ictx.kparams = kparams; + ictx.phase1_base = phase1_base; + ictx.row_indices_size = layout.row_indices_size; + ictx.batch_rows = layout.batch_rows; + ictx.row_start = row_start; + ictx.row_end = row_end; + ictx.nrows_per_hvx = dr; + + work_queue_run(octx->ctx->hvx_queue, htp_top_k_identity_job, &ictx, octx->n_hvx); + return HTP_STATUS_OK; + } + if (total_rows == 1 && kparams->n_chunks > 1) { struct htp_sort_chunk_ctx cctx; cctx.octx = octx; cctx.kparams = kparams; cctx.phase1_base = phase1_base; cctx.phase1_slot_size = layout.phase1_slot_size; + cctx.off_cand = layout.off_cand; cctx.merge_values = merge_values; cctx.merge_indices = merge_indices; memset(cctx.real_count, 0, sizeof(cctx.real_count)); + memset(cctx.cand_count, 0, sizeof(cctx.cand_count)); work_queue_run(octx->ctx->hvx_queue, htp_sort_chunk_job, &cctx, (uint32_t) kparams->n_chunks); if (is_top_k) { - uint32_t chunk_elems = (uint32_t) kparams->chunk_elems; - uint32_t local_k = MIN(k, chunk_elems); - - if (k == 1 && ne00 >= 128*1024) { - float * cand_vals = merge_values; - int32_t * cand_idxs = merge_indices; - float best_val = cand_vals[0]; - int32_t best_idx = cand_idxs[0]; - for (int32_t c = 1; c < kparams->n_chunks; c++) { - if (cand_vals[c] > best_val) { - best_val = cand_vals[c]; - best_idx = cand_idxs[c]; + const uint32_t chunk_elems = (uint32_t) kparams->chunk_elems; + const uint32_t local_k = MIN(k, chunk_elems); + + struct htp_thread_trace * tr = &octx->ctx->trace[0]; + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, 0); + + if (k == 1u) { + int32_t best_key = (int32_t) 0x80000000u; + int32_t best_idx = 0; + for (uint32_t c = 0; c < (uint32_t) kparams->n_chunks; c++) { + if (cctx.cand_count[c] == 0u) { + continue; + } + union { float f; uint32_t u; int32_t i; } u = { .f = merge_values[c * local_k] }; + const int32_t key = ((u.u & 0x7fffffffu) > 0x7f800000u) + ? (int32_t) 0x80000001u + : ((u.i < 0) ? (int32_t) (u.u ^ 0x7fffffffu) : u.i); + if (key > best_key) { + best_key = key; + best_idx = merge_indices[c * local_k]; } } - int32_t * dst_ptr = (int32_t *) dst->data; - dst_ptr[0] = best_idx; + merge_indices[0] = best_idx; + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, 0); + dma_sync_write(octx->ctx->dma[0], dst->data, merge_indices, sizeof(int32_t)); return HTP_STATUS_OK; } - uint32_t total_candidates = (uint32_t) kparams->n_chunks * local_k; - float * cand_vals = merge_values; - int32_t * cand_idxs = merge_indices; - uint32_t merge_elems = (uint32_t) kparams->merge_elems; - - if (merge_elems > total_candidates) { - hvx_splat_f32_u((uint8_t *) (cand_vals + total_candidates), -INFINITY, merge_elems - total_candidates); - for (uint32_t j = total_candidates; j < merge_elems; j++) { - cand_idxs[j] = 0; + uint32_t total_candidates = 0; + for (uint32_t c = 0; c < (uint32_t) kparams->n_chunks; c++) { + const uint32_t cnt = cctx.cand_count[c]; + const uint32_t base = c * local_k; + if (total_candidates != base) { + for (uint32_t j = 0; j < cnt; j++) { + merge_values[total_candidates + j] = merge_values[base + j]; + merge_indices[total_candidates + j] = merge_indices[base + j]; + } } + total_candidates += cnt; } - struct htp_thread_trace * tr = &octx->ctx->trace[0]; - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, 0); - bitonic_sort_vtcm_desc((uint8_t *) cand_vals, (uint8_t *) cand_idxs, merge_elems / 32, false); + int32_t * pos_idx = (int32_t *) phase1_base; + const size_t pos_bytes = ((size_t) k * sizeof(int32_t) + 127u) & ~(size_t) 127u; + int32_t * cand_scratch = (int32_t *) (phase1_base + pos_bytes); + + top_k_select_hvx(merge_values, pos_idx, NULL, cand_scratch, total_candidates, k, 0); + + int32_t * final_idx = (int32_t *) merge_values; + for (uint32_t t = 0; t < k; t++) { + final_idx[t] = merge_indices[pos_idx[t]]; + } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, 0); - dma_sync_write(octx->ctx->dma[0], dst->data, cand_idxs, k * sizeof(int32_t)); + dma_sync_write(octx->ctx->dma[0], dst->data, final_idx, k * sizeof(int32_t)); } else { bool asc = kparams->order == GGML_SORT_ORDER_ASC; if (kparams->n_chunks == 8) { @@ -1022,20 +1677,14 @@ static int op_sort_common(struct htp_ops_context * octx, bool is_top_k) { mctx.kparams = kparams; mctx.phase1_base = phase1_base; mctx.phase1_slot_size = layout.phase1_slot_size; + mctx.row_values_size = layout.row_values_size; + mctx.row_indices_size = layout.row_indices_size; + mctx.off_cand = layout.off_cand; + mctx.batch_rows = layout.batch_rows; mctx.row_start = row_start; mctx.row_end = row_end; - uint32_t dst_row_bytes = (uint32_t) dst_row_size; - uint32_t rows_per_chunk = 0; - htp_tensor_mdev_rows_per_chunk(dst, sizeof(int32_t), dst_row_bytes, &rows_per_chunk); - if (rows_per_chunk == 0) { - rows_per_chunk = 1; - } - uint32_t dr = fastdiv(nrows + octx->n_hvx - 1, &octx->n_hvx_div); - if (rows_per_chunk > 1) { - dr = hex_round_up(dr, rows_per_chunk); - } - mctx.nrows_per_hvx = dr; + mctx.nrows_per_hvx = fastdiv(nrows + octx->n_hvx - 1, &octx->n_hvx_div); work_queue_run(octx->ctx->hvx_queue, htp_sort_multi_row_job, &mctx, octx->n_hvx); diff --git a/ggml/src/ggml-hexagon/htp/argsort-ops.h b/ggml/src/ggml-hexagon/htp/argsort-ops.h index d1cb8087b584..5cc4f27111ae 100644 --- a/ggml/src/ggml-hexagon/htp/argsort-ops.h +++ b/ggml/src/ggml-hexagon/htp/argsort-ops.h @@ -25,6 +25,9 @@ struct htp_sort_kernel_params { struct htp_sort_vtcm_layout { size_t total_bytes; size_t phase1_slot_size; + size_t row_values_size; + size_t row_indices_size; + size_t off_cand; size_t off_phase1; size_t off_merge_values; size_t off_merge_indices; @@ -33,16 +36,20 @@ struct htp_sort_vtcm_layout { uint32_t merge_elems; uint32_t n_hvx; uint32_t n_slots; + uint32_t batch_rows; }; static inline void htp_sort_vtcm_layout_build( struct htp_sort_vtcm_layout * L, + uint32_t ne00, uint32_t total_rows, uint32_t chunk_elems, uint32_t n_chunks, uint32_t merge_elems, uint32_t n_hvx, - uint32_t n_slots) { + uint32_t n_slots, + uint32_t k, + bool is_top_k) { memset(L, 0, sizeof(*L)); L->chunk_elems = chunk_elems; @@ -51,19 +58,65 @@ static inline void htp_sort_vtcm_layout_build( L->n_hvx = n_hvx; L->n_slots = n_slots; - const size_t values_size = ((chunk_elems * sizeof(float)) + 127) & ~127; - const size_t indices_size = ((chunk_elems * sizeof(int32_t)) + 127) & ~127; - L->phase1_slot_size = ((values_size + indices_size) + 255) & ~255; + if (is_top_k && k >= ne00) { + const size_t idx_size = ((k * sizeof(int32_t)) + 127u) & ~(size_t) 127u; + uint32_t batch_rows = 1u; + if ((idx_size << 4) <= 65536u) { + batch_rows = 16u; + } else if ((idx_size << 2) <= 65536u) { + batch_rows = 4u; + } + if (batch_rows > total_rows && total_rows > 0u) { + batch_rows = total_rows; + } + L->row_indices_size = idx_size; + L->batch_rows = batch_rows; + L->phase1_slot_size = ((idx_size * batch_rows) + 255u) & ~(size_t) 255u; + + size_t off = 0; + VTCM_LAYOUT_ALLOC(off, off_phase1, L->phase1_slot_size); + L->total_bytes = off; + return; + } + + uint32_t indices_elems = chunk_elems; + if (is_top_k) { + if (total_rows == 1u && n_chunks > 1u) { + indices_elems = 0u; + } else if (k < chunk_elems) { + indices_elems = k; + } + } + + uint32_t batch_rows = 1u; + if (total_rows > 1u && chunk_elems <= 256u) { + if (total_rows > 7u * n_hvx) { + batch_rows = 8u; + } else if (total_rows > 3u * n_hvx) { + batch_rows = 4u; + } + } + + const size_t row_values_size = ((chunk_elems * sizeof(float)) + 127u) & ~(size_t) 127u; + const size_t row_indices_size = ((indices_elems * sizeof(int32_t)) + 127u) & ~(size_t) 127u; + const size_t off_cand = (row_values_size + row_indices_size) * batch_rows; + const size_t cand_size = (is_top_k && chunk_elems > 256u) ? 512u : 0u; + + L->row_values_size = row_values_size; + L->row_indices_size = row_indices_size; + L->off_cand = off_cand; + L->batch_rows = batch_rows; + L->phase1_slot_size = ((off_cand + cand_size) + 255u) & ~(size_t) 255u; size_t off = 0; - if (total_rows > 1) { + if (total_rows > 1u) { VTCM_LAYOUT_ALLOC(off, off_phase1, L->phase1_slot_size * n_slots * n_hvx); } else { VTCM_LAYOUT_ALLOC(off, off_phase1, L->phase1_slot_size * n_chunks * n_slots); - const size_t merge_values_size = ((merge_elems * sizeof(float)) + 127) & ~127; - const size_t merge_indices_size = ((merge_elems * sizeof(int32_t)) + 127) & ~127; - VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_merge_values, merge_values_size, n_chunks > 1); - VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_merge_indices, merge_indices_size, n_chunks > 1); + const size_t merge_values_size = ((merge_elems * sizeof(float)) + 127u) & ~(size_t) 127u; + const size_t merge_indices_size = ((merge_elems * sizeof(int32_t)) + 127u) & ~(size_t) 127u; + VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_merge_values, merge_values_size, n_chunks > 1u); + VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_merge_indices, merge_indices_size, n_chunks > 1u); } L->total_bytes = off; } @@ -79,79 +132,111 @@ static inline bool htp_sort_solve_layout( memset(layout, 0, sizeof(*layout)); - if (total_rows > 1) { - uint32_t n_hvx = total_rows < n_hvx_max ? total_rows : n_hvx_max; - - uint32_t n_vec = (ne00 + 31) / 32; - uint32_t n_vec_pow2 = 1; - while (n_vec_pow2 < n_vec) n_vec_pow2 <<= 1; - uint32_t ne00_padded = n_vec_pow2 * 32; + if (is_top_k && k >= ne00) { + htp_sort_vtcm_layout_build(layout, ne00, total_rows, ne00, 1, 0, 1, 1, k, true); + if (layout->total_bytes > vtcm_budget) { + return false; + } + uint32_t n_hvx = 1u; + if (total_rows > 1u && (size_t) total_rows * k * sizeof(int32_t) > 16384u) { + const uint32_t b = layout->batch_rows > 0u ? layout->batch_rows : 1u; + const uint32_t max_w = (total_rows + b - 1u) / b; + n_hvx = max_w < n_hvx_max ? max_w : n_hvx_max; + } + htp_sort_vtcm_layout_build(layout, ne00, total_rows, ne00, 1, 0, n_hvx, 1, k, true); + return layout->total_bytes <= vtcm_budget; + } - size_t values_size = ((ne00_padded * sizeof(float)) + 127) & ~127; - size_t indices_size = ((ne00_padded * sizeof(int32_t)) + 127) & ~127; - size_t spad_per_slot = ((values_size + indices_size) + 255) & ~255; + if (total_rows > 1u) { + uint32_t n_hvx = total_rows < n_hvx_max ? total_rows : n_hvx_max; + if (ne00 <= 128u) { + const uint32_t cap = (total_rows >= 4u) ? ((total_rows + 3u) >> 2) : 1u; + if (n_hvx > cap) { + n_hvx = cap; + } + } - uint32_t n_slots = 2; - if (spad_per_slot * 2 > vtcm_budget) { - n_slots = 1; + uint32_t ne00_padded = 0u; + if (is_top_k && ne00 > 256u) { + ne00_padded = (ne00 + 31u) & ~31u; + } else { + const uint32_t n_vec = (ne00 + 31u) >> 5; + uint32_t n_vec_pow2 = 1u; + while (n_vec_pow2 < n_vec) { + n_vec_pow2 <<= 1; + } + ne00_padded = n_vec_pow2 * 32u; } - size_t spad_per_hvx = spad_per_slot * n_slots; + uint32_t n_slots = 2u; + htp_sort_vtcm_layout_build(layout, ne00, total_rows, ne00_padded, 1, 0, 1, n_slots, k, is_top_k); + if (layout->total_bytes > vtcm_budget) { + n_slots = 1u; + } - while (n_hvx > 1 && (spad_per_hvx * n_hvx) > vtcm_budget) { + htp_sort_vtcm_layout_build(layout, ne00, total_rows, ne00_padded, 1, 0, n_hvx, n_slots, k, is_top_k); + while (n_hvx > 1u && layout->total_bytes > vtcm_budget) { n_hvx--; + htp_sort_vtcm_layout_build(layout, ne00, total_rows, ne00_padded, 1, 0, n_hvx, n_slots, k, is_top_k); + } + if (layout->total_bytes > vtcm_budget && n_slots > 1u) { + n_slots = 1u; + htp_sort_vtcm_layout_build(layout, ne00, total_rows, ne00_padded, 1, 0, n_hvx, n_slots, k, is_top_k); } - - htp_sort_vtcm_layout_build(layout, total_rows, ne00_padded, 1, 0, n_hvx, n_slots); return layout->total_bytes <= vtcm_budget; } - uint32_t n_vec = (ne00 + 31) / 32; - uint32_t n_vec_pow2 = 1; - while (n_vec_pow2 < n_vec) n_vec_pow2 <<= 1; - - uint32_t n_chunks = 1; - if (ne00 > 1024) { - while (n_chunks * 2 <= n_hvx_max && n_chunks * 2 <= n_vec_pow2) { - n_chunks *= 2; - } + const uint32_t n_vec = (ne00 + 31u) >> 5; + uint32_t n_vec_pow2 = 1u; + while (n_vec_pow2 < n_vec) { + n_vec_pow2 <<= 1; } - uint32_t chunk_n_vec = n_vec_pow2 / n_chunks; - uint32_t chunk_elems = chunk_n_vec * 32; - uint32_t merge_elems = 0; - - if (n_chunks > 1) { - if (is_top_k) { - uint32_t local_k = k < chunk_elems ? k : chunk_elems; - uint32_t total_candidates = n_chunks * local_k; - uint32_t merge_n_vec = (total_candidates + 31) / 32; - uint32_t merge_n_vec_pow2 = 1; - while (merge_n_vec_pow2 < merge_n_vec) merge_n_vec_pow2 <<= 1; - merge_elems = merge_n_vec_pow2 * 32; - } else { - merge_elems = n_vec_pow2 * 32; + if (is_top_k) { + uint32_t n_chunks = 1u; + if (ne00 > 2048u) { + while (n_chunks * 2u <= n_hvx_max && (n_chunks * 2u) * 32u <= n_vec) { + n_chunks *= 2u; + } } - } - htp_sort_vtcm_layout_build(layout, 1, chunk_elems, n_chunks, merge_elems, n_chunks, 1); + while (n_chunks > 1u) { + const uint32_t chunk_n_vec = (n_vec + n_chunks - 1u) / n_chunks; + const uint32_t chunk_elems = chunk_n_vec * 32u; + const uint32_t local_k = k < chunk_elems ? k : chunk_elems; + const uint32_t merge_elems = ((n_chunks * local_k) + 31u) & ~31u; + + htp_sort_vtcm_layout_build(layout, ne00, 1, chunk_elems, n_chunks, merge_elems, n_chunks, 1, k, true); + if (layout->total_bytes <= vtcm_budget) { + return true; + } + n_chunks >>= 1; + } - if (layout->total_bytes > vtcm_budget && n_chunks > 1) { - n_chunks = 1; - chunk_elems = n_vec_pow2 * 32; - merge_elems = 0; - htp_sort_vtcm_layout_build(layout, 1, chunk_elems, n_chunks, merge_elems, 1, 1); + const uint32_t chunk_elems = (ne00 > 256u) ? (n_vec * 32u) : (n_vec_pow2 * 32u); + htp_sort_vtcm_layout_build(layout, ne00, 1, chunk_elems, 1, 0, 1, 1, k, true); + return layout->total_bytes <= vtcm_budget; } - if (layout->total_bytes > vtcm_budget) { - return false; + uint32_t n_chunks = 1u; + if (ne00 > 1024u) { + while (n_chunks * 2u <= n_hvx_max && n_chunks * 2u <= n_vec_pow2) { + n_chunks *= 2u; + } } - if (n_chunks == 1 && layout->phase1_slot_size * 2 <= vtcm_budget) { - htp_sort_vtcm_layout_build(layout, 1, chunk_elems, 1, 0, 1, 2); + while (n_chunks > 1u) { + const uint32_t chunk_elems = (n_vec_pow2 / n_chunks) * 32u; + const uint32_t merge_elems = n_vec_pow2 * 32u; + htp_sort_vtcm_layout_build(layout, ne00, 1, chunk_elems, n_chunks, merge_elems, n_chunks, 1, k, false); + if (layout->total_bytes <= vtcm_budget) { + return true; + } + n_chunks >>= 1; } - return true; + htp_sort_vtcm_layout_build(layout, ne00, 1, n_vec_pow2 * 32u, 1, 0, 1, 1, k, false); + return layout->total_bytes <= vtcm_budget; } #if defined(__cplusplus) diff --git a/ggml/src/ggml-hexagon/htp/binary-ops.c b/ggml/src/ggml-hexagon/htp/binary-ops.c index a5951556b131..cb8d7b428591 100644 --- a/ggml/src/ggml-hexagon/htp/binary-ops.c +++ b/ggml/src/ggml-hexagon/htp/binary-ops.c @@ -1,7 +1,3 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include @@ -9,6 +5,7 @@ #include #include "dma-queue.h" +#include "dma-pipeline.h" #include "hvx-utils.h" #define GGML_COMMON_DECL_C @@ -46,7 +43,13 @@ struct htp_binary_context { size_t src0_row_size_aligned; size_t src1_row_size_aligned; size_t dst_row_size_aligned; - size_t row_size_bytes; + size_t src0_row_size; + size_t src1_row_size; + size_t dst_row_size; + uint32_t src0_elem_size; + uint32_t src1_elem_size; + uint32_t dst_elem_size; + uint32_t src1_table_elem_size; bool split_at_ne01; bool split_at_ne02; @@ -54,34 +57,34 @@ struct htp_binary_context { void * compute; }; -#define htp_binary_preamble \ - const struct htp_tensor * src0 = octx->src[0]; \ - const struct htp_tensor * src1 = octx->src[1]; \ - const struct htp_tensor * dst = octx->dst; \ - \ - const uint32_t ne00 = src0->ne[0]; \ - const uint32_t ne01 = src0->ne[1]; \ - const uint32_t ne02 = src0->ne[2]; \ - const uint32_t ne03 = src0->ne[3]; \ - \ - const uint32_t ne10 = src1->ne[0]; \ - const uint32_t ne11 = src1->ne[1]; \ - const uint32_t ne12 = src1->ne[2]; \ - const uint32_t ne13 = src1->ne[3]; \ - \ - const uint32_t nb01 = src0->nb[1]; \ - const uint32_t nb02 = src0->nb[2]; \ - const uint32_t nb03 = src0->nb[3]; \ - \ - const uint32_t nb11 = src1->nb[1]; \ - const uint32_t nb12 = src1->nb[2]; \ - const uint32_t nb13 = src1->nb[3]; \ - \ - const uint32_t nb1 = dst->nb[1]; \ - const uint32_t nb2 = dst->nb[2]; \ - const uint32_t nb3 = dst->nb[3]; - -static inline uint32_t calc_block_size(struct htp_binary_context * bctx, uint32_t ir, uint32_t end_row, uint32_t ne01, uint32_t ne02) { +#define htp_binary_preamble \ + const struct htp_tensor * src0 = octx->src[0]; \ + const struct htp_tensor * src1 = octx->src[1]; \ + const struct htp_tensor * dst = octx->dst; \ + \ + const uint32_t __attribute__((unused)) ne00 = src0->ne[0]; \ + const uint32_t __attribute__((unused)) ne01 = src0->ne[1]; \ + const uint32_t __attribute__((unused)) ne02 = src0->ne[2]; \ + const uint32_t __attribute__((unused)) ne03 = src0->ne[3]; \ + \ + const uint32_t __attribute__((unused)) ne10 = src1->ne[0]; \ + const uint32_t __attribute__((unused)) ne11 = src1->ne[1]; \ + const uint32_t __attribute__((unused)) ne12 = src1->ne[2]; \ + const uint32_t __attribute__((unused)) ne13 = src1->ne[3]; \ + \ + const uint32_t __attribute__((unused)) nb01 = src0->nb[1]; \ + const uint32_t __attribute__((unused)) nb02 = src0->nb[2]; \ + const uint32_t __attribute__((unused)) nb03 = src0->nb[3]; \ + \ + const uint32_t __attribute__((unused)) nb11 = src1->nb[1]; \ + const uint32_t __attribute__((unused)) nb12 = src1->nb[2]; \ + const uint32_t __attribute__((unused)) nb13 = src1->nb[3]; \ + \ + const uint32_t __attribute__((unused)) nb1 = dst->nb[1]; \ + const uint32_t __attribute__((unused)) nb2 = dst->nb[2]; \ + const uint32_t __attribute__((unused)) nb3 = dst->nb[3]; + +static inline uint32_t calc_block_size(const struct htp_binary_context * bctx, uint32_t ir, uint32_t end_row, uint32_t ne01, uint32_t ne02) { uint32_t i03, i02, i01, rem; i03 = fastdiv(ir, &bctx->src0_dim12_div); rem = ir - i03 * (ne02 * ne01); @@ -236,125 +239,580 @@ DEFINE_COMPUTE_REPEAT(mul_f16, _Float16, hvx_mul_f16_uuu) DEFINE_COMPUTE_REPEAT(div_f32, float, hvx_div_f32_uuu) DEFINE_COMPUTE_REPEAT(div_f16, _Float16, hvx_div_f16_uuu) +static inline HVX_Vector binary_clamp_f16_finite_vec(HVX_Vector v, HVX_Vector max_f16, HVX_Vector min_f16, HVX_Vector inf) { + const HVX_VectorPred finite = Q6_Q_vcmp_gt_VsfVsf(inf, hvx_vec_abs_f32(v)); + const HVX_VectorPred high = Q6_Q_and_QQ(finite, Q6_Q_vcmp_gt_VsfVsf(v, max_f16)); + const HVX_VectorPred low = Q6_Q_and_QQ(finite, Q6_Q_vcmp_gt_VsfVsf(min_f16, v)); + v = Q6_V_vmux_QVV(high, max_f16, v); + return Q6_V_vmux_QVV(low, min_f16, v); +} + +#define BINARY_OP_ADD(a, b, nan_inf_mask) ((void) (nan_inf_mask), hvx_vec_add_f32_f32(a, b)) +#define BINARY_OP_SUB(a, b, nan_inf_mask) ((void) (nan_inf_mask), hvx_vec_sub_f32_f32(a, b)) +#define BINARY_OP_MUL(a, b, nan_inf_mask) ((void) (nan_inf_mask), hvx_vec_mul_f32_f32(a, b)) +#define BINARY_OP_DIV(a, b, nan_inf_mask) hvx_vec_mul_f32_f32(a, hvx_vec_inverse_f32_guard(b, nan_inf_mask)) + +#define BINARY_LOAD64_A_F16(vsrc, k, s_lo, s_hi) \ + HVX_VectorPair p_##s_lo = hvx_vec_f16_to_f32((vsrc)[k]); \ + HVX_Vector s_lo = Q6_V_lo_W(p_##s_lo); \ + HVX_Vector s_hi = Q6_V_hi_W(p_##s_lo) + +#define BINARY_LOAD64_A_F32(vsrc, k, s_lo, s_hi) \ + HVX_Vector s_lo = (vsrc)[2 * (k) + 0]; \ + HVX_Vector s_hi = (vsrc)[2 * (k) + 1] + +#define BINARY_LOAD64_U_F16(src, k, s_lo, s_hi) \ + HVX_VectorPair p_##s_lo = hvx_vec_f16_to_f32(hvx_vmemu((src) + (size_t) (k) * 128)); \ + HVX_Vector s_lo = Q6_V_lo_W(p_##s_lo); \ + HVX_Vector s_hi = Q6_V_hi_W(p_##s_lo) + +#define BINARY_LOAD64_U_F32(src, k, s_lo, s_hi) \ + HVX_Vector s_lo = hvx_vmemu((src) + (size_t) (2 * (k) + 0) * 128); \ + HVX_Vector s_hi = hvx_vmemu((src) + (size_t) (2 * (k) + 1) * 128) + +#define BINARY_TAIL_LO_A_F16(vsrc, nvec, s_lo, s_hi) \ + BINARY_LOAD64_A_F16(vsrc, nvec, s_lo, s_hi) +#define BINARY_TAIL_HI_A_F16(vsrc, nvec, s_hi) \ + ((void) (vsrc), (void) (nvec), (void) (s_hi)) + +#define BINARY_TAIL_LO_A_F32(vsrc, nvec, s_lo, s_hi) \ + HVX_Vector s_lo = (vsrc)[2 * (nvec)]; \ + HVX_Vector s_hi +#define BINARY_TAIL_HI_A_F32(vsrc, nvec, s_hi) \ + s_hi = (vsrc)[2 * (nvec) + 1] + +#define BINARY_TAIL_LO_U_F16(src, nvec, s_lo, s_hi) \ + BINARY_LOAD64_U_F16(src, nvec, s_lo, s_hi) +#define BINARY_TAIL_HI_U_F16(src, nvec, s_hi) \ + ((void) (src), (void) (nvec), (void) (s_hi)) + +#define BINARY_TAIL_LO_U_F32(src, nvec, s_lo, s_hi) \ + HVX_Vector s_lo = hvx_vmemu((src) + (size_t) (2 * (nvec)) * 128); \ + HVX_Vector s_hi +#define BINARY_TAIL_HI_U_F32(src, nvec, s_hi) \ + s_hi = hvx_vmemu((src) + (size_t) (2 * (nvec) + 1) * 128) + +#define DEFINE_BINARY_MIXED_F32(NAME, T0, T1, OP, UNROLL) \ +static void NAME(uint8_t * dst, const uint8_t * src0, const uint8_t * src1, uint32_t n) { \ + const HVX_Vector nan_inf_mask = Q6_V_vsplat_R(0x7f800000); \ + const uint32_t nvec = n / 64; \ + const uint32_t nloe = n % 64; \ + if (hex_is_aligned(dst, 128) && hex_is_aligned(src0, 128) && hex_is_aligned(src1, 128)) { \ + const HVX_Vector * restrict vsrc0 = (const HVX_Vector *) src0; \ + const HVX_Vector * restrict vsrc1 = (const HVX_Vector *) src1; \ + HVX_Vector * restrict vdst = (HVX_Vector *) dst; \ + UNROLL \ + for (uint32_t k = 0; k < nvec; k++) { \ + BINARY_LOAD64_A_##T0(vsrc0, k, s0_0, s0_1); \ + BINARY_LOAD64_A_##T1(vsrc1, k, s1_0, s1_1); \ + vdst[2 * k + 0] = OP(s0_0, s1_0, nan_inf_mask); \ + vdst[2 * k + 1] = OP(s0_1, s1_1, nan_inf_mask); \ + } \ + if (nloe) { \ + BINARY_TAIL_LO_A_##T0(vsrc0, nvec, s0_0, s0_1); \ + BINARY_TAIL_LO_A_##T1(vsrc1, nvec, s1_0, s1_1); \ + HVX_Vector out0 = OP(s0_0, s1_0, nan_inf_mask); \ + if (nloe <= 32) { \ + hvx_vec_store_a(&vdst[2 * nvec], nloe * sizeof(float), out0); \ + } else { \ + vdst[2 * nvec] = out0; \ + BINARY_TAIL_HI_A_##T0(vsrc0, nvec, s0_1); \ + BINARY_TAIL_HI_A_##T1(vsrc1, nvec, s1_1); \ + HVX_Vector out1 = OP(s0_1, s1_1, nan_inf_mask); \ + hvx_vec_store_a(&vdst[2 * nvec + 1], (nloe - 32) * sizeof(float), out1); \ + } \ + } \ + return; \ + } \ + for (uint32_t k = 0; k < nvec; k++) { \ + BINARY_LOAD64_U_##T0(src0, k, s0_0, s0_1); \ + BINARY_LOAD64_U_##T1(src1, k, s1_0, s1_1); \ + *(HVX_UVector *) (dst + (size_t) (2 * k + 0) * 128) = OP(s0_0, s1_0, nan_inf_mask); \ + *(HVX_UVector *) (dst + (size_t) (2 * k + 1) * 128) = OP(s0_1, s1_1, nan_inf_mask); \ + } \ + if (nloe) { \ + BINARY_TAIL_LO_U_##T0(src0, nvec, s0_0, s0_1); \ + BINARY_TAIL_LO_U_##T1(src1, nvec, s1_0, s1_1); \ + HVX_Vector out0 = OP(s0_0, s1_0, nan_inf_mask); \ + if (nloe <= 32) { \ + hvx_vec_store_u(dst + (size_t) (2 * nvec) * 128, nloe * sizeof(float), out0); \ + } else { \ + *(HVX_UVector *) (dst + (size_t) (2 * nvec) * 128) = out0; \ + BINARY_TAIL_HI_U_##T0(src0, nvec, s0_1); \ + BINARY_TAIL_HI_U_##T1(src1, nvec, s1_1); \ + HVX_Vector out1 = OP(s0_1, s1_1, nan_inf_mask); \ + hvx_vec_store_u(dst + (size_t) (2 * nvec + 1) * 128, (nloe - 32) * sizeof(float), out1); \ + } \ + } \ +} + +#define DEFINE_BINARY_MIXED_F16(NAME, T0, T1, OP, UNROLL) \ +static void NAME(uint8_t * dst, const uint8_t * src0, const uint8_t * src1, uint32_t n) { \ + const HVX_Vector nan_inf_mask = Q6_V_vsplat_R(0x7f800000); \ + const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); \ + const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); \ + const HVX_Vector inf = hvx_vec_splat_f32(INFINITY); \ + const uint32_t nvec = n / 64; \ + const uint32_t nloe = n % 64; \ + if (hex_is_aligned(dst, 128) && hex_is_aligned(src0, 128) && hex_is_aligned(src1, 128)) { \ + const HVX_Vector * restrict vsrc0 = (const HVX_Vector *) src0; \ + const HVX_Vector * restrict vsrc1 = (const HVX_Vector *) src1; \ + HVX_Vector * restrict vdst = (HVX_Vector *) dst; \ + UNROLL \ + for (uint32_t k = 0; k < nvec; k++) { \ + BINARY_LOAD64_A_##T0(vsrc0, k, s0_0, s0_1); \ + BINARY_LOAD64_A_##T1(vsrc1, k, s1_0, s1_1); \ + HVX_Vector out0 = OP(s0_0, s1_0, nan_inf_mask); \ + HVX_Vector out1 = OP(s0_1, s1_1, nan_inf_mask); \ + out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \ + out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \ + vdst[k] = hvx_vec_f32_to_f16(out0, out1); \ + } \ + if (nloe) { \ + BINARY_TAIL_LO_A_##T0(vsrc0, nvec, s0_0, s0_1); \ + BINARY_TAIL_LO_A_##T1(vsrc1, nvec, s1_0, s1_1); \ + HVX_Vector out0 = OP(s0_0, s1_0, nan_inf_mask); \ + out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \ + HVX_Vector out1 = Q6_V_vzero(); \ + if (nloe > 32) { \ + BINARY_TAIL_HI_A_##T0(vsrc0, nvec, s0_1); \ + BINARY_TAIL_HI_A_##T1(vsrc1, nvec, s1_1); \ + out1 = OP(s0_1, s1_1, nan_inf_mask); \ + out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \ + } \ + HVX_Vector packed = hvx_vec_f32_to_f16(out0, out1); \ + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), packed); \ + } \ + return; \ + } \ + for (uint32_t k = 0; k < nvec; k++) { \ + BINARY_LOAD64_U_##T0(src0, k, s0_0, s0_1); \ + BINARY_LOAD64_U_##T1(src1, k, s1_0, s1_1); \ + HVX_Vector out0 = OP(s0_0, s1_0, nan_inf_mask); \ + HVX_Vector out1 = OP(s0_1, s1_1, nan_inf_mask); \ + out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \ + out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \ + *(HVX_UVector *) (dst + (size_t) k * 128) = hvx_vec_f32_to_f16(out0, out1); \ + } \ + if (nloe) { \ + BINARY_TAIL_LO_U_##T0(src0, nvec, s0_0, s0_1); \ + BINARY_TAIL_LO_U_##T1(src1, nvec, s1_0, s1_1); \ + HVX_Vector out0 = OP(s0_0, s1_0, nan_inf_mask); \ + out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \ + HVX_Vector out1 = Q6_V_vzero(); \ + if (nloe > 32) { \ + BINARY_TAIL_HI_U_##T0(src0, nvec, s0_1); \ + BINARY_TAIL_HI_U_##T1(src1, nvec, s1_1); \ + out1 = OP(s0_1, s1_1, nan_inf_mask); \ + out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \ + } \ + HVX_Vector packed = hvx_vec_f32_to_f16(out0, out1); \ + hvx_vec_store_u(dst + (size_t) nvec * 128, nloe * sizeof(_Float16), packed); \ + } \ +} + +#define DEFINE_BINARY_MIXED_F16_F16_F16(NAME, OP) \ +static void NAME(uint8_t * dst, const uint8_t * src0, const uint8_t * src1, uint32_t n) { \ + const HVX_Vector nan_inf_mask = Q6_V_vsplat_R(0x7f800000); \ + const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); \ + const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); \ + const HVX_Vector inf = hvx_vec_splat_f32(INFINITY); \ + const uint32_t nvec = n / 64; \ + const uint32_t nloe = n % 64; \ + if (hex_is_aligned(dst, 128) && hex_is_aligned(src0, 128) && hex_is_aligned(src1, 128)) { \ + const HVX_Vector * restrict vsrc0 = (const HVX_Vector *) src0; \ + const HVX_Vector * restrict vsrc1 = (const HVX_Vector *) src1; \ + HVX_Vector * restrict vdst = (HVX_Vector *) dst; \ + _Pragma("unroll(2)") \ + for (uint32_t k = 0; k < nvec; k++) { \ + HVX_VectorPair p0 = hvx_vec_f16_to_f32_shuff(vsrc0[k]); \ + HVX_VectorPair p1 = hvx_vec_f16_to_f32_shuff(vsrc1[k]); \ + HVX_Vector out0 = OP(Q6_V_lo_W(p0), Q6_V_lo_W(p1), nan_inf_mask); \ + HVX_Vector out1 = OP(Q6_V_hi_W(p0), Q6_V_hi_W(p1), nan_inf_mask); \ + out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \ + out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \ + vdst[k] = hvx_vec_f32_to_f16_shuff(out0, out1); \ + } \ + if (nloe) { \ + HVX_VectorPair p0 = hvx_vec_f16_to_f32_shuff(vsrc0[nvec]); \ + HVX_VectorPair p1 = hvx_vec_f16_to_f32_shuff(vsrc1[nvec]); \ + HVX_Vector out0 = OP(Q6_V_lo_W(p0), Q6_V_lo_W(p1), nan_inf_mask); \ + HVX_Vector out1 = OP(Q6_V_hi_W(p0), Q6_V_hi_W(p1), nan_inf_mask); \ + out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \ + out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \ + HVX_Vector packed = hvx_vec_f32_to_f16_shuff(out0, out1); \ + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), packed); \ + } \ + return; \ + } \ + for (uint32_t k = 0; k < nvec; k++) { \ + HVX_VectorPair p0 = hvx_vec_f16_to_f32_shuff(hvx_vmemu(src0 + (size_t) k * 128)); \ + HVX_VectorPair p1 = hvx_vec_f16_to_f32_shuff(hvx_vmemu(src1 + (size_t) k * 128)); \ + HVX_Vector out0 = OP(Q6_V_lo_W(p0), Q6_V_lo_W(p1), nan_inf_mask); \ + HVX_Vector out1 = OP(Q6_V_hi_W(p0), Q6_V_hi_W(p1), nan_inf_mask); \ + out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \ + out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \ + *(HVX_UVector *) (dst + (size_t) k * 128) = hvx_vec_f32_to_f16_shuff(out0, out1); \ + } \ + if (nloe) { \ + HVX_VectorPair p0 = hvx_vec_f16_to_f32_shuff(hvx_vmemu(src0 + (size_t) nvec * 128)); \ + HVX_VectorPair p1 = hvx_vec_f16_to_f32_shuff(hvx_vmemu(src1 + (size_t) nvec * 128)); \ + HVX_Vector out0 = OP(Q6_V_lo_W(p0), Q6_V_lo_W(p1), nan_inf_mask); \ + HVX_Vector out1 = OP(Q6_V_hi_W(p0), Q6_V_hi_W(p1), nan_inf_mask); \ + out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \ + out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \ + HVX_Vector packed = hvx_vec_f32_to_f16_shuff(out0, out1); \ + hvx_vec_store_u(dst + (size_t) nvec * 128, nloe * sizeof(_Float16), packed); \ + } \ +} + +#define DEFINE_BINARY_MIXED_OP(OP_NAME, OP, UNROLL) \ + DEFINE_BINARY_MIXED_F16(binary_##OP_NAME##_f16_f32_f16, F16, F32, OP, UNROLL) \ + DEFINE_BINARY_MIXED_F32(binary_##OP_NAME##_f16_f32_f32, F16, F32, OP, UNROLL) \ + DEFINE_BINARY_MIXED_F16(binary_##OP_NAME##_f32_f16_f16, F32, F16, OP, UNROLL) \ + DEFINE_BINARY_MIXED_F32(binary_##OP_NAME##_f32_f16_f32, F32, F16, OP, UNROLL) \ + DEFINE_BINARY_MIXED_F32(binary_##OP_NAME##_f16_f16_f32, F16, F16, OP, UNROLL) \ + DEFINE_BINARY_MIXED_F16(binary_##OP_NAME##_f32_f32_f16, F32, F32, OP, UNROLL) + +DEFINE_BINARY_MIXED_OP(add, BINARY_OP_ADD, _Pragma("unroll(2)")) +DEFINE_BINARY_MIXED_OP(sub, BINARY_OP_SUB, _Pragma("unroll(2)")) +DEFINE_BINARY_MIXED_OP(mul, BINARY_OP_MUL, _Pragma("unroll(2)")) +DEFINE_BINARY_MIXED_OP(div, BINARY_OP_DIV, ) +DEFINE_BINARY_MIXED_F16_F16_F16(binary_add_f16_f16_f16, BINARY_OP_ADD) + +#define DEFINE_COMPUTE_MIXED_SHAPES(OP_NAME, TYPES) \ + DEFINE_COMPUTE_SAME_SHAPE(OP_NAME##_##TYPES, binary_##OP_NAME##_##TYPES) \ + DEFINE_COMPUTE_ROW_BCAST(OP_NAME##_##TYPES, binary_##OP_NAME##_##TYPES) \ + DEFINE_COMPUTE_COMPLEX(OP_NAME##_##TYPES, binary_##OP_NAME##_##TYPES) + +#define DEFINE_COMPUTE_MIXED_REPEAT(OP_NAME, TYPES, DST_TYPE, SRC0_TYPE) \ +static void compute_repeat_##OP_NAME##_##TYPES( \ + uint8_t * dst, const uint8_t * src0, const uint8_t * src1_plane, \ + uint32_t i01, uint32_t ne11, const struct fastdiv_values * div11, uint32_t src1_stride, \ + uint32_t n_rows, size_t dst_stride, size_t src0_stride, uint32_t ne00, uint32_t ne10) { \ + for (uint32_t r = 0; r < n_rows; r++) { \ + uint32_t i11 = fastmodulo(i01 + r, ne11, div11); \ + const uint8_t * r_src1 = src1_plane + i11 * src1_stride; \ + for (uint32_t c = 0; c < ne00; c += ne10) { \ + binary_##OP_NAME##_##TYPES(dst + r * dst_stride + (size_t) c * sizeof(DST_TYPE), \ + src0 + r * src0_stride + (size_t) c * sizeof(SRC0_TYPE), r_src1, MIN(ne10, ne00 - c)); \ + } \ + } \ +} + +#define DEFINE_COMPUTE_MIXED_ALL(OP_NAME) \ + DEFINE_COMPUTE_MIXED_SHAPES(OP_NAME, f16_f32_f16) \ + DEFINE_COMPUTE_MIXED_SHAPES(OP_NAME, f16_f32_f32) \ + DEFINE_COMPUTE_MIXED_SHAPES(OP_NAME, f32_f16_f16) \ + DEFINE_COMPUTE_MIXED_SHAPES(OP_NAME, f32_f16_f32) \ + DEFINE_COMPUTE_MIXED_SHAPES(OP_NAME, f16_f16_f32) \ + DEFINE_COMPUTE_MIXED_SHAPES(OP_NAME, f32_f32_f16) \ + DEFINE_COMPUTE_MIXED_REPEAT(OP_NAME, f16_f32_f16, _Float16, _Float16) \ + DEFINE_COMPUTE_MIXED_REPEAT(OP_NAME, f16_f32_f32, float, _Float16) \ + DEFINE_COMPUTE_MIXED_REPEAT(OP_NAME, f32_f16_f16, _Float16, float) \ + DEFINE_COMPUTE_MIXED_REPEAT(OP_NAME, f32_f16_f32, float, float) \ + DEFINE_COMPUTE_MIXED_REPEAT(OP_NAME, f16_f16_f32, float, _Float16) \ + DEFINE_COMPUTE_MIXED_REPEAT(OP_NAME, f32_f32_f16, _Float16, float) + +DEFINE_COMPUTE_MIXED_ALL(add) +DEFINE_COMPUTE_MIXED_ALL(sub) +DEFINE_COMPUTE_MIXED_ALL(mul) +DEFINE_COMPUTE_MIXED_ALL(div) + +#define DEFINE_BINARY_MIXED_SCALAR_F16_F16(NAME, OP) \ +static void NAME(uint8_t * dst, const uint8_t * src0, float val, uint32_t n) { \ + const HVX_Vector nan_inf_mask = Q6_V_vsplat_R(0x7f800000); \ + const HVX_Vector val_vec = hvx_vec_splat_f32(val); \ + const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); \ + const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); \ + const HVX_Vector inf = hvx_vec_splat_f32(INFINITY); \ + const HVX_Vector * restrict vsrc0 = (const HVX_Vector *) src0; \ + HVX_Vector * restrict vdst = (HVX_Vector *) dst; \ + const uint32_t nvec = n / 64; \ + const uint32_t nloe = n % 64; \ + _Pragma("unroll(2)") \ + for (uint32_t k = 0; k < nvec; k++) { \ + HVX_VectorPair pair = hvx_vec_f16_to_f32_shuff(vsrc0[k]); \ + HVX_Vector out0 = OP(Q6_V_lo_W(pair), val_vec, nan_inf_mask); \ + HVX_Vector out1 = OP(Q6_V_hi_W(pair), val_vec, nan_inf_mask); \ + out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \ + out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \ + vdst[k] = hvx_vec_f32_to_f16_shuff(out0, out1); \ + } \ + if (nloe) { \ + HVX_VectorPair pair = hvx_vec_f16_to_f32_shuff(vsrc0[nvec]); \ + HVX_Vector out0 = OP(Q6_V_lo_W(pair), val_vec, nan_inf_mask); \ + HVX_Vector out1 = OP(Q6_V_hi_W(pair), val_vec, nan_inf_mask); \ + out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \ + out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \ + HVX_Vector packed = hvx_vec_f32_to_f16_shuff(out0, out1); \ + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), packed); \ + } \ +} + +#define DEFINE_BINARY_MIXED_SCALAR_F16_F32(NAME, OP) \ +static void NAME(uint8_t * dst, const uint8_t * src0, float val, uint32_t n) { \ + const HVX_Vector nan_inf_mask = Q6_V_vsplat_R(0x7f800000); \ + const HVX_Vector val_vec = hvx_vec_splat_f32(val); \ + const HVX_Vector * restrict vsrc0 = (const HVX_Vector *) src0; \ + HVX_Vector * restrict vdst = (HVX_Vector *) dst; \ + const uint32_t nvec = n / 64; \ + const uint32_t nloe = n % 64; \ + _Pragma("unroll(2)") \ + for (uint32_t k = 0; k < nvec; k++) { \ + HVX_VectorPair pair = hvx_vec_f16_to_f32(vsrc0[k]); \ + vdst[2 * k + 0] = OP(Q6_V_lo_W(pair), val_vec, nan_inf_mask); \ + vdst[2 * k + 1] = OP(Q6_V_hi_W(pair), val_vec, nan_inf_mask); \ + } \ + if (nloe) { \ + HVX_VectorPair pair = hvx_vec_f16_to_f32(vsrc0[nvec]); \ + HVX_Vector out0 = OP(Q6_V_lo_W(pair), val_vec, nan_inf_mask); \ + if (nloe <= 32) { \ + hvx_vec_store_a(&vdst[2 * nvec], nloe * sizeof(float), out0); \ + } else { \ + vdst[2 * nvec] = out0; \ + HVX_Vector out1 = OP(Q6_V_hi_W(pair), val_vec, nan_inf_mask); \ + hvx_vec_store_a(&vdst[2 * nvec + 1], (nloe - 32) * sizeof(float), out1); \ + } \ + } \ +} + +#define DEFINE_BINARY_MIXED_SCALAR_F32_F16(NAME, OP) \ +static void NAME(uint8_t * dst, const uint8_t * src0, float val, uint32_t n) { \ + const HVX_Vector nan_inf_mask = Q6_V_vsplat_R(0x7f800000); \ + const HVX_Vector val_vec = hvx_vec_splat_f32(val); \ + const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); \ + const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); \ + const HVX_Vector inf = hvx_vec_splat_f32(INFINITY); \ + const HVX_Vector * restrict vsrc0 = (const HVX_Vector *) src0; \ + HVX_Vector * restrict vdst = (HVX_Vector *) dst; \ + const uint32_t nvec = n / 64; \ + const uint32_t nloe = n % 64; \ + _Pragma("unroll(2)") \ + for (uint32_t k = 0; k < nvec; k++) { \ + HVX_Vector out0 = OP(vsrc0[2 * k + 0], val_vec, nan_inf_mask); \ + HVX_Vector out1 = OP(vsrc0[2 * k + 1], val_vec, nan_inf_mask); \ + out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \ + out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \ + vdst[k] = hvx_vec_f32_to_f16(out0, out1); \ + } \ + if (nloe) { \ + HVX_Vector out0 = OP(vsrc0[2 * nvec], val_vec, nan_inf_mask); \ + out0 = binary_clamp_f16_finite_vec(out0, max_f16, min_f16, inf); \ + HVX_Vector out1 = Q6_V_vzero(); \ + if (nloe > 32) { \ + out1 = OP(vsrc0[2 * nvec + 1], val_vec, nan_inf_mask); \ + out1 = binary_clamp_f16_finite_vec(out1, max_f16, min_f16, inf); \ + } \ + HVX_Vector packed = hvx_vec_f32_to_f16(out0, out1); \ + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), packed); \ + } \ +} + +#define DEFINE_BINARY_MIXED_SCALAR_F32_F32(NAME, OP) \ +static void NAME(uint8_t * dst, const uint8_t * src0, float val, uint32_t n) { \ + const HVX_Vector nan_inf_mask = Q6_V_vsplat_R(0x7f800000); \ + const HVX_Vector val_vec = hvx_vec_splat_f32(val); \ + const HVX_Vector * restrict vsrc0 = (const HVX_Vector *) src0; \ + HVX_Vector * restrict vdst = (HVX_Vector *) dst; \ + const uint32_t nvec = n / 32; \ + const uint32_t nloe = n % 32; \ + _Pragma("unroll(2)") \ + for (uint32_t k = 0; k < nvec; k++) { \ + vdst[k] = OP(vsrc0[k], val_vec, nan_inf_mask); \ + } \ + if (nloe) { \ + HVX_Vector out = OP(vsrc0[nvec], val_vec, nan_inf_mask); \ + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(float), out); \ + } \ +} + +#define DEFINE_COMPUTE_MIXED_SCALAR(NAME, SRC0_TYPE, DST_TYPE, FN) \ +static void compute_scalar_##NAME( \ + uint8_t * dst, const uint8_t * src0, const void * s1_table, \ + uint32_t cur_i11, uint32_t ne11, uint32_t n_rows, \ + size_t dst_stride, size_t src0_stride, uint32_t ne00) { \ + const float * table = (const float *) s1_table; \ + for (uint32_t r = 0; r < n_rows; r++) { \ + FN(dst + r * dst_stride, src0 + r * src0_stride, table[cur_i11], ne00); \ + if (ne11 > 1 && ++cur_i11 == ne11) cur_i11 = 0; \ + } \ +} + +#define DEFINE_COMPUTE_MIXED_SCALAR_OP(OP_NAME, OP) \ + DEFINE_BINARY_MIXED_SCALAR_F16_F16(binary_scalar_##OP_NAME##_f16_f16, OP) \ + DEFINE_BINARY_MIXED_SCALAR_F16_F32(binary_scalar_##OP_NAME##_f16_f32, OP) \ + DEFINE_BINARY_MIXED_SCALAR_F32_F16(binary_scalar_##OP_NAME##_f32_f16, OP) \ + DEFINE_BINARY_MIXED_SCALAR_F32_F32(binary_scalar_##OP_NAME##_f32_f32, OP) \ + DEFINE_COMPUTE_MIXED_SCALAR(OP_NAME##_f16_f32_f16, _Float16, _Float16, binary_scalar_##OP_NAME##_f16_f16) \ + DEFINE_COMPUTE_MIXED_SCALAR(OP_NAME##_f16_f32_f32, _Float16, float, binary_scalar_##OP_NAME##_f16_f32) \ + DEFINE_COMPUTE_MIXED_SCALAR(OP_NAME##_f32_f16_f16, float, _Float16, binary_scalar_##OP_NAME##_f32_f16) \ + DEFINE_COMPUTE_MIXED_SCALAR(OP_NAME##_f32_f16_f32, float, float, binary_scalar_##OP_NAME##_f32_f32) \ + DEFINE_COMPUTE_MIXED_SCALAR(OP_NAME##_f16_f16_f32, _Float16, float, binary_scalar_##OP_NAME##_f16_f32) \ + DEFINE_COMPUTE_MIXED_SCALAR(OP_NAME##_f32_f32_f16, float, _Float16, binary_scalar_##OP_NAME##_f32_f16) + +DEFINE_COMPUTE_MIXED_SCALAR_OP(add, BINARY_OP_ADD) +DEFINE_COMPUTE_MIXED_SCALAR_OP(sub, BINARY_OP_SUB) +DEFINE_COMPUTE_MIXED_SCALAR_OP(mul, BINARY_OP_MUL) +DEFINE_COMPUTE_MIXED_SCALAR_OP(div, BINARY_OP_DIV) + typedef void (*compute_add_id_t)( uint8_t * dst, const uint8_t * src0, const uint8_t * src1_data, const int32_t * src2_ids, uint32_t i01, uint32_t i02, uint32_t ne01, uint32_t src1_stride, uint32_t n_rows, size_t dst_stride, size_t src0_stride, uint32_t ne00); -static void compute_add_id_f32( - uint8_t * dst, const uint8_t * src0, const uint8_t * src1_data, const int32_t * src2_ids, - uint32_t i01, uint32_t i02, uint32_t ne01, uint32_t src1_stride, - uint32_t n_rows, size_t dst_stride, size_t src0_stride, uint32_t ne00) { - for (uint32_t r = 0; r < n_rows; r++) { - uint32_t r_i01 = i01 + r; - const int32_t idx = src2_ids[i02 * ne01 + r_i01]; - if (idx < 0) { - memcpy(dst + r * dst_stride, src0 + r * src0_stride, ne00 * sizeof(float)); - continue; - } - const uint8_t * r_src1 = src1_data + idx * src1_stride; - const uint8_t * r_src0 = src0 + r * src0_stride; - uint8_t * r_dst = dst + r * dst_stride; - hvx_add_f32_aaa(r_dst, r_src0, r_src1, ne00); - } +#define DEFINE_ADD_ID_COPY(NAME, STMT) \ +static void add_id_copy_##NAME(uint8_t * dst, const uint8_t * src, uint32_t n) { \ + STMT; \ } -// 1. Scalar src1 in VTCM via DMA (ne10 == 1) -static void binary_thread_scalar(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { - struct htp_binary_context * bctx = (struct htp_binary_context *) data; - struct htp_ops_context * octx = bctx->octx; - htp_binary_preamble; +DEFINE_ADD_ID_COPY(f16_f16, hvx_copy_f16_aa(dst, src, n)) +DEFINE_ADD_ID_COPY(f32_f32, hvx_copy_f32_aa(dst, src, n)) +DEFINE_ADD_ID_COPY(f16_f32, binary_scalar_add_f16_f32(dst, src, 0.0f, n)) +DEFINE_ADD_ID_COPY(f32_f16, binary_scalar_add_f32_f16(dst, src, 0.0f, n)) + +#define DEFINE_COMPUTE_ADD_ID(NAME, ADD_FN, COPY_FN) \ +static void compute_add_id_##NAME( \ + uint8_t * dst, const uint8_t * src0, const uint8_t * src1_data, const int32_t * src2_ids, \ + uint32_t i01, uint32_t i02, uint32_t ne01, uint32_t src1_stride, \ + uint32_t n_rows, size_t dst_stride, size_t src0_stride, uint32_t ne00) { \ + for (uint32_t r = 0; r < n_rows; r++) { \ + const uint32_t r_i01 = i01 + r; \ + const int32_t idx = src2_ids[i02 * ne01 + r_i01]; \ + const uint8_t * r_src0 = src0 + r * src0_stride; \ + uint8_t * r_dst = dst + r * dst_stride; \ + if (idx < 0) { \ + COPY_FN(r_dst, r_src0, ne00); \ + continue; \ + } \ + const uint8_t * r_src1 = src1_data + idx * src1_stride; \ + ADD_FN(r_dst, r_src0, r_src1, ne00); \ + } \ +} + +DEFINE_COMPUTE_ADD_ID(f16_f16_f16, binary_add_f16_f16_f16, add_id_copy_f16_f16) +DEFINE_COMPUTE_ADD_ID(f32_f32_f32, hvx_add_f32_aaa, add_id_copy_f32_f32) +DEFINE_COMPUTE_ADD_ID(f16_f16_f32, binary_add_f16_f16_f32, add_id_copy_f16_f32) +DEFINE_COMPUTE_ADD_ID(f16_f32_f16, binary_add_f16_f32_f16, add_id_copy_f16_f16) +DEFINE_COMPUTE_ADD_ID(f16_f32_f32, binary_add_f16_f32_f32, add_id_copy_f16_f32) +DEFINE_COMPUTE_ADD_ID(f32_f16_f16, binary_add_f32_f16_f16, add_id_copy_f32_f16) +DEFINE_COMPUTE_ADD_ID(f32_f16_f32, binary_add_f32_f16_f32, add_id_copy_f32_f32) +DEFINE_COMPUTE_ADD_ID(f32_f32_f16, binary_add_f32_f32_f16, add_id_copy_f32_f16) + +struct binary_io_pipe_state { + const struct htp_binary_context * bctx; + dma_addr_t src0_data; + dma_addr_t dst_data; + const uint8_t * vtcm_src1; + const int32_t * vtcm_src2; + size_t s1_row_stride; + size_t s1_plane_stride; + size_t s1_vol_stride; + uint32_t ne00, ne01, ne02; + uint32_t ne10, ne11, ne12, ne13; + uint32_t nb01, nb02, nb03; + uint32_t nb1, nb2, nb3; + uint32_t ir; + uint32_t ir_end; +}; - const uint32_t elem_size = (src0->type == HTP_TYPE_F32) ? sizeof(float) : sizeof(_Float16); - const size_t plane_stride = (size_t) ne12 * ne11 * elem_size; - const size_t row_stride = (size_t) ne11 * elem_size; +static bool binary_io_next_task(void * ctx, struct dma_pipe_task * task) { + struct binary_io_pipe_state * s = (struct binary_io_pipe_state *) ctx; + if (s->ir >= s->ir_end) { + return false; + } + const uint32_t block_size = calc_block_size(s->bctx, s->ir, s->ir_end, s->ne01, s->ne02); + task->row = s->ir; + task->off = 0; + task->len = block_size; + task->aux = 0; + s->ir += block_size; + return true; +} - const uint32_t row_size_bytes = bctx->row_size_bytes; - const uint32_t start_row = bctx->row_start + bctx->nrows_per_hvx * ith; - const uint32_t end_row = MIN(start_row + bctx->nrows_per_hvx, bctx->row_start + bctx->total_rows); - if (start_row >= end_row) return; +static void binary_io_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct binary_io_pipe_state * s = (struct binary_io_pipe_state *) ctx; + const struct htp_binary_context * bctx = s->bctx; + const uint32_t i03 = fastdiv(task->row, &bctx->src0_dim12_div); + const uint32_t rem = task->row - i03 * (s->ne02 * s->ne01); + const uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div); + const uint32_t i01 = rem - i02 * s->ne01; + const dma_addr_t src0_addr = s->src0_data + (size_t) i03 * s->nb03 + (size_t) i02 * s->nb02 + (size_t) i01 * s->nb01; + dma_queue_push(dma_q, dma_make_data(in_spad, src0_addr), + bctx->src0_row_size_aligned, s->nb01, bctx->src0_row_size, task->len); +} - FARF(HIGH, "binary-scalar: %d/%d (%u:%u) row-size %u (%u)", - ith, nth, start_row, end_row, nb01, bctx->dst_row_size_aligned); +static void binary_io_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) { + struct binary_io_pipe_state * s = (struct binary_io_pipe_state *) ctx; + const struct htp_binary_context * bctx = s->bctx; + const uint32_t i03 = fastdiv(task->row, &bctx->src0_dim12_div); + const uint32_t rem = task->row - i03 * (s->ne02 * s->ne01); + const uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div); + const uint32_t i01 = rem - i02 * s->ne01; + const dma_addr_t dst_addr = s->dst_data + (size_t) i03 * s->nb3 + (size_t) i02 * s->nb2 + (size_t) i01 * s->nb1; + dma_queue_push(dma_q, dma_make_data(dst_addr, out_spad), + s->nb1, bctx->dst_row_size_aligned, bctx->dst_row_size, task->len); +} +static void binary_io_run(const htp_thread_t * th, unsigned int ith, struct htp_binary_context * bctx, + struct binary_io_pipe_state * s, dma_pipe_compute_io_fn compute) { const struct htp_binary_vtcm_layout * layout = &bctx->vtcm_layout; uint8_t * src0_spad_base = VTCM_LAYOUT_PTR(uint8_t, bctx->vtcm_base, layout->off_src0) + (ith * layout->src0_bytes_per_hvx); uint8_t * dst_spad_base = VTCM_LAYOUT_PTR(uint8_t, bctx->vtcm_base, layout->off_dst) + (ith * layout->dst_bytes_per_hvx); - size_t src0_spad_half = layout->src0_spad_half_size; - size_t dst_spad_half = layout->dst_spad_half_size; - const void * s1_table = VTCM_LAYOUT_PTR(const void, bctx->vtcm_base, layout->off_src1); + void * in_buf[2] = { src0_spad_base, src0_spad_base + layout->src0_spad_half_size }; + void * out_buf[2] = { dst_spad_base, dst_spad_base + layout->dst_spad_half_size }; - dma_queue * dma_q = th->dma_q; - uint32_t ir_prefetch = start_row; - int spad_idx = 0; - - for (int k = 0; k < 2 && ir_prefetch < end_row; k++) { - uint32_t current_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02); - uint32_t i03, i02, i01, rem; - i03 = fastdiv(ir_prefetch, &bctx->src0_dim12_div); - rem = ir_prefetch - i03 * (ne02 * ne01); - i02 = fastdiv(rem, &bctx->src0_dim1_div); - i01 = rem - i02 * ne01; - - dma_addr_t src0_curr = src0->data + i03 * nb03 + i02 * nb02 + i01 * nb01; - dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1; + dma_pipe_io_run(th->dma_q, th->trace, s, in_buf, out_buf, + binary_io_next_task, binary_io_push_in, compute, binary_io_push_out); +} - uint8_t * s0_spad = src0_spad_base + spad_idx * src0_spad_half; - uint8_t * d_spad = dst_spad_base + spad_idx * dst_spad_half; +static void binary_scalar_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct binary_io_pipe_state * s = (struct binary_io_pipe_state *) ctx; + const struct htp_binary_context * bctx = s->bctx; + const uint32_t i03 = fastdiv(task->row, &bctx->src0_dim12_div); + const uint32_t rem = task->row - i03 * (s->ne02 * s->ne01); + const uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div); + const uint32_t i01 = rem - i02 * s->ne01; - dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, 0); - dma_queue_push(dma_q, dma_make_data(s0_spad, src0_curr), bctx->src0_row_size_aligned, nb01, row_size_bytes, - current_block_size); - ir_prefetch += current_block_size; - spad_idx ^= 1; - } + const uint32_t i13 = fastmodulo(i03, s->ne13, &bctx->src1_dim3_div); + const uint32_t i12 = fastmodulo(i02, s->ne12, &bctx->src1_dim2_div); + const uint32_t i11 = fastmodulo(i01, s->ne11, &bctx->src1_dim1_div); + const uint8_t * scalar_table = s->vtcm_src1 + i13 * s->s1_plane_stride + i12 * s->s1_row_stride; - struct htp_thread_trace * tr = th->trace; compute_scalar_t compute = (compute_scalar_t) bctx->compute; + compute((uint8_t *) out_spad, (const uint8_t *) in_spad, scalar_table, i11, s->ne11, task->len, + bctx->dst_row_size_aligned, bctx->src0_row_size_aligned, s->ne00); +} - for (uint32_t ir = start_row; ir < end_row; ) { - uint32_t current_block_size = calc_block_size(bctx, ir, end_row, ne01, ne02); - - uint8_t * d_spad = (uint8_t *) dma_queue_pop(dma_q).src; - uint8_t * s0_spad = (uint8_t *) dma_queue_pop(dma_q).dst; - - uint32_t i03, i02, i01, rem; - i03 = fastdiv(ir, &bctx->src0_dim12_div); - rem = ir - i03 * (ne02 * ne01); - i02 = fastdiv(rem, &bctx->src0_dim1_div); - i01 = rem - i02 * ne01; - - uint32_t i13 = fastmodulo(i03, ne13, &bctx->src1_dim3_div); - uint32_t i12 = fastmodulo(i02, ne12, &bctx->src1_dim2_div); - uint32_t i11 = fastmodulo(i01, ne11, &bctx->src1_dim1_div); - const uint8_t * scalar_table = (const uint8_t *) s1_table + - i13 * plane_stride + i12 * row_stride; - - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); - compute(d_spad, s0_spad, scalar_table, i11, ne11, current_block_size, - bctx->dst_row_size_aligned, bctx->src0_row_size_aligned, ne00); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); +// 1. Scalar src1 in VTCM via DMA (ne10 == 1) +static void binary_thread_scalar(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + struct htp_binary_context * bctx = (struct htp_binary_context *) data; + struct htp_ops_context * octx = bctx->octx; + htp_binary_preamble; - dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1; - dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, - current_block_size); + const uint32_t start_row = bctx->row_start + bctx->nrows_per_hvx * ith; + const uint32_t end_row = MIN(start_row + bctx->nrows_per_hvx, bctx->row_start + bctx->total_rows); + if (start_row >= end_row) return; - if (ir_prefetch < end_row) { - uint32_t next_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02); - uint32_t p03, p02, p01, prem; - p03 = fastdiv(ir_prefetch, &bctx->src0_dim12_div); - prem = ir_prefetch - p03 * (ne02 * ne01); - p02 = fastdiv(prem, &bctx->src0_dim1_div); - p01 = prem - p02 * ne01; - dma_addr_t s0_next = src0->data + p03 * nb03 + p02 * nb02 + p01 * nb01; - dma_queue_push(dma_q, dma_make_data(s0_spad, s0_next), bctx->src0_row_size_aligned, nb01, row_size_bytes, - next_block_size); - ir_prefetch += next_block_size; - } - ir += current_block_size; - } + FARF(HIGH, "binary-scalar: %d/%d (%u:%u) row-size %u (%u)", + ith, nth, start_row, end_row, nb01, bctx->dst_row_size_aligned); - dma_queue_flush(dma_q); + struct binary_io_pipe_state s = { + .bctx = bctx, + .src0_data = src0->data, + .dst_data = dst->data, + .vtcm_src1 = VTCM_LAYOUT_PTR(const uint8_t, bctx->vtcm_base, bctx->vtcm_layout.off_src1), + .s1_row_stride = (size_t) ne11 * bctx->src1_table_elem_size, + .s1_plane_stride = (size_t) ne12 * ne11 * bctx->src1_table_elem_size, + .ne00 = ne00, .ne01 = ne01, .ne02 = ne02, + .ne10 = ne10, .ne11 = ne11, .ne12 = ne12, .ne13 = ne13, + .nb01 = nb01, .nb02 = nb02, .nb03 = nb03, + .nb1 = nb1, .nb2 = nb2, .nb3 = nb3, + .ir = start_row, + .ir_end = end_row, + }; + + binary_io_run(th, ith, bctx, &s, binary_scalar_compute); } // 2. Vector Same Shape (ne1x == ne0x) or Simple Broadcast @@ -363,7 +821,9 @@ static void binary_thread_vector_same_shape(const htp_thread_t * th, unsigned in struct htp_ops_context * octx = bctx->octx; htp_binary_preamble; - const uint32_t row_size_bytes = bctx->row_size_bytes; + const uint32_t src0_row_size = bctx->src0_row_size; + const uint32_t src1_row_size = bctx->src1_row_size; + const uint32_t dst_row_size = bctx->dst_row_size; const uint32_t start_row = bctx->row_start + bctx->nrows_per_hvx * ith; const uint32_t end_row = MIN(start_row + bctx->nrows_per_hvx, bctx->row_start + bctx->total_rows); if (start_row >= end_row) return; @@ -400,8 +860,8 @@ static void binary_thread_vector_same_shape(const htp_thread_t * th, unsigned in uint8_t * s1_spad = src1_spad_base + spad_idx * src1_spad_half; uint8_t * d_spad = dst_spad_base + spad_idx * dst_spad_half; - dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, 0); - dma_queue_push(dma_q, dma_make_data(s0_spad, src0_curr), bctx->src0_row_size_aligned, nb01, row_size_bytes, current_block_size); + dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, dst_row_size, 0); + dma_queue_push(dma_q, dma_make_data(s0_spad, src0_curr), bctx->src0_row_size_aligned, nb01, src0_row_size, current_block_size); for (uint32_t s = 1; s < n_srcs; s++) { const struct htp_tensor * src_s = octx->src[s]; uint32_t is3 = (src_s->ne[3] == 1) ? 0 : i03; @@ -409,7 +869,7 @@ static void binary_thread_vector_same_shape(const htp_thread_t * th, unsigned in uint32_t is1 = (src_s->ne[1] == 1) ? 0 : i01; dma_addr_t s_curr = src_s->data + is3 * src_s->nb[3] + is2 * src_s->nb[2] + is1 * src_s->nb[1]; uint8_t * s_spad = s1_spad + (s - 1) * 2 * src1_spad_half; - dma_queue_push(dma_q, dma_make_data(s_spad, s_curr), bctx->src1_row_size_aligned, src_s->nb[1], row_size_bytes, current_block_size); + dma_queue_push(dma_q, dma_make_data(s_spad, s_curr), bctx->src1_row_size_aligned, src_s->nb[1], src1_row_size, current_block_size); } ir_prefetch += current_block_size; spad_idx ^= 1; @@ -440,7 +900,7 @@ static void binary_thread_vector_same_shape(const htp_thread_t * th, unsigned in i02 = fastdiv(rem, &bctx->src0_dim1_div); i01 = rem - i02 * ne01; dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1; - dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, current_block_size); + dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, dst_row_size, current_block_size); if (ir_prefetch < end_row) { uint32_t next_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02); @@ -451,7 +911,7 @@ static void binary_thread_vector_same_shape(const htp_thread_t * th, unsigned in p01 = prem - p02 * ne01; dma_addr_t s0_next = src0->data + p03 * nb03 + p02 * nb02 + p01 * nb01; - dma_queue_push(dma_q, dma_make_data(s0_spad, s0_next), bctx->src0_row_size_aligned, nb01, row_size_bytes, next_block_size); + dma_queue_push(dma_q, dma_make_data(s0_spad, s0_next), bctx->src0_row_size_aligned, nb01, src0_row_size, next_block_size); for (uint32_t s = 1; s < n_srcs; s++) { const struct htp_tensor * src_s = octx->src[s]; @@ -460,7 +920,7 @@ static void binary_thread_vector_same_shape(const htp_thread_t * th, unsigned in uint32_t ps1 = (src_s->ne[1] == 1) ? 0 : p01; dma_addr_t s_next = src_s->data + ps3 * src_s->nb[3] + ps2 * src_s->nb[2] + ps1 * src_s->nb[1]; uint8_t * s_spad = s1_spad + (s - 1) * 2 * src1_spad_half; - dma_queue_push(dma_q, dma_make_data(s_spad, s_next), bctx->src1_row_size_aligned, src_s->nb[1], row_size_bytes, next_block_size); + dma_queue_push(dma_q, dma_make_data(s_spad, s_next), bctx->src1_row_size_aligned, src_s->nb[1], src1_row_size, next_block_size); } ir_prefetch += next_block_size; @@ -471,13 +931,20 @@ static void binary_thread_vector_same_shape(const htp_thread_t * th, unsigned in dma_queue_flush(dma_q); } +static void binary_row_bcast_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct binary_io_pipe_state * s = (struct binary_io_pipe_state *) ctx; + const struct htp_binary_context * bctx = s->bctx; + compute_row_bcast_t compute = (compute_row_bcast_t) bctx->compute; + compute((uint8_t *) out_spad, (const uint8_t *) in_spad, s->vtcm_src1, task->len, + bctx->dst_row_size_aligned, bctx->src0_row_size_aligned, s->ne00); +} + // 3. Row Broadcast (ne11 == 1, ne12 == 1, single row src1) static void binary_thread_vector_row_broadcast(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { struct htp_binary_context * bctx = (struct htp_binary_context *) data; struct htp_ops_context * octx = bctx->octx; htp_binary_preamble; - const uint32_t row_size_bytes = bctx->row_size_bytes; const uint32_t start_row = bctx->row_start + bctx->nrows_per_hvx * ith; const uint32_t end_row = MIN(start_row + bctx->nrows_per_hvx, bctx->row_start + bctx->total_rows); if (start_row >= end_row) return; @@ -485,73 +952,36 @@ static void binary_thread_vector_row_broadcast(const htp_thread_t * th, unsigned FARF(HIGH, "binary-row-bcast: %d/%d (%u:%u) row-size %u (%u)", ith, nth, start_row, end_row, nb01, bctx->dst_row_size_aligned); - const struct htp_binary_vtcm_layout * layout = &bctx->vtcm_layout; - uint8_t * src0_spad_base = VTCM_LAYOUT_PTR(uint8_t, bctx->vtcm_base, layout->off_src0) + (ith * layout->src0_bytes_per_hvx); - uint8_t * dst_spad_base = VTCM_LAYOUT_PTR(uint8_t, bctx->vtcm_base, layout->off_dst) + (ith * layout->dst_bytes_per_hvx); - - size_t src0_spad_half = layout->src0_spad_half_size; - size_t dst_spad_half = layout->dst_spad_half_size; - - dma_queue * dma_q = th->dma_q; - uint32_t ir_prefetch = start_row; - int spad_idx = 0; - - void * s1_ptr = VTCM_LAYOUT_PTR(void, bctx->vtcm_base, layout->off_src1); - - for (int k = 0; k < 2 && ir_prefetch < end_row; k++) { - uint32_t current_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02); - uint32_t i03 = fastdiv(ir_prefetch, &bctx->src0_dim12_div); - uint32_t rem = ir_prefetch - i03 * (ne02 * ne01); - uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div); - uint32_t i01 = rem - i02 * ne01; - - dma_addr_t src0_curr = src0->data + i03 * nb03 + i02 * nb02 + i01 * nb01; - dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1; - - uint8_t * s0_spad = src0_spad_base + spad_idx * src0_spad_half; - uint8_t * d_spad = dst_spad_base + spad_idx * dst_spad_half; - - dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, 0); - dma_queue_push(dma_q, dma_make_data(s0_spad, src0_curr), bctx->src0_row_size_aligned, nb01, row_size_bytes, current_block_size); - ir_prefetch += current_block_size; - spad_idx ^= 1; - } - - struct htp_thread_trace * tr = th->trace; - compute_row_bcast_t compute = (compute_row_bcast_t) bctx->compute; - - for (uint32_t ir = start_row; ir < end_row; ) { - uint32_t current_block_size = calc_block_size(bctx, ir, end_row, ne01, ne02); - uint8_t * d_spad = (uint8_t *) dma_queue_pop(dma_q).src; - uint8_t * s0_spad = (uint8_t *) dma_queue_pop(dma_q).dst; + struct binary_io_pipe_state s = { + .bctx = bctx, + .src0_data = src0->data, + .dst_data = dst->data, + .vtcm_src1 = VTCM_LAYOUT_PTR(const uint8_t, bctx->vtcm_base, bctx->vtcm_layout.off_src1), + .ne00 = ne00, .ne01 = ne01, .ne02 = ne02, + .nb01 = nb01, .nb02 = nb02, .nb03 = nb03, + .nb1 = nb1, .nb2 = nb2, .nb3 = nb3, + .ir = start_row, + .ir_end = end_row, + }; + + binary_io_run(th, ith, bctx, &s, binary_row_bcast_compute); +} - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); - compute(d_spad, s0_spad, (const uint8_t *)s1_ptr, current_block_size, - bctx->dst_row_size_aligned, bctx->src0_row_size_aligned, ne00); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); +static void binary_complex_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct binary_io_pipe_state * s = (struct binary_io_pipe_state *) ctx; + const struct htp_binary_context * bctx = s->bctx; + const uint32_t i03 = fastdiv(task->row, &bctx->src0_dim12_div); + const uint32_t rem = task->row - i03 * (s->ne02 * s->ne01); + const uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div); + const uint32_t i01 = rem - i02 * s->ne01; - uint32_t i03 = fastdiv(ir, &bctx->src0_dim12_div); - uint32_t rem = ir - i03 * (ne02 * ne01); - uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div); - uint32_t i01 = rem - i02 * ne01; - dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1; - dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, current_block_size); + const uint32_t i13 = fastmodulo(i03, s->ne13, &bctx->src1_dim3_div); + const uint32_t i12 = fastmodulo(i02, s->ne12, &bctx->src1_dim2_div); + const uint8_t * src1_plane = s->vtcm_src1 + i13 * s->s1_vol_stride + i12 * s->s1_plane_stride; - if (ir_prefetch < end_row) { - uint32_t next_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02); - uint32_t p03, p02, p01, prem; - p03 = fastdiv(ir_prefetch, &bctx->src0_dim12_div); - prem = ir_prefetch - p03 * (ne02 * ne01); - p02 = fastdiv(prem, &bctx->src0_dim1_div); - p01 = prem - p02 * ne01; - dma_addr_t s0_next = src0->data + p03 * nb03 + p02 * nb02 + p01 * nb01; - dma_queue_push(dma_q, dma_make_data(s0_spad, s0_next), bctx->src0_row_size_aligned, nb01, row_size_bytes, next_block_size); - ir_prefetch += next_block_size; - } - ir += current_block_size; - } - - dma_queue_flush(dma_q); + compute_complex_t compute = (compute_complex_t) bctx->compute; + compute((uint8_t *) out_spad, (const uint8_t *) in_spad, src1_plane, i01, s->ne11, &bctx->src1_dim1_div, + s->s1_row_stride, task->len, bctx->dst_row_size_aligned, bctx->src0_row_size_aligned, s->ne00); } // 4. Vector Complex (ne10 == ne00, complex broadcast) @@ -560,7 +990,6 @@ static void binary_thread_vector_complex(const htp_thread_t * th, unsigned int n struct htp_ops_context * octx = bctx->octx; htp_binary_preamble; - const uint32_t row_size_bytes = bctx->row_size_bytes; const uint32_t start_row = bctx->row_start + bctx->nrows_per_hvx * ith; const uint32_t end_row = MIN(start_row + bctx->nrows_per_hvx, bctx->row_start + bctx->total_rows); if (start_row >= end_row) return; @@ -568,81 +997,43 @@ static void binary_thread_vector_complex(const htp_thread_t * th, unsigned int n FARF(HIGH, "binary-complex: %d/%d (%u:%u) row-size %u (%u)", ith, nth, start_row, end_row, nb01, bctx->dst_row_size_aligned); - const struct htp_binary_vtcm_layout * layout = &bctx->vtcm_layout; - uint8_t * src0_spad_base = VTCM_LAYOUT_PTR(uint8_t, bctx->vtcm_base, layout->off_src0) + (ith * layout->src0_bytes_per_hvx); - uint8_t * dst_spad_base = VTCM_LAYOUT_PTR(uint8_t, bctx->vtcm_base, layout->off_dst) + (ith * layout->dst_bytes_per_hvx); - size_t src0_spad_half = layout->src0_spad_half_size; - size_t dst_spad_half = layout->dst_spad_half_size; - const uint8_t * vtcm_src1 = VTCM_LAYOUT_PTR(const uint8_t, bctx->vtcm_base, layout->off_src1); - - const uint32_t elem_size = (src0->type == HTP_TYPE_F32) ? sizeof(float) : sizeof(_Float16); - const size_t vtcm_row_stride = (size_t) ne10 * elem_size; + const size_t vtcm_row_stride = (size_t) ne10 * bctx->src1_elem_size; const size_t vtcm_plane_stride = (size_t) ne11 * vtcm_row_stride; - const size_t vtcm_vol_stride = (size_t) ne12 * vtcm_plane_stride; - - dma_queue * dma_q = th->dma_q; - uint32_t ir_prefetch = start_row; - int spad_idx = 0; - for (int k = 0; k < 2 && ir_prefetch < end_row; k++) { - uint32_t current_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02); - uint32_t i03 = fastdiv(ir_prefetch, &bctx->src0_dim12_div); - uint32_t rem = ir_prefetch - i03 * (ne02 * ne01); - uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div); - uint32_t i01 = rem - i02 * ne01; - - dma_addr_t src0_curr = src0->data + i03 * nb03 + i02 * nb02 + i01 * nb01; - dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1; - - uint8_t * s0_spad = src0_spad_base + spad_idx * src0_spad_half; - uint8_t * d_spad = dst_spad_base + spad_idx * dst_spad_half; - - dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, 0); - dma_queue_push(dma_q, dma_make_data(s0_spad, src0_curr), bctx->src0_row_size_aligned, nb01, row_size_bytes, current_block_size); - ir_prefetch += current_block_size; - spad_idx ^= 1; - } - - struct htp_thread_trace * tr = th->trace; - compute_complex_t compute = (compute_complex_t) bctx->compute; - - for (uint32_t ir = start_row; ir < end_row; ) { - uint32_t current_block_size = calc_block_size(bctx, ir, end_row, ne01, ne02); - uint8_t * d_spad = (uint8_t *) dma_queue_pop(dma_q).src; - uint8_t * s0_spad = (uint8_t *) dma_queue_pop(dma_q).dst; - - uint32_t i03 = fastdiv(ir, &bctx->src0_dim12_div); - uint32_t rem = ir - i03 * (ne02 * ne01); - uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div); - uint32_t i01 = rem - i02 * ne01; - - uint32_t i13 = fastmodulo(i03, ne13, &bctx->src1_dim3_div); - uint32_t i12 = fastmodulo(i02, ne12, &bctx->src1_dim2_div); - const uint8_t * src1_plane = vtcm_src1 + i13 * vtcm_vol_stride + i12 * vtcm_plane_stride; + struct binary_io_pipe_state s = { + .bctx = bctx, + .src0_data = src0->data, + .dst_data = dst->data, + .vtcm_src1 = VTCM_LAYOUT_PTR(const uint8_t, bctx->vtcm_base, bctx->vtcm_layout.off_src1), + .s1_row_stride = vtcm_row_stride, + .s1_plane_stride = vtcm_plane_stride, + .s1_vol_stride = (size_t) ne12 * vtcm_plane_stride, + .ne00 = ne00, .ne01 = ne01, .ne02 = ne02, + .ne10 = ne10, .ne11 = ne11, .ne12 = ne12, .ne13 = ne13, + .nb01 = nb01, .nb02 = nb02, .nb03 = nb03, + .nb1 = nb1, .nb2 = nb2, .nb3 = nb3, + .ir = start_row, + .ir_end = end_row, + }; + + binary_io_run(th, ith, bctx, &s, binary_complex_compute); +} - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); - compute(d_spad, s0_spad, src1_plane, i01, ne11, &bctx->src1_dim1_div, vtcm_row_stride, - current_block_size, bctx->dst_row_size_aligned, bctx->src0_row_size_aligned, ne00); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); +static void binary_repeat_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct binary_io_pipe_state * s = (struct binary_io_pipe_state *) ctx; + const struct htp_binary_context * bctx = s->bctx; + const uint32_t i03 = fastdiv(task->row, &bctx->src0_dim12_div); + const uint32_t rem = task->row - i03 * (s->ne02 * s->ne01); + const uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div); + const uint32_t i01 = rem - i02 * s->ne01; - dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1; - dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, current_block_size); + const uint32_t i13 = fastmodulo(i03, s->ne13, &bctx->src1_dim3_div); + const uint32_t i12 = fastmodulo(i02, s->ne12, &bctx->src1_dim2_div); + const uint8_t * src1_plane = s->vtcm_src1 + i13 * s->s1_vol_stride + i12 * s->s1_plane_stride; - if (ir_prefetch < end_row) { - uint32_t next_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02); - uint32_t p03, p02, p01, prem; - p03 = fastdiv(ir_prefetch, &bctx->src0_dim12_div); - prem = ir_prefetch - p03 * (ne02 * ne01); - p02 = fastdiv(prem, &bctx->src0_dim1_div); - p01 = prem - p02 * ne01; - dma_addr_t s0_next = src0->data + p03 * nb03 + p02 * nb02 + p01 * nb01; - dma_queue_push(dma_q, dma_make_data(s0_spad, s0_next), bctx->src0_row_size_aligned, nb01, row_size_bytes, next_block_size); - ir_prefetch += next_block_size; - } - ir += current_block_size; - } - - dma_queue_flush(dma_q); + compute_repeat_t compute = (compute_repeat_t) bctx->compute; + compute((uint8_t *) out_spad, (const uint8_t *) in_spad, src1_plane, i01, s->ne11, &bctx->src1_dim1_div, + s->s1_row_stride, task->len, bctx->dst_row_size_aligned, bctx->src0_row_size_aligned, s->ne00, s->ne10); } // 5. Element Repeat (ne10 != ne00) @@ -651,187 +1042,75 @@ static void binary_thread_element_repeat(const htp_thread_t * th, unsigned int n struct htp_ops_context * octx = bctx->octx; htp_binary_preamble; - const uint32_t row_size_bytes = bctx->row_size_bytes; const uint32_t start_row = bctx->row_start + bctx->nrows_per_hvx * ith; const uint32_t end_row = MIN(start_row + bctx->nrows_per_hvx, bctx->row_start + bctx->total_rows); if (start_row >= end_row) return; - const struct htp_binary_vtcm_layout * layout = &bctx->vtcm_layout; - uint8_t * src0_spad_base = VTCM_LAYOUT_PTR(uint8_t, bctx->vtcm_base, layout->off_src0) + (ith * layout->src0_bytes_per_hvx); - uint8_t * dst_spad_base = VTCM_LAYOUT_PTR(uint8_t, bctx->vtcm_base, layout->off_dst) + (ith * layout->dst_bytes_per_hvx); - size_t src0_spad_half = layout->src0_spad_half_size; - size_t dst_spad_half = layout->dst_spad_half_size; - const uint8_t * vtcm_src1 = VTCM_LAYOUT_PTR(const uint8_t, bctx->vtcm_base, layout->off_src1); - - const uint32_t elem_size = (src0->type == HTP_TYPE_F32) ? sizeof(float) : sizeof(_Float16); - const size_t vtcm_row_stride = (size_t) ne10 * elem_size; - const size_t vtcm_plane_stride = (size_t) ne11 * vtcm_row_stride; - const size_t vtcm_vol_stride = (size_t) ne12 * vtcm_plane_stride; - FARF(HIGH, "binary-repeat: %d/%d (%u:%u) row-size %u (%u)", ith, nth, start_row, end_row, nb01, bctx->dst_row_size_aligned); - dma_queue * dma_q = th->dma_q; - uint32_t ir_prefetch = start_row; - int spad_idx = 0; - - for (int k = 0; k < 2 && ir_prefetch < end_row; k++) { - uint32_t current_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02); - uint32_t i03 = fastdiv(ir_prefetch, &bctx->src0_dim12_div); - uint32_t rem = ir_prefetch - i03 * (ne02 * ne01); - uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div); - uint32_t i01 = rem - i02 * ne01; - - dma_addr_t src0_curr = src0->data + i03 * nb03 + i02 * nb02 + i01 * nb01; - dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1; - - uint8_t * s0_spad = src0_spad_base + spad_idx * src0_spad_half; - uint8_t * d_spad = dst_spad_base + spad_idx * dst_spad_half; - - dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, 0); - dma_queue_push(dma_q, dma_make_data(s0_spad, src0_curr), bctx->src0_row_size_aligned, nb01, row_size_bytes, current_block_size); - ir_prefetch += current_block_size; - spad_idx ^= 1; - } - - struct htp_thread_trace * tr = th->trace; - compute_repeat_t compute = (compute_repeat_t) bctx->compute; - - for (uint32_t ir = start_row; ir < end_row; ) { - uint32_t current_block_size = calc_block_size(bctx, ir, end_row, ne01, ne02); - uint8_t * d_spad = (uint8_t *) dma_queue_pop(dma_q).src; - uint8_t * s0_spad = (uint8_t *) dma_queue_pop(dma_q).dst; - - uint32_t i03 = fastdiv(ir, &bctx->src0_dim12_div); - uint32_t rem = ir - i03 * (ne02 * ne01); - uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div); - uint32_t i01 = rem - i02 * ne01; - - uint32_t i13 = fastmodulo(i03, ne13, &bctx->src1_dim3_div); - uint32_t i12 = fastmodulo(i02, ne12, &bctx->src1_dim2_div); - const uint8_t * src1_plane = vtcm_src1 + i13 * vtcm_vol_stride + i12 * vtcm_plane_stride; - - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); - compute(d_spad, s0_spad, src1_plane, i01, ne11, &bctx->src1_dim1_div, vtcm_row_stride, - current_block_size, bctx->dst_row_size_aligned, bctx->src0_row_size_aligned, ne00, ne10); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); - - dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1; - dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, current_block_size); + const size_t vtcm_row_stride = (size_t) ne10 * bctx->src1_elem_size; + const size_t vtcm_plane_stride = (size_t) ne11 * vtcm_row_stride; - if (ir_prefetch < end_row) { - uint32_t next_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02); - uint32_t p03, p02, p01, prem; - p03 = fastdiv(ir_prefetch, &bctx->src0_dim12_div); - prem = ir_prefetch - p03 * (ne02 * ne01); - p02 = fastdiv(prem, &bctx->src0_dim1_div); - p01 = prem - p02 * ne01; - dma_addr_t s0_next = src0->data + p03 * nb03 + p02 * nb02 + p01 * nb01; - dma_queue_push(dma_q, dma_make_data(s0_spad, s0_next), bctx->src0_row_size_aligned, nb01, row_size_bytes, next_block_size); - ir_prefetch += next_block_size; - } - ir += current_block_size; - } + struct binary_io_pipe_state s = { + .bctx = bctx, + .src0_data = src0->data, + .dst_data = dst->data, + .vtcm_src1 = VTCM_LAYOUT_PTR(const uint8_t, bctx->vtcm_base, bctx->vtcm_layout.off_src1), + .s1_row_stride = vtcm_row_stride, + .s1_plane_stride = vtcm_plane_stride, + .s1_vol_stride = (size_t) ne12 * vtcm_plane_stride, + .ne00 = ne00, .ne01 = ne01, .ne02 = ne02, + .ne10 = ne10, .ne11 = ne11, .ne12 = ne12, .ne13 = ne13, + .nb01 = nb01, .nb02 = nb02, .nb03 = nb03, + .nb1 = nb1, .nb2 = nb2, .nb3 = nb3, + .ir = start_row, + .ir_end = end_row, + }; + + binary_io_run(th, ith, bctx, &s, binary_repeat_compute); +} - dma_queue_flush(dma_q); +static void binary_add_id_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct binary_io_pipe_state * s = (struct binary_io_pipe_state *) ctx; + const struct htp_binary_context * bctx = s->bctx; + const uint32_t i03 = fastdiv(task->row, &bctx->src0_dim12_div); + const uint32_t rem = task->row - i03 * (s->ne02 * s->ne01); + const uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div); + const uint32_t i01 = rem - i02 * s->ne01; + + compute_add_id_t compute = (compute_add_id_t) bctx->compute; + compute((uint8_t *) out_spad, (const uint8_t *) in_spad, s->vtcm_src1, s->vtcm_src2, + i01, i02, s->ne01, bctx->src1_row_size_aligned, + task->len, bctx->dst_row_size_aligned, bctx->src0_row_size_aligned, s->ne00); } // 6. ADD_ID (src1 gathered via src2 indices) -static void binary_thread_add_id_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { +static void binary_thread_add_id(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; struct htp_binary_context * bctx = (struct htp_binary_context *) data; struct htp_ops_context * octx = bctx->octx; - const struct htp_tensor * src0 = octx->src[0]; - const struct htp_tensor * src1 = octx->src[1]; const struct htp_tensor * dst = octx->dst; - const uint32_t ne00 = src0->ne[0]; - const uint32_t ne01 = src0->ne[1]; - const uint32_t ne02 = src0->ne[2]; - const uint32_t ne03 = src0->ne[3]; - - const uint32_t nb01 = src0->nb[1]; - const uint32_t nb02 = src0->nb[2]; - const uint32_t nb03 = src0->nb[3]; - const uint32_t src1_stride = bctx->src1_row_size_aligned; - - const uint32_t nb1 = dst->nb[1]; - const uint32_t nb2 = dst->nb[2]; - const uint32_t nb3 = dst->nb[3]; - - const uint32_t row_size_bytes = bctx->row_size_bytes; const uint32_t start_row = bctx->row_start + bctx->nrows_per_hvx * ith; const uint32_t end_row = MIN(start_row + bctx->nrows_per_hvx, bctx->row_start + bctx->total_rows); if (start_row >= end_row) return; - const struct htp_binary_vtcm_layout * layout = &bctx->vtcm_layout; - uint8_t * src0_spad_base = VTCM_LAYOUT_PTR(uint8_t, bctx->vtcm_base, layout->off_src0) + (ith * layout->src0_bytes_per_hvx); - uint8_t * dst_spad_base = VTCM_LAYOUT_PTR(uint8_t, bctx->vtcm_base, layout->off_dst) + (ith * layout->dst_bytes_per_hvx); - const uint8_t * vtcm_src1 = VTCM_LAYOUT_PTR(const uint8_t, bctx->vtcm_base, layout->off_src1); - const int32_t * vtcm_src2 = VTCM_LAYOUT_PTR(const int32_t, bctx->vtcm_base, layout->off_src2); - size_t src0_spad_half = layout->src0_spad_half_size; - size_t dst_spad_half = layout->dst_spad_half_size; - - dma_queue * dma_q = th->dma_q; - uint32_t ir_prefetch = start_row; - int spad_idx = 0; - - for (int k = 0; k < 2 && ir_prefetch < end_row; k++) { - uint32_t current_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02); - uint32_t i03 = fastdiv(ir_prefetch, &bctx->src0_dim12_div); - uint32_t rem = ir_prefetch - i03 * (ne02 * ne01); - uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div); - uint32_t i01 = rem - i02 * ne01; - - dma_addr_t src0_curr = src0->data + i03 * nb03 + i02 * nb02 + i01 * nb01; - dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1; - - uint8_t * s0_spad = src0_spad_base + spad_idx * src0_spad_half; - uint8_t * d_spad = dst_spad_base + spad_idx * dst_spad_half; - - dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, 0); - dma_queue_push(dma_q, dma_make_data(s0_spad, src0_curr), bctx->src0_row_size_aligned, nb01, row_size_bytes, current_block_size); - ir_prefetch += current_block_size; - spad_idx ^= 1; - } - - struct htp_thread_trace * tr = th->trace; - - for (uint32_t ir = start_row; ir < end_row; ) { - uint32_t current_block_size = calc_block_size(bctx, ir, end_row, ne01, ne02); - uint8_t * d_spad = (uint8_t *) dma_queue_pop(dma_q).src; - uint8_t * s0_spad = (uint8_t *) dma_queue_pop(dma_q).dst; - - uint32_t i03 = fastdiv(ir, &bctx->src0_dim12_div); - uint32_t rem = ir - i03 * (ne02 * ne01); - uint32_t i02 = fastdiv(rem, &bctx->src0_dim1_div); - uint32_t i01 = rem - i02 * ne01; - - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); - compute_add_id_t compute = (compute_add_id_t) bctx->compute; - compute(d_spad, s0_spad, vtcm_src1, vtcm_src2, - i01, i02, ne01, src1_stride, - current_block_size, bctx->dst_row_size_aligned, bctx->src0_row_size_aligned, ne00); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); - - dma_addr_t dst_curr = dst->data + i03 * nb3 + i02 * nb2 + i01 * nb1; - dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), nb1, bctx->dst_row_size_aligned, row_size_bytes, current_block_size); - - if (ir_prefetch < end_row) { - uint32_t next_block_size = calc_block_size(bctx, ir_prefetch, end_row, ne01, ne02); - uint32_t p03, p02, p01, prem; - p03 = fastdiv(ir_prefetch, &bctx->src0_dim12_div); - prem = ir_prefetch - p03 * (ne02 * ne01); - p02 = fastdiv(prem, &bctx->src0_dim1_div); - p01 = prem - p02 * ne01; - dma_addr_t s0_next = src0->data + p03 * nb03 + p02 * nb02 + p01 * nb01; - dma_queue_push(dma_q, dma_make_data(s0_spad, s0_next), bctx->src0_row_size_aligned, nb01, row_size_bytes, next_block_size); - ir_prefetch += next_block_size; - } - ir += current_block_size; - } - - dma_queue_flush(dma_q); + struct binary_io_pipe_state s = { + .bctx = bctx, + .src0_data = src0->data, + .dst_data = dst->data, + .vtcm_src1 = VTCM_LAYOUT_PTR(const uint8_t, bctx->vtcm_base, bctx->vtcm_layout.off_src1), + .vtcm_src2 = VTCM_LAYOUT_PTR(const int32_t, bctx->vtcm_base, bctx->vtcm_layout.off_src2), + .ne00 = src0->ne[0], .ne01 = src0->ne[1], .ne02 = src0->ne[2], + .nb01 = src0->nb[1], .nb02 = src0->nb[2], .nb03 = src0->nb[3], + .nb1 = dst->nb[1], .nb2 = dst->nb[2], .nb3 = dst->nb[3], + .ir = start_row, + .ir_end = end_row, + }; + + binary_io_run(th, ith, bctx, &s, binary_add_id_compute); } static inline void hvx_div_scalar_f32(uint8_t * restrict dst, const uint8_t * restrict src, const float val, const uint32_t num_elems) { @@ -842,6 +1121,81 @@ static inline void hvx_div_scalar_f16(uint8_t * restrict dst, const uint8_t * re hvx_div_scalar_f16_aa(dst, src, val, num_elems); } +static void binary_expand_f16_to_f32(uint8_t * data, uint32_t n) { + uint32_t end = n; + while (end > 0) { + const uint32_t start = (end - 1) & ~63u; + const uint32_t count = end - start; + HVX_VectorPair pair = hvx_vec_f16_to_f32(hvx_vmemu(data + (size_t) start * sizeof(_Float16))); + hvx_vec_store_u(data + (size_t) start * sizeof(float), MIN(count, 32) * sizeof(float), Q6_V_lo_W(pair)); + if (count > 32) { + hvx_vec_store_u(data + (size_t) (start + 32) * sizeof(float), (count - 32) * sizeof(float), Q6_V_hi_W(pair)); + } + end = start; + } +} + +#define SELECT_MIXED_COMPUTE(PREFIX, type_key, out) \ + do { \ + switch (type_key) { \ + case 1: \ + switch (octx->op) { \ + case HTP_OP_ADD: out = PREFIX##_add_f16_f16_f32; break; \ + case HTP_OP_SUB: out = PREFIX##_sub_f16_f16_f32; break; \ + case HTP_OP_MUL: out = PREFIX##_mul_f16_f16_f32; break; \ + case HTP_OP_DIV: out = PREFIX##_div_f16_f16_f32; break; \ + default: break; \ + } \ + break; \ + case 2: \ + switch (octx->op) { \ + case HTP_OP_ADD: out = PREFIX##_add_f16_f32_f16; break; \ + case HTP_OP_SUB: out = PREFIX##_sub_f16_f32_f16; break; \ + case HTP_OP_MUL: out = PREFIX##_mul_f16_f32_f16; break; \ + case HTP_OP_DIV: out = PREFIX##_div_f16_f32_f16; break; \ + default: break; \ + } \ + break; \ + case 3: \ + switch (octx->op) { \ + case HTP_OP_ADD: out = PREFIX##_add_f16_f32_f32; break; \ + case HTP_OP_SUB: out = PREFIX##_sub_f16_f32_f32; break; \ + case HTP_OP_MUL: out = PREFIX##_mul_f16_f32_f32; break; \ + case HTP_OP_DIV: out = PREFIX##_div_f16_f32_f32; break; \ + default: break; \ + } \ + break; \ + case 4: \ + switch (octx->op) { \ + case HTP_OP_ADD: out = PREFIX##_add_f32_f16_f16; break; \ + case HTP_OP_SUB: out = PREFIX##_sub_f32_f16_f16; break; \ + case HTP_OP_MUL: out = PREFIX##_mul_f32_f16_f16; break; \ + case HTP_OP_DIV: out = PREFIX##_div_f32_f16_f16; break; \ + default: break; \ + } \ + break; \ + case 5: \ + switch (octx->op) { \ + case HTP_OP_ADD: out = PREFIX##_add_f32_f16_f32; break; \ + case HTP_OP_SUB: out = PREFIX##_sub_f32_f16_f32; break; \ + case HTP_OP_MUL: out = PREFIX##_mul_f32_f16_f32; break; \ + case HTP_OP_DIV: out = PREFIX##_div_f32_f16_f32; break; \ + default: break; \ + } \ + break; \ + case 6: \ + switch (octx->op) { \ + case HTP_OP_ADD: out = PREFIX##_add_f32_f32_f16; break; \ + case HTP_OP_SUB: out = PREFIX##_sub_f32_f32_f16; break; \ + case HTP_OP_MUL: out = PREFIX##_mul_f32_f32_f16; break; \ + case HTP_OP_DIV: out = PREFIX##_div_f32_f32_f16; break; \ + default: break; \ + } \ + break; \ + default: break; \ + } \ + } while (0) + typedef void (*compute_binary_chunked_t)( uint8_t * restrict dst, const uint8_t * restrict src0, @@ -873,6 +1227,9 @@ struct binary_chunked_context { uint32_t chunks_per_hvx; uint32_t total_chunks; uint32_t n_srcs; + uint32_t src0_elem_size; + uint32_t src1_elem_size; + uint32_t dst_elem_size; bool is_scalar; float scalar_f32; _Float16 scalar_f16; @@ -894,10 +1251,10 @@ static void binary_thread_chunked(const htp_thread_t * th, unsigned int nth, uns return; } - const uint32_t src0_type = src0->type; - const size_t elem_size = (src0_type == HTP_TYPE_F32) ? sizeof(float) : sizeof(_Float16); const uint32_t chunk_size = ctx->chunk_size; - const size_t chunk_bytes = ctx->vtcm_layout.src0_spad_half_size; + const size_t src0_chunk_bytes = ctx->vtcm_layout.src0_spad_half_size; + const size_t src1_chunk_bytes = ctx->vtcm_layout.src1_spad_half_size; + const size_t dst_chunk_bytes = ctx->vtcm_layout.dst_spad_half_size; FARF(HIGH, "binary-chunked: %d/%d (%u:%u) chunks %u elems %u", ith, nth, start_chunk, end_chunk, ctx->total_chunks, ctx->nelem); @@ -916,22 +1273,24 @@ static void binary_thread_chunked(const htp_thread_t * th, unsigned int nth, uns const uint32_t c_start = ctx->elem_start + prefetch_chunk * chunk_size; const uint32_t c_end = MIN(c_start + chunk_size, ctx->elem_start + ctx->nelem); const uint32_t cur_elems = c_end - c_start; - const uint32_t cur_bytes = cur_elems * elem_size; + const uint32_t src0_bytes = cur_elems * ctx->src0_elem_size; + const uint32_t src1_bytes = cur_elems * ctx->src1_elem_size; + const uint32_t dst_bytes = cur_elems * ctx->dst_elem_size; - dma_addr_t s0_curr = src0->data + (size_t) c_start * elem_size; - dma_addr_t d_curr = dst->data + (size_t) c_start * elem_size; + dma_addr_t s0_curr = src0->data + (size_t) c_start * ctx->src0_elem_size; + dma_addr_t d_curr = dst->data + (size_t) c_start * ctx->dst_elem_size; - uint8_t * s0_spad = src0_spad_base + spad_idx * chunk_bytes; - uint8_t * d_spad = dst_spad_base + spad_idx * chunk_bytes; + uint8_t * s0_spad = src0_spad_base + spad_idx * src0_chunk_bytes; + uint8_t * d_spad = dst_spad_base + spad_idx * dst_chunk_bytes; - dma_queue_push(dma_q, dma_make_data(d_curr, d_spad), chunk_bytes, chunk_bytes, cur_bytes, 0); - dma_queue_push(dma_q, dma_make_data(s0_spad, s0_curr), chunk_bytes, chunk_bytes, cur_bytes, 1); + dma_queue_push(dma_q, dma_make_data(d_curr, d_spad), dst_chunk_bytes, dst_chunk_bytes, dst_bytes, 0); + dma_queue_push(dma_q, dma_make_data(s0_spad, s0_curr), src0_chunk_bytes, src0_chunk_bytes, src0_bytes, 1); if (!ctx->is_scalar) { - uint8_t * s1_spad = src1_spad_base + spad_idx * chunk_bytes; + uint8_t * s1_spad = src1_spad_base + spad_idx * src1_chunk_bytes; for (uint32_t s = 1; s < n_srcs; s++) { - dma_addr_t s_curr = octx->src[s]->data + (size_t) c_start * elem_size; - uint8_t * s_spad = s1_spad + (s - 1) * 2 * chunk_bytes; - dma_queue_push(dma_q, dma_make_data(s_spad, s_curr), chunk_bytes, chunk_bytes, cur_bytes, 1); + dma_addr_t s_curr = octx->src[s]->data + (size_t) c_start * ctx->src1_elem_size; + uint8_t * s_spad = s1_spad + (s - 1) * 2 * src1_chunk_bytes; + dma_queue_push(dma_q, dma_make_data(s_spad, s_curr), src1_chunk_bytes, src1_chunk_bytes, src1_bytes, 1); } } @@ -945,7 +1304,7 @@ static void binary_thread_chunked(const htp_thread_t * th, unsigned int nth, uns const uint32_t c_start = ctx->elem_start + c * chunk_size; const uint32_t c_end = MIN(c_start + chunk_size, ctx->elem_start + ctx->nelem); const uint32_t cur_elems = c_end - c_start; - const uint32_t cur_bytes = cur_elems * elem_size; + const uint32_t dst_bytes = cur_elems * ctx->dst_elem_size; uint8_t * d_spad = (uint8_t *) dma_queue_pop(dma_q).src; uint8_t * s0_spad = (uint8_t *) dma_queue_pop(dma_q).dst; @@ -953,7 +1312,7 @@ static void binary_thread_chunked(const htp_thread_t * th, unsigned int nth, uns htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) c); if (ctx->is_scalar) { - if (src0_type == HTP_TYPE_F32) { + if (ctx->compute_scalar_f32) { ctx->compute_scalar_f32(d_spad, s0_spad, ctx->scalar_f32, cur_elems); } else { ctx->compute_scalar_f16(d_spad, s0_spad, ctx->scalar_f16, cur_elems); @@ -967,22 +1326,23 @@ static void binary_thread_chunked(const htp_thread_t * th, unsigned int nth, uns } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) c); - dma_addr_t dst_curr = dst->data + (size_t) c_start * elem_size; - dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), chunk_bytes, chunk_bytes, cur_bytes, 1); + dma_addr_t dst_curr = dst->data + (size_t) c_start * ctx->dst_elem_size; + dma_queue_push(dma_q, dma_make_data(dst_curr, d_spad), dst_chunk_bytes, dst_chunk_bytes, dst_bytes, 1); if (prefetch_chunk < end_chunk) { const uint32_t pc_start = ctx->elem_start + prefetch_chunk * chunk_size; const uint32_t pc_end = MIN(pc_start + chunk_size, ctx->elem_start + ctx->nelem); const uint32_t p_elems = pc_end - pc_start; - const uint32_t p_bytes = p_elems * elem_size; + const uint32_t p_src0_bytes = p_elems * ctx->src0_elem_size; + const uint32_t p_src1_bytes = p_elems * ctx->src1_elem_size; - dma_addr_t s0_next = src0->data + (size_t) pc_start * elem_size; - dma_queue_push(dma_q, dma_make_data(s0_spad, s0_next), chunk_bytes, chunk_bytes, p_bytes, 1); + dma_addr_t s0_next = src0->data + (size_t) pc_start * ctx->src0_elem_size; + dma_queue_push(dma_q, dma_make_data(s0_spad, s0_next), src0_chunk_bytes, src0_chunk_bytes, p_src0_bytes, 1); if (!ctx->is_scalar) { for (uint32_t s = 1; s < n_srcs; s++) { - dma_addr_t s_next = octx->src[s]->data + (size_t) pc_start * elem_size; - uint8_t * s_spad = s1_spad + (s - 1) * 2 * chunk_bytes; - dma_queue_push(dma_q, dma_make_data(s_spad, s_next), chunk_bytes, chunk_bytes, p_bytes, 1); + dma_addr_t s_next = octx->src[s]->data + (size_t) pc_start * ctx->src1_elem_size; + uint8_t * s_spad = s1_spad + (s - 1) * 2 * src1_chunk_bytes; + dma_queue_push(dma_q, dma_make_data(s_spad, s_next), src1_chunk_bytes, src1_chunk_bytes, p_src1_bytes, 1); } } @@ -1003,11 +1363,19 @@ static int execute_op_binary(struct htp_ops_context * octx) { const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3]; // Use packed row sizes for VTCM allocation and alignment - const uint32_t src0_type = octx->src[0]->type; - const size_t elem_size = (src0_type == HTP_TYPE_F32) ? sizeof(float) : sizeof(_Float16); - const size_t src0_row_size = src0->ne[0] * elem_size; - const size_t src1_row_size = src1->ne[0] * elem_size; - const size_t dst_row_size = dst->ne[0] * elem_size; + const uint32_t src0_type = src0->type; + const uint32_t src1_type = src1->type; + const uint32_t dst_type = dst->type; + const uint32_t src0_elem_size = kparams->src0_elem_size; + const uint32_t src1_elem_size = kparams->src1_elem_size; + const uint32_t dst_elem_size = kparams->dst_elem_size; + const size_t src0_row_size = src0->ne[0] * src0_elem_size; + const size_t src1_row_size = src1->ne[0] * src1_elem_size; + const size_t dst_row_size = dst->ne[0] * dst_elem_size; + const uint32_t type_key = (src0_type == HTP_TYPE_F32 ? 4 : 0) | + (src1_type == HTP_TYPE_F32 ? 2 : 0) | + (dst_type == HTP_TYPE_F32 ? 1 : 0); + const uint32_t table_type_key = type_key == 0 ? 0 : (type_key | 2); if (kparams->kernel_type == HTP_BINARY_KERNEL_CHUNKED) { const bool is_scalar = kparams->is_scalar; @@ -1017,7 +1385,7 @@ static int execute_op_binary(struct htp_ops_context * octx) { compute_binary_scalar_chunked_f16_t compute_scalar_f16 = NULL; if (is_scalar) { - if (src0_type == HTP_TYPE_F32) { + if (type_key == 7) { switch (octx->op) { case HTP_OP_ADD: compute_scalar_f32 = hvx_add_scalar_f32; break; case HTP_OP_SUB: compute_scalar_f32 = hvx_sub_scalar_f32; break; @@ -1025,7 +1393,7 @@ static int execute_op_binary(struct htp_ops_context * octx) { case HTP_OP_DIV: compute_scalar_f32 = hvx_div_scalar_f32; break; default: break; } - } else if (src0_type == HTP_TYPE_F16) { + } else if (type_key == 0) { switch (octx->op) { case HTP_OP_ADD: compute_scalar_f16 = hvx_add_scalar_f16; break; case HTP_OP_SUB: compute_scalar_f16 = hvx_sub_scalar_f16; break; @@ -1033,12 +1401,44 @@ static int execute_op_binary(struct htp_ops_context * octx) { case HTP_OP_DIV: compute_scalar_f16 = hvx_div_scalar_f16; break; default: break; } + } else if (src0_type == HTP_TYPE_F16 && dst_type == HTP_TYPE_F16) { + switch (octx->op) { + case HTP_OP_ADD: compute_scalar_f32 = binary_scalar_add_f16_f16; break; + case HTP_OP_SUB: compute_scalar_f32 = binary_scalar_sub_f16_f16; break; + case HTP_OP_MUL: compute_scalar_f32 = binary_scalar_mul_f16_f16; break; + case HTP_OP_DIV: compute_scalar_f32 = binary_scalar_div_f16_f16; break; + default: break; + } + } else if (src0_type == HTP_TYPE_F16) { + switch (octx->op) { + case HTP_OP_ADD: compute_scalar_f32 = binary_scalar_add_f16_f32; break; + case HTP_OP_SUB: compute_scalar_f32 = binary_scalar_sub_f16_f32; break; + case HTP_OP_MUL: compute_scalar_f32 = binary_scalar_mul_f16_f32; break; + case HTP_OP_DIV: compute_scalar_f32 = binary_scalar_div_f16_f32; break; + default: break; + } + } else if (dst_type == HTP_TYPE_F16) { + switch (octx->op) { + case HTP_OP_ADD: compute_scalar_f32 = binary_scalar_add_f32_f16; break; + case HTP_OP_SUB: compute_scalar_f32 = binary_scalar_sub_f32_f16; break; + case HTP_OP_MUL: compute_scalar_f32 = binary_scalar_mul_f32_f16; break; + case HTP_OP_DIV: compute_scalar_f32 = binary_scalar_div_f32_f16; break; + default: break; + } + } else { + switch (octx->op) { + case HTP_OP_ADD: compute_scalar_f32 = binary_scalar_add_f32_f32; break; + case HTP_OP_SUB: compute_scalar_f32 = binary_scalar_sub_f32_f32; break; + case HTP_OP_MUL: compute_scalar_f32 = binary_scalar_mul_f32_f32; break; + case HTP_OP_DIV: compute_scalar_f32 = binary_scalar_div_f32_f32; break; + default: break; + } } if (!compute_scalar_f32 && !compute_scalar_f16) { return HTP_STATUS_NO_SUPPORT; } } else { - if (src0_type == HTP_TYPE_F32) { + if (type_key == 7) { switch (octx->op) { case HTP_OP_ADD: compute = hvx_add_f32; break; case HTP_OP_SUB: compute = hvx_sub_f32; break; @@ -1046,7 +1446,7 @@ static int execute_op_binary(struct htp_ops_context * octx) { case HTP_OP_DIV: compute = hvx_div_f32; break; default: break; } - } else if (src0_type == HTP_TYPE_F16) { + } else if (type_key == 0) { switch (octx->op) { case HTP_OP_ADD: compute = hvx_add_f16; break; case HTP_OP_SUB: compute = hvx_sub_f16; break; @@ -1054,6 +1454,8 @@ static int execute_op_binary(struct htp_ops_context * octx) { case HTP_OP_DIV: compute = hvx_div_f16; break; default: break; } + } else { + SELECT_MIXED_COMPUTE(binary, type_key, compute); } if (!compute) { return HTP_STATUS_NO_SUPPORT; @@ -1067,18 +1469,14 @@ static int execute_op_binary(struct htp_ops_context * octx) { uint32_t elem_start = 0; uint32_t nelem = total_elems; - const uint32_t elems_per_line = (src0_type == HTP_TYPE_F32) ? 32 : 64; + const uint32_t elems_per_line = 128 / dst_elem_size; if (octx->ctx->mdev.count > 1) { - bool can_split = htp_tensor_mdev_data_aligned(dst) && - htp_tensor_mdev_data_aligned(src0) && - (is_scalar || htp_tensor_mdev_data_aligned(src1)) && - htp_tensor_is_contiguous(dst, elem_size) && - htp_tensor_is_contiguous(src0, elem_size) && - (is_scalar || htp_tensor_is_contiguous(src1, elem_size)); + bool can_split = htp_tensor_is_contiguous(dst, dst_elem_size) && + htp_tensor_is_contiguous(src0, src0_elem_size) && + (is_scalar || htp_tensor_is_contiguous(src1, src1_elem_size)); for (uint32_t s = 2; can_split && s < n_srcs; s++) { - can_split = htp_tensor_mdev_data_aligned(octx->src[s]) && - htp_tensor_is_contiguous(octx->src[s], elem_size); + can_split = htp_tensor_is_contiguous(octx->src[s], src1_elem_size); } const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( total_elems, can_split ? elems_per_line : 0, @@ -1111,13 +1509,15 @@ static int execute_op_binary(struct htp_ops_context * octx) { if (is_scalar) { uint8_t * vtcm_src1 = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, vtcm_layout.off_src1); dma_queue * dma_q = octx->ctx->dma[0]; - dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data), 128, 0, elem_size, 1); + dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data), 128, 0, src1_elem_size, 1); dma_queue_pop(dma_q); - if (src0_type == HTP_TYPE_F32) { - scalar_f32 = ((const float *) vtcm_src1)[0]; + const HVX_Vector v_src1 = hvx_vmem(vtcm_src1); + if (type_key != 0) { + const HVX_Vector v_f32 = (src1_type == HTP_TYPE_F16) ? Q6_V_lo_W(hvx_vec_f16_to_f32(v_src1)) : v_src1; + scalar_f32 = hvx_vec_get_f32(v_f32); } else { - scalar_f16 = ((const _Float16 *) vtcm_src1)[0]; + scalar_f16 = hvx_vec_get_f16(v_src1); } } @@ -1131,6 +1531,9 @@ static int execute_op_binary(struct htp_ops_context * octx) { .chunks_per_hvx = chunks_per_hvx, .total_chunks = total_chunks, .n_srcs = n_srcs, + .src0_elem_size = src0_elem_size, + .src1_elem_size = src1_elem_size, + .dst_elem_size = dst_elem_size, .is_scalar = is_scalar, .scalar_f32 = scalar_f32, .scalar_f16 = scalar_f16, @@ -1147,9 +1550,7 @@ static int execute_op_binary(struct htp_ops_context * octx) { uint32_t nrows = src0_nrows; if (octx->ctx->mdev.count > 1) { - uint32_t rows_per_chunk = 0; - htp_tensor_mdev_rows_per_chunk(dst, (uint32_t) elem_size, (uint32_t) dst_row_size, &rows_per_chunk); - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, rows_per_chunk, + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); row_start = range.start; nrows = range.count; @@ -1182,7 +1583,7 @@ static int execute_op_binary(struct htp_ops_context * octx) { switch (kparams->kernel_type) { case HTP_BINARY_KERNEL_SAME_SHAPE: worker_func = binary_thread_vector_same_shape; - if (src0_type == HTP_TYPE_F32) { + if (type_key == 7) { switch (octx->op) { case HTP_OP_ADD: compute_func = compute_same_shape_add_f32; break; case HTP_OP_SUB: compute_func = compute_same_shape_sub_f32; break; @@ -1190,7 +1591,7 @@ static int execute_op_binary(struct htp_ops_context * octx) { case HTP_OP_DIV: compute_func = compute_same_shape_div_f32; break; default: break; } - } else if (src0_type == HTP_TYPE_F16) { + } else if (type_key == 0) { switch (octx->op) { case HTP_OP_ADD: compute_func = compute_same_shape_add_f16; break; case HTP_OP_SUB: compute_func = compute_same_shape_sub_f16; break; @@ -1198,11 +1599,13 @@ static int execute_op_binary(struct htp_ops_context * octx) { case HTP_OP_DIV: compute_func = compute_same_shape_div_f16; break; default: break; } + } else { + SELECT_MIXED_COMPUTE(compute_same_shape, type_key, compute_func); } break; case HTP_BINARY_KERNEL_ROW_BCAST: worker_func = binary_thread_vector_row_broadcast; - if (src0_type == HTP_TYPE_F32) { + if (table_type_key == 7) { switch (octx->op) { case HTP_OP_ADD: compute_func = compute_row_bcast_add_f32; break; case HTP_OP_SUB: compute_func = compute_row_bcast_sub_f32; break; @@ -1210,7 +1613,7 @@ static int execute_op_binary(struct htp_ops_context * octx) { case HTP_OP_DIV: compute_func = compute_row_bcast_div_f32; break; default: break; } - } else if (src0_type == HTP_TYPE_F16) { + } else if (type_key == 0) { switch (octx->op) { case HTP_OP_ADD: compute_func = compute_row_bcast_add_f16; break; case HTP_OP_SUB: compute_func = compute_row_bcast_sub_f16; break; @@ -1218,11 +1621,13 @@ static int execute_op_binary(struct htp_ops_context * octx) { case HTP_OP_DIV: compute_func = compute_row_bcast_div_f16; break; default: break; } + } else { + SELECT_MIXED_COMPUTE(compute_row_bcast, table_type_key, compute_func); } break; case HTP_BINARY_KERNEL_SCALAR: worker_func = binary_thread_scalar; - if (src0_type == HTP_TYPE_F32) { + if (table_type_key == 7) { switch (octx->op) { case HTP_OP_ADD: compute_func = compute_scalar_add_f32; break; case HTP_OP_SUB: compute_func = compute_scalar_sub_f32; break; @@ -1230,7 +1635,7 @@ static int execute_op_binary(struct htp_ops_context * octx) { case HTP_OP_DIV: compute_func = compute_scalar_div_f32; break; default: break; } - } else if (src0_type == HTP_TYPE_F16) { + } else if (type_key == 0) { switch (octx->op) { case HTP_OP_ADD: compute_func = compute_scalar_add_f16; break; case HTP_OP_SUB: compute_func = compute_scalar_sub_f16; break; @@ -1238,11 +1643,13 @@ static int execute_op_binary(struct htp_ops_context * octx) { case HTP_OP_DIV: compute_func = compute_scalar_div_f16; break; default: break; } + } else { + SELECT_MIXED_COMPUTE(compute_scalar, table_type_key, compute_func); } break; case HTP_BINARY_KERNEL_COMPLEX: worker_func = binary_thread_vector_complex; - if (src0_type == HTP_TYPE_F32) { + if (type_key == 7) { switch (octx->op) { case HTP_OP_ADD: compute_func = compute_complex_add_f32; break; case HTP_OP_SUB: compute_func = compute_complex_sub_f32; break; @@ -1250,7 +1657,7 @@ static int execute_op_binary(struct htp_ops_context * octx) { case HTP_OP_DIV: compute_func = compute_complex_div_f32; break; default: break; } - } else if (src0_type == HTP_TYPE_F16) { + } else if (type_key == 0) { switch (octx->op) { case HTP_OP_ADD: compute_func = compute_complex_add_f16; break; case HTP_OP_SUB: compute_func = compute_complex_sub_f16; break; @@ -1258,11 +1665,13 @@ static int execute_op_binary(struct htp_ops_context * octx) { case HTP_OP_DIV: compute_func = compute_complex_div_f16; break; default: break; } + } else { + SELECT_MIXED_COMPUTE(compute_complex, type_key, compute_func); } break; case HTP_BINARY_KERNEL_REPEAT: worker_func = binary_thread_element_repeat; - if (src0_type == HTP_TYPE_F32) { + if (type_key == 7) { switch (octx->op) { case HTP_OP_ADD: compute_func = compute_repeat_add_f32; break; case HTP_OP_SUB: compute_func = compute_repeat_sub_f32; break; @@ -1270,7 +1679,7 @@ static int execute_op_binary(struct htp_ops_context * octx) { case HTP_OP_DIV: compute_func = compute_repeat_div_f32; break; default: break; } - } else if (src0_type == HTP_TYPE_F16) { + } else if (type_key == 0) { switch (octx->op) { case HTP_OP_ADD: compute_func = compute_repeat_add_f16; break; case HTP_OP_SUB: compute_func = compute_repeat_sub_f16; break; @@ -1278,12 +1687,24 @@ static int execute_op_binary(struct htp_ops_context * octx) { case HTP_OP_DIV: compute_func = compute_repeat_div_f16; break; default: break; } + } else { + SELECT_MIXED_COMPUTE(compute_repeat, type_key, compute_func); } break; case HTP_BINARY_KERNEL_ADD_ID: - if (octx->op == HTP_OP_ADD_ID && src0_type == HTP_TYPE_F32) { - worker_func = binary_thread_add_id_f32; - compute_func = (void *) compute_add_id_f32; + if (octx->op == HTP_OP_ADD_ID) { + worker_func = binary_thread_add_id; + switch (type_key) { + case 0: compute_func = (void *) compute_add_id_f16_f16_f16; break; + case 1: compute_func = (void *) compute_add_id_f16_f16_f32; break; + case 2: compute_func = (void *) compute_add_id_f16_f32_f16; break; + case 3: compute_func = (void *) compute_add_id_f16_f32_f32; break; + case 4: compute_func = (void *) compute_add_id_f32_f16_f16; break; + case 5: compute_func = (void *) compute_add_id_f32_f16_f32; break; + case 6: compute_func = (void *) compute_add_id_f32_f32_f16; break; + case 7: compute_func = (void *) compute_add_id_f32_f32_f32; break; + default: break; + } } break; default: break; @@ -1296,12 +1717,16 @@ static int execute_op_binary(struct htp_ops_context * octx) { dma_queue * dma_q = octx->ctx->dma[0]; uint8_t * vtcm_src1 = VTCM_LAYOUT_PTR(uint8_t, bctx.vtcm_base, bctx.vtcm_layout.off_src1); if (kparams->kernel_type == HTP_BINARY_KERNEL_ROW_BCAST) { - dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data), bctx.vtcm_layout.src1_size, 0, src1->ne[0] * elem_size, 1); + if (!kparams->src1_strided) { + dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data), bctx.vtcm_layout.src1_size, 0, src1->ne[0] * src1_elem_size, 1); + } else { + dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data), src1_elem_size, src1->nb[0], src1_elem_size, src1->ne[0]); + } } else if (kparams->kernel_type == HTP_BINARY_KERNEL_SCALAR || kparams->kernel_type == HTP_BINARY_KERNEL_REPEAT || kparams->kernel_type == HTP_BINARY_KERNEL_COMPLEX) { if (!kparams->src1_strided) { - const size_t src1_bytes = (size_t) src1->ne[0] * src1->ne[1] * src1->ne[2] * src1->ne[3] * elem_size; + const size_t src1_bytes = (size_t) src1->ne[0] * src1->ne[1] * src1->ne[2] * src1->ne[3] * src1_elem_size; dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data), bctx.vtcm_layout.src1_size, 0, src1_bytes, 1); if (kparams->kernel_type == HTP_BINARY_KERNEL_SCALAR && octx->src[2] != NULL) { uint8_t * vtcm_src2 = VTCM_LAYOUT_PTR(uint8_t, bctx.vtcm_base, bctx.vtcm_layout.off_src2); @@ -1311,14 +1736,29 @@ static int execute_op_binary(struct htp_ops_context * octx) { const uint32_t ne11 = src1->ne[1]; const uint32_t ne12 = src1->ne[2]; const uint32_t ne13 = src1->ne[3]; - const size_t row_bytes = src1->ne[0] * elem_size; - for (uint32_t i13 = 0; i13 < ne13; i13++) { - for (uint32_t i12 = 0; i12 < ne12; i12++) { - dma_addr_t src_addr = src1->data + i13 * src1->nb[3] + i12 * src1->nb[2]; - uint8_t * dst_ptr = vtcm_src1 + (i13 * ne12 * ne11 + i12 * ne11) * row_bytes; - while (!dma_queue_push(dma_q, dma_make_data(dst_ptr, src_addr), - row_bytes, src1->nb[1], row_bytes, ne11)) { - dma_queue_pop(dma_q); + const size_t row_bytes = src1->ne[0] * src1_elem_size; + if (src1->nb[0] == src1_elem_size) { + for (uint32_t i13 = 0; i13 < ne13; i13++) { + for (uint32_t i12 = 0; i12 < ne12; i12++) { + dma_addr_t src_addr = src1->data + i13 * src1->nb[3] + i12 * src1->nb[2]; + uint8_t * dst_ptr = vtcm_src1 + (i13 * ne12 * ne11 + i12 * ne11) * row_bytes; + while (!dma_queue_push(dma_q, dma_make_data(dst_ptr, src_addr), + row_bytes, src1->nb[1], row_bytes, ne11)) { + dma_queue_pop(dma_q); + } + } + } + } else { + for (uint32_t i13 = 0; i13 < ne13; i13++) { + for (uint32_t i12 = 0; i12 < ne12; i12++) { + for (uint32_t i11 = 0; i11 < ne11; i11++) { + dma_addr_t src_addr = src1->data + i13 * src1->nb[3] + i12 * src1->nb[2] + i11 * src1->nb[1]; + uint8_t * dst_ptr = vtcm_src1 + ((i13 * ne12 * ne11 + i12 * ne11 + i11) * src1->ne[0]) * src1_elem_size; + while (!dma_queue_push(dma_q, dma_make_data(dst_ptr, src_addr), + src1_elem_size, src1->nb[0], src1_elem_size, src1->ne[0])) { + dma_queue_pop(dma_q); + } + } } } } @@ -1328,7 +1768,7 @@ static int execute_op_binary(struct htp_ops_context * octx) { uint8_t * vtcm_src2 = VTCM_LAYOUT_PTR(uint8_t, bctx.vtcm_base, bctx.vtcm_layout.off_src2); dma_queue_push(dma_q, dma_make_data(vtcm_src1, src1->data), kparams->src1_row_size_aligned, src1->nb[1], - src1->ne[0] * elem_size, src1->ne[1]); + src1->ne[0] * src1_elem_size, src1->ne[1]); const size_t src2_row_bytes = src2->ne[0] * sizeof(int32_t); dma_queue_push(dma_q, dma_make_data(vtcm_src2, src2->data), src2_row_bytes, src2->nb[1], @@ -1344,7 +1784,13 @@ static int execute_op_binary(struct htp_ops_context * octx) { bctx.src0_row_size_aligned = src0_row_size_aligned; bctx.src1_row_size_aligned = src1_row_size_aligned; bctx.dst_row_size_aligned = dst_row_size_aligned; - bctx.row_size_bytes = src0_row_size; + bctx.src0_row_size = src0_row_size; + bctx.src1_row_size = src1_row_size; + bctx.dst_row_size = dst_row_size; + bctx.src0_elem_size = src0_elem_size; + bctx.src1_elem_size = src1_elem_size; + bctx.dst_elem_size = dst_elem_size; + bctx.src1_table_elem_size = table_type_key == 0 ? sizeof(_Float16) : sizeof(float); bctx.src0_dim1_div = kparams->div_ne01; bctx.src0_dim2_div = kparams->div_ne02; @@ -1364,6 +1810,10 @@ static int execute_op_binary(struct htp_ops_context * octx) { kparams->kernel_type == HTP_BINARY_KERNEL_COMPLEX || kparams->kernel_type == HTP_BINARY_KERNEL_ADD_ID) { dma_queue_flush(dma_q); + if ((kparams->kernel_type == HTP_BINARY_KERNEL_ROW_BCAST || kparams->kernel_type == HTP_BINARY_KERNEL_SCALAR) && + type_key != 0 && src1_type == HTP_TYPE_F16) { + binary_expand_f16_to_f32(vtcm_src1, (uint32_t) (src1->ne[0] * src1->ne[1] * src1->ne[2] * src1->ne[3])); + } if (kparams->kernel_type == HTP_BINARY_KERNEL_SCALAR && octx->src[2] != NULL && octx->op == HTP_OP_MUL) { uint8_t * vtcm_src2 = VTCM_LAYOUT_PTR(uint8_t, bctx.vtcm_base, bctx.vtcm_layout.off_src2); const uint32_t n_scalars = src1->ne[0] * src1->ne[1] * src1->ne[2] * src1->ne[3]; diff --git a/ggml/src/ggml-hexagon/htp/binary-ops.h b/ggml/src/ggml-hexagon/htp/binary-ops.h index 6f849396ce45..b6706db05752 100644 --- a/ggml/src/ggml-hexagon/htp/binary-ops.h +++ b/ggml/src/ggml-hexagon/htp/binary-ops.h @@ -28,7 +28,11 @@ struct htp_binary_kernel_params { uint8_t n_srcs; uint8_t is_scalar; - uint8_t pad[2]; + uint8_t src0_elem_size; + uint8_t src1_elem_size; + + uint8_t dst_elem_size; + uint8_t pad[3]; uint32_t n_hvx; uint32_t rows_per_buffer; @@ -61,16 +65,18 @@ static inline bool htp_binary_strides_safe( const struct ggml_tensor * src0, const struct ggml_tensor * src1, const struct ggml_tensor * dst, - size_t elem_size + size_t src0_elem_size, + size_t src1_elem_size, + size_t dst_elem_size ) { - if ((src0->ne[0] != 1 && src0->nb[0] != elem_size) || - (src1->ne[0] != 1 && src1->nb[0] != elem_size) || - (dst->ne[0] != 1 && dst->nb[0] != elem_size)) { + (void) src1; + (void) src1_elem_size; + if ((src0->ne[0] != 1 && src0->nb[0] != src0_elem_size) || + (dst->ne[0] != 1 && dst->nb[0] != dst_elem_size)) { return false; } - if ((src0->ne[1] > 1 && src0->nb[1] < src0->ne[0] * elem_size) || - (src1->ne[1] > 1 && src1->nb[1] < src1->ne[0] * elem_size) || - (dst->ne[1] > 1 && dst->nb[1] < dst->ne[0] * elem_size)) { + if ((src0->ne[1] > 1 && src0->nb[1] < src0->ne[0] * src0_elem_size) || + (dst->ne[1] > 1 && dst->nb[1] < dst->ne[0] * dst_elem_size)) { return false; } return true; @@ -114,18 +120,20 @@ static inline void htp_binary_vtcm_layout_build( const uint32_t n_srcs = kparams->n_srcs > 2 ? kparams->n_srcs : 2; if (kparams->kernel_type == HTP_BINARY_KERNEL_CHUNKED) { - const size_t chunk_bytes = kparams->chunk_bytes; - if (chunk_bytes == 0) { + const size_t src0_chunk_bytes = hex_round_up((size_t) kparams->chunk_size * kparams->src0_elem_size, 128); + const size_t src1_chunk_bytes = hex_round_up((size_t) kparams->chunk_size * kparams->src1_elem_size, 128); + const size_t dst_chunk_bytes = hex_round_up((size_t) kparams->chunk_size * kparams->dst_elem_size, 128); + if (src0_chunk_bytes == 0 || src1_chunk_bytes == 0 || dst_chunk_bytes == 0) { return; } - L->src0_bytes_per_hvx = 2 * chunk_bytes; - L->src1_bytes_per_hvx = kparams->is_scalar ? 0 : (2 * (n_srcs - 1) * chunk_bytes); - L->dst_bytes_per_hvx = 2 * chunk_bytes; + L->src0_bytes_per_hvx = 2 * src0_chunk_bytes; + L->src1_bytes_per_hvx = kparams->is_scalar ? 0 : (2 * (n_srcs - 1) * src1_chunk_bytes); + L->dst_bytes_per_hvx = 2 * dst_chunk_bytes; - L->src0_spad_half_size = chunk_bytes; - L->src1_spad_half_size = kparams->is_scalar ? 0 : chunk_bytes; - L->dst_spad_half_size = chunk_bytes; + L->src0_spad_half_size = src0_chunk_bytes; + L->src1_spad_half_size = kparams->is_scalar ? 0 : src1_chunk_bytes; + L->dst_spad_half_size = dst_chunk_bytes; L->rows_per_buffer = 1; L->src1_size = 0; @@ -199,13 +207,18 @@ static inline bool htp_binary_solve_chunked( struct htp_binary_vtcm_layout * L, struct htp_binary_kernel_params * kparams, uint32_t total_elems, - uint32_t elem_size, + uint32_t src0_elem_size, + uint32_t src1_elem_size, + uint32_t dst_elem_size, uint32_t max_hvx, uint32_t n_srcs, bool is_scalar, size_t vtcm_size ) { const size_t n_bufs = is_scalar ? 2 : (size_t) n_srcs + 1; + const uint32_t elem_size = src0_elem_size > src1_elem_size ? + (src0_elem_size > dst_elem_size ? src0_elem_size : dst_elem_size) : + (src1_elem_size > dst_elem_size ? src1_elem_size : dst_elem_size); const size_t scalar_bytes = is_scalar ? 128 : 0; const size_t budget_per_buf = (max_hvx > 0 && vtcm_size > scalar_bytes) ? hex_align_down((vtcm_size - scalar_bytes) / (2 * max_hvx * n_bufs), 128) @@ -230,6 +243,9 @@ static inline bool htp_binary_solve_chunked( kparams->n_srcs = (uint8_t) n_srcs; kparams->rows_per_buffer = 1; kparams->src1_row_size_aligned = is_scalar ? 0 : kparams->src0_row_size_aligned; + kparams->src0_elem_size = (uint8_t) src0_elem_size; + kparams->src1_elem_size = (uint8_t) src1_elem_size; + kparams->dst_elem_size = (uint8_t) dst_elem_size; kparams->src1_size = 0; kparams->chunk_size = chunk_size; kparams->chunk_bytes = chunk_bytes; diff --git a/ggml/src/ggml-hexagon/htp/concat-ops.c b/ggml/src/ggml-hexagon/htp/concat-ops.c index a374a8fd6020..7be12c55b22f 100644 --- a/ggml/src/ggml-hexagon/htp/concat-ops.c +++ b/ggml/src/ggml-hexagon/htp/concat-ops.c @@ -17,40 +17,244 @@ #include +static inline uint32_t concat_type_size(uint32_t type) { + return (type == HTP_TYPE_F16) ? 2 : 4; +} + +static inline HVX_Vector hvx_vec_clamp_f16_f32(HVX_Vector x) { + const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f); + const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f); + return Q6_Vsf_vmin_VsfVsf(Q6_Vsf_vmax_VsfVsf(x, f16_min), f16_max); +} + +static __attribute__((noinline)) void concat_cvt_f16_to_f32_aa( + uint8_t * restrict dst, + const uint8_t * restrict src, + uint32_t n) { + + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + HVX_Vector * restrict vdst = (HVX_Vector *) dst; + + uint32_t i = 0; + for (; i + 64 <= n; i += 64) { + const HVX_VectorPair vp = hvx_vec_f16_to_f32(*vsrc++); + *vdst++ = Q6_V_lo_W(vp); + *vdst++ = Q6_V_hi_W(vp); + } + if (i < n) { + const HVX_VectorPair vp = hvx_vec_f16_to_f32(*vsrc); + const uint32_t rem = n - i; + if (rem >= 32) { + *vdst++ = Q6_V_lo_W(vp); + if (rem > 32) { + hvx_vec_store_a(vdst, (rem - 32) * sizeof(float), Q6_V_hi_W(vp)); + } + } else { + hvx_vec_store_a(vdst, rem * sizeof(float), Q6_V_lo_W(vp)); + } + } +} + +static __attribute__((noinline)) void concat_cvt_f32_to_f16_aa( + uint8_t * restrict dst, + const uint8_t * restrict src, + uint32_t n) { + + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + HVX_Vector * restrict vdst = (HVX_Vector *) dst; + + uint32_t i = 0; + for (; i + 64 <= n; i += 64) { + const HVX_Vector v0 = hvx_vec_clamp_f16_f32(vsrc[0]); + const HVX_Vector v1 = hvx_vec_clamp_f16_f32(vsrc[1]); + vsrc += 2; + *vdst++ = hvx_vec_f32_to_f16(v0, v1); + } + if (i < n) { + const uint32_t rem = n - i; + const HVX_Vector v0 = hvx_vec_clamp_f16_f32(vsrc[0]); + const HVX_Vector v1 = (rem > 32) ? hvx_vec_clamp_f16_f32(vsrc[1]) : Q6_V_vzero(); + const HVX_Vector out = hvx_vec_f32_to_f16(v0, v1); + hvx_vec_store_a(vdst, rem * sizeof(__fp16), out); + } +} + +static __attribute__((noinline)) void concat_cvt_src0_rows_f16_to_f32( + uint8_t * restrict spad0, + uint8_t * restrict spad2, + uint32_t spad0_stride, + uint32_t dst_lead_pre, + uint32_t lead_ne0, + uint32_t nrows) { + + if (lead_ne0 == 0) { + return; + } + for (uint32_t r = 0; r < nrows; r++) { + uint8_t * row_ptr = spad0 + r * spad0_stride; + concat_cvt_f16_to_f32_aa(spad2, row_ptr, lead_ne0); + hvx_copy_f32_ua(row_ptr + dst_lead_pre, spad2, lead_ne0); + } +} + +static __attribute__((noinline)) void concat_cvt_src0_rows_f32_to_f16( + uint8_t * restrict spad0, + uint8_t * restrict spad2, + uint32_t spad0_stride, + uint32_t dst_lead_pre, + uint32_t lead_ne0, + uint32_t nrows) { + + if (lead_ne0 == 0) { + return; + } + for (uint32_t r = 0; r < nrows; r++) { + uint8_t * row_ptr = spad0 + r * spad0_stride; + concat_cvt_f32_to_f16_aa(spad2, row_ptr, lead_ne0); + hvx_copy_f16_ua(row_ptr + dst_lead_pre, spad2, lead_ne0); + } +} + +static __attribute__((noinline)) void concat_transpose_f32( + uint8_t * restrict dst_base, + uint32_t dst_stride, + const uint8_t * restrict src_base, + uint32_t src_stride, + uint32_t nrows, + uint32_t ncols) { + + const HVX_Vector offsets = hvx_vec_gather_offsets_w(src_stride); + for (uint32_t c = 0; c < ncols; c += 32) { + hvx_transpose_32x32_w_gather(dst_base + c * sizeof(float), dst_stride, + src_base + c * src_stride, src_stride, + offsets, nrows, MIN(ncols - c, 32)); + } + hvx_gather_sync(dst_base); +} + +static __attribute__((noinline)) void concat_transpose_f16( + uint8_t * restrict dst_base, + uint32_t dst_stride, + const uint8_t * restrict src_base, + uint32_t src_stride, + uint32_t nrows, + uint32_t ncols) { + + const HVX_Vector offsets = hvx_vec_gather_offsets_h(src_stride); + for (uint32_t c = 0; c < ncols; c += 64) { + hvx_transpose_64x64_h_gather(dst_base + c * sizeof(__fp16), dst_stride, + src_base + c * src_stride, src_stride, + offsets, nrows, MIN(ncols - c, 64)); + } + hvx_gather_sync(dst_base); +} + +static __attribute__((noinline)) void concat_transpose_cvt_f16_to_f32( + uint8_t * restrict dst_base, + uint32_t dst_stride, + const uint8_t * restrict src_base, + uint32_t src_stride, + uint8_t * restrict spad2, + uint32_t nrows, + uint32_t ncols) { + + const HVX_Vector offsets = hvx_vec_gather_offsets_h(src_stride); + for (uint32_t c = 0; c < ncols; c += 64) { + hvx_transpose_64x64_h_gather(spad2, 128, + src_base + c * src_stride, src_stride, + offsets, nrows, MIN(ncols - c, 64)); + for (uint32_t r = 0; r < nrows; r++) { + const HVX_Vector v = *(const HVX_Vector *) (spad2 + r * 128); + const HVX_VectorPair vp = hvx_vec_f16_to_f32(v); + HVX_Vector * restrict vdst = (HVX_Vector *) (dst_base + r * dst_stride + c * sizeof(float)); + vdst[0] = Q6_V_lo_W(vp); + vdst[1] = Q6_V_hi_W(vp); + } + } +} + +static __attribute__((noinline)) void concat_transpose_cvt_f32_to_f16( + uint8_t * restrict dst_base, + uint32_t dst_stride, + const uint8_t * restrict src_base, + uint32_t src_stride, + uint8_t * restrict spad2, + uint32_t nrows, + uint32_t ncols) { + + const HVX_Vector offsets = hvx_vec_gather_offsets_w(src_stride); + for (uint32_t c = 0; c < ncols; c += 64) { + const uint32_t chunk_cols = MIN(ncols - c, 64); + hvx_transpose_32x32_w_gather(spad2, 256, + src_base + c * src_stride, src_stride, + offsets, nrows, MIN(chunk_cols, 32)); + if (chunk_cols > 32) { + hvx_transpose_32x32_w_gather(spad2 + 128, 256, + src_base + (c + 32) * src_stride, src_stride, + offsets, nrows, chunk_cols - 32); + } + if (chunk_cols > 32) { + for (uint32_t r = 0; r < nrows; r++) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) (spad2 + r * 256); + const HVX_Vector v0 = hvx_vec_clamp_f16_f32(vsrc[0]); + const HVX_Vector v1 = hvx_vec_clamp_f16_f32(vsrc[1]); + *(HVX_Vector *) (dst_base + r * dst_stride + c * sizeof(__fp16)) = hvx_vec_f32_to_f16(v0, v1); + } + } else { + const HVX_Vector zero = Q6_V_vzero(); + for (uint32_t r = 0; r < nrows; r++) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) (spad2 + r * 256); + const HVX_Vector v0 = hvx_vec_clamp_f16_f32(vsrc[0]); + *(HVX_Vector *) (dst_base + r * dst_stride + c * sizeof(__fp16)) = hvx_vec_f32_to_f16(v0, zero); + } + } + } +} + struct htp_concat_context { - struct htp_ops_context * octx; - uint8_t * spad0_base; - uint8_t * spad1_base; - uint32_t spad0_size_per_hvx; - uint32_t spad1_size_per_hvx; - uint32_t row_start; - uint32_t nrows; - uint32_t nrows_per_hvx; - uint32_t nplanes; - struct fastdiv_values div_ne2; + struct htp_ops_context * octx; + const struct htp_tensor * lead_src; + const struct htp_tensor * trans_src; + const struct htp_tensor * dst_view; + uint8_t * spad0_base; + uint8_t * spad1_base; + uint8_t * spad2_base; + uint32_t spad0_size_per_hvx; + uint32_t spad1_size_per_hvx; + uint32_t spad2_size_per_hvx; + uint32_t row_start; + uint32_t nrows; + uint32_t nrows_per_hvx; + uint32_t nplanes; + struct fastdiv_values div_ne2; }; static inline dma_addr_t concat_plane_addr(const struct htp_tensor * t, uint32_t p, const struct fastdiv_values * div_ne2, uint32_t ne2) { const uint32_t i3 = fastdiv(p, div_ne2); const uint32_t i2 = p - i3 * ne2; - return t->data + i2 * t->nb[2] + i3 * t->nb[3]; + return t->data + (i2 * t->nb[2] + i3 * t->nb[3]); } -static void concat_2d_f32_transposed(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { +static void concat_2d_transposed_worker(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; struct htp_concat_context * cctx = (struct htp_concat_context *) data; - struct htp_ops_context * octx = cctx->octx; - const struct htp_tensor * src0 = octx->src[0]; - const struct htp_tensor * src1 = octx->src[1]; - const struct htp_tensor * dst = octx->dst; + const struct htp_tensor * src0 = cctx->lead_src; + const struct htp_tensor * src1 = cctx->trans_src; + const struct htp_tensor * dst = cctx->dst_view; - const uint32_t src0_ne0 = src0->ne[0]; + const uint32_t src0_ne0 = src0 ? src0->ne[0] : 0; const uint32_t src1_ne0 = src1->ne[0]; - // dst rows [row_begin, row_end) of this thread; a dst row is a src0 row followed by a src1 column + const uint32_t dst_es = concat_type_size(dst->type); + const uint32_t src0_es = src0 ? concat_type_size(src0->type) : dst_es; + const uint32_t src1_es = concat_type_size(src1->type); + const uint32_t row_begin = cctx->row_start + ith * cctx->nrows_per_hvx; const uint32_t row_end = MIN(row_begin + cctx->nrows_per_hvx, cctx->row_start + cctx->nrows); - if (row_begin >= row_end) return; + if (row_begin >= row_end) { + return; + } dma_queue * dma_q = th->dma_q; struct htp_thread_trace * tr = th->trace; @@ -58,37 +262,39 @@ static void concat_2d_f32_transposed(const htp_thread_t * th, unsigned int nth, const struct fastdiv_values * div_ne2 = &cctx->div_ne2; const uint32_t ne2 = dst->ne[2]; - // tile: block_rows dst rows x block_cols src1 columns const uint32_t block_rows = 128; - const uint32_t block_cols = 256; - // +1 element spreads the gather lanes across VTCM, so they do not serialize on one path - const uint32_t spad1_stride = block_rows * sizeof(float) + sizeof(float); - - const HVX_Vector offsets = hvx_vec_gather_offsets_w(spad1_stride); - const uint32_t block_cols_padded = MIN(hex_round_up(src1_ne0, 32), block_cols); - const uint32_t src0_row_bytes = src0_ne0 * sizeof(float); - const uint32_t src0_row_padded = hex_round_up(src0_row_bytes, VLEN); - const uint32_t src0_pre = src0_row_padded - src0_row_bytes; - const uint32_t spad0_stride = src0_row_padded + block_cols_padded * sizeof(float); - - // two slots per scratchpad: tile b gathers in slot b&1 while dst[b-1] and src1[b+1] DMA in the other - uint8_t * spad0_base = cctx->spad0_base + ith * cctx->spad0_size_per_hvx; - uint8_t * spad1_base = cctx->spad1_base + ith * cctx->spad1_size_per_hvx; + const uint32_t block_cols = (src1_es == 2 && dst_es == 2) ? 512 : 256; + const uint32_t col_align = (src1_es == 2 || dst_es == 2) ? 64 : 32; + const uint32_t spad1_stride = block_rows * src1_es + src1_es; + + const uint32_t block_cols_padded = MIN(hex_round_up(src1_ne0, col_align), block_cols); + const uint32_t dst_src0_row_bytes = src0_ne0 * dst_es; + const uint32_t dst_src0_row_padded = hex_round_up(dst_src0_row_bytes, VLEN); + const uint32_t dst_src0_pre = dst_src0_row_padded - dst_src0_row_bytes; + const uint32_t raw_src0_row_bytes = src0_ne0 * src0_es; + const uint32_t raw_src0_row_padded = (src0_es != dst_es) ? hex_round_up(raw_src0_row_bytes, VLEN) : 0; + const uint32_t spad0_stride = MAX(dst_src0_row_padded + block_cols_padded * dst_es, raw_src0_row_padded); + const uint32_t src0_dma_off = (src0_es == dst_es) ? dst_src0_pre : 0; + + uint8_t * spad0_base = cctx->spad0_base + (size_t) ith * cctx->spad0_size_per_hvx; + uint8_t * spad1_base = cctx->spad1_base + (size_t) ith * cctx->spad1_size_per_hvx; + uint8_t * spad2 = cctx->spad2_base ? (cctx->spad2_base + (size_t) ith * cctx->spad2_size_per_hvx) : NULL; const uint32_t spad0_slot = block_rows * spad0_stride; const uint32_t spad1_slot = block_cols_padded * spad1_stride; - // tiles walk (plane, row, col) with col fastest; src0 goes out with the col == 0 tile only uint32_t plane = 0; uint32_t row = row_begin; uint32_t col = 0; uint32_t slot = 0; - bool dst_pending = false; const dma_addr_t src1_addr = concat_plane_addr(src1, plane, div_ne2, ne2) + row * src1->nb[1]; - dma_queue_push(dma_q, dma_make_data(spad1_base, src1_addr), spad1_stride, src1->nb[0], MIN(row_end - row, block_rows) * sizeof(float), MIN(src1_ne0, block_cols)); + dma_queue_push(dma_q, dma_make_data(spad1_base, src1_addr), spad1_stride, src1->nb[0], MIN(row_end - row, block_rows) * src1_es, MIN(src1_ne0, block_cols)); - const dma_addr_t src0_addr = concat_plane_addr(src0, plane, div_ne2, ne2) + row * src0->nb[1]; - dma_queue_push(dma_q, dma_make_data(spad0_base + src0_pre, src0_addr), spad0_stride, src0->nb[1], src0_row_bytes, MIN(row_end - row, block_rows)); + if (src0) { + const dma_addr_t src0_addr = concat_plane_addr(src0, plane, div_ne2, ne2) + row * src0->nb[1]; + dma_queue_push(dma_q, dma_make_data(spad0_base + src0_dma_off, src0_addr), spad0_stride, src0->nb[1], raw_src0_row_bytes, MIN(row_end - row, block_rows)); + } + dma_queue_push(dma_q, dma_make_data(dst->data, spad0_base), 0, 0, 0, 0); while (plane < cctx->nplanes) { const uint32_t nrows = MIN(row_end - row, block_rows); @@ -98,7 +304,7 @@ static void concat_2d_f32_transposed(const htp_thread_t * th, unsigned int nth, uint8_t * spad1 = spad1_base + slot * spad1_slot; dma_queue_pop(dma_q); // src1 - if (col == 0) { + if (src0 && col == 0) { dma_queue_pop(dma_q); // src0 } @@ -117,33 +323,43 @@ static void concat_2d_f32_transposed(const htp_thread_t * th, unsigned int nth, const uint32_t next_nrows = MIN(row_end - next_row, block_rows); const uint32_t next_ncols = MIN(src1_ne0 - next_col, block_cols); - // other spad1 slot is free since the previous gather sync if (has_next) { - const dma_addr_t addr = concat_plane_addr(src1, next_plane, div_ne2, ne2) + next_row * src1->nb[1] + next_col * src1->nb[0]; - dma_queue_push(dma_q, dma_make_data(spad1_base + (slot ^ 1) * spad1_slot, addr), spad1_stride, src1->nb[0], next_nrows * sizeof(float), next_ncols); + const dma_addr_t addr = concat_plane_addr(src1, next_plane, div_ne2, ne2) + (next_row * src1->nb[1] + next_col * src1->nb[0]); + dma_queue_push(dma_q, dma_make_data(spad1_base + (slot ^ 1) * spad1_slot, addr), spad1_stride, src1->nb[0], next_nrows * src1_es, next_ncols); } htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) row); - for (uint32_t c = 0; c < ncols; c += 32) { - hvx_transpose_32x32_w_gather(spad0 + src0_row_padded + c * sizeof(float), spad0_stride, spad1 + c * spad1_stride, spad1_stride, offsets, nrows, MIN(ncols - c, 32)); + if (src0 && col == 0 && src0_es != dst_es) { + if (dst_es == 4) { + concat_cvt_src0_rows_f16_to_f32(spad0, spad2, spad0_stride, dst_src0_pre, src0_ne0, nrows); + } else { + concat_cvt_src0_rows_f32_to_f16(spad0, spad2, spad0_stride, dst_src0_pre, src0_ne0, nrows); + } } - hvx_gather_sync(spad0 + src0_row_padded); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) row); - // other spad0 slot is free once dst[b-1] is written - if (dst_pending) { - dma_queue_pop(dma_q); // dst + uint8_t * dst_trans = spad0 + dst_src0_row_padded; + if (src1_es == dst_es) { + if (dst_es == 4) { + concat_transpose_f32(dst_trans, spad0_stride, spad1, spad1_stride, nrows, ncols); + } else { + concat_transpose_f16(dst_trans, spad0_stride, spad1, spad1_stride, nrows, ncols); + } + } else if (dst_es == 4) { + concat_transpose_cvt_f16_to_f32(dst_trans, spad0_stride, spad1, spad1_stride, spad2, nrows, ncols); + } else { + concat_transpose_cvt_f32_to_f16(dst_trans, spad0_stride, spad1, spad1_stride, spad2, nrows, ncols); } - if (has_next && next_col == 0) { + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) row); + + dma_queue_pop(dma_q); // dst + if (src0 && has_next && next_col == 0) { const dma_addr_t addr = concat_plane_addr(src0, next_plane, div_ne2, ne2) + next_row * src0->nb[1]; - dma_queue_push(dma_q, dma_make_data(spad0_base + (slot ^ 1) * spad0_slot + src0_pre, addr), spad0_stride, src0->nb[1], src0_row_bytes, next_nrows); + dma_queue_push(dma_q, dma_make_data(spad0_base + (slot ^ 1) * spad0_slot + src0_dma_off, addr), spad0_stride, src0->nb[1], raw_src0_row_bytes, next_nrows); } - // the col == 0 tile also carries the src0 columns in front - const uint32_t lead = (col == 0) ? src0_row_bytes : 0; - const dma_addr_t dst_addr = concat_plane_addr(dst, plane, div_ne2, ne2) + row * dst->nb[1] + src0_row_bytes + col * sizeof(float) - lead; - dma_queue_push(dma_q, dma_make_data(dst_addr, spad0 + src0_row_padded - lead), dst->nb[1], spad0_stride, lead + ncols * sizeof(float), nrows); - dst_pending = true; + const uint32_t lead = (src0 && col == 0) ? dst_src0_row_bytes : 0; + const dma_addr_t dst_addr = concat_plane_addr(dst, plane, div_ne2, ne2) + (row * dst->nb[1] + dst_src0_row_bytes + col * dst_es - lead); + dma_queue_push(dma_q, dma_make_data(dst_addr, spad0 + dst_src0_row_padded - lead), dst->nb[1], spad0_stride, lead + ncols * dst_es, nrows); plane = next_plane; row = next_row; @@ -153,127 +369,256 @@ static void concat_2d_f32_transposed(const htp_thread_t * th, unsigned int nth, dma_queue_flush(dma_q); } -static void concat_2d_f16_transposed(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { - struct htp_concat_context * cctx = (struct htp_concat_context *) data; - struct htp_ops_context * octx = cctx->octx; +struct concat_regular_cvt_task { + struct htp_ops_context * octx; + const struct htp_tensor * src; + const struct htp_tensor * dst; + uint32_t r_start; + uint32_t nrows; + uint32_t rows_per_hvx; + uint32_t src_es; + uint32_t dst_es; + struct fastdiv_values div_ne1; + struct fastdiv_values div_ne2_ne1; +}; - const struct htp_tensor * src0 = octx->src[0]; - const struct htp_tensor * src1 = octx->src[1]; - const struct htp_tensor * dst = octx->dst; +static inline void concat_regular_row_addrs( + const struct concat_regular_cvt_task * task, + uint32_t r, + uint32_t * i1_out, + dma_addr_t * src_addr_out, + dma_addr_t * dst_addr_out) { + + const struct htp_tensor * src = task->src; + const struct htp_tensor * dst = task->dst; + const uint32_t ne1 = src->ne[1]; + const uint32_t ne2_ne1 = src->ne[2] * ne1; + + const uint32_t i3 = fastdiv(r, &task->div_ne2_ne1); + const uint32_t rem = r - i3 * ne2_ne1; + const uint32_t i2 = fastdiv(rem, &task->div_ne1); + const uint32_t i1 = rem - i2 * ne1; + + *i1_out = i1; + *src_addr_out = src->data + (i1 * src->nb[1] + i2 * src->nb[2] + i3 * src->nb[3]); + *dst_addr_out = dst->data + (i1 * dst->nb[1] + i2 * dst->nb[2] + i3 * dst->nb[3]); +} - const uint32_t src0_ne0 = src0->ne[0]; - const uint32_t src1_ne0 = src1->ne[0]; +static void concat_regular_cvt_worker(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; + const struct concat_regular_cvt_task * task = (const struct concat_regular_cvt_task *) data; + const struct htp_tensor * src = task->src; + const struct htp_tensor * dst = task->dst; + + const uint32_t r_offset = MIN(ith * task->rows_per_hvx, task->nrows); + const uint32_t r_beg = task->r_start + r_offset; + const uint32_t r_end = task->r_start + MIN(r_offset + task->rows_per_hvx, task->nrows); + if (r_beg >= r_end) { + return; + } - // dst rows [row_begin, row_end) of this thread; a dst row is a src0 row followed by a src1 column - const uint32_t row_begin = cctx->row_start + ith * cctx->nrows_per_hvx; - const uint32_t row_end = MIN(row_begin + cctx->nrows_per_hvx, cctx->row_start + cctx->nrows); - if (row_begin >= row_end) return; + const uint32_t ne0 = src->ne[0]; + const uint32_t ne1 = src->ne[1]; + if (ne0 == 0) { + return; + } - dma_queue * dma_q = th->dma_q; + const uint32_t src_es = task->src_es; + const uint32_t dst_es = task->dst_es; + const uint32_t max_es = MAX(src_es, dst_es); + + uint8_t * base = (uint8_t *) task->octx->ctx->vtcm_base + (size_t) ith * (4 * HTP_CONCAT_REG_BLK_BYTES); + uint8_t * sbuf[2] = { + base + 0 * HTP_CONCAT_REG_BLK_BYTES, + base + 1 * HTP_CONCAT_REG_BLK_BYTES, + }; + uint8_t * dbuf[2] = { + base + 2 * HTP_CONCAT_REG_BLK_BYTES, + base + 3 * HTP_CONCAT_REG_BLK_BYTES, + }; + + dma_queue * q = th->dma_q; struct htp_thread_trace * tr = th->trace; - const struct fastdiv_values * div_ne2 = &cctx->div_ne2; - const uint32_t ne2 = dst->ne[2]; + const uint32_t row_max_bytes = ne0 * max_es; + if (row_max_bytes <= HTP_CONCAT_REG_BLK_BYTES) { + uint32_t max_rows_per_blk = HTP_CONCAT_REG_BLK_BYTES / row_max_bytes; + if (src->nb[1] > 65535 || dst->nb[1] > 65535) { + max_rows_per_blk = 1; + } + if (max_rows_per_blk > DMA_MAX_NROWS) { + max_rows_per_blk = DMA_MAX_NROWS; + } - // tile: block_rows dst rows x block_cols src1 columns - const uint32_t block_rows = 128; - const uint32_t block_cols = 512; - // +1 element spreads the gather lanes across VTCM, so they do not serialize on one path - const uint32_t spad1_stride = block_rows * sizeof(__fp16) + sizeof(__fp16); - - const HVX_Vector offsets = hvx_vec_gather_offsets_h(spad1_stride); - const uint32_t block_cols_padded = MIN(hex_round_up(src1_ne0, 64), block_cols); - const uint32_t src0_row_bytes = src0_ne0 * sizeof(__fp16); - const uint32_t src0_row_padded = hex_round_up(src0_row_bytes, VLEN); - const uint32_t src0_pre = src0_row_padded - src0_row_bytes; - const uint32_t spad0_stride = src0_row_padded + block_cols_padded * sizeof(__fp16); - - // two slots per scratchpad: tile b gathers in slot b&1 while dst[b-1] and src1[b+1] DMA in the other - uint8_t * spad0_base = cctx->spad0_base + ith * cctx->spad0_size_per_hvx; - uint8_t * spad1_base = cctx->spad1_base + ith * cctx->spad1_size_per_hvx; - const uint32_t spad0_slot = block_rows * spad0_stride; - const uint32_t spad1_slot = block_cols_padded * spad1_stride; + const uint32_t src_row_bytes = ne0 * src_es; + const uint32_t dst_row_bytes = ne0 * dst_es; - // tiles walk (plane, row, col) with col fastest; src0 goes out with the col == 0 tile only - uint32_t plane = 0; - uint32_t row = row_begin; - uint32_t col = 0; - uint32_t slot = 0; - bool dst_pending = false; + uint32_t cur_r = r_beg; + uint32_t cur_i1 = 0; + dma_addr_t cur_src_addr = 0; + dma_addr_t cur_dst_addr = 0; + concat_regular_row_addrs(task, cur_r, &cur_i1, &cur_src_addr, &cur_dst_addr); + uint32_t cur_nr = MIN(MIN(r_end - cur_r, max_rows_per_blk), ne1 - cur_i1); - const dma_addr_t src1_addr = concat_plane_addr(src1, plane, div_ne2, ne2) + row * src1->nb[1]; - dma_queue_push(dma_q, dma_make_data(spad1_base, src1_addr), spad1_stride, src1->nb[0], MIN(row_end - row, block_rows) * sizeof(__fp16), MIN(src1_ne0, block_cols)); + const size_t s_stride0 = (cur_nr > 1) ? src->nb[1] : src_row_bytes; + dma_queue_push(q, dma_make_data(sbuf[0], cur_src_addr), src_row_bytes, s_stride0, src_row_bytes, cur_nr); + dma_queue_push(q, dma_make_data(cur_dst_addr, dbuf[1]), 0, 0, 0, 0); - const dma_addr_t src0_addr = concat_plane_addr(src0, plane, div_ne2, ne2) + row * src0->nb[1]; - dma_queue_push(dma_q, dma_make_data(spad0_base + src0_pre, src0_addr), spad0_stride, src0->nb[1], src0_row_bytes, MIN(row_end - row, block_rows)); + uint32_t slot = 0; - while (plane < cctx->nplanes) { - const uint32_t nrows = MIN(row_end - row, block_rows); - const uint32_t ncols = MIN(src1_ne0 - col, block_cols); + while (cur_r < r_end) { + const uint32_t next_r = cur_r + cur_nr; + uint32_t next_i1 = 0; + dma_addr_t next_src_addr = 0; + dma_addr_t next_dst_addr = 0; + uint32_t next_nr = 0; - uint8_t * spad0 = spad0_base + slot * spad0_slot; - uint8_t * spad1 = spad1_base + slot * spad1_slot; + dma_queue_pop(q); // sbuf[slot] - dma_queue_pop(dma_q); // src1 - if (col == 0) { - dma_queue_pop(dma_q); // src0 - } + if (next_r < r_end) { + concat_regular_row_addrs(task, next_r, &next_i1, &next_src_addr, &next_dst_addr); + next_nr = MIN(MIN(r_end - next_r, max_rows_per_blk), ne1 - next_i1); + const size_t s_stride_next = (next_nr > 1) ? src->nb[1] : src_row_bytes; + dma_queue_push(q, dma_make_data(sbuf[slot ^ 1], next_src_addr), src_row_bytes, s_stride_next, src_row_bytes, next_nr); + } - uint32_t next_plane = plane; - uint32_t next_row = row; - uint32_t next_col = col + block_cols; - if (next_col >= src1_ne0) { - next_col = 0; - next_row = row + block_rows; - if (next_row >= row_end) { - next_row = row_begin; - next_plane++; + dma_queue_pop(q); // dbuf[slot ^ 1] + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) cur_r); + if (dst_es == 4) { + concat_cvt_f16_to_f32_aa(dbuf[slot], sbuf[slot], cur_nr * ne0); + } else { + concat_cvt_f32_to_f16_aa(dbuf[slot], sbuf[slot], cur_nr * ne0); } - } - const bool has_next = next_plane < cctx->nplanes; - const uint32_t next_nrows = MIN(row_end - next_row, block_rows); - const uint32_t next_ncols = MIN(src1_ne0 - next_col, block_cols); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) cur_r); - // other spad1 slot is free since the previous gather sync - if (has_next) { - const dma_addr_t addr = concat_plane_addr(src1, next_plane, div_ne2, ne2) + next_row * src1->nb[1] + next_col * src1->nb[0]; - dma_queue_push(dma_q, dma_make_data(spad1_base + (slot ^ 1) * spad1_slot, addr), spad1_stride, src1->nb[0], next_nrows * sizeof(__fp16), next_ncols); - } + const size_t d_stride = (cur_nr > 1) ? dst->nb[1] : dst_row_bytes; + dma_queue_push(q, dma_make_data(cur_dst_addr, dbuf[slot]), d_stride, dst_row_bytes, dst_row_bytes, cur_nr); - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) row); - for (uint32_t c = 0; c < ncols; c += 64) { - hvx_transpose_64x64_h_gather(spad0 + src0_row_padded + c * sizeof(__fp16), spad0_stride, spad1 + c * spad1_stride, spad1_stride, offsets, nrows, MIN(ncols - c, 64)); + cur_r = next_r; + cur_i1 = next_i1; + cur_src_addr = next_src_addr; + cur_dst_addr = next_dst_addr; + cur_nr = next_nr; + slot ^= 1; } - hvx_gather_sync(spad0 + src0_row_padded); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) row); + dma_queue_flush(q); + } else { + const uint32_t max_cols = HTP_CONCAT_REG_BLK_BYTES / max_es; + uint32_t r = r_beg; + uint32_t col = 0; + uint32_t i1 = 0; + dma_addr_t row_src_addr = 0; + dma_addr_t row_dst_addr = 0; + concat_regular_row_addrs(task, r, &i1, &row_src_addr, &row_dst_addr); + + uint32_t cur_cols = MIN(ne0 - col, max_cols); + const uint32_t s_bytes0 = cur_cols * src_es; + dma_queue_push(q, dma_make_data(sbuf[0], row_src_addr), s_bytes0, s_bytes0, s_bytes0, 1); + dma_queue_push(q, dma_make_data(row_dst_addr, dbuf[1]), 0, 0, 0, 0); + + uint32_t slot = 0; + + while (r < r_end) { + uint32_t next_r = r; + uint32_t next_col = col + cur_cols; + uint32_t next_i1 = i1; + dma_addr_t next_row_src_addr = row_src_addr; + dma_addr_t next_row_dst_addr = row_dst_addr; + if (next_col >= ne0) { + next_col = 0; + next_r = r + 1; + if (next_r < r_end) { + concat_regular_row_addrs(task, next_r, &next_i1, &next_row_src_addr, &next_row_dst_addr); + } + } - // other spad0 slot is free once dst[b-1] is written - if (dst_pending) { - dma_queue_pop(dma_q); // dst - } - if (has_next && next_col == 0) { - const dma_addr_t addr = concat_plane_addr(src0, next_plane, div_ne2, ne2) + next_row * src0->nb[1]; - dma_queue_push(dma_q, dma_make_data(spad0_base + (slot ^ 1) * spad0_slot + src0_pre, addr), spad0_stride, src0->nb[1], src0_row_bytes, next_nrows); + dma_queue_pop(q); // sbuf[slot] + + if (next_r < r_end) { + const uint32_t next_cols = MIN(ne0 - next_col, max_cols); + const uint32_t s_bytes_next = next_cols * src_es; + dma_queue_push(q, dma_make_data(sbuf[slot ^ 1], next_row_src_addr + next_col * src_es), + s_bytes_next, s_bytes_next, s_bytes_next, 1); + } + + dma_queue_pop(q); // dbuf[slot ^ 1] + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r); + if (dst_es == 4) { + concat_cvt_f16_to_f32_aa(dbuf[slot], sbuf[slot], cur_cols); + } else { + concat_cvt_f32_to_f16_aa(dbuf[slot], sbuf[slot], cur_cols); + } + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r); + + const uint32_t d_bytes = cur_cols * dst_es; + dma_queue_push(q, dma_make_data(row_dst_addr + col * dst_es, dbuf[slot]), + d_bytes, d_bytes, d_bytes, 1); + + r = next_r; + col = next_col; + i1 = next_i1; + row_src_addr = next_row_src_addr; + row_dst_addr = next_row_dst_addr; + cur_cols = MIN(ne0 - col, max_cols); + slot ^= 1; } + dma_queue_flush(q); + } +} - // the col == 0 tile also carries the src0 columns in front - const uint32_t lead = (col == 0) ? src0_row_bytes : 0; - const dma_addr_t dst_addr = concat_plane_addr(dst, plane, div_ne2, ne2) + row * dst->nb[1] + src0_row_bytes + col * sizeof(__fp16) - lead; - dma_queue_push(dma_q, dma_make_data(dst_addr, spad0 + src0_row_padded - lead), dst->nb[1], spad0_stride, lead + ncols * sizeof(__fp16), nrows); - dst_pending = true; +static void concat_regular_side( + struct htp_ops_context * octx, + const struct htp_tensor * dst_view, + const struct htp_tensor * src, + uint32_t rstart, + uint32_t nrows, + const struct fastdiv_values * div_ne1, + const struct fastdiv_values * div_ne2_ne1) { + + if (nrows == 0 || src->ne[0] == 0) { + return; + } - plane = next_plane; - row = next_row; - col = next_col; - slot ^= 1; + const uint32_t dst_es = (dst_view->type == HTP_TYPE_F32 || dst_view->type == HTP_TYPE_I32) ? 4 : 2; + if (src->type == dst_view->type) { + dma_queue * q = octx->ctx->dma[0]; + dma_cpy_sametype_sameshape_range(q, dst_view, src, dst_es, rstart, nrows); + dma_queue_flush(q); + return; } - dma_queue_flush(dma_q); + + const uint32_t n_hvx = octx->n_hvx; + struct concat_regular_cvt_task task; + task.octx = octx; + task.src = src; + task.dst = dst_view; + task.r_start = rstart; + task.nrows = nrows; + task.rows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div); + task.src_es = concat_type_size(src->type); + task.dst_es = dst_es; + task.div_ne1 = *div_ne1; + task.div_ne2_ne1 = *div_ne2_ne1; + + work_queue_run(octx->ctx->hvx_queue, concat_regular_cvt_worker, &task, n_hvx); } -static int concat_regular(struct htp_ops_context * octx, int dim, uint32_t type_size) { +static int concat_regular(struct htp_ops_context * octx, const struct htp_concat_kernel_params * kparams) { const struct htp_tensor * src0 = octx->src[0]; const struct htp_tensor * src1 = octx->src[1]; const struct htp_tensor * dst = octx->dst; + const int dim = kparams->dim; + + if (src0->type != dst->type || src1->type != dst->type) { + if (!htp_ops_context_set_n_hvx(octx, kparams->n_hvx)) { + return HTP_STATUS_INVAL_PARAMS; + } + if (kparams->vtcm_size > octx->ctx->vtcm_size) { + return HTP_STATUS_VTCM_TOO_SMALL; + } + } struct htp_tensor view0 = *dst; struct htp_tensor view1 = *dst; @@ -301,27 +646,29 @@ static int concat_regular(struct htp_ops_context * octx, int dim, uint32_t type_ nrows1 = range1.count; } - dma_queue * q = octx->ctx->dma[0]; - - dma_cpy_sametype_sameshape_range(q, &view0, src0, type_size, rstart0, nrows0); - dma_cpy_sametype_sameshape_range(q, &view1, src1, type_size, rstart1, nrows1); - dma_queue_flush(q); + concat_regular_side(octx, &view0, src0, rstart0, nrows0, + &kparams->u.regular.div_ne01, &kparams->u.regular.div_ne02_ne01); + concat_regular_side(octx, &view1, src1, rstart1, nrows1, + &kparams->u.regular.div_ne11, &kparams->u.regular.div_ne12_ne11); return HTP_STATUS_OK; } -static int concat_transposed(struct htp_ops_context * octx, const struct htp_concat_kernel_params * kparams, uint32_t type_size) { +static int concat_transposed(struct htp_ops_context * octx, const struct htp_concat_kernel_params * kparams) { if (!htp_ops_context_set_n_hvx(octx, kparams->n_hvx)) { return HTP_STATUS_INVAL_PARAMS; } - const struct htp_tensor * dst = octx->dst; + const struct htp_tensor * src0 = octx->src[0]; + const struct htp_tensor * src1 = octx->src[1]; + const struct htp_tensor * dst = octx->dst; const uint32_t total_rows = dst->ne[1]; uint32_t row_start = 0; uint32_t nrows = total_rows; if (octx->ctx->mdev.count > 1) { - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( + total_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); row_start = range.start; nrows = range.count; } @@ -334,27 +681,492 @@ static int concat_transposed(struct htp_ops_context * octx, const struct htp_con return HTP_STATUS_VTCM_TOO_SMALL; } - const uint32_t n_hvx = octx->n_hvx; + const uint32_t n_hvx = octx->n_hvx; + const uint32_t src0_es = concat_type_size(src0->type); + const uint32_t src1_es = concat_type_size(src1->type); + const uint32_t dst_es = concat_type_size(dst->type); - struct htp_concat_transposed_vtcm_layout layout; - htp_concat_transposed_vtcm_layout_build(&layout, octx->src[0]->ne[0], octx->src[1]->ne[0], type_size, n_hvx); + const bool is_src0_transposed = (src0->nb[0] > src0->nb[1]); + const bool is_src1_transposed = (src1->nb[0] > src1->nb[1]); uint8_t * vtcm_base = (uint8_t *) octx->ctx->vtcm_base; - struct htp_concat_context cctx; - cctx.octx = octx; - cctx.spad0_base = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_spad0); - cctx.spad1_base = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_spad1); - cctx.spad0_size_per_hvx = layout.src0_spad_size_per_hvx; - cctx.spad1_size_per_hvx = layout.src1_spad_size_per_hvx; - cctx.row_start = row_start; - cctx.nrows = nrows; - cctx.nplanes = dst->ne[2] * dst->ne[3]; - cctx.div_ne2 = kparams->u.transposed.div_ne2; - cctx.nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div); - - work_queue_func_t worker_func = (type_size == 4) ? concat_2d_f32_transposed : concat_2d_f16_transposed; - work_queue_run(octx->ctx->hvx_queue, worker_func, &cctx, n_hvx); + if (!is_src0_transposed && is_src1_transposed) { + struct htp_concat_transposed_vtcm_layout layout; + htp_concat_transposed_vtcm_layout_build(&layout, src0->ne[0], src1->ne[0], src0_es, src1_es, dst_es, n_hvx); + + struct htp_concat_context cctx; + cctx.octx = octx; + cctx.lead_src = src0; + cctx.trans_src = src1; + cctx.dst_view = dst; + cctx.spad0_base = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_spad0); + cctx.spad1_base = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_spad1); + cctx.spad2_base = layout.cvt_spad_size_per_hvx > 0 ? VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_spad2) : NULL; + cctx.spad0_size_per_hvx = layout.src0_spad_size_per_hvx; + cctx.spad1_size_per_hvx = layout.src1_spad_size_per_hvx; + cctx.spad2_size_per_hvx = layout.cvt_spad_size_per_hvx; + cctx.row_start = row_start; + cctx.nrows = nrows; + cctx.nplanes = dst->ne[2] * dst->ne[3]; + cctx.div_ne2 = kparams->u.transposed.div_ne2; + cctx.nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div); + + work_queue_run(octx->ctx->hvx_queue, concat_2d_transposed_worker, &cctx, n_hvx); + return HTP_STATUS_OK; + } + + struct htp_tensor view0 = *dst; + struct htp_tensor view1 = *dst; + view0.ne[0] = src0->ne[0]; + view1.ne[0] = src1->ne[0]; + view1.data += src0->ne[0] * dst_es; + + if (src0->ne[0] > 0) { + struct htp_concat_transposed_vtcm_layout layout0; + htp_concat_transposed_vtcm_layout_build(&layout0, 0, src0->ne[0], dst_es, src0_es, dst_es, n_hvx); + + struct htp_concat_context cctx0; + cctx0.octx = octx; + cctx0.lead_src = NULL; + cctx0.trans_src = src0; + cctx0.dst_view = &view0; + cctx0.spad0_base = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout0.off_spad0); + cctx0.spad1_base = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout0.off_spad1); + cctx0.spad2_base = layout0.cvt_spad_size_per_hvx > 0 ? VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout0.off_spad2) : NULL; + cctx0.spad0_size_per_hvx = layout0.src0_spad_size_per_hvx; + cctx0.spad1_size_per_hvx = layout0.src1_spad_size_per_hvx; + cctx0.spad2_size_per_hvx = layout0.cvt_spad_size_per_hvx; + cctx0.row_start = row_start; + cctx0.nrows = nrows; + cctx0.nplanes = dst->ne[2] * dst->ne[3]; + cctx0.div_ne2 = kparams->u.transposed.div_ne2; + cctx0.nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div); + + work_queue_run(octx->ctx->hvx_queue, concat_2d_transposed_worker, &cctx0, n_hvx); + } + + if (is_src1_transposed) { + if (src1->ne[0] > 0) { + struct htp_concat_transposed_vtcm_layout layout1; + htp_concat_transposed_vtcm_layout_build(&layout1, 0, src1->ne[0], dst_es, src1_es, dst_es, n_hvx); + + struct htp_concat_context cctx1; + cctx1.octx = octx; + cctx1.lead_src = NULL; + cctx1.trans_src = src1; + cctx1.dst_view = &view1; + cctx1.spad0_base = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout1.off_spad0); + cctx1.spad1_base = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout1.off_spad1); + cctx1.spad2_base = layout1.cvt_spad_size_per_hvx > 0 ? VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout1.off_spad2) : NULL; + cctx1.spad0_size_per_hvx = layout1.src0_spad_size_per_hvx; + cctx1.spad1_size_per_hvx = layout1.src1_spad_size_per_hvx; + cctx1.spad2_size_per_hvx = layout1.cvt_spad_size_per_hvx; + cctx1.row_start = row_start; + cctx1.nrows = nrows; + cctx1.nplanes = dst->ne[2] * dst->ne[3]; + cctx1.div_ne2 = kparams->u.transposed.div_ne2; + cctx1.nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div); + + work_queue_run(octx->ctx->hvx_queue, concat_2d_transposed_worker, &cctx1, n_hvx); + } + } else if (src1->ne[0] > 0) { + const uint32_t total_rows_1 = src1->ne[1] * src1->ne[2] * src1->ne[3]; + uint32_t rstart1 = 0, nrows1 = total_rows_1; + if (octx->ctx->mdev.count > 1) { + const struct htp_tensor_mdev_range range1 = htp_tensor_mdev_partition( + total_rows_1, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + rstart1 = range1.start; + nrows1 = range1.count; + } + const struct fastdiv_values div_ne11 = init_fastdiv_values(src1->ne[1]); + const struct fastdiv_values div_ne12_ne11 = init_fastdiv_values(src1->ne[1] * src1->ne[2]); + concat_regular_side(octx, &view1, src1, rstart1, nrows1, &div_ne11, &div_ne12_ne11); + } + + return HTP_STATUS_OK; +} + +typedef void (*concat_gather_compute_fn_t)( + uint8_t * restrict out, const uint8_t * restrict region, uint32_t nvec, + const struct htp_gather_rows_params * restrict kparams, + const HVX_Vector * restrict tab, const HVX_Vector * restrict inc, HVX_Vector * restrict cur); + +struct concat_gather_rows_mixed_task { + struct htp_ops_context * octx; + const struct htp_tensor * a; + const struct htp_tensor * b; + dma_addr_t dst; + uint32_t r_start; + uint32_t rows; + uint32_t rows_per_hvx; + uint32_t src0_es; + uint32_t src1_es; + uint32_t dst_es; + const struct htp_gather_rows_params * kparams; + concat_gather_compute_fn_t compute; +}; + +static __attribute__((noinline)) void concat_gather_rows_init_tables_f32( + HVX_Vector * tab, HVX_Vector * inc, + const struct htp_gather_rows_params * kparams, + uint32_t a_reg_nb1, uint32_t b_reg_nb1) { + + const int32_t s_a = (int32_t) (kparams->rg * a_reg_nb1); + const int32_t s_b = (int32_t) (kparams->rg * b_reg_nb1); + uint32_t row = 0; + uint32_t col = 0; + int32_t t_buf[32] __attribute__((aligned(128))); + int32_t s_buf[32] __attribute__((aligned(128))); + for (uint32_t k = 0; k < kparams->vg; k++) { + for (uint32_t lane = 0; lane < 32; lane++) { + if (col < kparams->na) { + t_buf[lane] = (int32_t) (row * a_reg_nb1 + col * 4); + s_buf[lane] = s_a; + } else { + t_buf[lane] = (int32_t) (kparams->v1 + (col - kparams->na) * kparams->span1 + row * b_reg_nb1); + s_buf[lane] = s_b; + } + if (++col == kparams->ne) { + col = 0; + row++; + } + } + tab[k] = *(const HVX_Vector *) t_buf; + inc[k] = *(const HVX_Vector *) s_buf; + } +} + +static __attribute__((noinline)) void concat_gather_rows_init_tables_f16( + HVX_Vector * tab, HVX_Vector * inc, + const struct htp_gather_rows_params * kparams, + uint32_t a_reg_nb1, uint32_t b_reg_nb1) { + + const int16_t s_a = (int16_t) (kparams->rg * a_reg_nb1); + const int16_t s_b = (int16_t) (kparams->rg * b_reg_nb1); + uint32_t row = 0; + uint32_t col = 0; + int16_t t_buf[64] __attribute__((aligned(128))); + int16_t s_buf[64] __attribute__((aligned(128))); + for (uint32_t k = 0; k < kparams->vg; k++) { + for (uint32_t lane = 0; lane < 64; lane++) { + if (col < kparams->na) { + t_buf[lane] = (int16_t) (row * a_reg_nb1 + col * 2); + s_buf[lane] = s_a; + } else { + t_buf[lane] = (int16_t) (kparams->v1 + (col - kparams->na) * kparams->span1 + row * b_reg_nb1); + s_buf[lane] = s_b; + } + if (++col == kparams->ne) { + col = 0; + row++; + } + } + tab[k] = *(const HVX_Vector *) t_buf; + inc[k] = *(const HVX_Vector *) s_buf; + } +} + +static __attribute__((noinline)) void concat_gather_compute_f32_vg1( + uint8_t * restrict out, const uint8_t * restrict region, uint32_t nvec, + const struct htp_gather_rows_params * restrict kparams, + const HVX_Vector * restrict tab, const HVX_Vector * restrict inc, HVX_Vector * restrict cur) { + (void) cur; + const uint32_t region_size = kparams->region_size; + HVX_Vector vcur = tab[0]; + const HVX_Vector vinc = inc[0]; + #pragma unroll(4) + for (uint32_t v = 0; v < nvec; v++) { + Q6_vgather_ARMVw((HVX_Vector *) (out + v * 128), (size_t) region, region_size, vcur); + vcur = Q6_Vw_vadd_VwVw(vcur, vinc); + } +} + +static __attribute__((noinline)) void concat_gather_compute_f32_vgn( + uint8_t * restrict out, const uint8_t * restrict region, uint32_t nvec, + const struct htp_gather_rows_params * restrict kparams, + const HVX_Vector * restrict tab, const HVX_Vector * restrict inc, HVX_Vector * restrict cur) { + const uint32_t vg = kparams->vg; + const uint32_t region_size = kparams->region_size; + for (uint32_t k = 0; k < vg; k++) { + cur[k] = tab[k]; + } + uint32_t k = 0; + #pragma unroll(4) + for (uint32_t v = 0; v < nvec; v++) { + Q6_vgather_ARMVw((HVX_Vector *) (out + v * 128), (size_t) region, region_size, cur[k]); + cur[k] = Q6_Vw_vadd_VwVw(cur[k], inc[k]); + if (++k == vg) { + k = 0; + } + } +} + +static __attribute__((noinline)) void concat_gather_compute_f16_vg1( + uint8_t * restrict out, const uint8_t * restrict region, uint32_t nvec, + const struct htp_gather_rows_params * restrict kparams, + const HVX_Vector * restrict tab, const HVX_Vector * restrict inc, HVX_Vector * restrict cur) { + (void) cur; + const uint32_t region_size = kparams->region_size; + HVX_Vector vcur = tab[0]; + const HVX_Vector vinc = inc[0]; + #pragma unroll(4) + for (uint32_t v = 0; v < nvec; v++) { + Q6_vgather_ARMVh((HVX_Vector *) (out + v * 128), (size_t) region, region_size, vcur); + vcur = Q6_Vh_vadd_VhVh(vcur, vinc); + } +} + +static __attribute__((noinline)) void concat_gather_compute_f16_vgn( + uint8_t * restrict out, const uint8_t * restrict region, uint32_t nvec, + const struct htp_gather_rows_params * restrict kparams, + const HVX_Vector * restrict tab, const HVX_Vector * restrict inc, HVX_Vector * restrict cur) { + const uint32_t vg = kparams->vg; + const uint32_t region_size = kparams->region_size; + for (uint32_t k = 0; k < vg; k++) { + cur[k] = tab[k]; + } + uint32_t k = 0; + #pragma unroll(4) + for (uint32_t v = 0; v < nvec; v++) { + Q6_vgather_ARMVh((HVX_Vector *) (out + v * 128), (size_t) region, region_size, cur[k]); + cur[k] = Q6_Vh_vadd_VhVh(cur[k], inc[k]); + if (++k == vg) { + k = 0; + } + } +} + +static inline void concat_gather_rows_dma_in( + dma_queue * q, + const struct concat_gather_rows_mixed_task * task, + uint8_t * region, uint8_t * raw_a, uint8_t * raw_b, + uint32_t r, uint32_t nr) { + + const struct htp_tensor * a = task->a; + const struct htp_tensor * b = task->b; + const struct htp_gather_rows_params * kparams = task->kparams; + const uint32_t src0_es = task->src0_es; + const uint32_t src1_es = task->src1_es; + const uint32_t dst_es = task->dst_es; + + if (kparams->na > 0) { + uint8_t * dst_a = (src0_es == dst_es) ? region : raw_a; + const size_t a_size = (size_t) (nr - 1) * a->nb[1] + (size_t) kparams->na * src0_es; + dma_queue_push(q, dma_make_data(dst_a, a->data + r * a->nb[1]), a_size, a_size, a_size, 1); + } + + if (b && kparams->nb > 0) { + uint8_t * dst_b = (src1_es == dst_es) ? (region + kparams->v1) : raw_b; + if (kparams->b_dense) { + const size_t b_size = (size_t) (nr - 1) * b->nb[1] + (size_t) kparams->nb * src1_es; + dma_queue_push(q, dma_make_data(dst_b, b->data + r * b->nb[1]), b_size, b_size, b_size, 1); + } else { + const size_t b_size = (size_t) (nr - 1) * b->nb[1] + src1_es; + const size_t dst_span1 = (src1_es == dst_es) + ? kparams->span1 + : (((size_t) kparams->span1 / dst_es) * src1_es); + for (uint32_t k = 0; k < kparams->nb; k++) { + dma_queue_push(q, dma_make_data(dst_b + k * dst_span1, + b->data + (k * b->nb[0] + r * b->nb[1])), + b_size, b_size, b_size, 1); + } + } + } +} + +static inline void concat_gather_rows_dma_out( + dma_queue * q, + const struct concat_gather_rows_mixed_task * task, + uint8_t * out, uint32_t r, uint32_t nr) { + + const struct htp_gather_rows_params * kparams = task->kparams; + const size_t out_size = (size_t) nr * kparams->ne * task->dst_es; + dma_queue_push(q, dma_make_data(task->dst + r * kparams->ne * task->dst_es, out), out_size, out_size, out_size, 1); +} + +static void concat_gather_rows_mixed_worker(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; + const struct concat_gather_rows_mixed_task * task = (const struct concat_gather_rows_mixed_task *) data; + const struct htp_gather_rows_params * kparams = task->kparams; + const struct htp_tensor * a = task->a; + const struct htp_tensor * b = task->b; + + const uint32_t r_offset = MIN(ith * task->rows_per_hvx, task->rows); + const uint32_t r_beg = task->r_start + r_offset; + const uint32_t r_end = task->r_start + MIN(r_offset + task->rows_per_hvx, task->rows); + if (r_beg >= r_end) { + return; + } + + struct htp_thread_trace * tr = th->trace; + + const uint32_t src0_es = task->src0_es; + const uint32_t src1_es = task->src1_es; + const uint32_t dst_es = task->dst_es; + + struct htp_concat_gather_rows_vtcm_layout layout; + htp_concat_gather_rows_vtcm_layout_build(&layout, kparams->vg, kparams->region_size, kparams->nr_max, + kparams->na, a->nb[1], + kparams->nb, b ? b->nb[1] : 0, kparams->b_dense != 0, kparams->span1, + kparams->ne, src0_es, src1_es, dst_es); + + uint8_t * base = VTCM_LAYOUT_PTR(uint8_t, task->octx->ctx->vtcm_base, (size_t) ith * kparams->slice); + HVX_Vector * tab = VTCM_LAYOUT_PTR(HVX_Vector, base, layout.off_tab); + HVX_Vector * inc = VTCM_LAYOUT_PTR(HVX_Vector, base, layout.off_inc); + HVX_Vector * cur = VTCM_LAYOUT_PTR(HVX_Vector, base, layout.off_cur); + + uint8_t * region[2] = { + VTCM_LAYOUT_PTR(uint8_t, base, layout.off_region0), + VTCM_LAYOUT_PTR(uint8_t, base, layout.off_region1), + }; + uint8_t * out[2] = { + VTCM_LAYOUT_PTR(uint8_t, base, layout.off_out0), + VTCM_LAYOUT_PTR(uint8_t, base, layout.off_out1), + }; + uint8_t * raw_a[2] = { + layout.off_raw_a0 ? VTCM_LAYOUT_PTR(uint8_t, base, layout.off_raw_a0) : NULL, + layout.off_raw_a1 ? VTCM_LAYOUT_PTR(uint8_t, base, layout.off_raw_a1) : NULL, + }; + uint8_t * raw_b[2] = { + layout.off_raw_b0 ? VTCM_LAYOUT_PTR(uint8_t, base, layout.off_raw_b0) : NULL, + layout.off_raw_b1 ? VTCM_LAYOUT_PTR(uint8_t, base, layout.off_raw_b1) : NULL, + }; + + const uint32_t a_elem_stride = a->nb[1] / src0_es; + const uint32_t b_elem_stride = b ? (b->nb[1] / src1_es) : 0; + const uint32_t a_reg_nb1 = a_elem_stride * dst_es; + const uint32_t b_reg_nb1 = b_elem_stride * dst_es; + + htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, (uint16_t) r_beg); + if (dst_es == 4) { + concat_gather_rows_init_tables_f32(tab, inc, kparams, a_reg_nb1, b_reg_nb1); + } else { + concat_gather_rows_init_tables_f16(tab, inc, kparams, a_reg_nb1, b_reg_nb1); + } + htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, (uint16_t) r_beg); + + dma_queue * q = th->dma_q; + const uint32_t n_in = (kparams->na > 0 ? 1 : 0) + ((b && kparams->nb > 0) ? (kparams->b_dense ? 1 : kparams->nb) : 0); + const uint32_t nr_max = kparams->nr_max; + const uint32_t nr0 = MIN(nr_max, r_end - r_beg); + + dma_queue_push(q, dma_make_data(task->dst, out[0]), 0, 0, 0, 0); // dummy out + concat_gather_rows_dma_in(q, task, region[0], raw_a[0], raw_b[0], r_beg, nr0); + + const uint32_t r1 = r_beg + nr_max; + if (r1 < r_end) { + const uint32_t nr1 = MIN(nr_max, r_end - r1); + dma_queue_push(q, dma_make_data(task->dst, out[1]), 0, 0, 0, 0); // dummy out + concat_gather_rows_dma_in(q, task, region[1], raw_a[1], raw_b[1], r1, nr1); + } + + uint32_t buf = 0; + for (uint32_t r = r_beg; r < r_end; r += nr_max) { + const uint32_t nr = MIN(nr_max, r_end - r); + const uint32_t next_buf = buf ^ 1; + + dma_queue_pop(q); // complete out + for (uint32_t i = 0; i < n_in; i++) { + dma_queue_pop(q); + } + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r); + if (src0_es != dst_es && kparams->na > 0) { + const uint32_t a_elems = (nr - 1) * a_elem_stride + kparams->na; + if (dst_es == 4) { + concat_cvt_f16_to_f32_aa(region[buf], raw_a[buf], a_elems); + } else { + concat_cvt_f32_to_f16_aa(region[buf], raw_a[buf], a_elems); + } + } + if (src1_es != dst_es && b && kparams->nb > 0) { + const uint32_t b_elems = kparams->b_dense + ? ((nr - 1) * b_elem_stride + kparams->nb) + : (kparams->nb * (kparams->span1 / dst_es)); + if (dst_es == 4) { + concat_cvt_f16_to_f32_aa(region[buf] + kparams->v1, raw_b[buf], b_elems); + } else { + concat_cvt_f32_to_f16_aa(region[buf] + kparams->v1, raw_b[buf], b_elems); + } + } + + const uint32_t nvec = (dst_es == 4) + ? ((nr * kparams->ne + 31) >> 5) + : ((nr * kparams->ne + 63) >> 6); + task->compute(out[buf], region[buf], nvec, kparams, tab, inc, cur); + hvx_gather_sync(out[buf]); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r); + + concat_gather_rows_dma_out(q, task, out[buf], r, nr); + + const uint32_t r_prefetch = r + 2 * nr_max; + if (r_prefetch < r_end) { + const uint32_t nr_prefetch = MIN(nr_max, r_end - r_prefetch); + concat_gather_rows_dma_in(q, task, region[buf], raw_a[buf], raw_b[buf], r_prefetch, nr_prefetch); + } + + buf = next_buf; + } + dma_queue_flush(q); +} + +static int concat_gather_rows( + struct htp_ops_context * octx, + const struct htp_tensor * src0, + const struct htp_tensor * src1, + const struct htp_gather_rows_params * kparams, + uint32_t n_hvx) { + + const struct htp_tensor * dst = octx->dst; + if (src0->type == dst->type && src1->type == dst->type) { + return htp_gather_rows(octx, src0, src1, kparams, n_hvx); + } + + if (!htp_ops_context_set_n_hvx(octx, n_hvx)) { + return HTP_STATUS_INVAL_PARAMS; + } + + if (kparams->slice * octx->n_hvx > octx->ctx->vtcm_size) { + return HTP_STATUS_VTCM_TOO_SMALL; + } + + const uint32_t total_rows = kparams->total_rows; + uint32_t r_start = 0; + uint32_t r_count = total_rows; + if (octx->ctx->mdev.count > 1) { + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( + total_rows, kparams->rg, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + r_start = range.start; + r_count = range.count; + } + + if (r_count == 0) { + return HTP_STATUS_OK; + } + + const uint32_t dst_es = concat_type_size(dst->type); + + struct concat_gather_rows_mixed_task task; + task.octx = octx; + task.a = src0; + task.b = src1; + task.dst = dst->data; + task.r_start = r_start; + task.rows = r_count; + task.rows_per_hvx = kparams->rows_per_hvx; + task.src0_es = concat_type_size(src0->type); + task.src1_es = concat_type_size(src1->type); + task.dst_es = dst_es; + task.kparams = kparams; + + if (dst_es == 2) { + task.compute = (kparams->vg == 1) ? concat_gather_compute_f16_vg1 : concat_gather_compute_f16_vgn; + } else { + task.compute = (kparams->vg == 1) ? concat_gather_compute_f32_vg1 : concat_gather_compute_f32_vgn; + } + + work_queue_run(octx->ctx->hvx_queue, concat_gather_rows_mixed_worker, &task, octx->n_hvx); return HTP_STATUS_OK; } @@ -362,22 +1174,20 @@ int op_concat(struct htp_ops_context * octx) { const struct htp_concat_kernel_params * kparams = (const struct htp_concat_kernel_params *) octx->kernel_params; const struct htp_tensor * src0 = octx->src[0]; const struct htp_tensor * src1 = octx->src[1]; - const struct htp_tensor * dst = octx->dst; int status = HTP_STATUS_OK; - const uint32_t type_size = (dst->type == HTP_TYPE_F32 || dst->type == HTP_TYPE_I32) ? 4 : 2; switch (kparams->kernel_type) { case HTP_CONCAT_KERNEL_REGULAR: - status = concat_regular(octx, kparams->dim, type_size); + status = concat_regular(octx, kparams); break; case HTP_CONCAT_KERNEL_TRANSPOSED: - status = concat_transposed(octx, kparams, type_size); + status = concat_transposed(octx, kparams); break; case HTP_CONCAT_KERNEL_GATHER_ROWS: - status = htp_gather_rows(octx, src0, src1, &kparams->u.gather, kparams->n_hvx); + status = concat_gather_rows(octx, src0, src1, &kparams->u.gather, kparams->n_hvx); break; default: diff --git a/ggml/src/ggml-hexagon/htp/concat-ops.h b/ggml/src/ggml-hexagon/htp/concat-ops.h index 580fe0e15c6b..228cd81bb1bf 100644 --- a/ggml/src/ggml-hexagon/htp/concat-ops.h +++ b/ggml/src/ggml-hexagon/htp/concat-ops.h @@ -14,6 +14,15 @@ enum htp_concat_kernel_type { HTP_CONCAT_KERNEL_GATHER_ROWS = 3, }; +#define HTP_CONCAT_REG_BLK_BYTES (32 * 1024) + +struct htp_concat_regular_params { + struct fastdiv_values div_ne01; + struct fastdiv_values div_ne02_ne01; + struct fastdiv_values div_ne11; + struct fastdiv_values div_ne12_ne11; +}; + struct htp_concat_transposed_params { struct fastdiv_values div_ne2; }; @@ -27,6 +36,7 @@ struct htp_concat_kernel_params { uint32_t vtcm_size; union { + struct htp_concat_regular_params regular; struct htp_concat_transposed_params transposed; struct htp_gather_rows_params gather; } u; @@ -38,11 +48,198 @@ static_assert(sizeof(struct htp_concat_kernel_params) <= 128, "htp_concat_kernel _Static_assert(sizeof(struct htp_concat_kernel_params) <= 128, "htp_concat_kernel_params is too large for kernel_params blob"); #endif +struct htp_concat_gather_rows_vtcm_layout { + size_t off_tab; + size_t off_inc; + size_t off_cur; + size_t off_region0; + size_t off_out0; + size_t off_region1; + size_t off_out1; + size_t off_raw_a0; + size_t off_raw_a1; + size_t off_raw_b0; + size_t off_raw_b1; + size_t total_per_hvx; +}; + +static inline void htp_concat_gather_rows_vtcm_layout_build( + struct htp_concat_gather_rows_vtcm_layout * L, + uint32_t vg, + uint32_t region_size, + uint32_t nr_max, + uint32_t na, uint32_t a_nb1, + uint32_t nb, uint32_t b_nb1, bool b_dense, uint32_t span1, + uint32_t ne, + uint32_t src0_es, uint32_t src1_es, uint32_t dst_es) { + + const size_t vec_bytes = (size_t) vg * 128; + const size_t region_aligned = hex_round_up(region_size, 128); + const size_t out_aligned = hex_round_up(region_aligned + (size_t) nr_max * ne * dst_es, 128) - region_aligned; + + size_t raw_a_aligned = 0; + if (src0_es != dst_es && na > 0) { + raw_a_aligned = hex_round_up((size_t) (nr_max - 1) * a_nb1 + (size_t) na * src0_es, 128); + } + + size_t raw_b_aligned = 0; + if (src1_es != dst_es && nb > 0) { + const size_t raw_span1 = ((size_t) span1 / dst_es) * src1_es; + const size_t raw_b_bytes = b_dense + ? ((size_t) (nr_max - 1) * b_nb1 + (size_t) nb * src1_es) + : ((size_t) nb * raw_span1); + raw_b_aligned = hex_round_up(raw_b_bytes, 128); + } + + size_t off = 0; + VTCM_LAYOUT_ALLOC(off, off_tab, vec_bytes); + VTCM_LAYOUT_ALLOC(off, off_inc, vec_bytes); + VTCM_LAYOUT_ALLOC(off, off_cur, vec_bytes); + VTCM_LAYOUT_ALLOC(off, off_region0, region_aligned); + VTCM_LAYOUT_ALLOC(off, off_out0, out_aligned); + VTCM_LAYOUT_ALLOC(off, off_region1, region_aligned); + VTCM_LAYOUT_ALLOC(off, off_out1, out_aligned); + if (raw_a_aligned > 0) { + VTCM_LAYOUT_ALLOC(off, off_raw_a0, raw_a_aligned); + VTCM_LAYOUT_ALLOC(off, off_raw_a1, raw_a_aligned); + } else { + L->off_raw_a0 = 0; + L->off_raw_a1 = 0; + } + if (raw_b_aligned > 0) { + VTCM_LAYOUT_ALLOC(off, off_raw_b0, raw_b_aligned); + VTCM_LAYOUT_ALLOC(off, off_raw_b1, raw_b_aligned); + } else { + L->off_raw_b0 = 0; + L->off_raw_b1 = 0; + } + L->total_per_hvx = off; +} + +static inline bool htp_concat_gather_rows_solve_layout( + struct htp_gather_rows_params * kparams, + uint32_t na, uint32_t a_nb1, + uint32_t nb, uint32_t b_nb1, bool b_dense, + uint32_t src0_es, uint32_t src1_es, uint32_t dst_es, + uint32_t total_rows, + uint32_t n_hvx, + uint32_t mdev_count, + uint32_t vtcm_size) { + + if (src0_es == dst_es && src1_es == dst_es) { + return htp_gather_rows_solve_layout(kparams, na, a_nb1, nb, b_nb1, b_dense, dst_es, dst_es, total_rows, n_hvx, mdev_count, vtcm_size); + } + + const uint32_t max_ne0 = 128 / dst_es; + const uint32_t ne = na + nb; + if (ne == 0 || ne > max_ne0) { + return false; + } + + if ((dst_es != 4 && dst_es != 2) || (src0_es != 4 && src0_es != 2) || (src1_es != 4 && src1_es != 2)) { + return false; + } + if ((a_nb1 % src0_es) != 0 || (b_nb1 % src1_es) != 0) { + return false; + } + + const uint32_t a_reg_nb1 = (a_nb1 / src0_es) * dst_es; + const uint32_t b_reg_nb1 = (b_nb1 / src1_es) * dst_es; + + const uint32_t v_lanes = 128 / dst_es; + const uint32_t g = hex_gcd_u32(ne, v_lanes); + const uint32_t rg = v_lanes / g; + const uint32_t vg = ne / g; + + const uint32_t slice = (vtcm_size / n_hvx) & ~127u; + const uint32_t total_chunks = total_rows / rg; + const uint32_t chunks_per_dev = (total_chunks + mdev_count - 1) / mdev_count; + const uint32_t max_rows_per_dev = (mdev_count > 1 && total_chunks >= mdev_count) + ? (chunks_per_dev * rg + (total_rows % rg)) + : total_rows; + const uint32_t rows_per_hvx = hex_round_up((max_rows_per_dev + n_hvx - 1) / n_hvx, rg); + + const uint32_t fixed = 3 * vg * 128; + const uint32_t per_row_reg_a = na > 0 ? a_reg_nb1 : 0; + const uint32_t per_row_reg_b = nb > 0 ? (b_dense ? b_reg_nb1 : nb * b_reg_nb1) : 0; + const uint32_t per_row_raw_a = (src0_es != dst_es && na > 0) ? a_nb1 : 0; + const uint32_t per_row_raw_b = (src1_es != dst_es && nb > 0) ? (b_dense ? b_nb1 : nb * b_nb1) : 0; + const uint32_t per_row = per_row_reg_a + per_row_reg_b + per_row_raw_a + per_row_raw_b + ne * dst_es; + if (slice <= fixed + 2 * per_row * rg) { + return false; + } + + const uint32_t avail_per_buf = (slice - fixed) / 2; + uint32_t nr_max = MIN(avail_per_buf / per_row, rows_per_hvx); + if (dst_es == 2) { + const uint32_t per_row_region = per_row_reg_a + per_row_reg_b; + if (per_row_region > 0) { + nr_max = MIN(nr_max, (32768u - 256u) / per_row_region); + } + } + nr_max = (nr_max / rg) * rg; + + uint32_t v1 = 0; + uint32_t span1 = 0; + uint32_t region_size = 0; + + while (nr_max > 0) { + v1 = na > 0 ? hex_round_up((nr_max - 1) * a_reg_nb1 + na * dst_es, 128) : 0; + if (nb > 0) { + if (b_dense) { + span1 = dst_es; + region_size = v1 + (nr_max - 1) * b_reg_nb1 + nb * dst_es; + } else { + span1 = (nr_max - 1) * b_reg_nb1 + dst_es; + region_size = v1 + nb * span1; + } + } else { + span1 = 0; + region_size = v1; + } + + struct htp_concat_gather_rows_vtcm_layout layout; + htp_concat_gather_rows_vtcm_layout_build(&layout, vg, region_size, nr_max, + na, a_nb1, nb, b_nb1, b_dense, span1, ne, + src0_es, src1_es, dst_es); + + if ((dst_es != 2 || region_size <= 32768) && layout.total_per_hvx <= slice) { + break; + } + + nr_max -= rg; + } + + if (nr_max == 0) { + return false; + } + + kparams->na = na; + kparams->nb = nb; + kparams->ne = ne; + kparams->rg = rg; + kparams->vg = vg; + kparams->nr_max = nr_max; + kparams->v1 = v1; + kparams->span1 = span1; + kparams->region_size = region_size; + kparams->slice = slice; + kparams->total_rows = total_rows; + kparams->rows_per_hvx = rows_per_hvx; + kparams->b_dense = b_dense ? 1 : 0; + kparams->pad[0] = 0; + kparams->pad[1] = 0; + kparams->pad[2] = 0; + return true; +} + struct htp_concat_transposed_vtcm_layout { uint32_t src0_spad_size_per_hvx; uint32_t src1_spad_size_per_hvx; + uint32_t cvt_spad_size_per_hvx; size_t off_spad0; size_t off_spad1; + size_t off_spad2; uint32_t total_bytes; }; @@ -50,24 +247,39 @@ static inline void htp_concat_transposed_vtcm_layout_build( struct htp_concat_transposed_vtcm_layout * L, uint32_t src0_ne0, uint32_t src1_ne0, - uint32_t type_size, + uint32_t src0_es, + uint32_t src1_es, + uint32_t dst_es, uint32_t n_hvx) { // src1_ne0 is processed in chunks of block_cols tokens, so VTCM does not grow with the batch uint32_t block_rows = 128; - uint32_t block_cols = (type_size == 4) ? 256 : 512; + uint32_t block_cols = (src1_es == 2 && dst_es == 2) ? 512 : 256; + uint32_t col_align = (src1_es == 2 || dst_es == 2) ? 64 : 32; // +1 element spreads the gather lanes across VTCM, so they do not serialize on one path - uint32_t spad1_stride = block_rows * type_size + type_size; - uint32_t block_cols_padded = MIN(hex_round_up(src1_ne0, (type_size == 4) ? 32 : 64), block_cols); - uint32_t spad0_row_bytes = hex_round_up(src0_ne0 * type_size, 128) + block_cols_padded * type_size; + uint32_t spad1_stride = block_rows * src1_es + src1_es; + uint32_t block_cols_padded = MIN(hex_round_up(src1_ne0, col_align), block_cols); + + uint32_t dst_src0_row_padded = hex_round_up(src0_ne0 * dst_es, 128); + uint32_t raw_src0_row_padded = (src0_es != dst_es) ? hex_round_up(src0_ne0 * src0_es, 128) : 0; + uint32_t spad0_row_bytes = MAX(dst_src0_row_padded + block_cols_padded * dst_es, raw_src0_row_padded); + + uint32_t cvt1_bytes = (src1_es != dst_es) ? (block_rows * 64 * src1_es) : 0; + uint32_t cvt0_bytes = (src0_es != dst_es) ? dst_src0_row_padded : 0; // double-buffered: two slots per thread L->src0_spad_size_per_hvx = 2 * block_rows * spad0_row_bytes; L->src1_spad_size_per_hvx = 2 * block_cols_padded * spad1_stride; + L->cvt_spad_size_per_hvx = hex_round_up(MAX(cvt1_bytes, cvt0_bytes), 128); size_t off = 0; VTCM_LAYOUT_ALLOC(off, off_spad0, (size_t) n_hvx * L->src0_spad_size_per_hvx); VTCM_LAYOUT_ALLOC(off, off_spad1, (size_t) n_hvx * L->src1_spad_size_per_hvx); + if (L->cvt_spad_size_per_hvx > 0) { + VTCM_LAYOUT_ALLOC(off, off_spad2, (size_t) n_hvx * L->cvt_spad_size_per_hvx); + } else { + L->off_spad2 = 0; + } L->total_bytes = (uint32_t) off; } diff --git a/ggml/src/ggml-hexagon/htp/conv2d-ops.c b/ggml/src/ggml-hexagon/htp/conv2d-ops.c index 67e8ec67b70f..1bcab08fdf09 100644 --- a/ggml/src/ggml-hexagon/htp/conv2d-ops.c +++ b/ggml/src/ggml-hexagon/htp/conv2d-ops.c @@ -1,6 +1,3 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" - #include #include #include @@ -1406,9 +1403,8 @@ static void conv2d_hmx_win_wrows_dma(const struct htp_conv2d_win_context * wc, d } // K-contiguous kernel (k = cin * T + t): transpose the 32 cout rows of a packing unit to k rows of 32 cout, then into tiles -__attribute__((noinline)) -static void conv2d_hmx_win_wrows_pack(const struct htp_conv2d_win_context * wc, const uint8_t * raw, uint8_t * xr, HVX_Vector * vin, - HVX_Vector * scratch, uint32_t unit, uint32_t n_cs) { +static inline void conv2d_hmx_win_wrows_pack_impl(const struct htp_conv2d_win_context * wc, const uint8_t * raw, uint8_t * xr, HVX_Vector * vin, + HVX_Vector * scratch, uint32_t unit, uint32_t n_cs, const bool is_f16) { const struct htp_conv2d_kernel_params * kp = wc->kp; const struct htp_tensor * kernel = wc->octx->src[0]; @@ -1419,7 +1415,6 @@ static void conv2d_hmx_win_wrows_pack(const struct htp_conv2d_win_context * wc, const uint32_t T = KW * KH; const uint32_t n_cc = kp->window.n_cc; const uint32_t CS = kp->window.w_cs; - const bool is_f16 = kernel->type == HTP_TYPE_F16; const uint32_t kpw = is_f16 ? 64 : 32; // k per vector const uint32_t rstep = is_f16 ? 64 : 128; // bytes per transposed k row @@ -1491,6 +1486,27 @@ static void conv2d_hmx_win_wrows_pack(const struct htp_conv2d_win_context * wc, } } +__attribute__((noinline)) +static void conv2d_hmx_win_wrows_pack_f16(const struct htp_conv2d_win_context * wc, const uint8_t * raw, uint8_t * xr, HVX_Vector * vin, + HVX_Vector * scratch, uint32_t unit, uint32_t n_cs) { + conv2d_hmx_win_wrows_pack_impl(wc, raw, xr, vin, scratch, unit, n_cs, true); +} + +__attribute__((noinline)) +static void conv2d_hmx_win_wrows_pack_f32(const struct htp_conv2d_win_context * wc, const uint8_t * raw, uint8_t * xr, HVX_Vector * vin, + HVX_Vector * scratch, uint32_t unit, uint32_t n_cs) { + conv2d_hmx_win_wrows_pack_impl(wc, raw, xr, vin, scratch, unit, n_cs, false); +} + +static inline void conv2d_hmx_win_wrows_pack(const struct htp_conv2d_win_context * wc, const uint8_t * raw, uint8_t * xr, HVX_Vector * vin, + HVX_Vector * scratch, uint32_t unit, uint32_t n_cs) { + if (wc->octx->src[0]->type == HTP_TYPE_F16) { + conv2d_hmx_win_wrows_pack_f16(wc, raw, xr, vin, scratch, unit, n_cs); + } else { + conv2d_hmx_win_wrows_pack_f32(wc, raw, xr, vin, scratch, unit, n_cs); + } +} + static void conv2d_hmx_win_wpack_rows(const struct htp_conv2d_win_context * wc, const htp_thread_t * th, unsigned int nth, unsigned int ith) { struct htp_ops_context * octx = wc->octx; const struct htp_conv2d_kernel_params * kp = wc->kp; @@ -1807,7 +1823,6 @@ static void conv2d_hmx_win_croutons_fold(const struct htp_conv2d_win_context * w const uint32_t Cin = input->ne[2]; const uint32_t N = input->ne[3]; const uint32_t KW = octx->src[0]->ne[0]; - const uint32_t nch = KW * Cin; const uint32_t SR = kp->window.sr; const uint32_t IHS = kp->window.ihs; const int32_t p0 = octx->op_params[2]; @@ -1984,7 +1999,6 @@ static void conv2d_hmx_win_croutons_fold_cwhn(const struct htp_conv2d_win_contex } static void conv2d_hmx_win_pack(const struct htp_conv2d_win_context * wc, const htp_thread_t * th, unsigned int nth, unsigned int ith) { - struct htp_ops_context * octx = wc->octx; const struct htp_conv2d_kernel_params * kp = wc->kp; uint32_t ts; diff --git a/ggml/src/ggml-hexagon/htp/cpy-ops.c b/ggml/src/ggml-hexagon/htp/cpy-ops.c index cdf4d8ec62eb..8f37fc70348e 100644 --- a/ggml/src/ggml-hexagon/htp/cpy-ops.c +++ b/ggml/src/ggml-hexagon/htp/cpy-ops.c @@ -1,7 +1,3 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include #include @@ -13,6 +9,7 @@ #include "ggml-common.h" #include "cpy-ops.h" #include "dma-copy.h" +#include "dma-pipeline.h" #include "htp-ctx.h" #include "htp-fence.h" #include "htp-ops.h" @@ -20,9 +17,19 @@ #include "hvx-utils.h" #include "gather-rows.h" +typedef void (*cpy_convert_block_fn_t)( + uint8_t * restrict dst_spad, + const uint8_t * restrict src_spad, + uint32_t nr, + uint32_t ne00, + uint32_t dst_row_stride, + uint32_t src0_row_stride +); + struct htp_copy_context { struct htp_ops_context * octx; const struct htp_copy_kernel_params * kparams; + cpy_convert_block_fn_t convert_block; uint32_t row_start; uint32_t nrows; @@ -41,29 +48,29 @@ struct htp_copy_context { uint32_t tiles_per_hvx; }; -#define cpy_preamble \ - const struct htp_tensor *src0 = octx->src[0]; \ - const struct htp_tensor *dst = octx->dst; \ - \ - const uint32_t ne00 = src0->ne[0]; \ - const uint32_t ne01 = src0->ne[1]; \ - const uint32_t ne02 = src0->ne[2]; \ - const uint32_t ne03 = src0->ne[3]; \ - \ - const uint32_t nb00 = src0->nb[0]; \ - const uint32_t nb01 = src0->nb[1]; \ - const uint32_t nb02 = src0->nb[2]; \ - const uint32_t nb03 = src0->nb[3]; \ - \ - const uint32_t ne0 = dst->ne[0]; \ - const uint32_t ne1 = dst->ne[1]; \ - const uint32_t ne2 = dst->ne[2]; \ - const uint32_t ne3 = dst->ne[3]; \ - \ - const uint32_t nb0 = dst->nb[0]; \ - const uint32_t nb1 = dst->nb[1]; \ - const uint32_t nb2 = dst->nb[2]; \ - const uint32_t nb3 = dst->nb[3]; +#define cpy_preamble \ + const struct htp_tensor *src0 = octx->src[0]; \ + const struct htp_tensor *dst = octx->dst; \ + \ + const uint32_t __attribute__((unused)) ne00 = src0->ne[0]; \ + const uint32_t __attribute__((unused)) ne01 = src0->ne[1]; \ + const uint32_t __attribute__((unused)) ne02 = src0->ne[2]; \ + const uint32_t __attribute__((unused)) ne03 = src0->ne[3]; \ + \ + const uint32_t __attribute__((unused)) nb00 = src0->nb[0]; \ + const uint32_t __attribute__((unused)) nb01 = src0->nb[1]; \ + const uint32_t __attribute__((unused)) nb02 = src0->nb[2]; \ + const uint32_t __attribute__((unused)) nb03 = src0->nb[3]; \ + \ + const uint32_t __attribute__((unused)) ne0 = dst->ne[0]; \ + const uint32_t __attribute__((unused)) ne1 = dst->ne[1]; \ + const uint32_t __attribute__((unused)) ne2 = dst->ne[2]; \ + const uint32_t __attribute__((unused)) ne3 = dst->ne[3]; \ + \ + const uint32_t __attribute__((unused)) nb0 = dst->nb[0]; \ + const uint32_t __attribute__((unused)) nb1 = dst->nb[1]; \ + const uint32_t __attribute__((unused)) nb2 = dst->nb[2]; \ + const uint32_t __attribute__((unused)) nb3 = dst->nb[3]; #define DEFINE_CPY_RESHAPE(NAME, ELEM_TYPE, ELEM_SIZE) \ static void cpy_thread_##NAME##_reshape(const htp_thread_t * th, unsigned int nth, unsigned int ith, \ @@ -332,85 +339,120 @@ static void cpy_thread_transpose(const htp_thread_t * th, unsigned int nth, unsi dma_queue_flush(dma_q); } -#define DEFINE_CPY_CONVERT_SAMESHAPE(NAME, CONV_FUNC) \ -static void cpy_thread_##NAME##_sameshape(const htp_thread_t * th, unsigned int nth, \ - unsigned int ith, void * data) { \ - struct htp_copy_context * ct = (struct htp_copy_context *) data; \ - struct htp_ops_context * octx = ct->octx; \ - cpy_preamble; \ - \ - const uint32_t dr = ct->src0_nrows_per_hvx; \ - const uint32_t ir0 = ct->row_start + dr * ith; \ - const uint32_t ir1 = MIN(ir0 + dr, ct->row_start + ct->nrows); \ - if (ir0 >= ir1) return; \ - \ - dma_queue * dma_q = th->dma_q; \ - struct htp_thread_trace * tr = th->trace; \ - \ - const struct htp_copy_convert_params * cvt = &ct->kparams->u.convert; \ - const struct htp_copy_convert_vtcm_layout * L = &ct->layout; \ - const uint32_t src0_buf_size = L->src0_buf_size; \ - const uint32_t dst_buf_size = L->dst_buf_size; \ - const uint32_t src0_row_stride = L->src0_row_stride; \ - const uint32_t dst_row_stride = L->dst_row_stride; \ - const uint32_t blk_rows = L->blk_rows; \ - uint8_t * vtcm_src0_base = ct->vtcm_src0 + ith * L->spad0_size_per_hvx; \ - uint8_t * vtcm_dst_base = ct->vtcm_dst + ith * L->spad1_size_per_hvx; \ - const uint32_t src0_row_size = ne00 * ct->kparams->src0_type_size; \ - const uint32_t dst_row_size = ne00 * ct->kparams->dst_type_size; \ - \ - const uint32_t ne02_ne01 = ne02 * ne01; \ - uint32_t i03 = fastdiv(ir0, &cvt->div_ne02_ne01); \ - uint32_t rem = ir0 - i03 * ne02_ne01; \ - uint32_t i02 = fastdiv(rem, &cvt->div_ne01); \ - uint32_t i01 = rem - i02 * ne01; \ - \ - struct cpy_row_cursor f = { ir0, i01, i02, i03 }; \ - struct cpy_row_cursor c = f; \ - \ - for (uint32_t b = 0; b < 2 && f.r < ir1; ++b) { \ - uint8_t * src_spad = vtcm_src0_base + b * src0_buf_size; \ - uint8_t * dst_spad = vtcm_dst_base + b * dst_buf_size; \ - const uint32_t nr = MIN(blk_rows, MIN(ne01 - f.i01, ir1 - f.r)); \ - dma_addr_t f_src0_addr = src0->data + f.i01*nb01 + f.i02*nb02 + f.i03*nb03; \ - dma_queue_push(dma_q, dma_make_data(dst->data, dst_spad), \ - dst_row_size, dst_buf_size, dst_row_size, 0); \ - dma_queue_push(dma_q, dma_make_data(src_spad, f_src0_addr), \ - src0_row_stride, nb01, src0_row_size, nr); \ - cpy_cursor_advance(&f, nr, ne01, ne02); \ - } \ - \ - for (uint32_t blk = 0; c.r < ir1; ++blk) { \ - const uint32_t nr = MIN(blk_rows, MIN(ne01 - c.i01, ir1 - c.r)); \ - uint8_t * dst_spad = (uint8_t *) (uintptr_t) dma_queue_pop(dma_q).src; \ - uint8_t * src_spad = (uint8_t *) (uintptr_t) dma_queue_pop(dma_q).dst; \ - \ - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) blk); \ - for (uint32_t r = 0; r < nr; ++r) { \ - CONV_FUNC(dst_spad + r * dst_row_stride, src_spad + r * src0_row_stride, ne00); \ - } \ - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) blk); \ - \ - dma_addr_t c_dst_addr = dst->data + c.i01*nb1 + c.i02*nb2 + c.i03*nb3; \ - dma_queue_push(dma_q, dma_make_data(c_dst_addr, dst_spad), \ - nb1, dst_row_stride, dst_row_size, nr); \ - cpy_cursor_advance(&c, nr, ne01, ne02); \ - \ - if (f.r < ir1) { \ - const uint32_t fnr = MIN(blk_rows, MIN(ne01 - f.i01, ir1 - f.r)); \ - dma_addr_t f_src0_addr = src0->data + f.i01*nb01 + f.i02*nb02 + f.i03*nb03; \ - dma_queue_push(dma_q, dma_make_data(src_spad, f_src0_addr), \ - src0_row_stride, nb01, src0_row_size, fnr); \ - cpy_cursor_advance(&f, fnr, ne01, ne02); \ - } \ - } \ - dma_queue_flush(dma_q); \ +#define DEFINE_CPY_CONVERT_BLOCK(NAME, CONV_FUNC) \ +static void __attribute__((noinline)) cpy_convert_block_##NAME( \ + uint8_t * restrict dst_spad, \ + const uint8_t * restrict src_spad, \ + uint32_t nr, \ + uint32_t ne00, \ + uint32_t dst_row_stride, \ + uint32_t src0_row_stride \ +) { \ + for (uint32_t r = 0; r < nr; ++r) { \ + CONV_FUNC(dst_spad + r * dst_row_stride, src_spad + r * src0_row_stride, ne00); \ + } \ } -DEFINE_CPY_CONVERT_SAMESHAPE(f16_f32, hvx_copy_f16_f32_aa) -DEFINE_CPY_CONVERT_SAMESHAPE(f32_f16, hvx_copy_f32_f16_aa) -DEFINE_CPY_CONVERT_SAMESHAPE(i32_f32, hvx_copy_i32_f32_aa) -DEFINE_CPY_CONVERT_SAMESHAPE(f32_i32, hvx_copy_f32_i32_aa) +DEFINE_CPY_CONVERT_BLOCK(f16_f32, hvx_copy_f16_f32_aa) +DEFINE_CPY_CONVERT_BLOCK(f32_f16, hvx_copy_f32_f16_aa) +DEFINE_CPY_CONVERT_BLOCK(i32_f32, hvx_copy_i32_f32_aa) +DEFINE_CPY_CONVERT_BLOCK(f32_i32, hvx_copy_f32_i32_aa) + +struct cpy_convert_pipe_state { + dma_addr_t src0_data; + dma_addr_t dst_data; + cpy_convert_block_fn_t convert_block; + uint32_t ne00, ne01, ne02; + uint32_t nb01, nb02, nb03; + uint32_t nb1, nb2, nb3; + uint32_t src0_row_size; + uint32_t dst_row_size; + uint32_t src0_row_stride; + uint32_t dst_row_stride; + uint32_t blk_rows; + uint32_t ir1; + struct cpy_row_cursor cur; +}; + +static bool cpy_convert_next_task(void * ctx, struct dma_pipe_task * task) { + struct cpy_convert_pipe_state * s = (struct cpy_convert_pipe_state *) ctx; + if (s->cur.r >= s->ir1) { + return false; + } + const uint32_t nr = MIN(s->blk_rows, MIN(s->ne01 - s->cur.i01, s->ir1 - s->cur.r)); + task->row = s->cur.i01; + task->off = s->cur.i02; + task->len = nr; + task->aux = s->cur.i03; + cpy_cursor_advance(&s->cur, nr, s->ne01, s->ne02); + return true; +} + +static void cpy_convert_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct cpy_convert_pipe_state * s = (struct cpy_convert_pipe_state *) ctx; + const dma_addr_t src0_addr = s->src0_data + (size_t) task->row * s->nb01 + (size_t) task->off * s->nb02 + (size_t) task->aux * s->nb03; + dma_queue_push(dma_q, dma_make_data(in_spad, src0_addr), + s->src0_row_stride, s->nb01, s->src0_row_size, task->len); +} + +static void cpy_convert_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct cpy_convert_pipe_state * s = (struct cpy_convert_pipe_state *) ctx; + s->convert_block((uint8_t *) out_spad, (const uint8_t *) in_spad, task->len, s->ne00, s->dst_row_stride, s->src0_row_stride); +} + +static void cpy_convert_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) { + struct cpy_convert_pipe_state * s = (struct cpy_convert_pipe_state *) ctx; + const dma_addr_t dst_addr = s->dst_data + (size_t) task->row * s->nb1 + (size_t) task->off * s->nb2 + (size_t) task->aux * s->nb3; + dma_queue_push(dma_q, dma_make_data(dst_addr, out_spad), + s->nb1, s->dst_row_stride, s->dst_row_size, task->len); +} + +static void cpy_thread_convert_sameshape(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; + struct htp_copy_context * ct = (struct htp_copy_context *) data; + struct htp_ops_context * octx = ct->octx; + cpy_preamble; + + const uint32_t dr = ct->src0_nrows_per_hvx; + const uint32_t ir0 = ct->row_start + dr * ith; + const uint32_t ir1 = MIN(ir0 + dr, ct->row_start + ct->nrows); + if (ir0 >= ir1) { + return; + } + + const struct htp_copy_convert_params * cvt = &ct->kparams->u.convert; + const struct htp_copy_convert_vtcm_layout * L = &ct->layout; + + uint8_t * vtcm_src0_base = ct->vtcm_src0 + ith * L->spad0_size_per_hvx; + uint8_t * vtcm_dst_base = ct->vtcm_dst + ith * L->spad1_size_per_hvx; + void * in_buf[2] = { vtcm_src0_base, vtcm_src0_base + L->src0_buf_size }; + void * out_buf[2] = { vtcm_dst_base, vtcm_dst_base + L->dst_buf_size }; + + const uint32_t ne02_ne01 = ne02 * ne01; + uint32_t i03 = fastdiv(ir0, &cvt->div_ne02_ne01); + uint32_t rem = ir0 - i03 * ne02_ne01; + uint32_t i02 = fastdiv(rem, &cvt->div_ne01); + uint32_t i01 = rem - i02 * ne01; + + struct cpy_convert_pipe_state s = { + .src0_data = src0->data, + .dst_data = dst->data, + .convert_block = ct->convert_block, + .ne00 = ne00, .ne01 = ne01, .ne02 = ne02, + .nb01 = nb01, .nb02 = nb02, .nb03 = nb03, + .nb1 = nb1, .nb2 = nb2, .nb3 = nb3, + .src0_row_size = ne00 * ct->kparams->src0_type_size, + .dst_row_size = ne00 * ct->kparams->dst_type_size, + .src0_row_stride = L->src0_row_stride, + .dst_row_stride = L->dst_row_stride, + .blk_rows = L->blk_rows, + .ir1 = ir1, + .cur = { ir0, i01, i02, i03 }, + }; + + dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, + cpy_convert_next_task, cpy_convert_push_in, cpy_convert_compute, cpy_convert_push_out); +} static int cpy_scalar(struct htp_ops_context * octx, const struct htp_copy_kernel_params * kparams) { if (octx->ctx->mdev.count > 1 && octx->ctx->mdev.idx > 0) { @@ -550,26 +592,24 @@ static int cpy_sameshape_convert(struct htp_ops_context * octx, const struct htp ct.vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, ct.layout.off_src0); ct.vtcm_dst = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, ct.layout.off_dst); - work_queue_func_t copy_fun = NULL; if (dst->type == HTP_TYPE_F16 && src0->type == HTP_TYPE_F32) { - copy_fun = cpy_thread_f16_f32_sameshape; + ct.convert_block = cpy_convert_block_f16_f32; } else if (dst->type == HTP_TYPE_F32 && src0->type == HTP_TYPE_F16) { - copy_fun = cpy_thread_f32_f16_sameshape; + ct.convert_block = cpy_convert_block_f32_f16; } else if (dst->type == HTP_TYPE_I32 && src0->type == HTP_TYPE_F32) { - copy_fun = cpy_thread_i32_f32_sameshape; + ct.convert_block = cpy_convert_block_i32_f32; } else if (dst->type == HTP_TYPE_F32 && src0->type == HTP_TYPE_I32) { - copy_fun = cpy_thread_f32_i32_sameshape; + ct.convert_block = cpy_convert_block_f32_i32; } else { return HTP_STATUS_NO_SUPPORT; } - work_queue_run(octx->ctx->hvx_queue, copy_fun, &ct, n_hvx); + work_queue_run(octx->ctx->hvx_queue, cpy_thread_convert_sameshape, &ct, n_hvx); return HTP_STATUS_OK; } static int cpy_reshape(struct htp_ops_context * octx, const struct htp_copy_kernel_params * kparams) { const struct htp_tensor * src0 = octx->src[0]; - const struct htp_tensor * dst = octx->dst; if (!htp_ops_context_set_n_hvx(octx, kparams->n_hvx)) { return HTP_STATUS_INVAL_PARAMS; diff --git a/ggml/src/ggml-hexagon/htp/cumsum-ops.c b/ggml/src/ggml-hexagon/htp/cumsum-ops.c index 292a054550ae..08be5134b4c7 100644 --- a/ggml/src/ggml-hexagon/htp/cumsum-ops.c +++ b/ggml/src/ggml-hexagon/htp/cumsum-ops.c @@ -1,7 +1,3 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include @@ -16,48 +12,44 @@ #include "hvx-types.h" #include "hvx-utils.h" #include "dma-queue.h" +#include "dma-pipeline.h" #include "cumsum-ops.h" -#define htp_cumsum_tensors_preamble \ - const struct htp_tensor * restrict src0 = octx->src[0]; \ - const struct htp_tensor * restrict dst = octx->dst; \ - \ - const uint32_t ne00 = src0->ne[0]; \ - const uint32_t ne01 = src0->ne[1]; \ - const uint32_t ne02 = src0->ne[2]; \ - const uint32_t ne03 = src0->ne[3]; \ - \ - const uint32_t ne0 = dst->ne[0]; \ - const uint32_t ne1 = dst->ne[1]; \ - const uint32_t ne2 = dst->ne[2]; \ - const uint32_t ne3 = dst->ne[3]; \ - \ - const uint32_t nb00 = src0->nb[0]; \ - const uint32_t nb01 = src0->nb[1]; \ - const uint32_t nb02 = src0->nb[2]; \ - const uint32_t nb03 = src0->nb[3]; \ - \ - const uint32_t nb0 = dst->nb[0]; \ - const uint32_t nb1 = dst->nb[1]; \ - const uint32_t nb2 = dst->nb[2]; \ - const uint32_t nb3 = dst->nb[3]; - struct htp_cumsum_context { struct htp_ops_context * octx; - size_t src_row_size; - size_t dst_row_size; - size_t src_row_size_aligned; - size_t dst_row_size_aligned; - uint32_t rows_per_hvx; - uint32_t total_rows; - uint32_t row_start; + dma_pipe_compute_io_fn compute; + uint8_t * vtcm_src0; + uint8_t * vtcm_dst; + size_t src0_bytes_per_hvx; + size_t dst_bytes_per_hvx; + size_t src_elem_size; + size_t dst_elem_size; + size_t src_row_size; + size_t dst_row_size; + size_t src_chunk_bytes_aligned; + size_t dst_chunk_bytes_aligned; + uint32_t chunk_elems; + uint32_t rows_per_hvx; + uint32_t total_rows; + uint32_t row_start; }; -#define htp_cumsum_preamble \ - struct htp_cumsum_context * cctx = (struct htp_cumsum_context *) data; \ - struct htp_ops_context * octx = cctx->octx; \ - htp_cumsum_tensors_preamble; \ - dma_queue * dma_q = th->dma_q; +struct cumsum_pipe_state { + dma_addr_t src_data; + dma_addr_t dst_data; + size_t src_elem_size; + size_t dst_elem_size; + size_t src_row_size; + size_t dst_row_size; + size_t src_chunk_bytes_aligned; + size_t dst_chunk_bytes_aligned; + uint32_t ne00; + uint32_t chunk_elems; + uint32_t row; + uint32_t row_end; + uint32_t off; + uint32_t carry_bits; +}; // --------------------------------------------------------------------------- // HVX prefix scan helpers @@ -71,7 +63,7 @@ static inline HVX_Vector hvx_cumsum_vadd(HVX_Vector a, HVX_Vector b) { static inline HVX_Vector hvx_cumsum_vadd(HVX_Vector a, HVX_Vector b) { return Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_VsfVsf(a, b)); } -#endif // __HVX_ARCH__ > 75 +#endif // __HVX_ARCH__ > 75 static inline HVX_Vector hvx_prefix_scan_f32(HVX_Vector v, HVX_Vector carry_in) { const HVX_Vector zero = Q6_V_vsplat_R(0); @@ -90,126 +82,229 @@ static inline HVX_Vector hvx_splat_last_f32(HVX_Vector v) { return hvx_vec_repl4(Q6_V_vror_VR(v, 124)); } -static inline void hvx_cumsum_row_f32(const float * restrict src, float * restrict dst, uint32_t n) { +static inline HVX_Vector hvx_cumsum_clamp_f16(HVX_Vector v) { + const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); + const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); + return Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v)); +} + +static void __attribute__((noinline)) cumsum_compute_f32_f32(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct cumsum_pipe_state * s = (struct cumsum_pipe_state *) ctx; + + const float * restrict src = (const float *) in_spad; + float * restrict dst = (float *) out_spad; + + const uint32_t n = task->len; const uint32_t nvec = n >> 5; const uint32_t nloe = n & (VLEN_FP32 - 1); - HVX_Vector carry = Q6_V_vsplat_R(0); + HVX_Vector carry = (task->off == 0) ? Q6_V_vsplat_R(0) : Q6_V_vsplat_R(s->carry_bits); for (uint32_t i = 0; i < nvec; i++) { - HVX_Vector v = *((const HVX_UVector *) (src + i * VLEN_FP32)); + HVX_Vector v = *((const HVX_Vector *) (src + i * VLEN_FP32)); v = hvx_prefix_scan_f32(v, carry); - hvx_vec_store_u(dst + i * VLEN_FP32, VLEN, v); + *((HVX_Vector *) (dst + i * VLEN_FP32)) = v; carry = hvx_splat_last_f32(v); } if (nloe) { - float acc = hvx_vec_get_f32(carry); - const float * src_tail = src + nvec * VLEN_FP32; - float * dst_tail = dst + nvec * VLEN_FP32; - for (uint32_t i = 0; i < nloe; i++) { - acc += src_tail[i]; - dst_tail[i] = acc; - } + HVX_Vector v = *((const HVX_Vector *) (src + nvec * VLEN_FP32)); + v = hvx_prefix_scan_f32(v, carry); + hvx_vec_store_a(dst + nvec * VLEN_FP32, nloe * sizeof(float), v); } + + s->carry_bits = (uint32_t) Q6_R_vextract_VR(carry, 0); } -// --------------------------------------------------------------------------- -// Per thread worker: Double-buffered DMA -// --------------------------------------------------------------------------- +static void __attribute__((noinline)) cumsum_compute_f16_f16(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct cumsum_pipe_state * s = (struct cumsum_pipe_state *) ctx; -static void cumsum_thread_f32_dma(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { - htp_cumsum_preamble; + const HVX_Vector * restrict vsrc = (const HVX_Vector *) in_spad; + HVX_Vector * restrict vdst = (HVX_Vector *) out_spad; - const uint32_t ir0 = cctx->row_start + cctx->rows_per_hvx * ith; - const uint32_t ir1 = MIN(ir0 + cctx->rows_per_hvx, cctx->row_start + cctx->total_rows); + const uint32_t n = task->len; + const uint32_t nvec = n >> 6; + const uint32_t nloe = n & (VLEN_FP16 - 1); - if (ir0 >= ir1) { - return; + HVX_Vector carry = (task->off == 0) ? Q6_V_vsplat_R(0) : Q6_V_vsplat_R(s->carry_bits); + + for (uint32_t i = 0; i < nvec; i++) { + const HVX_VectorPair p = hvx_vec_f16_to_f32(vsrc[i]); + const HVX_Vector v0 = hvx_prefix_scan_f32(Q6_V_lo_W(p), carry); + carry = hvx_splat_last_f32(v0); + const HVX_Vector v1 = hvx_prefix_scan_f32(Q6_V_hi_W(p), carry); + carry = hvx_splat_last_f32(v1); + vdst[i] = hvx_vec_f32_to_f16(hvx_cumsum_clamp_f16(v0), hvx_cumsum_clamp_f16(v1)); + } + + if (nloe) { + const HVX_VectorPair p = hvx_vec_f16_to_f32(vsrc[nvec]); + const HVX_Vector v0 = hvx_prefix_scan_f32(Q6_V_lo_W(p), carry); + carry = hvx_splat_last_f32(v0); + const HVX_Vector v1 = hvx_prefix_scan_f32(Q6_V_hi_W(p), carry); + const HVX_Vector out = hvx_vec_f32_to_f16(hvx_cumsum_clamp_f16(v0), hvx_cumsum_clamp_f16(v1)); + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(__fp16), out); } - const size_t src_row_size = cctx->src_row_size; - const size_t dst_row_size = cctx->dst_row_size; - const size_t src_row_size_aligned = cctx->src_row_size_aligned; - const size_t dst_row_size_aligned = cctx->dst_row_size_aligned; + s->carry_bits = (uint32_t) Q6_R_vextract_VR(carry, 0); +} + +static void __attribute__((noinline)) cumsum_compute_f16_f32(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct cumsum_pipe_state * s = (struct cumsum_pipe_state *) ctx; + + const HVX_Vector * restrict vsrc = (const HVX_Vector *) in_spad; + HVX_Vector * restrict vdst = (HVX_Vector *) out_spad; - const dma_addr_t src_data = src0->data; - const dma_addr_t dst_data = dst->data; + const uint32_t n = task->len; + const uint32_t nvec = n >> 6; + const uint32_t nloe = n & (VLEN_FP16 - 1); - uint8_t * src_spad = octx->src0_spad.data + (ith * src_row_size_aligned * 2); - uint8_t * dst_spad = octx->dst_spad.data + (ith * dst_row_size_aligned * 2); + HVX_Vector carry = (task->off == 0) ? Q6_V_vsplat_R(0) : Q6_V_vsplat_R(s->carry_bits); - for (uint32_t ir = ir0, spad_idx = 0; ir < ir1 && spad_idx < 2; ir++, spad_idx++) { - // Dummy dst writeback to establish queue ordering - dma_queue_push(dma_q, - dma_make_data(dst_data, dst_spad + (spad_idx * dst_row_size_aligned)), - dst_row_size, dst_row_size_aligned, dst_row_size, 0); + for (uint32_t i = 0; i < nvec; i++) { + const HVX_VectorPair p = hvx_vec_f16_to_f32(vsrc[i]); + const HVX_Vector v0 = hvx_prefix_scan_f32(Q6_V_lo_W(p), carry); + carry = hvx_splat_last_f32(v0); + const HVX_Vector v1 = hvx_prefix_scan_f32(Q6_V_hi_W(p), carry); + carry = hvx_splat_last_f32(v1); + vdst[2 * i] = v0; + vdst[2 * i + 1] = v1; + } - dma_queue_push(dma_q, - dma_make_data(src_spad + (spad_idx * src_row_size_aligned), - src_data + (ir * src_row_size)), - src_row_size_aligned, src_row_size, src_row_size, 1); + if (nloe) { + const HVX_VectorPair p = hvx_vec_f16_to_f32(vsrc[nvec]); + const HVX_Vector v0 = hvx_prefix_scan_f32(Q6_V_lo_W(p), carry); + if (nloe > VLEN_FP32) { + vdst[2 * nvec] = v0; + carry = hvx_splat_last_f32(v0); + const HVX_Vector v1 = hvx_prefix_scan_f32(Q6_V_hi_W(p), carry); + hvx_vec_store_a(&vdst[2 * nvec + 1], (nloe - VLEN_FP32) * sizeof(float), v1); + } else { + hvx_vec_store_a(&vdst[2 * nvec], nloe * sizeof(float), v0); + } } - struct htp_thread_trace * tr = th->trace; + s->carry_bits = (uint32_t) Q6_R_vextract_VR(carry, 0); +} - for (uint32_t ir = ir0; ir < ir1; ir++) { - float * dst_spad_row = (float *) dma_queue_pop(dma_q).src; - float * src_spad_row = (float *) dma_queue_pop(dma_q).dst; +static void __attribute__((noinline)) cumsum_compute_f32_f16(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct cumsum_pipe_state * s = (struct cumsum_pipe_state *) ctx; - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); - hvx_cumsum_row_f32(src_spad_row, dst_spad_row, ne00); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); + const HVX_Vector * restrict vsrc = (const HVX_Vector *) in_spad; + HVX_Vector * restrict vdst = (HVX_Vector *) out_spad; - dma_queue_push(dma_q, - dma_make_data(dst_data + (ir * dst_row_size), dst_spad_row), - dst_row_size, dst_row_size_aligned, dst_row_size, 1); + const uint32_t n = task->len; + const uint32_t nvec = n >> 6; + const uint32_t nloe = n & (VLEN_FP16 - 1); - const uint32_t next_row = ir + 2; - if (next_row < ir1) { - dma_queue_push(dma_q, - dma_make_data(src_spad_row, src_data + (next_row * src_row_size)), - src_row_size_aligned, src_row_size, src_row_size, 1); - } + HVX_Vector carry = (task->off == 0) ? Q6_V_vsplat_R(0) : Q6_V_vsplat_R(s->carry_bits); + + for (uint32_t i = 0; i < nvec; i++) { + const HVX_Vector v0 = hvx_prefix_scan_f32(vsrc[2 * i], carry); + carry = hvx_splat_last_f32(v0); + const HVX_Vector v1 = hvx_prefix_scan_f32(vsrc[2 * i + 1], carry); + carry = hvx_splat_last_f32(v1); + vdst[i] = hvx_vec_f32_to_f16(hvx_cumsum_clamp_f16(v0), hvx_cumsum_clamp_f16(v1)); } - dma_queue_flush(dma_q); + if (nloe) { + const HVX_Vector v0 = hvx_prefix_scan_f32(vsrc[2 * nvec], carry); + carry = hvx_splat_last_f32(v0); + const HVX_Vector v1 = (nloe > VLEN_FP32) ? hvx_prefix_scan_f32(vsrc[2 * nvec + 1], carry) : Q6_V_vzero(); + const HVX_Vector out = hvx_vec_f32_to_f16(hvx_cumsum_clamp_f16(v0), hvx_cumsum_clamp_f16(v1)); + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(__fp16), out); + } - FARF(HIGH, "cumsum-f32-dma %d/%d: %ux%ux%ux%u (%u:%u) -> %ux%ux%ux%u\n", - ith, nth, src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3], ir0, ir1, - dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3]); + s->carry_bits = (uint32_t) Q6_R_vextract_VR(carry, 0); } // --------------------------------------------------------------------------- -// Per thread worker: Direct HVX (no DMA) +// Per thread worker: Double-buffered DMA pipeline // --------------------------------------------------------------------------- -static void cumsum_thread_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { - htp_cumsum_preamble; +static bool cumsum_next_task(void * ctx, struct dma_pipe_task * task) { + struct cumsum_pipe_state * s = (struct cumsum_pipe_state *) ctx; + if (s->row >= s->row_end) { + return false; + } + + const uint32_t rem = s->ne00 - s->off; + const uint32_t len = MIN(s->chunk_elems, rem); + + task->row = s->row; + task->off = s->off; + task->len = len; + task->aux = 0; + + s->off += len; + if (s->off >= s->ne00) { + s->off = 0; + s->row++; + } + return true; +} + +static void cumsum_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct cumsum_pipe_state * s = (struct cumsum_pipe_state *) ctx; + + const size_t bytes = (size_t) task->len * s->src_elem_size; + const dma_addr_t src = s->src_data + (size_t) task->row * s->src_row_size + (size_t) task->off * s->src_elem_size; + + dma_queue_push(dma_q, dma_make_data(in_spad, src), s->src_chunk_bytes_aligned, bytes, bytes, 1); +} + +static void cumsum_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) { + struct cumsum_pipe_state * s = (struct cumsum_pipe_state *) ctx; + + const size_t bytes = (size_t) task->len * s->dst_elem_size; + const dma_addr_t dst = s->dst_data + (size_t) task->row * s->dst_row_size + (size_t) task->off * s->dst_elem_size; - const uint8_t * src_data = (const uint8_t *) src0->data; - uint8_t * dst_data = (uint8_t *) dst->data; + dma_queue_push(dma_q, dma_make_data(dst, out_spad), bytes, s->dst_chunk_bytes_aligned, bytes, 1); +} + +static void cumsum_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + struct htp_cumsum_context * cctx = (struct htp_cumsum_context *) data; + struct htp_ops_context * octx = cctx->octx; + const struct htp_tensor * src0 = octx->src[0]; + const struct htp_tensor * dst = octx->dst; const uint32_t ir0 = cctx->row_start + cctx->rows_per_hvx * ith; const uint32_t ir1 = MIN(ir0 + cctx->rows_per_hvx, cctx->row_start + cctx->total_rows); - struct htp_thread_trace * tr = th->trace; - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir0); - - for (uint32_t ir = ir0; ir < ir1; ir++) { - const float * restrict src_row = (const float *) (src_data + ir * cctx->src_row_size); - float * restrict dst_row = (float *) (dst_data + ir * cctx->dst_row_size); - hvx_cumsum_row_f32(src_row, dst_row, ne00); + if (ir0 >= ir1) { + return; } - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir0); + uint8_t * src_spad = cctx->vtcm_src0 + ith * cctx->src0_bytes_per_hvx; + uint8_t * dst_spad = cctx->vtcm_dst + ith * cctx->dst_bytes_per_hvx; + void * in_buf[2] = { src_spad, src_spad + cctx->src_chunk_bytes_aligned }; + void * out_buf[2] = { dst_spad, dst_spad + cctx->dst_chunk_bytes_aligned }; + + struct cumsum_pipe_state s = { + .src_data = src0->data, + .dst_data = dst->data, + .src_elem_size = cctx->src_elem_size, + .dst_elem_size = cctx->dst_elem_size, + .src_row_size = cctx->src_row_size, + .dst_row_size = cctx->dst_row_size, + .src_chunk_bytes_aligned = cctx->src_chunk_bytes_aligned, + .dst_chunk_bytes_aligned = cctx->dst_chunk_bytes_aligned, + .ne00 = src0->ne[0], + .chunk_elems = cctx->chunk_elems, + .row = ir0, + .row_end = ir1, + .off = 0, + .carry_bits = 0, + }; + + dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, cumsum_next_task, cumsum_push_in, cctx->compute, cumsum_push_out); - FARF(HIGH, "cumsum-f32 %d/%d: %ux%ux%ux%u (%u:%u) -> %ux%ux%ux%u\n", + FARF(HIGH, "cumsum %d/%d: %ux%ux%ux%u (%u:%u) -> %ux%ux%ux%u\n", ith, nth, src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3], ir0, ir1, dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3]); } -int op_cumsum_f32(struct htp_ops_context * octx) { +static int op_cumsum_impl(struct htp_ops_context * octx, size_t src_elem_size, size_t dst_elem_size, dma_pipe_compute_io_fn compute) { const struct htp_tensor * src0 = octx->src[0]; const struct htp_tensor * dst = octx->dst; const struct htp_cumsum_kernel_params * kparams = @@ -223,9 +318,7 @@ int op_cumsum_f32(struct htp_ops_context * octx) { uint32_t nrows = total_rows; if (octx->ctx->mdev.count > 1) { - uint32_t rows_per_chunk = 0; - htp_tensor_mdev_rows_per_chunk(dst, sizeof(float), (uint32_t) dst_row_size, &rows_per_chunk); - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_rows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); row_start = range.start; nrows = range.count; } @@ -240,51 +333,48 @@ int op_cumsum_f32(struct htp_ops_context * octx) { const uint32_t n_hvx = octx->n_hvx; - if (!kparams->use_dma && (htp_tensor_is_extended(src0) || htp_tensor_is_extended(dst))) { - return HTP_STATUS_NO_SUPPORT; - } - struct htp_cumsum_vtcm_layout layout = { 0 }; - if (kparams->use_dma) { - htp_cumsum_vtcm_layout_build(&layout, src_row_size, dst_row_size, n_hvx); - - octx->src0_spad.size_per_hvx = layout.src0_bytes_per_hvx; - octx->dst_spad.size_per_hvx = layout.dst_bytes_per_hvx; - octx->src0_spad.size = n_hvx * layout.src0_bytes_per_hvx; - octx->dst_spad.size = n_hvx * layout.dst_bytes_per_hvx; - octx->src0_spad.data = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_src0); - octx->dst_spad.data = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_dst); - octx->src0_spad.src = NULL; - octx->dst_spad.src = NULL; - } + htp_cumsum_vtcm_layout_build(&layout, (size_t) kparams->chunk_elems * src_elem_size, (size_t) kparams->chunk_elems * dst_elem_size, n_hvx); struct htp_cumsum_context cctx = { - .octx = octx, - .src_row_size = src_row_size, - .dst_row_size = dst_row_size, - .src_row_size_aligned = layout.src_row_size_aligned, - .dst_row_size_aligned = layout.dst_row_size_aligned, - .rows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div), - .total_rows = nrows, - .row_start = row_start, + .octx = octx, + .compute = compute, + .vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_src0), + .vtcm_dst = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_dst), + .src0_bytes_per_hvx = layout.src0_bytes_per_hvx, + .dst_bytes_per_hvx = layout.dst_bytes_per_hvx, + .src_elem_size = src_elem_size, + .dst_elem_size = dst_elem_size, + .src_row_size = src_row_size, + .dst_row_size = dst_row_size, + .src_chunk_bytes_aligned = layout.src_chunk_bytes_aligned, + .dst_chunk_bytes_aligned = layout.dst_chunk_bytes_aligned, + .chunk_elems = kparams->chunk_elems, + .rows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div), + .total_rows = nrows, + .row_start = row_start, }; - if (kparams->use_dma) { - work_queue_run(octx->ctx->hvx_queue, cumsum_thread_f32_dma, &cctx, n_hvx); - } else { - work_queue_run(octx->ctx->hvx_queue, cumsum_thread_f32, &cctx, n_hvx); - } + work_queue_run(octx->ctx->hvx_queue, cumsum_thread, &cctx, n_hvx); return HTP_STATUS_OK; } int op_cumsum(struct htp_ops_context * octx) { - const struct htp_tensor * dst = octx->dst; + const struct htp_tensor * src0 = octx->src[0]; + const struct htp_tensor * dst = octx->dst; - switch (dst->type) { - case HTP_TYPE_F32: - return op_cumsum_f32(octx); - default: - return HTP_STATUS_NO_SUPPORT; + if (src0->type == HTP_TYPE_F32 && dst->type == HTP_TYPE_F32) { + return op_cumsum_impl(octx, sizeof(float), sizeof(float), cumsum_compute_f32_f32); + } + if (src0->type == HTP_TYPE_F16 && dst->type == HTP_TYPE_F16) { + return op_cumsum_impl(octx, sizeof(__fp16), sizeof(__fp16), cumsum_compute_f16_f16); + } + if (src0->type == HTP_TYPE_F16 && dst->type == HTP_TYPE_F32) { + return op_cumsum_impl(octx, sizeof(__fp16), sizeof(float), cumsum_compute_f16_f32); + } + if (src0->type == HTP_TYPE_F32 && dst->type == HTP_TYPE_F16) { + return op_cumsum_impl(octx, sizeof(float), sizeof(__fp16), cumsum_compute_f32_f16); } + return HTP_STATUS_NO_SUPPORT; } diff --git a/ggml/src/ggml-hexagon/htp/cumsum-ops.h b/ggml/src/ggml-hexagon/htp/cumsum-ops.h index 48f4053ed49c..457357eeb695 100644 --- a/ggml/src/ggml-hexagon/htp/cumsum-ops.h +++ b/ggml/src/ggml-hexagon/htp/cumsum-ops.h @@ -9,22 +9,22 @@ struct htp_cumsum_vtcm_layout { size_t total_bytes; size_t off_src0; size_t off_dst; - size_t src_row_size_aligned; - size_t dst_row_size_aligned; + size_t src_chunk_bytes_aligned; + size_t dst_chunk_bytes_aligned; size_t src0_bytes_per_hvx; size_t dst_bytes_per_hvx; }; static inline void htp_cumsum_vtcm_layout_build( struct htp_cumsum_vtcm_layout * L, - size_t src_row_size, - size_t dst_row_size, + size_t src_chunk_bytes, + size_t dst_chunk_bytes, uint32_t n_hvx ) { - L->src_row_size_aligned = hex_round_up(src_row_size, 128); - L->dst_row_size_aligned = hex_round_up(dst_row_size, 128); - L->src0_bytes_per_hvx = 2 * L->src_row_size_aligned; - L->dst_bytes_per_hvx = 2 * L->dst_row_size_aligned; + L->src_chunk_bytes_aligned = hex_round_up(src_chunk_bytes, 128); + L->dst_chunk_bytes_aligned = hex_round_up(dst_chunk_bytes, 128); + L->src0_bytes_per_hvx = 2 * L->src_chunk_bytes_aligned; + L->dst_bytes_per_hvx = 2 * L->dst_chunk_bytes_aligned; size_t off = 0; VTCM_LAYOUT_ALLOC(off, off_src0, L->src0_bytes_per_hvx * n_hvx); @@ -36,7 +36,7 @@ static inline void htp_cumsum_vtcm_layout_build( struct htp_cumsum_kernel_params { uint32_t n_hvx; uint32_t total_rows; - uint32_t use_dma; + uint32_t chunk_elems; uint32_t vtcm_size; }; diff --git a/ggml/src/ggml-hexagon/htp/diag-ops.c b/ggml/src/ggml-hexagon/htp/diag-ops.c index ea1a50316d66..1f1aae281bc7 100644 --- a/ggml/src/ggml-hexagon/htp/diag-ops.c +++ b/ggml/src/ggml-hexagon/htp/diag-ops.c @@ -1,5 +1,3 @@ -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include @@ -15,149 +13,189 @@ #include "hex-utils.h" #include "hvx-copy.h" #include "dma-queue.h" +#include "dma-pipeline.h" #include "diag-ops.h" -#define htp_diag_tensors_preamble \ - const struct htp_tensor * restrict src0 = octx->src[0]; \ - const struct htp_tensor * restrict dst = octx->dst; \ - \ - const uint32_t ne02 = src0->ne[2]; \ - \ - const uint32_t ne0 = dst->ne[0]; \ - const uint32_t ne1 = dst->ne[1]; \ - \ - const uint32_t nb02 = src0->nb[2]; \ - const uint32_t nb03 = src0->nb[3]; \ - \ - const uint32_t nb1 = dst->nb[1]; \ - const uint32_t nb2 = dst->nb[2]; \ - const uint32_t nb3 = dst->nb[3]; - struct htp_diag_context { - struct htp_ops_context * octx; + struct htp_ops_context * octx; const struct htp_diag_kernel_params * kparams; - size_t src_batch_size; - size_t dst_row_size; - size_t src_batch_size_aligned; - size_t dst_row_size_aligned; - uint32_t batches_per_hvx; - uint32_t total_batches; - uint32_t batch_start; + dma_pipe_compute_io_fn compute; + uint8_t * vtcm_src0; + uint8_t * vtcm_dst; + size_t src0_bytes_per_hvx; + size_t dst_bytes_per_hvx; + size_t elem_size; + size_t dst_chunk_bytes_aligned; + uint32_t chunk_elems; + uint32_t batches_per_hvx; + uint32_t total_batches; + uint32_t batch_start; }; -#define htp_diag_preamble \ - struct htp_diag_context * dctx = (struct htp_diag_context *) data; \ - struct htp_ops_context * octx = dctx->octx; \ - htp_diag_tensors_preamble; - -static inline void hvx_diag_row_f32(const float * restrict src, float * restrict dst, - uint32_t row_idx, uint32_t n) { - hvx_splat_f32_a((uint8_t *) dst, 0.0f, n); - dst[row_idx] = src[row_idx]; -} +struct diag_pipe_state { + dma_addr_t src_data; + dma_addr_t dst_data; + size_t elem_size; + size_t dst_chunk_bytes_aligned; + uint32_t ne0; + uint32_t ne1; + uint32_t ne02; + uint32_t nb02; + uint32_t nb03; + uint32_t nb1; + uint32_t nb2; + uint32_t nb3; + uint32_t chunk_elems; + uint32_t ib; + uint32_t ib_end; + uint32_t i1; + uint32_t off; + const struct fastdiv_values * div_ne02; +}; -// --------------------------------------------------------------------------- -// Per thread worker: DMA src fetch, compute in VTCM, DMA dst writeback -// --------------------------------------------------------------------------- +static void __attribute__((noinline)) diag_compute_f32(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + (void) ctx; -static void diag_thread_f32_dma(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { - htp_diag_preamble; - dma_queue * dma_q = th->dma_q; + uint8_t * restrict dst = (uint8_t *) out_spad; + const uint8_t * restrict src = (const uint8_t *) in_spad; - const uint32_t ib0 = dctx->batch_start + dctx->batches_per_hvx * ith; - const uint32_t ib1 = MIN(ib0 + dctx->batches_per_hvx, dctx->batch_start + dctx->total_batches); + hvx_splat_f32_a(dst, 0.0f, task->len); - if (ib0 >= ib1) { - return; + if (task->row >= task->off && task->row < task->off + task->len) { + const uint32_t local_idx = task->row - task->off; + const uint32_t vec_idx = local_idx >> 5; + const uint32_t b_off = (local_idx & 31u) * sizeof(float); + const HVX_Vector src_v = *((const HVX_Vector *) src); + const HVX_Vector val_v = Q6_V_vsplat_R(Q6_R_vextract_VR(src_v, 0)); + const HVX_VectorPred b_mask = Q6_Q_vsetq_R(b_off); + const HVX_VectorPred e_mask = Q6_Q_vsetq2_R(b_off + sizeof(float)); + Q6_vmem_QnRIV(Q6_Q_or_QQn(b_mask, e_mask), &((HVX_Vector *) dst)[vec_idx], val_v); } +} - const size_t src_batch_size = dctx->src_batch_size; - const size_t dst_row_size = dctx->dst_row_size; - const size_t src_batch_size_aligned = dctx->src_batch_size_aligned; - const size_t dst_row_size_aligned = dctx->dst_row_size_aligned; - - const dma_addr_t src_data = src0->data; - const dma_addr_t dst_data = dst->data; +static void __attribute__((noinline)) diag_compute_f16(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + (void) ctx; - // 1 src buffer + 1 dst row buffer per thread in VTCM - uint8_t * src_spad = octx->src0_spad.data + (ith * src_batch_size_aligned); - uint8_t * dst_spad = octx->dst_spad.data + (ith * dst_row_size_aligned); + uint8_t * restrict dst = (uint8_t *) out_spad; + const uint8_t * restrict src = (const uint8_t *) in_spad; - struct htp_thread_trace * tr = th->trace; + hvx_splat_u16_a(dst, 0, task->len); - for (uint32_t ib = ib0; ib < ib1; ib++) { - const uint32_t i3 = fastdiv(ib, &dctx->kparams->div_ne02); - const uint32_t i2 = ib - i3 * ne02; + if (task->row >= task->off && task->row < task->off + task->len) { + const uint32_t local_idx = task->row - task->off; + const uint32_t vec_idx = local_idx >> 6; + const uint32_t b_off = (local_idx & 63u) * sizeof(__fp16); + const HVX_Vector src_v = *((const HVX_Vector *) src); + const HVX_Vector val_v = Q6_Vh_vsplat_R(Q6_R_vextract_VR(src_v, 0)); + const HVX_VectorPred b_mask = Q6_Q_vsetq_R(b_off); + const HVX_VectorPred e_mask = Q6_Q_vsetq2_R(b_off + sizeof(__fp16)); + Q6_vmem_QnRIV(Q6_Q_or_QQn(b_mask, e_mask), &((HVX_Vector *) dst)[vec_idx], val_v); + } +} - const dma_addr_t src_batch = src_data + i3 * nb03 + i2 * nb02; +// --------------------------------------------------------------------------- +// Per thread worker: Double-buffered DMA pipeline +// --------------------------------------------------------------------------- - // Fetch source vector into VTCM - dma_queue_push(dma_q, - dma_make_data(src_spad, src_batch), - src_batch_size_aligned, src_batch_size, src_batch_size, 1); - dma_queue_flush(dma_q); +static bool diag_next_task(void * ctx, struct dma_pipe_task * task) { + struct diag_pipe_state * s = (struct diag_pipe_state *) ctx; + if (s->ib >= s->ib_end) { + return false; + } - const float * src_spad_f32 = (const float *) src_spad; - float * dst_spad_f32 = (float *) dst_spad; + const uint32_t rem = s->ne0 - s->off; + const uint32_t len = MIN(s->chunk_elems, rem); + + task->row = s->i1; + task->off = s->off; + task->len = len; + task->aux = s->ib; + + s->off += len; + if (s->off >= s->ne0) { + s->off = 0; + s->i1++; + if (s->i1 >= s->ne1) { + s->i1 = 0; + s->ib++; + } + } + return true; +} - for (uint32_t i1 = 0; i1 < ne1; i1++) { - // Compute row in VTCM - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) (ib * ne1 + i1)); - hvx_diag_row_f32(src_spad_f32, dst_spad_f32, i1, ne0); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) (ib * ne1 + i1)); +static void diag_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct diag_pipe_state * s = (struct diag_pipe_state *) ctx; - // Write completed row back to DDR - const dma_addr_t dst_row = dst_data + i3 * nb3 + i2 * nb2 + i1 * nb1; - dma_queue_push(dma_q, - dma_make_data(dst_row, dst_spad), - dst_row_size, dst_row_size_aligned, dst_row_size, 1); - dma_queue_flush(dma_q); - } + if (task->row < task->off || task->row >= task->off + task->len) { + dma_queue_push(dma_q, dma_make_data(in_spad, 0), 0, 0, 0, 0); + return; } - FARF(HIGH, "diag-f32-dma %d/%d: %ux%ux%ux%u (%u:%u) -> %ux%ux%ux%u\n", - ith, nth, src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3], ib0, ib1, - dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3]); + const uint32_t i3 = fastdiv(task->aux, s->div_ne02); + const uint32_t i2 = task->aux - i3 * s->ne02; + const dma_addr_t src_elem = s->src_data + (size_t) i3 * s->nb03 + (size_t) i2 * s->nb02 + (size_t) task->row * s->elem_size; + + dma_queue_push(dma_q, dma_make_data(in_spad, src_elem), s->elem_size, s->elem_size, s->elem_size, 1); } -// --------------------------------------------------------------------------- -// Per thread worker: Direct HVX (no DMA) -// --------------------------------------------------------------------------- +static void diag_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) { + struct diag_pipe_state * s = (struct diag_pipe_state *) ctx; -static void diag_thread_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { - htp_diag_preamble; + const uint32_t i3 = fastdiv(task->aux, s->div_ne02); + const uint32_t i2 = task->aux - i3 * s->ne02; + const size_t bytes = (size_t) task->len * s->elem_size; + const dma_addr_t dst = s->dst_data + (size_t) i3 * s->nb3 + (size_t) i2 * s->nb2 + (size_t) task->row * s->nb1 + (size_t) task->off * s->elem_size; - const uint8_t * src_data = (const uint8_t *) src0->data; - uint8_t * dst_data = (uint8_t *) dst->data; + dma_queue_push(dma_q, dma_make_data(dst, out_spad), bytes, s->dst_chunk_bytes_aligned, bytes, 1); +} + +static void diag_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + struct htp_diag_context * dctx = (struct htp_diag_context *) data; + struct htp_ops_context * octx = dctx->octx; + const struct htp_tensor * src0 = octx->src[0]; + const struct htp_tensor * dst = octx->dst; const uint32_t ib0 = dctx->batch_start + dctx->batches_per_hvx * ith; const uint32_t ib1 = MIN(ib0 + dctx->batches_per_hvx, dctx->batch_start + dctx->total_batches); - struct htp_thread_trace * tr = th->trace; - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ib0); - - for (uint32_t ib = ib0; ib < ib1; ib++) { - const uint32_t i3 = fastdiv(ib, &dctx->kparams->div_ne02); - const uint32_t i2 = ib - i3 * ne02; - - const float * restrict src_batch = (const float *)(src_data + i3 * nb03 + i2 * nb02); - - for (uint32_t i1 = 0; i1 < ne1; i1++) { - float * restrict dst_row = (float *)(dst_data + i3 * nb3 + i2 * nb2 + i1 * nb1); - hvx_diag_row_f32(src_batch, dst_row, i1, ne0); - } + if (ib0 >= ib1) { + return; } - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ib0); + uint8_t * src_spad = dctx->vtcm_src0 + ith * dctx->src0_bytes_per_hvx; + uint8_t * dst_spad = dctx->vtcm_dst + ith * dctx->dst_bytes_per_hvx; + void * in_buf[2] = { src_spad, src_spad + 128 }; + void * out_buf[2] = { dst_spad, dst_spad + dctx->dst_chunk_bytes_aligned }; + + struct diag_pipe_state s = { + .src_data = src0->data, + .dst_data = dst->data, + .elem_size = dctx->elem_size, + .dst_chunk_bytes_aligned = dctx->dst_chunk_bytes_aligned, + .ne0 = dst->ne[0], + .ne1 = dst->ne[1], + .ne02 = src0->ne[2], + .nb02 = src0->nb[2], + .nb03 = src0->nb[3], + .nb1 = dst->nb[1], + .nb2 = dst->nb[2], + .nb3 = dst->nb[3], + .chunk_elems = dctx->chunk_elems, + .ib = ib0, + .ib_end = ib1, + .i1 = 0, + .off = 0, + .div_ne02 = &dctx->kparams->div_ne02, + }; + + dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, diag_next_task, diag_push_in, dctx->compute, diag_push_out); - FARF(HIGH, "diag-f32 %d/%d: %ux%ux%ux%u (%u:%u) -> %ux%ux%ux%u\n", + FARF(HIGH, "diag %d/%d: %ux%ux%ux%u (%u:%u) -> %ux%ux%ux%u\n", ith, nth, src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3], ib0, ib1, dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3]); } -int op_diag_f32(struct htp_ops_context * octx) { - const struct htp_tensor * src0 = octx->src[0]; - const struct htp_tensor * dst = octx->dst; +static int op_diag_impl(struct htp_ops_context * octx, size_t elem_size, dma_pipe_compute_io_fn compute) { const struct htp_diag_kernel_params * kparams = (const struct htp_diag_kernel_params *) octx->kernel_params; @@ -167,8 +205,7 @@ int op_diag_f32(struct htp_ops_context * octx) { uint32_t nbatches = total_batches; if (octx->ctx->mdev.count > 1) { - const bool can_split = (kparams->can_split != 0) && htp_tensor_mdev_data_aligned(dst); - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_batches, can_split ? kparams->batches_per_chunk : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_batches, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); batch_start = range.start; nbatches = range.count; } @@ -183,61 +220,44 @@ int op_diag_f32(struct htp_ops_context * octx) { const uint32_t n_hvx = octx->n_hvx; - if (!kparams->use_dma && (htp_tensor_is_extended(src0) || htp_tensor_is_extended(dst))) { - return HTP_STATUS_NO_SUPPORT; - } - - const size_t src_batch_size = src0->ne[0] * sizeof(float); - const size_t dst_row_size = dst->ne[0] * sizeof(float); - struct htp_diag_vtcm_layout layout = { 0 }; - if (kparams->use_dma) { - htp_diag_vtcm_layout_build(&layout, src_batch_size, dst_row_size, n_hvx); - - octx->src0_spad.size_per_hvx = layout.src0_bytes_per_hvx; - octx->dst_spad.size_per_hvx = layout.dst_bytes_per_hvx; - octx->src0_spad.size = n_hvx * layout.src0_bytes_per_hvx; - octx->dst_spad.size = n_hvx * layout.dst_bytes_per_hvx; - octx->src0_spad.data = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_src0); - octx->dst_spad.data = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_dst); - octx->src0_spad.src = NULL; - octx->dst_spad.src = NULL; - } + htp_diag_vtcm_layout_build(&layout, (size_t) kparams->chunk_elems * elem_size, n_hvx); struct htp_diag_context dctx = { - .octx = octx, - .kparams = kparams, - .src_batch_size = src_batch_size, - .dst_row_size = dst_row_size, - .src_batch_size_aligned = layout.src_batch_size_aligned, - .dst_row_size_aligned = layout.dst_row_size_aligned, - .batches_per_hvx = fastdiv(nbatches + n_hvx - 1, &octx->n_hvx_div), - .total_batches = nbatches, - .batch_start = batch_start, + .octx = octx, + .kparams = kparams, + .compute = compute, + .vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_src0), + .vtcm_dst = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_dst), + .src0_bytes_per_hvx = layout.src0_bytes_per_hvx, + .dst_bytes_per_hvx = layout.dst_bytes_per_hvx, + .elem_size = elem_size, + .dst_chunk_bytes_aligned = layout.dst_chunk_bytes_aligned, + .chunk_elems = kparams->chunk_elems, + .batches_per_hvx = fastdiv(nbatches + n_hvx - 1, &octx->n_hvx_div), + .total_batches = nbatches, + .batch_start = batch_start, }; - if (kparams->use_dma) { - work_queue_run(octx->ctx->hvx_queue, diag_thread_f32_dma, &dctx, n_hvx); - } else { - work_queue_run(octx->ctx->hvx_queue, diag_thread_f32, &dctx, n_hvx); - } + work_queue_run(octx->ctx->hvx_queue, diag_thread, &dctx, n_hvx); return HTP_STATUS_OK; } int op_diag(struct htp_ops_context * octx) { - const struct htp_tensor * dst = octx->dst; + const struct htp_tensor * src0 = octx->src[0]; + const struct htp_tensor * dst = octx->dst; - int err = HTP_STATUS_OK; + if (src0->type != dst->type) { + return HTP_STATUS_NO_SUPPORT; + } switch (dst->type) { case HTP_TYPE_F32: - err = op_diag_f32(octx); - break; + return op_diag_impl(octx, sizeof(float), diag_compute_f32); + case HTP_TYPE_F16: + return op_diag_impl(octx, sizeof(__fp16), diag_compute_f16); default: - err = HTP_STATUS_NO_SUPPORT; - break; + return HTP_STATUS_NO_SUPPORT; } - - return err; } diff --git a/ggml/src/ggml-hexagon/htp/diag-ops.h b/ggml/src/ggml-hexagon/htp/diag-ops.h index 609a061c5108..ac7cd7cb667e 100644 --- a/ggml/src/ggml-hexagon/htp/diag-ops.h +++ b/ggml/src/ggml-hexagon/htp/diag-ops.h @@ -10,22 +10,19 @@ struct htp_diag_vtcm_layout { size_t total_bytes; size_t off_src0; size_t off_dst; - size_t src_batch_size_aligned; - size_t dst_row_size_aligned; + size_t dst_chunk_bytes_aligned; size_t src0_bytes_per_hvx; size_t dst_bytes_per_hvx; }; static inline void htp_diag_vtcm_layout_build( struct htp_diag_vtcm_layout * L, - size_t src_batch_size, - size_t dst_row_size, + size_t dst_chunk_bytes, uint32_t n_hvx ) { - L->src_batch_size_aligned = hex_round_up(src_batch_size, 128); - L->dst_row_size_aligned = hex_round_up(dst_row_size, 128); - L->src0_bytes_per_hvx = L->src_batch_size_aligned; - L->dst_bytes_per_hvx = L->dst_row_size_aligned; + L->dst_chunk_bytes_aligned = hex_round_up(dst_chunk_bytes, 128); + L->src0_bytes_per_hvx = 2 * 128; + L->dst_bytes_per_hvx = 2 * L->dst_chunk_bytes_aligned; size_t off = 0; VTCM_LAYOUT_ALLOC(off, off_src0, L->src0_bytes_per_hvx * n_hvx); @@ -37,9 +34,7 @@ static inline void htp_diag_vtcm_layout_build( struct htp_diag_kernel_params { uint32_t n_hvx; uint32_t total_batches; - uint32_t use_dma; - uint32_t can_split; - uint32_t batches_per_chunk; + uint32_t chunk_elems; uint32_t vtcm_size; struct fastdiv_values div_ne02; diff --git a/ggml/src/ggml-hexagon/htp/dma-pipeline.h b/ggml/src/ggml-hexagon/htp/dma-pipeline.h new file mode 100644 index 000000000000..ea898148cddc --- /dev/null +++ b/ggml/src/ggml-hexagon/htp/dma-pipeline.h @@ -0,0 +1,200 @@ +#ifndef HTP_DMA_PIPELINE_H +#define HTP_DMA_PIPELINE_H + +#include +#include + +#include "dma-queue.h" +#include "htp-trace.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct dma_pipe_task { + uint32_t row; + uint32_t off; + uint32_t len; + uint32_t aux; +}; + +typedef bool (*dma_pipe_next_task_fn)(void * ctx, struct dma_pipe_task * task); +typedef void (*dma_pipe_push_in_fn)(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad); +typedef void (*dma_pipe_push_in2_fn)(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in0_spad, void * in1_spad); +typedef void (*dma_pipe_compute_io_fn)(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad); +typedef void (*dma_pipe_compute_io2_fn)(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in0_spad, void * in1_spad); +typedef void (*dma_pipe_compute_1_fn)(void * ctx, const struct dma_pipe_task * task, void * spad); +typedef void (*dma_pipe_push_out_fn)(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad); + +// Double-buffered DDR -> VTCM -> HVX -> VTCM -> DDR pipeline. +// Uses dummy output pushes in the prologue and dma_queue_pop().src/.dst to +// recycle VTCM slot pointers directly through the DMA ring. +// push_in/push_out must always push exactly one descriptor per task (use a +// zero-nrows dummy push carrying the VTCM pointer when skipping a transfer). +static inline void dma_pipe_io_run( + dma_queue * dma_q, + struct htp_thread_trace * tr, + void * ctx, + void * in_buf[2], + void * out_buf[2], + dma_pipe_next_task_fn next_task, + dma_pipe_push_in_fn push_in, + dma_pipe_compute_io_fn compute, + dma_pipe_push_out_fn push_out +) { + struct dma_pipe_task t[2]; + uint32_t head = 0, tail = 0; + + for (uint32_t b = 0; b < 2; ++b) { + if (!next_task(ctx, &t[tail & 1])) { + break; + } + dma_queue_push(dma_q, dma_make_data(0, out_buf[b]), 0, 0, 0, 0); + push_in(dma_q, ctx, &t[tail & 1], in_buf[b]); + tail++; + } + + while (head != tail) { + const struct dma_pipe_task cur = t[head & 1]; + head++; + + void * out_spad = (void *) (uintptr_t) dma_queue_pop(dma_q).src; + void * in_spad = (void *) (uintptr_t) dma_queue_pop(dma_q).dst; + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) cur.row); + compute(ctx, &cur, out_spad, in_spad); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) cur.row); + + push_out(dma_q, ctx, &cur, out_spad); + + if (next_task(ctx, &t[tail & 1])) { + push_in(dma_q, ctx, &t[tail & 1], in_spad); + tail++; + } + } + + dma_queue_flush(dma_q); +} + +// Double-buffered 2-input DDR -> VTCM -> HVX -> VTCM -> DDR pipeline. +static inline void dma_pipe_io2_run( + dma_queue * dma_q, + struct htp_thread_trace * tr, + void * ctx, + void * in0_buf[2], + void * in1_buf[2], + void * out_buf[2], + dma_pipe_next_task_fn next_task, + dma_pipe_push_in2_fn push_in, + dma_pipe_compute_io2_fn compute, + dma_pipe_push_out_fn push_out +) { + struct dma_pipe_task t[2]; + uint32_t head = 0, tail = 0; + + for (uint32_t b = 0; b < 2; ++b) { + if (!next_task(ctx, &t[tail & 1])) { + break; + } + dma_queue_push(dma_q, dma_make_data(0, out_buf[b]), 0, 0, 0, 0); + push_in(dma_q, ctx, &t[tail & 1], in0_buf[b], in1_buf[b]); + tail++; + } + + while (head != tail) { + const struct dma_pipe_task cur = t[head & 1]; + head++; + + void * out_spad = (void *) (uintptr_t) dma_queue_pop(dma_q).src; + void * in0_spad = (void *) (uintptr_t) dma_queue_pop(dma_q).dst; + void * in1_spad = (void *) (uintptr_t) dma_queue_pop(dma_q).dst; + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) cur.row); + compute(ctx, &cur, out_spad, in0_spad, in1_spad); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) cur.row); + + push_out(dma_q, ctx, &cur, out_spad); + + if (next_task(ctx, &t[tail & 1])) { + push_in(dma_q, ctx, &t[tail & 1], in0_spad, in1_spad); + tail++; + } + } + + dma_queue_flush(dma_q); +} + +// Double-buffered DDR -> VTCM -> HVX pipeline for input-only reductions. +static inline void dma_pipe_in_run( + dma_queue * dma_q, + struct htp_thread_trace * tr, + void * ctx, + void * in_buf[2], + dma_pipe_next_task_fn next_task, + dma_pipe_push_in_fn push_in, + dma_pipe_compute_1_fn compute +) { + struct dma_pipe_task t[2]; + uint32_t head = 0, tail = 0; + + for (uint32_t b = 0; b < 2; ++b) { + if (!next_task(ctx, &t[tail & 1])) { + break; + } + push_in(dma_q, ctx, &t[tail & 1], in_buf[b]); + tail++; + } + + while (head != tail) { + const struct dma_pipe_task cur = t[head & 1]; + head++; + + void * in_spad = (void *) (uintptr_t) dma_queue_pop(dma_q).dst; + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) cur.row); + compute(ctx, &cur, in_spad); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) cur.row); + + if (next_task(ctx, &t[tail & 1])) { + push_in(dma_q, ctx, &t[tail & 1], in_spad); + tail++; + } + } + + dma_queue_flush(dma_q); +} + +// Bounded in-flight HVX -> VTCM -> DDR pipeline for output-only generators. +static inline void dma_pipe_out_run( + dma_queue * dma_q, + struct htp_thread_trace * tr, + void * ctx, + void * const * out_bufs, + uint32_t n_bufs, + dma_pipe_next_task_fn next_task, + dma_pipe_compute_1_fn compute, + dma_pipe_push_out_fn push_out +) { + for (uint32_t b = 0; b < n_bufs; ++b) { + dma_queue_push(dma_q, dma_make_data(0, out_bufs[b]), 0, 0, 0, 0); + } + + struct dma_pipe_task cur; + while (next_task(ctx, &cur)) { + void * out_spad = (void *) (uintptr_t) dma_queue_pop(dma_q).src; + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) cur.row); + compute(ctx, &cur, out_spad); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) cur.row); + + push_out(dma_q, ctx, &cur, out_spad); + } + + dma_queue_flush(dma_q); +} + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // HTP_DMA_PIPELINE_H diff --git a/ggml/src/ggml-hexagon/htp/dma-proxy.c b/ggml/src/ggml-hexagon/htp/dma-proxy.c new file mode 100644 index 000000000000..b28bb100ce16 --- /dev/null +++ b/ggml/src/ggml-hexagon/htp/dma-proxy.c @@ -0,0 +1,188 @@ +#include "dma-proxy.h" + +#include +#include +#include + +#include +#include + +#define QURT_LOWEST_PRIO (254) + +static bool __attribute__((noinline)) dma_proxy_reap_completed(dma_proxy_t p, bool wait_one) { + dma_ring * r = p->th.dma_q->ring0; + uint32_t id = atomic_load_explicit(&p->idx_done, memory_order_relaxed); + if (id == p->idx_submit) { + return false; + } + + bool reaped = false; + dmpoll(); + #pragma clang loop vectorize(disable) interleave(disable) + while (id != p->idx_submit) { + volatile dma_descriptor_2d * hw_desc = &r->desc[r->pop_idx]; + if (!hw_desc->done) { + if (!wait_one) { + break; + } + while (!hw_desc->done) { + dmpoll(); + } + } + dma_ring_pop_nowait(r); + id++; + atomic_store_explicit(&p->idx_done, id, memory_order_release); + wait_one = false; + reaped = true; + } + return reaped; +} + +static void dma_proxy_thread(void * arg) { + dma_proxy_t p = (dma_proxy_t) arg; + + FARF(HIGH, "dma-proxy-thread (tid %u): started", p->th.tid); + + const uint32_t max_inflight = dma_queue_capacity(p->th.dma_q) - 1; + unsigned int poll_cnt = DMA_PROXY_POLL_COUNT; + unsigned int prev_seqn = 0; + + while (1) { + bool did_work = false; + + uint32_t iw = atomic_load_explicit(&p->idx_write, memory_order_acquire); + #pragma clang loop vectorize(disable) interleave(disable) + while (p->idx_submit != iw) { + uint32_t id = atomic_load_explicit(&p->idx_done, memory_order_relaxed); + if ((p->idx_submit - id) >= max_inflight) { + dma_proxy_reap_completed(p, true); + } + const struct dma_proxy_desc * d = &p->desc[p->idx_submit & p->idx_mask]; + const size_t nrows = (d->nrows != 0 && d->row_size != 0) ? d->nrows : 0; + dma_queue_push(p->th.dma_q, d->ddata, d->dst_stride, d->src_stride, d->row_size, nrows); + p->idx_submit++; + did_work = true; + } + + if (atomic_load_explicit(&p->idx_done, memory_order_relaxed) != p->idx_submit) { + if (!dma_proxy_reap_completed(p, false) && !did_work) { + hex_pause(); + } + poll_cnt = DMA_PROXY_POLL_COUNT; + continue; + } + + if (did_work) { + poll_cnt = DMA_PROXY_POLL_COUNT; + continue; + } + + if (atomic_load_explicit(&p->killed, memory_order_acquire)) { + break; + } + + unsigned int seqn = atomic_load_explicit(&p->seqn, memory_order_acquire); + if (seqn != prev_seqn) { + prev_seqn = seqn; + poll_cnt = DMA_PROXY_POLL_COUNT; + continue; + } + + if (--poll_cnt) { + hex_pause(); + continue; + } + + FARF(HIGH, "dma-proxy-thread: sleeping"); + qurt_futex_wait(&p->seqn, prev_seqn); + poll_cnt = DMA_PROXY_POLL_COUNT; + } + + FARF(HIGH, "dma-proxy-thread (tid %u): stopped", p->th.tid); +} + +size_t dma_proxy_sizeof(size_t capacity, uint32_t stack_size) { + capacity = hex_ceil_pow2(capacity > 0 ? capacity : 1); + size_t size_p = hex_align_up(sizeof(struct dma_proxy_s), HEX_L2_LINE_SIZE); + size_t size_desc = hex_align_up(capacity * sizeof(struct dma_proxy_desc), HEX_L2_LINE_SIZE); + size_t size_stack = stack_size; + return size_p + size_desc + size_stack; +} + +size_t dma_proxy_alignof(void) { + return HEX_L2_LINE_SIZE; +} + +dma_proxy_t dma_proxy_init(void * ptr, size_t capacity, uint32_t stack_size, dma_queue_t * dma, struct htp_thread_trace * trace) { + capacity = hex_ceil_pow2(capacity > 0 ? capacity : 1); + size_t size_p = hex_align_up(sizeof(struct dma_proxy_s), HEX_L2_LINE_SIZE); + size_t size_desc = hex_align_up(capacity * sizeof(struct dma_proxy_desc), HEX_L2_LINE_SIZE); + + uint8_t * block = (uint8_t *) ptr; + + dma_proxy_t p = (dma_proxy_t) block; + block += size_p; + memset(p, 0, sizeof(struct dma_proxy_s)); + + p->capacity = (uint32_t) capacity; + p->idx_mask = (uint32_t) (capacity - 1); + p->idx_pop = 0; + p->idx_submit = 0; + atomic_init(&p->idx_write, 0); + atomic_init(&p->idx_done, 0); + atomic_init(&p->seqn, 0); + atomic_init(&p->killed, false); + + p->desc = (struct dma_proxy_desc *) block; + block += size_desc; + memset(p->desc, 0, capacity * sizeof(struct dma_proxy_desc)); + + p->stack = block; + memset(p->stack, 0, stack_size); + + htp_thread_init(&p->th, dma, trace); + + int prio = qurt_thread_get_priority(qurt_thread_get_id()); + if (prio < 1) { + prio = 1; + } + if (prio > QURT_LOWEST_PRIO) { + prio = QURT_LOWEST_PRIO; + } + + qurt_thread_attr_t attr; + qurt_thread_attr_init(&attr); + qurt_thread_attr_set_stack_addr(&attr, p->stack); + qurt_thread_attr_set_stack_size(&attr, stack_size); + qurt_thread_attr_set_priority(&attr, prio); + qurt_thread_attr_set_name(&attr, "dma-proxy"); + + int err = qurt_thread_create(&p->thread, &attr, dma_proxy_thread, p); + if (err) { + FARF(ERROR, "dma-proxy: thread create failed (%d)", err); + return NULL; + } + + FARF(HIGH, "dma-proxy: capacity %u\n", (unsigned) capacity); + + return p; +} + +void dma_proxy_free(dma_proxy_t p) { + if (!p) { + return; + } + + dma_proxy_flush(p); + atomic_store_explicit(&p->killed, true, memory_order_release); + + unsigned int seqn = atomic_load_explicit(&p->seqn, memory_order_relaxed) + 1; + atomic_store_explicit(&p->seqn, seqn, memory_order_release); + qurt_futex_wake(&p->seqn, 1); + + if (p->thread) { + int status = 0; + (void) qurt_thread_join(p->thread, &status); + p->thread = 0; + } +} diff --git a/ggml/src/ggml-hexagon/htp/dma-proxy.h b/ggml/src/ggml-hexagon/htp/dma-proxy.h new file mode 100644 index 000000000000..1e276cdcfb37 --- /dev/null +++ b/ggml/src/ggml-hexagon/htp/dma-proxy.h @@ -0,0 +1,117 @@ +#ifndef HTP_DMA_PROXY_H +#define HTP_DMA_PROXY_H + +#include +#include +#include +#include + +#include +#include +#include + +#include "dma-queue.h" +#include "hex-utils.h" +#include "htp-thread.h" +#include "htp-trace.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if __HVX_ARCH__ > 79 +#define DMA_PROXY_POLL_COUNT 2000 +#else +#define DMA_PROXY_POLL_COUNT 1 +#endif + +struct dma_proxy_desc { + dma_data ddata; + uint32_t dst_stride; + uint32_t src_stride; + uint32_t row_size; + uint32_t nrows; +}; + +struct dma_proxy_s { + struct dma_proxy_desc * desc; + atomic_uint idx_write; // monotonic, updated by producer (push) + uint32_t idx_pop; // monotonic, updated by producer (pop) + uint32_t idx_mask; + uint32_t capacity; + atomic_uint seqn; // incremented on push/kill, used with futex + atomic_bool killed; + + atomic_uint idx_done __attribute__((aligned(HEX_L2_LINE_SIZE))); // monotonic, updated by consumer + uint32_t idx_submit; // monotonic, private to consumer + + qurt_thread_t thread; + htp_thread_t th; + void * stack; +}; + +typedef struct dma_proxy_s * dma_proxy_t; + +size_t dma_proxy_sizeof(size_t capacity, uint32_t stack_size); +size_t dma_proxy_alignof(void); +dma_proxy_t dma_proxy_init(void * ptr, size_t capacity, uint32_t stack_size, dma_queue_t * dma, struct htp_thread_trace * trace); +void dma_proxy_free(dma_proxy_t p); + +static inline bool dma_proxy_empty(dma_proxy_t p) { + return p->idx_pop == atomic_load_explicit(&p->idx_write, memory_order_relaxed); +} + +static inline bool dma_proxy_push(dma_proxy_t p, dma_data ddata, size_t dst_stride, size_t src_stride, size_t row_size, size_t nrows) { + uint32_t iw = atomic_load_explicit(&p->idx_write, memory_order_relaxed); + if ((iw - p->idx_pop) >= p->capacity) { + FARF(HIGH, "dma-proxy-push: queue is full\n"); + return false; + } + + struct dma_proxy_desc * d = &p->desc[iw & p->idx_mask]; + d->ddata = ddata; + d->dst_stride = (uint32_t) dst_stride; + d->src_stride = (uint32_t) src_stride; + d->row_size = (uint32_t) row_size; + d->nrows = (uint32_t) nrows; + + atomic_store_explicit(&p->idx_write, iw + 1, memory_order_release); + + // wake up proxy thread + unsigned int seqn = atomic_load_explicit(&p->seqn, memory_order_relaxed) + 1; + atomic_store_explicit(&p->seqn, seqn, memory_order_release); + qurt_futex_wake(&p->seqn, 1); + + return true; +} + +static inline dma_data dma_proxy_pop(dma_proxy_t p) { + uint32_t ip = p->idx_pop; + uint32_t iw = atomic_load_explicit(&p->idx_write, memory_order_relaxed); + + dma_data ddata = { 0 }; + if (ip == iw) { + return ddata; + } + + while ((int32_t) (atomic_load_explicit(&p->idx_done, memory_order_relaxed) - ip) <= 0) { + hex_pause(); + } + atomic_thread_fence(memory_order_acquire); + + ddata = p->desc[ip & p->idx_mask].ddata; + p->idx_pop = ip + 1; + return ddata; +} + +static inline void dma_proxy_flush(dma_proxy_t p) { + while (!dma_proxy_empty(p)) { + dma_proxy_pop(p); + } +} + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif /* HTP_DMA_PROXY_H */ diff --git a/ggml/src/ggml-hexagon/htp/dma-queue.c b/ggml/src/ggml-hexagon/htp/dma-queue.c index 11d52a919ac5..f8bd1ec227e7 100644 --- a/ggml/src/ggml-hexagon/htp/dma-queue.c +++ b/ggml/src/ggml-hexagon/htp/dma-queue.c @@ -4,8 +4,6 @@ #include #include -#pragma clang diagnostic ignored "-Wunused-function" - static inline uint32_t pow2_ceil(uint32_t x) { if (x <= 1) { return 1; diff --git a/ggml/src/ggml-hexagon/htp/dsv4-hc-ops.c b/ggml/src/ggml-hexagon/htp/dsv4-hc-ops.c index b7123923caa7..247f8bbc1bd2 100644 --- a/ggml/src/ggml-hexagon/htp/dsv4-hc-ops.c +++ b/ggml/src/ggml-hexagon/htp/dsv4-hc-ops.c @@ -1,6 +1,3 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" - #include #include @@ -51,6 +48,117 @@ static inline HVX_Vector dsv4_hc_sigmoid_f32(HVX_Vector v, HVX_Vector max_exp, H return Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(v3, r)); } +typedef void (*dsv4_hc_unpack_fn_t)(uint8_t * p); + +static void dsv4_hc_unpack_noop(uint8_t * p) { + (void) p; +} + +static void dsv4_hc_unpack_f16_0(uint8_t * p) { + *(HVX_Vector *) p = Q6_V_lo_W(hvx_vec_f16_to_f32(*(const HVX_Vector *) p)); +} + +static void dsv4_hc_unpack_f16_128(uint8_t * p) { + *(HVX_Vector *) (p + 128) = Q6_V_lo_W(hvx_vec_f16_to_f32(*(const HVX_Vector *) (p + 128))); +} + +static void dsv4_hc_unpack_f16_0_128(uint8_t * p) { + *(HVX_Vector *) p = Q6_V_lo_W(hvx_vec_f16_to_f32(*(const HVX_Vector *) p)); + *(HVX_Vector *) (p + 128) = Q6_V_lo_W(hvx_vec_f16_to_f32(*(const HVX_Vector *) (p + 128))); +} + +#define DSV4_HC_LOAD2_f32(lo, hi, ptr) \ + do { \ + lo = *(const HVX_Vector *) (ptr); \ + hi = *(const HVX_Vector *) ((ptr) + VLEN); \ + } while (0) + +#define DSV4_HC_LOAD2_f16(lo, hi, ptr) \ + do { \ + const HVX_VectorPair _p = hvx_vec_f16_to_f32(*(const HVX_Vector *) (ptr)); \ + lo = Q6_V_lo_W(_p); \ + hi = Q6_V_hi_W(_p); \ + } while (0) + +#define DSV4_HC_LOAD2_f16s(lo, hi, ptr) \ + do { \ + const HVX_VectorPair _p = hvx_vec_f16_to_f32_shuff(*(const HVX_Vector *) (ptr)); \ + lo = Q6_V_lo_W(_p); \ + hi = Q6_V_hi_W(_p); \ + } while (0) + +#define DSV4_HC_STORE2_f32(ptr, lo, hi) \ + do { \ + *(HVX_Vector *) (ptr) = (lo); \ + *(HVX_Vector *) ((ptr) + VLEN) = (hi); \ + } while (0) + +#define DSV4_HC_STORE2_f16(ptr, lo, hi) \ + do { \ + *(HVX_Vector *) (ptr) = hvx_vec_f32_to_f16((lo), (hi)); \ + } while (0) + +#define DSV4_HC_STORE2_f16s(ptr, lo, hi) \ + do { \ + *(HVX_Vector *) (ptr) = hvx_vec_f32_to_f16_shuff((lo), (hi)); \ + } while (0) + +#define DSV4_HC_STORE2_TAIL_f16s(ptr, lo, hi, has_hi) \ + do { \ + (void) (has_hi); \ + *(HVX_Vector *) (ptr) = hvx_vec_f32_to_f16_shuff((lo), (hi)); \ + } while (0) + +#define DSV4_HC_STORE2_TAIL_f32s(ptr, lo, hi, has_hi) \ + do { \ + const HVX_VectorPair _p = Q6_W_vshuff_VVR((hi), (lo), -4); \ + *(HVX_Vector *) (ptr) = Q6_V_lo_W(_p); \ + if (has_hi) { \ + *(HVX_Vector *) ((ptr) + VLEN) = Q6_V_hi_W(_p); \ + } \ + } while (0) + +#define DSV4_HC_LOAD1_f32(v, ptr) \ + do { \ + v = *(const HVX_Vector *) (ptr); \ + } while (0) + +#define DSV4_HC_LOAD1_f16(v, ptr) \ + do { \ + v = Q6_V_lo_W(hvx_vec_f16_to_f32(*(const HVX_Vector *) (ptr))); \ + } while (0) + +#define DSV4_HC_LOAD1_f16s(v, ptr) DSV4_HC_LOAD1_f16(v, ptr) + +#define DSV4_HC_STORE1_f32(ptr, v) \ + do { \ + *(HVX_Vector *) (ptr) = (v); \ + } while (0) + +#define DSV4_HC_STORE1_f16(ptr, v) \ + do { \ + *(HVX_Vector *) (ptr) = hvx_vec_f32_to_f16((v), (v)); \ + } while (0) + +#define DSV4_HC_STORE1_f16s(ptr, v) DSV4_HC_STORE1_f16(ptr, v) + +struct dsv4_hc_pre_context; +struct dsv4_hc_block; + +typedef void (*dsv4_hc_pre_plain_fn_t)( + const struct dsv4_hc_pre_context * dctx, + const struct dsv4_hc_block * block, + const uint8_t * x_spad, + uint8_t * d_spad, + const float * wb); + +typedef void (*dsv4_hc_pre_gated_fn_t)( + const struct dsv4_hc_pre_context * dctx, + const struct dsv4_hc_block * block, + const uint8_t * x_spad, + const uint8_t * g_spad, + uint8_t * d_spad); + struct dsv4_hc_pre_context { struct htp_ops_context * octx; const struct htp_dsv4_hc_pre_kernel_params * kparams; @@ -63,6 +171,13 @@ struct dsv4_hc_pre_context { uint32_t dma_block_chunks; uint32_t dma_row_stride; uint32_t dma_buffer_size; + uint32_t x_chunk_bytes; + uint32_t w_chunk_bytes; + uint32_t w_row_bytes; + uint32_t dst_chunk_bytes; + dsv4_hc_unpack_fn_t unpack_weights; + dsv4_hc_pre_plain_fn_t compute_plain; + dsv4_hc_pre_gated_fn_t compute_gated; }; struct dsv4_hc_block { @@ -93,10 +208,12 @@ static inline void dsv4_hc_pre_push_plain( const struct htp_tensor * x = dctx->octx->src[0]; const struct htp_tensor * weights = dctx->octx->src[1]; const uint32_t row_stride = dctx->dma_row_stride; - const uint32_t row_size = block->count * VLEN; + const uint32_t x_cb = dctx->x_chunk_bytes; + const uint32_t w_bytes = dctx->w_row_bytes; + const uint32_t x_size = block->count * x_cb; - dma_queue_push(dma_q, dma_make_data(spad, x->data + (block->it*x->nb[2] + block->chunk*VLEN)), row_stride, x->nb[1], row_size, 4); - dma_queue_push(dma_q, dma_make_data(spad + 5*row_stride, weights->data + (block->it*weights->nb[1])), 16, 16, 16, 1); + dma_queue_push(dma_q, dma_make_data(spad, x->data + (block->it*x->nb[2] + block->chunk*x_cb)), row_stride, x->nb[1], x_size, 4); + dma_queue_push(dma_q, dma_make_data(spad + 5*row_stride, weights->data + (block->it*weights->nb[1])), w_bytes, w_bytes, w_bytes, 1); } static inline void dsv4_hc_pre_push_gated( @@ -107,78 +224,203 @@ static inline void dsv4_hc_pre_push_gated( const struct htp_tensor * x = dctx->octx->src[0]; const struct htp_tensor * g = dctx->octx->src[1]; const uint32_t row_stride = dctx->dma_row_stride; - const uint32_t row_size = block->count * VLEN; + const uint32_t x_cb = dctx->x_chunk_bytes; + const uint32_t g_cb = dctx->w_chunk_bytes; + const uint32_t x_size = block->count * x_cb; + const uint32_t g_size = block->count * g_cb; - dma_queue_push(dma_q, dma_make_data(spad, x->data + (block->it*x->nb[2] + block->chunk*VLEN)), row_stride, x->nb[1], row_size, 4); - dma_queue_push(dma_q, dma_make_data(spad + 4*row_stride, g->data + (block->it*g->nb[2] + block->chunk*VLEN)), row_stride, g->nb[1], row_size, 4); + dma_queue_push(dma_q, dma_make_data(spad, x->data + (block->it*x->nb[2] + block->chunk*x_cb)), row_stride, x->nb[1], x_size, 4); + dma_queue_push(dma_q, dma_make_data(spad + 4*row_stride, g->data + (block->it*g->nb[2] + block->chunk*g_cb)), row_stride, g->nb[1], g_size, 4); } -static __attribute__((noinline)) void dsv4_hc_pre_plain_block_f32( - const struct dsv4_hc_pre_context * dctx, - const struct dsv4_hc_block * block, - const uint8_t * x_spad, - uint8_t * d_spad, - const float * wb) { - const uint32_t row_stride = dctx->dma_row_stride; - const HVX_Vector scale_v = hvx_vec_splat_f32(dctx->scale); - const HVX_Vector w0 = hvx_vec_splat_f32(wb[0]); - const HVX_Vector w1 = hvx_vec_splat_f32(wb[1]); - const HVX_Vector w2 = hvx_vec_splat_f32(wb[2]); - const HVX_Vector w3 = hvx_vec_splat_f32(wb[3]); - - for (uint32_t c = 0; c < block->count; ++c) { - const uint8_t * xb = x_spad + c*VLEN; - - HVX_Vector x0 = *(const HVX_Vector *) xb; - HVX_Vector x1 = *(const HVX_Vector *) (xb + row_stride); - HVX_Vector x2 = *(const HVX_Vector *) (xb + 2*row_stride); - HVX_Vector x3 = *(const HVX_Vector *) (xb + 3*row_stride); - - HVX_Vector acc = hvx_vec_mul_f32_f32(x0, w0); - acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(x1, w1)); - acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(x2, w2)); - acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(x3, w3)); - - *(HVX_Vector *) (d_spad + c*VLEN) = hvx_vec_mul_f32_f32(acc, scale_v); - } +#define DEFINE_DSV4_HC_PRE_PLAIN_BLOCK(SUFFIX, TX, TDST, X_CB, D_CB) \ +static __attribute__((noinline)) void dsv4_hc_pre_plain_block_##SUFFIX( \ + const struct dsv4_hc_pre_context * dctx, \ + const struct dsv4_hc_block * block, \ + const uint8_t * x_spad, \ + uint8_t * d_spad, \ + const float * wb) { \ + const uint32_t row_stride = dctx->dma_row_stride; \ + const float scale = dctx->scale; \ + const HVX_Vector w0 = hvx_vec_splat_f32(wb[0] * scale); \ + const HVX_Vector w1 = hvx_vec_splat_f32(wb[1] * scale); \ + const HVX_Vector w2 = hvx_vec_splat_f32(wb[2] * scale); \ + const HVX_Vector w3 = hvx_vec_splat_f32(wb[3] * scale); \ + const uint32_t count = block->count; \ + uint32_t c = 0; \ + for (; c + 2 <= count; c += 2) { \ + const uint8_t * xb = x_spad + c * (X_CB); \ + HVX_Vector x0, x1; \ + DSV4_HC_LOAD2_##TX(x0, x1, xb); \ + HVX_Vector acc0 = hvx_vec_mul_f32_f32(x0, w0); \ + HVX_Vector acc1 = hvx_vec_mul_f32_f32(x1, w0); \ + DSV4_HC_LOAD2_##TX(x0, x1, xb + row_stride); \ + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(x0, w1)); \ + acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(x1, w1)); \ + DSV4_HC_LOAD2_##TX(x0, x1, xb + 2 * row_stride); \ + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(x0, w2)); \ + acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(x1, w2)); \ + DSV4_HC_LOAD2_##TX(x0, x1, xb + 3 * row_stride); \ + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(x0, w3)); \ + acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(x1, w3)); \ + DSV4_HC_STORE2_##TDST(d_spad + c * (D_CB), acc0, acc1); \ + } \ + if (c < count) { \ + const uint8_t * xb = x_spad + c * (X_CB); \ + HVX_Vector x0; \ + DSV4_HC_LOAD1_##TX(x0, xb); \ + HVX_Vector acc0 = hvx_vec_mul_f32_f32(x0, w0); \ + DSV4_HC_LOAD1_##TX(x0, xb + row_stride); \ + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(x0, w1)); \ + DSV4_HC_LOAD1_##TX(x0, xb + 2 * row_stride); \ + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(x0, w2)); \ + DSV4_HC_LOAD1_##TX(x0, xb + 3 * row_stride); \ + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(x0, w3)); \ + DSV4_HC_STORE1_##TDST(d_spad + c * (D_CB), acc0); \ + } \ } -static __attribute__((noinline)) void dsv4_hc_pre_gated_block_f32( - const struct dsv4_hc_pre_context * dctx, - const struct dsv4_hc_block * block, - const uint8_t * x_spad, - const uint8_t * g_spad, - uint8_t * d_spad) { - const uint32_t row_stride = dctx->dma_row_stride; - const HVX_Vector scale_v = hvx_vec_splat_f32(dctx->scale); - const HVX_Vector max_exp = hvx_vec_splat_f32(87.0f); - const HVX_Vector min_exp = hvx_vec_splat_f32(-87.0f); - - for (uint32_t c = 0; c < block->count; ++c) { - const uint8_t * xb = x_spad + c*VLEN; - const uint8_t * gb = g_spad + c*VLEN; - - HVX_Vector xv = *(const HVX_Vector *) xb; - HVX_Vector gv = dsv4_hc_sigmoid_f32(*(const HVX_Vector *) gb, max_exp, min_exp); - HVX_Vector acc = hvx_vec_mul_f32_f32(xv, gv); - - xv = *(const HVX_Vector *) (xb + row_stride); - gv = dsv4_hc_sigmoid_f32(*(const HVX_Vector *) (gb + row_stride), max_exp, min_exp); - acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(xv, gv)); - - xv = *(const HVX_Vector *) (xb + 2*row_stride); - gv = dsv4_hc_sigmoid_f32(*(const HVX_Vector *) (gb + 2*row_stride), max_exp, min_exp); - acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(xv, gv)); - - xv = *(const HVX_Vector *) (xb + 3*row_stride); - gv = dsv4_hc_sigmoid_f32(*(const HVX_Vector *) (gb + 3*row_stride), max_exp, min_exp); - acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(xv, gv)); +DEFINE_DSV4_HC_PRE_PLAIN_BLOCK(f32_f32, f32, f32, 128, 128) +DEFINE_DSV4_HC_PRE_PLAIN_BLOCK(f32_f16, f32, f16, 128, 64) +DEFINE_DSV4_HC_PRE_PLAIN_BLOCK(f16_f32, f16, f32, 64, 128) +DEFINE_DSV4_HC_PRE_PLAIN_BLOCK(f16_f16, f16s, f16s, 64, 64) + +#define DSV4_HC_SIGMOID2_f32(lo, hi, ptr, max_exp, min_exp) \ + do { \ + lo = dsv4_hc_sigmoid_f32(*(const HVX_Vector *) (ptr), max_exp, min_exp); \ + hi = dsv4_hc_sigmoid_f32(*(const HVX_Vector *) ((ptr) + VLEN), max_exp, min_exp); \ + } while (0) + +#define DSV4_HC_SIGMOID2_f16(lo, hi, ptr, max_exp, min_exp) \ + do { \ + (void) (max_exp); \ + (void) (min_exp); \ + const HVX_VectorPair _p = hvx_vec_f16_to_f32(hvx_vec_fast_sigmoid_f16(*(const HVX_Vector *) (ptr))); \ + lo = Q6_V_lo_W(_p); \ + hi = Q6_V_hi_W(_p); \ + } while (0) + +#define DSV4_HC_SIGMOID1_f32(v, ptr, max_exp, min_exp) \ + do { \ + v = dsv4_hc_sigmoid_f32(*(const HVX_Vector *) (ptr), max_exp, min_exp); \ + } while (0) + +#define DSV4_HC_SIGMOID1_f16(v, ptr, max_exp, min_exp) \ + do { \ + (void) (max_exp); \ + (void) (min_exp); \ + v = Q6_V_lo_W(hvx_vec_f16_to_f32(hvx_vec_fast_sigmoid_f16(*(const HVX_Vector *) (ptr)))); \ + } while (0) + +#define DSV4_HC_PRE_GATED_STREAM2(TX, TG, xb, gb, off, acc0, acc1, max_exp, min_exp) \ + do { \ + const uint8_t * _xp = (xb) + (off); \ + const uint8_t * _gp = (gb) + (off); \ + asm volatile("" : "+v"(acc0), "+v"(acc1), "+r"(_xp), "+r"(_gp)); \ + HVX_Vector _x0, _x1, _g0, _g1; \ + DSV4_HC_LOAD2_##TX(_x0, _x1, _xp); \ + DSV4_HC_SIGMOID2_##TG(_g0, _g1, _gp, max_exp, min_exp); \ + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(_x0, _g0)); \ + acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(_x1, _g1)); \ + } while (0) + +#define DEFINE_DSV4_HC_PRE_GATED_BLOCK(SUFFIX, TX, TG, TDST, X_CB, G_CB, D_CB) \ +static __attribute__((noinline)) void dsv4_hc_pre_gated_block_##SUFFIX( \ + const struct dsv4_hc_pre_context * dctx, \ + const struct dsv4_hc_block * block, \ + const uint8_t * x_spad, \ + const uint8_t * g_spad, \ + uint8_t * d_spad) { \ + const uint32_t row_stride = dctx->dma_row_stride; \ + const HVX_Vector scale_v = hvx_vec_splat_f32(dctx->scale); \ + const HVX_Vector max_exp = hvx_vec_splat_f32(87.0f); \ + const HVX_Vector min_exp = hvx_vec_splat_f32(-87.0f); \ + const uint32_t count = block->count; \ + uint32_t c = 0; \ + for (; c + 2 <= count; c += 2) { \ + const uint8_t * xb = x_spad + c * (X_CB); \ + const uint8_t * gb = g_spad + c * (G_CB); \ + HVX_Vector x0, x1, g0, g1; \ + DSV4_HC_LOAD2_##TX(x0, x1, xb); \ + DSV4_HC_SIGMOID2_##TG(g0, g1, gb, max_exp, min_exp); \ + HVX_Vector acc0 = hvx_vec_mul_f32_f32(x0, g0); \ + HVX_Vector acc1 = hvx_vec_mul_f32_f32(x1, g1); \ + DSV4_HC_PRE_GATED_STREAM2(TX, TG, xb, gb, row_stride, acc0, acc1, max_exp, \ + min_exp); \ + DSV4_HC_PRE_GATED_STREAM2(TX, TG, xb, gb, 2 * row_stride, acc0, acc1, max_exp, \ + min_exp); \ + DSV4_HC_PRE_GATED_STREAM2(TX, TG, xb, gb, 3 * row_stride, acc0, acc1, max_exp, \ + min_exp); \ + acc0 = hvx_vec_mul_f32_f32(acc0, scale_v); \ + acc1 = hvx_vec_mul_f32_f32(acc1, scale_v); \ + DSV4_HC_STORE2_##TDST(d_spad + c * (D_CB), acc0, acc1); \ + } \ + if (c < count) { \ + const uint8_t * xb = x_spad + c * (X_CB); \ + const uint8_t * gb = g_spad + c * (G_CB); \ + HVX_Vector x0, g0; \ + DSV4_HC_LOAD1_##TX(x0, xb); \ + DSV4_HC_SIGMOID1_##TG(g0, gb, max_exp, min_exp); \ + HVX_Vector acc0 = hvx_vec_mul_f32_f32(x0, g0); \ + DSV4_HC_LOAD1_##TX(x0, xb + row_stride); \ + DSV4_HC_SIGMOID1_##TG(g0, gb + row_stride, max_exp, min_exp); \ + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(x0, g0)); \ + DSV4_HC_LOAD1_##TX(x0, xb + 2 * row_stride); \ + DSV4_HC_SIGMOID1_##TG(g0, gb + 2 * row_stride, max_exp, min_exp); \ + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(x0, g0)); \ + DSV4_HC_LOAD1_##TX(x0, xb + 3 * row_stride); \ + DSV4_HC_SIGMOID1_##TG(g0, gb + 3 * row_stride, max_exp, min_exp); \ + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(x0, g0)); \ + acc0 = hvx_vec_mul_f32_f32(acc0, scale_v); \ + DSV4_HC_STORE1_##TDST(d_spad + c * (D_CB), acc0); \ + } \ +} - *(HVX_Vector *) (d_spad + c*VLEN) = hvx_vec_mul_f32_f32(acc, scale_v); - } +#define DSV4_HC_PRE_GATED_EVAL_F16(xb, gb, row_stride, scale_v, acc0, acc1) \ + do { \ + const uint8_t * _xb = (xb); \ + const uint8_t * _gb = (gb); \ + const HVX_Vector _s0 = hvx_vec_fast_sigmoid_f16(*(const HVX_Vector *) _gb); \ + const HVX_Vector _s1 = hvx_vec_fast_sigmoid_f16(*(const HVX_Vector *) (_gb + (row_stride))); \ + const HVX_Vector _s2 = hvx_vec_fast_sigmoid_f16(*(const HVX_Vector *) (_gb + 2 * (row_stride))); \ + const HVX_Vector _s3 = hvx_vec_fast_sigmoid_f16(*(const HVX_Vector *) (_gb + 3 * (row_stride))); \ + asm volatile("" : "+r"(_xb) : "v"(_s0), "v"(_s1), "v"(_s2), "v"(_s3)); \ + HVX_VectorPair _acc = hvx_vec_mpy_f32_f16(*(const HVX_Vector *) _xb, _s0); \ + _acc = hvx_vec_mpyacc_f32_f16(_acc, *(const HVX_Vector *) (_xb + (row_stride)), _s1); \ + _acc = hvx_vec_mpyacc_f32_f16(_acc, *(const HVX_Vector *) (_xb + 2 * (row_stride)), _s2); \ + _acc = hvx_vec_mpyacc_f32_f16(_acc, *(const HVX_Vector *) (_xb + 3 * (row_stride)), _s3); \ + acc0 = hvx_vec_mul_f32_f32(Q6_V_lo_W(_acc), scale_v); \ + acc1 = hvx_vec_mul_f32_f32(Q6_V_hi_W(_acc), scale_v); \ + } while (0) + +#define DEFINE_DSV4_HC_PRE_GATED_F16_BLOCK(SUFFIX, TDST, D_CB) \ +static __attribute__((noinline)) void dsv4_hc_pre_gated_block_##SUFFIX( \ + const struct dsv4_hc_pre_context * dctx, \ + const struct dsv4_hc_block * block, \ + const uint8_t * x_spad, \ + const uint8_t * g_spad, \ + uint8_t * d_spad) { \ + const uint32_t row_stride = dctx->dma_row_stride; \ + const HVX_Vector scale_v = hvx_vec_splat_f32(dctx->scale); \ + const uint32_t count = block->count; \ + for (uint32_t c = 0; c < count; c += 2) { \ + HVX_Vector acc0, acc1; \ + DSV4_HC_PRE_GATED_EVAL_F16(x_spad + c * 64, g_spad + c * 64, row_stride, \ + scale_v, acc0, acc1); \ + DSV4_HC_STORE2_TAIL_##TDST(d_spad + c * (D_CB), acc0, acc1, c + 1 < count); \ + } \ } -static void dsv4_hc_pre_thread_plain_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { +DEFINE_DSV4_HC_PRE_GATED_BLOCK(f32_f32_f32, f32, f32, f32, 128, 128, 128) +DEFINE_DSV4_HC_PRE_GATED_BLOCK(f32_f32_f16, f32, f32, f16, 128, 128, 64) +DEFINE_DSV4_HC_PRE_GATED_BLOCK(f32_f16_f32, f32, f16, f32, 128, 64, 128) +DEFINE_DSV4_HC_PRE_GATED_BLOCK(f32_f16_f16, f32, f16, f16, 128, 64, 64) +DEFINE_DSV4_HC_PRE_GATED_BLOCK(f16_f32_f32, f16, f32, f32, 64, 128, 128) +DEFINE_DSV4_HC_PRE_GATED_BLOCK(f16_f32_f16, f16, f32, f16, 64, 128, 64) +DEFINE_DSV4_HC_PRE_GATED_F16_BLOCK(f16_f16_f32, f32s, 128) +DEFINE_DSV4_HC_PRE_GATED_F16_BLOCK(f16_f16_f16, f16s, 64) + +static void dsv4_hc_pre_thread_plain(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { struct dsv4_hc_pre_context * dctx = (struct dsv4_hc_pre_context *) data; struct htp_ops_context * octx = dctx->octx; @@ -187,6 +429,7 @@ static void dsv4_hc_pre_thread_plain_f32(const htp_thread_t * th, unsigned int n const uint32_t row_stride = dctx->dma_row_stride; const uint32_t buffer_size = dctx->dma_buffer_size; + const uint32_t dst_cb = dctx->dst_chunk_bytes; const uint32_t start = dctx->jobs_per_hvx * ith; const uint32_t end = hex_smin(start + dctx->jobs_per_hvx, dctx->total_jobs); if (start >= end) { @@ -202,13 +445,16 @@ static void dsv4_hc_pre_thread_plain_f32(const htp_thread_t * th, unsigned int n uint32_t prefetch_job = start; for (uint32_t i = 0; i < 2 && prefetch_job < end; ++i) { const struct dsv4_hc_block block = dsv4_hc_pre_block_make(dctx, prefetch_job, end); + const uint32_t d_bytes = block.count * dst_cb; // empty dst writeback keeps pop order dst, x, weights in loop - dma_queue_push(dma_q, dma_make_data(d_data, spad[i] + 4*row_stride), block.count*VLEN, block.count*VLEN, 0, 0); + dma_queue_push(dma_q, dma_make_data(d_data, spad[i] + 4*row_stride), d_bytes, d_bytes, 0, 0); dsv4_hc_pre_push_plain(dma_q, dctx, &block, spad[i]); prefetch_job += block.count; } struct htp_thread_trace * tr = th->trace; + const dsv4_hc_unpack_fn_t unpack = dctx->unpack_weights; + const dsv4_hc_pre_plain_fn_t compute = dctx->compute_plain; uint32_t job = start; uint32_t curr = 0; @@ -219,15 +465,17 @@ static void dsv4_hc_pre_thread_plain_f32(const htp_thread_t * th, unsigned int n dma_queue_pop(dma_q); dma_queue_pop(dma_q); - const float * wb = (const float *) (spad[curr] + 5*row_stride); + uint8_t * w_spad = spad[curr] + 5*row_stride; uint8_t * d_spad = spad[curr] + 4*row_stride; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) block.it); - dsv4_hc_pre_plain_block_f32(dctx, &block, spad[curr], d_spad, wb); + unpack(w_spad); + compute(dctx, &block, spad[curr], d_spad, (const float *) w_spad); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) block.it); - const uint64_t d_dst = d_data + (block.it*dst->nb[1] + block.chunk*VLEN); - dma_queue_push(dma_q, dma_make_data(d_dst, d_spad), block.count*VLEN, block.count*VLEN, block.count*VLEN, 1); + const uint32_t d_bytes = block.count * dst_cb; + const uint64_t d_dst = d_data + (block.it*dst->nb[1] + block.chunk*dst_cb); + dma_queue_push(dma_q, dma_make_data(d_dst, d_spad), d_bytes, d_bytes, d_bytes, 1); if (prefetch_job < end) { const struct dsv4_hc_block next = dsv4_hc_pre_block_make(dctx, prefetch_job, end); @@ -244,7 +492,7 @@ static void dsv4_hc_pre_thread_plain_f32(const htp_thread_t * th, unsigned int n (void) nth; } -static void dsv4_hc_pre_thread_gated_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { +static void dsv4_hc_pre_thread_gated(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { struct dsv4_hc_pre_context * dctx = (struct dsv4_hc_pre_context *) data; struct htp_ops_context * octx = dctx->octx; @@ -253,6 +501,7 @@ static void dsv4_hc_pre_thread_gated_f32(const htp_thread_t * th, unsigned int n const uint32_t row_stride = dctx->dma_row_stride; const uint32_t buffer_size = dctx->dma_buffer_size; + const uint32_t dst_cb = dctx->dst_chunk_bytes; const uint32_t start = dctx->jobs_per_hvx * ith; const uint32_t end = hex_smin(start + dctx->jobs_per_hvx, dctx->total_jobs); if (start >= end) { @@ -268,13 +517,15 @@ static void dsv4_hc_pre_thread_gated_f32(const htp_thread_t * th, unsigned int n uint32_t prefetch_job = start; for (uint32_t i = 0; i < 2 && prefetch_job < end; ++i) { const struct dsv4_hc_block block = dsv4_hc_pre_block_make(dctx, prefetch_job, end); + const uint32_t d_bytes = block.count * dst_cb; // empty dst writeback keeps pop order dst, x, g in loop - dma_queue_push(dma_q, dma_make_data(d_data, spad[i] + 8*row_stride), block.count*VLEN, block.count*VLEN, 0, 0); + dma_queue_push(dma_q, dma_make_data(d_data, spad[i] + 8*row_stride), d_bytes, d_bytes, 0, 0); dsv4_hc_pre_push_gated(dma_q, dctx, &block, spad[i]); prefetch_job += block.count; } struct htp_thread_trace * tr = th->trace; + const dsv4_hc_pre_gated_fn_t compute = dctx->compute_gated; uint32_t job = start; uint32_t curr = 0; @@ -288,11 +539,12 @@ static void dsv4_hc_pre_thread_gated_f32(const htp_thread_t * th, unsigned int n uint8_t * d_spad = spad[curr] + 8*row_stride; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) block.it); - dsv4_hc_pre_gated_block_f32(dctx, &block, spad[curr], spad[curr] + 4*row_stride, d_spad); + compute(dctx, &block, spad[curr], spad[curr] + 4*row_stride, d_spad); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) block.it); - const uint64_t d_dst = d_data + (block.it*dst->nb[1] + block.chunk*VLEN); - dma_queue_push(dma_q, dma_make_data(d_dst, d_spad), block.count*VLEN, block.count*VLEN, block.count*VLEN, 1); + const uint32_t d_bytes = block.count * dst_cb; + const uint64_t d_dst = d_data + (block.it*dst->nb[1] + block.chunk*dst_cb); + dma_queue_push(dma_q, dma_make_data(d_dst, d_spad), d_bytes, d_bytes, d_bytes, 1); if (prefetch_job < end) { const struct dsv4_hc_block next = dsv4_hc_pre_block_make(dctx, prefetch_job, end); @@ -327,8 +579,7 @@ int op_dsv4_hc_pre(struct htp_ops_context * octx) { uint32_t total_jobs = kparams->total_jobs; uint32_t jobs_per_hvx = kparams->jobs_per_hvx; if (octx->ctx->mdev.count > 1) { - const bool can_split = htp_tensor_mdev_data_aligned(dst) && ((dst->nb[1] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0); - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(n_tokens, can_split ? 1 : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(n_tokens, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); token_start = range.start; n_tokens = range.count; total_jobs = n_tokens * kparams->n_chunks; @@ -342,6 +593,28 @@ int op_dsv4_hc_pre(struct htp_ops_context * octx) { float scale; memcpy(&scale, octx->op_params, sizeof(scale)); + const uint32_t x_f16 = (x->type == HTP_TYPE_F16) ? 1u : 0u; + const uint32_t w_f16 = (weights->type == HTP_TYPE_F16) ? 1u : 0u; + const uint32_t d_f16 = (dst->type == HTP_TYPE_F16) ? 1u : 0u; + + static const dsv4_hc_pre_plain_fn_t plain_fns[4] = { + dsv4_hc_pre_plain_block_f32_f32, + dsv4_hc_pre_plain_block_f32_f16, + dsv4_hc_pre_plain_block_f16_f32, + dsv4_hc_pre_plain_block_f16_f16, + }; + + static const dsv4_hc_pre_gated_fn_t gated_fns[8] = { + dsv4_hc_pre_gated_block_f32_f32_f32, + dsv4_hc_pre_gated_block_f32_f32_f16, + dsv4_hc_pre_gated_block_f32_f16_f32, + dsv4_hc_pre_gated_block_f32_f16_f16, + dsv4_hc_pre_gated_block_f16_f32_f32, + dsv4_hc_pre_gated_block_f16_f32_f16, + dsv4_hc_pre_gated_block_f16_f16_f32, + dsv4_hc_pre_gated_block_f16_f16_f16, + }; + struct dsv4_hc_pre_context dctx = { .octx = octx, .kparams = kparams, @@ -354,12 +627,19 @@ int op_dsv4_hc_pre(struct htp_ops_context * octx) { .dma_block_chunks = kparams->dma_block_chunks, .dma_row_stride = kparams->dma_row_stride, .dma_buffer_size = kparams->dma_buffer_size, + .x_chunk_bytes = x_f16 ? 64u : 128u, + .w_chunk_bytes = w_f16 ? 64u : 128u, + .w_row_bytes = w_f16 ? 8u : 16u, + .dst_chunk_bytes = d_f16 ? 64u : 128u, + .unpack_weights = w_f16 ? dsv4_hc_unpack_f16_0 : dsv4_hc_unpack_noop, + .compute_plain = plain_fns[(x_f16 << 1) | d_f16], + .compute_gated = gated_fns[(x_f16 << 2) | (w_f16 << 1) | d_f16], }; work_queue_func_t worker = NULL; switch (kparams->kernel_type) { - case HTP_DSV4_HC_PRE_KERNEL_PLAIN: worker = dsv4_hc_pre_thread_plain_f32; break; - case HTP_DSV4_HC_PRE_KERNEL_GATED: worker = dsv4_hc_pre_thread_gated_f32; break; + case HTP_DSV4_HC_PRE_KERNEL_PLAIN: worker = dsv4_hc_pre_thread_plain; break; + case HTP_DSV4_HC_PRE_KERNEL_GATED: worker = dsv4_hc_pre_thread_gated; break; default: return HTP_STATUS_INVAL_PARAMS; } @@ -375,6 +655,16 @@ int op_dsv4_hc_pre(struct htp_ops_context * octx) { // DSV4_HC_POST // --------------------------------------------------------------------------- +typedef void (*dsv4_hc_post_compute_fn_t)( + const uint8_t * xb, + const uint8_t * rb, + size_t r_stride, + uint8_t * db, + size_t d_stride, + uint32_t count, + const float * p, + const float * c); + struct dsv4_hc_post_context { struct htp_ops_context * octx; const struct htp_dsv4_hc_post_kernel_params * kparams; @@ -382,6 +672,13 @@ struct dsv4_hc_post_context { uint32_t total_jobs; uint32_t jobs_per_hvx; uint8_t * vtcm; + uint32_t x_chunk_bytes; + uint32_t r_chunk_bytes; + uint32_t dst_chunk_bytes; + uint32_t post_bytes; + uint32_t comb_row_bytes; + dsv4_hc_unpack_fn_t unpack_params; + dsv4_hc_post_compute_fn_t compute; }; static inline struct dsv4_hc_block dsv4_hc_post_block_make( @@ -399,56 +696,138 @@ static inline struct dsv4_hc_block dsv4_hc_post_block_make( }; } -static __attribute__((noinline)) void dsv4_hc_post_identity_block_f32( - const uint8_t * xb, - const uint8_t * rb, - size_t r_stride, - uint8_t * db, - size_t d_stride, - uint32_t count, - const float * p) { - for (uint32_t id = 0; id < 4; ++id) { - const HVX_Vector pv = hvx_vec_splat_f32(p[id]); - const uint8_t * rr = rb + id*r_stride; - uint8_t * dd = db + id*d_stride; - - for (uint32_t i = 0; i < count; ++i) { - const HVX_Vector xv = *(const HVX_Vector *) (xb + i*VLEN); - const HVX_Vector rv = *(const HVX_Vector *) (rr + i*VLEN); - *(HVX_Vector *) (dd + i*VLEN) = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(xv, pv), rv); - } - } +#define DEFINE_DSV4_HC_POST_IDENTITY_BLOCK(SUFFIX, TX, TR, TDST, X_CB, R_CB, D_CB) \ +static __attribute__((noinline)) void dsv4_hc_post_identity_block_##SUFFIX( \ + const uint8_t * xb, \ + const uint8_t * rb, \ + size_t r_stride, \ + uint8_t * db, \ + size_t d_stride, \ + uint32_t count, \ + const float * p, \ + const float * c_unused) { \ + (void) c_unused; \ + const HVX_Vector pv0 = hvx_vec_splat_f32(p[0]); \ + const HVX_Vector pv1 = hvx_vec_splat_f32(p[1]); \ + const HVX_Vector pv2 = hvx_vec_splat_f32(p[2]); \ + const HVX_Vector pv3 = hvx_vec_splat_f32(p[3]); \ + uint32_t i = 0; \ + for (; i + 2 <= count; i += 2) { \ + HVX_Vector x0, x1, r0, r1; \ + DSV4_HC_LOAD2_##TX(x0, x1, xb + i * (X_CB)); \ + const uint8_t * rr = rb + i * (R_CB); \ + uint8_t * dd = db + i * (D_CB); \ + DSV4_HC_LOAD2_##TR(r0, r1, rr); \ + DSV4_HC_STORE2_##TDST(dd, \ + hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x0, pv0), r0), \ + hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x1, pv0), r1)); \ + DSV4_HC_LOAD2_##TR(r0, r1, rr + r_stride); \ + DSV4_HC_STORE2_##TDST(dd + d_stride, \ + hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x0, pv1), r0), \ + hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x1, pv1), r1)); \ + DSV4_HC_LOAD2_##TR(r0, r1, rr + 2 * r_stride); \ + DSV4_HC_STORE2_##TDST(dd + 2 * d_stride, \ + hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x0, pv2), r0), \ + hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x1, pv2), r1)); \ + DSV4_HC_LOAD2_##TR(r0, r1, rr + 3 * r_stride); \ + DSV4_HC_STORE2_##TDST(dd + 3 * d_stride, \ + hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x0, pv3), r0), \ + hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x1, pv3), r1)); \ + } \ + if (i < count) { \ + HVX_Vector x0, r0; \ + DSV4_HC_LOAD1_##TX(x0, xb + i * (X_CB)); \ + const uint8_t * rr = rb + i * (R_CB); \ + uint8_t * dd = db + i * (D_CB); \ + DSV4_HC_LOAD1_##TR(r0, rr); \ + DSV4_HC_STORE1_##TDST(dd, \ + hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x0, pv0), r0)); \ + DSV4_HC_LOAD1_##TR(r0, rr + r_stride); \ + DSV4_HC_STORE1_##TDST(dd + d_stride, \ + hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x0, pv1), r0)); \ + DSV4_HC_LOAD1_##TR(r0, rr + 2 * r_stride); \ + DSV4_HC_STORE1_##TDST(dd + 2 * d_stride, \ + hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x0, pv2), r0)); \ + DSV4_HC_LOAD1_##TR(r0, rr + 3 * r_stride); \ + DSV4_HC_STORE1_##TDST(dd + 3 * d_stride, \ + hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x0, pv3), r0)); \ + } \ } -static __attribute__((noinline)) void dsv4_hc_post_comb_block_f32( - const uint8_t * xb, - const uint8_t * rb, - size_t r_stride, - uint8_t * db, - size_t d_stride, - uint32_t count, - const float * p, - const float * c) { - for (uint32_t id = 0; id < 4; ++id) { - const HVX_Vector pv = hvx_vec_splat_f32(p[id]); - const HVX_Vector c0 = hvx_vec_splat_f32(c[id]); - const HVX_Vector c1 = hvx_vec_splat_f32(c[4 + id]); - const HVX_Vector c2 = hvx_vec_splat_f32(c[8 + id]); - const HVX_Vector c3 = hvx_vec_splat_f32(c[12 + id]); - uint8_t * dd = db + id*d_stride; - - for (uint32_t i = 0; i < count; ++i) { - const uint8_t * r = rb + i*VLEN; - HVX_Vector acc = hvx_vec_mul_f32_f32(*(const HVX_Vector *) (xb + i*VLEN), pv); - acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(*(const HVX_Vector *) r, c0)); - acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(*(const HVX_Vector *) (r + r_stride), c1)); - acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(*(const HVX_Vector *) (r + 2*r_stride), c2)); - acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(*(const HVX_Vector *) (r + 3*r_stride), c3)); - *(HVX_Vector *) (dd + i*VLEN) = acc; - } - } +DEFINE_DSV4_HC_POST_IDENTITY_BLOCK(f32_f32_f32, f32, f32, f32, 128, 128, 128) +DEFINE_DSV4_HC_POST_IDENTITY_BLOCK(f32_f32_f16, f32, f32, f16, 128, 128, 64) +DEFINE_DSV4_HC_POST_IDENTITY_BLOCK(f32_f16_f32, f32, f16, f32, 128, 64, 128) +DEFINE_DSV4_HC_POST_IDENTITY_BLOCK(f32_f16_f16, f32, f16, f16, 128, 64, 64) +DEFINE_DSV4_HC_POST_IDENTITY_BLOCK(f16_f32_f32, f16, f32, f32, 64, 128, 128) +DEFINE_DSV4_HC_POST_IDENTITY_BLOCK(f16_f32_f16, f16, f32, f16, 64, 128, 64) +DEFINE_DSV4_HC_POST_IDENTITY_BLOCK(f16_f16_f32, f16, f16, f32, 64, 64, 128) +DEFINE_DSV4_HC_POST_IDENTITY_BLOCK(f16_f16_f16, f16s, f16s, f16s, 64, 64, 64) + +#define DEFINE_DSV4_HC_POST_COMB_BLOCK(SUFFIX, TX, TR, TDST, X_CB, R_CB, D_CB) \ +static __attribute__((noinline)) void dsv4_hc_post_comb_block_##SUFFIX( \ + const uint8_t * xb, \ + const uint8_t * rb, \ + size_t r_stride, \ + uint8_t * db, \ + size_t d_stride, \ + uint32_t count, \ + const float * p, \ + const float * c) { \ + for (uint32_t id = 0; id < 4; ++id) { \ + const HVX_Vector pv = hvx_vec_splat_f32(p[id]); \ + const HVX_Vector c0 = hvx_vec_splat_f32(c[id]); \ + const HVX_Vector c1 = hvx_vec_splat_f32(c[4 + id]); \ + const HVX_Vector c2 = hvx_vec_splat_f32(c[8 + id]); \ + const HVX_Vector c3 = hvx_vec_splat_f32(c[12 + id]); \ + uint8_t * dd = db + id * d_stride; \ + uint32_t i = 0; \ + for (; i + 2 <= count; i += 2) { \ + HVX_Vector v0, v1; \ + DSV4_HC_LOAD2_##TX(v0, v1, xb + i * (X_CB)); \ + HVX_Vector acc0 = hvx_vec_mul_f32_f32(v0, pv); \ + HVX_Vector acc1 = hvx_vec_mul_f32_f32(v1, pv); \ + const uint8_t * r = rb + i * (R_CB); \ + DSV4_HC_LOAD2_##TR(v0, v1, r); \ + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(v0, c0)); \ + acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(v1, c0)); \ + DSV4_HC_LOAD2_##TR(v0, v1, r + r_stride); \ + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(v0, c1)); \ + acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(v1, c1)); \ + DSV4_HC_LOAD2_##TR(v0, v1, r + 2 * r_stride); \ + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(v0, c2)); \ + acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(v1, c2)); \ + DSV4_HC_LOAD2_##TR(v0, v1, r + 3 * r_stride); \ + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(v0, c3)); \ + acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(v1, c3)); \ + DSV4_HC_STORE2_##TDST(dd + i * (D_CB), acc0, acc1); \ + } \ + if (i < count) { \ + HVX_Vector v0; \ + DSV4_HC_LOAD1_##TX(v0, xb + i * (X_CB)); \ + HVX_Vector acc0 = hvx_vec_mul_f32_f32(v0, pv); \ + const uint8_t * r = rb + i * (R_CB); \ + DSV4_HC_LOAD1_##TR(v0, r); \ + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(v0, c0)); \ + DSV4_HC_LOAD1_##TR(v0, r + r_stride); \ + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(v0, c1)); \ + DSV4_HC_LOAD1_##TR(v0, r + 2 * r_stride); \ + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(v0, c2)); \ + DSV4_HC_LOAD1_##TR(v0, r + 3 * r_stride); \ + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(v0, c3)); \ + DSV4_HC_STORE1_##TDST(dd + i * (D_CB), acc0); \ + } \ + } \ } +DEFINE_DSV4_HC_POST_COMB_BLOCK(f32_f32_f32, f32, f32, f32, 128, 128, 128) +DEFINE_DSV4_HC_POST_COMB_BLOCK(f32_f32_f16, f32, f32, f16, 128, 128, 64) +DEFINE_DSV4_HC_POST_COMB_BLOCK(f32_f16_f32, f32, f16, f32, 128, 64, 128) +DEFINE_DSV4_HC_POST_COMB_BLOCK(f32_f16_f16, f32, f16, f16, 128, 64, 64) +DEFINE_DSV4_HC_POST_COMB_BLOCK(f16_f32_f32, f16, f32, f32, 64, 128, 128) +DEFINE_DSV4_HC_POST_COMB_BLOCK(f16_f32_f16, f16, f32, f16, 64, 128, 64) +DEFINE_DSV4_HC_POST_COMB_BLOCK(f16_f16_f32, f16, f16, f32, 64, 64, 128) +DEFINE_DSV4_HC_POST_COMB_BLOCK(f16_f16_f16, f16s, f16s, f16s, 64, 64, 64) + static inline void dsv4_hc_post_push_identity( dma_queue * dma_q, const struct dsv4_hc_post_context * dctx, @@ -458,14 +837,18 @@ static inline void dsv4_hc_post_push_identity( const struct htp_tensor * residual = dctx->octx->src[1]; const struct htp_tensor * post = dctx->octx->src[2]; const uint32_t row_stride = dctx->kparams->dma_row_stride; - const uint32_t row_size = block->count * VLEN; - - dma_queue_push(dma_q, dma_make_data(spad, residual->data + (block->it*residual->nb[2] + block->chunk*VLEN)), - row_stride, residual->nb[1], row_size, 4); - dma_queue_push(dma_q, dma_make_data(spad + 4*row_stride, x->data + (block->it*x->nb[1] + block->chunk*VLEN)), - row_stride, row_size, row_size, 1); + const uint32_t x_cb = dctx->x_chunk_bytes; + const uint32_t r_cb = dctx->r_chunk_bytes; + const uint32_t p_bytes = dctx->post_bytes; + const uint32_t x_size = block->count * x_cb; + const uint32_t r_size = block->count * r_cb; + + dma_queue_push(dma_q, dma_make_data(spad, residual->data + (block->it*residual->nb[2] + block->chunk*r_cb)), + row_stride, residual->nb[1], r_size, 4); + dma_queue_push(dma_q, dma_make_data(spad + 4*row_stride, x->data + (block->it*x->nb[1] + block->chunk*x_cb)), + row_stride, x_size, x_size, 1); dma_queue_push(dma_q, dma_make_data(spad + 9*row_stride, post->data + (block->it*post->nb[1])), - 16, 16, 16, 1); + p_bytes, p_bytes, p_bytes, 1); } static inline void dsv4_hc_post_push_comb( @@ -475,13 +858,14 @@ static inline void dsv4_hc_post_push_comb( uint8_t * spad) { const struct htp_tensor * comb = dctx->octx->src[3]; const uint32_t row_stride = dctx->kparams->dma_row_stride; + const uint32_t c_bytes = dctx->comb_row_bytes; dsv4_hc_post_push_identity(dma_q, dctx, block, spad); - dma_queue_push(dma_q, dma_make_data(spad + 9*row_stride + 64, comb->data + (block->it*comb->nb[2])), - 16, comb->nb[1], 16, 4); + dma_queue_push(dma_q, dma_make_data(spad + 9*row_stride + 128, comb->data + (block->it*comb->nb[2])), + c_bytes, comb->nb[1], c_bytes, 4); } -static void dsv4_hc_post_thread_identity_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { +static void dsv4_hc_post_thread_identity(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { struct dsv4_hc_post_context * dctx = (struct dsv4_hc_post_context *) data; struct htp_ops_context * octx = dctx->octx; @@ -491,6 +875,7 @@ static void dsv4_hc_post_thread_identity_f32(const htp_thread_t * th, unsigned i const uint32_t block_chunks = dctx->kparams->dma_block_chunks; const uint32_t row_stride = dctx->kparams->dma_row_stride; const uint32_t buffer_size = dctx->kparams->dma_buffer_size; + const uint32_t dst_cb = dctx->dst_chunk_bytes; const uint32_t start = dctx->jobs_per_hvx * ith; const uint32_t end = hex_smin(start + dctx->jobs_per_hvx, dctx->total_jobs); if (start >= end) { @@ -512,7 +897,9 @@ static void dsv4_hc_post_thread_identity_f32(const htp_thread_t * th, unsigned i prefetch_job += block.count; } - struct htp_thread_trace * tr = th->trace; + struct htp_thread_trace * tr = th->trace; + const dsv4_hc_unpack_fn_t unpack = dctx->unpack_params; + const dsv4_hc_post_compute_fn_t compute = dctx->compute; uint32_t job = start; uint32_t curr = 0; @@ -524,15 +911,16 @@ static void dsv4_hc_post_thread_identity_f32(const htp_thread_t * th, unsigned i dma_queue_pop(dma_q); dma_queue_pop(dma_q); - const float * p = (const float *) (spad[curr] + 9*row_stride); - uint8_t * d_spad = spad[curr] + 5*row_stride; + uint8_t * row9 = spad[curr] + 9*row_stride; + uint8_t * d_spad = spad[curr] + 5*row_stride; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) block.it); - dsv4_hc_post_identity_block_f32(spad[curr] + 4*row_stride, spad[curr], row_stride, d_spad, row_stride, block.count, p); + unpack(row9); + compute(spad[curr] + 4*row_stride, spad[curr], row_stride, d_spad, row_stride, block.count, (const float *) row9, NULL); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) block.it); - const uint64_t d_dst = d_data + (block.it*dst->nb[2] + block.chunk*VLEN); - dma_queue_push(dma_q, dma_make_data(d_dst, d_spad), dst->nb[1], row_stride, block.count*VLEN, 4); + const uint64_t d_dst = d_data + (block.it*dst->nb[2] + block.chunk*dst_cb); + dma_queue_push(dma_q, dma_make_data(d_dst, d_spad), dst->nb[1], row_stride, block.count*dst_cb, 4); if (prefetch_job < end) { const struct dsv4_hc_block next = dsv4_hc_post_block_make(dctx, prefetch_job, end, block_chunks); @@ -549,7 +937,7 @@ static void dsv4_hc_post_thread_identity_f32(const htp_thread_t * th, unsigned i (void) nth; } -static void dsv4_hc_post_thread_comb_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { +static void dsv4_hc_post_thread_comb(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { struct dsv4_hc_post_context * dctx = (struct dsv4_hc_post_context *) data; struct htp_ops_context * octx = dctx->octx; @@ -559,6 +947,7 @@ static void dsv4_hc_post_thread_comb_f32(const htp_thread_t * th, unsigned int n const uint32_t block_chunks = dctx->kparams->dma_block_chunks; const uint32_t row_stride = dctx->kparams->dma_row_stride; const uint32_t buffer_size = dctx->kparams->dma_buffer_size; + const uint32_t dst_cb = dctx->dst_chunk_bytes; const uint32_t start = dctx->jobs_per_hvx * ith; const uint32_t end = hex_smin(start + dctx->jobs_per_hvx, dctx->total_jobs); if (start >= end) { @@ -580,7 +969,9 @@ static void dsv4_hc_post_thread_comb_f32(const htp_thread_t * th, unsigned int n prefetch_job += block.count; } - struct htp_thread_trace * tr = th->trace; + struct htp_thread_trace * tr = th->trace; + const dsv4_hc_unpack_fn_t unpack = dctx->unpack_params; + const dsv4_hc_post_compute_fn_t compute = dctx->compute; uint32_t job = start; uint32_t curr = 0; @@ -593,16 +984,17 @@ static void dsv4_hc_post_thread_comb_f32(const htp_thread_t * th, unsigned int n dma_queue_pop(dma_q); dma_queue_pop(dma_q); - const float * p = (const float *) (spad[curr] + 9*row_stride); - const float * c = (const float *) (spad[curr] + 9*row_stride + 64); - uint8_t * d_spad = spad[curr] + 5*row_stride; + uint8_t * row9 = spad[curr] + 9*row_stride; + uint8_t * d_spad = spad[curr] + 5*row_stride; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) block.it); - dsv4_hc_post_comb_block_f32(spad[curr] + 4*row_stride, spad[curr], row_stride, d_spad, row_stride, block.count, p, c); + unpack(row9); + compute(spad[curr] + 4*row_stride, spad[curr], row_stride, d_spad, row_stride, block.count, + (const float *) row9, (const float *) (row9 + 128)); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) block.it); - const uint64_t d_dst = d_data + (block.it*dst->nb[2] + block.chunk*VLEN); - dma_queue_push(dma_q, dma_make_data(d_dst, d_spad), dst->nb[1], row_stride, block.count*VLEN, 4); + const uint64_t d_dst = d_data + (block.it*dst->nb[2] + block.chunk*dst_cb); + dma_queue_push(dma_q, dma_make_data(d_dst, d_spad), dst->nb[1], row_stride, block.count*dst_cb, 4); if (prefetch_job < end) { const struct dsv4_hc_block next = dsv4_hc_post_block_make(dctx, prefetch_job, end, block_chunks); @@ -622,10 +1014,12 @@ static void dsv4_hc_post_thread_comb_f32(const htp_thread_t * th, unsigned int n int op_dsv4_hc_post(struct htp_ops_context * octx) { const struct htp_tensor * x = octx->src[0]; const struct htp_tensor * residual = octx->src[1]; + const struct htp_tensor * post = octx->src[2]; const struct htp_tensor * dst = octx->dst; const struct htp_dsv4_hc_post_kernel_params * kparams = (const struct htp_dsv4_hc_post_kernel_params *) octx->kernel_params; + const struct htp_tensor * comb = kparams->has_comb ? octx->src[3] : NULL; const uint32_t n_hvx = kparams->n_hvx; if (!htp_ops_context_set_n_hvx_div(octx, n_hvx, kparams->div_n_hvx)) { @@ -637,8 +1031,7 @@ int op_dsv4_hc_post(struct htp_ops_context * octx) { uint32_t total_jobs = kparams->total_jobs; uint32_t jobs_per_hvx = kparams->jobs_per_hvx; if (octx->ctx->mdev.count > 1) { - const bool can_split = htp_tensor_mdev_data_aligned(dst) && ((dst->nb[2] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0); - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(n_tokens, can_split ? 1 : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(n_tokens, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); token_start = range.start; n_tokens = range.count; total_jobs = n_tokens * kparams->n_chunks; @@ -649,6 +1042,43 @@ int op_dsv4_hc_post(struct htp_ops_context * octx) { return HTP_STATUS_OK; } + const uint32_t x_f16 = (x->type == HTP_TYPE_F16) ? 1u : 0u; + const uint32_t r_f16 = (residual->type == HTP_TYPE_F16) ? 1u : 0u; + const uint32_t d_f16 = (dst->type == HTP_TYPE_F16) ? 1u : 0u; + const uint32_t p_f16 = (post->type == HTP_TYPE_F16) ? 1u : 0u; + const uint32_t c_f16 = (comb && comb->type == HTP_TYPE_F16) ? 1u : 0u; + + static const dsv4_hc_unpack_fn_t unpack_fns[4] = { + dsv4_hc_unpack_noop, + dsv4_hc_unpack_f16_0, + dsv4_hc_unpack_f16_128, + dsv4_hc_unpack_f16_0_128, + }; + + static const dsv4_hc_post_compute_fn_t identity_fns[8] = { + dsv4_hc_post_identity_block_f32_f32_f32, + dsv4_hc_post_identity_block_f32_f32_f16, + dsv4_hc_post_identity_block_f32_f16_f32, + dsv4_hc_post_identity_block_f32_f16_f16, + dsv4_hc_post_identity_block_f16_f32_f32, + dsv4_hc_post_identity_block_f16_f32_f16, + dsv4_hc_post_identity_block_f16_f16_f32, + dsv4_hc_post_identity_block_f16_f16_f16, + }; + + static const dsv4_hc_post_compute_fn_t comb_fns[8] = { + dsv4_hc_post_comb_block_f32_f32_f32, + dsv4_hc_post_comb_block_f32_f32_f16, + dsv4_hc_post_comb_block_f32_f16_f32, + dsv4_hc_post_comb_block_f32_f16_f16, + dsv4_hc_post_comb_block_f16_f32_f32, + dsv4_hc_post_comb_block_f16_f32_f16, + dsv4_hc_post_comb_block_f16_f16_f32, + dsv4_hc_post_comb_block_f16_f16_f16, + }; + + const uint32_t fn_idx = (x_f16 << 2) | (r_f16 << 1) | d_f16; + struct dsv4_hc_post_context dctx = { .octx = octx, .kparams = kparams, @@ -656,12 +1086,19 @@ int op_dsv4_hc_post(struct htp_ops_context * octx) { .total_jobs = total_jobs, .jobs_per_hvx = jobs_per_hvx, .vtcm = (uint8_t *) octx->ctx->vtcm_base, + .x_chunk_bytes = x_f16 ? 64u : 128u, + .r_chunk_bytes = r_f16 ? 64u : 128u, + .dst_chunk_bytes = d_f16 ? 64u : 128u, + .post_bytes = p_f16 ? 8u : 16u, + .comb_row_bytes = c_f16 ? 8u : 16u, + .unpack_params = unpack_fns[p_f16 | (c_f16 << 1)], + .compute = (kparams->kernel_type == HTP_DSV4_HC_POST_KERNEL_COMB) ? comb_fns[fn_idx] : identity_fns[fn_idx], }; work_queue_func_t worker = NULL; switch (kparams->kernel_type) { - case HTP_DSV4_HC_POST_KERNEL_IDENTITY: worker = dsv4_hc_post_thread_identity_f32; break; - case HTP_DSV4_HC_POST_KERNEL_COMB: worker = dsv4_hc_post_thread_comb_f32; break; + case HTP_DSV4_HC_POST_KERNEL_IDENTITY: worker = dsv4_hc_post_thread_identity; break; + case HTP_DSV4_HC_POST_KERNEL_COMB: worker = dsv4_hc_post_thread_comb; break; default: return HTP_STATUS_INVAL_PARAMS; } diff --git a/ggml/src/ggml-hexagon/htp/fill-ops.c b/ggml/src/ggml-hexagon/htp/fill-ops.c index 62026306304f..de024492b2c2 100644 --- a/ggml/src/ggml-hexagon/htp/fill-ops.c +++ b/ggml/src/ggml-hexagon/htp/fill-ops.c @@ -1,10 +1,7 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include +#include "dma-queue.h" #include "hex-common.h" #include "htp-trace.h" @@ -16,39 +13,67 @@ #include "htp-ctx.h" #include "htp-ops.h" #include "htp-tensor.h" +#include "htp-vtcm.h" #include "fill-ops.h" // ggml op_params layout for FILL: // op_params[0] (as float) - the scalar fill value -#define fill_preamble \ - const struct htp_tensor * dst = octx->dst; \ - \ - const uint32_t ne0 = dst->ne[0]; \ - const uint32_t ne1 = dst->ne[1]; \ - const uint32_t ne2 = dst->ne[2]; \ - const uint32_t ne3 = dst->ne[3]; \ - \ - const uint32_t nb1 = dst->nb[1]; \ - const uint32_t nb2 = dst->nb[2]; \ - const uint32_t nb3 = dst->nb[3]; +#define fill_preamble \ + const struct htp_tensor * dst = octx->dst; \ + \ + const uint32_t ne0 = dst->ne[0]; \ + const uint32_t __attribute__((unused)) ne1 = dst->ne[1]; \ + const uint32_t __attribute__((unused)) ne2 = dst->ne[2]; \ + \ + const uint32_t __attribute__((unused)) nb1 = dst->nb[1]; \ + const uint32_t __attribute__((unused)) nb2 = dst->nb[2]; \ + const uint32_t __attribute__((unused)) nb3 = dst->nb[3]; struct htp_fill_context { - struct htp_ops_context * octx; + struct htp_ops_context * octx; const struct htp_fill_kernel_params * kparams; - uint32_t nrows_per_hvx; - uint32_t total_rows; // ne1 * ne2 * ne3 - uint32_t row_start; - HVX_Vector splat_vec; - uint32_t elem_size; + dma_addr_t data_dst; + uint8_t * vtcm_tile; + size_t tile_bytes; + uint32_t nrows_per_hvx; + uint32_t total_rows; + uint32_t row_start; + uint32_t splat_bits; + uint32_t elem_size; }; +static void __attribute__((noinline)) fill_splat_vtcm( + uint8_t * vtcm_tile, + uint32_t splat_bits, + uint32_t n_bytes, + uint32_t elem_size +) { + const HVX_Vector sv = (elem_size == 2) ? Q6_Vh_vsplat_R((int32_t) splat_bits) : Q6_V_vsplat_R((int32_t) splat_bits); + hvx_splat_a(vtcm_tile, sv, n_bytes, 1); +} + +static inline void fill_dma_write_capped( + dma_queue * dma_q, + uint32_t * in_flight, + uint32_t max_in_flight, + dma_addr_t dst_addr, + const uint8_t * src_vtcm, + size_t nbytes +) { + if (*in_flight >= max_in_flight) { + dma_queue_pop(dma_q); + (*in_flight)--; + } + dma_queue_push(dma_q, dma_make_data(dst_addr, src_vtcm), nbytes, nbytes, nbytes, 1); + (*in_flight)++; +} + static void fill_thread_contiguous(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { const struct htp_fill_context * fctx = (const struct htp_fill_context *) data; - struct htp_ops_context * octx = fctx->octx; + struct htp_ops_context * octx = fctx->octx; fill_preamble; - // Parallelise over the flat row index spanning ne1*ne2*ne3 const uint32_t ir0 = fctx->row_start + fctx->nrows_per_hvx * ith; const uint32_t ir1 = MIN(ir0 + fctx->nrows_per_hvx, fctx->row_start + fctx->total_rows); @@ -56,25 +81,40 @@ static void fill_thread_contiguous(const htp_thread_t * th, unsigned int nth, un return; } + const size_t tile_bytes = fctx->tile_bytes; + const uint32_t elem_size = fctx->elem_size; + const size_t total_bytes = (size_t) (ir1 - ir0) * ne0 * elem_size; + const size_t splat_bytes = MIN(tile_bytes, hex_round_up(total_bytes, 128)); + uint8_t * vtcm_tile = fctx->vtcm_tile + ith * tile_bytes; + struct htp_thread_trace * tr = th->trace; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir0); + fill_splat_vtcm(vtcm_tile, fctx->splat_bits, (uint32_t) splat_bytes, elem_size); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir1); - const uint32_t elem_start = ir0 * ne0; - const uint32_t elem_end = ir1 * ne0; - uint8_t * dst_ptr = (uint8_t *) dst->data + elem_start * fctx->elem_size; - hvx_splat_u(dst_ptr, fctx->splat_vec, elem_end - elem_start, fctx->elem_size); + dma_queue * dma_q = th->dma_q; + const uint32_t max_in_flight = MIN(8u, dma_queue_capacity(dma_q) - 1); + uint32_t in_flight = 0; + const dma_addr_t dst_base = fctx->data_dst + (size_t) ir0 * ne0 * elem_size; + + for (size_t off = 0; off < total_bytes; off += tile_bytes) { + const size_t chunk = MIN(tile_bytes, total_bytes - off); + fill_dma_write_capped(dma_q, &in_flight, max_in_flight, dst_base + off, vtcm_tile, chunk); + } + + while (in_flight--) { + dma_queue_pop(dma_q); + } - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir1); FARF(HIGH, "fill-contig %u/%u: rows %u:%u\n", ith, nth, ir0, ir1); } static void fill_thread_strided(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { - const struct htp_fill_context * fctx = (const struct htp_fill_context *) data; - struct htp_ops_context * octx = fctx->octx; + const struct htp_fill_context * fctx = (const struct htp_fill_context *) data; + struct htp_ops_context * octx = fctx->octx; const struct htp_fill_kernel_params * kparams = fctx->kparams; fill_preamble; - // Parallelise over the flat row index spanning ne1*ne2*ne3 const uint32_t ir0 = fctx->row_start + fctx->nrows_per_hvx * ith; const uint32_t ir1 = MIN(ir0 + fctx->nrows_per_hvx, fctx->row_start + fctx->total_rows); @@ -82,19 +122,38 @@ static void fill_thread_strided(const htp_thread_t * th, unsigned int nth, unsig return; } + const size_t tile_bytes = fctx->tile_bytes; + const uint32_t elem_size = fctx->elem_size; + const size_t row_bytes = (size_t) ne0 * elem_size; + const size_t splat_bytes = MIN(tile_bytes, hex_round_up(row_bytes, 128)); + uint8_t * vtcm_tile = fctx->vtcm_tile + ith * tile_bytes; + struct htp_thread_trace * tr = th->trace; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir0); + fill_splat_vtcm(vtcm_tile, fctx->splat_bits, (uint32_t) splat_bytes, elem_size); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir1); + + dma_queue * dma_q = th->dma_q; + const uint32_t max_in_flight = MIN(8u, dma_queue_capacity(dma_q) - 1); + uint32_t in_flight = 0; for (uint32_t ir = ir0; ir < ir1; ++ir) { - const uint32_t i3 = fastdiv(ir, &kparams->div_ne1_ne2); - const uint32_t rem = ir - i3 * (ne1 * ne2); - const uint32_t i2 = fastdiv(rem, &kparams->div_ne1); - const uint32_t i1 = rem - i2 * ne1; - uint8_t * dst_ptr = (uint8_t *) dst->data + i1*nb1 + i2*nb2 + i3*nb3; - hvx_splat_u(dst_ptr, fctx->splat_vec, ne0, fctx->elem_size); + const uint32_t i3 = fastdiv(ir, &kparams->div_ne1_ne2); + const uint32_t rem = ir - i3 * (ne1 * ne2); + const uint32_t i2 = fastdiv(rem, &kparams->div_ne1); + const uint32_t i1 = rem - i2 * ne1; + const dma_addr_t dst_row = fctx->data_dst + (size_t) i1 * nb1 + (size_t) i2 * nb2 + (size_t) i3 * nb3; + + for (size_t off = 0; off < row_bytes; off += tile_bytes) { + const size_t chunk = MIN(tile_bytes, row_bytes - off); + fill_dma_write_capped(dma_q, &in_flight, max_in_flight, dst_row + off, vtcm_tile, chunk); + } + } + + while (in_flight--) { + dma_queue_pop(dma_q); } - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir1); FARF(HIGH, "fill-strided %u/%u: rows %u:%u\n", ith, nth, ir0, ir1); } @@ -103,15 +162,13 @@ int op_fill(struct htp_ops_context * octx) { const struct htp_fill_kernel_params * kparams = (const struct htp_fill_kernel_params *) octx->kernel_params; - if (htp_tensor_is_extended(dst)) { - return HTP_STATUS_NO_SUPPORT; - } - uint32_t row_start = 0; uint32_t nrows = kparams->total_rows; if (octx->ctx->mdev.count > 1) { - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(kparams->total_rows, htp_tensor_mdev_data_aligned(dst) ? kparams->rows_per_chunk : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( + kparams->total_rows, 1, + octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); row_start = range.start; nrows = range.count; } @@ -126,6 +183,13 @@ int op_fill(struct htp_ops_context * octx) { const uint32_t n_hvx = octx->n_hvx; + struct htp_fill_vtcm_layout layout; + htp_fill_vtcm_layout_build(&layout, kparams->tile_bytes, n_hvx); + if (octx->ctx->vtcm_size < layout.total_bytes) { + FARF(ERROR, "fill: VTCM size %zu is too small, needed %zu\n", octx->ctx->vtcm_size, layout.total_bytes); + return HTP_STATUS_VTCM_TOO_SMALL; + } + FARF(HIGH, "fill: (%ux%ux%ux%u) type=%u ktype=%u\n", dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3], dst->type, kparams->kernel_type); @@ -133,21 +197,28 @@ int op_fill(struct htp_ops_context * octx) { memcpy(&val_f32, &octx->op_params[0], sizeof(float)); struct htp_fill_context fctx = { - .octx = octx, - .kparams = kparams, - .nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div), - .total_rows = nrows, - .row_start = row_start, - .elem_size = kparams->elem_size, + .octx = octx, + .kparams = kparams, + .data_dst = (dma_addr_t) dst->data, + .vtcm_tile = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_tile), + .tile_bytes = layout.tile_bytes, + .nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div), + .total_rows = nrows, + .row_start = row_start, + .elem_size = kparams->elem_size, }; switch (dst->type) { case HTP_TYPE_F32: - fctx.splat_vec = hvx_vec_splat_f32(val_f32); + memcpy(&fctx.splat_bits, &val_f32, sizeof(uint32_t)); break; - case HTP_TYPE_F16: - fctx.splat_vec = hvx_vec_splat_f16((_Float16) val_f32); + case HTP_TYPE_F16: { + const _Float16 val_f16 = (_Float16) val_f32; + uint16_t bits16 = 0; + memcpy(&bits16, &val_f16, sizeof(uint16_t)); + fctx.splat_bits = bits16; break; + } default: return HTP_STATUS_NO_SUPPORT; } diff --git a/ggml/src/ggml-hexagon/htp/fill-ops.h b/ggml/src/ggml-hexagon/htp/fill-ops.h index 06fe082092b0..b19f23e1f17e 100644 --- a/ggml/src/ggml-hexagon/htp/fill-ops.h +++ b/ggml/src/ggml-hexagon/htp/fill-ops.h @@ -1,7 +1,10 @@ #ifndef HTP_FILL_OPS_H #define HTP_FILL_OPS_H +#include "hex-common.h" #include "hex-fastdiv.h" +#include "htp-vtcm.h" +#include #include enum htp_fill_kernel_type { @@ -9,12 +12,31 @@ enum htp_fill_kernel_type { HTP_FILL_KERNEL_STRIDED = 1, }; +struct htp_fill_vtcm_layout { + size_t tile_bytes; + size_t off_tile; + size_t total_bytes; +}; + +static inline void htp_fill_vtcm_layout_build( + struct htp_fill_vtcm_layout * L, + size_t tile_bytes, + uint32_t n_hvx +) { + size_t off = 0; + + L->tile_bytes = hex_round_up(tile_bytes, 128); + VTCM_LAYOUT_ALLOC(off, off_tile, (size_t) n_hvx * L->tile_bytes); + L->total_bytes = off; +} + struct htp_fill_kernel_params { uint8_t kernel_type; uint32_t n_hvx; uint32_t total_rows; uint32_t elem_size; - uint32_t rows_per_chunk; + uint32_t tile_bytes; + uint32_t vtcm_size; struct fastdiv_values div_ne1; struct fastdiv_values div_ne1_ne2; diff --git a/ggml/src/ggml-hexagon/htp/flash-attn-ops.c b/ggml/src/ggml-hexagon/htp/flash-attn-ops.c index 6506f28fc7d2..bb0cd2c9e4af 100644 --- a/ggml/src/ggml-hexagon/htp/flash-attn-ops.c +++ b/ggml/src/ggml-hexagon/htp/flash-attn-ops.c @@ -1,7 +1,3 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include #include @@ -35,6 +31,7 @@ #include "flash-attn-ops.h" #include "hvx-fa-kernels.h" #include "hmx-fa-kernels.h" +#include "hmx-fa-w8a8-kernels.h" // Must be multiple of 32 #define FLASH_ATTN_BLOCK_SIZE (32 * 2) @@ -45,6 +42,8 @@ struct hvx_fa_ddr_spad { __fp16 slopes[512]; uint16_t active_blocks[FA_MAX_KV_BLOCKS]; uint16_t thread_active_blocks[HTP_MAX_NHVX][FA_MAX_KV_BLOCKS] __attribute__((aligned(128))); + float split_m[HTP_MAX_NHVX][FA_HVX_G_MAX] __attribute__((aligned(128))); + float split_s[HTP_MAX_NHVX][FA_HVX_G_MAX] __attribute__((aligned(128))); }; struct hmx_fa_ddr_spad { @@ -98,6 +97,11 @@ struct htp_fa_context { uint32_t qrows_per_hvx; uint32_t qrow_start; + uint32_t kv_head_start; + uint32_t n_kv_local; + uint32_t G; + uint32_t splits_per_kv; + bool is_q_fp32; size_t size_q_block; @@ -123,10 +127,12 @@ struct hmx_fa_context { const struct htp_tensor * k; const struct htp_tensor * v; bool pipeline; // true when n_kv_blocks >= FA_MIN_KV_BLOCKS && n_hvx >= 2 + bool is_w8a8; uint32_t n_hvx; // Op parameters __fp16 scale; + float scale_f32; float max_bias; bool has_softcap; __fp16 logit_softcap; @@ -177,6 +183,18 @@ struct hmx_fa_context { __fp16 * vtcm_mask_buf; // VTCM mask buffer [Br * m_line], DMA'd per KV block __fp16 * vtcm_slopes; // ALiBi slopes [g_br] float * vtcm_sinks; // Attention sinks + float * vtcm_q_scales; // W8A8 Q per-row scales [g_br] + float * vtcm_k_scales[2]; // W8A8 K per-col scales [Bc] + uint8_t * vtcm_k_bias[2]; // W8A8 K HMX bias banks [n_col_tiles * 2 * 256] + float * vtcm_o_f32; // W8A8 FP32 O accumulator [g_br, DV] + uint8_t * vtcm_do_tiles; // W8A8 PV output tiles [n_row_tiles_64, DV/32, 2] + float * vtcm_v_scales[2]; // W8A8 V per-col scales [DV] + uint8_t * vtcm_v_bias[2]; // W8A8 V HMX bias banks [DV/32 * 2 * 256] + float * vtcm_p_scales[2]; // W8A8 P per-row scales [g_br] + float * vtcm_exp_mdiff[2]; // W8A8 exp2(m_prev - m_curr) [g_br] + size_t k_raw_row_padded; // W8A8 raw Q8_0 K row stride in VTCM + size_t v_raw_row_padded; // W8A8 raw Q8_0 V row stride in VTCM + size_t o_f32_bytes; __fp16 * ddr_slopes; // ALiBi slopes staging buffer in DDR [g_br] size_t row_buf_stride; // HVX vectors per row buffer (Bc/64) size_t mask_buf_row_stride; // elements (__fp16) per row in mask buffer @@ -260,6 +278,332 @@ static uint32_t fa_scan_active_blocks( return n_active; } +static __attribute__((noinline)) void fa_hvx_zero_acc(float * dst, uint32_t n) { + hvx_splat_f32_a((uint8_t *) dst, 0, n); +} + +static __attribute__((noinline)) void fa_hvx_q_f32_to_f16(uint8_t * dst, uint32_t DK) { + hvx_copy_f16_f32_aa(dst, dst, DK); +} + +static __attribute__((noinline)) float fa_hvx_exp_scalar(float x) { + return hvx_vec_get_f32(hvx_vec_exp_f32(hvx_vec_splat_f32(x))); +} + +static __attribute__((noinline)) void fa_hvx_split_exp_weights(float * dst, const float * src) { + *(HVX_Vector *) dst = hvx_vec_exp_f32(*(const HVX_Vector *) src); +} + +static __attribute__((noinline)) void fa_hvx_dequant_q8_0_block( + uint8_t * base, + size_t row_stride, + uint32_t n_rows, + uint32_t dim) { + for (uint32_t r = 0; r < n_rows; ++r) { + __fp16 * row = (__fp16 *) (base + r * row_stride); + hvx_dequantize_row_flat_q8_0_f16(row, row, dim); + } +} + +// Accumulate PV in dealt HVX_VectorPair order. +static __attribute__((always_inline)) inline void fa_hvx_pv_accum_fixed( + float * restrict vkq, + const uint8_t * restrict v_base, + size_t v_stride, + HVX_Vector P, + HVX_Vector ms_vec, + uint32_t block_size, + const uint32_t n_pairs) { + HVX_VectorPair * restrict vp = (HVX_VectorPair *) vkq; + HVX_VectorPair acc[4]; + + #pragma clang loop unroll(full) + for (uint32_t p = 0; p < n_pairs; ++p) { + acc[p] = Q6_W_vcombine_VV( + HVX_OP_MUL_F32(Q6_V_hi_W(vp[p]), ms_vec), + HVX_OP_MUL_F32(Q6_V_lo_W(vp[p]), ms_vec) + ); + } + + const uint8_t * v_ptr = v_base; + const size_t stride2 = v_stride * 2; + uint32_t j = 0; + for (; j + 1 < block_size; j += 2) { + const HVX_Vector S0 = hvx_vec_repl_f16(Q6_V_vror_VR(P, j * 2)); + const HVX_Vector S1 = hvx_vec_repl_f16(Q6_V_vror_VR(P, (j + 1) * 2)); + const HVX_Vector * vx0 = (const HVX_Vector *) v_ptr; + const HVX_Vector * vx1 = (const HVX_Vector *) (v_ptr + v_stride); + + #pragma clang loop unroll(full) + for (uint32_t p = 0; p < n_pairs; ++p) { + acc[p] = hvx_vec_mpyacc_f32_f16(acc[p], vx0[p], S0); + acc[p] = hvx_vec_mpyacc_f32_f16(acc[p], vx1[p], S1); + } + v_ptr += stride2; + } + if (j < block_size) { + const HVX_Vector S0 = hvx_vec_repl_f16(Q6_V_vror_VR(P, j * 2)); + const HVX_Vector * vx0 = (const HVX_Vector *) v_ptr; + #pragma clang loop unroll(full) + for (uint32_t p = 0; p < n_pairs; ++p) { + acc[p] = hvx_vec_mpyacc_f32_f16(acc[p], vx0[p], S0); + } + } + + #pragma clang loop unroll(full) + for (uint32_t p = 0; p < n_pairs; ++p) { + vp[p] = acc[p]; + } +} + +static __attribute__((noinline)) void fa_hvx_pv_accum_64( + float * restrict vkq, const uint8_t * restrict v_base, size_t v_stride, + HVX_Vector P, HVX_Vector ms_vec, uint32_t block_size) { + fa_hvx_pv_accum_fixed(vkq, v_base, v_stride, P, ms_vec, block_size, 1); +} + +static __attribute__((noinline)) void fa_hvx_pv_accum_128( + float * restrict vkq, const uint8_t * restrict v_base, size_t v_stride, + HVX_Vector P, HVX_Vector ms_vec, uint32_t block_size) { + fa_hvx_pv_accum_fixed(vkq, v_base, v_stride, P, ms_vec, block_size, 2); +} + +static __attribute__((noinline)) void fa_hvx_pv_accum_256( + float * restrict vkq, const uint8_t * restrict v_base, size_t v_stride, + HVX_Vector P, HVX_Vector ms_vec, uint32_t block_size) { + fa_hvx_pv_accum_fixed(vkq, v_base, v_stride, P, ms_vec, block_size, 4); +} + +static __attribute__((noinline)) void fa_hvx_pv_accum_generic( + float * restrict vkq, + const uint8_t * restrict v_base, + size_t v_stride, + HVX_Vector P, + HVX_Vector ms_vec, + uint32_t block_size, + uint32_t DV) { + const uint32_t n_pairs = (DV + 63) / 64; + HVX_VectorPair * restrict vp = (HVX_VectorPair *) vkq; + for (uint32_t p = 0; p < n_pairs; ++p) { + HVX_VectorPair v = vp[p]; + vp[p] = Q6_W_vcombine_VV( + HVX_OP_MUL_F32(Q6_V_hi_W(v), ms_vec), + HVX_OP_MUL_F32(Q6_V_lo_W(v), ms_vec) + ); + } + + const uint8_t * v_ptr = v_base; + const size_t stride2 = v_stride * 2; + uint32_t j = 0; + for (; j + 1 < block_size; j += 2) { + const HVX_Vector S0 = hvx_vec_repl_f16(Q6_V_vror_VR(P, j * 2)); + const HVX_Vector S1 = hvx_vec_repl_f16(Q6_V_vror_VR(P, (j + 1) * 2)); + const HVX_Vector * vx0 = (const HVX_Vector *) v_ptr; + const HVX_Vector * vx1 = (const HVX_Vector *) (v_ptr + v_stride); + for (uint32_t p = 0; p < n_pairs; ++p) { + HVX_VectorPair acc = vp[p]; + acc = hvx_vec_mpyacc_f32_f16(acc, vx0[p], S0); + acc = hvx_vec_mpyacc_f32_f16(acc, vx1[p], S1); + vp[p] = acc; + } + v_ptr += stride2; + } + if (j < block_size) { + const HVX_Vector S0 = hvx_vec_repl_f16(Q6_V_vror_VR(P, j * 2)); + const HVX_Vector * vx0 = (const HVX_Vector *) v_ptr; + for (uint32_t p = 0; p < n_pairs; ++p) { + vp[p] = hvx_vec_mpyacc_f32_f16(vp[p], vx0[p], S0); + } + } +} + +static inline void fa_hvx_pv_accum( + float * restrict vkq, + const uint8_t * restrict v_base, + size_t v_stride, + HVX_Vector P, + HVX_Vector ms_vec, + uint32_t block_size, + uint32_t DV) { + if (DV == 64) { + fa_hvx_pv_accum_64(vkq, v_base, v_stride, P, ms_vec, block_size); + } else if (DV == 128) { + fa_hvx_pv_accum_128(vkq, v_base, v_stride, P, ms_vec, block_size); + } else if (DV == 256) { + fa_hvx_pv_accum_256(vkq, v_base, v_stride, P, ms_vec, block_size); + } else { + fa_hvx_pv_accum_generic(vkq, v_base, v_stride, P, ms_vec, block_size, DV); + } +} + +static __attribute__((noinline)) void fa_hvx_finalize_dealt_row_f32( + void * dst, + const float * src, + uint32_t DV, + float scale_out) { + const uint32_t n_pairs = (DV + 63) / 64; + const HVX_Vector v_scale = hvx_vec_splat_f32(scale_out); + const HVX_VectorPair * vp_src = (const HVX_VectorPair *) src; + HVX_VectorPair * vp_dst = (HVX_VectorPair *) dst; + + for (uint32_t p = 0; p < n_pairs; ++p) { + const HVX_VectorPair vp = vp_src[p]; + const HVX_Vector lo = HVX_OP_MUL_F32(Q6_V_lo_W(vp), v_scale); + const HVX_Vector hi = HVX_OP_MUL_F32(Q6_V_hi_W(vp), v_scale); + vp_dst[p] = Q6_W_vshuff_VVR(hi, lo, -4); + } +} + +static __attribute__((noinline)) void fa_hvx_finalize_dealt_row_f16( + void * dst, + const float * src, + uint32_t DV, + float scale_out) { + const uint32_t n_pairs = (DV + 63) / 64; + const HVX_Vector v_scale = hvx_vec_splat_f32(scale_out); + const HVX_VectorPair * vp_src = (const HVX_VectorPair *) src; + HVX_Vector * v_dst = (HVX_Vector *) dst; + + for (uint32_t p = 0; p < n_pairs; ++p) { + const HVX_VectorPair vp = vp_src[p]; + const HVX_Vector lo = HVX_OP_MUL_F32(Q6_V_lo_W(vp), v_scale); + const HVX_Vector hi = HVX_OP_MUL_F32(Q6_V_hi_W(vp), v_scale); + v_dst[p] = hvx_vec_f32_to_f16_shuff(lo, hi); + } +} + +static __attribute__((always_inline)) inline HVX_VectorPair fa_hvx_merge_dealt_pair( + const uint8_t * restrict src_ptr, + size_t worker_stride, + uint32_t n_splits, + const float * restrict scales) { + HVX_Vector v_lo = Q6_V_vzero(); + HVX_Vector v_hi = Q6_V_vzero(); + for (uint32_t s = 0; s < n_splits; ++s) { + const HVX_VectorPair vp = *(const HVX_VectorPair *) src_ptr; + const HVX_Vector vs = hvx_vec_splat_f32(scales[s]); + v_lo = HVX_OP_ADD_F32(v_lo, HVX_OP_MUL_F32(Q6_V_lo_W(vp), vs)); + v_hi = HVX_OP_ADD_F32(v_hi, HVX_OP_MUL_F32(Q6_V_hi_W(vp), vs)); + src_ptr += worker_stride; + } + return Q6_W_vcombine_VV(v_hi, v_lo); +} + +static __attribute__((noinline)) void fa_hvx_merge_and_store_row_f32( + void * restrict dst, + const uint8_t * restrict spad_a_base, + size_t worker_stride, + uint32_t n_splits, + const float * restrict scales, + uint32_t DV) { + const uint32_t n_pairs = (DV + 63) / 64; + HVX_VectorPair * restrict vp_dst = (HVX_VectorPair *) dst; + + for (uint32_t p = 0; p < n_pairs; ++p) { + const HVX_VectorPair sum = fa_hvx_merge_dealt_pair(spad_a_base + p * sizeof(HVX_VectorPair), worker_stride, n_splits, scales); + vp_dst[p] = Q6_W_vshuff_VVR(Q6_V_hi_W(sum), Q6_V_lo_W(sum), -4); + } +} + +static __attribute__((noinline)) void fa_hvx_merge_and_store_row_f16( + void * restrict dst, + const uint8_t * restrict spad_a_base, + size_t worker_stride, + uint32_t n_splits, + const float * restrict scales, + uint32_t DV) { + const uint32_t n_pairs = (DV + 63) / 64; + HVX_Vector * restrict v_dst = (HVX_Vector *) dst; + + for (uint32_t p = 0; p < n_pairs; ++p) { + const HVX_VectorPair sum = fa_hvx_merge_dealt_pair(spad_a_base + p * sizeof(HVX_VectorPair), worker_stride, n_splits, scales); + v_dst[p] = hvx_vec_f32_to_f16_shuff(Q6_V_lo_W(sum), Q6_V_hi_W(sum)); + } +} + +static __attribute__((noinline)) void fa_hvx_qk_block( + const struct htp_fa_context * factx, + const uint8_t * restrict q_ptr, + const uint8_t * restrict k_base, + const __fp16 * restrict m_base, + uint32_t block_size, + uint16_t slope_bits, + void * restrict out_scores) { + const uint32_t DK = factx->k->ne[0]; + const size_t k_stride = factx->size_k_row_padded; + + HVX_Vector scores_f16 = Q6_V_vzero(); + if (block_size > 0) { + HVX_Vector scores0 = hvx_dot_f16_f16_aa_rx32(q_ptr, k_base, k_stride, DK, factx->scale); + HVX_Vector scores1 = (block_size > 32) + ? hvx_dot_f16_f16_aa_rx32(q_ptr, k_base + 32 * k_stride, k_stride, DK, factx->scale) + : Q6_V_vzero(); + scores_f16 = hvx_vec_f32_to_f16(scores0, scores1); + } + + if (factx->has_softcap) { + scores_f16 = hvx_vec_tanh_f16(scores_f16); + scores_f16 = hvx_vec_mul_f16_f16(scores_f16, hvx_vec_splat_f16(factx->logit_softcap)); + } + + const HVX_Vector v_neg_inf = Q6_Vh_vsplat_R(0xfbff); + const HVX_VectorPred q_tail_keep = Q6_Q_vsetq2_R(block_size * sizeof(__fp16)); + + if (m_base) { + const HVX_Vector vinf = Q6_Vh_vsplat_R(0xFC00); + const HVX_Vector vmin = Q6_Vh_vsplat_R(0xFBFF); + HVX_Vector m_vals_f16 = *(const HVX_UVector *) m_base; + HVX_VectorPred is_inf = Q6_Q_vcmp_eq_VhVh(m_vals_f16, vinf); + m_vals_f16 = Q6_V_vmux_QVV(is_inf, vmin, m_vals_f16); + + HVX_Vector m_scaled = hvx_vec_mul_f16_f16(m_vals_f16, Q6_Vh_vsplat_R(slope_bits)); + scores_f16 = Q6_V_vmux_QVV(q_tail_keep, hvx_vec_add_f16_f16(scores_f16, m_scaled), v_neg_inf); + } else { + scores_f16 = Q6_V_vmux_QVV(q_tail_keep, scores_f16, v_neg_inf); + } + + *(HVX_Vector *) out_scores = scores_f16; +} + +static __attribute__((noinline)) void fa_hvx_sfm_pv_block( + const struct htp_fa_context * factx, + float * restrict vkq, + const uint8_t * restrict v_base, + const void * restrict in_scores, + uint32_t block_size, + float * restrict io_m, + float * restrict io_s) { + const HVX_Vector scores_f16 = *(const HVX_Vector *) in_scores; + const HVX_Vector v_log2e = hvx_vec_splat_f16(EXP_LOG2E_F); + const HVX_VectorPred q_tail_keep = Q6_Q_vsetq2_R(block_size * sizeof(__fp16)); + + const HVX_Vector v_max_f16 = hvx_vec_reduce_max_f16(scores_f16); + const HVX_Vector v_max = Q6_V_lo_W(hvx_vec_f16_to_f32(v_max_f16)); + + const HVX_Vector m_prev = hvx_vec_splat_f32(*io_m); + const HVX_Vector s_prev = hvx_vec_splat_f32(*io_s); + const HVX_Vector m_new = Q6_Vsf_vmax_VsfVsf(v_max, m_prev); + const HVX_Vector diff_vec = HVX_OP_SUB_F32(m_prev, m_new); + const HVX_Vector diff_f16 = hvx_vec_f32_to_f16(diff_vec, diff_vec); + const HVX_Vector ms_f16 = hvx_vec_exp2_neg_f16(hvx_vec_mul_f16_f16(diff_f16, v_log2e)); + const HVX_Vector ms_vec = Q6_V_lo_W(hvx_vec_f16_to_f32(ms_f16)); + + const HVX_Vector v_m_f16 = hvx_vec_f32_to_f16(m_new, m_new); + const HVX_Vector v_sm = Q6_Vqf16_vsub_VhfVhf(scores_f16, v_m_f16); + const HVX_Vector v_sm_b2 = hvx_vec_mul_f16_f16(Q6_Vhf_equals_Vqf16(v_sm), v_log2e); + HVX_Vector P = hvx_vec_exp2_neg_f16(v_sm_b2); + P = Q6_V_vmux_QVV(q_tail_keep, P, Q6_V_vzero()); + + const HVX_VectorPair P_pair = hvx_vec_f16_to_f32(P); + const HVX_Vector p_sum_vec = hvx_vec_reduce_sum_f32(HVX_OP_ADD_F32(Q6_V_lo_W(P_pair), Q6_V_hi_W(P_pair))); + const HVX_Vector s_new = HVX_OP_ADD_F32(HVX_OP_MUL_F32(s_prev, ms_vec), p_sum_vec); + + *io_m = hvx_vec_get_f32(m_new); + *io_s = hvx_vec_get_f32(s_new); + + fa_hvx_pv_accum(vkq, v_base, factx->size_v_row_padded, P, ms_vec, block_size, factx->v->ne[0]); +} + static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { struct htp_fa_context * factx = (struct htp_fa_context *) data; const struct htp_ops_context * octx = factx->octx; @@ -270,20 +614,13 @@ static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth, const struct htp_tensor * sinks = octx->src[4]; const struct htp_tensor * dst = octx->dst; - const uint32_t neq0 = q->ne[0]; const uint32_t neq1 = q->ne[1]; const uint32_t neq2 = q->ne[2]; - const uint32_t neq3 = q->ne[3]; const uint32_t nek0 = k->ne[0]; const uint32_t nek1 = k->ne[1]; - const uint32_t nek2 = k->ne[2]; - const uint32_t nek3 = k->ne[3]; const uint32_t nev0 = v->ne[0]; - const uint32_t nev1 = v->ne[1]; - const uint32_t nev2 = v->ne[2]; - const uint32_t nev3 = v->ne[3]; const uint32_t nbq1 = q->nb[1]; const uint32_t nbq2 = q->nb[2]; @@ -297,14 +634,6 @@ static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth, const uint32_t nbv2 = v->nb[2]; const uint32_t nbv3 = v->nb[3]; - const uint32_t ne1 = dst->ne[1]; - const uint32_t ne2 = dst->ne[2]; - const uint32_t ne3 = dst->ne[3]; - - const uint32_t nb1 = dst->nb[1]; - const uint32_t nb2 = dst->nb[2]; - const uint32_t nb3 = dst->nb[3]; - // total rows in q const uint32_t dr = factx->qrows_per_hvx; const uint32_t ir0 = factx->qrow_start + dr * ith; @@ -319,7 +648,7 @@ static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth, const uint32_t DK = nek0; const uint32_t DV = nev0; - const size_t size_q_row = DK * ((q->type == HTP_TYPE_F32) ? 4 : 2); + const size_t size_q_row = htp_tensor_get_row_size(q->type, DK); const size_t size_k_row = htp_tensor_get_row_size(k->type, DK); const size_t size_v_row = htp_tensor_get_row_size(v->type, DV); @@ -345,7 +674,8 @@ static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth, } } - const size_t size_vkq_acc_single = hex_round_up(DV * sizeof(float), 128); + const size_t size_vkq_acc_single = hex_round_up(DV * sizeof(float), 256); + const uint32_t dv_zero_elems = ((DV + 63) / 64) * 64; uint32_t ir = ir0; while (ir < ir1) { @@ -393,12 +723,13 @@ static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth, } } - uint32_t heads[FA_HVX_G_MAX]; - HVX_Vector slope_vecs[FA_HVX_G_MAX] __attribute__((aligned(128))); - HVX_Vector S_vec[FA_HVX_G_MAX] __attribute__((aligned(128))); - HVX_Vector M_vec[FA_HVX_G_MAX] __attribute__((aligned(128))); + uint8_t scores_buf[128] __attribute__((aligned(128))); + uint32_t heads[FA_HVX_G_MAX]; + uint16_t slopes[FA_HVX_G_MAX]; + float S_vals[FA_HVX_G_MAX]; + float M_vals[FA_HVX_G_MAX]; uint8_t * q_ptrs[FA_HVX_G_MAX]; - float * vkq_ptrs[FA_HVX_G_MAX]; + float * vkq_ptrs[FA_HVX_G_MAX]; for (uint32_t g = 0; g < G_local; ++g) { const uint32_t r = ir + g; @@ -406,19 +737,17 @@ static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth, const uint32_t r_iq2 = fastdiv(r - r_iq3*neq2*neq1, &factx->src0_div1); const uint32_t r_iq1 = (r - r_iq3*neq2*neq1 - r_iq2 * neq1); - heads[g] = r_iq2; - const __fp16 slope = factx->ddr->slopes[r_iq2]; - slope_vecs[g] = hvx_vec_splat_f16(slope); - - S_vec[g] = hvx_vec_splat_f32(0.0f); - M_vec[g] = hvx_vec_splat_f32(HTP_FA_M_INITIAL_VAL); + heads[g] = r_iq2; + memcpy(&slopes[g], &factx->ddr->slopes[r_iq2], sizeof(uint16_t)); + S_vals[g] = 0.0f; + M_vals[g] = HTP_FA_M_INITIAL_VAL; uint8_t * q_dst = spad_q + g * factx->size_q_row_padded; q_ptrs[g] = q_dst; float * vkq_dst = (float *)(spad_a + g * size_vkq_acc_single); vkq_ptrs[g] = vkq_dst; - hvx_splat_f32_a((uint8_t *) vkq_dst, 0, DV); + fa_hvx_zero_acc(vkq_dst, dv_zero_elems); // Fetch Q row g const dma_addr_t q_row_ptr = q->data + r_iq1*nbq1 + r_iq2*nbq2 + r_iq3*nbq3; @@ -452,18 +781,10 @@ static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth, for (uint32_t g = 0; g < G_local; ++g) { uint8_t * q_ptr_vtcm = (void *) dma_queue_pop(dma_q).dst; if (factx->is_q_fp32) { - hvx_copy_f16_f32_aa(q_ptr_vtcm, q_ptr_vtcm, DK); + fa_hvx_q_f32_to_f16(q_ptr_vtcm, DK); } } - const HVX_Vector v_neg_inf = Q6_Vh_vsplat_R(0xfbff); - const bool has_softcap = factx->has_softcap; - const HVX_Vector v_cap = has_softcap ? hvx_vec_splat_f16(factx->logit_softcap) : Q6_V_vzero(); - const HVX_Vector vinf = Q6_Vh_vsplat_R(0xFC00); - const HVX_Vector vmin = Q6_Vh_vsplat_R(0xFBFF); - const HVX_Vector v_log2e = hvx_vec_splat_f16(EXP_LOG2E_F); - const uint32_t stride_v2 = factx->size_v_row_padded * 2; - for (uint32_t step = 0; step < n_active_blocks; ++step) { const uint32_t ib = active_blocks[step]; const uint32_t ic_start = ib * FLASH_ATTN_BLOCK_SIZE; @@ -476,56 +797,20 @@ static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth, if (factx->k->type == HTP_TYPE_Q8_0) { htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_K_PREP, ir); - for (uint32_t r = 0; r < current_block_size; ++r) { - __fp16 * row_k = (__fp16 *)(k_base + r * factx->size_k_row_padded); - hvx_dequantize_row_flat_q8_0_f16(row_k, row_k, DK); - } + fa_hvx_dequant_q8_0_block(k_base, factx->size_k_row_padded, current_block_size, DK); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_K_PREP, ir); } if (factx->v->type == HTP_TYPE_Q8_0) { htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_V_PREP, ir); - for (uint32_t r = 0; r < current_block_size; ++r) { - __fp16 * row_v = (__fp16 *)(v_base + r * factx->size_v_row_padded); - hvx_dequantize_row_flat_q8_0_f16(row_v, row_v, DV); - } + fa_hvx_dequant_q8_0_block(v_base, factx->size_v_row_padded, current_block_size, DV); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_V_PREP, ir); } for (uint32_t g = 0; g < G_local; ++g) { const uint32_t head_ir = ir + g; - uint8_t * q_ptr_vtcm = q_ptrs[g]; - float * VKQ32 = vkq_ptrs[g]; - const HVX_Vector slope_vec = slope_vecs[g]; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_QK, head_ir); - - HVX_Vector scores_f16 = Q6_V_vzero(); - if (current_block_size > 0) { - HVX_Vector scores0 = hvx_dot_f16_f16_aa_rx32(q_ptr_vtcm, k_base, factx->size_k_row_padded, DK, factx->scale); - HVX_Vector scores1 = (current_block_size > 32) ? hvx_dot_f16_f16_aa_rx32(q_ptr_vtcm, k_base + 32 * factx->size_k_row_padded, factx->size_k_row_padded, DK, factx->scale) : Q6_V_vzero(); - scores_f16 = hvx_vec_f32_to_f16(scores0, scores1); - } - - if (has_softcap) { - scores_f16 = hvx_vec_tanh_f16(scores_f16); - scores_f16 = hvx_vec_mul_f16_f16(scores_f16, v_cap); - } - - HVX_VectorPred q_tail_keep = Q6_Q_vsetq2_R(current_block_size * sizeof(__fp16)); - - if (mask) { - HVX_Vector m_vals_f16 = *(const HVX_UVector *) m_base; - HVX_VectorPred is_inf = Q6_Q_vcmp_eq_VhVh(m_vals_f16, vinf); - m_vals_f16 = Q6_V_vmux_QVV(is_inf, vmin, m_vals_f16); - - HVX_Vector m_scaled = hvx_vec_mul_f16_f16(m_vals_f16, slope_vec); - scores_f16 = Q6_V_vmux_QVV(q_tail_keep, hvx_vec_add_f16_f16(scores_f16, m_scaled), v_neg_inf); - } else { - scores_f16 = Q6_V_vmux_QVV(q_tail_keep, scores_f16, v_neg_inf); - } - - HVX_Vector v_max_f16 = hvx_vec_reduce_max_f16(scores_f16); - HVX_Vector v_max = Q6_V_lo_W(hvx_vec_f16_to_f32(v_max_f16)); + fa_hvx_qk_block(factx, q_ptrs[g], k_base, m_base, current_block_size, slopes[g], scores_buf); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_QK, head_ir); // prefetch K for step + 2 after last head finished QK @@ -539,156 +824,7 @@ static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth, } htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_SFM, head_ir); - { - HVX_Vector M_new_vec = Q6_Vsf_vmax_VsfVsf(v_max, M_vec[g]); - HVX_Vector diff_vec = HVX_OP_SUB_F32(M_vec[g], M_new_vec); - - HVX_Vector diff_f16 = hvx_vec_f32_to_f16(diff_vec, diff_vec); - HVX_Vector diff_base2 = hvx_vec_mul_f16_f16(diff_f16, v_log2e); - HVX_Vector ms_f16 = hvx_vec_exp2_f16(diff_base2); - HVX_Vector ms_vec = Q6_V_lo_W(hvx_vec_f16_to_f32(ms_f16)); - - M_vec[g] = M_new_vec; - - HVX_Vector v_m_vec_f16 = hvx_vec_f32_to_f16(M_vec[g], M_vec[g]); - HVX_Vector v_s_minus_m = Q6_Vqf16_vsub_VhfVhf(scores_f16, v_m_vec_f16); - HVX_Vector v_s_minus_m_base2 = hvx_vec_mul_f16_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m), v_log2e); - - HVX_Vector P = hvx_vec_exp2_f16(v_s_minus_m_base2); - P = Q6_V_vmux_QVV(q_tail_keep, P, Q6_V_vzero()); - - HVX_VectorPair P_pair = hvx_vec_f16_to_f32(P); - HVX_Vector P0 = Q6_V_lo_W(P_pair); - HVX_Vector P1 = Q6_V_hi_W(P_pair); - HVX_Vector p_sum_vec = hvx_vec_reduce_sum_f32(HVX_OP_ADD_F32(P0, P1)); - - S_vec[g] = HVX_OP_ADD_F32(HVX_OP_MUL_F32(S_vec[g], ms_vec), p_sum_vec); - - const uint8_t * v_ptr = v_base; - - if (DV == 64) { - HVX_VectorPair vkq0 = *((const HVX_VectorPair *) VKQ32); - vkq0 = Q6_W_vcombine_VV( - HVX_OP_MUL_F32(Q6_V_hi_W(vkq0), ms_vec), - HVX_OP_MUL_F32(Q6_V_lo_W(vkq0), ms_vec) - ); - - for (uint32_t j = 0; j < current_block_size; j += 2) { - HVX_Vector S0 = hvx_vec_repl_f16(Q6_V_vror_VR(P, j * 2)); - const HVX_Vector * vx0 = (const HVX_Vector *) v_ptr; - if (j + 1 == current_block_size) { - vkq0 = hvx_vec_mpyacc_f32_f16(vkq0, Q6_Vh_vshuff_Vh(vx0[0]), S0); - break; - } - - HVX_Vector S1 = hvx_vec_repl_f16(Q6_V_vror_VR(P, (j + 1) * 2)); - const HVX_Vector * vx1 = (const HVX_Vector *) (v_ptr + factx->size_v_row_padded); - vkq0 = hvx_vec_mpyacc_f32_f16(vkq0, Q6_Vh_vshuff_Vh(vx0[0]), S0); - vkq0 = hvx_vec_mpyacc_f32_f16(vkq0, Q6_Vh_vshuff_Vh(vx1[0]), S1); - v_ptr += stride_v2; - } - - *((HVX_VectorPair *) VKQ32) = vkq0; - } else if (DV == 128) { - HVX_VectorPair vkq0 = ((const HVX_VectorPair *) VKQ32)[0]; - HVX_VectorPair vkq1 = ((const HVX_VectorPair *) VKQ32)[1]; - vkq0 = Q6_W_vcombine_VV( - HVX_OP_MUL_F32(Q6_V_hi_W(vkq0), ms_vec), - HVX_OP_MUL_F32(Q6_V_lo_W(vkq0), ms_vec) - ); - vkq1 = Q6_W_vcombine_VV( - HVX_OP_MUL_F32(Q6_V_hi_W(vkq1), ms_vec), - HVX_OP_MUL_F32(Q6_V_lo_W(vkq1), ms_vec) - ); - - for (uint32_t j = 0; j < current_block_size; j += 2) { - HVX_Vector S0 = hvx_vec_repl_f16(Q6_V_vror_VR(P, j * 2)); - const HVX_Vector * vx0 = (const HVX_Vector *) v_ptr; - if (j + 1 == current_block_size) { - vkq0 = hvx_vec_mpyacc_f32_f16(vkq0, Q6_Vh_vshuff_Vh(vx0[0]), S0); - vkq1 = hvx_vec_mpyacc_f32_f16(vkq1, Q6_Vh_vshuff_Vh(vx0[1]), S0); - break; - } - - HVX_Vector S1 = hvx_vec_repl_f16(Q6_V_vror_VR(P, (j + 1) * 2)); - const HVX_Vector * vx1 = (const HVX_Vector *) (v_ptr + factx->size_v_row_padded); - vkq0 = hvx_vec_mpyacc_f32_f16(vkq0, Q6_Vh_vshuff_Vh(vx0[0]), S0); - vkq0 = hvx_vec_mpyacc_f32_f16(vkq0, Q6_Vh_vshuff_Vh(vx1[0]), S1); - vkq1 = hvx_vec_mpyacc_f32_f16(vkq1, Q6_Vh_vshuff_Vh(vx0[1]), S0); - vkq1 = hvx_vec_mpyacc_f32_f16(vkq1, Q6_Vh_vshuff_Vh(vx1[1]), S1); - v_ptr += stride_v2; - } - - ((HVX_VectorPair *) VKQ32)[0] = vkq0; - ((HVX_VectorPair *) VKQ32)[1] = vkq1; - } else if (DV == 256) { - HVX_VectorPair vkq0 = ((const HVX_VectorPair *) VKQ32)[0]; - HVX_VectorPair vkq1 = ((const HVX_VectorPair *) VKQ32)[1]; - HVX_VectorPair vkq2 = ((const HVX_VectorPair *) VKQ32)[2]; - HVX_VectorPair vkq3 = ((const HVX_VectorPair *) VKQ32)[3]; - vkq0 = Q6_W_vcombine_VV( - HVX_OP_MUL_F32(Q6_V_hi_W(vkq0), ms_vec), - HVX_OP_MUL_F32(Q6_V_lo_W(vkq0), ms_vec) - ); - vkq1 = Q6_W_vcombine_VV( - HVX_OP_MUL_F32(Q6_V_hi_W(vkq1), ms_vec), - HVX_OP_MUL_F32(Q6_V_lo_W(vkq1), ms_vec) - ); - vkq2 = Q6_W_vcombine_VV( - HVX_OP_MUL_F32(Q6_V_hi_W(vkq2), ms_vec), - HVX_OP_MUL_F32(Q6_V_lo_W(vkq2), ms_vec) - ); - vkq3 = Q6_W_vcombine_VV( - HVX_OP_MUL_F32(Q6_V_hi_W(vkq3), ms_vec), - HVX_OP_MUL_F32(Q6_V_lo_W(vkq3), ms_vec) - ); - - for (uint32_t j = 0; j < current_block_size; j += 2) { - HVX_Vector S0 = hvx_vec_repl_f16(Q6_V_vror_VR(P, j * 2)); - const HVX_Vector * vx0 = (const HVX_Vector *) v_ptr; - if (j + 1 == current_block_size) { - vkq0 = hvx_vec_mpyacc_f32_f16(vkq0, Q6_Vh_vshuff_Vh(vx0[0]), S0); - vkq1 = hvx_vec_mpyacc_f32_f16(vkq1, Q6_Vh_vshuff_Vh(vx0[1]), S0); - vkq2 = hvx_vec_mpyacc_f32_f16(vkq2, Q6_Vh_vshuff_Vh(vx0[2]), S0); - vkq3 = hvx_vec_mpyacc_f32_f16(vkq3, Q6_Vh_vshuff_Vh(vx0[3]), S0); - break; - } - - HVX_Vector S1 = hvx_vec_repl_f16(Q6_V_vror_VR(P, (j + 1) * 2)); - const HVX_Vector * vx1 = (const HVX_Vector *) (v_ptr + factx->size_v_row_padded); - vkq0 = hvx_vec_mpyacc_f32_f16(vkq0, Q6_Vh_vshuff_Vh(vx0[0]), S0); - vkq0 = hvx_vec_mpyacc_f32_f16(vkq0, Q6_Vh_vshuff_Vh(vx1[0]), S1); - vkq1 = hvx_vec_mpyacc_f32_f16(vkq1, Q6_Vh_vshuff_Vh(vx0[1]), S0); - vkq1 = hvx_vec_mpyacc_f32_f16(vkq1, Q6_Vh_vshuff_Vh(vx1[1]), S1); - vkq2 = hvx_vec_mpyacc_f32_f16(vkq2, Q6_Vh_vshuff_Vh(vx0[2]), S0); - vkq2 = hvx_vec_mpyacc_f32_f16(vkq2, Q6_Vh_vshuff_Vh(vx1[2]), S1); - vkq3 = hvx_vec_mpyacc_f32_f16(vkq3, Q6_Vh_vshuff_Vh(vx0[3]), S0); - vkq3 = hvx_vec_mpyacc_f32_f16(vkq3, Q6_Vh_vshuff_Vh(vx1[3]), S1); - v_ptr += stride_v2; - } - - ((HVX_VectorPair *) VKQ32)[0] = vkq0; - ((HVX_VectorPair *) VKQ32)[1] = vkq1; - ((HVX_VectorPair *) VKQ32)[2] = vkq2; - ((HVX_VectorPair *) VKQ32)[3] = vkq3; - } else { - hvx_scale_vec_f32_aa((uint8_t *) VKQ32, (const uint8_t *) VKQ32, DV, ms_vec); - - for (uint32_t j = 0; j < current_block_size; j += 2) { - if (j + 1 == current_block_size) { - HVX_Vector S0 = hvx_vec_repl_f16(Q6_V_vror_VR(P, j * 2)); - hvx_mad_f32_f16_aa_vec(VKQ32, v_ptr, S0, DV); - break; - } - - HVX_Vector S0 = hvx_vec_repl_f16(Q6_V_vror_VR(P, j * 2)); - HVX_Vector S1 = hvx_vec_repl_f16(Q6_V_vror_VR(P, (j + 1) * 2)); - - hvx_mad_f32_f16_aa_rx2_vec(VKQ32, v_ptr, v_ptr + factx->size_v_row_padded, S0, S1, DV); - v_ptr += stride_v2; - } - } - } + fa_hvx_sfm_pv_block(factx, vkq_ptrs[g], v_base, scores_buf, current_block_size, &M_vals[g], &S_vals[g]); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_SFM, head_ir); // prefetch V and mask for step + 2 after last head finished V accumulation @@ -717,49 +853,334 @@ static void flash_attn_ext_f16_thread(const htp_thread_t * th, unsigned int nth, htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, head_ir); - float M = hvx_vec_get_f32(M_vec[g]); - float S = hvx_vec_get_f32(S_vec[g]); + float M = M_vals[g]; + float S = S_vals[g]; + float scale_out = 1.0f; if (sinks) { const float s = factx->spad_sinks[h]; - float vs = 1.0f; - if (s > M) { - HVX_Vector diff_vec = hvx_vec_splat_f32(M - s); - HVX_Vector ms_vec = hvx_vec_exp_f32(diff_vec); - hvx_scale_vec_f32_aa((uint8_t *) VKQ32, (const uint8_t *) VKQ32, DV, ms_vec); - - float ms = hvx_vec_get_f32(ms_vec); - S = S * ms + vs; + const float ms = fa_hvx_exp_scalar(M - s); + S = S * ms + 1.0f; + scale_out = ms; } else { - HVX_Vector diff_vec = hvx_vec_splat_f32(s - M); - vs = hvx_vec_get_f32(hvx_vec_exp_f32(diff_vec)); + const float vs = fa_hvx_exp_scalar(s - M); S += vs; } } - const float S_inv = S == 0.0f ? 0.0f : 1.0f/S; - hvx_scale_f32_aa((uint8_t *) VKQ32, (const uint8_t *) VKQ32, DV, S_inv); + scale_out = (S == 0.0f) ? 0.0f : (scale_out / S); const uint32_t r_iq3 = fastdiv(head_ir, &factx->src0_div21); const uint32_t r_iq2 = fastdiv(head_ir - r_iq3*neq2*neq1, &factx->src0_div1); const uint32_t r_iq1 = (head_ir - r_iq3*neq2*neq1 - r_iq2 * neq1); - uint8_t * dst_ptr = (uint8_t *) dst->data + r_iq2 * dst->nb[1] + r_iq1 * dst->nb[2] + r_iq3 * dst->nb[3]; + const dma_addr_t dst_addr = dst->data + r_iq2 * dst->nb[1] + r_iq1 * dst->nb[2] + r_iq3 * dst->nb[3]; if (dst->type == HTP_TYPE_F32) { - hvx_copy_f32_ua(dst_ptr, (uint8_t *) VKQ32, DV); + fa_hvx_finalize_dealt_row_f32(VKQ32, VKQ32, DV, scale_out); + const size_t row_bytes = DV * sizeof(float); + dma_queue_push(dma_q, dma_make_data(dst_addr, VKQ32), row_bytes, row_bytes, row_bytes, 1); } else if (dst->type == HTP_TYPE_F16) { - hvx_copy_f16_f32_ua(dst_ptr, (uint8_t *) VKQ32, DV); + fa_hvx_finalize_dealt_row_f16(VKQ32, VKQ32, DV, scale_out); + const size_t row_bytes = DV * sizeof(__fp16); + dma_queue_push(dma_q, dma_make_data(dst_addr, VKQ32), row_bytes, row_bytes, row_bytes, 1); } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, head_ir); } + dma_queue_flush(dma_q); + ir += G_local; } } +static void flash_attn_ext_f16_split_kv_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + struct htp_fa_context * factx = (struct htp_fa_context *) data; + const struct htp_ops_context * octx = factx->octx; + const struct htp_tensor * q = octx->src[0]; + const struct htp_tensor * k = octx->src[1]; + const struct htp_tensor * v = octx->src[2]; + const struct htp_tensor * mask = octx->src[3]; + + const uint32_t splits_per_kv = factx->splits_per_kv; + const uint32_t n_workers = factx->n_kv_local * splits_per_kv; + if (ith >= n_workers) { + return; + } + + const uint32_t kv_local = ith / splits_per_kv; + const uint32_t split_idx = ith % splits_per_kv; + const uint32_t kv_head = factx->kv_head_start + kv_local; + const uint32_t G = factx->G; + const uint32_t q_base = kv_head * G; + + const uint32_t base_blocks = factx->n_active_blocks / splits_per_kv; + const uint32_t rem_blocks = factx->n_active_blocks % splits_per_kv; + const uint32_t step_start = split_idx * base_blocks + MIN(split_idx, rem_blocks); + const uint32_t step_count = base_blocks + (split_idx < rem_blocks ? 1 : 0); + const uint32_t step_end = step_start + step_count; + + const uint32_t DK = k->ne[0]; + const uint32_t DV = v->ne[0]; + const uint32_t nek1 = k->ne[1]; + + const uint32_t nbq1 = q->nb[1]; + const uint32_t nbq2 = q->nb[2]; + const uint32_t nbk1 = k->nb[1]; + const uint32_t nbk2 = k->nb[2]; + const uint32_t nbv1 = v->nb[1]; + const uint32_t nbv2 = v->nb[2]; + + const size_t size_q_row = htp_tensor_get_row_size(q->type, DK); + const size_t size_k_row = htp_tensor_get_row_size(k->type, DK); + const size_t size_v_row = htp_tensor_get_row_size(v->type, DV); + + struct htp_thread_trace * tr = th->trace; + dma_queue * dma_q = th->dma_q; + + uint8_t * spad_q = factx->spad_q + factx->size_q_block * ith; + uint8_t * spad_k = factx->spad_k + factx->size_k_block * 2 * ith; + uint8_t * spad_v = factx->spad_v + factx->size_v_block * 2 * ith; + uint8_t * spad_m = factx->spad_m + (mask ? factx->size_m_block * HVX_FA_DMA_CACHE_SIZE : 0) * ith; + uint8_t * spad_a = factx->spad_a + factx->size_vkq_acc * ith; + + dma_cache_dm * m_cache = &factx->m_cache[ith]; + dma_cache_dm_init(m_cache, spad_m, factx->size_m_block, HVX_FA_DMA_CACHE_SIZE); + + const uint16_t * active_blocks = factx->shared_active_blocks ? factx->ddr->active_blocks : NULL; + const dma_addr_t mp_base = mask ? mask->data : 0; + + const size_t size_vkq_acc_single = hex_round_up(DV * sizeof(float), 256); + const uint32_t dv_zero_elems = ((DV + 63) / 64) * 64; + + uint8_t scores_buf[128] __attribute__((aligned(128))); + uint16_t slopes[FA_HVX_G_MAX]; + float S_vals[FA_HVX_G_MAX]; + float M_vals[FA_HVX_G_MAX]; + uint8_t * q_ptrs[FA_HVX_G_MAX]; + float * vkq_ptrs[FA_HVX_G_MAX]; + + for (uint32_t g = 0; g < G; ++g) { + const uint32_t qh = q_base + g; + memcpy(&slopes[g], &factx->ddr->slopes[qh], sizeof(uint16_t)); + S_vals[g] = 0.0f; + M_vals[g] = HTP_FA_M_INITIAL_VAL; + + uint8_t * q_dst = spad_q + g * factx->size_q_row_padded; + q_ptrs[g] = q_dst; + + float * vkq_dst = (float *) (spad_a + g * size_vkq_acc_single); + vkq_ptrs[g] = vkq_dst; + fa_hvx_zero_acc(vkq_dst, dv_zero_elems); + + const dma_addr_t q_row_ptr = q->data + qh * nbq2; + dma_queue_push(dma_q, dma_make_data(q_dst, q_row_ptr), factx->size_q_row_padded, nbq1, size_q_row, 1); + } + + const uint32_t n_prefetch = MIN(step_count, 2); + for (uint32_t p = 0; p < n_prefetch; ++p) { + const uint32_t step = step_start + p; + const uint32_t ib = active_blocks ? active_blocks[step] : step; + const uint32_t ic_start = ib * FLASH_ATTN_BLOCK_SIZE; + const uint32_t current_block_size = MIN(FLASH_ATTN_BLOCK_SIZE, nek1 - ic_start); + + const dma_addr_t k_src = k->data + ic_start * nbk1 + kv_head * nbk2; + uint8_t * k_dst = spad_k + (p & 1) * factx->size_k_block; + dma_queue_push(dma_q, dma_make_data(k_dst, k_src), factx->size_k_row_padded, nbk1, size_k_row, current_block_size); + + const dma_addr_t v_src = v->data + ic_start * nbv1 + kv_head * nbv2; + uint8_t * v_dst = spad_v + (p & 1) * factx->size_v_block; + dma_queue_push(dma_q, dma_make_data(v_dst, v_src), factx->size_v_row_padded, nbv1, size_v_row, current_block_size); + + if (mask) { + const dma_addr_t m_src = mp_base + ic_start * sizeof(__fp16); + dma_cache_dm_push(dma_q, m_cache, ib, m_src, current_block_size * 2, current_block_size * 2, current_block_size * 2, 1); + } + } + + for (uint32_t g = 0; g < G; ++g) { + uint8_t * q_ptr_vtcm = (void *) dma_queue_pop(dma_q).dst; + if (factx->is_q_fp32) { + fa_hvx_q_f32_to_f16(q_ptr_vtcm, DK); + } + } + + for (uint32_t step = step_start; step < step_end; ++step) { + const uint32_t ib = active_blocks ? active_blocks[step] : step; + const uint32_t ic_start = ib * FLASH_ATTN_BLOCK_SIZE; + const uint32_t current_block_size = MIN(FLASH_ATTN_BLOCK_SIZE, nek1 - ic_start); + + uint8_t * k_base = (void *) dma_queue_pop(dma_q).dst; + uint8_t * v_base = (void *) dma_queue_pop(dma_q).dst; + __fp16 * m_base = mask ? (__fp16 *) dma_queue_pop(dma_q).dst : NULL; + + if (factx->k->type == HTP_TYPE_Q8_0) { + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_K_PREP, q_base); + fa_hvx_dequant_q8_0_block(k_base, factx->size_k_row_padded, current_block_size, DK); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_K_PREP, q_base); + } + if (factx->v->type == HTP_TYPE_Q8_0) { + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_V_PREP, q_base); + fa_hvx_dequant_q8_0_block(v_base, factx->size_v_row_padded, current_block_size, DV); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_V_PREP, q_base); + } + + for (uint32_t g = 0; g < G; ++g) { + const uint32_t head_ir = q_base + g; + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_QK, head_ir); + fa_hvx_qk_block(factx, q_ptrs[g], k_base, m_base, current_block_size, slopes[g], scores_buf); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_QK, head_ir); + + if (g + 1 == G && step + 2 < step_end) { + const uint32_t next_ib = active_blocks ? active_blocks[step + 2] : (step + 2); + const uint32_t next_ic_start = next_ib * FLASH_ATTN_BLOCK_SIZE; + const uint32_t next_block_size = MIN(FLASH_ATTN_BLOCK_SIZE, nek1 - next_ic_start); + + const dma_addr_t k_src = k->data + next_ic_start * nbk1 + kv_head * nbk2; + dma_queue_push(dma_q, dma_make_data(k_base, k_src), factx->size_k_row_padded, nbk1, size_k_row, next_block_size); + } + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_SFM, head_ir); + fa_hvx_sfm_pv_block(factx, vkq_ptrs[g], v_base, scores_buf, current_block_size, &M_vals[g], &S_vals[g]); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_SFM, head_ir); + + if (g + 1 == G && step + 2 < step_end) { + const uint32_t next_ib = active_blocks ? active_blocks[step + 2] : (step + 2); + const uint32_t next_ic_start = next_ib * FLASH_ATTN_BLOCK_SIZE; + const uint32_t next_block_size = MIN(FLASH_ATTN_BLOCK_SIZE, nek1 - next_ic_start); + + const dma_addr_t v_src = v->data + next_ic_start * nbv1 + kv_head * nbv2; + dma_queue_push(dma_q, dma_make_data(v_base, v_src), factx->size_v_row_padded, nbv1, size_v_row, next_block_size); + + if (mask) { + const dma_addr_t m_src = mp_base + next_ic_start * sizeof(__fp16); + dma_cache_dm_push(dma_q, m_cache, next_ib, m_src, next_block_size * 2, next_block_size * 2, next_block_size * 2, 1); + } + } + } + } + + for (uint32_t g = 0; g < G; ++g) { + factx->ddr->split_m[ith][g] = M_vals[g]; + factx->ddr->split_s[ith][g] = S_vals[g]; + } + + (void) nth; +} + +static void flash_attn_ext_f16_split_merge_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + struct htp_fa_context * factx = (struct htp_fa_context *) data; + const struct htp_ops_context * octx = factx->octx; + const struct htp_tensor * v = octx->src[2]; + const struct htp_tensor * sinks = octx->src[4]; + const struct htp_tensor * dst = octx->dst; + + const uint32_t G = factx->G; + const uint32_t splits_per_kv = factx->splits_per_kv; + const uint32_t n_q_local = factx->n_kv_local * G; + const uint32_t h_per_t = (n_q_local + nth - 1) / nth; + const uint32_t h_start = ith * h_per_t; + const uint32_t h_end = MIN(h_start + h_per_t, n_q_local); + + if (h_start >= h_end) { + return; + } + + const uint32_t DV = v->ne[0]; + const size_t row_bytes = htp_tensor_get_row_size(dst->type, DV); + const size_t out_stride = hex_round_up(row_bytes, 256); + const size_t acc_stride = hex_round_up(DV * sizeof(float), 256); + + // spad_v is unused during merge and has 128 * size_v_row_padded bytes per thread. + uint8_t * out_base = factx->spad_v + ith * factx->size_v_block * 2; + + struct htp_thread_trace * tr = th->trace; + dma_queue * dma_q = th->dma_q; + + float diffs[32] __attribute__((aligned(128))); + float weights[32] __attribute__((aligned(128))); + float scales[HTP_MAX_NHVX]; + + uint32_t kv_local = h_start / G; + uint32_t g = h_start % G; + + for (uint32_t hl = h_start; hl < h_end; ++hl) { + const uint32_t q_head = (factx->kv_head_start + kv_local) * G + g; + const uint32_t w_base = kv_local * splits_per_kv; + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, q_head); + + bool has_valid = false; + float m_global = HTP_FA_M_INITIAL_VAL; + for (uint32_t s = 0; s < splits_per_kv; ++s) { + if (factx->ddr->split_s[w_base + s][g] > 0.0f) { + const float ms = factx->ddr->split_m[w_base + s][g]; + if (!has_valid || ms > m_global) { + m_global = ms; + has_valid = true; + } + } + } + + float sink_val = 0.0f; + if (sinks) { + sink_val = factx->spad_sinks[q_head]; + if (!has_valid || sink_val > m_global) { + m_global = sink_val; + has_valid = true; + } + } + + memset(diffs, 0, sizeof(diffs)); + for (uint32_t s = 0; s < splits_per_kv; ++s) { + if (factx->ddr->split_s[w_base + s][g] > 0.0f) { + diffs[s] = factx->ddr->split_m[w_base + s][g] - m_global; + } + } + if (sinks) { + diffs[splits_per_kv] = sink_val - m_global; + } + + fa_hvx_split_exp_weights(weights, diffs); + + float l_global = sinks ? weights[splits_per_kv] : 0.0f; + for (uint32_t s = 0; s < splits_per_kv; ++s) { + const float ls = factx->ddr->split_s[w_base + s][g]; + if (ls > 0.0f) { + l_global += ls * weights[s]; + } + } + + const float inv_l = (l_global == 0.0f) ? 0.0f : (1.0f / l_global); + for (uint32_t s = 0; s < splits_per_kv; ++s) { + scales[s] = (factx->ddr->split_s[w_base + s][g] > 0.0f) ? (weights[s] * inv_l) : 0.0f; + } + + uint8_t * out_ptr = out_base + (hl - h_start) * out_stride; + const uint8_t * spad_a_base = factx->spad_a + w_base * factx->size_vkq_acc + g * acc_stride; + if (dst->type == HTP_TYPE_F32) { + fa_hvx_merge_and_store_row_f32(out_ptr, spad_a_base, factx->size_vkq_acc, splits_per_kv, scales, DV); + } else { + fa_hvx_merge_and_store_row_f16(out_ptr, spad_a_base, factx->size_vkq_acc, splits_per_kv, scales, DV); + } + + const dma_addr_t dst_addr = dst->data + q_head * dst->nb[1]; + dma_queue_push(dma_q, dma_make_data(dst_addr, out_ptr), row_bytes, row_bytes, row_bytes, 1); + + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, q_head); + + if (++g == G) { + g = 0; + ++kv_local; + } + } + + dma_queue_flush(dma_q); +} + // ============================================================================ // HMX Phase args and thread logic // ============================================================================ @@ -781,32 +1202,71 @@ static void fa_k_interleave_thread(const htp_thread_t * th, unsigned int n, unsi const uint32_t total_rows = args->kv_rows; const uint32_t rows_per_t = args->rows_per_t; const uint32_t start = i * rows_per_t; - const uint32_t end = (uint32_t) hex_smin(start + rows_per_t, total_rows); if (start >= total_rows) { return; } + const uint32_t end_valid = (uint32_t) hex_smin(start + rows_per_t, total_rows); + const uint32_t end_tiled = (uint32_t) hex_smin(start + rows_per_t, hex_align_up(total_rows, HMX_FP16_TILE_N_ROWS)); + struct htp_thread_trace * tr = th->trace; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_K_PREP, (uint16_t) (args->kv_start + start)); if (factx->k->type == HTP_TYPE_Q8_0) { - for (uint32_t r = start; r < end; ++r) { + for (uint32_t r = start; r < end_valid; ++r) { __fp16 * row_k = (__fp16 *)((char *)args->curr_k + r * args->src_stride * sizeof(__fp16)); hvx_dequantize_row_flat_q8_0_f16(row_k, row_k, factx->DK); } } hmx_interleave_rows_to_tiles(factx->vtcm_k_tiles[args->buf_idx], (const __fp16 *) args->curr_k, total_rows, factx->DK_pad, - args->src_stride, start, end); + args->src_stride, start, end_tiled); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_K_PREP, (uint16_t) (args->kv_start + start)); } +static void fa_w8a8_k_prep_thread(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { + fa_k_int_args_t * args = (fa_k_int_args_t *) data; + struct hmx_fa_context * factx = args->factx; + + const uint32_t total_rows = args->kv_rows; + const uint32_t n_col_tiles = hmx_ceil_div(total_rows, HMX_W8A8_TILE_N_COLS); + const uint32_t tiles_per_t = hmx_ceil_div(n_col_tiles, n); + const uint32_t ct_start = i * tiles_per_t; + const uint32_t ct_end = (uint32_t) hex_smin(ct_start + tiles_per_t, n_col_tiles); + + if (ct_start >= n_col_tiles) { + return; + } + + struct htp_thread_trace * tr = th->trace; + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_K_PREP, (uint16_t) (args->kv_start + ct_start * HMX_W8A8_TILE_N_COLS)); + + const uint32_t n_dot = factx->DK / 32; + const size_t buf_idx = args->buf_idx; + + for (uint32_t ct = ct_start; ct < ct_end; ++ct) { + const uint32_t valid_rows = (uint32_t) hex_smin(HMX_W8A8_TILE_N_COLS, total_rows - ct * HMX_W8A8_TILE_N_COLS); + const uint8_t * k_raw = (const uint8_t *) args->curr_k + (size_t) ct * HMX_W8A8_TILE_N_COLS * factx->k_raw_row_padded; + uint8_t * dst_wt = (uint8_t *) factx->vtcm_k_tiles[buf_idx] + (size_t) ct * n_dot * HMX_W8A8_WT_TILE_SIZE; + float * dst_sc = factx->vtcm_k_scales[buf_idx] + (size_t) ct * HMX_W8A8_TILE_N_COLS; + HVX_Vector * bias_out = (HVX_Vector *) (factx->vtcm_k_bias[buf_idx] + (size_t) ct * 2 * HMX_W8A8_BIAS_BANK_SIZE); + hmx_fa_w8a8_k_prep_tile(k_raw, dst_wt, dst_sc, bias_out, valid_rows, n_dot, factx->k_raw_row_padded); + } + + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_K_PREP, (uint16_t) (args->kv_start + ct_start * HMX_W8A8_TILE_N_COLS)); +} + static void fa_phase_k_interleave(struct hmx_fa_context * factx, uint32_t kv_rows, size_t src_stride, void * curr_k, uint32_t kv_start, size_t buf_idx) { work_queue_t wp = factx->octx->ctx->hvx_queue; - uint32_t n = 1; - if (factx->n_hvx > 1 && kv_rows >= factx->n_hvx * 2) { - n = factx->n_hvx; + if (factx->is_w8a8) { + const uint32_t n_col_tiles = hmx_ceil_div(kv_rows, HMX_W8A8_TILE_N_COLS); + const uint32_t n = (uint32_t) hex_smin(factx->n_hvx, n_col_tiles); + fa_k_int_args_t args = { factx, kv_rows, src_stride, curr_k, kv_start, 0, buf_idx }; + work_queue_run(wp, fa_w8a8_k_prep_thread, &args, n); + return; } - uint32_t rows_per_t = hex_align_up(hmx_ceil_div(kv_rows, n), 2); + const uint32_t n_col_tiles = hmx_ceil_div(kv_rows, HMX_FP16_TILE_N_ROWS); + const uint32_t n = (uint32_t) hex_smin(factx->n_hvx, n_col_tiles); + const uint32_t rows_per_t = hmx_ceil_div(n_col_tiles, n) * HMX_FP16_TILE_N_ROWS; fa_k_int_args_t args = { factx, kv_rows, src_stride, curr_k, kv_start, rows_per_t, buf_idx }; work_queue_run(wp, fa_k_interleave_thread, &args, n); } @@ -820,6 +1280,7 @@ typedef struct { size_t n_col_tiles; uint32_t kv_start; uint32_t rows_per_t; + size_t buf_idx; } fa_v_int_args_t; static void fa_v_interleave_thread(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { @@ -850,34 +1311,70 @@ static void fa_v_interleave_thread(const htp_thread_t * th, unsigned int n, unsi htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_V_PREP, (uint16_t) (args->kv_start + start)); } +static void fa_w8a8_v_prep_thread(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { + fa_v_int_args_t * args = (fa_v_int_args_t *) data; + struct hmx_fa_context * factx = args->factx; + + const uint32_t n_v_tiles = factx->DV / HMX_W8A8_TILE_N_COLS; + const uint32_t tiles_per_t = hmx_ceil_div(n_v_tiles, n); + const uint32_t dv_start = i * tiles_per_t; + const uint32_t dv_end = (uint32_t) hex_smin(dv_start + tiles_per_t, n_v_tiles); + + if (dv_start >= n_v_tiles) { + return; + } + + struct htp_thread_trace * tr = th->trace; + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_V_PREP, (uint16_t) (args->kv_start + dv_start * HMX_W8A8_TILE_N_COLS)); + + const uint32_t kv_rows = args->kv_rows; + const uint32_t n_col_tiles = hmx_ceil_div(kv_rows, HMX_W8A8_TILE_N_COLS); + const size_t buf_idx = args->buf_idx; + + for (uint32_t dv_tile = dv_start; dv_tile < dv_end; ++dv_tile) { + const uint8_t * v_base = (const uint8_t *) args->v_src + (size_t) dv_tile * 34; + uint8_t * dst_wt = (uint8_t *) args->v_tiles_dst + (size_t) dv_tile * n_col_tiles * HMX_W8A8_WT_TILE_SIZE; + float * dst_sc = factx->vtcm_v_scales[buf_idx] + (size_t) dv_tile * HMX_W8A8_TILE_N_COLS; + HVX_Vector * bias_out = (HVX_Vector *) (factx->vtcm_v_bias[buf_idx] + (size_t) dv_tile * 2 * HMX_W8A8_BIAS_BANK_SIZE); + hmx_fa_w8a8_v_prep_tile(v_base, dst_wt, dst_sc, bias_out, kv_rows, n_col_tiles, factx->v_raw_row_padded); + } + + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_V_PREP, (uint16_t) (args->kv_start + dv_start * HMX_W8A8_TILE_N_COLS)); +} + static void fa_phase_v_interleave(struct hmx_fa_context * factx, uint32_t kv_rows, size_t src_stride, void * v_src, void * v_tiles_dst, size_t n_col_tiles, - uint32_t kv_start) { + uint32_t kv_start, + size_t buf_idx) { work_queue_t wp = factx->octx->ctx->hvx_queue; + if (factx->is_w8a8) { + const uint32_t n_v_tiles = factx->DV / HMX_W8A8_TILE_N_COLS; + const uint32_t n = (uint32_t) hex_smin(factx->n_hvx, n_v_tiles); + fa_v_int_args_t args = { factx, kv_rows, src_stride, v_src, v_tiles_dst, n_col_tiles, kv_start, 0, buf_idx }; + work_queue_run(wp, fa_w8a8_v_prep_thread, &args, n); + return; + } uint32_t n = 1; if (factx->n_hvx > 1 && kv_rows >= factx->n_hvx * 2) { n = factx->n_hvx; } uint32_t rows_per_t = hex_align_up(hmx_ceil_div(kv_rows, n), 2); - fa_v_int_args_t args = { factx, kv_rows, src_stride, v_src, v_tiles_dst, n_col_tiles, kv_start, rows_per_t }; + fa_v_int_args_t args = { factx, kv_rows, src_stride, v_src, v_tiles_dst, n_col_tiles, kv_start, rows_per_t, buf_idx }; work_queue_run(wp, fa_v_interleave_thread, &args, n); } typedef struct { - struct hmx_fa_context * factx; - const struct htp_tensor * q; - uint32_t q_start; - uint32_t kv_head; - uint32_t ib3; - size_t n_rows_g; - size_t rows_per_t; - size_t n_rows_q; - bool q_transposed; - atomic_uint barrier; + struct hmx_fa_context * factx; + uint32_t q_start; + size_t n_rows_g; + size_t rows_per_t; + size_t n_rows_q; + bool q_transposed; + atomic_uint barrier; } fa_q_load_args_t; static void fa_q_load_thread(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { @@ -899,9 +1396,6 @@ static void fa_q_load_thread(const htp_thread_t * th, unsigned int n, unsigned i // Parallel initialization of per-block state { - const uint32_t g_br = factx->g_br; - const uint32_t DV = factx->DV; - const size_t col_vec_bytes = factx->col_vec_bytes; const size_t d_tile_bytes = factx->d_tile_bytes; @@ -933,43 +1427,30 @@ static void fa_q_load_thread(const htp_thread_t * th, unsigned int n, unsigned i } if (start < factx->g_br) { - const struct htp_tensor * q = args->q; - const uint32_t q_start = args->q_start; - const uint32_t kv_head = args->kv_head; - const uint32_t ib3 = args->ib3; - - const bool use_q_dma = (factx->vtcm_q_dma != NULL); - - __fp16 * q_tiles = factx->vtcm_q_tiles; - const size_t DK_pad = factx->DK_pad; - if (use_q_dma) { - const size_t g_rows_end = hex_smin(end, n_rows_g); - const uint32_t d_limit = factx->is_q_fp32 ? DK / 32 : DK / 64; - - uint8_t * q_flat = (uint8_t *) factx->vtcm_q_dma; - if (DK_pad != DK) { - if (factx->is_q_fp32) { - hmx_fa_q_prep_fp32_pad(q_tiles, q_flat, start, end, g_rows_end, DK, DK_pad, G, args->n_rows_q, &factx->div_G, args->q_transposed); - } else { - hmx_fa_q_prep_fp16_pad(q_tiles, q_flat, start, end, g_rows_end, DK, DK_pad, G, args->n_rows_q, &factx->div_G, args->q_transposed); - } - } else if (factx->is_q_fp32) { - switch (d_limit) { - case 2: hmx_fa_q_prep_fp32_d2(q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, args->q_transposed); break; - case 4: hmx_fa_q_prep_fp32_d4(q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, args->q_transposed); break; - default: hmx_fa_q_prep_fp32( q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, d_limit, args->q_transposed); break; - } + __fp16 * q_tiles = factx->vtcm_q_tiles; + const size_t DK_pad = factx->DK_pad; + const size_t g_rows_end = hex_smin(end, n_rows_g); + const uint32_t d_limit = factx->is_q_fp32 ? DK / 32 : DK / 64; + + uint8_t * q_flat = (uint8_t *) factx->vtcm_q_dma; + if (DK_pad != DK) { + if (factx->is_q_fp32) { + hmx_fa_q_prep_fp32_pad(q_tiles, q_flat, start, end, g_rows_end, DK, DK_pad, G, args->n_rows_q, &factx->div_G, args->q_transposed); } else { - switch (d_limit) { - case 1: hmx_fa_q_prep_fp16_d1(q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, args->q_transposed); break; - case 2: hmx_fa_q_prep_fp16_d2(q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, args->q_transposed); break; - default: hmx_fa_q_prep_fp16( q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, d_limit, args->q_transposed); break; - } + hmx_fa_q_prep_fp16_pad(q_tiles, q_flat, start, end, g_rows_end, DK, DK_pad, G, args->n_rows_q, &factx->div_G, args->q_transposed); + } + } else if (factx->is_q_fp32) { + switch (d_limit) { + case 2: hmx_fa_q_prep_fp32_d2(q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, args->q_transposed); break; + case 4: hmx_fa_q_prep_fp32_d4(q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, args->q_transposed); break; + default: hmx_fa_q_prep_fp32( q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, d_limit, args->q_transposed); break; } } else { - // Fallback: direct-from-DDR/L2 path - hmx_fa_q_prep_fallback(q_tiles, q->data, q->nb[1], q->nb[2], q->nb[3], - q_start, kv_head, ib3, start, end, n_rows_g, G, DK, DK_pad, factx->is_q_fp32, &factx->div_G); + switch (d_limit) { + case 1: hmx_fa_q_prep_fp16_d1(q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, args->q_transposed); break; + case 2: hmx_fa_q_prep_fp16_d2(q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, args->q_transposed); break; + default: hmx_fa_q_prep_fp16( q_tiles, q_flat, start, end, g_rows_end, DK, G, args->n_rows_q, &factx->div_G, d_limit, args->q_transposed); break; + } } } @@ -983,8 +1464,6 @@ static void fa_q_load_thread(const htp_thread_t * th, unsigned int n, unsigned i // Zero out vtcm_o_tiles[0] as it was used as temp_q_vtcm { - const uint32_t g_br = factx->g_br; - const uint32_t DV = factx->DV; const size_t o_tile_bytes = factx->o_tile_bytes; const size_t o_bytes_per_t = hex_align_up(o_tile_bytes / n, 128); const size_t o_start = i * o_bytes_per_t; @@ -996,80 +1475,126 @@ static void fa_q_load_thread(const htp_thread_t * th, unsigned int n, unsigned i htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_Q_PREP, (uint16_t) (args->q_start * G + start)); } +static void fa_w8a8_q_prep_thread(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { + fa_q_load_args_t * args = (fa_q_load_args_t *) data; + struct hmx_fa_context * factx = args->factx; + + const size_t n_rows_g = args->n_rows_g; + const size_t G = factx->G; + const size_t DK = factx->DK; + const size_t rows_per_t = args->rows_per_t; + const size_t start = (size_t) i * rows_per_t; + const size_t end = hex_smin(start + rows_per_t, factx->g_br); + + struct htp_thread_trace * tr = th->trace; + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_Q_PREP, (uint16_t) (args->q_start * G + start)); + + // Parallel initialization of per-block state + { + const size_t col_vec_bytes = factx->col_vec_bytes; + const size_t o_f32_bytes = factx->o_f32_bytes; + + const size_t l_bytes_per_t = hex_align_up(col_vec_bytes / n, 128); + const size_t l_start = i * l_bytes_per_t; + const size_t l_end = hex_smin(l_start + l_bytes_per_t, col_vec_bytes); + + const size_t m_bytes_per_t = hex_align_up(col_vec_bytes / n, 128); + const size_t m_start = i * m_bytes_per_t; + const size_t m_end = hex_smin(m_start + m_bytes_per_t, col_vec_bytes); + + if (l_start < col_vec_bytes) { + hvx_splat_u8_a((char *) factx->vtcm_l_vec + l_start, 0, l_end - l_start); + } + if (m_start < col_vec_bytes) { + hvx_splat_f32_a((char *) factx->vtcm_m_vec + m_start, HTP_FA_M_INITIAL_VAL, (m_end - m_start) / sizeof(float)); + } + + const size_t o_bytes_per_t = hex_align_up(o_f32_bytes / n, 128); + const size_t o_start = i * o_bytes_per_t; + const size_t o_end = hex_smin(o_start + o_bytes_per_t, o_f32_bytes); + if (o_start < o_f32_bytes) { + hvx_splat_u8_a((char *) factx->vtcm_o_f32 + o_start, 0, o_end - o_start); + } + } + + if (start < factx->g_br) { + const size_t g_rows_end = hex_smin(end, n_rows_g); + uint8_t * q_tiles = (uint8_t *) factx->vtcm_q_tiles; + const uint8_t * q_flat = (const uint8_t *) factx->vtcm_q_dma; + if (factx->is_q_fp32) { + hmx_fa_w8a8_q_prep_f32(q_tiles, factx->vtcm_q_scales, q_flat, start, end, g_rows_end, + DK, G, args->n_rows_q, &factx->div_G, args->q_transposed, factx->scale_f32); + } else { + hmx_fa_w8a8_q_prep_f16(q_tiles, factx->vtcm_q_scales, q_flat, start, end, g_rows_end, + DK, G, args->n_rows_q, &factx->div_G, args->q_transposed, factx->scale_f32); + } + } + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_Q_PREP, (uint16_t) (args->q_start * G + start)); +} + static void fa_phase_q_load(struct hmx_fa_context * factx, const struct htp_tensor * q, uint32_t q_start, - uint32_t kv_head, - uint32_t ib3, size_t n_rows_g) { work_queue_t wp = factx->octx->ctx->hvx_queue; uint32_t n = 1; - if (factx->n_hvx > 1 && n_rows_g >= (size_t) (factx->n_hvx * 2)) { + const size_t row_align = factx->is_w8a8 ? 4 : 2; + if (factx->n_hvx > 1 && n_rows_g >= (size_t) (factx->n_hvx * row_align)) { n = factx->n_hvx; } - size_t rows_per_t = hex_align_up(hmx_ceil_div(factx->g_br, n), 2); + size_t rows_per_t = hex_align_up(hmx_ceil_div(factx->g_br, n), row_align); const uint32_t n_rows_q = hex_smin(factx->Br, factx->neq1 - q_start); fa_q_load_args_t args; args.factx = factx; - args.q = q; args.q_start = q_start; - args.kv_head = kv_head; - args.ib3 = ib3; args.n_rows_g = n_rows_g; args.rows_per_t = rows_per_t; args.n_rows_q = n_rows_q; args.q_transposed = q->nb[1] < q->nb[2]; atomic_init(&args.barrier, n); - work_queue_run(wp, fa_q_load_thread, &args, n); + work_queue_run(wp, factx->is_w8a8 ? fa_w8a8_q_prep_thread : fa_q_load_thread, &args, n); } typedef struct { - struct hmx_fa_context * factx; - const struct htp_tensor * dst; - const __fp16 * o_tile_src; - uint32_t q_start; - uint32_t kv_head; - uint32_t ib3; - size_t n_rows_g; - size_t rows_per_t; + struct hmx_fa_context * factx; + uint8_t * vtcm_dst; + const __fp16 * o_tile_src; + uint32_t q_start; + uint32_t kv_head; + size_t row_off; + size_t n_rows; + size_t rows_per_t; } fa_o_store_args_t; static void fa_o_store_thread_f32(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { fa_o_store_args_t * args = (fa_o_store_args_t *) data; struct hmx_fa_context * factx = args->factx; - const size_t n_rows_g = args->n_rows_g; - const size_t G = factx->G; - const size_t DV = factx->DV; - + const size_t n_rows = args->n_rows; + const size_t G = factx->G; + const size_t DV = factx->DV; const size_t rows_per_t = args->rows_per_t; const size_t start = (size_t) i * rows_per_t; - const size_t end = hex_smin(start + rows_per_t, n_rows_g); + const size_t end = hex_smin(start + rows_per_t, n_rows); - if (start >= n_rows_g) { + if (start >= n_rows) { return; } struct htp_thread_trace * tr = th->trace; - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * G + start)); - - const struct htp_tensor * dst = args->dst; - const __fp16 * o_tile_src = args->o_tile_src; - const uint32_t q_start = args->q_start; - const uint32_t kv_head = args->kv_head; - const uint32_t ib3 = args->ib3; - - const size_t DV_pad = factx->DV_pad; - - size_t q_idx = fastdiv(start, &factx->div_G); - size_t h_idx = fastmodulo(start, G, &factx->div_G); - - for (size_t r = start; r < end; ++r) { - float * out = (float *) ((uint8_t *) dst->data + (kv_head * G + h_idx) * dst->nb[1] + - (q_start + q_idx) * dst->nb[2] + ib3 * dst->nb[3]); - - size_t r0 = r / HMX_FP16_TILE_N_ROWS; - size_t r1 = r % HMX_FP16_TILE_N_ROWS; + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * G + args->row_off + start)); + + uint8_t * vtcm_dst = args->vtcm_dst; + const __fp16 * o_tile_src = args->o_tile_src; + const size_t row_off = args->row_off; + const size_t DV_pad = factx->DV_pad; + const size_t row_bytes = DV * sizeof(float); + + for (size_t rl = start; rl < end; ++rl) { + const size_t r = row_off + rl; + float * out = (float *) (vtcm_dst + rl * row_bytes); + const size_t r0 = r / HMX_FP16_TILE_N_ROWS; + const size_t r1 = r % HMX_FP16_TILE_N_ROWS; const __fp16 * tile_row_base = o_tile_src + r0 * HMX_FP16_TILE_N_ROWS * DV_pad; for (uint32_t d = 0; d < DV / 32; ++d) { @@ -1081,8 +1606,6 @@ static void fa_o_store_thread_f32(const htp_thread_t * th, unsigned int n, unsig *(HVX_UVector *) (out + d * 32) = Q6_V_hi_W(vp); } } - // Ragged tail: DV not a multiple of 32 (e.g. 72 -> last 8 lanes). Partial vector-write - // for the remaining (DV % 32) floats. const uint32_t d_tail = DV / 32; const uint32_t rem = DV - d_tail * 32; if (rem) { @@ -1091,52 +1614,39 @@ static void fa_o_store_thread_f32(const htp_thread_t * th, unsigned int n, unsig HVX_Vector vd = (r1 % 2 == 0) ? Q6_V_lo_W(vp) : Q6_V_hi_W(vp); hvx_vec_store_u((void *) (out + d_tail * 32), rem * sizeof(float), vd); } - - h_idx++; - if (h_idx == G) { - h_idx = 0; - q_idx++; - } } - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * G + start)); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * G + args->row_off + start)); } static void fa_o_store_thread_f16(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { fa_o_store_args_t * args = (fa_o_store_args_t *) data; struct hmx_fa_context * factx = args->factx; - const size_t n_rows_g = args->n_rows_g; + const size_t n_rows = args->n_rows; const size_t rows_per_t = args->rows_per_t; const size_t G = factx->G; const size_t DV = factx->DV; const size_t start = (size_t) i * rows_per_t; - const size_t end = hex_smin(start + rows_per_t, n_rows_g); + const size_t end = hex_smin(start + rows_per_t, n_rows); - if (start >= n_rows_g) { + if (start >= n_rows) { return; } struct htp_thread_trace * tr = th->trace; - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * G + start)); - - const struct htp_tensor * dst = args->dst; - const __fp16 * o_tile_src = args->o_tile_src; - const uint32_t q_start = args->q_start; - const uint32_t kv_head = args->kv_head; - const uint32_t ib3 = args->ib3; - - // O-tiles use the padded head dim (DV_pad); dst holds the real DV lanes. - const size_t DV_pad = factx->DV_pad; - - size_t q_idx = fastdiv(start, &factx->div_G); - size_t h_idx = fastmodulo(start, G, &factx->div_G); - - for (size_t r = start; r < end; ++r) { - __fp16 * out = (__fp16 *) ((uint8_t *) dst->data + (kv_head * G + h_idx) * dst->nb[1] + - (q_start + q_idx) * dst->nb[2] + ib3 * dst->nb[3]); - - size_t r0 = r / HMX_FP16_TILE_N_ROWS; - size_t r1 = r % HMX_FP16_TILE_N_ROWS; + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * G + args->row_off + start)); + + uint8_t * vtcm_dst = args->vtcm_dst; + const __fp16 * o_tile_src = args->o_tile_src; + const size_t row_off = args->row_off; + const size_t DV_pad = factx->DV_pad; + const size_t row_bytes = DV * sizeof(__fp16); + + for (size_t rl = start; rl < end; ++rl) { + const size_t r = row_off + rl; + __fp16 * out = (__fp16 *) (vtcm_dst + rl * row_bytes); + const size_t r0 = r / HMX_FP16_TILE_N_ROWS; + const size_t r1 = r % HMX_FP16_TILE_N_ROWS; const __fp16 * tile_row_base = o_tile_src + r0 * HMX_FP16_TILE_N_ROWS * DV_pad; for (uint32_t d = 0; d < DV / 64; ++d) { @@ -1150,7 +1660,6 @@ static void fa_o_store_thread_f16(const htp_thread_t * th, unsigned int n, unsig *(HVX_UVector *) (out + d * 64) = Q6_V_hi_W(vp); } } - // Ragged tail when DV is not a multiple of 64. const uint32_t d_tail = DV / 64; const uint32_t rem = DV - d_tail * 64; if (rem) { @@ -1161,32 +1670,99 @@ static void fa_o_store_thread_f16(const htp_thread_t * th, unsigned int n, unsig HVX_Vector vd = (r1 % 2 == 0) ? Q6_V_lo_W(vp) : Q6_V_hi_W(vp); hvx_vec_store_u((void *) (out + d_tail * 64), rem * sizeof(__fp16), vd); } + } + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * G + args->row_off + start)); +} - h_idx++; - if (h_idx == G) { - h_idx = 0; - q_idx++; +// Push [row_off, row_off + n_rows) from vtcm_src to dst->data via bypass DMA. +// Always leaves exactly 1 pending DMA descriptor on dma_q. +static void fa_push_o_dma(dma_queue * dma_q, + const struct htp_tensor * dst, + const uint8_t * vtcm_src, + size_t vtcm_row_stride, + size_t row_bytes, + uint32_t q_start, + uint32_t kv_head, + uint32_t ib3, + uint32_t G, + const struct fastdiv_values * div_G, + size_t row_off, + size_t n_rows) { + const dma_addr_t dst_base = dst->data + ib3 * dst->nb[3] + (kv_head * G) * dst->nb[1]; + + if (G == 1) { + const dma_addr_t d = dst_base + (q_start + row_off) * dst->nb[2]; + dma_queue_push(dma_q, dma_make_data(d, vtcm_src), dst->nb[2], vtcm_row_stride, row_bytes, n_rows); + return; + } + + const size_t q0 = fastdiv(row_off, div_G); + const size_t h0 = fastmodulo(row_off, G, div_G); + if (h0 == 0 && (n_rows % G) == 0 && dst->nb[1] == row_bytes && vtcm_row_stride == row_bytes) { + const size_t n_q = n_rows / G; + const size_t g_bytes = (size_t) G * row_bytes; + const dma_addr_t d = dst_base + (q_start + q0) * dst->nb[2]; + dma_queue_push(dma_q, dma_make_data(d, vtcm_src), dst->nb[2], g_bytes, g_bytes, n_q); + return; + } + + size_t q_idx = q0; + size_t h_idx = h0; + size_t done = 0; + while (done < n_rows) { + const size_t cnt = hex_smin(G - h_idx, n_rows - done); + const dma_addr_t d = dst_base + h_idx * dst->nb[1] + (q_start + q_idx) * dst->nb[2]; + const uint8_t * s = vtcm_src + done * vtcm_row_stride; + if (!dma_queue_push(dma_q, dma_make_data(d, s), dst->nb[1], vtcm_row_stride, row_bytes, cnt)) { + dma_queue_pop(dma_q); + dma_queue_push(dma_q, dma_make_data(d, s), dst->nb[1], vtcm_row_stride, row_bytes, cnt); } + done += cnt; + h_idx = 0; + q_idx += 1; + } + while (dma_queue_depth(dma_q) > 1) { + dma_queue_pop(dma_q); } - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * G + start)); } static void fa_phase_o_store(struct hmx_fa_context * factx, + dma_queue * dma_q, const struct htp_tensor * dst, const __fp16 * o_tile_src, + uint8_t * vtcm_dst, uint32_t q_start, uint32_t kv_head, uint32_t ib3, size_t n_rows_g) { - work_queue_t wp = factx->octx->ctx->hvx_queue; - uint32_t n = 1; - if (factx->n_hvx > 1 && n_rows_g >= (size_t) (factx->n_hvx * 2)) { - n = factx->n_hvx; + work_queue_t wp = factx->octx->ctx->hvx_queue; + const size_t row_bytes = factx->DV * (factx->is_dst_fp32 ? sizeof(float) : sizeof(__fp16)); + work_queue_func_t store_fn = factx->is_dst_fp32 ? fa_o_store_thread_f32 : fa_o_store_thread_f16; + + size_t max_rows = factx->o_tile_bytes / row_bytes; + if (max_rows >= factx->G && max_rows < n_rows_g) { + max_rows = (max_rows / factx->G) * factx->G; + } + if (max_rows == 0) { + max_rows = 1; + } + + for (size_t row_off = 0; row_off < n_rows_g; row_off += max_rows) { + if (row_off > 0) { + dma_queue_pop(dma_q); + } + const size_t n_rows = hex_smin(max_rows, n_rows_g - row_off); + uint32_t n = 1; + if (factx->n_hvx > 1 && n_rows >= (size_t) (factx->n_hvx * 2)) { + n = factx->n_hvx; + } + const size_t rows_per_t = hmx_ceil_div(n_rows, n); + fa_o_store_args_t args = { factx, vtcm_dst, o_tile_src, q_start, kv_head, row_off, n_rows, rows_per_t }; + work_queue_run(wp, store_fn, &args, n); + + fa_push_o_dma(dma_q, dst, vtcm_dst, row_bytes, row_bytes, + q_start, kv_head, ib3, factx->G, &factx->div_G, row_off, n_rows); } - size_t rows_per_t = hmx_ceil_div(n_rows_g, n); - fa_o_store_args_t args = { factx, dst, o_tile_src, q_start, kv_head, ib3, n_rows_g, rows_per_t }; - work_queue_func_t store_fn = factx->is_dst_fp32 ? fa_o_store_thread_f32 : fa_o_store_thread_f16; - work_queue_run(wp, store_fn, &args, n); } typedef struct { @@ -1227,9 +1803,7 @@ static inline void fa_softmax_impl( const size_t kv_rows = args->kv_rows; const size_t Bc = args->Bc; const size_t G = args->G; - const size_t n_tiles_per_bc = args->n_tiles_per_bc; const size_t n_row_vec_cnt = hmx_ceil_div(n_rows_g, 64); - const uint32_t im3 = has_mask ? fastmodulo(args->ib3, args->mask->ne[3], &factx->src3_div3) : 0; size_t vec_start = 0; size_t vec_end = n_row_vec_cnt; @@ -1479,10 +2053,10 @@ static inline void fa_softmax_impl( HVX_Vector v_s_minus_m0_1 = Q6_Vqf16_vsub_VhfVhf(my_row_buf0[ci1], v_dup_m0); HVX_Vector v_s_minus_m1_1 = Q6_Vqf16_vsub_VhfVhf(my_row_buf1[ci1], v_dup_m1); - HVX_Vector v_p_row0_hf_0 = hvx_vec_exp2_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m0_0)); - HVX_Vector v_p_row1_hf_0 = hvx_vec_exp2_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m1_0)); - HVX_Vector v_p_row0_hf_1 = hvx_vec_exp2_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m0_1)); - HVX_Vector v_p_row1_hf_1 = hvx_vec_exp2_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m1_1)); + HVX_Vector v_p_row0_hf_0 = hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m0_0)); + HVX_Vector v_p_row1_hf_0 = hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m1_0)); + HVX_Vector v_p_row0_hf_1 = hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m0_1)); + HVX_Vector v_p_row1_hf_1 = hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m1_1)); __fp16 * out_dtile0 = p_st_base + ci0 * HMX_FP16_TILE_N_ELMS * 2; __fp16 * out_dtile1 = p_st_base + ci1 * HMX_FP16_TILE_N_ELMS * 2; @@ -1514,8 +2088,8 @@ static inline void fa_softmax_impl( HVX_Vector v_s_minus_m0 = Q6_Vqf16_vsub_VhfVhf(my_row_buf0[ci], v_dup_m0); HVX_Vector v_s_minus_m1 = Q6_Vqf16_vsub_VhfVhf(my_row_buf1[ci], v_dup_m1); - HVX_Vector v_p_row0_hf = hvx_vec_exp2_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m0)); - HVX_Vector v_p_row1_hf = hvx_vec_exp2_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m1)); + HVX_Vector v_p_row0_hf = hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m0)); + HVX_Vector v_p_row1_hf = hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(v_s_minus_m1)); __fp16 * out_dtile = p_st_base + ci * HMX_FP16_TILE_N_ELMS * 2; HVX_Vector * pv_p_out0 = ((HVX_Vector *) out_dtile) + r1 / 2; HVX_Vector * pv_p_out1 = pv_p_out0 + 16; @@ -1559,122 +2133,849 @@ static inline void fa_softmax_impl( HVX_Vector v_m_diff1 = HVX_OP_SUB_F32(m_prev_v1, v_m_curr1); HVX_Vector v_m_diff_f16 = hvx_vec_f32_to_f16(v_m_diff0, v_m_diff1); - HVX_Vector exp_m_diff_f16 = hvx_vec_exp2_f16(v_m_diff_f16); + HVX_Vector exp_m_diff_f16 = hvx_vec_exp2_neg_f16(v_m_diff_f16); HVX_VectorPair exp_m_diff_pair = hvx_vec_f16_to_f32(exp_m_diff_f16); HVX_Vector exp_m_diff0 = Q6_V_lo_W(exp_m_diff_pair); HVX_Vector exp_m_diff1 = Q6_V_hi_W(exp_m_diff_pair); - HVX_VectorPair rowsum_acc_pair = hvx_vec_f16_to_f32(rowsum_acc_v); - HVX_Vector v_rowsum_acc_f32_0 = Q6_V_lo_W(rowsum_acc_pair); - HVX_Vector v_rowsum_acc_f32_1 = Q6_V_hi_W(rowsum_acc_pair); + HVX_VectorPair rowsum_acc_pair = hvx_vec_f16_to_f32(rowsum_acc_v); + HVX_Vector v_rowsum_acc_f32_0 = Q6_V_lo_W(rowsum_acc_pair); + HVX_Vector v_rowsum_acc_f32_1 = Q6_V_hi_W(rowsum_acc_pair); + + HVX_Vector l_prev_v0 = factx->vtcm_l_vec[r_vec_idx * 2 + 0]; + HVX_Vector l_prev_v1 = factx->vtcm_l_vec[r_vec_idx * 2 + 1]; + HVX_Vector v_l_curr0 = HVX_OP_ADD_F32(HVX_OP_MUL_F32(l_prev_v0, exp_m_diff0), v_rowsum_acc_f32_0); + HVX_Vector v_l_curr1 = HVX_OP_ADD_F32(HVX_OP_MUL_F32(l_prev_v1, exp_m_diff1), v_rowsum_acc_f32_1); + + factx->vtcm_m_vec[r_vec_idx * 2 + 0] = v_m_curr0; + factx->vtcm_m_vec[r_vec_idx * 2 + 1] = v_m_curr1; + factx->vtcm_l_vec[r_vec_idx * 2 + 0] = v_l_curr0; + factx->vtcm_l_vec[r_vec_idx * 2 + 1] = v_l_curr1; + + // Build diagonal tile D = diag(exp(m_diff)) + const HVX_Vector v_offsets = *(const HVX_Vector *) d_tile_scatter_offsets; + const HVX_VectorPred q_32_mask = Q6_Q_vsetq_R(32 * sizeof(__fp16)); + HVX_Vector v_exp_m_diff = exp_m_diff_f16; + + __fp16 * const d_tiles_out = factx->vtcm_d_tiles[args->buf_idx]; + + size_t t0 = r_vec_idx * 2; + if (t0 < args->n_row_tiles) { + const HVX_Vector v_content = v_exp_m_diff; + __fp16 * out_base = d_tiles_out + t0 * HMX_FP16_TILE_N_ELMS; + Q6_vscatter_QRMVhV(q_32_mask, (size_t) out_base, HMX_FP16_TILE_SIZE - 1, v_offsets, v_content); + } + + size_t t1 = r_vec_idx * 2 + 1; + if (t1 < args->n_row_tiles) { + const HVX_Vector v_content = Q6_V_vror_VR(v_exp_m_diff, 64); + __fp16 * out_base = d_tiles_out + t1 * HMX_FP16_TILE_N_ELMS; + Q6_vscatter_QRMVhV(q_32_mask, (size_t) out_base, HMX_FP16_TILE_SIZE - 1, v_offsets, v_content); + } + } + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_SFM, (uint16_t) (args->q_start * G + vec_start * 64)); +} + +static void fa_softmax_thread_nomask(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { + fa_softmax_impl(th, n, i, data, + /*has_mask=*/false, + /*mask_broadcast=*/false, + /*is_g1=*/false, + /*has_alibi=*/false, + /*has_softcap=*/false); +} + +static void fa_softmax_thread_mask_broadcast_g1(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { + fa_softmax_impl(th, n, i, data, + /*has_mask=*/true, + /*mask_broadcast=*/true, + /*is_g1=*/true, + /*has_alibi=*/false, + /*has_softcap=*/false); +} + +static void fa_softmax_thread_mask_broadcast_gn(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { + fa_softmax_impl(th, n, i, data, + /*has_mask=*/true, + /*mask_broadcast=*/true, + /*is_g1=*/false, + /*has_alibi=*/false, + /*has_softcap=*/false); +} + +static void fa_softmax_thread(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { + fa_softmax_args_t * args = (fa_softmax_args_t *) data; + struct hmx_fa_context * factx = args->factx; + + const bool has_mask = (args->mask != NULL); + const bool mask_broadcast = factx->mask_broadcast; + const bool is_g1 = (args->G == 1); + const bool has_alibi = args->has_alibi; + const bool has_softcap = factx->has_softcap; + + fa_softmax_impl(th, n, i, data, has_mask, mask_broadcast, is_g1, has_alibi, has_softcap); +} + +static inline HVX_Vector hvx_fa_load_sinks(const float * sinks_data, size_t idx, size_t count) { + const HVX_Vector * v_src = (const HVX_Vector *) sinks_data + (idx >> 5); + const size_t lane_off = idx & 31; + const size_t byte_off = lane_off * sizeof(float); + return (lane_off + count > 32) + ? Q6_V_valign_VVR(v_src[1], v_src[0], byte_off) + : Q6_V_vror_VR(v_src[0], byte_off); +} + +static __attribute__((noinline)) void fa_build_d_diag_inv_l(struct hmx_fa_context * factx, + size_t n_row_tiles, + size_t n_row_tiles_g_br, + uint32_t kv_head, + size_t n_rows_g) { + (void) n_row_tiles_g_br; + + // sinks: l += exp(sink - m * ln2) in f32, m and l are in the log2 domain + if (factx->sinks) { + const float * sinks_data = factx->vtcm_sinks; + const size_t G = factx->G; + const size_t head_base = (size_t) kv_head * G; + const HVX_Vector v_ln2 = Q6_V_vsplat_R(EXP_LOGN2); + const HVX_Vector v_head_sinks = (G <= 32) ? hvx_fa_load_sinks(sinks_data, head_base, G) : Q6_V_vzero(); + HVX_Vector v_sink = Q6_V_vzero(); + size_t g_prev = SIZE_MAX; + + for (size_t i = 0; i < n_row_tiles; ++i) { + // the sink pattern of a tile only depends on (i * 32) % G, rebuild it when that changes + const size_t r0 = i * 32; + const size_t g0 = fastmodulo(r0, G, &factx->div_G); + if (g0 != g_prev) { + const size_t rem_g = G - g0; + if (G <= 32) { + const HVX_Vector v_lo = Q6_V_vror_VR(v_head_sinks, g0 * sizeof(float)); + const HVX_Vector v_hi = Q6_V_vror_VR(v_head_sinks, 128 - rem_g * sizeof(float)); + v_sink = Q6_V_vmux_QVV(Q6_Q_vsetq2_R(rem_g * sizeof(float)), v_lo, v_hi); + for (size_t len = G; len < 32; len <<= 1) { + const HVX_VectorPred q_keep = Q6_Q_vsetq_R(len * sizeof(float)); + const HVX_Vector v_shifted = Q6_V_vror_VR(v_sink, 128 - len * sizeof(float)); + v_sink = Q6_V_vmux_QVV(q_keep, v_sink, v_shifted); + } + } else if (rem_g >= 32) { + v_sink = hvx_fa_load_sinks(sinks_data, head_base + g0, 32); + } else { + const HVX_Vector v_lo = hvx_fa_load_sinks(sinks_data, head_base + g0, rem_g); + const HVX_Vector v_hi = hvx_fa_load_sinks(sinks_data, head_base, 32 - rem_g); + v_sink = Q6_V_vmux_QVV(Q6_Q_vsetq_R(rem_g * sizeof(float)), v_lo, Q6_V_vror_VR(v_hi, 128 - rem_g * sizeof(float))); + } + g_prev = g0; + } + + HVX_Vector v_d = HVX_OP_SUB_F32(v_sink, HVX_OP_MUL_F32(factx->vtcm_m_vec[i], v_ln2)); + if (r0 + 32 > n_rows_g) { + const HVX_VectorPred q_valid = Q6_Q_vsetq_R((n_rows_g - r0) * sizeof(float)); + v_d = Q6_V_vmux_QVV(q_valid, v_d, Q6_V_vzero()); + } + factx->vtcm_l_vec[i] = HVX_OP_ADD_F32(factx->vtcm_l_vec[i], hvx_vec_exp_f32(v_d)); + } + } + + const HVX_Vector v_offsets = *(const HVX_Vector *) d_tile_scatter_offsets; + const HVX_VectorPred q_32_mask = Q6_Q_vsetq_R(32 * sizeof(__fp16)); + const HVX_Vector one = hvx_vec_splat_f32(1.0f); + + HVX_Vector v_content = Q6_V_vzero(); + for (size_t i = 0; i < n_row_tiles; ++i) { + if ((i % 2) == 0) { + HVX_Vector inv_lo = HVX_OP_MUL_F32(one, hvx_vec_inverse_f32(factx->vtcm_l_vec[i])); + HVX_Vector inv_hi = (i + 1 < n_row_tiles) ? HVX_OP_MUL_F32(one, hvx_vec_inverse_f32(factx->vtcm_l_vec[i + 1])) : Q6_V_vzero(); + v_content = hvx_vec_f32_to_f16(inv_lo, inv_hi); + } else { + v_content = Q6_V_vror_VR(v_content, 64); + } + + __fp16 * out_base = factx->vtcm_d_inv_l + i * HMX_FP16_TILE_N_ELMS; + Q6_vscatter_QRMVhV(q_32_mask, (size_t) out_base, HMX_FP16_TILE_SIZE - 1, v_offsets, v_content); + } +} + +static __attribute__((always_inline)) inline void fa_w8a8_mask_and_rowmax_pair( + struct hmx_fa_context * factx, + fa_softmax_args_t * args, + HVX_Vector * row_buf0, + HVX_Vector * row_buf1, + uint32_t r, + uint32_t r_vec_off, + size_t n_rows_g, + size_t kv_rows, + const __fp16 * slopes_row64, + HVX_Vector * v_rowmax0_out, + HVX_Vector * v_rowmax1_out, + const bool has_mask, + const bool mask_broadcast, + const bool is_g1, + const bool has_alibi +) { + int32_t slope0_u16 = 0; + int32_t slope1_u16 = 0; + if (has_alibi) { + const HVX_Vector v_sl = hvx_vmem(slopes_row64); + slope0_u16 = Q6_R_vextract_VR(v_sl, (int) (r_vec_off * 2)); + if (r + 1 < n_rows_g) { + slope1_u16 = Q6_R_vextract_VR(v_sl, (int) ((r_vec_off + 1) * 2)); + } + } + + HVX_Vector v_s_rowmax0 = Q6_Vh_vsplat_R(0xfbff); + HVX_Vector v_s_rowmax1 = Q6_Vh_vsplat_R(0xfbff); + + if (has_mask) { + #pragma clang loop pipeline(disable) unroll(disable) + for (size_t c = 0; c < kv_rows; c += 64) { + const HVX_Vector v_neg_inf = Q6_Vh_vsplat_R(0xfbff); + const HVX_Vector v_threshold = Q6_Vh_vsplat_R(0xcc00); // fp16 -16.0 + size_t ci = c / 64; + const size_t ne = hex_smin(kv_rows - c, 64); + HVX_VectorPred q_tail_keep = Q6_Q_vsetq2_R(ne * sizeof(__fp16)); + + HVX_Vector v_mask0, v_mask1; + if (mask_broadcast) { + if (is_g1) { + const size_t qi0 = r + 0; + v_mask0 = *(const HVX_Vector *) (args->mask_vtcm + qi0 * args->mask_vtcm_row_stride + c); + v_mask1 = v_neg_inf; + if (r + 1 < n_rows_g) { + const size_t qi1 = r + 1; + v_mask1 = *(const HVX_Vector *) (args->mask_vtcm + qi1 * args->mask_vtcm_row_stride + c); + } + } else { + const size_t qi0 = fastdiv(r + 0, &factx->div_G); + v_mask0 = *(const HVX_Vector *) (args->mask_vtcm + qi0 * args->mask_vtcm_row_stride + c); + v_mask1 = v_neg_inf; + if (r + 1 < n_rows_g) { + const size_t qi1 = fastdiv(r + 1, &factx->div_G); + if (qi1 == qi0) { + v_mask1 = v_mask0; + } else { + v_mask1 = *(const HVX_Vector *) (args->mask_vtcm + qi1 * args->mask_vtcm_row_stride + c); + } + } + } + } else { + const size_t m0 = r + 0; + v_mask0 = *(const HVX_Vector *) (args->mask_vtcm + m0 * args->mask_vtcm_row_stride + c); + v_mask1 = v_neg_inf; + if (r + 1 < n_rows_g) { + const size_t m1 = r + 1; + v_mask1 = *(const HVX_Vector *) (args->mask_vtcm + m1 * args->mask_vtcm_row_stride + c); + } + } + + const HVX_Vector v_log2e = hvx_vec_splat_f16(EXP_LOG2E_F); + { + HVX_VectorPred q_keep0 = Q6_Q_and_QQ(Q6_Q_vcmp_gt_VhfVhf(v_mask0, v_threshold), q_tail_keep); + HVX_Vector v_m0 = hvx_vec_mul_f16_f16(v_mask0, v_log2e); + if (has_alibi) { + v_m0 = hvx_vec_mul_f16_f16(v_m0, Q6_Vh_vsplat_R(slope0_u16)); + } + HVX_Vector v_r0 = Q6_V_vmux_QVV(q_keep0, hvx_vec_add_f16_f16(row_buf0[ci], v_m0), v_neg_inf); + row_buf0[ci] = v_r0; + v_s_rowmax0 = Q6_Vhf_vmax_VhfVhf(v_s_rowmax0, v_r0); + } + { + HVX_VectorPred q_keep1 = Q6_Q_and_QQ(Q6_Q_vcmp_gt_VhfVhf(v_mask1, v_threshold), q_tail_keep); + HVX_Vector v_m1 = hvx_vec_mul_f16_f16(v_mask1, v_log2e); + if (has_alibi) { + v_m1 = hvx_vec_mul_f16_f16(v_m1, Q6_Vh_vsplat_R(slope1_u16)); + } + HVX_Vector v_r1 = Q6_V_vmux_QVV(q_keep1, hvx_vec_add_f16_f16(row_buf1[ci], v_m1), v_neg_inf); + row_buf1[ci] = v_r1; + v_s_rowmax1 = Q6_Vhf_vmax_VhfVhf(v_s_rowmax1, v_r1); + } + } + } else { + size_t c = 0; + for (; c + 128 <= kv_rows; c += 128) { + size_t ci0 = c / 64; + size_t ci1 = ci0 + 1; + v_s_rowmax0 = Q6_Vhf_vmax_VhfVhf(v_s_rowmax0, row_buf0[ci0]); + v_s_rowmax1 = Q6_Vhf_vmax_VhfVhf(v_s_rowmax1, row_buf1[ci0]); + v_s_rowmax0 = Q6_Vhf_vmax_VhfVhf(v_s_rowmax0, row_buf0[ci1]); + v_s_rowmax1 = Q6_Vhf_vmax_VhfVhf(v_s_rowmax1, row_buf1[ci1]); + } + for (; c < kv_rows; c += 64) { + const HVX_Vector v_neg_inf = Q6_Vh_vsplat_R(0xfbff); + size_t ci = c / 64; + const size_t ne = hex_smin(kv_rows - c, 64); + HVX_VectorPred q_tail_keep = Q6_Q_vsetq2_R(ne * sizeof(__fp16)); + if (ne < 64) { + row_buf0[ci] = Q6_V_vmux_QVV(q_tail_keep, row_buf0[ci], v_neg_inf); + row_buf1[ci] = Q6_V_vmux_QVV(q_tail_keep, row_buf1[ci], v_neg_inf); + } + v_s_rowmax0 = Q6_Vhf_vmax_VhfVhf(v_s_rowmax0, row_buf0[ci]); + v_s_rowmax1 = Q6_Vhf_vmax_VhfVhf(v_s_rowmax1, row_buf1[ci]); + } + } + + const HVX_Vector v_neg_inf = Q6_Vh_vsplat_R(0xfbff); + *v_rowmax0_out = (r + 0 < n_rows_g) ? hvx_vec_reduce_max_f16(v_s_rowmax0) : v_neg_inf; + *v_rowmax1_out = (r + 1 < n_rows_g) ? hvx_vec_reduce_max_f16(v_s_rowmax1) : v_neg_inf; +} + +static __attribute__((noinline)) void fa_w8a8_exp_quant_quad( + HVX_Vector * restrict row_buf0, + HVX_Vector * restrict row_buf1, + HVX_Vector * restrict row_buf2, + HVX_Vector * restrict row_buf3, + uint8_t * restrict p_row64_base, + uint32_t rg, + size_t kv_rows, + uint32_t n_col_tiles, + int32_t smax0, + int32_t smax1, + int32_t smax2, + int32_t smax3, + uint32_t valid_mask, + float * restrict rowsum_dst, + uint32_t rmp0_bits, + uint32_t rmp1_bits, + uint32_t rmp2_bits, + uint32_t rmp3_bits +) { + HVX_Vector * bufs[4] = { row_buf0, row_buf1, row_buf2, row_buf3 }; + int32_t smaxs[4] = { smax0, smax1, smax2, smax3 }; + uint32_t rmps[4] = { rmp0_bits, rmp1_bits, rmp2_bits, rmp3_bits }; + int32_t sum_bits[4]; + + for (uint32_t k = 0; k < 4; ++k) { + HVX_Vector * rb = bufs[k]; + const int32_t sm = smaxs[k]; + HVX_Vector v_sum = Q6_V_vzero(); + #pragma clang loop pipeline(disable) unroll(disable) + for (size_t c = 0; c < kv_rows; c += 64) { + const size_t ci = c / 64; + HVX_Vector v_p = hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(rb[ci], Q6_Vh_vsplat_R(sm)))); + rb[ci] = v_p; + HVX_VectorPair vp = hvx_vec_f16_to_f32_shuff(v_p); + v_sum = Q6_Vqf32_vadd_Vqf32Vqf32(v_sum, Q6_Vqf32_vadd_VsfVsf(Q6_V_lo_W(vp), Q6_V_hi_W(vp))); + } + HVX_Vector v_s = Q6_Vsf_equals_Vqf32(hvx_qf32_mul_sf_scalar(hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(v_sum)), rmps[k])); + sum_bits[k] = Q6_R_vextract_VR(v_s, 0); + } + + { + HVX_Vector v02 = Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_vsplat_R(sum_bits[2]), Q6_V_vsplat_R(sum_bits[0]), -4)); + HVX_Vector v13 = Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_vsplat_R(sum_bits[3]), Q6_V_vsplat_R(sum_bits[1]), -4)); + hvx_vec_store_u(rowsum_dst, 4 * sizeof(float), Q6_V_lo_W(Q6_W_vshuff_VVR(v13, v02, -4))); + } + + #pragma clang loop pipeline(disable) unroll(disable) + for (size_t c = 0; c < kv_rows; c += 64) { + const size_t ci = c / 64; + const uint32_t kt = (uint32_t) (ci * 2); + const bool write_hi = (kt + 1 < n_col_tiles); + const HVX_Vector v_255_hf = hvx_vec_splat_f16(255.0f); + + HVX_Vector hf0 = (valid_mask & 1u) ? hvx_vec_mul_f16_f16(row_buf0[ci], v_255_hf) : Q6_V_vzero(); + HVX_Vector hf1 = (valid_mask & 2u) ? hvx_vec_mul_f16_f16(row_buf1[ci], v_255_hf) : Q6_V_vzero(); + HVX_Vector hf2 = (valid_mask & 4u) ? hvx_vec_mul_f16_f16(row_buf2[ci], v_255_hf) : Q6_V_vzero(); + HVX_Vector hf3 = (valid_mask & 8u) ? hvx_vec_mul_f16_f16(row_buf3[ci], v_255_hf) : Q6_V_vzero(); + + hmx_fa_w8a8_pack_p_quad_u8_sm(p_row64_base, kt, rg, write_hi, hf0, hf1, hf2, hf3); + } +} + +static __attribute__((noinline)) void fa_w8a8_decode_s_quad_rows_nocap( + const uint8_t * restrict tile_base, + const float * restrict dw_base, + HVX_Vector * restrict row_buf0, + HVX_Vector * restrict row_buf1, + HVX_Vector * restrict row_buf2, + HVX_Vector * restrict row_buf3, + size_t kv_rows, + uint32_t da0, + uint32_t da1, + uint32_t da2, + uint32_t da3 +) { + #pragma clang loop pipeline(disable) unroll(disable) + for (size_t c = 0; c < kv_rows; c += 64) { + const size_t ci = c / 64; + const HVX_Vector sign_80 = Q6_Vb_vsplat_R(0x80); + HVX_Vector s0_lo, s1_lo, s2_lo, s3_lo; + hmx_fa_w8a8_eval_s_tile_quad(tile_base, dw_base, c, da0, da1, da2, da3, sign_80, + &s0_lo, &s1_lo, &s2_lo, &s3_lo); + + HVX_Vector s0_hi = Q6_V_vzero(); + HVX_Vector s1_hi = Q6_V_vzero(); + HVX_Vector s2_hi = Q6_V_vzero(); + HVX_Vector s3_hi = Q6_V_vzero(); + if (c + 32 < kv_rows) { + hmx_fa_w8a8_eval_s_tile_quad(tile_base, dw_base, c + 32, da0, da1, da2, da3, sign_80, + &s0_hi, &s1_hi, &s2_hi, &s3_hi); + } + + row_buf0[ci] = hvx_vec_f32_to_f16(s0_lo, s0_hi); + row_buf1[ci] = hvx_vec_f32_to_f16(s1_lo, s1_hi); + row_buf2[ci] = hvx_vec_f32_to_f16(s2_lo, s2_hi); + row_buf3[ci] = hvx_vec_f32_to_f16(s3_lo, s3_hi); + } +} + +static __attribute__((noinline)) void fa_w8a8_decode_s_quad_rows_cap( + const uint8_t * restrict tile_base, + const float * restrict dw_base, + HVX_Vector * restrict row_buf0, + HVX_Vector * restrict row_buf1, + HVX_Vector * restrict row_buf2, + HVX_Vector * restrict row_buf3, + size_t kv_rows, + uint32_t da0, + uint32_t da1, + uint32_t da2, + uint32_t da3, + const __fp16 * logit_softcap_ptr +) { + fa_w8a8_decode_s_quad_rows_nocap( + tile_base, dw_base, row_buf0, row_buf1, row_buf2, row_buf3, + kv_rows, da0, da1, da2, da3); + + HVX_Vector * bufs[4] = { row_buf0, row_buf1, row_buf2, row_buf3 }; + const __fp16 cap = *logit_softcap_ptr; + for (uint32_t k = 0; k < 4; ++k) { + HVX_Vector * rb = bufs[k]; + #pragma clang loop pipeline(disable) unroll(disable) + for (size_t c = 0; c < kv_rows; c += 64) { + const size_t ci = c / 64; + rb[ci] = hvx_vec_mul_f16_f16(hvx_vec_tanh_f16(rb[ci]), hvx_vec_splat_f16(cap)); + } + } +} + +static __attribute__((always_inline)) inline void fa_w8a8_softmax_impl( + const htp_thread_t * th, unsigned int n, unsigned int i, void * data, + const bool has_mask, + const bool mask_broadcast, + const bool is_g1, + const bool has_alibi, + const bool has_softcap +) { + fa_softmax_args_t * args = (fa_softmax_args_t *) data; + struct hmx_fa_context * factx = args->factx; + + const size_t n_rows_g = args->n_rows_g; + const size_t kv_rows = args->kv_rows; + const size_t G = args->G; + const size_t n_row_vec_cnt = hmx_ceil_div(n_rows_g, 64); + + size_t vec_start = 0; + size_t vec_end = n_row_vec_cnt; + if (n > 1) { + const size_t vecs_per_t = fastdiv(n_row_vec_cnt + n - 1, &args->thread_div); + vec_start = i * vecs_per_t; + vec_end = hex_smin(vec_start + vecs_per_t, n_row_vec_cnt); + } + + if (vec_start >= n_row_vec_cnt) { + return; + } + + struct htp_thread_trace * tr = th->trace; + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_FA_SFM, (uint16_t) (args->q_start * G + vec_start * 64)); + + const size_t row_buf_stride = factx->row_buf_stride; + HVX_Vector * my_row_buf0 = factx->vtcm_row_bufs + (size_t) i * 4 * row_buf_stride; + HVX_Vector * my_row_buf1 = my_row_buf0 + row_buf_stride; + HVX_Vector * my_row_buf2 = my_row_buf1 + row_buf_stride; + HVX_Vector * my_row_buf3 = my_row_buf2 + row_buf_stride; + + const float * dw_base = factx->vtcm_k_scales[args->buf_idx]; + const uint8_t * s_base = (const uint8_t *) factx->vtcm_s_tiles[args->buf_idx]; + uint8_t * p_base = (uint8_t *) factx->vtcm_p_tiles[args->buf_idx]; + float * p_scales = factx->vtcm_p_scales[args->buf_idx]; + float * s_rowmax = (float *) factx->vtcm_s_rowmax; + float * p_rowsum = (float *) factx->vtcm_p_rowsum; + const uint32_t n_ct = (uint32_t) args->n_col_tiles; + + for (size_t r_vec_idx = vec_start; r_vec_idx < vec_end; ++r_vec_idx) { + factx->vtcm_s_rowmax[r_vec_idx * 2 + 0] = factx->vtcm_m_vec[r_vec_idx * 2 + 0]; + factx->vtcm_s_rowmax[r_vec_idx * 2 + 1] = factx->vtcm_m_vec[r_vec_idx * 2 + 1]; + factx->vtcm_p_rowsum[r_vec_idx * 2 + 0] = Q6_V_vzero(); + factx->vtcm_p_rowsum[r_vec_idx * 2 + 1] = Q6_V_vzero(); + + const uint8_t * s_row64_base = s_base + r_vec_idx * n_ct * 2 * HMX_W8A8_ACT_TILE_SIZE; + uint8_t * p_row64_base = p_base + r_vec_idx * n_ct * HMX_W8A8_ACT_TILE_SIZE; + + #pragma clang loop unroll(disable) + for (uint32_t r_vec_off = 0; r_vec_off < 64; r_vec_off += 4) { + const uint32_t r = (uint32_t) (r_vec_idx * 64 + r_vec_off); + if (r >= n_rows_g) { + break; + } + + const uint32_t rg = r_vec_off >> 2; + const uint8_t * tile_base = s_row64_base + (size_t) rg * 128; + + const HVX_Vector v_da = hvx_vmem(factx->vtcm_q_scales + r_vec_idx * 64 + (r_vec_off & 32u)); + const int doff = (int) ((r_vec_off & 31u) * 4u); + const uint32_t da0 = (uint32_t) Q6_R_vextract_VR(v_da, doff + 0); + const uint32_t da1 = (uint32_t) Q6_R_vextract_VR(v_da, doff + 4); + const uint32_t da2 = (uint32_t) Q6_R_vextract_VR(v_da, doff + 8); + const uint32_t da3 = (uint32_t) Q6_R_vextract_VR(v_da, doff + 12); + + if (has_softcap) { + fa_w8a8_decode_s_quad_rows_cap( + tile_base, dw_base, + my_row_buf0, my_row_buf1, my_row_buf2, my_row_buf3, + kv_rows, da0, da1, da2, da3, &factx->logit_softcap); + } else { + fa_w8a8_decode_s_quad_rows_nocap( + tile_base, dw_base, + my_row_buf0, my_row_buf1, my_row_buf2, my_row_buf3, + kv_rows, da0, da1, da2, da3); + } + + const HVX_Vector v_neg_inf = Q6_Vh_vsplat_R(0xfbff); + const __fp16 * slopes_row64 = args->slopes + r_vec_idx * 64; + HVX_Vector v_smax0, v_smax1, v_smax2, v_smax3; + fa_w8a8_mask_and_rowmax_pair( + factx, args, my_row_buf0, my_row_buf1, + r + 0, r_vec_off + 0, n_rows_g, kv_rows, slopes_row64, + &v_smax0, &v_smax1, has_mask, mask_broadcast, is_g1, has_alibi); + if (r + 2 < n_rows_g) { + fa_w8a8_mask_and_rowmax_pair( + factx, args, my_row_buf2, my_row_buf3, + r + 2, r_vec_off + 2, n_rows_g, kv_rows, slopes_row64, + &v_smax2, &v_smax3, has_mask, mask_broadcast, is_g1, has_alibi); + } else { + v_smax2 = v_neg_inf; + v_smax3 = v_neg_inf; + } + + // Compute m_new = max(m_prev, s_rowmax) and store to vtcm_s_rowmax + HVX_Vector m_src = factx->vtcm_m_vec[r_vec_idx * 2 + (r_vec_off >> 5)]; + uint32_t m_off = r_vec_off & 31u; + HVX_Vector mp0 = hvx_vec_repl_f32(Q6_V_vror_VR(m_src, (m_off + 0) * 4)); + HVX_Vector mp1 = hvx_vec_repl_f32(Q6_V_vror_VR(m_src, (m_off + 1) * 4)); + HVX_Vector mp2 = hvx_vec_repl_f32(Q6_V_vror_VR(m_src, (m_off + 2) * 4)); + HVX_Vector mp3 = hvx_vec_repl_f32(Q6_V_vror_VR(m_src, (m_off + 3) * 4)); + + HVX_Vector v_dup_m0 = Q6_Vhf_vmax_VhfVhf(hvx_vec_f32_to_f16(mp0, mp0), v_smax0); + HVX_Vector v_dup_m1 = Q6_Vhf_vmax_VhfVhf(hvx_vec_f32_to_f16(mp1, mp1), v_smax1); + HVX_Vector v_dup_m2 = Q6_Vhf_vmax_VhfVhf(hvx_vec_f32_to_f16(mp2, mp2), v_smax2); + HVX_Vector v_dup_m3 = Q6_Vhf_vmax_VhfVhf(hvx_vec_f32_to_f16(mp3, mp3), v_smax3); + + { + HVX_Vector fm0 = Q6_V_lo_W(hvx_vec_f16_to_f32(v_dup_m0)); + HVX_Vector fm1 = Q6_V_lo_W(hvx_vec_f16_to_f32(v_dup_m1)); + HVX_Vector fm2 = Q6_V_lo_W(hvx_vec_f16_to_f32(v_dup_m2)); + HVX_Vector fm3 = Q6_V_lo_W(hvx_vec_f16_to_f32(v_dup_m3)); + HVX_Vector m02 = Q6_V_lo_W(Q6_W_vshuff_VVR(fm2, fm0, -4)); + HVX_Vector m13 = Q6_V_lo_W(Q6_W_vshuff_VVR(fm3, fm1, -4)); + hvx_vec_store_u(s_rowmax + r, 4 * sizeof(float), Q6_V_lo_W(Q6_W_vshuff_VVR(m13, m02, -4))); + } + + // row_max_p = exp2(s_rowmax - m_new); zero if row is masked or out of bounds + HVX_VectorPred q_ok0 = Q6_Q_vcmp_gt_VhfVhf(v_smax0, v_neg_inf); + HVX_VectorPred q_ok1 = Q6_Q_vcmp_gt_VhfVhf(v_smax1, v_neg_inf); + HVX_VectorPred q_ok2 = Q6_Q_vcmp_gt_VhfVhf(v_smax2, v_neg_inf); + HVX_VectorPred q_ok3 = Q6_Q_vcmp_gt_VhfVhf(v_smax3, v_neg_inf); + + const HVX_Vector v_one_i = Q6_V_vsplat_R(1); + uint32_t valid_mask = 0; + valid_mask |= (Q6_R_vextract_VR(Q6_V_vmux_QVV(q_ok0, v_one_i, Q6_V_vzero()), 0) & 1u) << 0; + valid_mask |= (Q6_R_vextract_VR(Q6_V_vmux_QVV(q_ok1, v_one_i, Q6_V_vzero()), 0) & 1u) << 1; + valid_mask |= (Q6_R_vextract_VR(Q6_V_vmux_QVV(q_ok2, v_one_i, Q6_V_vzero()), 0) & 1u) << 2; + valid_mask |= (Q6_R_vextract_VR(Q6_V_vmux_QVV(q_ok3, v_one_i, Q6_V_vzero()), 0) & 1u) << 3; + + const int32_t smax0 = Q6_R_vextract_VR(v_smax0, 0); + const int32_t smax1 = Q6_R_vextract_VR(v_smax1, 0); + const int32_t smax2 = Q6_R_vextract_VR(v_smax2, 0); + const int32_t smax3 = Q6_R_vextract_VR(v_smax3, 0); + + HVX_Vector v_rmp_hf0 = Q6_V_vmux_QVV(q_ok0, hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(v_smax0, v_dup_m0))), Q6_V_vzero()); + HVX_Vector v_rmp_hf1 = Q6_V_vmux_QVV(q_ok1, hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(v_smax1, v_dup_m1))), Q6_V_vzero()); + HVX_Vector v_rmp_hf2 = Q6_V_vmux_QVV(q_ok2, hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(v_smax2, v_dup_m2))), Q6_V_vzero()); + HVX_Vector v_rmp_hf3 = Q6_V_vmux_QVV(q_ok3, hvx_vec_exp2_neg_f16(Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(v_smax3, v_dup_m3))), Q6_V_vzero()); + + const uint32_t rmp0_bits = (uint32_t) Q6_R_vextract_VR(Q6_V_lo_W(hvx_vec_f16_to_f32(v_rmp_hf0)), 0); + const uint32_t rmp1_bits = (uint32_t) Q6_R_vextract_VR(Q6_V_lo_W(hvx_vec_f16_to_f32(v_rmp_hf1)), 0); + const uint32_t rmp2_bits = (uint32_t) Q6_R_vextract_VR(Q6_V_lo_W(hvx_vec_f16_to_f32(v_rmp_hf2)), 0); + const uint32_t rmp3_bits = (uint32_t) Q6_R_vextract_VR(Q6_V_lo_W(hvx_vec_f16_to_f32(v_rmp_hf3)), 0); + + { + const HVX_Vector v_inv255 = hvx_vec_splat_f32(1.0f / 255.0f); + HVX_Vector vd0 = hvx_vec_mul_f32_f32(Q6_V_vsplat_R((int32_t) rmp0_bits), v_inv255); + HVX_Vector vd1 = hvx_vec_mul_f32_f32(Q6_V_vsplat_R((int32_t) rmp1_bits), v_inv255); + HVX_Vector vd2 = hvx_vec_mul_f32_f32(Q6_V_vsplat_R((int32_t) rmp2_bits), v_inv255); + HVX_Vector vd3 = hvx_vec_mul_f32_f32(Q6_V_vsplat_R((int32_t) rmp3_bits), v_inv255); + HVX_Vector v_d02 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd2, vd0, -4)); + HVX_Vector v_d13 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd3, vd1, -4)); + HVX_Vector v_dp = Q6_V_lo_W(Q6_W_vshuff_VVR(v_d13, v_d02, -4)); + hvx_vec_store_u(p_scales + r, 4 * sizeof(float), v_dp); + } + + fa_w8a8_exp_quant_quad( + my_row_buf0, my_row_buf1, my_row_buf2, my_row_buf3, + p_row64_base, rg, kv_rows, n_ct, + smax0, smax1, smax2, smax3, valid_mask, + p_rowsum + r, rmp0_bits, rmp1_bits, rmp2_bits, rmp3_bits); + } + + HVX_Vector m_prev_v0 = factx->vtcm_m_vec[r_vec_idx * 2 + 0]; + HVX_Vector m_prev_v1 = factx->vtcm_m_vec[r_vec_idx * 2 + 1]; + HVX_Vector v_m_curr0 = Q6_Vsf_vmax_VsfVsf(m_prev_v0, factx->vtcm_s_rowmax[r_vec_idx * 2 + 0]); + HVX_Vector v_m_curr1 = Q6_Vsf_vmax_VsfVsf(m_prev_v1, factx->vtcm_s_rowmax[r_vec_idx * 2 + 1]); + + HVX_Vector v_m_diff0 = HVX_OP_SUB_F32(m_prev_v0, v_m_curr0); + HVX_Vector v_m_diff1 = HVX_OP_SUB_F32(m_prev_v1, v_m_curr1); + + HVX_Vector v_m_diff_f16 = hvx_vec_f32_to_f16(v_m_diff0, v_m_diff1); + HVX_Vector exp_m_diff_f16 = hvx_vec_exp2_neg_f16(v_m_diff_f16); + HVX_VectorPair exp_m_diff_pair = hvx_vec_f16_to_f32(exp_m_diff_f16); + HVX_Vector exp_m_diff0 = Q6_V_lo_W(exp_m_diff_pair); + HVX_Vector exp_m_diff1 = Q6_V_hi_W(exp_m_diff_pair); HVX_Vector l_prev_v0 = factx->vtcm_l_vec[r_vec_idx * 2 + 0]; HVX_Vector l_prev_v1 = factx->vtcm_l_vec[r_vec_idx * 2 + 1]; - HVX_Vector v_l_curr0 = HVX_OP_ADD_F32(HVX_OP_MUL_F32(l_prev_v0, exp_m_diff0), v_rowsum_acc_f32_0); - HVX_Vector v_l_curr1 = HVX_OP_ADD_F32(HVX_OP_MUL_F32(l_prev_v1, exp_m_diff1), v_rowsum_acc_f32_1); + HVX_Vector v_l_curr0 = HVX_OP_ADD_F32(HVX_OP_MUL_F32(l_prev_v0, exp_m_diff0), factx->vtcm_p_rowsum[r_vec_idx * 2 + 0]); + HVX_Vector v_l_curr1 = HVX_OP_ADD_F32(HVX_OP_MUL_F32(l_prev_v1, exp_m_diff1), factx->vtcm_p_rowsum[r_vec_idx * 2 + 1]); factx->vtcm_m_vec[r_vec_idx * 2 + 0] = v_m_curr0; factx->vtcm_m_vec[r_vec_idx * 2 + 1] = v_m_curr1; factx->vtcm_l_vec[r_vec_idx * 2 + 0] = v_l_curr0; factx->vtcm_l_vec[r_vec_idx * 2 + 1] = v_l_curr1; - // Build diagonal tile D = diag(exp(m_diff)) - const HVX_Vector v_offsets = *(const HVX_Vector *) d_tile_scatter_offsets; - const HVX_VectorPred q_32_mask = Q6_Q_vsetq_R(32 * sizeof(__fp16)); - HVX_Vector v_exp_m_diff = exp_m_diff_f16; - - __fp16 * const d_tiles_out = factx->vtcm_d_tiles[args->buf_idx]; - - size_t t0 = r_vec_idx * 2; - if (t0 < args->n_row_tiles) { - const HVX_Vector v_content = v_exp_m_diff; - __fp16 * out_base = d_tiles_out + t0 * HMX_FP16_TILE_N_ELMS; - Q6_vscatter_QRMVhV(q_32_mask, (size_t) out_base, HMX_FP16_TILE_SIZE - 1, v_offsets, v_content); - } - - size_t t1 = r_vec_idx * 2 + 1; - if (t1 < args->n_row_tiles) { - const HVX_Vector v_content = Q6_V_vror_VR(v_exp_m_diff, 64); - __fp16 * out_base = d_tiles_out + t1 * HMX_FP16_TILE_N_ELMS; - Q6_vscatter_QRMVhV(q_32_mask, (size_t) out_base, HMX_FP16_TILE_SIZE - 1, v_offsets, v_content); - } + HVX_Vector * exp_mdiff_out = (HVX_Vector *) (factx->vtcm_exp_mdiff[args->buf_idx] + r_vec_idx * 64); + exp_mdiff_out[0] = exp_m_diff0; + exp_mdiff_out[1] = exp_m_diff1; } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_FA_SFM, (uint16_t) (args->q_start * G + vec_start * 64)); } -static void fa_softmax_thread_nomask(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { - fa_softmax_impl(th, n, i, data, - /*has_mask=*/false, - /*mask_broadcast=*/false, - /*is_g1=*/false, - /*has_alibi=*/false, - /*has_softcap=*/false); +static void fa_w8a8_softmax_thread_nomask(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { + fa_w8a8_softmax_impl(th, n, i, data, false, false, false, false, false); } -static void fa_softmax_thread_mask_broadcast_g1(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { - fa_softmax_impl(th, n, i, data, - /*has_mask=*/true, - /*mask_broadcast=*/true, - /*is_g1=*/true, - /*has_alibi=*/false, - /*has_softcap=*/false); +static void fa_w8a8_softmax_thread_mask_broadcast_g1(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { + fa_w8a8_softmax_impl(th, n, i, data, true, true, true, false, false); } -static void fa_softmax_thread_mask_broadcast_gn(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { - fa_softmax_impl(th, n, i, data, - /*has_mask=*/true, - /*mask_broadcast=*/true, - /*is_g1=*/false, - /*has_alibi=*/false, - /*has_softcap=*/false); +static void fa_w8a8_softmax_thread_mask_broadcast_gn(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { + fa_w8a8_softmax_impl(th, n, i, data, true, true, false, false, false); } -static void fa_softmax_thread(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { +static void fa_w8a8_softmax_thread(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { fa_softmax_args_t * args = (fa_softmax_args_t *) data; struct hmx_fa_context * factx = args->factx; + fa_w8a8_softmax_impl(th, n, i, data, + args->mask != NULL, factx->mask_broadcast, args->G == 1, + args->has_alibi, factx->has_softcap); +} - const bool has_mask = (args->mask != NULL); - const bool mask_broadcast = factx->mask_broadcast; - const bool is_g1 = (args->G == 1); - const bool has_alibi = args->has_alibi; - const bool has_softcap = factx->has_softcap; +static void fa_phase_softmax_and_build_d(struct hmx_fa_context * factx, + fa_softmax_args_t * sargs, + size_t n_row_tiles, + size_t n_row_tiles_g_br) { + work_queue_t wp = factx->octx->ctx->hvx_queue; + const size_t n_row_vec_cnt = hmx_ceil_div(sargs->n_rows_g, 64); - fa_softmax_impl(th, n, i, data, has_mask, mask_broadcast, is_g1, has_alibi, has_softcap); + work_queue_func_t softmax_fn; + if (factx->is_w8a8) { + softmax_fn = fa_w8a8_softmax_thread; + if (sargs->mask == NULL && !factx->has_softcap && !sargs->has_alibi) { + softmax_fn = fa_w8a8_softmax_thread_nomask; + } else if (sargs->mask != NULL && factx->mask_broadcast && !factx->has_softcap && !sargs->has_alibi) { + softmax_fn = (sargs->G == 1) ? fa_w8a8_softmax_thread_mask_broadcast_g1 : fa_w8a8_softmax_thread_mask_broadcast_gn; + } + } else { + softmax_fn = fa_softmax_thread; + if (sargs->mask == NULL && !factx->has_softcap && !sargs->has_alibi) { + softmax_fn = fa_softmax_thread_nomask; + } else if (sargs->mask != NULL && factx->mask_broadcast && !factx->has_softcap && !sargs->has_alibi) { + softmax_fn = (sargs->G == 1) ? fa_softmax_thread_mask_broadcast_g1 : fa_softmax_thread_mask_broadcast_gn; + } + } + + uint32_t n_use = 1; + if (factx->n_hvx > 1 && n_row_vec_cnt >= 2) { + n_use = (uint32_t) hex_smin((size_t) factx->n_hvx, n_row_vec_cnt); + sargs->thread_div = init_fastdiv_values(n_use); + } + work_queue_run(wp, softmax_fn, sargs, n_use); } -static inline HVX_Vector hvx_fa_load_sinks(const float * sinks_data, size_t idx, size_t count) { - const HVX_Vector * v_src = (const HVX_Vector *) sinks_data + (idx >> 5); - const size_t lane_off = idx & 31; - const size_t byte_off = lane_off * sizeof(float); - return (lane_off + count > 32) - ? Q6_V_valign_VVR(v_src[1], v_src[0], byte_off) - : Q6_V_vror_VR(v_src[0], byte_off); +typedef struct { + struct hmx_fa_context * factx; + size_t buf_idx; + size_t n_rows_g; + uint32_t q_start; + bool is_first; +} fa_w8a8_o_accum_args_t; + +static __attribute__((noinline)) void fa_w8a8_o_accum_quad_first( + const uint8_t * restrict tile_base, + const float * restrict dv_scales, + float * restrict o0, + float * restrict o1, + float * restrict o2, + float * restrict o3, + size_t DV, + uint32_t dp0, + uint32_t dp1, + uint32_t dp2, + uint32_t dp3) { + const HVX_Vector sign_80 = Q6_Vb_vsplat_R(0x80); + #pragma clang loop pipeline(disable) unroll(disable) + for (size_t c = 0; c < DV; c += 32) { + HVX_Vector do0, do1, do2, do3; + hmx_fa_w8a8_eval_s_tile_quad(tile_base, dv_scales, c, dp0, dp1, dp2, dp3, sign_80, + &do0, &do1, &do2, &do3); + *(HVX_Vector *) (o0 + c) = do0; + *(HVX_Vector *) (o1 + c) = do1; + *(HVX_Vector *) (o2 + c) = do2; + *(HVX_Vector *) (o3 + c) = do3; + } } -static __attribute__((noinline)) void fa_build_d_diag_inv_l(struct hmx_fa_context * factx, - size_t n_row_tiles, - size_t n_row_tiles_g_br, - uint32_t kv_head, - size_t n_rows_g) { - (void) n_row_tiles_g_br; +static __attribute__((noinline)) void fa_w8a8_o_accum_quad_update( + const uint8_t * restrict tile_base, + const float * restrict dv_scales, + float * restrict o0, + float * restrict o1, + float * restrict o2, + float * restrict o3, + size_t DV, + uint32_t dp0, + uint32_t dp1, + uint32_t dp2, + uint32_t dp3, + uint32_t em0, + uint32_t em1, + uint32_t em2, + uint32_t em3) { + const HVX_Vector sign_80 = Q6_Vb_vsplat_R(0x80); + #pragma clang loop pipeline(disable) unroll(disable) + for (size_t c = 0; c < DV; c += 32) { + HVX_Vector do0, do1, do2, do3; + hmx_fa_w8a8_eval_s_tile_quad(tile_base, dv_scales, c, dp0, dp1, dp2, dp3, sign_80, + &do0, &do1, &do2, &do3); + *(HVX_Vector *) (o0 + c) = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(hvx_qf32_mul_sf_scalar(*(const HVX_Vector *) (o0 + c), em0), do0)); + *(HVX_Vector *) (o1 + c) = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(hvx_qf32_mul_sf_scalar(*(const HVX_Vector *) (o1 + c), em1), do1)); + *(HVX_Vector *) (o2 + c) = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(hvx_qf32_mul_sf_scalar(*(const HVX_Vector *) (o2 + c), em2), do2)); + *(HVX_Vector *) (o3 + c) = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(hvx_qf32_mul_sf_scalar(*(const HVX_Vector *) (o3 + c), em3), do3)); + } +} - // sinks: l += exp(sink - m * ln2) in f32, m and l are in the log2 domain - if (factx->sinks) { - const float * sinks_data = factx->vtcm_sinks; - const size_t G = factx->G; - const size_t head_base = (size_t) kv_head * G; - const HVX_Vector v_ln2 = Q6_V_vsplat_R(EXP_LOGN2); - const HVX_Vector v_head_sinks = (G <= 32) ? hvx_fa_load_sinks(sinks_data, head_base, G) : Q6_V_vzero(); - HVX_Vector v_sink = Q6_V_vzero(); - size_t g_prev = SIZE_MAX; +static void fa_w8a8_o_accum_thread(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { + fa_w8a8_o_accum_args_t * args = (fa_w8a8_o_accum_args_t *) data; + struct hmx_fa_context * factx = args->factx; - for (size_t i = 0; i < n_row_tiles; ++i) { - // the sink pattern of a tile only depends on (i * 32) % G, rebuild it when that changes - const size_t r0 = i * 32; - const size_t g0 = fastmodulo(r0, G, &factx->div_G); - if (g0 != g_prev) { + const size_t n_rows_g = args->n_rows_g; + const size_t n_quads = hmx_ceil_div(n_rows_g, 4); + const size_t quads_per_t = hmx_ceil_div(n_quads, n); + const size_t q_start_idx = (size_t) i * quads_per_t; + const size_t q_end_idx = hex_smin(q_start_idx + quads_per_t, n_quads); + + if (q_start_idx >= n_quads) { + return; + } + + struct htp_thread_trace * tr = th->trace; + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * factx->G + q_start_idx * 4)); + + const size_t DV = factx->DV; + const size_t n_v_tiles = DV / HMX_W8A8_TILE_N_COLS; + const uint8_t * do_tiles = factx->vtcm_do_tiles; + const float * dv_scales = factx->vtcm_v_scales[args->buf_idx]; + const float * p_scales = factx->vtcm_p_scales[args->buf_idx]; + const float * exp_mdiff = factx->vtcm_exp_mdiff[args->buf_idx]; + float * o_f32 = factx->vtcm_o_f32; + const bool is_first = args->is_first; + + for (size_t quad = q_start_idx; quad < q_end_idx; ++quad) { + const size_t r = quad * 4; + const size_t r_vec_idx = r >> 6; + const size_t r_tile = r >> 5; + const uint32_t r_vec_off = (uint32_t) (r & 63); + const uint32_t rg = r_vec_off >> 2; + const int off = (int) ((r & 31u) * 4u); + + const HVX_Vector v_dp = hvx_vmem(p_scales + r_tile * 32); + const uint32_t dp0 = (uint32_t) Q6_R_vextract_VR(v_dp, off + 0); + const uint32_t dp1 = (uint32_t) Q6_R_vextract_VR(v_dp, off + 4); + const uint32_t dp2 = (uint32_t) Q6_R_vextract_VR(v_dp, off + 8); + const uint32_t dp3 = (uint32_t) Q6_R_vextract_VR(v_dp, off + 12); + + const uint8_t * tile_base = do_tiles + r_vec_idx * n_v_tiles * 2 * HMX_W8A8_ACT_TILE_SIZE + (size_t) rg * 128; + float * o0 = o_f32 + (r + 0) * DV; + float * o1 = o_f32 + (r + 1) * DV; + float * o2 = o_f32 + (r + 2) * DV; + float * o3 = o_f32 + (r + 3) * DV; + + if (is_first) { + fa_w8a8_o_accum_quad_first(tile_base, dv_scales, o0, o1, o2, o3, DV, dp0, dp1, dp2, dp3); + } else { + const HVX_Vector v_em = hvx_vmem(exp_mdiff + r_tile * 32); + const uint32_t em0 = (uint32_t) Q6_R_vextract_VR(v_em, off + 0); + const uint32_t em1 = (uint32_t) Q6_R_vextract_VR(v_em, off + 4); + const uint32_t em2 = (uint32_t) Q6_R_vextract_VR(v_em, off + 8); + const uint32_t em3 = (uint32_t) Q6_R_vextract_VR(v_em, off + 12); + fa_w8a8_o_accum_quad_update(tile_base, dv_scales, o0, o1, o2, o3, DV, dp0, dp1, dp2, dp3, em0, em1, em2, em3); + } + } + + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * factx->G + q_start_idx * 4)); +} + +static void fa_phase_w8a8_o_accum(struct hmx_fa_context * factx, + size_t buf_idx, + size_t n_rows_g, + uint32_t q_start, + bool is_first) { + work_queue_t wp = factx->octx->ctx->hvx_queue; + const size_t n_q = hmx_ceil_div(n_rows_g, 4); + const uint32_t n = (uint32_t) hex_smin((size_t) factx->n_hvx, n_q); + fa_w8a8_o_accum_args_t args = { factx, buf_idx, n_rows_g, q_start, is_first }; + work_queue_run(wp, fa_w8a8_o_accum_thread, &args, n); +} + +static void fa_w8a8_o_store_thread(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { + fa_o_store_args_t * args = (fa_o_store_args_t *) data; + struct hmx_fa_context * factx = args->factx; + + const size_t n_rows = args->n_rows; + const size_t rows_per_t = args->rows_per_t; + const size_t start = (size_t) i * rows_per_t; + const size_t end = hex_smin(start + rows_per_t, n_rows); + + if (start >= n_rows) { + return; + } + + const size_t G = factx->G; + const size_t DV = factx->DV; + + struct htp_thread_trace * tr = th->trace; + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * G + start)); + + const uint32_t kv_head = args->kv_head; + float * o_f32 = factx->vtcm_o_f32; + const bool has_sinks = (factx->sinks != NULL); + const bool is_f32 = factx->is_dst_fp32; + const size_t head_base = (size_t) kv_head * G; + const HVX_Vector v_ln2 = Q6_V_vsplat_R(EXP_LOGN2); + const HVX_Vector v_one = hvx_vec_splat_f32(1.0f); + const HVX_Vector v_head_sinks = (has_sinks && G <= 32) ? hvx_fa_load_sinks(factx->vtcm_sinks, head_base, G) : Q6_V_vzero(); + + size_t prev_r_tile = SIZE_MAX; + HVX_Vector v_sc = Q6_V_vzero(); + + for (size_t r = start; r < end; ++r) { + const size_t r_tile = r >> 5; + if (r_tile != prev_r_tile) { + HVX_Vector v_l = factx->vtcm_l_vec[r_tile]; + if (has_sinks) { + const size_t g0 = fastmodulo(r_tile * 32, G, &factx->div_G); const size_t rem_g = G - g0; + HVX_Vector v_sink; if (G <= 32) { const HVX_Vector v_lo = Q6_V_vror_VR(v_head_sinks, g0 * sizeof(float)); const HVX_Vector v_hi = Q6_V_vror_VR(v_head_sinks, 128 - rem_g * sizeof(float)); @@ -1685,67 +2986,74 @@ static __attribute__((noinline)) void fa_build_d_diag_inv_l(struct hmx_fa_contex v_sink = Q6_V_vmux_QVV(q_keep, v_sink, v_shifted); } } else if (rem_g >= 32) { - v_sink = hvx_fa_load_sinks(sinks_data, head_base + g0, 32); + v_sink = hvx_fa_load_sinks(factx->vtcm_sinks, head_base + g0, 32); } else { - const HVX_Vector v_lo = hvx_fa_load_sinks(sinks_data, head_base + g0, rem_g); - const HVX_Vector v_hi = hvx_fa_load_sinks(sinks_data, head_base, 32 - rem_g); + const HVX_Vector v_lo = hvx_fa_load_sinks(factx->vtcm_sinks, head_base + g0, rem_g); + const HVX_Vector v_hi = hvx_fa_load_sinks(factx->vtcm_sinks, head_base, 32 - rem_g); v_sink = Q6_V_vmux_QVV(Q6_Q_vsetq_R(rem_g * sizeof(float)), v_lo, Q6_V_vror_VR(v_hi, 128 - rem_g * sizeof(float))); } - g_prev = g0; - } - HVX_Vector v_d = HVX_OP_SUB_F32(v_sink, HVX_OP_MUL_F32(factx->vtcm_m_vec[i], v_ln2)); - if (r0 + 32 > n_rows_g) { - const HVX_VectorPred q_valid = Q6_Q_vsetq_R((n_rows_g - r0) * sizeof(float)); - v_d = Q6_V_vmux_QVV(q_valid, v_d, Q6_V_vzero()); + HVX_Vector v_me = HVX_OP_MUL_F32(factx->vtcm_m_vec[r_tile], v_ln2); + HVX_VectorPred q_gt = Q6_Q_vcmp_gt_VsfVsf(v_sink, v_me); + HVX_Vector v_diff = Q6_V_vmux_QVV(q_gt, HVX_OP_SUB_F32(v_me, v_sink), HVX_OP_SUB_F32(v_sink, v_me)); + HVX_Vector v_exp = hvx_vec_exp_f32(v_diff); + HVX_Vector v_l_new = Q6_V_vmux_QVV(q_gt, HVX_OP_ADD_F32(HVX_OP_MUL_F32(v_l, v_exp), v_one), HVX_OP_ADD_F32(v_l, v_exp)); + HVX_Vector v_num = Q6_V_vmux_QVV(q_gt, v_exp, v_one); + HVX_VectorPred q_nz = Q6_Q_vcmp_gt_VsfVsf(v_l_new, Q6_V_vzero()); + v_sc = Q6_V_vmux_QVV(q_nz, HVX_OP_MUL_F32(v_num, hvx_vec_inverse_f32(v_l_new)), Q6_V_vzero()); + } else { + HVX_VectorPred q_nz = Q6_Q_vcmp_gt_VsfVsf(v_l, Q6_V_vzero()); + v_sc = Q6_V_vmux_QVV(q_nz, hvx_vec_inverse_f32(v_l), Q6_V_vzero()); } - factx->vtcm_l_vec[i] = HVX_OP_ADD_F32(factx->vtcm_l_vec[i], hvx_vec_exp_f32(v_d)); + prev_r_tile = r_tile; } - } - const HVX_Vector v_offsets = *(const HVX_Vector *) d_tile_scatter_offsets; - const HVX_VectorPred q_32_mask = Q6_Q_vsetq_R(32 * sizeof(__fp16)); - const HVX_Vector one = hvx_vec_splat_f32(1.0f); + const uint32_t sc_bits = (uint32_t) Q6_R_vextract_VR(v_sc, (int) ((r & 31u) * 4u)); + float * o_row = o_f32 + r * DV; - HVX_Vector v_content = Q6_V_vzero(); - for (size_t i = 0; i < n_row_tiles; ++i) { - if ((i % 2) == 0) { - HVX_Vector inv_lo = HVX_OP_MUL_F32(one, hvx_vec_inverse_f32(factx->vtcm_l_vec[i])); - HVX_Vector inv_hi = (i + 1 < n_row_tiles) ? HVX_OP_MUL_F32(one, hvx_vec_inverse_f32(factx->vtcm_l_vec[i + 1])) : Q6_V_vzero(); - v_content = hvx_vec_f32_to_f16(inv_lo, inv_hi); + // Normalize in-place in VTCM; caller writes out via bypass DMA. + if (is_f32) { + for (size_t c = 0; c < DV; c += 32) { + *(HVX_Vector *) (o_row + c) = Q6_Vsf_equals_Vqf32(hvx_qf32_mul_sf_scalar(*(const HVX_Vector *) (o_row + c), sc_bits)); + } } else { - v_content = Q6_V_vror_VR(v_content, 64); + __fp16 * out = (__fp16 *) o_row; + size_t c = 0; + for (; c + 64 <= DV; c += 64) { + HVX_Vector v0 = Q6_Vsf_equals_Vqf32(hvx_qf32_mul_sf_scalar(*(const HVX_Vector *) (o_row + c + 0), sc_bits)); + HVX_Vector v1 = Q6_Vsf_equals_Vqf32(hvx_qf32_mul_sf_scalar(*(const HVX_Vector *) (o_row + c + 32), sc_bits)); + *(HVX_Vector *) (out + c) = hvx_vec_f32_to_f16(v0, v1); + } + if (c < DV) { + HVX_Vector v0 = Q6_Vsf_equals_Vqf32(hvx_qf32_mul_sf_scalar(*(const HVX_Vector *) (o_row + c), sc_bits)); + hvx_vec_store_a(out + c, 32 * sizeof(__fp16), hvx_vec_f32_to_f16(v0, Q6_V_vzero())); + } } - - __fp16 * out_base = factx->vtcm_d_inv_l + i * HMX_FP16_TILE_N_ELMS; - Q6_vscatter_QRMVhV(q_32_mask, (size_t) out_base, HMX_FP16_TILE_SIZE - 1, v_offsets, v_content); } + + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) (args->q_start * G + start)); } -static void fa_phase_softmax_and_build_d(struct hmx_fa_context * factx, - fa_softmax_args_t * sargs, - size_t n_row_tiles, - size_t n_row_tiles_g_br) { +static void fa_phase_w8a8_o_store(struct hmx_fa_context * factx, + dma_queue * dma_q, + const struct htp_tensor * dst, + uint32_t q_start, + uint32_t kv_head, + uint32_t ib3, + size_t n_rows_g) { work_queue_t wp = factx->octx->ctx->hvx_queue; - const size_t n_row_vec_cnt = hmx_ceil_div(sargs->n_rows_g, 64); - - work_queue_func_t softmax_fn = fa_softmax_thread; - if (sargs->mask == NULL && !factx->has_softcap && !sargs->has_alibi) { - softmax_fn = fa_softmax_thread_nomask; - } else if (sargs->mask != NULL && factx->mask_broadcast && !factx->has_softcap && !sargs->has_alibi) { - if (sargs->G == 1) { - softmax_fn = fa_softmax_thread_mask_broadcast_g1; - } else { - softmax_fn = fa_softmax_thread_mask_broadcast_gn; - } - } - - uint32_t n_use = 1; - if (factx->n_hvx > 1 && n_row_vec_cnt >= 2) { - n_use = (uint32_t) hex_smin((size_t) factx->n_hvx, n_row_vec_cnt); - sargs->thread_div = init_fastdiv_values(n_use); + uint32_t n = 1; + if (factx->n_hvx > 1 && n_rows_g >= (size_t) (factx->n_hvx * 2)) { + n = factx->n_hvx; } - work_queue_run(wp, softmax_fn, sargs, n_use); + const size_t rows_per_t = hmx_ceil_div(n_rows_g, n); + fa_o_store_args_t args = { factx, (uint8_t *) factx->vtcm_o_f32, NULL, q_start, kv_head, 0, n_rows_g, rows_per_t }; + work_queue_run(wp, fa_w8a8_o_store_thread, &args, n); + + const size_t vtcm_row_stride = factx->DV * sizeof(float); + const size_t row_bytes = factx->DV * (factx->is_dst_fp32 ? sizeof(float) : sizeof(__fp16)); + fa_push_o_dma(dma_q, dst, (const uint8_t *) factx->vtcm_o_f32, vtcm_row_stride, row_bytes, + q_start, kv_head, ib3, factx->G, &factx->div_G, 0, n_rows_g); } // ============================================================================ @@ -1919,6 +3227,45 @@ static __attribute__((noinline)) void fa_compute_slopes( hvx_copy_f16_aa((uint8_t *)slopes, (const uint8_t *)temp_slopes, n_rows_g); } +static inline void fa_push_q_dma(dma_queue * dma_q, + const struct htp_tensor * q, + void * vtcm_q_dma, + uint32_t q_start, + uint32_t kv_head, + uint32_t ib3, + uint32_t G, + uint32_t n_rows_q, + size_t q_elem_row_bytes, + bool q_transposed) { + const dma_addr_t q_ptr = q->data + q_start * q->nb[1] + (kv_head * G) * q->nb[2] + ib3 * q->nb[3]; + const size_t q_inner_nb = q_transposed ? q->nb[1] : q->nb[2]; + const size_t q_outer_nb = q_transposed ? q->nb[2] : q->nb[1]; + const size_t n_inner = q_transposed ? n_rows_q : G; + const size_t n_outer = q_transposed ? G : n_rows_q; + + if (__builtin_expect(q_inner_nb == q_elem_row_bytes, true)) { + const size_t row_bytes = n_inner * q_elem_row_bytes; + dma_queue_push(dma_q, dma_make_data(vtcm_q_dma, q_ptr), row_bytes, hex_smax(q_outer_nb, row_bytes), row_bytes, n_outer); + return; + } + + // Non-contiguous inner dim: one 2D DMA per outer slice, keeping dma_q depth at 2 (prev O + Q). + uint8_t * dst_ptr = (uint8_t *) vtcm_q_dma; + const size_t dst_outer_stride = n_inner * q_elem_row_bytes; + const size_t src_inner_stride = hex_smax(q_inner_nb, q_elem_row_bytes); + for (size_t o = 0; o < n_outer; ++o) { + if (!dma_queue_push(dma_q, dma_make_data(dst_ptr + o * dst_outer_stride, q_ptr + o * q_outer_nb), + q_elem_row_bytes, src_inner_stride, q_elem_row_bytes, n_inner)) { + dma_queue_pop(dma_q); + dma_queue_push(dma_q, dma_make_data(dst_ptr + o * dst_outer_stride, q_ptr + o * q_outer_nb), + q_elem_row_bytes, src_inner_stride, q_elem_row_bytes, n_inner); + } + } + while (dma_queue_depth(dma_q) > 2) { + dma_queue_pop(dma_q); + } +} + static void fa_push_mask_dma_gqa( dma_queue * dma_q, const struct htp_tensor * mask, @@ -1993,7 +3340,6 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { const uint32_t neq2 = q->ne[2]; // n_heads const uint32_t neq3 = q->ne[3]; // n_seqs - const uint32_t nek0 = k->ne[0]; // head_dim const uint32_t nek1 = k->ne[1]; // kv_len const uint32_t nev0 = v->ne[0]; // head_dim (DV) @@ -2037,6 +3383,7 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { factx.is_q_fp32 = (q->type == HTP_TYPE_F32); factx.is_dst_fp32 = (dst->type == HTP_TYPE_F32); factx.pipeline = (kparams->u.hmx.pipeline != 0); + factx.is_w8a8 = (kparams->kernel_type == HTP_FA_KERNEL_HMX_W8A8); factx.mask_broadcast = (kparams->u.hmx.mask_broadcast != 0); if (mask) { factx.src3_div2 = kparams->src3_div2; @@ -2045,6 +3392,7 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { factx.has_softcap = (kparams->logit_softcap != 0.0f); factx.scale = (__fp16) kparams->scale; + factx.scale_f32 = kparams->scale; factx.max_bias = kparams->max_bias; factx.logit_softcap = 0; if (factx.has_softcap) { @@ -2073,10 +3421,8 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { if (octx->ctx->mdev.count > 1) { const uint32_t mdev_count = octx->ctx->mdev.count; const uint32_t mdev_idx = octx->ctx->mdev.idx; - const uint32_t dst_e_size = (dst->type == HTP_TYPE_F32) ? sizeof(float) : sizeof(__fp16); - const bool can_split = htp_tensor_can_row_partition(dst, dst_e_size); - if ((kparams->flags & HTP_FA_FLAG_TEAM_SPLIT) && can_split) { + if (kparams->flags & HTP_FA_FLAG_TEAM_SPLIT) { // KV heads split across teams, Q-blocks split within a team uint32_t n_teams, team_size; htp_fa_mdev_teams(n_kv_heads, mdev_count, kparams->head_split != 0, &n_teams, &team_size); @@ -2098,12 +3444,12 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { q_start_min = b0 * Br; q_start_max = MIN((b0 + nblk) * Br, neq1); - } else if (kparams->head_split && can_split && n_kv_heads >= mdev_count && n_kv_heads % mdev_count == 0) { + } else if (kparams->head_split && n_kv_heads >= mdev_count && n_kv_heads % mdev_count == 0) { const uint32_t kv_per_core = n_kv_heads / mdev_count; kv_head_min = mdev_idx * kv_per_core; kv_head_max = kv_head_min + kv_per_core; } else { - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(n_q_blocks, can_split ? 1 : 0, mdev_idx, mdev_count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(n_q_blocks, 1, mdev_idx, mdev_count, &octx->ctx->mdev.count_div); const uint32_t block_start = range.start; const uint32_t block_end = range.start + range.count; @@ -2121,26 +3467,41 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { // throughout the KV loop below. The DMA copies only the real DK/DV columns; the // staging rows are padded to hold DK_pad/DV_pad columns (tail zero-filled below) // so the HMX interleave/tile logic can operate on 64-aligned head dims. - const size_t size_k_row = htp_tensor_get_row_size(k->type, DK); - const size_t size_v_row = htp_tensor_get_row_size(v->type, DV); - const size_t size_k_row_padded = hex_round_up(DK_pad * sizeof(__fp16), 128); - const size_t size_v_row_padded = hex_round_up(DV_pad * sizeof(__fp16), 128); - // Build the VTCM layout once (shared with the host estimator) and place every // scratch buffer at its computed offset. Padded head dims size the HMX tiles. + const struct hmx_fa_layout_params lp = { + .kernel_type = kparams->kernel_type, + .q_type = q->type, + .gqa_factor = G, + .DK = DK_pad, + .DV = DV_pad, + .Br = Br, + .Bc = Bc, + .n_hvx = n_hvx, + .n_heads = factx.n_heads, + .pipeline = pipeline, + .has_mask = mask != NULL, + .mask_broadcast = factx.mask_broadcast, + .has_sinks = factx.sinks != NULL, + }; struct hmx_fa_vtcm_layout L; - hmx_fa_vtcm_layout_build(&L, G, DK_pad, DV_pad, Br, Bc, n_hvx, pipeline, factx.is_q_fp32, factx.sinks != NULL, factx.n_heads); + hmx_fa_vtcm_layout_build(&L, &lp); if (L.total_bytes > ctx->vtcm_size) { return HTP_STATUS_VTCM_TOO_SMALL; } + const size_t size_k_row = htp_tensor_get_row_size(k->type, DK); + const size_t size_v_row = htp_tensor_get_row_size(v->type, DV); + const size_t size_k_row_padded = factx.is_w8a8 ? L.k_raw_row_padded : hex_round_up(DK_pad * sizeof(__fp16), 128); + const size_t size_v_row_padded = factx.is_w8a8 ? L.v_raw_row_padded : hex_round_up(DV_pad * sizeof(__fp16), 128); + uint8_t * const base = ctx->vtcm_base; factx.vtcm_q_dma = VTCM_LAYOUT_PTR(__fp16, base, L.off_q_dma); factx.vtcm_q_tiles = VTCM_LAYOUT_PTR(__fp16, base, L.off_q_tiles); - factx.vtcm_o_tiles[0] = VTCM_LAYOUT_PTR(__fp16, base, L.off_o_tiles[0]); - factx.vtcm_o_tiles[1] = VTCM_LAYOUT_PTR(__fp16, base, L.off_o_tiles[1]); + factx.vtcm_o_tiles[0] = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_o_tiles[0], !factx.is_w8a8); + factx.vtcm_o_tiles[1] = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_o_tiles[1], !factx.is_w8a8); factx.vtcm_k_fp16[0] = VTCM_LAYOUT_PTR(__fp16, base, L.off_k_fp16[0]); factx.vtcm_k_fp16[1] = VTCM_LAYOUT_PTR(__fp16, base, L.off_k_fp16[1]); factx.vtcm_v_fp16[0] = VTCM_LAYOUT_PTR(__fp16, base, L.off_v_fp16[0]); @@ -2153,9 +3514,9 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { factx.vtcm_s_tiles[1] = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_s_tiles[1], pipeline); factx.vtcm_p_tiles[0] = VTCM_LAYOUT_PTR(__fp16, base, L.off_p_tiles[0]); factx.vtcm_p_tiles[1] = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_p_tiles[1], pipeline); - factx.vtcm_d_tiles[0] = VTCM_LAYOUT_PTR(__fp16, base, L.off_d_tiles[0]); - factx.vtcm_d_tiles[1] = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_d_tiles[1], pipeline); - factx.vtcm_d_inv_l = VTCM_LAYOUT_PTR(__fp16, base, L.off_d_inv_l); + factx.vtcm_d_tiles[0] = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_d_tiles[0], !factx.is_w8a8); + factx.vtcm_d_tiles[1] = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_d_tiles[1], !factx.is_w8a8 && pipeline); + factx.vtcm_d_inv_l = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_d_inv_l, !factx.is_w8a8); factx.vtcm_m_vec = VTCM_LAYOUT_PTR(HVX_Vector, base, L.off_m_vec); factx.vtcm_l_vec = VTCM_LAYOUT_PTR(HVX_Vector, base, L.off_l_vec); factx.vtcm_s_rowmax = VTCM_LAYOUT_PTR(HVX_Vector, base, L.off_s_rowmax); @@ -2164,15 +3525,33 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { factx.row_buf_stride = L.row_buf_stride; factx.vtcm_hmx_scales_id = VTCM_LAYOUT_PTR(uint8_t, base, L.off_hmx_scales_id); factx.vtcm_hmx_scales_qk = VTCM_LAYOUT_PTR(uint8_t, base, L.off_hmx_scales_qk); - factx.vtcm_mask_buf = VTCM_LAYOUT_PTR(__fp16, base, L.off_mask_buf); + factx.vtcm_mask_buf = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_mask_buf, mask != NULL); factx.mask_buf_row_stride = L.mask_buf_row_stride; factx.q_tile_bytes = L.q_tile_bytes; factx.k_tile_bytes = L.k_tile_bytes; factx.o_tile_bytes = L.o_tile_bytes; factx.col_vec_bytes = L.col_vec_bytes; factx.d_tile_bytes = L.d_tile_bytes; + factx.o_f32_bytes = L.o_f32_bytes; factx.vtcm_slopes = VTCM_LAYOUT_PTR(__fp16, base, L.off_slopes); factx.vtcm_sinks = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_sinks, factx.sinks != NULL); + factx.vtcm_q_scales = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_q_scales, factx.is_w8a8); + factx.vtcm_k_scales[0] = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_k_scales[0], factx.is_w8a8); + factx.vtcm_k_scales[1] = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_k_scales[1], factx.is_w8a8 && pipeline); + factx.vtcm_k_bias[0] = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, base, L.off_k_bias[0], factx.is_w8a8); + factx.vtcm_k_bias[1] = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, base, L.off_k_bias[1], factx.is_w8a8 && pipeline); + factx.vtcm_o_f32 = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_o_f32, factx.is_w8a8); + factx.vtcm_do_tiles = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, base, L.off_do_tiles, factx.is_w8a8); + factx.vtcm_v_scales[0] = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_v_scales[0], factx.is_w8a8); + factx.vtcm_v_scales[1] = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_v_scales[1], factx.is_w8a8 && pipeline); + factx.vtcm_v_bias[0] = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, base, L.off_v_bias[0], factx.is_w8a8); + factx.vtcm_v_bias[1] = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, base, L.off_v_bias[1], factx.is_w8a8 && pipeline); + factx.vtcm_p_scales[0] = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_p_scales[0], factx.is_w8a8); + factx.vtcm_p_scales[1] = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_p_scales[1], factx.is_w8a8 && pipeline); + factx.vtcm_exp_mdiff[0] = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_exp_mdiff[0], factx.is_w8a8); + factx.vtcm_exp_mdiff[1] = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_exp_mdiff[1], factx.is_w8a8 && pipeline); + factx.k_raw_row_padded = L.k_raw_row_padded; + factx.v_raw_row_padded = L.v_raw_row_padded; const size_t m_line_bytes = L.m_line_bytes; // used by the mask DMAs in the KV loop @@ -2183,7 +3562,9 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { factx.ddr_slopes = ddr->slopes; factx.m_cache = &octx->dma_cache_fa[0]; - dma_cache_fa_init(factx.m_cache, (uint8_t *) factx.vtcm_mask_buf, L.m_buf_slot_bytes, HMX_FA_DMA_CACHE_SIZE); + if (mask && factx.mask_broadcast) { + dma_cache_fa_init(factx.m_cache, (uint8_t *) factx.vtcm_mask_buf, L.m_buf_slot_bytes, HMX_FA_DMA_CACHE_SIZE); + } // Head-dim padding: the K/V DMA staging buffers and the flat-Q buffer are laid out // with padded row strides (size_{k,v,q}_row_padded, covering D_pad columns) but the @@ -2197,10 +3578,8 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { hvx_splat_u8_a((char *) factx.vtcm_v_fp16[0], 0, v_buf_bytes); hvx_splat_u8_a((char *) factx.vtcm_v_fp16[1], 0, v_buf_bytes); // Flat-Q DMA scratch - if (factx.vtcm_q_dma) { - const size_t q_dma_bytes = hex_align_up(factx.g_br * DK * (factx.is_q_fp32 ? sizeof(float) : sizeof(__fp16)), 128); - hvx_splat_u8_a((char *) factx.vtcm_q_dma, 0, q_dma_bytes); - } + const size_t q_dma_bytes = hex_align_up(factx.g_br * DK * (factx.is_q_fp32 ? sizeof(float) : sizeof(__fp16)), 128); + hvx_splat_u8_a((char *) factx.vtcm_q_dma, 0, q_dma_bytes); } // ======== Initialize HMX output scales ======== @@ -2221,15 +3600,14 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { const size_t n_row_tiles_g_br = g_br / HMX_FP16_TILE_N_ROWS; const size_t n_tiles_per_bc = Bc / HMX_FP16_TILE_N_COLS; - const size_t qo_element_size = factx.is_q_fp32 ? sizeof(float) : sizeof(__fp16); - - const bool q_transposed = q->nb[1] < q->nb[2]; - const size_t q_src_stride = q_transposed ? q->nb[2] : q->nb[1]; - const size_t q_row_bytes_untransposed = factx.G * factx.DK * qo_element_size; - const size_t q_row_bytes_trans_factor = factx.DK * qo_element_size; + const size_t qo_element_size = factx.is_q_fp32 ? sizeof(float) : sizeof(__fp16); + const bool q_transposed = q->nb[1] < q->nb[2]; + const size_t q_elem_row_bytes = factx.DK * qo_element_size; // ======== Reusable job descriptors for pipeline ======== hmx_fa_qk_job_t qk_job; + hmx_fa_w8a8_qk_job_t w8a8_qk_job; + hmx_fa_w8a8_pv_job_t w8a8_pv_job; hmx_fa_o_update_job_t ou_job; hmx_fa_o_norm_job_t on_job; @@ -2237,10 +3615,11 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { for (uint32_t ib3 = 0; ib3 < neq3; ++ib3) { const uint32_t im3 = mask ? fastmodulo(ib3, mask->ne[3], &factx.src3_div3) : 0; for (uint32_t q_start = q_start_min; q_start < q_start_max; q_start += Br) { - const uint32_t n_rows_q = hex_smin(Br, neq1 - q_start); - const size_t n_rows_g = n_rows_q * G; - const size_t g_br_actual = hex_align_up(n_rows_g, HMX_FP16_TILE_N_ROWS); - const size_t n_row_tiles = g_br_actual / HMX_FP16_TILE_N_ROWS; + const uint32_t n_rows_q = hex_smin(Br, neq1 - q_start); + const size_t n_rows_g = n_rows_q * G; + const size_t g_br_actual = hex_align_up(n_rows_g, HMX_FP16_TILE_N_ROWS); + const size_t n_row_tiles = g_br_actual / HMX_FP16_TILE_N_ROWS; + const uint32_t n_row_tiles_64 = (uint32_t) hmx_ceil_div(n_rows_g, HMX_W8A8_ACT_TILE_N_ROWS); uint16_t * active_blocks = ddr->active_blocks; uint32_t n_active_blocks = factx.n_kv_blocks; @@ -2259,6 +3638,9 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { const uint32_t b0_start = b0 * Bc; const uint32_t b0_rows = hex_smin(Bc, nek1 - b0_start); + // Dummy O writeback so every kv_head iteration pops prev O then curr Q unconditionally. + dma_queue_push(dma_q, dma_make_data(dst->data, factx.vtcm_o_tiles[0]), 0, 0, 0, 0); + for (uint32_t kv_head = kv_head_min; kv_head < kv_head_max; ++kv_head) { const uint32_t ik2 = kv_head; const uint32_t ik3 = fastdiv(ib3, &kparams->broadcast_rk3); @@ -2268,11 +3650,7 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { // 1. Push Q and KV DMAs for the first kv_head of this q_start block. // Subsequent kv_head iterations are enqueued early at the end of the previous iteration. if (kv_head == kv_head_min) { - const dma_addr_t q_ptr = q->data + q_start * q->nb[1] + - (kv_head * factx.G) * q->nb[2] + ib3 * q->nb[3]; - const size_t q_row_bytes = q_transposed ? n_rows_q * q_row_bytes_trans_factor : q_row_bytes_untransposed; - const size_t n_rows = q_transposed ? factx.G : n_rows_q; - dma_queue_push(dma_q, dma_make_data(factx.vtcm_q_dma, q_ptr), q_row_bytes, hex_smax(q_src_stride, q_row_bytes), q_row_bytes, n_rows); + fa_push_q_dma(dma_q, q, factx.vtcm_q_dma, q_start, kv_head, ib3, factx.G, n_rows_q, q_elem_row_bytes, q_transposed); if (n_active_blocks > 0) { const dma_addr_t k_src = k->data + b0_start * k->nb[1] + ik2 * k->nb[2] + ik3 * k->nb[3]; @@ -2292,11 +3670,12 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { } } - // 2. Pop Q DMA (blocks until Q is loaded) + // 2. Pop previous kv_head's O writeback and current Q DMA. + dma_queue_pop(dma_q); dma_queue_pop(dma_q); // ---- Load Q block & Initialize per-block state ---- - fa_phase_q_load(&factx, q, q_start, kv_head, ib3, n_rows_g); + fa_phase_q_load(&factx, q, q_start, n_rows_g); __fp16 * o_tile_prev = factx.vtcm_o_tiles[0]; __fp16 * o_tile_curr = factx.vtcm_o_tiles[1]; @@ -2316,6 +3695,8 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { if (factx.pipeline) { // Double-buffered job structs because HMX queue runs asynchronously hmx_fa_qk_job_t qk_job[2]; + hmx_fa_w8a8_qk_job_t w8a8_qk_job[2]; + hmx_fa_w8a8_pv_job_t w8a8_pv_job[2]; hmx_fa_o_update_job_t ou_job[2]; // Prefetch second active block early if there are multiple active blocks @@ -2328,15 +3709,26 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { void * curr_k0 = (void *) dma_queue_pop(dma_q).dst; fa_phase_k_interleave(&factx, b0_rows, k_src_stride, curr_k0, b0_start, 0); - qk_job[0].q_tiles = factx.vtcm_q_tiles; - qk_job[0].k_tiles = factx.vtcm_k_tiles[0]; - qk_job[0].s_tiles = factx.vtcm_s_tiles[0]; - qk_job[0].n_row_tiles = n_row_tiles; - qk_job[0].n_col_tiles = hmx_ceil_div(b0_rows, HMX_FP16_TILE_N_COLS); - qk_job[0].n_dot_tiles = DK_pad / 32; - qk_job[0].n_tiles_per_bc = n_tiles_per_bc; - qk_job[0].hmx_scales = factx.vtcm_hmx_scales_qk; - hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_qk_dot_worker, &qk_job[0])); + if (factx.is_w8a8) { + w8a8_qk_job[0].q_tiles = (const uint8_t *) factx.vtcm_q_tiles; + w8a8_qk_job[0].k_tiles = (const uint8_t *) factx.vtcm_k_tiles[0]; + w8a8_qk_job[0].k_bias = factx.vtcm_k_bias[0]; + w8a8_qk_job[0].s_tiles = (uint8_t *) factx.vtcm_s_tiles[0]; + w8a8_qk_job[0].n_row_tiles_64 = n_row_tiles_64; + w8a8_qk_job[0].n_col_tiles = (uint32_t) hmx_ceil_div(b0_rows, HMX_W8A8_TILE_N_COLS); + w8a8_qk_job[0].n_dot_tiles = DK / 32; + hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_w8a8_qk_dot_worker, &w8a8_qk_job[0])); + } else { + qk_job[0].q_tiles = factx.vtcm_q_tiles; + qk_job[0].k_tiles = factx.vtcm_k_tiles[0]; + qk_job[0].s_tiles = factx.vtcm_s_tiles[0]; + qk_job[0].n_row_tiles = n_row_tiles; + qk_job[0].n_col_tiles = hmx_ceil_div(b0_rows, HMX_FP16_TILE_N_COLS); + qk_job[0].n_dot_tiles = DK_pad / 32; + qk_job[0].n_tiles_per_bc = n_tiles_per_bc; + qk_job[0].hmx_scales = factx.vtcm_hmx_scales_qk; + hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_qk_dot_worker, &qk_job[0])); + } for (uint32_t step = 0; step < n_active_blocks; ++step) { const uint32_t kv_blk = active_blocks[step]; @@ -2346,7 +3738,7 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { // ---- 1. Pop and run V-prep for current block ---- void * curr_v = (void *) dma_queue_pop(dma_q).dst; - fa_phase_v_interleave(&factx, kv_rows, v_src_stride, curr_v, factx.vtcm_v_tiles[buf_idx], n_tiles_per_bc, kv_start); + fa_phase_v_interleave(&factx, kv_rows, v_src_stride, curr_v, factx.vtcm_v_tiles[buf_idx], n_tiles_per_bc, kv_start, buf_idx); // ---- 2. Pop and run mask-prep for current block ---- __fp16 * current_mask_vtcm = NULL; @@ -2359,28 +3751,36 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { } } - // ---- 3. Start HMX O update for step - 1 (reads P[1 - buf_idx], V[1 - buf_idx], D) ---- - // O update relies on the previous block's P and V tiles. - // O update MUST be pushed before the next block's QK-dot: hmx_queue_pop() retires the + // ---- 3. Start HMX O update / PV for step - 1 (reads P[1 - buf_idx], V[1 - buf_idx]) ---- + // MUST be pushed before the next block's QK-dot: hmx_queue_pop() retires the // oldest descriptor, so push order alone decides which pop waits for which job. - // If OU went in after QK(i+1), the pop below would retire QK(i+1) and leave - // OU(i-1) in flight into the next iteration, where V-prep overwrites V[prev_buf]. if (step > 0) { - const uint32_t prev_blk = active_blocks[step - 1]; - const size_t prev_buf = 1 - buf_idx; - ou_job[prev_buf].o_curr = o_tile_curr; - ou_job[prev_buf].o_prev = o_tile_prev; - ou_job[prev_buf].p_tiles = factx.vtcm_p_tiles[prev_buf]; - ou_job[prev_buf].v_tiles = factx.vtcm_v_tiles[prev_buf]; - ou_job[prev_buf].d_tiles = factx.vtcm_d_tiles[prev_buf]; - ou_job[prev_buf].hmx_scales = factx.vtcm_hmx_scales_id; - ou_job[prev_buf].n_row_tiles = n_row_tiles; - ou_job[prev_buf].n_col_tiles = - hmx_ceil_div(hex_smin(Bc, nek1 - prev_blk * Bc), HMX_FP16_TILE_N_COLS); - ou_job[prev_buf].n_row_tiles_g_br = n_row_tiles_g_br; - ou_job[prev_buf].n_tiles_per_bc = n_tiles_per_bc; - ou_job[prev_buf].DV = DV_pad; - hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_o_update_worker, &ou_job[prev_buf])); + const uint32_t prev_blk = active_blocks[step - 1]; + const size_t prev_buf = 1 - buf_idx; + const size_t prev_ct = hmx_ceil_div(hex_smin(Bc, nek1 - prev_blk * Bc), HMX_FP16_TILE_N_COLS); + if (factx.is_w8a8) { + w8a8_pv_job[prev_buf].p_tiles = (const uint8_t *) factx.vtcm_p_tiles[prev_buf]; + w8a8_pv_job[prev_buf].v_tiles = (const uint8_t *) factx.vtcm_v_tiles[prev_buf]; + w8a8_pv_job[prev_buf].v_bias = factx.vtcm_v_bias[prev_buf]; + w8a8_pv_job[prev_buf].do_tiles = factx.vtcm_do_tiles; + w8a8_pv_job[prev_buf].n_row_tiles_64 = n_row_tiles_64; + w8a8_pv_job[prev_buf].n_v_tiles = DV / HMX_W8A8_TILE_N_COLS; + w8a8_pv_job[prev_buf].n_dot_tiles = (uint32_t) prev_ct; + hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_w8a8_pv_worker, &w8a8_pv_job[prev_buf])); + } else { + ou_job[prev_buf].o_curr = o_tile_curr; + ou_job[prev_buf].o_prev = o_tile_prev; + ou_job[prev_buf].p_tiles = factx.vtcm_p_tiles[prev_buf]; + ou_job[prev_buf].v_tiles = factx.vtcm_v_tiles[prev_buf]; + ou_job[prev_buf].d_tiles = factx.vtcm_d_tiles[prev_buf]; + ou_job[prev_buf].hmx_scales = factx.vtcm_hmx_scales_id; + ou_job[prev_buf].n_row_tiles = n_row_tiles; + ou_job[prev_buf].n_col_tiles = prev_ct; + ou_job[prev_buf].n_row_tiles_g_br = n_row_tiles_g_br; + ou_job[prev_buf].n_tiles_per_bc = n_tiles_per_bc; + ou_job[prev_buf].DV = DV_pad; + hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_o_update_worker, &ou_job[prev_buf])); + } } // ---- 4. Pop and run K-prep for next active block & push next QK-dot ---- @@ -2393,15 +3793,26 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { void * next_k = (void *) dma_queue_pop(dma_q).dst; fa_phase_k_interleave(&factx, next_rows, k_src_stride, next_k, next_start, next_buf); - qk_job[next_buf].q_tiles = factx.vtcm_q_tiles; - qk_job[next_buf].k_tiles = factx.vtcm_k_tiles[next_buf]; - qk_job[next_buf].s_tiles = factx.vtcm_s_tiles[next_buf]; - qk_job[next_buf].n_row_tiles = n_row_tiles; - qk_job[next_buf].n_col_tiles = hmx_ceil_div(next_rows, HMX_FP16_TILE_N_COLS); - qk_job[next_buf].n_dot_tiles = DK_pad / 32; - qk_job[next_buf].n_tiles_per_bc = n_tiles_per_bc; - qk_job[next_buf].hmx_scales = factx.vtcm_hmx_scales_qk; - hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_qk_dot_worker, &qk_job[next_buf])); + if (factx.is_w8a8) { + w8a8_qk_job[next_buf].q_tiles = (const uint8_t *) factx.vtcm_q_tiles; + w8a8_qk_job[next_buf].k_tiles = (const uint8_t *) factx.vtcm_k_tiles[next_buf]; + w8a8_qk_job[next_buf].k_bias = factx.vtcm_k_bias[next_buf]; + w8a8_qk_job[next_buf].s_tiles = (uint8_t *) factx.vtcm_s_tiles[next_buf]; + w8a8_qk_job[next_buf].n_row_tiles_64 = n_row_tiles_64; + w8a8_qk_job[next_buf].n_col_tiles = (uint32_t) hmx_ceil_div(next_rows, HMX_W8A8_TILE_N_COLS); + w8a8_qk_job[next_buf].n_dot_tiles = DK / 32; + hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_w8a8_qk_dot_worker, &w8a8_qk_job[next_buf])); + } else { + qk_job[next_buf].q_tiles = factx.vtcm_q_tiles; + qk_job[next_buf].k_tiles = factx.vtcm_k_tiles[next_buf]; + qk_job[next_buf].s_tiles = factx.vtcm_s_tiles[next_buf]; + qk_job[next_buf].n_row_tiles = n_row_tiles; + qk_job[next_buf].n_col_tiles = hmx_ceil_div(next_rows, HMX_FP16_TILE_N_COLS); + qk_job[next_buf].n_dot_tiles = DK_pad / 32; + qk_job[next_buf].n_tiles_per_bc = n_tiles_per_bc; + qk_job[next_buf].hmx_scales = factx.vtcm_hmx_scales_qk; + hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_qk_dot_worker, &qk_job[next_buf])); + } } // ---- 5. Wait for current block's QK-dot to finish ---- @@ -2433,10 +3844,14 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { // Run Softmax on HVX (blocking call) fa_phase_softmax_and_build_d(&factx, &sargs, n_row_tiles, n_row_tiles_g_br); - // Wait for HMX O update for step - 1 to finish + // Wait for HMX O update / PV for step - 1 to finish if (step > 0) { hmx_queue_pop(hmx_q); - hex_swap_ptr((void **) &o_tile_curr, (void **) &o_tile_prev); + if (factx.is_w8a8) { + fa_phase_w8a8_o_accum(&factx, 1 - buf_idx, n_rows_g, q_start, step == 1); + } else { + hex_swap_ptr((void **) &o_tile_curr, (void **) &o_tile_prev); + } } // Prefetch block step + 2 @@ -2450,28 +3865,42 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { // Epilogue if (n_active_blocks > 0) { - const uint32_t last_blk = active_blocks[n_active_blocks - 1]; - const size_t last_cols = hmx_ceil_div(hex_smin(Bc, nek1 - last_blk * Bc), HMX_FP16_TILE_N_COLS); - ou_job[0].o_curr = o_tile_curr; - ou_job[0].o_prev = o_tile_prev; - ou_job[0].p_tiles = factx.vtcm_p_tiles[1 - buf_idx]; - ou_job[0].v_tiles = factx.vtcm_v_tiles[1 - buf_idx]; - ou_job[0].d_tiles = factx.vtcm_d_tiles[1 - buf_idx]; - ou_job[0].hmx_scales = factx.vtcm_hmx_scales_id; - ou_job[0].n_row_tiles = n_row_tiles; - ou_job[0].n_col_tiles = last_cols; - ou_job[0].n_row_tiles_g_br = n_row_tiles_g_br; - ou_job[0].n_tiles_per_bc = n_tiles_per_bc; - ou_job[0].DV = DV_pad; - hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_o_update_worker, &ou_job[0])); - - // Overlapped: run HVX build diag inv L while HMX is busy executing the update - htp_trace_event_start(tr_hvx, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) q_start); - fa_build_d_diag_inv_l(&factx, n_row_tiles, n_row_tiles_g_br, kv_head, n_rows_g); - htp_trace_event_stop(tr_hvx, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) q_start); - hmx_queue_pop(hmx_q); + const uint32_t last_blk = active_blocks[n_active_blocks - 1]; + const size_t last_cols = hmx_ceil_div(hex_smin(Bc, nek1 - last_blk * Bc), HMX_FP16_TILE_N_COLS); + const size_t last_buf = 1 - buf_idx; + if (factx.is_w8a8) { + w8a8_pv_job[0].p_tiles = (const uint8_t *) factx.vtcm_p_tiles[last_buf]; + w8a8_pv_job[0].v_tiles = (const uint8_t *) factx.vtcm_v_tiles[last_buf]; + w8a8_pv_job[0].v_bias = factx.vtcm_v_bias[last_buf]; + w8a8_pv_job[0].do_tiles = factx.vtcm_do_tiles; + w8a8_pv_job[0].n_row_tiles_64 = n_row_tiles_64; + w8a8_pv_job[0].n_v_tiles = DV / HMX_W8A8_TILE_N_COLS; + w8a8_pv_job[0].n_dot_tiles = (uint32_t) last_cols; + hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_w8a8_pv_worker, &w8a8_pv_job[0])); + hmx_queue_pop(hmx_q); + fa_phase_w8a8_o_accum(&factx, last_buf, n_rows_g, q_start, n_active_blocks == 1); + } else { + ou_job[0].o_curr = o_tile_curr; + ou_job[0].o_prev = o_tile_prev; + ou_job[0].p_tiles = factx.vtcm_p_tiles[last_buf]; + ou_job[0].v_tiles = factx.vtcm_v_tiles[last_buf]; + ou_job[0].d_tiles = factx.vtcm_d_tiles[last_buf]; + ou_job[0].hmx_scales = factx.vtcm_hmx_scales_id; + ou_job[0].n_row_tiles = n_row_tiles; + ou_job[0].n_col_tiles = last_cols; + ou_job[0].n_row_tiles_g_br = n_row_tiles_g_br; + ou_job[0].n_tiles_per_bc = n_tiles_per_bc; + ou_job[0].DV = DV_pad; + hmx_queue_push(hmx_q, hmx_queue_make_desc(hmx_fa_o_update_worker, &ou_job[0])); + + // Overlapped: run HVX build diag inv L while HMX is busy executing the update + htp_trace_event_start(tr_hvx, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) q_start); + fa_build_d_diag_inv_l(&factx, n_row_tiles, n_row_tiles_g_br, kv_head, n_rows_g); + htp_trace_event_stop(tr_hvx, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) q_start); + hmx_queue_pop(hmx_q); - hex_swap_ptr((void **) &o_tile_curr, (void **) &o_tile_prev); + hex_swap_ptr((void **) &o_tile_curr, (void **) &o_tile_prev); + } } } else { @@ -2506,7 +3935,18 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { void * curr_k = (void *) dma_queue_pop(dma_q).dst; fa_phase_k_interleave(&factx, kv_rows, k_src_stride, curr_k, kv_start, 0); - { + if (factx.is_w8a8) { + w8a8_qk_job.q_tiles = (const uint8_t *) factx.vtcm_q_tiles; + w8a8_qk_job.k_tiles = (const uint8_t *) factx.vtcm_k_tiles[0]; + w8a8_qk_job.k_bias = factx.vtcm_k_bias[0]; + w8a8_qk_job.s_tiles = (uint8_t *) factx.vtcm_s_tiles[0]; + w8a8_qk_job.n_row_tiles_64 = n_row_tiles_64; + w8a8_qk_job.n_col_tiles = (uint32_t) n_col_tiles; + w8a8_qk_job.n_dot_tiles = DK / 32; + + hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_fa_w8a8_qk_dot_worker, &w8a8_qk_job)); + hmx_queue_pop(ctx->hmx_queue); + } else { qk_job.q_tiles = factx.vtcm_q_tiles; qk_job.k_tiles = factx.vtcm_k_tiles[0]; qk_job.s_tiles = factx.vtcm_s_tiles[0]; @@ -2522,7 +3962,7 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { // Wait for current V DMA and interleave void * curr_v = (void *) dma_queue_pop(dma_q).dst; - fa_phase_v_interleave(&factx, kv_rows, v_src_stride, curr_v, factx.vtcm_v_tiles[0], n_tiles_per_bc, kv_start); + fa_phase_v_interleave(&factx, kv_rows, v_src_stride, curr_v, factx.vtcm_v_tiles[0], n_tiles_per_bc, kv_start, 0); // ---- Phase 3: softmax + build_D ---- __fp16 * current_mask_vtcm = NULL; @@ -2557,7 +3997,19 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { sargs.slopes = factx.vtcm_slopes; fa_phase_softmax_and_build_d(&factx, &sargs, n_row_tiles, n_row_tiles_g_br); - { + if (factx.is_w8a8) { + w8a8_pv_job.p_tiles = (const uint8_t *) factx.vtcm_p_tiles[0]; + w8a8_pv_job.v_tiles = (const uint8_t *) factx.vtcm_v_tiles[0]; + w8a8_pv_job.v_bias = factx.vtcm_v_bias[0]; + w8a8_pv_job.do_tiles = factx.vtcm_do_tiles; + w8a8_pv_job.n_row_tiles_64 = n_row_tiles_64; + w8a8_pv_job.n_v_tiles = DV / HMX_W8A8_TILE_N_COLS; + w8a8_pv_job.n_dot_tiles = (uint32_t) n_col_tiles; + + hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_fa_w8a8_pv_worker, &w8a8_pv_job)); + hmx_queue_pop(ctx->hmx_queue); + fa_phase_w8a8_o_accum(&factx, 0, n_rows_g, q_start, step == 0); + } else { ou_job.o_curr = o_tile_curr; ou_job.o_prev = o_tile_prev; ou_job.p_tiles = factx.vtcm_p_tiles[0]; @@ -2586,15 +4038,29 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { } } - // Enqueue DMAs for the next kv_head early so they overlap with O-PROC + // ---- Final normalization & Store O block (via bypass DMA) ---- + if (factx.is_w8a8) { + fa_phase_w8a8_o_store(&factx, dma_q, dst, q_start, kv_head, ib3, n_rows_g); + } else { + on_job.o_curr = o_tile_curr; + on_job.o_prev = o_tile_prev; + on_job.d_tiles = factx.vtcm_d_inv_l; + on_job.hmx_scales = factx.vtcm_hmx_scales_id; + on_job.n_row_tiles = n_row_tiles; + on_job.n_row_tiles_g_br = n_row_tiles_g_br; + on_job.DV = DV_pad; + hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_fa_o_norm_worker, &on_job)); + hmx_queue_pop(ctx->hmx_queue); + + fa_phase_o_store(&factx, dma_q, dst, o_tile_curr, (uint8_t *) o_tile_prev, q_start, kv_head, ib3, n_rows_g); + } + + // Enqueue DMAs for the next kv_head behind O writeback on dma_q. const uint32_t next_kv_head = kv_head + 1; - const bool has_next = (next_kv_head < kv_head_max); + const bool has_next = (next_kv_head < kv_head_max); if (has_next) { - const dma_addr_t next_q_ptr = q->data + q_start * q->nb[1] + (next_kv_head * factx.G) * q->nb[2] + ib3 * q->nb[3]; - const size_t next_q_row_bytes = q_transposed ? n_rows_q * q_row_bytes_trans_factor : q_row_bytes_untransposed; - const size_t next_n_rows = q_transposed ? factx.G : n_rows_q; - dma_queue_push(dma_q, dma_make_data(factx.vtcm_q_dma, next_q_ptr), next_q_row_bytes, hex_smax(q_src_stride, next_q_row_bytes), next_q_row_bytes, next_n_rows); + fa_push_q_dma(dma_q, q, factx.vtcm_q_dma, q_start, next_kv_head, ib3, factx.G, n_rows_q, q_elem_row_bytes, q_transposed); if (n_active_blocks > 0) { const uint32_t next_ik2 = next_kv_head; @@ -2616,23 +4082,9 @@ int hmx_flash_attn_ext(struct htp_ops_context * octx) { } } } - - // ---- Final normalization ---- - { - on_job.o_curr = o_tile_curr; - on_job.o_prev = o_tile_prev; - on_job.d_tiles = factx.vtcm_d_inv_l; - on_job.hmx_scales = factx.vtcm_hmx_scales_id; - on_job.n_row_tiles = n_row_tiles; - on_job.n_row_tiles_g_br = n_row_tiles_g_br; - on_job.DV = DV_pad; - hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_fa_o_norm_worker, &on_job)); - hmx_queue_pop(ctx->hmx_queue); - } - - // ---- Store O block ---- - fa_phase_o_store(&factx, dst, o_tile_curr, q_start, kv_head, ib3, n_rows_g); } + + dma_queue_pop(dma_q); } } @@ -2644,7 +4096,6 @@ int op_flash_attn_ext(struct htp_ops_context * octx) { const struct htp_tensor * k = octx->src[1]; const struct htp_tensor * v = octx->src[2]; const struct htp_tensor * mask = octx->src[3]; - const struct htp_tensor * dst = octx->dst; // Check support if ((q->type != HTP_TYPE_F16 && q->type != HTP_TYPE_F32) || @@ -2653,10 +4104,6 @@ int op_flash_attn_ext(struct htp_ops_context * octx) { return HTP_STATUS_NO_SUPPORT; } - if (htp_tensor_is_extended(dst)) { - return HTP_STATUS_NO_SUPPORT; - } - const struct htp_fa_kernel_params * kparams = (const struct htp_fa_kernel_params *) octx->kernel_params; if (kparams->kernel_type == HTP_FA_KERNEL_UNSUPPORTED || kparams->n_kv_blocks > FA_MAX_KV_BLOCKS) { @@ -2667,7 +4114,7 @@ int op_flash_attn_ext(struct htp_ops_context * octx) { return HTP_STATUS_INVAL_PARAMS; } - if (kparams->kernel_type == HTP_FA_KERNEL_HMX) { + if (kparams->kernel_type == HTP_FA_KERNEL_HMX_F16 || kparams->kernel_type == HTP_FA_KERNEL_HMX_W8A8) { return hmx_flash_attn_ext(octx); } @@ -2729,28 +4176,31 @@ int op_flash_attn_ext(struct htp_ops_context * octx) { const uint32_t neq3 = q->ne[3]; const uint32_t total_qrows = neq1 * neq2 * neq3; - uint32_t qrow_start = 0; - uint32_t qrows = total_qrows; + uint32_t qrow_start = 0; + uint32_t qrows = total_qrows; + uint32_t kv_head_start = 0; + uint32_t n_kv_local = k->ne[2]; if (octx->ctx->mdev.count > 1) { const uint32_t mdev_count = octx->ctx->mdev.count; const uint32_t mdev_idx = octx->ctx->mdev.idx; const uint32_t n_kv_heads = k->ne[2]; - const uint32_t dst_e_size = (dst->type == HTP_TYPE_F32) ? sizeof(float) : sizeof(__fp16); - const bool can_split = htp_tensor_can_row_partition(dst, dst_e_size); // head range is contiguous in flat row space only when neq3 == 1 - if (kparams->head_split && can_split && neq3 == 1 && n_kv_heads >= mdev_count && n_kv_heads % mdev_count == 0) { + if (kparams->head_split && neq3 == 1 && n_kv_heads >= mdev_count && n_kv_heads % mdev_count == 0) { const uint32_t G = kparams->G; const uint32_t kv_per_core = n_kv_heads / mdev_count; const uint32_t heads_per_core = kv_per_core * G; const uint32_t head_start = mdev_idx * heads_per_core; - qrow_start = head_start * neq1; - qrows = heads_per_core * neq1; + qrow_start = head_start * neq1; + qrows = heads_per_core * neq1; + kv_head_start = mdev_idx * kv_per_core; + n_kv_local = kv_per_core; } else { - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_qrows, can_split ? 1 : 0, mdev_idx, mdev_count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_qrows, 1, mdev_idx, mdev_count, &octx->ctx->mdev.count_div); qrow_start = range.start; qrows = range.count; + n_kv_local = 0; } } @@ -2760,14 +4210,27 @@ int op_flash_attn_ext(struct htp_ops_context * octx) { const uint32_t n_hvx = octx->n_hvx; - factx.qrows = qrows; - factx.qrow_start = qrow_start; - factx.qrows_per_hvx = fastdiv(qrows + n_hvx - 1, &octx->n_hvx_div); + factx.qrows = qrows; + factx.qrow_start = qrow_start; + factx.qrows_per_hvx = fastdiv(qrows + n_hvx - 1, &octx->n_hvx_div); + factx.kv_head_start = kv_head_start; + factx.n_kv_local = n_kv_local; + factx.G = kparams->G; + factx.splits_per_kv = 1; const bool has_mask = (mask != NULL); const bool has_sinks = (octx->src[4] != NULL); + const struct hvx_fa_layout_params lp = { + .q_type = q->type, + .DK = k->ne[0], + .DV = v->ne[0], + .n_heads = n_head, + .n_hvx = n_hvx, + .has_mask = has_mask, + .has_sinks = has_sinks, + }; struct hvx_fa_vtcm_layout L; - hvx_fa_vtcm_layout_build(&L, k->ne[0], v->ne[0], factx.is_q_fp32, has_mask, has_sinks, n_head, n_hvx); + hvx_fa_vtcm_layout_build(&L, &lp); if (L.total_bytes > octx->ctx->vtcm_size) { return HTP_STATUS_VTCM_TOO_SMALL; @@ -2804,6 +4267,27 @@ int op_flash_attn_ext(struct htp_ops_context * octx) { dma_queue_pop(dma_q); } + const bool can_split_kv = + (neq1 == 1) && + (neq3 == 1) && + (k->ne[2] == v->ne[2]) && + (!has_mask || mask->ne[2] == 1) && + (n_kv_local > 0 && n_kv_local < n_hvx) && + (factx.G > 0 && factx.G <= FA_HVX_G_MAX) && + (factx.n_active_blocks >= 4); + + if (can_split_kv) { + const uint32_t max_splits = MIN(n_hvx / n_kv_local, factx.n_active_blocks / 2); + if (max_splits >= 2) { + factx.splits_per_kv = max_splits; + const uint32_t n_workers = n_kv_local * max_splits; + const uint32_t n_merge = MIN(n_hvx, n_kv_local * factx.G); + work_queue_run(octx->ctx->hvx_queue, flash_attn_ext_f16_split_kv_thread, &factx, n_workers); + work_queue_run(octx->ctx->hvx_queue, flash_attn_ext_f16_split_merge_thread, &factx, n_merge); + return HTP_STATUS_OK; + } + } + work_queue_run(octx->ctx->hvx_queue, flash_attn_ext_f16_thread, &factx, n_hvx); return HTP_STATUS_OK; diff --git a/ggml/src/ggml-hexagon/htp/flash-attn-ops.h b/ggml/src/ggml-hexagon/htp/flash-attn-ops.h index 70cf3e41aa23..32f15dde2daa 100644 --- a/ggml/src/ggml-hexagon/htp/flash-attn-ops.h +++ b/ggml/src/ggml-hexagon/htp/flash-attn-ops.h @@ -7,6 +7,7 @@ #include "hex-fastdiv.h" #include "hex-common.h" +#include "htp-tensor.h" #include "htp-vtcm.h" #ifdef __cplusplus @@ -14,11 +15,17 @@ extern "C" { #endif // Tile constants (mirrored from hmx-utils.h for use on host side if needed) -#define HTP_FA_HMX_TILE_SIZE 2048 -#define HMX_FP16_TILE_SIZE 2048 -#define HMX_FP16_TILE_N_ROWS 32 -#define HMX_FP16_TILE_N_COLS 32 -#define HMX_FP16_TILE_N_ELMS 1024 +#define HTP_FA_HMX_TILE_SIZE 2048 +#define HMX_FP16_TILE_SIZE 2048 +#define HMX_FP16_TILE_N_ROWS 32 +#define HMX_FP16_TILE_N_COLS 32 +#define HMX_FP16_TILE_N_ELMS 1024 + +#define HMX_W8A8_ACT_TILE_N_ROWS 64 +#define HMX_W8A8_TILE_N_COLS 32 +#define HMX_W8A8_ACT_TILE_SIZE 2048 +#define HMX_W8A8_WT_TILE_SIZE 1024 +#define HMX_W8A8_BIAS_BANK_SIZE 256 #define HVX_FA_DMA_CACHE_SIZE 128 #define HMX_FA_DMA_CACHE_SIZE 4 @@ -29,7 +36,8 @@ extern "C" { enum htp_fa_kernel_type { HTP_FA_KERNEL_UNSUPPORTED = 0, HTP_FA_KERNEL_HVX, - HTP_FA_KERNEL_HMX + HTP_FA_KERNEL_HMX_F16, + HTP_FA_KERNEL_HMX_W8A8, }; // Multicore: gcd(n_kv_heads, N) teams own the KV heads, team members share the Q-blocks @@ -129,68 +137,143 @@ struct hmx_fa_vtcm_layout { size_t off_mask_buf; size_t off_slopes; size_t off_sinks; + size_t off_q_scales; + size_t off_k_scales[2]; + size_t off_k_bias[2]; + size_t off_o_f32; + size_t off_do_tiles; + size_t off_v_scales[2]; + size_t off_v_bias[2]; + size_t off_p_scales[2]; + size_t off_exp_mdiff[2]; // Region byte sizes reused by the device at runtime (not just for allocation). size_t q_tile_bytes; size_t o_tile_bytes; size_t k_tile_bytes; - size_t s_tile_bytes; // S and P tiles (same size) + size_t s_tile_bytes; // S tiles (2x in W8A8 for hi+lo) + size_t p_tile_bytes; // P tiles size_t d_tile_bytes; // d_tiles[0..1] + d_inv_l, allocated back to back + size_t o_f32_bytes; // W8A8 FP32 O accumulator size_t m_line_bytes; // one mask row size_t m_buf_slot_bytes; // one dma_cache slot = align_up(Br * m_line_bytes, 4096) size_t col_vec_bytes; size_t sinks_bytes; + size_t k_raw_row_padded; + size_t v_raw_row_padded; // Derived strides. size_t row_buf_stride; // HVX vectors (128B) per row buffer size_t mask_buf_row_stride; // __fp16 elements per row in the mask buffer bool pipeline; + bool is_w8a8; size_t total_bytes; }; #define FA_MAX_KV_BLOCKS 1024 +struct hmx_fa_layout_params { + int kernel_type; + int q_type; + size_t gqa_factor; + size_t DK; + size_t DV; + size_t Br; + size_t Bc; + size_t n_hvx; + size_t n_heads; + bool pipeline; + bool has_mask; + bool mask_broadcast; + bool has_sinks; +}; + // Build the VTCM layout. static inline void hmx_fa_vtcm_layout_build(struct hmx_fa_vtcm_layout * L, - size_t gqa_factor, size_t DK, size_t DV, - size_t Br, size_t Bc, size_t n_hvx, - bool pipeline, bool is_q_fp32, - bool has_sinks, size_t n_heads) { - const size_t g_br = hex_align_up(gqa_factor * Br, HMX_FP16_TILE_N_ROWS); - const size_t q_tile_size = hex_align_up(g_br * DK * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE); - const size_t o_tile_size = hex_align_up(g_br * DV * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE); - const size_t k_tile_size = hex_align_up(Bc * DK * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE); - const size_t v_tile_size = hex_align_up(Bc * DV * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE); - const size_t s_tile_size = hex_align_up(g_br * Bc * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE); + const struct hmx_fa_layout_params * p) { + const bool is_w8a8 = (p->kernel_type == HTP_FA_KERNEL_HMX_W8A8); + const size_t gqa_factor = p->gqa_factor; + const size_t DK = p->DK; + const size_t DV = p->DV; + const size_t Br = p->Br; + const size_t Bc = p->Bc; + const size_t n_hvx = p->n_hvx; + const size_t n_heads = p->n_heads; + const bool pipeline = p->pipeline; + const bool has_mask = p->has_mask; + const bool mask_broadcast = p->mask_broadcast; + const bool has_sinks = p->has_sinks; + + const size_t g_br = hex_align_up(gqa_factor * Br, is_w8a8 ? HMX_W8A8_ACT_TILE_N_ROWS : HMX_FP16_TILE_N_ROWS); + const size_t n_row_tiles_64 = g_br / HMX_W8A8_ACT_TILE_N_ROWS; + const size_t n_col_tiles = Bc / HMX_W8A8_TILE_N_COLS; + const size_t n_k_tiles = DK / HMX_W8A8_TILE_N_COLS; + const size_t n_v_tiles = DV / HMX_W8A8_TILE_N_COLS; + + const size_t q_tile_size = is_w8a8 + ? (n_row_tiles_64 * n_k_tiles * HMX_W8A8_ACT_TILE_SIZE) + : hex_align_up(g_br * DK * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE); + const size_t o_tile_size = is_w8a8 + ? 0 + : hex_align_up(g_br * DV * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE); + const size_t k_tile_size = is_w8a8 + ? hex_align_up(n_col_tiles * n_k_tiles * HMX_W8A8_WT_TILE_SIZE, HTP_FA_HMX_TILE_SIZE) + : hex_align_up(Bc * DK * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE); + const size_t v_tile_size = is_w8a8 + ? hex_align_up(n_v_tiles * n_col_tiles * HMX_W8A8_WT_TILE_SIZE, HTP_FA_HMX_TILE_SIZE) + : hex_align_up(Bc * DV * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE); + const size_t s_tile_size = is_w8a8 + ? (n_row_tiles_64 * n_col_tiles * 2 * HMX_W8A8_ACT_TILE_SIZE) + : hex_align_up(g_br * Bc * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE); + const size_t p_tile_size = is_w8a8 + ? (n_row_tiles_64 * n_col_tiles * HMX_W8A8_ACT_TILE_SIZE) + : hex_align_up(g_br * Bc * sizeof(__fp16), HTP_FA_HMX_TILE_SIZE); // The rescale matrices are diagonal: the HMX kernels only ever load the g_br/32 // tiles that sit on the diagonal, so store just those, packed back to back with // a stride of one tile. The old [g_br, g_br] square layout allocated g_br/32 // times more than it used, which is also why a second D buffer was unaffordable. - const size_t d_tile_size = (g_br / HMX_FP16_TILE_N_ROWS) * HTP_FA_HMX_TILE_SIZE; - - const size_t q_dma_size = hex_align_up(g_br * DK * (is_q_fp32 ? sizeof(float) : sizeof(__fp16)), 128); - const size_t k_dma_size = hex_align_up(Bc * hex_round_up(DK * sizeof(__fp16), 128), 128); - const size_t v_dma_size = hex_align_up(Bc * hex_round_up(DV * sizeof(__fp16), 128), 128); - const size_t col_vec_size = hex_align_up(g_br * sizeof(float), 256); - const size_t row_vec_size = hex_align_up(Bc * sizeof(__fp16), 256); - const size_t m_line_size = hex_align_up(Bc * sizeof(__fp16), 128); - const size_t m_buf_slot = hex_align_up(Br * m_line_size, 256); - const size_t m_buf_size = m_buf_slot * HMX_FA_DMA_CACHE_SIZE; - const size_t slopes_size = hex_align_up(g_br * sizeof(__fp16), 128); - const size_t sinks_size = hex_round_up(n_heads * sizeof(float), 128); + const size_t d_tile_size = is_w8a8 ? 0 : (g_br / HMX_FP16_TILE_N_ROWS) * HTP_FA_HMX_TILE_SIZE; + const size_t o_f32_size = hex_align_up(g_br * DV * sizeof(float), 128); + const size_t do_tile_size = n_row_tiles_64 * n_v_tiles * 2 * HMX_W8A8_ACT_TILE_SIZE; + + const size_t k_raw_row_padded = is_w8a8 + ? hex_round_up((DK / 32) * 34, 128) + : hex_round_up(DK * sizeof(__fp16), 128); + const size_t v_raw_row_padded = is_w8a8 + ? hex_round_up((DV / 32) * 34, 128) + : hex_round_up(DV * sizeof(__fp16), 128); + + const size_t q_dma_size = hex_align_up(g_br * htp_tensor_get_row_size(p->q_type, DK), 128); + const size_t k_dma_size = hex_align_up(Bc * k_raw_row_padded, 128); + const size_t v_dma_size = hex_align_up(Bc * v_raw_row_padded, 128); + const size_t col_vec_size = hex_align_up(g_br * sizeof(float), 256); + const size_t row_vec_size = hex_align_up(Bc * sizeof(__fp16), 256); + const size_t m_line_size = hex_align_up(Bc * sizeof(__fp16), 128); + const size_t m_buf_slot = hex_align_up(Br * m_line_size, 256); + const size_t m_buf_slots = mask_broadcast ? HMX_FA_DMA_CACHE_SIZE : gqa_factor; + const size_t m_buf_size = m_buf_slot * m_buf_slots; + const size_t slopes_size = hex_align_up(g_br * sizeof(__fp16), 128); + const size_t sinks_size = hex_round_up(n_heads * sizeof(float), 128); + const size_t q_scales_size = hex_align_up(g_br * sizeof(float), 128); + const size_t k_scales_size = hex_align_up(Bc * sizeof(float), 128); + const size_t k_bias_size = hex_align_up(n_col_tiles * 2 * HMX_W8A8_BIAS_BANK_SIZE, HMX_W8A8_BIAS_BANK_SIZE); + const size_t v_scales_size = hex_align_up(DV * sizeof(float), 128); + const size_t v_bias_size = hex_align_up(n_v_tiles * 2 * HMX_W8A8_BIAS_BANK_SIZE, HMX_W8A8_BIAS_BANK_SIZE); + const size_t p_scales_size = hex_align_up(g_br * sizeof(float), 128); + const size_t exp_mdiff_size = hex_align_up(g_br * sizeof(float), 128); size_t off = 0; // Group A (Part 1 - HMX Tiled buffers) - VTCM_LAYOUT_ALLOC(off, off_q_tiles, q_tile_size); - VTCM_LAYOUT_ALLOC(off, off_o_tiles[0], o_tile_size); - VTCM_LAYOUT_ALLOC(off, off_o_tiles[1], o_tile_size); - VTCM_LAYOUT_ALLOC(off, off_d_tiles[0], d_tile_size); - VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_d_tiles[1], d_tile_size, pipeline); - VTCM_LAYOUT_ALLOC(off, off_d_inv_l, d_tile_size); + VTCM_LAYOUT_ALLOC(off, off_q_tiles, q_tile_size); + VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_o_tiles[0], o_tile_size, !is_w8a8); + VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_o_tiles[1], o_tile_size, !is_w8a8); + VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_d_tiles[0], d_tile_size, !is_w8a8); + VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_d_tiles[1], d_tile_size, !is_w8a8 && pipeline); + VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_d_inv_l, d_tile_size, !is_w8a8); // Group B & C share start offset (Group B tiles must be 2KB aligned) size_t off_group_b_c = hex_align_up(off, HTP_FA_HMX_TILE_SIZE); @@ -203,11 +286,27 @@ static inline void hmx_fa_vtcm_layout_build(struct hmx_fa_vtcm_layout * L, VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_v_tiles[1], v_tile_size, pipeline); VTCM_LAYOUT_ALLOC(off_group_b, off_s_tiles[0], s_tile_size); VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_s_tiles[1], s_tile_size, pipeline); - VTCM_LAYOUT_ALLOC(off_group_b, off_p_tiles[0], s_tile_size); - VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_p_tiles[1], s_tile_size, pipeline); + VTCM_LAYOUT_ALLOC(off_group_b, off_p_tiles[0], p_tile_size); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_p_tiles[1], p_tile_size, pipeline); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_do_tiles, do_tile_size, is_w8a8); VTCM_LAYOUT_ALLOC(off_group_b, off_s_rowmax, col_vec_size); VTCM_LAYOUT_ALLOC(off_group_b, off_p_rowsum, col_vec_size); - VTCM_LAYOUT_ALLOC(off_group_b, off_row_bufs, row_vec_size * 2 * n_hvx); + VTCM_LAYOUT_ALLOC(off_group_b, off_row_bufs, row_vec_size * (is_w8a8 ? 4 : 2) * n_hvx); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_k_scales[0], k_scales_size, is_w8a8); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_k_scales[1], k_scales_size, is_w8a8 && pipeline); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_v_scales[0], v_scales_size, is_w8a8); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_v_scales[1], v_scales_size, is_w8a8 && pipeline); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_p_scales[0], p_scales_size, is_w8a8); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_p_scales[1], p_scales_size, is_w8a8 && pipeline); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_exp_mdiff[0], exp_mdiff_size, is_w8a8); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_exp_mdiff[1], exp_mdiff_size, is_w8a8 && pipeline); + if (is_w8a8) { + off_group_b = hex_align_up(off_group_b, HMX_W8A8_BIAS_BANK_SIZE); + } + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_k_bias[0], k_bias_size, is_w8a8); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_k_bias[1], k_bias_size, is_w8a8 && pipeline); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_v_bias[0], v_bias_size, is_w8a8); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_v_bias[1], v_bias_size, is_w8a8 && pipeline); const size_t group_b_size = off_group_b - off_group_b_c; @@ -220,6 +319,7 @@ static inline void hmx_fa_vtcm_layout_build(struct hmx_fa_vtcm_layout * L, off = off_group_b_c + hex_smax(group_b_size, group_c_size); // Group A (Part 2 - remaining non-HMX buffers) + VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_o_f32, o_f32_size, is_w8a8); VTCM_LAYOUT_ALLOC(off, off_k_fp16[0], k_dma_size); VTCM_LAYOUT_ALLOC(off, off_k_fp16[1], k_dma_size); VTCM_LAYOUT_ALLOC(off, off_v_fp16[0], v_dma_size); @@ -228,8 +328,9 @@ static inline void hmx_fa_vtcm_layout_build(struct hmx_fa_vtcm_layout * L, VTCM_LAYOUT_ALLOC(off, off_l_vec, col_vec_size); VTCM_LAYOUT_ALLOC(off, off_hmx_scales_id, 256); VTCM_LAYOUT_ALLOC(off, off_hmx_scales_qk, 256); - VTCM_LAYOUT_ALLOC(off, off_mask_buf, m_buf_size); + VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_mask_buf, m_buf_size, has_mask); VTCM_LAYOUT_ALLOC(off, off_slopes, slopes_size); + VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_q_scales, q_scales_size, is_w8a8); VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_sinks, sinks_size, has_sinks); L->q_tile_bytes = q_tile_size; @@ -237,29 +338,44 @@ static inline void hmx_fa_vtcm_layout_build(struct hmx_fa_vtcm_layout * L, L->k_tile_bytes = k_tile_size; L->col_vec_bytes = col_vec_size; L->s_tile_bytes = s_tile_size; + L->p_tile_bytes = p_tile_size; // Measured from the actual offsets rather than assumed to be N * d_tile_size, so // that inserting a region between them (or adding padding to VTCM_LAYOUT_ALLOC) // cannot silently leave the tail of the run unzeroed. - L->d_tile_bytes = (L->off_d_inv_l + d_tile_size) - L->off_d_tiles[0]; + L->d_tile_bytes = is_w8a8 ? 0 : ((L->off_d_inv_l + d_tile_size) - L->off_d_tiles[0]); + L->o_f32_bytes = is_w8a8 ? o_f32_size : 0; L->m_line_bytes = m_line_size; L->m_buf_slot_bytes = m_buf_slot; + L->k_raw_row_padded = k_raw_row_padded; + L->v_raw_row_padded = v_raw_row_padded; L->row_buf_stride = row_vec_size / 128; L->mask_buf_row_stride = m_line_size / sizeof(__fp16); L->sinks_bytes = has_sinks ? sinks_size : 0; L->pipeline = pipeline; + L->is_w8a8 = is_w8a8; L->total_bytes = off; } -// Exact VTCM usage for a given (gqa_factor, DK, DV, Br, Bc) configuration. -static inline size_t hmx_fa_compute_vtcm_usage(size_t gqa_factor, size_t DK, size_t DV, size_t Br, size_t Bc, size_t n_hvx, bool pipeline, bool is_q_fp32, bool has_sinks, size_t n_heads) { +// Exact VTCM usage for a given HMX layout configuration. +static inline size_t hmx_fa_compute_vtcm_usage(const struct hmx_fa_layout_params * p) { struct hmx_fa_vtcm_layout L; - hmx_fa_vtcm_layout_build(&L, gqa_factor, DK, DV, Br, Bc, n_hvx, pipeline, is_q_fp32, has_sinks, n_heads); + hmx_fa_vtcm_layout_build(&L, p); return L.total_bytes; } #define FA_HVX_BLOCK_SIZE 64 #define FA_HVX_G_MAX 8 +struct hvx_fa_layout_params { + int q_type; + size_t DK; + size_t DV; + size_t n_heads; + size_t n_hvx; + bool has_mask; + bool has_sinks; +}; + struct hvx_fa_vtcm_layout { size_t off_q; size_t off_k; @@ -279,65 +395,57 @@ struct hvx_fa_vtcm_layout { }; static inline void hvx_fa_vtcm_layout_build(struct hvx_fa_vtcm_layout * L, - size_t DK, size_t DV, - bool is_q_fp32, bool has_mask, - bool has_sinks, size_t n_heads, - size_t n_hvx) { - const size_t size_q_row_padded = hex_round_up(DK * (is_q_fp32 ? 4 : 2), 128); - const size_t size_k_row_padded = hex_round_up(DK * sizeof(__fp16), 128); - const size_t size_v_row_padded = hex_round_up(DV * sizeof(__fp16), 128); + const struct hvx_fa_layout_params * p) { + const size_t size_q_row_padded = hex_round_up(htp_tensor_get_row_size(p->q_type, p->DK), 128); + const size_t size_k_row_padded = hex_round_up(p->DK * sizeof(__fp16), 128); + const size_t size_v_row_padded = hex_round_up(p->DV * sizeof(__fp16), 128); const size_t size_q_block = size_q_row_padded * FA_HVX_G_MAX; const size_t size_k_block = size_k_row_padded * FA_HVX_BLOCK_SIZE; const size_t size_v_block = size_v_row_padded * FA_HVX_BLOCK_SIZE; const size_t size_m_block = hex_round_up(FA_HVX_BLOCK_SIZE * sizeof(__fp16), 128); - const size_t size_vkq_acc = hex_round_up(DV * sizeof(float), 128) * FA_HVX_G_MAX; - const size_t size_sinks = hex_round_up(n_heads * sizeof(float), 128); + const size_t size_vkq_acc = hex_round_up(p->DV * sizeof(float), 256) * FA_HVX_G_MAX; + const size_t size_sinks = hex_round_up(p->n_heads * sizeof(float), 128); size_t off = 0; - VTCM_LAYOUT_ALLOC(off, off_q, size_q_block * n_hvx); - VTCM_LAYOUT_ALLOC(off, off_k, size_k_block * 2 * n_hvx); - VTCM_LAYOUT_ALLOC(off, off_v, size_v_block * 2 * n_hvx); - VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_m, size_m_block * HVX_FA_DMA_CACHE_SIZE * n_hvx, has_mask); - VTCM_LAYOUT_ALLOC(off, off_a, size_vkq_acc * n_hvx); - VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_sinks, size_sinks, has_sinks); + VTCM_LAYOUT_ALLOC(off, off_q, size_q_block * p->n_hvx); + VTCM_LAYOUT_ALLOC(off, off_k, size_k_block * 2 * p->n_hvx); + VTCM_LAYOUT_ALLOC(off, off_v, size_v_block * 2 * p->n_hvx); + VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_m, size_m_block * HVX_FA_DMA_CACHE_SIZE * p->n_hvx, p->has_mask); + VTCM_LAYOUT_ALLOC(off, off_a, size_vkq_acc * p->n_hvx); + VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_sinks, size_sinks, p->has_sinks); L->size_q_block = size_q_block; L->size_k_block = size_k_block; L->size_v_block = size_v_block; L->size_m_block = size_m_block; L->size_vkq_acc = size_vkq_acc; - L->size_sinks = has_sinks ? size_sinks : 0; + L->size_sinks = p->has_sinks ? size_sinks : 0; L->total_bytes = off; } -static inline size_t hvx_fa_compute_vtcm_usage(size_t DK, size_t DV, bool is_q_fp32, bool has_mask, bool has_sinks, size_t n_heads, size_t n_hvx) { +static inline size_t hvx_fa_compute_vtcm_usage(const struct hvx_fa_layout_params * p) { struct hvx_fa_vtcm_layout L; - hvx_fa_vtcm_layout_build(&L, DK, DV, is_q_fp32, has_mask, has_sinks, n_heads, n_hvx); + hvx_fa_vtcm_layout_build(&L, p); return L.total_bytes; } #define FA_MIN_KV_BLOCKS 3 // Cost-based (Br, Bc) search for flash attention with pipeline constraint. -static inline int hmx_fa_find_chunk_size(size_t * Br_out, - size_t * Bc_out, - size_t gqa_factor, - size_t DK, - size_t DV, - size_t qo_len, - size_t kv_len, - size_t vtcm_budget, - size_t n_hvx, - bool is_q_fp32, - bool has_sinks, - size_t n_heads, - size_t q_split) { - const size_t T = HMX_FP16_TILE_N_ROWS; // 32 - const size_t br_unit = hmx_ceil_div(T, gqa_factor); - const size_t bc_unit = HMX_FP16_TILE_N_COLS * 2; // 64 - const bool can_pipeline = (kv_len >= FA_MIN_KV_BLOCKS * bc_unit && n_hvx >= 2); +static inline int hmx_fa_find_chunk_size(struct hmx_fa_layout_params * p, + size_t qo_len, + size_t kv_len, + size_t vtcm_budget, + size_t q_split) { + const size_t gqa_factor = p->gqa_factor; + const size_t n_hvx = p->n_hvx; + const bool is_w8a8 = (p->kernel_type == HTP_FA_KERNEL_HMX_W8A8); + const size_t T = HMX_FP16_TILE_N_ROWS; // 32 + const size_t br_unit = hmx_ceil_div(T, gqa_factor); + const size_t bc_unit = HMX_FP16_TILE_N_COLS * 2; // 64 + const bool can_pipeline = (kv_len >= FA_MIN_KV_BLOCKS * bc_unit && n_hvx >= 2 && (!p->has_mask || p->mask_broadcast)); // Br_max: largest Br aligned to br_unit that does not exceed qo_len. const size_t Br_max = qo_len >= br_unit ? hex_align_down(qo_len, br_unit) : br_unit; @@ -350,6 +458,10 @@ static inline int hmx_fa_find_chunk_size(size_t * Br_out, if (qo_len <= 16 && kv_len <= 2048 && Bc_limit > 256) { Bc_limit = 256; } + // Cap Bc at 2048 for W8A8 so P * V always runs in 1 superblock (<= 64 tiles of 32) + if (is_w8a8 && Bc_limit > 2048) { + Bc_limit = 2048; + } // Cost coefficients calibrated from profiling const size_t c_q_fixed = 800; // per-Q-block: q_load + epilogue o_update + o_norm + o_store const size_t c_iter_base = 200; // per-KV-iter base (HMX dot/update + DMA) @@ -358,10 +470,15 @@ static inline int hmx_fa_find_chunk_size(size_t * Br_out, size_t best_cost = SIZE_MAX, best_mn = 0; size_t best_Br = 0, best_Bc = 0; + struct hmx_fa_layout_params cand = *p; + cand.pipeline = can_pipeline; + for (size_t Br = Br_max; Br >= br_unit; Br -= br_unit) { + cand.Br = Br; // Try all Bc candidates from Bc_limit down to bc_unit for (size_t Bc = Bc_limit; Bc >= bc_unit; Bc -= bc_unit) { - size_t vtcm_needed = hmx_fa_compute_vtcm_usage(gqa_factor, DK, DV, Br, Bc, n_hvx, can_pipeline, is_q_fp32, has_sinks, n_heads); + cand.Bc = Bc; + size_t vtcm_needed = hmx_fa_compute_vtcm_usage(&cand); if (vtcm_needed <= vtcm_budget) { // This Bc fits for this Br! const size_t q_blocks = (qo_len + Br - 1) / Br; @@ -398,8 +515,8 @@ static inline int hmx_fa_find_chunk_size(size_t * Br_out, return -1; } - *Br_out = best_Br; - *Bc_out = best_Bc; + p->Br = best_Br; + p->Bc = best_Bc; return 0; } 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 68b9c1d4767d..c468ffdbd0a1 100644 --- a/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c +++ b/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -8,6 +9,7 @@ #include "hvx-copy.h" #include "hvx-reduce.h" #include "hvx-exp.h" +#include "hvx-repl.h" #include "dma-queue.h" #include "ggml-common.h" #include "htp-ctx.h" @@ -18,20 +20,47 @@ #include "hmx-queue.h" #include "gated-delta-net-ops.h" -#ifndef MIN -#define MIN(a, b) ((a) < (b) ? (a) : (b)) -#endif +struct htp_gdn_context; + +typedef void (*gdn_load_vec_fn_t)(HVX_Vector * restrict dst, const void * restrict src, uint32_t n); +typedef void (*gdn_store_vec_fn_t)(void * restrict dst, const HVX_Vector * restrict src, uint32_t n); +typedef void (*gdn_step_fn_t)( + const struct htp_gdn_context * gctx, + float * restrict s_work, + void * restrict attn_out, + const void * restrict q_t, + const void * restrict k_t, + const void * restrict v_t, + const float * restrict g_t, + const float * restrict beta_t, + HVX_Vector * restrict vtcm_scratch, + float scale, + uint32_t S_v, + const void * restrict k_next, + bool has_memory +); struct htp_gdn_context { struct htp_ops_context * octx; const struct htp_gdn_kernel_params * kparams; struct htp_gdn_vtcm_layout layout; uint8_t * vtcm_base; + const void * ids_data; + const int32_t * n_rep_data; + uint32_t ids_type; + uint32_t n_pend; + bool replay; + bool keep; uint32_t row_start; uint32_t nrows; + gdn_load_vec_fn_t load_q; + gdn_load_vec_fn_t load_k; + gdn_load_vec_fn_t load_v; + gdn_store_vec_fn_t store_out; + gdn_step_fn_t step_fn; }; -static inline HVX_Vector gdn_mul_dot_f32(float * restrict dst, const HVX_Vector * restrict mul, const HVX_Vector * restrict dot, uint32_t n) { +static __attribute__((noinline)) HVX_Vector gdn_mul_dot_f32(float * restrict dst, const HVX_Vector * restrict mul, const HVX_Vector * restrict dot, uint32_t n) { HVX_Vector acc = Q6_V_vzero(); const uint32_t epv = 128 / sizeof(float); const uint32_t nvec = n / epv; @@ -60,7 +89,7 @@ static inline HVX_Vector gdn_mul_dot_f32(float * restrict dst, const HVX_Vector return hvx_vec_reduce_sum_f32(acc); } -static inline HVX_Vector gdn_mul_scalar_dot_f32(float * restrict dst, HVX_Vector vmul, const HVX_Vector * restrict dot, uint32_t n) { +static __attribute__((noinline)) HVX_Vector gdn_mul_scalar_dot_f32(float * restrict dst, HVX_Vector vmul, const HVX_Vector * restrict dot, uint32_t n) { HVX_Vector acc = Q6_V_vzero(); const uint32_t epv = 128 / sizeof(float); const uint32_t nvec = n / epv; @@ -87,7 +116,7 @@ static inline HVX_Vector gdn_mul_scalar_dot_f32(float * restrict dst, HVX_Vector return hvx_vec_reduce_sum_f32(acc); } -static inline HVX_Vector gdn_add_scaled_dot_f32(float * restrict dst, const HVX_Vector * restrict src, +static __attribute__((noinline)) HVX_Vector gdn_add_scaled_dot_f32(float * restrict dst, const HVX_Vector * restrict src, HVX_Vector vscale, const HVX_Vector * restrict dot, uint32_t n) { HVX_Vector acc = Q6_V_vzero(); const uint32_t epv = 128 / sizeof(float); @@ -117,7 +146,7 @@ static inline HVX_Vector gdn_add_scaled_dot_f32(float * restrict dst, const HVX_ return hvx_vec_reduce_sum_f32(acc); } -static inline HVX_Vector gdn_mul_dot4_f32(float * restrict dst0, float * restrict dst1, +static __attribute__((noinline)) HVX_Vector gdn_mul_dot4_f32(float * restrict dst0, float * restrict dst1, float * restrict dst2, float * restrict dst3, const HVX_Vector * restrict mul, const HVX_Vector * restrict dot, uint32_t n) { HVX_Vector acc0 = Q6_V_vzero(); @@ -175,7 +204,7 @@ static inline HVX_Vector gdn_mul_dot4_f32(float * restrict dst0, float * restric return hvx_vec_reduce_sum_f32x4(acc); } -static inline HVX_Vector gdn_mul_scalar_dot4_f32(float * restrict dst0, float * restrict dst1, +static __attribute__((noinline)) HVX_Vector gdn_mul_scalar_dot4_f32(float * restrict dst0, float * restrict dst1, float * restrict dst2, float * restrict dst3, HVX_Vector vmul, const HVX_Vector * restrict dot, uint32_t n) { HVX_Vector acc0 = Q6_V_vzero(); @@ -231,18 +260,18 @@ static inline HVX_Vector gdn_mul_scalar_dot4_f32(float * restrict dst0, float * return hvx_vec_reduce_sum_f32x4(acc); } -static inline HVX_Vector gdn_add_scaled_dot4_f32(float * restrict dst0, float * restrict dst1, +static __attribute__((noinline)) HVX_Vector gdn_add_scaled_dot4_f32(float * restrict dst0, float * restrict dst1, float * restrict dst2, float * restrict dst3, - const HVX_Vector * restrict src, const float * restrict scale, + const HVX_Vector * restrict src, HVX_Vector vscale, const HVX_Vector * restrict dot, uint32_t n) { HVX_Vector acc0 = Q6_V_vzero(); HVX_Vector acc1 = Q6_V_vzero(); HVX_Vector acc2 = Q6_V_vzero(); HVX_Vector acc3 = Q6_V_vzero(); - const HVX_Vector scale0 = hvx_vec_splat_f32(scale[0]); - const HVX_Vector scale1 = hvx_vec_splat_f32(scale[1]); - const HVX_Vector scale2 = hvx_vec_splat_f32(scale[2]); - const HVX_Vector scale3 = hvx_vec_splat_f32(scale[3]); + const HVX_Vector scale0 = hvx_vec_repl_f32(vscale); + const HVX_Vector scale1 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 1 * sizeof(float))); + const HVX_Vector scale2 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 2 * sizeof(float))); + const HVX_Vector scale3 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 3 * sizeof(float))); const uint32_t epv = 128 / sizeof(float); const uint32_t nvec = n / epv; @@ -294,7 +323,7 @@ static inline HVX_Vector gdn_add_scaled_dot4_f32(float * restrict dst0, float * return hvx_vec_reduce_sum_f32x4(acc); } -static inline HVX_Vector gdn_mul_dot8_f32(float * restrict dst0, float * restrict dst1, +static __attribute__((noinline)) HVX_Vector gdn_mul_dot8_f32(float * restrict dst0, float * restrict dst1, float * restrict dst2, float * restrict dst3, float * restrict dst4, float * restrict dst5, float * restrict dst6, float * restrict dst7, const HVX_Vector * restrict mul, const HVX_Vector * restrict dot, uint32_t n) { @@ -385,7 +414,7 @@ static inline HVX_Vector gdn_mul_dot8_f32(float * restrict dst0, float * restric return Q6_V_vmux_QVV(q16, rA, Q6_V_vror_VR(rB, 128 - 16)); } -static inline HVX_Vector gdn_mul_scalar_dot8_f32(float * restrict dst0, float * restrict dst1, +static __attribute__((noinline)) HVX_Vector gdn_mul_scalar_dot8_f32(float * restrict dst0, float * restrict dst1, float * restrict dst2, float * restrict dst3, float * restrict dst4, float * restrict dst5, float * restrict dst6, float * restrict dst7, HVX_Vector vmul, const HVX_Vector * restrict dot, uint32_t n) { @@ -474,10 +503,10 @@ static inline HVX_Vector gdn_mul_scalar_dot8_f32(float * restrict dst0, float * return Q6_V_vmux_QVV(q16, rA, Q6_V_vror_VR(rB, 128 - 16)); } -static inline HVX_Vector gdn_add_scaled_dot8_f32(float * restrict dst0, float * restrict dst1, +static __attribute__((noinline)) HVX_Vector gdn_add_scaled_dot8_f32(float * restrict dst0, float * restrict dst1, float * restrict dst2, float * restrict dst3, float * restrict dst4, float * restrict dst5, float * restrict dst6, float * restrict dst7, - const HVX_Vector * restrict src, const float * restrict scale, + const HVX_Vector * restrict src, HVX_Vector vscale, const HVX_Vector * restrict dot, uint32_t n) { HVX_Vector acc0 = Q6_V_vzero(); HVX_Vector acc1 = Q6_V_vzero(); @@ -487,14 +516,14 @@ static inline HVX_Vector gdn_add_scaled_dot8_f32(float * restrict dst0, float * HVX_Vector acc5 = Q6_V_vzero(); HVX_Vector acc6 = Q6_V_vzero(); HVX_Vector acc7 = Q6_V_vzero(); - const HVX_Vector scale0 = hvx_vec_splat_f32(scale[0]); - const HVX_Vector scale1 = hvx_vec_splat_f32(scale[1]); - const HVX_Vector scale2 = hvx_vec_splat_f32(scale[2]); - const HVX_Vector scale3 = hvx_vec_splat_f32(scale[3]); - const HVX_Vector scale4 = hvx_vec_splat_f32(scale[4]); - const HVX_Vector scale5 = hvx_vec_splat_f32(scale[5]); - const HVX_Vector scale6 = hvx_vec_splat_f32(scale[6]); - const HVX_Vector scale7 = hvx_vec_splat_f32(scale[7]); + const HVX_Vector scale0 = hvx_vec_repl_f32(vscale); + const HVX_Vector scale1 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 1 * sizeof(float))); + const HVX_Vector scale2 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 2 * sizeof(float))); + const HVX_Vector scale3 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 3 * sizeof(float))); + const HVX_Vector scale4 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 4 * sizeof(float))); + const HVX_Vector scale5 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 5 * sizeof(float))); + const HVX_Vector scale6 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 6 * sizeof(float))); + const HVX_Vector scale7 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 7 * sizeof(float))); const uint32_t epv = 128 / sizeof(float); const uint32_t nvec = n / epv; @@ -574,218 +603,933 @@ 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 __attribute__((noinline)) void gdn_add_scaled_f32(float * restrict dst, + const HVX_Vector * restrict src, HVX_Vector vscale, uint32_t n) { + const uint32_t epv = 128 / sizeof(float); + const uint32_t nvec = n / epv; + const uint32_t nloe = n % epv; + for (uint32_t i = 0; i < nvec; ++i) { + HVX_Vector vd = hvx_vmemu(dst + i * epv); + HVX_Vector out = hvx_vec_add_f32_f32(vd, hvx_vec_mul_f32_f32(src[i], vscale)); + hvx_vmemu(dst + i * epv) = out; + } + if (nloe) { + const uint32_t off = nvec * epv; + HVX_Vector out = hvx_vec_add_f32_f32(hvx_vmemu(dst + off), hvx_vec_mul_f32_f32(src[nvec], vscale)); + hvx_vec_store_u(dst + off, nloe * sizeof(float), out); + } +} + +static __attribute__((noinline)) void gdn_add_scaled4_f32(float * restrict dst0, float * restrict dst1, + float * restrict dst2, float * restrict dst3, + const HVX_Vector * restrict src, HVX_Vector vscale, uint32_t n) { + const HVX_Vector scale0 = hvx_vec_repl_f32(vscale); + const HVX_Vector scale1 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 1 * sizeof(float))); + const HVX_Vector scale2 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 2 * sizeof(float))); + const HVX_Vector scale3 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 3 * sizeof(float))); + + const uint32_t epv = 128 / sizeof(float); + const uint32_t nvec = n / epv; + const uint32_t nloe = n % epv; + for (uint32_t i = 0; i < nvec; ++i) { + HVX_Vector vs = src[i]; + hvx_vmemu(dst0 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst0 + i * epv), hvx_vec_mul_f32_f32(vs, scale0)); + hvx_vmemu(dst1 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst1 + i * epv), hvx_vec_mul_f32_f32(vs, scale1)); + hvx_vmemu(dst2 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst2 + i * epv), hvx_vec_mul_f32_f32(vs, scale2)); + hvx_vmemu(dst3 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst3 + i * epv), hvx_vec_mul_f32_f32(vs, scale3)); + } + if (nloe) { + const uint32_t off = nvec * epv; + HVX_Vector vs = src[nvec]; + hvx_vec_store_u(dst0 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst0 + off), hvx_vec_mul_f32_f32(vs, scale0))); + hvx_vec_store_u(dst1 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst1 + off), hvx_vec_mul_f32_f32(vs, scale1))); + hvx_vec_store_u(dst2 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst2 + off), hvx_vec_mul_f32_f32(vs, scale2))); + hvx_vec_store_u(dst3 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst3 + off), hvx_vec_mul_f32_f32(vs, scale3))); + } +} + +static __attribute__((noinline)) void gdn_add_scaled8_f32(float * restrict dst0, float * restrict dst1, + float * restrict dst2, float * restrict dst3, float * restrict dst4, + float * restrict dst5, float * restrict dst6, float * restrict dst7, + const HVX_Vector * restrict src, HVX_Vector vscale, uint32_t n) { + const HVX_Vector scale0 = hvx_vec_repl_f32(vscale); + const HVX_Vector scale1 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 1 * sizeof(float))); + const HVX_Vector scale2 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 2 * sizeof(float))); + const HVX_Vector scale3 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 3 * sizeof(float))); + const HVX_Vector scale4 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 4 * sizeof(float))); + const HVX_Vector scale5 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 5 * sizeof(float))); + const HVX_Vector scale6 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 6 * sizeof(float))); + const HVX_Vector scale7 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 7 * sizeof(float))); + + const uint32_t epv = 128 / sizeof(float); + const uint32_t nvec = n / epv; + const uint32_t nloe = n % epv; + for (uint32_t i = 0; i < nvec; ++i) { + HVX_Vector vs = src[i]; + hvx_vmemu(dst0 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst0 + i * epv), hvx_vec_mul_f32_f32(vs, scale0)); + hvx_vmemu(dst1 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst1 + i * epv), hvx_vec_mul_f32_f32(vs, scale1)); + hvx_vmemu(dst2 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst2 + i * epv), hvx_vec_mul_f32_f32(vs, scale2)); + hvx_vmemu(dst3 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst3 + i * epv), hvx_vec_mul_f32_f32(vs, scale3)); + hvx_vmemu(dst4 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst4 + i * epv), hvx_vec_mul_f32_f32(vs, scale4)); + hvx_vmemu(dst5 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst5 + i * epv), hvx_vec_mul_f32_f32(vs, scale5)); + hvx_vmemu(dst6 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst6 + i * epv), hvx_vec_mul_f32_f32(vs, scale6)); + hvx_vmemu(dst7 + i * epv) = hvx_vec_add_f32_f32(hvx_vmemu(dst7 + i * epv), hvx_vec_mul_f32_f32(vs, scale7)); + } + if (nloe) { + const uint32_t off = nvec * epv; + HVX_Vector vs = src[nvec]; + hvx_vec_store_u(dst0 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst0 + off), hvx_vec_mul_f32_f32(vs, scale0))); + hvx_vec_store_u(dst1 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst1 + off), hvx_vec_mul_f32_f32(vs, scale1))); + hvx_vec_store_u(dst2 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst2 + off), hvx_vec_mul_f32_f32(vs, scale2))); + hvx_vec_store_u(dst3 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst3 + off), hvx_vec_mul_f32_f32(vs, scale3))); + hvx_vec_store_u(dst4 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst4 + off), hvx_vec_mul_f32_f32(vs, scale4))); + hvx_vec_store_u(dst5 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst5 + off), hvx_vec_mul_f32_f32(vs, scale5))); + hvx_vec_store_u(dst6 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst6 + off), hvx_vec_mul_f32_f32(vs, scale6))); + hvx_vec_store_u(dst7 + off, nloe * sizeof(float), hvx_vec_add_f32_f32(hvx_vmemu(dst7 + off), hvx_vec_mul_f32_f32(vs, scale7))); + } +} + +static __attribute__((noinline)) HVX_Vector gdn_dot_f32(const float * restrict src, + const HVX_Vector * restrict dot, uint32_t n) { + HVX_Vector acc = Q6_V_vzero(); + const uint32_t epv = 128 / sizeof(float); + const uint32_t nvec = n / epv; + const uint32_t nloe = n % epv; + for (uint32_t i = 0; i < nvec; ++i) { + acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(hvx_vmemu(src + i * epv), dot[i])); + } + if (nloe) { + const uint32_t off = nvec * epv; + HVX_VectorPred mask = Q6_Q_vsetq2_R(nloe * sizeof(float)); + HVX_Vector zero = Q6_V_vzero(); + acc = hvx_vec_add_f32_f32(acc, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src + off), dot[nvec]), zero)); + } + return hvx_vec_reduce_sum_f32(acc); +} + +static __attribute__((noinline)) HVX_Vector gdn_dot4_f32(const float * restrict src0, const float * restrict src1, + const float * restrict src2, const float * restrict src3, + const HVX_Vector * restrict dot, uint32_t n) { + HVX_Vector acc0 = Q6_V_vzero(); + HVX_Vector acc1 = Q6_V_vzero(); + HVX_Vector acc2 = Q6_V_vzero(); + HVX_Vector acc3 = Q6_V_vzero(); + + const uint32_t epv = 128 / sizeof(float); + const uint32_t nvec = n / epv; + const uint32_t nloe = n % epv; + for (uint32_t i = 0; i < nvec; ++i) { + HVX_Vector vdot = dot[i]; + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(hvx_vmemu(src0 + i * epv), vdot)); + acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(hvx_vmemu(src1 + i * epv), vdot)); + acc2 = hvx_vec_add_f32_f32(acc2, hvx_vec_mul_f32_f32(hvx_vmemu(src2 + i * epv), vdot)); + acc3 = hvx_vec_add_f32_f32(acc3, hvx_vec_mul_f32_f32(hvx_vmemu(src3 + i * epv), vdot)); + } + if (nloe) { + const uint32_t off = nvec * epv; + HVX_Vector vdot = dot[nvec]; + HVX_VectorPred mask = Q6_Q_vsetq2_R(nloe * sizeof(float)); + HVX_Vector zero = Q6_V_vzero(); + acc0 = hvx_vec_add_f32_f32(acc0, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src0 + off), vdot), zero)); + acc1 = hvx_vec_add_f32_f32(acc1, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src1 + off), vdot), zero)); + acc2 = hvx_vec_add_f32_f32(acc2, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src2 + off), vdot), zero)); + acc3 = hvx_vec_add_f32_f32(acc3, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src3 + off), vdot), zero)); + } + + HVX_Vector_x4 acc = { .v = { acc0, acc1, acc2, acc3 } }; + return hvx_vec_reduce_sum_f32x4(acc); +} + +static __attribute__((noinline)) HVX_Vector gdn_dot8_f32(const float * restrict src0, const float * restrict src1, + const float * restrict src2, const float * restrict src3, const float * restrict src4, + const float * restrict src5, const float * restrict src6, const float * restrict src7, + const HVX_Vector * restrict dot, uint32_t n) { + HVX_Vector acc0 = Q6_V_vzero(); + HVX_Vector acc1 = Q6_V_vzero(); + HVX_Vector acc2 = Q6_V_vzero(); + HVX_Vector acc3 = Q6_V_vzero(); + HVX_Vector acc4 = Q6_V_vzero(); + HVX_Vector acc5 = Q6_V_vzero(); + HVX_Vector acc6 = Q6_V_vzero(); + HVX_Vector acc7 = Q6_V_vzero(); + + const uint32_t epv = 128 / sizeof(float); + const uint32_t nvec = n / epv; + const uint32_t nloe = n % epv; + for (uint32_t i = 0; i < nvec; ++i) { + HVX_Vector vdot = dot[i]; + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(hvx_vmemu(src0 + i * epv), vdot)); + acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(hvx_vmemu(src1 + i * epv), vdot)); + acc2 = hvx_vec_add_f32_f32(acc2, hvx_vec_mul_f32_f32(hvx_vmemu(src2 + i * epv), vdot)); + acc3 = hvx_vec_add_f32_f32(acc3, hvx_vec_mul_f32_f32(hvx_vmemu(src3 + i * epv), vdot)); + acc4 = hvx_vec_add_f32_f32(acc4, hvx_vec_mul_f32_f32(hvx_vmemu(src4 + i * epv), vdot)); + acc5 = hvx_vec_add_f32_f32(acc5, hvx_vec_mul_f32_f32(hvx_vmemu(src5 + i * epv), vdot)); + acc6 = hvx_vec_add_f32_f32(acc6, hvx_vec_mul_f32_f32(hvx_vmemu(src6 + i * epv), vdot)); + acc7 = hvx_vec_add_f32_f32(acc7, hvx_vec_mul_f32_f32(hvx_vmemu(src7 + i * epv), vdot)); + } + if (nloe) { + const uint32_t off = nvec * epv; + HVX_Vector vdot = dot[nvec]; + HVX_VectorPred mask = Q6_Q_vsetq2_R(nloe * sizeof(float)); + HVX_Vector zero = Q6_V_vzero(); + acc0 = hvx_vec_add_f32_f32(acc0, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src0 + off), vdot), zero)); + acc1 = hvx_vec_add_f32_f32(acc1, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src1 + off), vdot), zero)); + acc2 = hvx_vec_add_f32_f32(acc2, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src2 + off), vdot), zero)); + acc3 = hvx_vec_add_f32_f32(acc3, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src3 + off), vdot), zero)); + acc4 = hvx_vec_add_f32_f32(acc4, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src4 + off), vdot), zero)); + acc5 = hvx_vec_add_f32_f32(acc5, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src5 + off), vdot), zero)); + acc6 = hvx_vec_add_f32_f32(acc6, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src6 + off), vdot), zero)); + acc7 = hvx_vec_add_f32_f32(acc7, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(hvx_vmemu(src7 + off), vdot), zero)); + } + + HVX_Vector_x4 accA = { .v = { acc0, acc1, acc2, acc3 } }; + HVX_Vector_x4 accB = { .v = { acc4, acc5, acc6, acc7 } }; + HVX_Vector rA = hvx_vec_reduce_sum_f32x4(accA); + HVX_Vector rB = hvx_vec_reduce_sum_f32x4(accB); + HVX_VectorPred q16 = Q6_Q_vsetq2_R(16); + return Q6_V_vmux_QVV(q16, rA, Q6_V_vror_VR(rB, 128 - 16)); +} + +static __attribute__((noinline)) HVX_Vector gdn_scale_add_dot_f32(float * restrict dst, HVX_Vector vgate, + const HVX_Vector * restrict src, HVX_Vector vscale, + const HVX_Vector * restrict dot, uint32_t n) { + HVX_Vector acc = Q6_V_vzero(); + const uint32_t epv = 128 / sizeof(float); + const uint32_t nvec = n / epv; + const uint32_t nloe = n % epv; + for (uint32_t i = 0; i < nvec; ++i) { + HVX_Vector vd = hvx_vec_mul_f32_f32(hvx_vmemu(dst + i * epv), vgate); + HVX_Vector out = hvx_vec_add_f32_f32(vd, hvx_vec_mul_f32_f32(src[i], vscale)); + hvx_vmemu(dst + i * epv) = out; + acc = hvx_vec_add_f32_f32(acc, hvx_vec_mul_f32_f32(out, dot[i])); + } + if (nloe) { + const uint32_t off = nvec * epv; + HVX_VectorPred mask = Q6_Q_vsetq2_R(nloe * sizeof(float)); + HVX_Vector zero = Q6_V_vzero(); + HVX_Vector vd = hvx_vec_mul_f32_f32(hvx_vmemu(dst + off), vgate); + HVX_Vector out = hvx_vec_add_f32_f32(vd, hvx_vec_mul_f32_f32(src[nvec], vscale)); + hvx_vec_store_u(dst + off, nloe * sizeof(float), out); + acc = hvx_vec_add_f32_f32(acc, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out, dot[nvec]), zero)); + } + return hvx_vec_reduce_sum_f32(acc); +} + +static __attribute__((noinline)) HVX_Vector gdn_scale_add_dot4_f32(float * restrict dst0, float * restrict dst1, + float * restrict dst2, float * restrict dst3, HVX_Vector vgate, + const HVX_Vector * restrict src, HVX_Vector vscale, + const HVX_Vector * restrict dot, uint32_t n) { + HVX_Vector acc0 = Q6_V_vzero(); + HVX_Vector acc1 = Q6_V_vzero(); + HVX_Vector acc2 = Q6_V_vzero(); + HVX_Vector acc3 = Q6_V_vzero(); + const HVX_Vector scale0 = hvx_vec_repl_f32(vscale); + const HVX_Vector scale1 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 1 * sizeof(float))); + const HVX_Vector scale2 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 2 * sizeof(float))); + const HVX_Vector scale3 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 3 * sizeof(float))); + + const uint32_t epv = 128 / sizeof(float); + const uint32_t nvec = n / epv; + const uint32_t nloe = n % epv; + for (uint32_t i = 0; i < nvec; ++i) { + HVX_Vector vs = src[i]; + HVX_Vector vdot = dot[i]; + + HVX_Vector out0 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst0 + i * epv), vgate), hvx_vec_mul_f32_f32(vs, scale0)); + HVX_Vector out1 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst1 + i * epv), vgate), hvx_vec_mul_f32_f32(vs, scale1)); + HVX_Vector out2 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst2 + i * epv), vgate), hvx_vec_mul_f32_f32(vs, scale2)); + HVX_Vector out3 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst3 + i * epv), vgate), hvx_vec_mul_f32_f32(vs, scale3)); + + hvx_vmemu(dst0 + i * epv) = out0; + hvx_vmemu(dst1 + i * epv) = out1; + hvx_vmemu(dst2 + i * epv) = out2; + hvx_vmemu(dst3 + i * epv) = out3; + + acc0 = hvx_vec_add_f32_f32(acc0, hvx_vec_mul_f32_f32(out0, vdot)); + acc1 = hvx_vec_add_f32_f32(acc1, hvx_vec_mul_f32_f32(out1, vdot)); + acc2 = hvx_vec_add_f32_f32(acc2, hvx_vec_mul_f32_f32(out2, vdot)); + acc3 = hvx_vec_add_f32_f32(acc3, hvx_vec_mul_f32_f32(out3, vdot)); + } + if (nloe) { + const uint32_t off = nvec * epv; + HVX_Vector vs = src[nvec]; + HVX_Vector vdot = dot[nvec]; + HVX_VectorPred mask = Q6_Q_vsetq2_R(nloe * sizeof(float)); + HVX_Vector zero = Q6_V_vzero(); + + HVX_Vector out0 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst0 + off), vgate), hvx_vec_mul_f32_f32(vs, scale0)); + HVX_Vector out1 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst1 + off), vgate), hvx_vec_mul_f32_f32(vs, scale1)); + HVX_Vector out2 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst2 + off), vgate), hvx_vec_mul_f32_f32(vs, scale2)); + HVX_Vector out3 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst3 + off), vgate), hvx_vec_mul_f32_f32(vs, scale3)); + + hvx_vec_store_u(dst0 + off, nloe * sizeof(float), out0); + hvx_vec_store_u(dst1 + off, nloe * sizeof(float), out1); + hvx_vec_store_u(dst2 + off, nloe * sizeof(float), out2); + hvx_vec_store_u(dst3 + off, nloe * sizeof(float), out3); + + acc0 = hvx_vec_add_f32_f32(acc0, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out0, vdot), zero)); + acc1 = hvx_vec_add_f32_f32(acc1, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out1, vdot), zero)); + acc2 = hvx_vec_add_f32_f32(acc2, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out2, vdot), zero)); + acc3 = hvx_vec_add_f32_f32(acc3, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out3, vdot), zero)); + } + + HVX_Vector_x4 acc = { .v = { acc0, acc1, acc2, acc3 } }; + return hvx_vec_reduce_sum_f32x4(acc); +} + +static __attribute__((noinline)) HVX_VectorPair gdn_scale_add_dual_dot_f32(float * restrict dst, HVX_Vector vgate, + const HVX_Vector * restrict src, HVX_Vector vscale, + const HVX_Vector * restrict dot_q, const HVX_Vector * restrict dot_k, uint32_t n) { + HVX_Vector acc_q = Q6_V_vzero(); + HVX_Vector acc_k = Q6_V_vzero(); + const uint32_t epv = 128 / sizeof(float); + const uint32_t nvec = n / epv; + const uint32_t nloe = n % epv; + for (uint32_t i = 0; i < nvec; ++i) { + HVX_Vector vd = hvx_vec_mul_f32_f32(hvx_vmemu(dst + i * epv), vgate); + HVX_Vector out = hvx_vec_add_f32_f32(vd, hvx_vec_mul_f32_f32(src[i], vscale)); + hvx_vmemu(dst + i * epv) = out; + acc_q = hvx_vec_add_f32_f32(acc_q, hvx_vec_mul_f32_f32(out, dot_q[i])); + acc_k = hvx_vec_add_f32_f32(acc_k, hvx_vec_mul_f32_f32(out, dot_k[i])); + } + if (nloe) { + const uint32_t off = nvec * epv; + HVX_VectorPred mask = Q6_Q_vsetq2_R(nloe * sizeof(float)); + HVX_Vector zero = Q6_V_vzero(); + HVX_Vector vd = hvx_vec_mul_f32_f32(hvx_vmemu(dst + off), vgate); + HVX_Vector out = hvx_vec_add_f32_f32(vd, hvx_vec_mul_f32_f32(src[nvec], vscale)); + hvx_vec_store_u(dst + off, nloe * sizeof(float), out); + acc_q = hvx_vec_add_f32_f32(acc_q, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out, dot_q[nvec]), zero)); + acc_k = hvx_vec_add_f32_f32(acc_k, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out, dot_k[nvec]), zero)); + } + return Q6_W_vcombine_VV(hvx_vec_reduce_sum_f32(acc_k), hvx_vec_reduce_sum_f32(acc_q)); +} + +static __attribute__((noinline)) HVX_VectorPair gdn_scale_add_dual_dot4_f32(float * restrict dst0, float * restrict dst1, + float * restrict dst2, float * restrict dst3, HVX_Vector vgate, + const HVX_Vector * restrict src, HVX_Vector vscale, + const HVX_Vector * restrict dot_q, const HVX_Vector * restrict dot_k, uint32_t n) { + HVX_Vector aq0 = Q6_V_vzero(); + HVX_Vector aq1 = Q6_V_vzero(); + HVX_Vector aq2 = Q6_V_vzero(); + HVX_Vector aq3 = Q6_V_vzero(); + HVX_Vector ak0 = Q6_V_vzero(); + HVX_Vector ak1 = Q6_V_vzero(); + HVX_Vector ak2 = Q6_V_vzero(); + HVX_Vector ak3 = Q6_V_vzero(); + const HVX_Vector scale0 = hvx_vec_repl_f32(vscale); + const HVX_Vector scale1 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 1 * sizeof(float))); + const HVX_Vector scale2 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 2 * sizeof(float))); + const HVX_Vector scale3 = hvx_vec_repl_f32(Q6_V_vror_VR(vscale, 3 * sizeof(float))); + + const uint32_t epv = 128 / sizeof(float); + const uint32_t nvec = n / epv; + const uint32_t nloe = n % epv; + for (uint32_t i = 0; i < nvec; ++i) { + HVX_Vector vs = src[i]; + HVX_Vector vq = dot_q[i]; + HVX_Vector vk = dot_k[i]; + + HVX_Vector out0 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst0 + i * epv), vgate), hvx_vec_mul_f32_f32(vs, scale0)); + HVX_Vector out1 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst1 + i * epv), vgate), hvx_vec_mul_f32_f32(vs, scale1)); + HVX_Vector out2 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst2 + i * epv), vgate), hvx_vec_mul_f32_f32(vs, scale2)); + HVX_Vector out3 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst3 + i * epv), vgate), hvx_vec_mul_f32_f32(vs, scale3)); + + hvx_vmemu(dst0 + i * epv) = out0; + hvx_vmemu(dst1 + i * epv) = out1; + hvx_vmemu(dst2 + i * epv) = out2; + hvx_vmemu(dst3 + i * epv) = out3; + + aq0 = hvx_vec_add_f32_f32(aq0, hvx_vec_mul_f32_f32(out0, vq)); + aq1 = hvx_vec_add_f32_f32(aq1, hvx_vec_mul_f32_f32(out1, vq)); + aq2 = hvx_vec_add_f32_f32(aq2, hvx_vec_mul_f32_f32(out2, vq)); + aq3 = hvx_vec_add_f32_f32(aq3, hvx_vec_mul_f32_f32(out3, vq)); + + ak0 = hvx_vec_add_f32_f32(ak0, hvx_vec_mul_f32_f32(out0, vk)); + ak1 = hvx_vec_add_f32_f32(ak1, hvx_vec_mul_f32_f32(out1, vk)); + ak2 = hvx_vec_add_f32_f32(ak2, hvx_vec_mul_f32_f32(out2, vk)); + ak3 = hvx_vec_add_f32_f32(ak3, hvx_vec_mul_f32_f32(out3, vk)); + } + if (nloe) { + const uint32_t off = nvec * epv; + HVX_Vector vs = src[nvec]; + HVX_Vector vq = dot_q[nvec]; + HVX_Vector vk = dot_k[nvec]; + HVX_VectorPred mask = Q6_Q_vsetq2_R(nloe * sizeof(float)); + HVX_Vector zero = Q6_V_vzero(); + + HVX_Vector out0 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst0 + off), vgate), hvx_vec_mul_f32_f32(vs, scale0)); + HVX_Vector out1 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst1 + off), vgate), hvx_vec_mul_f32_f32(vs, scale1)); + HVX_Vector out2 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst2 + off), vgate), hvx_vec_mul_f32_f32(vs, scale2)); + HVX_Vector out3 = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmemu(dst3 + off), vgate), hvx_vec_mul_f32_f32(vs, scale3)); + + hvx_vec_store_u(dst0 + off, nloe * sizeof(float), out0); + hvx_vec_store_u(dst1 + off, nloe * sizeof(float), out1); + hvx_vec_store_u(dst2 + off, nloe * sizeof(float), out2); + hvx_vec_store_u(dst3 + off, nloe * sizeof(float), out3); + + aq0 = hvx_vec_add_f32_f32(aq0, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out0, vq), zero)); + aq1 = hvx_vec_add_f32_f32(aq1, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out1, vq), zero)); + aq2 = hvx_vec_add_f32_f32(aq2, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out2, vq), zero)); + aq3 = hvx_vec_add_f32_f32(aq3, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out3, vq), zero)); + + ak0 = hvx_vec_add_f32_f32(ak0, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out0, vk), zero)); + ak1 = hvx_vec_add_f32_f32(ak1, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out1, vk), zero)); + ak2 = hvx_vec_add_f32_f32(ak2, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out2, vk), zero)); + ak3 = hvx_vec_add_f32_f32(ak3, Q6_V_vmux_QVV(mask, hvx_vec_mul_f32_f32(out3, vk), zero)); + } + + HVX_Vector_x4 acc_q = { .v = { aq0, aq1, aq2, aq3 } }; + HVX_Vector_x4 acc_k = { .v = { ak0, ak1, ak2, ak3 } }; + return Q6_W_vcombine_VV(hvx_vec_reduce_sum_f32x4(acc_k), hvx_vec_reduce_sum_f32x4(acc_q)); +} + +static inline HVX_Vector gdn_clamp_f16_range_f32(HVX_Vector v, HVX_Vector v_min, HVX_Vector v_max) { + HVX_VectorPred p_gt = Q6_Q_vcmp_gt_VsfVsf(v, v_max); + v = Q6_V_vmux_QVV(p_gt, v_max, v); + HVX_VectorPred p_lt = Q6_Q_vcmp_gt_VsfVsf(v_min, v); + return Q6_V_vmux_QVV(p_lt, v_min, v); +} + +static inline HVX_Vector hvx_vec_load_u(const void * restrict src, uint32_t n) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) ((uintptr_t) src & ~(uintptr_t) 127); + const uint32_t left_off = (uint32_t) ((uintptr_t) src & 127); + const uint32_t right_off = left_off + n; + HVX_Vector v = (right_off > 128) ? Q6_V_valign_VVR(vsrc[1], vsrc[0], left_off) : Q6_V_vror_VR(vsrc[0], left_off); + return Q6_V_vand_QV(Q6_Q_vsetq2_R(n), v); +} + +static __attribute__((noinline)) void gdn_load_vec_f16_to_f32(HVX_Vector * restrict dst, const void * restrict src, uint32_t n) { + const __fp16 * restrict s16 = (const __fp16 *) src; + const uint32_t n64 = n / 64; + const uint32_t rem = n % 64; + #pragma clang loop unroll(disable) + for (uint32_t i = 0; i < n64; ++i) { + HVX_VectorPair p = hvx_vec_f16_to_f32(hvx_vmemu(s16 + i * 64)); + dst[2 * i + 0] = Q6_V_lo_W(p); + dst[2 * i + 1] = Q6_V_hi_W(p); + } + if (rem) { + HVX_VectorPair p = hvx_vec_f16_to_f32(hvx_vec_load_u(s16 + n64 * 64, rem * sizeof(__fp16))); + dst[2 * n64 + 0] = Q6_V_lo_W(p); + dst[2 * n64 + 1] = Q6_V_hi_W(p); + } +} + +static __attribute__((noinline)) void gdn_load_vec_f32(HVX_Vector * restrict dst, const void * restrict src, uint32_t n) { + const float * restrict s32 = (const float *) src; + const uint32_t n32 = n / 32; + const uint32_t rem = n % 32; + #pragma clang loop unroll(disable) + for (uint32_t i = 0; i < n32; ++i) { + dst[i] = hvx_vmemu(s32 + i * 32); + } + if (rem) { + dst[n32] = hvx_vec_load_u(s32 + n32 * 32, rem * sizeof(float)); + } +} + +static __attribute__((noinline)) void gdn_store_vec_f16(void * restrict dst, const HVX_Vector * restrict src, uint32_t n) { + __fp16 * restrict d16 = (__fp16 *) dst; + const HVX_Vector v_min = hvx_vec_splat_f32(-65504.0f); + const HVX_Vector v_max = hvx_vec_splat_f32(65504.0f); + const uint32_t n64 = n / 64; + const uint32_t rem = n % 64; + #pragma clang loop unroll(disable) + for (uint32_t i = 0; i < n64; ++i) { + HVX_Vector v0 = gdn_clamp_f16_range_f32(src[2 * i + 0], v_min, v_max); + HVX_Vector v1 = gdn_clamp_f16_range_f32(src[2 * i + 1], v_min, v_max); + hvx_vmemu(d16 + i * 64) = hvx_vec_f32_to_f16(v0, v1); + } + if (rem) { + HVX_Vector v0 = gdn_clamp_f16_range_f32(src[2 * n64 + 0], v_min, v_max); + HVX_Vector v1 = (rem > 32) ? gdn_clamp_f16_range_f32(src[2 * n64 + 1], v_min, v_max) : Q6_V_vzero(); + hvx_vec_store_u(d16 + n64 * 64, rem * sizeof(__fp16), hvx_vec_f32_to_f16(v0, v1)); + } +} + +static __attribute__((noinline)) void gdn_store_vec_f32(void * restrict dst, const HVX_Vector * restrict src, uint32_t n) { + float * restrict d32 = (float *) dst; + const uint32_t n32 = n / 32; + const uint32_t rem = n % 32; + #pragma clang loop unroll(disable) + for (uint32_t i = 0; i < n32; ++i) { + hvx_vmemu(d32 + i * 32) = src[i]; + } + if (rem) { + hvx_vec_store_u(d32 + n32 * 32, rem * sizeof(float), src[n32]); + } +} + +static __attribute__((noinline)) HVX_Vector gdn_vec_exp_f32(HVX_Vector v) { + return hvx_vec_exp_f32(v); +} + static __attribute__((noinline)) void gdn_step_kda_f32( + const struct htp_gdn_context * gctx, float * restrict s_work, - float * restrict attn_out, - const float * restrict q_t, - const float * restrict k_t, - const float * restrict v_t, + void * restrict attn_out, + const void * restrict q_t, + const void * restrict k_t, + const void * restrict v_t, const float * restrict g_t, - float beta_val, + const float * restrict beta_t, + HVX_Vector * restrict vtcm_scratch, float scale, - uint32_t S_v + uint32_t S_v, + const void * restrict k_next, + bool has_memory ) { + (void) k_next; + (void) has_memory; const uint32_t epv = 128 / sizeof(float); const uint32_t nvec = S_v / epv; const uint32_t nloe = S_v % epv; - HVX_Vector vq[4]; - HVX_Vector vk[4]; - HVX_Vector vg[4]; + HVX_Vector * restrict vq = vtcm_scratch + 0; + HVX_Vector * restrict vk = vtcm_scratch + 4; + HVX_Vector * restrict vg = vtcm_scratch + 8; + float * restrict v_buf = (float *) (vtcm_scratch + 12); + float * restrict out_buf = (float *) (vtcm_scratch + 16); + + gctx->load_q(vq, q_t, S_v); + gctx->load_k(vk, k_t, S_v); + gctx->load_v((HVX_Vector *) v_buf, v_t, S_v); for (uint32_t i = 0; i < nvec; ++i) { - vq[i] = hvx_vmemu(q_t + i * epv); - vk[i] = hvx_vmemu(k_t + i * epv); - vg[i] = hvx_vec_exp_f32(hvx_vmemu(g_t + i * epv)); + vg[i] = gdn_vec_exp_f32(hvx_vmemu(g_t + i * epv)); } if (nloe) { - vq[nvec] = hvx_vmemu(q_t + nvec * epv); - vk[nvec] = hvx_vmemu(k_t + nvec * epv); - vg[nvec] = hvx_vec_exp_f32(hvx_vmemu(g_t + nvec * epv)); + vg[nvec] = gdn_vec_exp_f32(hvx_vec_load_u(g_t + nvec * epv, nloe * sizeof(float))); } - const HVX_Vector vbeta = hvx_vec_splat_f32(beta_val); + const HVX_Vector vbeta = hvx_vec_repl_f32(hvx_vmemu(beta_t)); const HVX_Vector vscale = hvx_vec_splat_f32(scale); - float delta[8] __attribute__((aligned(128))); - uint32_t j = 0; for (; j + 8 <= S_v; j += 8) { - float * row0 = s_work + (uint64_t) (j + 0) * S_v; - float * row1 = s_work + (uint64_t) (j + 1) * S_v; - float * row2 = s_work + (uint64_t) (j + 2) * S_v; - float * row3 = s_work + (uint64_t) (j + 3) * S_v; - float * row4 = s_work + (uint64_t) (j + 4) * S_v; - float * row5 = s_work + (uint64_t) (j + 5) * S_v; - float * row6 = s_work + (uint64_t) (j + 6) * S_v; - float * row7 = s_work + (uint64_t) (j + 7) * S_v; + float * row0 = s_work + (j + 0) * S_v; + float * row1 = s_work + (j + 1) * S_v; + float * row2 = s_work + (j + 2) * S_v; + float * row3 = s_work + (j + 3) * S_v; + float * row4 = s_work + (j + 4) * S_v; + float * row5 = s_work + (j + 5) * S_v; + float * row6 = s_work + (j + 6) * S_v; + float * row7 = s_work + (j + 7) * S_v; HVX_Vector vsums = gdn_mul_dot8_f32(row0, row1, row2, row3, row4, row5, row6, row7, vg, vk, S_v); - HVX_Vector vv_t = hvx_vmemu(v_t + j); + HVX_Vector vv_t = hvx_vmemu(v_buf + j); HVX_Vector diff = hvx_vec_sub_f32_f32(vv_t, vsums); HVX_Vector vdelta = hvx_vec_mul_f32_f32(diff, vbeta); - hvx_vec_store_u(delta, 8 * sizeof(float), vdelta); HVX_Vector vattn = gdn_add_scaled_dot8_f32(row0, row1, row2, row3, row4, row5, row6, row7, - vk, delta, vq, S_v); + vk, vdelta, vq, S_v); HVX_Vector res_attn = hvx_vec_mul_f32_f32(vattn, vscale); - hvx_vec_store_u(attn_out + j, 8 * sizeof(float), res_attn); + hvx_vec_store_u(out_buf + j, 8 * sizeof(float), res_attn); } for (; j + 4 <= S_v; j += 4) { - float * row0 = s_work + (uint64_t) (j + 0) * S_v; - float * row1 = s_work + (uint64_t) (j + 1) * S_v; - float * row2 = s_work + (uint64_t) (j + 2) * S_v; - float * row3 = s_work + (uint64_t) (j + 3) * S_v; + float * row0 = s_work + (j + 0) * S_v; + float * row1 = s_work + (j + 1) * S_v; + float * row2 = s_work + (j + 2) * S_v; + float * row3 = s_work + (j + 3) * S_v; HVX_Vector vsums = gdn_mul_dot4_f32(row0, row1, row2, row3, vg, vk, S_v); - HVX_Vector vv_t = hvx_vmemu(v_t + j); + HVX_Vector vv_t = hvx_vmemu(v_buf + j); HVX_Vector diff = hvx_vec_sub_f32_f32(vv_t, vsums); HVX_Vector vdelta = hvx_vec_mul_f32_f32(diff, vbeta); - hvx_vec_store_u(delta, 4 * sizeof(float), vdelta); - HVX_Vector vattn = gdn_add_scaled_dot4_f32(row0, row1, row2, row3, vk, delta, vq, S_v); + HVX_Vector vattn = gdn_add_scaled_dot4_f32(row0, row1, row2, row3, vk, vdelta, vq, S_v); HVX_Vector res_attn = hvx_vec_mul_f32_f32(vattn, vscale); - hvx_vec_store_u(attn_out + j, 4 * sizeof(float), res_attn); + hvx_vec_store_u(out_buf + j, 4 * sizeof(float), res_attn); } for (; j < S_v; ++j) { - float * row = s_work + (uint64_t) j * S_v; + float * row = s_work + j * S_v; HVX_Vector vsum = gdn_mul_dot_f32(row, vg, vk, S_v); - HVX_Vector vv_t = hvx_vec_splat_f32(v_t[j]); + HVX_Vector vv_t = hvx_vec_repl_f32(hvx_vmemu(v_buf + j)); HVX_Vector vdj = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, vsum), vbeta); HVX_Vector vres = gdn_add_scaled_dot_f32(row, vk, vdj, vq, S_v); - attn_out[j] = hvx_vec_get_f32(hvx_vec_mul_f32_f32(vres, vscale)); + hvx_vec_store_u(out_buf + j, sizeof(float), hvx_vec_mul_f32_f32(vres, vscale)); } + + gctx->store_out(attn_out, (const HVX_Vector *) out_buf, S_v); } static __attribute__((noinline)) void gdn_step_scalar_f32( + const struct htp_gdn_context * gctx, float * restrict s_work, - float * restrict attn_out, - const float * restrict q_t, - const float * restrict k_t, - const float * restrict v_t, + void * restrict attn_out, + const void * restrict q_t, + const void * restrict k_t, + const void * restrict v_t, const float * restrict g_t, - float beta_val, + const float * restrict beta_t, + HVX_Vector * restrict vtcm_scratch, float scale, - uint32_t S_v + uint32_t S_v, + const void * restrict k_next, + bool has_memory ) { - const uint32_t epv = 128 / sizeof(float); - const uint32_t nvec = S_v / epv; - const uint32_t nloe = S_v % epv; - - HVX_Vector vq[4]; - HVX_Vector vk[4]; + HVX_Vector * restrict vq = vtcm_scratch + 0; + HVX_Vector * restrict vk = vtcm_scratch + 4; + HVX_Vector * restrict vk_next = vtcm_scratch + 8; + float * restrict v_buf = (float *) (vtcm_scratch + 12); + float * restrict out_buf = (float *) (vtcm_scratch + 16); + float * restrict mem_buf = (float *) (vtcm_scratch + 20); + + gctx->load_q(vq, q_t, S_v); + gctx->load_k(vk, k_t, S_v); + gctx->load_v((HVX_Vector *) v_buf, v_t, S_v); + + const HVX_Vector vgate = gdn_vec_exp_f32(hvx_vec_repl_f32(hvx_vmemu(g_t))); + const HVX_Vector vbeta = hvx_vec_repl_f32(hvx_vmemu(beta_t)); + const HVX_Vector vscale = hvx_vec_splat_f32(scale); - for (uint32_t i = 0; i < nvec; ++i) { - vq[i] = hvx_vmemu(q_t + i * epv); - vk[i] = hvx_vmemu(k_t + i * epv); + if (!has_memory) { + if (!k_next) { + uint32_t j = 0; + for (; j + 8 <= S_v; j += 8) { + float * row0 = s_work + (j + 0) * S_v; + float * row1 = s_work + (j + 1) * S_v; + float * row2 = s_work + (j + 2) * S_v; + float * row3 = s_work + (j + 3) * S_v; + float * row4 = s_work + (j + 4) * S_v; + float * row5 = s_work + (j + 5) * S_v; + float * row6 = s_work + (j + 6) * S_v; + float * row7 = s_work + (j + 7) * S_v; + + HVX_Vector vmem = gdn_dot8_f32(row0, row1, row2, row3, row4, row5, row6, row7, vk, S_v); + HVX_Vector vv_t = hvx_vmemu(v_buf + j); + HVX_Vector vdelta = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, hvx_vec_mul_f32_f32(vmem, vgate)), vbeta); + + HVX_Vector vattn0 = gdn_scale_add_dot4_f32(row0, row1, row2, row3, vgate, vk, vdelta, vq, S_v); + HVX_Vector vattn1 = gdn_scale_add_dot4_f32(row4, row5, row6, row7, vgate, vk, + Q6_V_vror_VR(vdelta, 4 * sizeof(float)), vq, S_v); + hvx_vec_store_u(out_buf + j + 0, 4 * sizeof(float), hvx_vec_mul_f32_f32(vattn0, vscale)); + hvx_vec_store_u(out_buf + j + 4, 4 * sizeof(float), hvx_vec_mul_f32_f32(vattn1, vscale)); + } + for (; j + 4 <= S_v; j += 4) { + float * row0 = s_work + (j + 0) * S_v; + float * row1 = s_work + (j + 1) * S_v; + float * row2 = s_work + (j + 2) * S_v; + float * row3 = s_work + (j + 3) * S_v; + + HVX_Vector vmem = gdn_dot4_f32(row0, row1, row2, row3, vk, S_v); + HVX_Vector vv_t = hvx_vmemu(v_buf + j); + HVX_Vector vdelta = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, hvx_vec_mul_f32_f32(vmem, vgate)), vbeta); + + HVX_Vector vattn = gdn_scale_add_dot4_f32(row0, row1, row2, row3, vgate, vk, vdelta, vq, S_v); + hvx_vec_store_u(out_buf + j, 4 * sizeof(float), hvx_vec_mul_f32_f32(vattn, vscale)); + } + for (; j < S_v; ++j) { + float * row = s_work + j * S_v; + HVX_Vector vmem = gdn_dot_f32(row, vk, S_v); + HVX_Vector vv_t = hvx_vec_repl_f32(hvx_vmemu(v_buf + j)); + HVX_Vector vdj = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, hvx_vec_mul_f32_f32(vmem, vgate)), vbeta); + HVX_Vector vres = gdn_scale_add_dot_f32(row, vgate, vk, vdj, vq, S_v); + hvx_vec_store_u(out_buf + j, sizeof(float), hvx_vec_mul_f32_f32(vres, vscale)); + } + gctx->store_out(attn_out, (const HVX_Vector *) out_buf, S_v); + return; + } + + // Token 0 of multi-token tile: read-only Pass 1 to seed mem_buf + uint32_t j = 0; + for (; j + 8 <= S_v; j += 8) { + float * row0 = s_work + (j + 0) * S_v; + float * row1 = s_work + (j + 1) * S_v; + float * row2 = s_work + (j + 2) * S_v; + float * row3 = s_work + (j + 3) * S_v; + float * row4 = s_work + (j + 4) * S_v; + float * row5 = s_work + (j + 5) * S_v; + float * row6 = s_work + (j + 6) * S_v; + float * row7 = s_work + (j + 7) * S_v; + + HVX_Vector vmem = gdn_dot8_f32(row0, row1, row2, row3, row4, row5, row6, row7, vk, S_v); + hvx_vec_store_u(mem_buf + j, 8 * sizeof(float), vmem); + } + for (; j + 4 <= S_v; j += 4) { + float * row0 = s_work + (j + 0) * S_v; + float * row1 = s_work + (j + 1) * S_v; + float * row2 = s_work + (j + 2) * S_v; + float * row3 = s_work + (j + 3) * S_v; + + HVX_Vector vmem = gdn_dot4_f32(row0, row1, row2, row3, vk, S_v); + hvx_vec_store_u(mem_buf + j, 4 * sizeof(float), vmem); + } + for (; j < S_v; ++j) { + HVX_Vector vmem = gdn_dot_f32(s_work + j * S_v, vk, S_v); + hvx_vec_store_u(mem_buf + j, sizeof(float), vmem); + } } - if (nloe) { - vq[nvec] = hvx_vmemu(q_t + nvec * epv); - vk[nvec] = hvx_vmemu(k_t + nvec * epv); + + if (k_next) { + gctx->load_k(vk_next, k_next, S_v); + + uint32_t j = 0; + for (; j + 4 <= S_v; j += 4) { + float * row0 = s_work + (j + 0) * S_v; + float * row1 = s_work + (j + 1) * S_v; + float * row2 = s_work + (j + 2) * S_v; + float * row3 = s_work + (j + 3) * S_v; + + HVX_Vector vmem = hvx_vmemu(mem_buf + j); + HVX_Vector vv_t = hvx_vmemu(v_buf + j); + HVX_Vector vdelta = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, hvx_vec_mul_f32_f32(vmem, vgate)), vbeta); + + HVX_VectorPair vp = gdn_scale_add_dual_dot4_f32(row0, row1, row2, row3, + vgate, vk, vdelta, vq, vk_next, S_v); + hvx_vec_store_u(out_buf + j, 4 * sizeof(float), hvx_vec_mul_f32_f32(Q6_V_lo_W(vp), vscale)); + hvx_vec_store_u(mem_buf + j, 4 * sizeof(float), Q6_V_hi_W(vp)); + } + for (; j < S_v; ++j) { + float * row = s_work + j * S_v; + HVX_Vector vmem = hvx_vec_repl_f32(hvx_vmemu(mem_buf + j)); + HVX_Vector vv_t = hvx_vec_repl_f32(hvx_vmemu(v_buf + j)); + HVX_Vector vdj = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, hvx_vec_mul_f32_f32(vmem, vgate)), vbeta); + HVX_VectorPair vp = gdn_scale_add_dual_dot_f32(row, vgate, vk, vdj, vq, vk_next, S_v); + hvx_vec_store_u(out_buf + j, sizeof(float), hvx_vec_mul_f32_f32(Q6_V_lo_W(vp), vscale)); + hvx_vec_store_u(mem_buf + j, sizeof(float), Q6_V_hi_W(vp)); + } + } else { + uint32_t j = 0; + for (; j + 4 <= S_v; j += 4) { + float * row0 = s_work + (j + 0) * S_v; + float * row1 = s_work + (j + 1) * S_v; + float * row2 = s_work + (j + 2) * S_v; + float * row3 = s_work + (j + 3) * S_v; + + HVX_Vector vmem = hvx_vmemu(mem_buf + j); + HVX_Vector vv_t = hvx_vmemu(v_buf + j); + HVX_Vector vdelta = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, hvx_vec_mul_f32_f32(vmem, vgate)), vbeta); + + HVX_Vector vattn = gdn_scale_add_dot4_f32(row0, row1, row2, row3, vgate, vk, vdelta, vq, S_v); + hvx_vec_store_u(out_buf + j, 4 * sizeof(float), hvx_vec_mul_f32_f32(vattn, vscale)); + } + for (; j < S_v; ++j) { + float * row = s_work + j * S_v; + HVX_Vector vmem = hvx_vec_repl_f32(hvx_vmemu(mem_buf + j)); + HVX_Vector vv_t = hvx_vec_repl_f32(hvx_vmemu(v_buf + j)); + HVX_Vector vdj = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, hvx_vec_mul_f32_f32(vmem, vgate)), vbeta); + HVX_Vector vres = gdn_scale_add_dot_f32(row, vgate, vk, vdj, vq, S_v); + hvx_vec_store_u(out_buf + j, sizeof(float), hvx_vec_mul_f32_f32(vres, vscale)); + } } - const HVX_Vector vgate = hvx_vec_exp_f32(hvx_vec_splat_f32(g_t[0])); - const HVX_Vector vbeta = hvx_vec_splat_f32(beta_val); - const HVX_Vector vscale = hvx_vec_splat_f32(scale); + gctx->store_out(attn_out, (const HVX_Vector *) out_buf, S_v); +} - float delta[8] __attribute__((aligned(128))); +static inline uint32_t gdn_read_seq_idx(const void * ids_data, uint32_t ids_type, uint32_t iv3) { + if (!ids_data) { + return iv3; + } + return (ids_type == HTP_TYPE_I64) + ? (uint32_t) (((const int64_t *) ids_data)[iv3]) + : (uint32_t) (((const int32_t *) ids_data)[iv3]); +} + +static inline bool gdn_has_replay(const struct htp_ops_context * octx) { + return octx->src[6] != NULL && octx->src[7] != NULL; +} + +static inline int gdn_prepare_aux_data( + struct htp_ops_context * octx, + const struct htp_tensor * t, + void ** out_buf +) { + if (!t) { + *out_buf = NULL; + return HTP_STATUS_OK; + } + const size_t nbytes = hex_round_up(htp_tensor_nbytes(t), 128); + void * buf = (nbytes <= octx->ctx->ddr_spad_size) ? octx->ctx->ddr_spad_base : memalign(128, nbytes); + if (!buf) { + return HTP_STATUS_INTERNAL_ERR; + } + if (htp_tensor_read(&octx->ctx->main_th, buf, nbytes, t) == 0) { + if (buf != octx->ctx->ddr_spad_base) { + free(buf); + } + return HTP_STATUS_INTERNAL_ERR; + } + *out_buf = buf; + return HTP_STATUS_OK; +} + +static inline void gdn_dma_push_tile_inputs( + dma_queue * dma_q, + void * vtcm_q, + void * vtcm_k, + void * vtcm_v, + void * vtcm_g, + void * vtcm_b, + const struct htp_tensor * q, + const struct htp_tensor * k, + const struct htp_tensor * v, + const struct htp_tensor * g, + const struct htp_tensor * beta, + uint32_t iq3, uint32_t iq1, + uint32_t ik3, uint32_t ik1, + uint32_t iv3, uint32_t iv1, + uint32_t t_base, + uint32_t tile_tokens, + uint32_t q_row_bytes, + uint32_t k_row_bytes, + uint32_t v_row_bytes, + uint32_t g_row_bytes +) { + const dma_addr_t q_dma = q->data + ((size_t) iq3 * q->nb[3] + (size_t) t_base * q->nb[2] + (size_t) iq1 * q->nb[1]); + const dma_addr_t k_dma = k->data + ((size_t) ik3 * k->nb[3] + (size_t) t_base * k->nb[2] + (size_t) ik1 * k->nb[1]); + const dma_addr_t v_dma = v->data + ((size_t) iv3 * v->nb[3] + (size_t) t_base * v->nb[2] + (size_t) iv1 * v->nb[1]); + const dma_addr_t g_dma = g->data + ((size_t) iv3 * g->nb[3] + (size_t) t_base * g->nb[2] + (size_t) iv1 * g->nb[1]); + const dma_addr_t b_dma = beta->data + ((size_t) iv3 * beta->nb[3] + (size_t) t_base * beta->nb[2] + (size_t) iv1 * beta->nb[1]); + + dma_queue_push(dma_q, dma_make_data(vtcm_q, q_dma), q_row_bytes, q->nb[2], q_row_bytes, tile_tokens); + dma_queue_push(dma_q, dma_make_data(vtcm_k, k_dma), k_row_bytes, k->nb[2], k_row_bytes, tile_tokens); + dma_queue_push(dma_q, dma_make_data(vtcm_v, v_dma), v_row_bytes, v->nb[2], v_row_bytes, tile_tokens); + dma_queue_push(dma_q, dma_make_data(vtcm_g, g_dma), g_row_bytes, g->nb[2], g_row_bytes, tile_tokens); + dma_queue_push(dma_q, dma_make_data(vtcm_b, b_dma), sizeof(float), beta->nb[2], sizeof(float), tile_tokens); +} + +static __attribute__((noinline)) void gdn_replay_step_f32( + float * restrict s_work, + const float * restrict k_t, + const float * restrict v_t, + const float * restrict g_t, + const float * restrict beta_t, + HVX_Vector * restrict vtcm_scratch, + bool kda, + uint32_t S_v +) { + const uint32_t epv = 128 / sizeof(float); + const uint32_t nvec = S_v / epv; + const uint32_t nloe = S_v % epv; + + HVX_Vector * restrict vk = vtcm_scratch + 0; + HVX_Vector * restrict vg = vtcm_scratch + 4; + float * restrict v_buf = (float *) (vtcm_scratch + 8); + + gdn_load_vec_f32(vk, k_t, S_v); + gdn_load_vec_f32((HVX_Vector *) v_buf, v_t, S_v); + + HVX_Vector vgate = Q6_V_vzero(); + if (kda) { + for (uint32_t i = 0; i < nvec; ++i) { + vg[i] = gdn_vec_exp_f32(hvx_vmemu(g_t + i * epv)); + } + if (nloe) { + vg[nvec] = gdn_vec_exp_f32(hvx_vec_load_u(g_t + nvec * epv, nloe * sizeof(float))); + } + } else { + vgate = gdn_vec_exp_f32(hvx_vec_repl_f32(hvx_vmemu(g_t))); + } + + const HVX_Vector vbeta = hvx_vec_repl_f32(hvx_vmemu(beta_t)); uint32_t j = 0; for (; j + 8 <= S_v; j += 8) { - float * row0 = s_work + (uint64_t) (j + 0) * S_v; - float * row1 = s_work + (uint64_t) (j + 1) * S_v; - float * row2 = s_work + (uint64_t) (j + 2) * S_v; - float * row3 = s_work + (uint64_t) (j + 3) * S_v; - float * row4 = s_work + (uint64_t) (j + 4) * S_v; - float * row5 = s_work + (uint64_t) (j + 5) * S_v; - float * row6 = s_work + (uint64_t) (j + 6) * S_v; - float * row7 = s_work + (uint64_t) (j + 7) * S_v; - - HVX_Vector vsums = gdn_mul_scalar_dot8_f32(row0, row1, row2, row3, row4, row5, row6, row7, - vgate, vk, S_v); - - HVX_Vector vv_t = hvx_vmemu(v_t + j); - HVX_Vector diff = hvx_vec_sub_f32_f32(vv_t, vsums); - HVX_Vector vdelta = hvx_vec_mul_f32_f32(diff, vbeta); - hvx_vec_store_u(delta, 8 * sizeof(float), vdelta); + float * row0 = s_work + (j + 0) * S_v; + float * row1 = s_work + (j + 1) * S_v; + float * row2 = s_work + (j + 2) * S_v; + float * row3 = s_work + (j + 3) * S_v; + float * row4 = s_work + (j + 4) * S_v; + float * row5 = s_work + (j + 5) * S_v; + float * row6 = s_work + (j + 6) * S_v; + float * row7 = s_work + (j + 7) * S_v; - HVX_Vector vattn = gdn_add_scaled_dot8_f32(row0, row1, row2, row3, row4, row5, row6, row7, - vk, delta, vq, S_v); + HVX_Vector vsums = kda + ? gdn_mul_dot8_f32(row0, row1, row2, row3, row4, row5, row6, row7, vg, vk, S_v) + : gdn_mul_scalar_dot8_f32(row0, row1, row2, row3, row4, row5, row6, row7, vgate, vk, S_v); - HVX_Vector res_attn = hvx_vec_mul_f32_f32(vattn, vscale); - hvx_vec_store_u(attn_out + j, 8 * sizeof(float), res_attn); + HVX_Vector vv_t = hvx_vmemu(v_buf + j); + HVX_Vector vdelta = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, vsums), vbeta); + + gdn_add_scaled8_f32(row0, row1, row2, row3, row4, row5, row6, row7, vk, vdelta, S_v); } for (; j + 4 <= S_v; j += 4) { - float * row0 = s_work + (uint64_t) (j + 0) * S_v; - float * row1 = s_work + (uint64_t) (j + 1) * S_v; - float * row2 = s_work + (uint64_t) (j + 2) * S_v; - float * row3 = s_work + (uint64_t) (j + 3) * S_v; + float * row0 = s_work + (j + 0) * S_v; + float * row1 = s_work + (j + 1) * S_v; + float * row2 = s_work + (j + 2) * S_v; + float * row3 = s_work + (j + 3) * S_v; - HVX_Vector vsums = gdn_mul_scalar_dot4_f32(row0, row1, row2, row3, vgate, vk, S_v); + HVX_Vector vsums = kda + ? gdn_mul_dot4_f32(row0, row1, row2, row3, vg, vk, S_v) + : gdn_mul_scalar_dot4_f32(row0, row1, row2, row3, vgate, vk, S_v); - HVX_Vector vv_t = hvx_vmemu(v_t + j); - HVX_Vector diff = hvx_vec_sub_f32_f32(vv_t, vsums); - HVX_Vector vdelta = hvx_vec_mul_f32_f32(diff, vbeta); - hvx_vec_store_u(delta, 4 * sizeof(float), vdelta); - - HVX_Vector vattn = gdn_add_scaled_dot4_f32(row0, row1, row2, row3, vk, delta, vq, S_v); + HVX_Vector vv_t = hvx_vmemu(v_buf + j); + HVX_Vector vdelta = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, vsums), vbeta); - HVX_Vector res_attn = hvx_vec_mul_f32_f32(vattn, vscale); - hvx_vec_store_u(attn_out + j, 4 * sizeof(float), res_attn); + gdn_add_scaled4_f32(row0, row1, row2, row3, vk, vdelta, S_v); } for (; j < S_v; ++j) { - float * row = s_work + (uint64_t) j * S_v; - HVX_Vector vsum = gdn_mul_scalar_dot_f32(row, vgate, vk, S_v); - HVX_Vector vv_t = hvx_vec_splat_f32(v_t[j]); + float * row = s_work + j * S_v; + HVX_Vector vsum = kda + ? gdn_mul_dot_f32(row, vg, vk, S_v) + : gdn_mul_scalar_dot_f32(row, vgate, vk, S_v); + HVX_Vector vv_t = hvx_vec_repl_f32(hvx_vmemu(v_buf + j)); HVX_Vector vdj = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv_t, vsum), vbeta); - HVX_Vector vres = gdn_add_scaled_dot_f32(row, vk, vdj, vq, S_v); - attn_out[j] = hvx_vec_get_f32(hvx_vec_mul_f32_f32(vres, vscale)); + gdn_add_scaled_f32(row, vk, vdj, S_v); } } -static inline void gdn_replay_f32( +static void gdn_replay_f32( const struct htp_ops_context * octx, + dma_queue * dma_q, float * restrict s_work, + float * restrict k_buf, + float * restrict v_buf, + float * restrict g_buf, + float * restrict b_buf, + HVX_Vector * restrict vtcm_scratch, + uint32_t tile_cap, uint32_t ik1, uint32_t iv1, uint32_t iv3, + uint32_t n_steps, + uint32_t n_pend, 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 vec_bytes = S_v * sizeof(float); + const uint32_t g_elems = kda ? S_v : 1; + const uint32_t g_bytes = g_elems * sizeof(float); - 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 dma_addr_t pk_base = pend_k->data + (size_t) iv3 * pend_k->nb[3] + (size_t) ik1 * pend_k->nb[1]; + const dma_addr_t pv_base = pend_v->data + (size_t) iv3 * pend_v->nb[3] + (size_t) iv1 * pend_v->nb[1]; + const dma_addr_t pgb_base = pend_gb->data + (size_t) iv3 * pend_gb->nb[3] + (size_t) iv1 * pend_gb->nb[1]; - 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_base = 0; t_base < n_steps; t_base += tile_cap) { + const uint32_t tile_tokens = hex_smin(tile_cap, n_steps - t_base); - 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]); + const dma_addr_t pk_dma = pk_base + (size_t) t_base * pend_k->nb[2]; + const dma_addr_t pv_dma = pv_base + (size_t) t_base * pend_v->nb[2]; + const dma_addr_t pg_dma = pgb_base + (size_t) t_base * pend_gb->nb[2]; + const dma_addr_t pb_dma = pgb_base + (size_t) (n_pend + t_base) * 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); + dma_queue_push(dma_q, dma_make_data(k_buf, pk_dma), vec_bytes, pend_k->nb[2], vec_bytes, tile_tokens); + dma_queue_push(dma_q, dma_make_data(v_buf, pv_dma), vec_bytes, pend_v->nb[2], vec_bytes, tile_tokens); + dma_queue_push(dma_q, dma_make_data(g_buf, pg_dma), g_bytes, pend_gb->nb[2], g_bytes, tile_tokens); + dma_queue_push(dma_q, dma_make_data(b_buf, pb_dma), sizeof(float), pend_gb->nb[2], sizeof(float), tile_tokens); + for (int d = 0; d < 4; ++d) { + dma_queue_pop(dma_q); + } + + for (uint32_t t_local = 0; t_local < tile_tokens; ++t_local) { + gdn_replay_step_f32( + s_work, + k_buf + (size_t) t_local * S_v, + v_buf + (size_t) t_local * S_v, + g_buf + (size_t) t_local * g_elems, + b_buf + t_local, + vtcm_scratch, kda, S_v); } } } @@ -816,14 +1560,35 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int const struct htp_tensor * dst_cache = octx->dsts[1]; const float scale = kparams->scale; - float * dst_base = (float *) (uintptr_t) dst->data; - float * state_out_base = dst_cache ? (float *) (uintptr_t) dst_cache->data : (dst_base + S_v * H * n_tokens * n_seqs); + + const uint32_t q_row_bytes = S_v * ((q->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float)); + const uint32_t k_row_bytes = S_v * ((k->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float)); + const uint32_t v_row_bytes = S_v * ((v->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float)); + const uint32_t g_row_bytes = (kparams->kda ? S_v : 1) * sizeof(float); + const uint32_t out_row_bytes = S_v * ((dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float)); + const uint32_t dst_row_stride = H * out_row_bytes; dma_queue * dma_q = th->dma_q; const struct htp_gdn_vtcm_layout * layout = &gctx->layout; - float * s_work[2]; - s_work[0] = (float *) (gctx->vtcm_base + layout->bytes_per_hvx * ith); - s_work[1] = s_work[0] + layout->state_aligned / sizeof(float); + uint8_t * th_vtcm = gctx->vtcm_base + layout->bytes_per_hvx * ith; + float * s_work_curr = (float *) th_vtcm; + HVX_Vector * vtcm_scratch = (HVX_Vector *) (th_vtcm + layout->off_scratch); + + uint8_t * q_spad[2]; + uint8_t * k_spad[2]; + uint8_t * v_spad[2]; + uint8_t * g_spad[2]; + uint8_t * o_spad[2]; + float * beta_spad[2]; + for (int b = 0; b < 2; ++b) { + uint8_t * spad = th_vtcm + layout->off_spad + (size_t) b * layout->spad_stride; + q_spad[b] = spad + 0 * layout->tile_vec_bytes; + k_spad[b] = spad + 1 * layout->tile_vec_bytes; + v_spad[b] = spad + 2 * layout->tile_vec_bytes; + g_spad[b] = spad + 3 * layout->tile_vec_bytes; + o_spad[b] = spad + 4 * layout->tile_vec_bytes; + beta_spad[b] = (float *) (spad + 5 * layout->tile_vec_bytes); + } const struct fastdiv_values * fd_H = &kparams->div_H; const struct fastdiv_values * fd_q1 = &kparams->div_q1; @@ -831,44 +1596,17 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int const struct fastdiv_values * fd_rq3 = &kparams->div_rq3; const struct fastdiv_values * fd_rk3 = &kparams->div_rk3; - 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; - - // Prefetch preamble (up to 2 steps) - for (int step = 0; step < 2 && ir_prefetch < row_end; step++) { - const uint32_t piv1 = fastmodulo(ir_prefetch, H, fd_H); - const uint32_t piv3 = fastdiv(ir_prefetch, fd_H); - dma_addr_t ps_in = state->data + ((uint64_t) piv3 * state_seq_stride + (uint64_t) piv1 * S_v * S_v) * sizeof(float); - dma_addr_t ps_out = state_out_dma_base + ((uint64_t) piv3 * H + piv1) * S_v * S_v * sizeof(float); - - // Push dummy write-back - dma_queue_push(dma_q, dma_make_data(ps_out, s_work[spad_idx]), - S_v * sizeof(float), S_v * sizeof(float), - S_v * sizeof(float), 0); - - // Push fetch - dma_queue_push(dma_q, dma_make_data(s_work[spad_idx], ps_in), - S_v * sizeof(float), S_v * sizeof(float), - S_v * sizeof(float), S_v); - - ir_prefetch += nth; - spad_idx ^= 1; - } + const uint32_t state_seq_stride = kparams->state_seq_stride; + const uint32_t state_size_per_snap = kparams->state_size_per_snap; + const dma_addr_t state_out_dma_base = dst_cache ? dst_cache->data : (dst->data + (size_t) S_v * H * n_tokens * n_seqs * sizeof(float)); + const bool replay = gctx->replay; + const bool keep = gctx->keep; struct htp_thread_trace * tr = th->trace; + const gdn_step_fn_t step_fn = gctx->step_fn; + const uint32_t n_tiles = (n_tokens + HTP_GDN_TOKEN_TILE - 1) / HTP_GDN_TOKEN_TILE; - int curr_spad_idx = 0; for (uint32_t ir = gctx->row_start + ith; ir < row_end; ir += nth) { - dma_queue_pop(dma_q); - dma_queue_pop(dma_q); - - float * s_work_curr = s_work[curr_spad_idx]; - const uint32_t iv1 = fastmodulo(ir, H, fd_H); const uint32_t iv3 = fastdiv(ir, fd_H); @@ -876,64 +1614,118 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int const uint32_t ik1 = fastmodulo(iv1, k->ne[1], fd_k1); const uint32_t iq3 = fastdiv(iv3, fd_rq3); const uint32_t ik3 = fastdiv(iv3, fd_rk3); + const uint32_t is3 = gdn_read_seq_idx(gctx->ids_data, gctx->ids_type, iv3); - dma_addr_t s_out = state_out_dma_base + ((uint64_t) iv3 * H + iv1) * S_v * S_v * sizeof(float); - float * attn_data = dst_base + ((uint64_t) iv3 * n_tokens * H + iv1) * S_v; + const dma_addr_t s_in = state->data + ((size_t) is3 * state_seq_stride + (size_t) iv1 * S_v * S_v) * sizeof(float); + const dma_addr_t s_out = state_out_dma_base + ((size_t) iv3 * H + iv1) * S_v * S_v * sizeof(float); - 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); + dma_queue_push(dma_q, dma_make_data(s_work_curr, s_in), + S_v * sizeof(float), S_v * sizeof(float), + S_v * sizeof(float), S_v); + dma_queue_pop(dma_q); + + if (replay) { + const int32_t raw_n_rep = gctx->n_rep_data[iv3]; + const uint32_t n_steps = raw_n_rep <= 0 ? 0 : hex_smin((uint32_t) raw_n_rep, gctx->n_pend); + if (n_steps > 0) { + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); + gdn_replay_f32(octx, dma_q, s_work_curr, + (float *) k_spad[0], (float *) v_spad[0], (float *) g_spad[0], beta_spad[0], + vtcm_scratch, HTP_GDN_TOKEN_TILE, + ik1, iv1, iv3, n_steps, gctx->n_pend, + kparams->kda != 0, S_v); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); + } + if (keep) { + 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); + dma_queue_pop(dma_q); + } } - 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]); - const float * k_t = (const float *) ((const uint8_t *) (uintptr_t) k->data + - (uint64_t) ik3 * k->nb[3] + (uint64_t) t * k->nb[2] + (uint64_t) ik1 * k->nb[1]); - const float * v_t = (const float *) ((const uint8_t *) (uintptr_t) v->data + - (uint64_t) iv3 * v->nb[3] + (uint64_t) t * v->nb[2] + (uint64_t) iv1 * v->nb[1]); - const float * g_t = (const float *) ((const uint8_t *) (uintptr_t) g->data + - (uint64_t) iv3 * g->nb[3] + (uint64_t) t * g->nb[2] + (uint64_t) iv1 * g->nb[1]); - const float beta_val = *(const float *) ((const uint8_t *) (uintptr_t) beta->data + - (uint64_t) iv3 * beta->nb[3] + (uint64_t) t * beta->nb[2] + (uint64_t) iv1 * beta->nb[1]); - - 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 { - gdn_step_scalar_f32(s_work_curr, attn_data, q_t, k_t, v_t, g_t, beta_val, scale, S_v); + + const uint32_t first_tokens = hex_smin(HTP_GDN_TOKEN_TILE, n_tokens); + gdn_dma_push_tile_inputs(dma_q, q_spad[0], k_spad[0], v_spad[0], g_spad[0], beta_spad[0], + q, k, v, g, beta, iq3, iq1, ik3, ik1, iv3, iv1, + 0, first_tokens, q_row_bytes, k_row_bytes, v_row_bytes, g_row_bytes); + + for (uint32_t tile_idx = 0; tile_idx < n_tiles; ++tile_idx) { + const uint32_t curr_buf = tile_idx & 1; + const uint32_t next_buf = curr_buf ^ 1; + const uint32_t t_base = tile_idx * HTP_GDN_TOKEN_TILE; + const uint32_t tile_tokens = hex_smin(HTP_GDN_TOKEN_TILE, n_tokens - t_base); + + for (int d = 0; d < 5; ++d) { + dma_queue_pop(dma_q); + } + if (tile_idx > 0) { + dma_queue_pop(dma_q); + } + + if (K <= 1 && tile_idx + 1 < n_tiles) { + const uint32_t next_t_base = (tile_idx + 1) * HTP_GDN_TOKEN_TILE; + const uint32_t next_tokens = hex_smin(HTP_GDN_TOKEN_TILE, n_tokens - next_t_base); + gdn_dma_push_tile_inputs(dma_q, q_spad[next_buf], k_spad[next_buf], v_spad[next_buf], g_spad[next_buf], beta_spad[next_buf], + q, k, v, g, beta, iq3, iq1, ik3, ik1, iv3, iv1, + next_t_base, next_tokens, q_row_bytes, k_row_bytes, v_row_bytes, g_row_bytes); } - if (K > 1) { - const int64_t target_slot = (int64_t) n_tokens - 1 - (int64_t) t; - if (target_slot > 0 && target_slot < (int64_t) K) { - float * curr_state_o = state_out_base + (uint64_t) target_slot * state_size_per_snap + ((uint64_t) iv3 * H + iv1) * S_v * S_v; - hvx_copy_f32_uu((uint8_t *) curr_state_o, (const uint8_t *) s_work_curr, S_v * S_v); + const uint8_t * q_curr = q_spad[curr_buf]; + const uint8_t * k_curr = k_spad[curr_buf]; + const uint8_t * v_curr = v_spad[curr_buf]; + const uint8_t * g_curr = g_spad[curr_buf]; + const float * b_curr = beta_spad[curr_buf]; + uint8_t * o_curr = o_spad[curr_buf]; + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); + for (uint32_t t_local = 0; t_local < tile_tokens; ++t_local) { + const void * k_next = (t_local + 1 < tile_tokens) ? (k_curr + (t_local + 1) * k_row_bytes) : NULL; + step_fn(gctx, s_work_curr, + o_curr + t_local * out_row_bytes, + q_curr + t_local * q_row_bytes, + k_curr + t_local * k_row_bytes, + v_curr + t_local * v_row_bytes, + (const float *) (g_curr + t_local * g_row_bytes), + b_curr + t_local, + vtcm_scratch, scale, S_v, k_next, t_local > 0); + + if (K > 1) { + const uint32_t t = t_base + t_local; + const int32_t target_slot = (int32_t) n_tokens - 1 - (int32_t) t; + if (target_slot > 0 && target_slot < (int32_t) K) { + const dma_addr_t snap_dma = state_out_dma_base + + ((size_t) target_slot * state_size_per_snap + ((size_t) iv3 * H + iv1) * S_v * S_v) * sizeof(float); + dma_queue_push(dma_q, dma_make_data(snap_dma, s_work_curr), + S_v * sizeof(float), S_v * sizeof(float), + S_v * sizeof(float), S_v); + dma_queue_pop(dma_q); + } } } + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); + + if (K > 1 && tile_idx + 1 < n_tiles) { + const uint32_t next_t_base = (tile_idx + 1) * HTP_GDN_TOKEN_TILE; + const uint32_t next_tokens = hex_smin(HTP_GDN_TOKEN_TILE, n_tokens - next_t_base); + gdn_dma_push_tile_inputs(dma_q, q_spad[next_buf], k_spad[next_buf], v_spad[next_buf], g_spad[next_buf], beta_spad[next_buf], + q, k, v, g, beta, iq3, iq1, ik3, ik1, iv3, iv1, + next_t_base, next_tokens, q_row_bytes, k_row_bytes, v_row_bytes, g_row_bytes); + } - attn_data += (uint64_t) S_v * H; + const dma_addr_t attn_out_dma = dst->data + + ((size_t) (iv3 * n_tokens + t_base) * H + iv1) * out_row_bytes; + dma_queue_push(dma_q, dma_make_data(attn_out_dma, o_curr), + dst_row_stride, out_row_bytes, out_row_bytes, tile_tokens); } - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); - - 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), keep ? 0 : S_v); - // Prefetch next block (if any) - if (ir_prefetch < row_end) { - const uint32_t piv1 = fastmodulo(ir_prefetch, H, fd_H); - const uint32_t piv3 = fastdiv(ir_prefetch, fd_H); - dma_addr_t ps_in = state->data + ((uint64_t) piv3 * state_seq_stride + (uint64_t) piv1 * S_v * S_v) * sizeof(float); + dma_queue_pop(dma_q); - dma_queue_push(dma_q, dma_make_data(s_work[spad_idx], ps_in), + if (!keep) { + 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); - - ir_prefetch += nth; - spad_idx ^= 1; + dma_queue_pop(dma_q); } - - curr_spad_idx ^= 1; } dma_queue_flush(dma_q); } @@ -962,13 +1754,36 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int const struct htp_tensor * dst_cache = octx->dsts[1]; const float scale = kparams->scale; - float * dst_base = (float *) (uintptr_t) dst->data; + + const uint32_t q_row_bytes = S_v * ((q->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float)); + const uint32_t k_row_bytes = S_v * ((k->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float)); + const uint32_t v_row_bytes = S_v * ((v->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float)); + const uint32_t g_row_bytes = (kparams->kda ? S_v : 1) * sizeof(float); + const uint32_t out_row_bytes = S_v * ((dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float)); dma_queue * dma_q = th->dma_q; const struct htp_gdn_vtcm_layout * layout = &gctx->layout; + uint8_t * th_vtcm = gctx->vtcm_base + layout->bytes_per_hvx * ith; float * s_work[2]; - s_work[0] = (float *) (gctx->vtcm_base + layout->bytes_per_hvx * ith); - s_work[1] = s_work[0] + layout->state_aligned / sizeof(float); + s_work[0] = (float *) th_vtcm; + s_work[1] = (float *) (th_vtcm + layout->state_aligned); + HVX_Vector * vtcm_scratch = (HVX_Vector *) (th_vtcm + layout->off_scratch); + + uint8_t * q_spad[2]; + uint8_t * k_spad[2]; + uint8_t * v_spad[2]; + uint8_t * g_spad[2]; + uint8_t * o_spad[2]; + float * beta_spad[2]; + for (int b = 0; b < 2; ++b) { + uint8_t * spad = th_vtcm + layout->off_spad + (size_t) b * layout->spad_stride; + q_spad[b] = spad + 0 * layout->tile_vec_bytes; + k_spad[b] = spad + 1 * layout->tile_vec_bytes; + v_spad[b] = spad + 2 * layout->tile_vec_bytes; + g_spad[b] = spad + 3 * layout->tile_vec_bytes; + o_spad[b] = spad + 4 * layout->tile_vec_bytes; + beta_spad[b] = (float *) (spad + 5 * layout->tile_vec_bytes); + } const struct fastdiv_values * fd_H = &kparams->div_H; const struct fastdiv_values * fd_q1 = &kparams->div_q1; @@ -977,8 +1792,7 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int const struct fastdiv_values * fd_rk3 = &kparams->div_rk3; 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; + const dma_addr_t state_out_dma_base = dst_cache ? dst_cache->data : (dst->data + (size_t) S_v * H * n_seqs * sizeof(float)); uint32_t ir_prefetch = gctx->row_start + ith; int spad_idx = 0; @@ -987,79 +1801,78 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int for (int step = 0; step < 2 && ir_prefetch < row_end; step++) { const uint32_t piv1 = fastmodulo(ir_prefetch, H, fd_H); const uint32_t piv3 = fastdiv(ir_prefetch, fd_H); - dma_addr_t ps_in = state->data + ((uint64_t) piv3 * state_seq_stride + (uint64_t) piv1 * S_v * S_v) * sizeof(float); - dma_addr_t ps_out = state_out_dma_base + ((uint64_t) piv3 * H + piv1) * S_v * S_v * sizeof(float); + const uint32_t piq1 = fastmodulo(piv1, q->ne[1], fd_q1); + const uint32_t pik1 = fastmodulo(piv1, k->ne[1], fd_k1); + const uint32_t piq3 = fastdiv(piv3, fd_rq3); + const uint32_t pik3 = fastdiv(piv3, fd_rk3); + const uint32_t pis3 = gdn_read_seq_idx(gctx->ids_data, gctx->ids_type, piv3); + + const dma_addr_t ps_in = state->data + ((size_t) pis3 * state_seq_stride + (size_t) piv1 * S_v * S_v) * sizeof(float); + const dma_addr_t ps_out = state_out_dma_base + ((size_t) piv3 * H + piv1) * S_v * S_v * sizeof(float); + const dma_addr_t po_out = dst->data + ((size_t) piv3 * H + piv1) * out_row_bytes; - // Push dummy write-back dma_queue_push(dma_q, dma_make_data(ps_out, s_work[spad_idx]), S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), 0); + dma_queue_push(dma_q, dma_make_data(po_out, o_spad[spad_idx]), + out_row_bytes, out_row_bytes, out_row_bytes, 0); - // Push fetch dma_queue_push(dma_q, dma_make_data(s_work[spad_idx], ps_in), S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v); + gdn_dma_push_tile_inputs(dma_q, q_spad[spad_idx], k_spad[spad_idx], v_spad[spad_idx], g_spad[spad_idx], beta_spad[spad_idx], + q, k, v, g, beta, piq3, piq1, pik3, pik1, piv3, piv1, + 0, 1, q_row_bytes, k_row_bytes, v_row_bytes, g_row_bytes); ir_prefetch += nth; spad_idx ^= 1; } struct htp_thread_trace * tr = th->trace; + const gdn_step_fn_t step_fn = gctx->step_fn; int curr_spad_idx = 0; for (uint32_t ir = gctx->row_start + ith; ir < row_end; ir += nth) { - dma_queue_pop(dma_q); - dma_queue_pop(dma_q); - - float * s_work_curr = s_work[curr_spad_idx]; + for (int d = 0; d < 8; ++d) { + dma_queue_pop(dma_q); + } const uint32_t iv1 = fastmodulo(ir, H, fd_H); const uint32_t iv3 = fastdiv(ir, fd_H); - const uint32_t iq1 = fastmodulo(iv1, q->ne[1], fd_q1); - const uint32_t ik1 = fastmodulo(iv1, k->ne[1], fd_k1); - const uint32_t iq3 = fastdiv(iv3, fd_rq3); - const uint32_t ik3 = fastdiv(iv3, fd_rk3); - - dma_addr_t s_out = state_out_dma_base + ((uint64_t) iv3 * H + iv1) * S_v * S_v * sizeof(float); - float * attn_data = dst_base + ((uint64_t) iv3 * H + iv1) * S_v; - - const float * q_t = (const float *) ((const uint8_t *) (uintptr_t) q->data + - (uint64_t) iq3 * q->nb[3] + (uint64_t) iq1 * q->nb[1]); - const float * k_t = (const float *) ((const uint8_t *) (uintptr_t) k->data + - (uint64_t) ik3 * k->nb[3] + (uint64_t) ik1 * k->nb[1]); - const float * v_t = (const float *) ((const uint8_t *) (uintptr_t) v->data + - (uint64_t) iv3 * v->nb[3] + (uint64_t) iv1 * v->nb[1]); - const float * g_t = (const float *) ((const uint8_t *) (uintptr_t) g->data + - (uint64_t) iv3 * g->nb[3] + (uint64_t) iv1 * g->nb[1]); - const float beta_val = *(const float *) ((const uint8_t *) (uintptr_t) beta->data + - (uint64_t) iv3 * beta->nb[3] + (uint64_t) iv1 * beta->nb[1]); + const dma_addr_t s_out = state_out_dma_base + ((size_t) iv3 * H + iv1) * S_v * S_v * sizeof(float); + const dma_addr_t po_out = dst->data + ((size_t) iv3 * H + iv1) * out_row_bytes; 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 { - gdn_step_scalar_f32(s_work_curr, attn_data, q_t, k_t, v_t, g_t, beta_val, scale, S_v); - } + step_fn(gctx, s_work[curr_spad_idx], o_spad[curr_spad_idx], + q_spad[curr_spad_idx], k_spad[curr_spad_idx], v_spad[curr_spad_idx], + (const float *) g_spad[curr_spad_idx], beta_spad[curr_spad_idx], + vtcm_scratch, scale, S_v, NULL, false); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); - dma_queue_push(dma_q, dma_make_data(s_out, s_work_curr), + dma_queue_push(dma_q, dma_make_data(s_out, s_work[curr_spad_idx]), S_v * sizeof(float), S_v * sizeof(float), - S_v * sizeof(float), keep ? 0 : S_v); + S_v * sizeof(float), S_v); + dma_queue_push(dma_q, dma_make_data(po_out, o_spad[curr_spad_idx]), + out_row_bytes, out_row_bytes, out_row_bytes, 1); - // Prefetch next block (if any) if (ir_prefetch < row_end) { const uint32_t piv1 = fastmodulo(ir_prefetch, H, fd_H); const uint32_t piv3 = fastdiv(ir_prefetch, fd_H); - dma_addr_t ps_in = state->data + ((uint64_t) piv3 * state_seq_stride + (uint64_t) piv1 * S_v * S_v) * sizeof(float); + const uint32_t piq1 = fastmodulo(piv1, q->ne[1], fd_q1); + const uint32_t pik1 = fastmodulo(piv1, k->ne[1], fd_k1); + const uint32_t piq3 = fastdiv(piv3, fd_rq3); + const uint32_t pik3 = fastdiv(piv3, fd_rk3); + const uint32_t pis3 = gdn_read_seq_idx(gctx->ids_data, gctx->ids_type, piv3); + + const dma_addr_t ps_in = state->data + ((size_t) pis3 * state_seq_stride + (size_t) piv1 * S_v * S_v) * sizeof(float); dma_queue_push(dma_q, dma_make_data(s_work[spad_idx], ps_in), S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v); + gdn_dma_push_tile_inputs(dma_q, q_spad[spad_idx], k_spad[spad_idx], v_spad[spad_idx], g_spad[spad_idx], beta_spad[spad_idx], + q, k, v, g, beta, piq3, piq1, pik3, pik1, piv3, piv1, + 0, 1, q_row_bytes, k_row_bytes, v_row_bytes, g_row_bytes); ir_prefetch += nth; spad_idx ^= 1; @@ -1070,56 +1883,205 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int dma_queue_flush(dma_q); } -struct htp_gdn_hmx_gemm_task { - const __fp16 * row_tiles; - const __fp16 * col_tiles; - __fp16 * out_tiles; - uint32_t n_row_tiles; - uint32_t n_col_tiles; - uint32_t n_dot_tiles; - uint32_t dot_stride; - uint8_t * hmx_scales; -}; +struct htp_gdn_head_ptrs { + float * s_state; + __fp16 * s_col_tiles; + __fp16 * s_update_tiles; + + float * q_f32[2]; + float * k_f32[2]; + float * v_f32[2]; + float * g_f32[2]; + float * b_f32[2]; + float * o_f32[2]; + + __fp16 * k_f16; + + __fp16 * q_row_tiles; + __fp16 * q_prime_row_tiles; + __fp16 * k_row_tiles; + __fp16 * k_col_tiles; + __fp16 * k_prime_row_tiles; + __fp16 * k_col_tiles_64x128[2]; + __fp16 * kk_tiles; + __fp16 * qk_tiles; + __fp16 * v_inter_tiles; + __fp16 * o_inter_tiles; + __fp16 * inv_row_tiles; + __fp16 * a_row_tiles; + __fp16 * v_prime_col_tiles; + __fp16 * delta_tiles; + __fp16 * o_intra_tiles; + __fp16 * d_row_tiles; + + __fp16 * gamma; + float * lambda_init[2]; + __fp16 * lambda_init_f16; + __fp16 * decay_m; + __fp16 * decay_a; + + HVX_Vector * rows_kk; + HVX_Vector * rows_qk; + HVX_Vector * rows_inv; + HVX_Vector * rows_a; -static void htp_gdn_hmx_gemm_worker(const htp_thread_t * th, void * data) { - struct htp_gdn_hmx_gemm_task * task = (struct htp_gdn_hmx_gemm_task *) data; - asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int)task->hmx_scales)); + HVX_Vector * vtcm_m; + HVX_Vector * vtcm_tmp; + + uint32_t iv1; + uint32_t iv3; + uint32_t iq1; + uint32_t ik1; + uint32_t iq3; + uint32_t ik3; + dma_addr_t state_in_dma; + dma_addr_t state_out_dma; +}; - const size_t dot_stride = task->dot_stride; - for (uint32_t r = 0; r < task->n_row_tiles; ++r) { - const __fp16 * r_tiles = task->row_tiles + r * dot_stride; - const __fp16 * c_tiles = task->col_tiles; - __fp16 * o_tile = task->out_tiles + r * task->n_col_tiles * HMX_FP16_TILE_N_ELMS; +struct htp_gdn_batch_context { + struct htp_gdn_head_ptrs * heads; + float * vtcm_g_raw[2]; + float * vtcm_b_raw[2]; + uint8_t * hmx_scales; + const int32_t * n_rep_data; + uint32_t n_pend; + bool replay; + bool keep; + uint32_t head_in_seq; + uint32_t iv3; + uint32_t curr_buf; + uint32_t s_update_buf; + uint32_t c; + uint32_t n_batch; + uint32_t S_v; + float scale; + struct htp_ops_context * octx; + const struct htp_gdn_kernel_params * kparams; +}; - for (uint32_t c = 0; c < task->n_col_tiles; ++c) { - hmx_fa_qk_dot_tile(r_tiles, c_tiles, o_tile, task->n_dot_tiles); +static inline void gdn_hmx_run_gemm( + const __fp16 * row_tiles, + const __fp16 * col_tiles, + __fp16 * out_tiles, + uint32_t n_row_tiles, + uint32_t n_col_tiles, + uint32_t n_dot_tiles +) { + const size_t dot_stride = (size_t) n_dot_tiles * HMX_FP16_TILE_N_ELMS; + for (uint32_t r = 0; r < n_row_tiles; ++r) { + const __fp16 * r_tiles = row_tiles + r * dot_stride; + const __fp16 * c_tiles = col_tiles; + __fp16 * o_tile = out_tiles + r * n_col_tiles * HMX_FP16_TILE_N_ELMS; + + for (uint32_t c = 0; c < n_col_tiles; ++c) { + hmx_fa_qk_dot_tile(r_tiles, c_tiles, o_tile, n_dot_tiles); c_tiles += dot_stride; o_tile += HMX_FP16_TILE_N_ELMS; } } } -static inline void htp_gdn_push_hmx_gemm_task( - hmx_queue_t q, - struct htp_gdn_hmx_gemm_task * task, - const __fp16 * row_tiles, - const __fp16 * col_tiles, - __fp16 * out_tiles, - uint32_t n_row_tiles, - uint32_t n_col_tiles, - uint32_t n_dot_tiles, - uint8_t * scales -) { - task->row_tiles = row_tiles; - task->col_tiles = col_tiles; - task->out_tiles = out_tiles; - task->n_row_tiles = n_row_tiles; - task->n_col_tiles = n_col_tiles; - task->n_dot_tiles = n_dot_tiles; - task->dot_stride = n_dot_tiles * HMX_FP16_TILE_N_ELMS; - task->hmx_scales = scales; +static void gdn_hmx_kk_worker(const htp_thread_t * th, void * data) { + (void) th; + const struct htp_gdn_batch_context * bctx = (const struct htp_gdn_batch_context *) data; + asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int) bctx->hmx_scales)); + const uint32_t n_sv_tiles = bctx->S_v >> 5; + for (uint32_t h = 0; h < bctx->n_batch; ++h) { + gdn_hmx_run_gemm(bctx->heads[h].k_row_tiles, bctx->heads[h].k_col_tiles, bctx->heads[h].kk_tiles, 2u, 2u, n_sv_tiles); + } +} - hmx_queue_push(q, hmx_queue_make_desc(htp_gdn_hmx_gemm_worker, task)); +static void gdn_hmx_qk_worker(const htp_thread_t * th, void * data) { + (void) th; + const struct htp_gdn_batch_context * bctx = (const struct htp_gdn_batch_context *) data; + asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int) bctx->hmx_scales)); + const uint32_t n_sv_tiles = bctx->S_v >> 5; + for (uint32_t h = 0; h < bctx->n_batch; ++h) { + gdn_hmx_run_gemm(bctx->heads[h].q_row_tiles, bctx->heads[h].k_col_tiles, bctx->heads[h].qk_tiles, 2u, 2u, n_sv_tiles); + } +} + +static void gdn_hmx_ks_worker(const htp_thread_t * th, void * data) { + (void) th; + const struct htp_gdn_batch_context * bctx = (const struct htp_gdn_batch_context *) data; + asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int) bctx->hmx_scales)); + const uint32_t n_sv_tiles = bctx->S_v >> 5; + for (uint32_t h = 0; h < bctx->n_batch; ++h) { + gdn_hmx_run_gemm(bctx->heads[h].k_prime_row_tiles, bctx->heads[h].s_col_tiles, bctx->heads[h].v_inter_tiles, 2u, n_sv_tiles, n_sv_tiles); + } +} + +static void gdn_hmx_qs_worker(const htp_thread_t * th, void * data) { + (void) th; + const struct htp_gdn_batch_context * bctx = (const struct htp_gdn_batch_context *) data; + asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int) bctx->hmx_scales)); + const uint32_t n_sv_tiles = bctx->S_v >> 5; + for (uint32_t h = 0; h < bctx->n_batch; ++h) { + gdn_hmx_run_gemm(bctx->heads[h].q_prime_row_tiles, bctx->heads[h].s_col_tiles, bctx->heads[h].o_inter_tiles, 2u, n_sv_tiles, n_sv_tiles); + } +} + +static void gdn_hmx_inv10_worker(const htp_thread_t * th, void * data) { + (void) th; + const struct htp_gdn_batch_context * bctx = (const struct htp_gdn_batch_context *) data; + asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int) bctx->hmx_scales)); + for (uint32_t h = 0; h < bctx->n_batch; ++h) { + const struct htp_gdn_head_ptrs * head = &bctx->heads[h]; + hmx_fa_qk_dot_tile( + (const __fp16 *) head->vtcm_m, + head->inv_row_tiles + 0 * HMX_FP16_TILE_N_ELMS, + (__fp16 *) head->vtcm_tmp, + 1u + ); + hmx_fa_qk_dot_tile( + (const __fp16 *) head->vtcm_m + HMX_FP16_TILE_N_ELMS, + (const __fp16 *) head->vtcm_tmp, + head->inv_row_tiles + 2 * HMX_FP16_TILE_N_ELMS, + 1u + ); + } +} + +static void gdn_hmx_delta_worker(const htp_thread_t * th, void * data) { + (void) th; + const struct htp_gdn_batch_context * bctx = (const struct htp_gdn_batch_context *) data; + asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int) bctx->hmx_scales)); + const uint32_t n_sv_tiles = bctx->S_v >> 5; + const size_t dot_stride = 2u * HMX_FP16_TILE_N_ELMS; + // Write delta_tiles in col-major order [c][r] so O_INTRA reads in place + for (uint32_t h = 0; h < bctx->n_batch; ++h) { + const struct htp_gdn_head_ptrs * head = &bctx->heads[h]; + for (uint32_t r = 0; r < 2u; ++r) { + const __fp16 * r_tiles = head->inv_row_tiles + r * dot_stride; + const __fp16 * c_tiles = head->v_prime_col_tiles; + for (uint32_t c = 0; c < n_sv_tiles; ++c) { + __fp16 * o_tile = head->delta_tiles + (c * 2u + r) * HMX_FP16_TILE_N_ELMS; + hmx_fa_qk_dot_tile(r_tiles, c_tiles, o_tile, 2u); + c_tiles += dot_stride; + } + } + } +} + +static void gdn_hmx_o_intra_worker(const htp_thread_t * th, void * data) { + (void) th; + const struct htp_gdn_batch_context * bctx = (const struct htp_gdn_batch_context *) data; + asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int) bctx->hmx_scales)); + const uint32_t n_sv_tiles = bctx->S_v >> 5; + for (uint32_t h = 0; h < bctx->n_batch; ++h) { + gdn_hmx_run_gemm(bctx->heads[h].a_row_tiles, bctx->heads[h].delta_tiles, bctx->heads[h].o_intra_tiles, 2u, n_sv_tiles, 2u); + } +} + +static void gdn_hmx_s_update_worker(const htp_thread_t * th, void * data) { + (void) th; + const struct htp_gdn_batch_context * bctx = (const struct htp_gdn_batch_context *) data; + asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int) bctx->hmx_scales)); + const uint32_t n_sv_tiles = bctx->S_v >> 5; + const uint32_t buf_idx = bctx->s_update_buf; + for (uint32_t h = 0; h < bctx->n_batch; ++h) { + gdn_hmx_run_gemm(bctx->heads[h].d_row_tiles, bctx->heads[h].k_col_tiles_64x128[buf_idx], bctx->heads[h].s_update_tiles, n_sv_tiles, n_sv_tiles, 2u); + } } static inline void gdn_unpack_64x64_tiles_to_vectors( @@ -1162,83 +2124,19 @@ static inline void gdn_pack_64x64_vectors_to_tiles( } } -static inline void gdn_unpack_64xS_tiles_to_f32( - float * restrict dst_f32, - const __fp16 * restrict tiles, - uint32_t S_v -) { - const uint32_t n_col_tiles = S_v / 32; - for (uint32_t r0 = 0; r0 < 2; ++r0) { - for (uint32_t d = 0; d < S_v / 64; ++d) { - const HVX_Vector * t0 = (const HVX_Vector *) (tiles + (r0 * n_col_tiles + 2 * d + 0) * HMX_FP16_TILE_N_ELMS); - const HVX_Vector * t1 = (const HVX_Vector *) (tiles + (r0 * n_col_tiles + 2 * d + 1) * HMX_FP16_TILE_N_ELMS); - - for (uint32_t r = 0; r < 16; ++r) { - HVX_VectorPair vp01 = Q6_W_vdeal_VVR(t1[r], t0[r], -2); - HVX_VectorPair p0 = hvx_vec_f16_to_f32(Q6_V_lo_W(vp01)); - HVX_VectorPair p1 = hvx_vec_f16_to_f32(Q6_V_hi_W(vp01)); - - float * out0 = dst_f32 + (r0 * 32 + 2 * r + 0) * S_v + d * 64; - float * out1 = dst_f32 + (r0 * 32 + 2 * r + 1) * S_v + d * 64; - - hvx_vmem(out0 + 0) = Q6_V_lo_W(p0); - hvx_vmem(out0 + 32) = Q6_V_hi_W(p0); - hvx_vmem(out1 + 0) = Q6_V_lo_W(p1); - hvx_vmem(out1 + 32) = Q6_V_hi_W(p1); - } - } - } +static inline float gdn_vtcm_load_f32(const float * vtcm_arr, uint32_t idx) { + const HVX_Vector v = hvx_vmem(&vtcm_arr[idx & ~31u]); + union { + int32_t i; + float f; + } u; + u.i = Q6_R_vextract_VR(v, (idx & 31u) * 4u); + return u.f; } -static inline void gdn_unpack_64xS_tiles_to_f16( - __fp16 * restrict dst_f16, - const __fp16 * restrict tiles, - uint32_t S_v -) { - const uint32_t n_col_tiles = S_v / 32; - for (uint32_t r0 = 0; r0 < 2; ++r0) { - for (uint32_t d = 0; d < S_v / 64; ++d) { - const HVX_Vector * t0 = (const HVX_Vector *) (tiles + (r0 * n_col_tiles + 2 * d + 0) * HMX_FP16_TILE_N_ELMS); - const HVX_Vector * t1 = (const HVX_Vector *) (tiles + (r0 * n_col_tiles + 2 * d + 1) * HMX_FP16_TILE_N_ELMS); - - for (uint32_t r = 0; r < 16; ++r) { - HVX_VectorPair vp01 = Q6_W_vdeal_VVR(t1[r], t0[r], -2); - __fp16 * out0 = dst_f16 + (r0 * 32 + 2 * r + 0) * S_v + d * 64; - __fp16 * out1 = dst_f16 + (r0 * 32 + 2 * r + 1) * S_v + d * 64; - - hvx_vmem(out0) = Q6_V_lo_W(vp01); - hvx_vmem(out1) = Q6_V_hi_W(vp01); - } - } - } -} - -static inline void gdn_unpack_SxS_tiles_to_f32( - float * restrict dst_f32, - const __fp16 * restrict tiles, - uint32_t S_v -) { - const uint32_t n_tiles = S_v / 32; - for (uint32_t r0 = 0; r0 < n_tiles; ++r0) { - for (uint32_t d = 0; d < S_v / 64; ++d) { - const HVX_Vector * t0 = (const HVX_Vector *) (tiles + (r0 * n_tiles + 2 * d + 0) * HMX_FP16_TILE_N_ELMS); - const HVX_Vector * t1 = (const HVX_Vector *) (tiles + (r0 * n_tiles + 2 * d + 1) * HMX_FP16_TILE_N_ELMS); - - for (uint32_t r = 0; r < 16; ++r) { - HVX_VectorPair vp01 = Q6_W_vdeal_VVR(t1[r], t0[r], -2); - HVX_VectorPair p0 = hvx_vec_f16_to_f32(Q6_V_lo_W(vp01)); - HVX_VectorPair p1 = hvx_vec_f16_to_f32(Q6_V_hi_W(vp01)); - - float * out0 = dst_f32 + (r0 * 32 + 2 * r + 0) * S_v + d * 64; - float * out1 = dst_f32 + (r0 * 32 + 2 * r + 1) * S_v + d * 64; - - hvx_vmem(out0 + 0) = Q6_V_lo_W(p0); - hvx_vmem(out0 + 32) = Q6_V_hi_W(p0); - hvx_vmem(out1 + 0) = Q6_V_lo_W(p1); - hvx_vmem(out1 + 32) = Q6_V_hi_W(p1); - } - } - } +static inline uint16_t gdn_hvx_extract_u16(HVX_Vector v, uint32_t idx) { + const uint32_t w = (uint32_t) Q6_R_vextract_VR(v, (idx & ~1u) * 2u); + return (uint16_t) ((idx & 1u) ? (w >> 16) : (w & 0xFFFFu)); } static inline void gdn_f32_to_hmx_row_tiles_and_f16( @@ -1248,22 +2146,20 @@ static inline void gdn_f32_to_hmx_row_tiles_and_f16( const float * restrict src, const __fp16 * restrict scale_per_row, uint32_t n_rows, - uint32_t n_cols + uint32_t n_cols, + const bool write_f16 ) { - const uint32_t n_col_tiles = n_cols / 32; - const uint32_t * scale_pairs = (const uint32_t *) scale_per_row; + const uint32_t n_col_tiles = n_cols >> 5; + const HVX_Vector v_scale_f16 = hvx_vmem(scale_per_row); for (uint32_t r = 0; r < n_rows; r += 2) { - uint32_t r0 = r / 32; - uint32_t r1 = (r % 32) / 2; + uint32_t r0 = r >> 5; + uint32_t r1 = (r & 31u) >> 1; const float * p0 = src + (r + 0) * n_cols; const float * p1 = src + (r + 1) * n_cols; - HVX_Vector v_scale; - if (dst_prime_tiles) { - uint32_t scale_pair = scale_pairs ? scale_pairs[r / 2] : 0x3c003c00; - v_scale = Q6_V_vsplat_R(scale_pair); - } + const uint32_t pair = (uint32_t) Q6_R_vextract_VR(v_scale_f16, r * 2u); + HVX_Vector v_scale = Q6_V_vsplat_R(pair); for (uint32_t c = 0; c < n_col_tiles; c += 2) { HVX_Vector v0_0 = hvx_vmem(p0 + (c + 0) * 32); @@ -1278,16 +2174,14 @@ static inline void gdn_f32_to_hmx_row_tiles_and_f16( ((HVX_Vector *) tile0)[r1] = vh0; ((HVX_Vector *) tile1)[r1] = vh1; - if (dst_prime_tiles) { - HVX_Vector vh0_s = hvx_vec_mul_f16_f16(vh0, v_scale); - HVX_Vector vh1_s = hvx_vec_mul_f16_f16(vh1, v_scale); - __fp16 * tile0_s = dst_prime_tiles + (r0 * n_col_tiles + c + 0) * HMX_FP16_TILE_N_ELMS; - __fp16 * tile1_s = dst_prime_tiles + (r0 * n_col_tiles + c + 1) * HMX_FP16_TILE_N_ELMS; - ((HVX_Vector *) tile0_s)[r1] = vh0_s; - ((HVX_Vector *) tile1_s)[r1] = vh1_s; - } + HVX_Vector vh0_s = hvx_vec_mul_f16_f16(vh0, v_scale); + HVX_Vector vh1_s = hvx_vec_mul_f16_f16(vh1, v_scale); + __fp16 * tile0_s = dst_prime_tiles + (r0 * n_col_tiles + c + 0) * HMX_FP16_TILE_N_ELMS; + __fp16 * tile1_s = dst_prime_tiles + (r0 * n_col_tiles + c + 1) * HMX_FP16_TILE_N_ELMS; + ((HVX_Vector *) tile0_s)[r1] = vh0_s; + ((HVX_Vector *) tile1_s)[r1] = vh1_s; - if (dst_f16) { + if (write_f16) { HVX_VectorPair vp01 = Q6_W_vdeal_VVR(vh1, vh0, -2); hvx_vmem(dst_f16 + (r + 0) * n_cols + c * 32) = Q6_V_lo_W(vp01); hvx_vmem(dst_f16 + (r + 1) * n_cols + c * 32) = Q6_V_hi_W(vp01); @@ -1296,74 +2190,76 @@ static inline void gdn_f32_to_hmx_row_tiles_and_f16( } } -static inline void hvx_transpose_32x32_words(HVX_Vector * restrict m, HVX_Vector * restrict tmp) { - for (int i = 0; i < 16; ++i) { - HVX_VectorPair p = Q6_W_vshuff_VVR(m[2*i + 1], m[2*i], -4); - tmp[2*i + 0] = Q6_V_lo_W(p); - tmp[2*i + 1] = Q6_V_hi_W(p); - } +static inline void gdn_f16_to_hmx_row_tiles( + __fp16 * restrict dst_tiles, + __fp16 * restrict dst_prime_tiles, + const __fp16 * restrict src, + const __fp16 * restrict scale_per_row, + uint32_t n_rows, + uint32_t n_cols +) { + const uint32_t n_col_tiles = n_cols >> 5; + const HVX_Vector v_scale_f16 = hvx_vmem(scale_per_row); - for (int b = 0; b < 32; b += 4) { - HVX_VectorPair p0 = Q6_W_vshuff_VVR(tmp[b + 2], tmp[b + 0], -8); - HVX_VectorPair p1 = Q6_W_vshuff_VVR(tmp[b + 3], tmp[b + 1], -8); - m[b + 0] = Q6_V_lo_W(p0); m[b + 1] = Q6_V_hi_W(p0); - m[b + 2] = Q6_V_lo_W(p1); m[b + 3] = Q6_V_hi_W(p1); - } + for (uint32_t r = 0; r < n_rows; r += 2) { + uint32_t r0 = r >> 5; + uint32_t r1 = (r & 31u) >> 1; + const __fp16 * p0 = src + (r + 0) * n_cols; + const __fp16 * p1 = src + (r + 1) * n_cols; - for (int b = 0; b < 32; b += 8) { - for (int i = 0; i < 4; ++i) { - HVX_VectorPair p = Q6_W_vshuff_VVR(m[b + i + 4], m[b + i], -16); - tmp[b + 2*i + 0] = Q6_V_lo_W(p); - tmp[b + 2*i + 1] = Q6_V_hi_W(p); - } - } + const uint32_t pair = (uint32_t) Q6_R_vextract_VR(v_scale_f16, r * 2u); + HVX_Vector v_scale = Q6_V_vsplat_R(pair); - for (int b = 0; b < 32; b += 16) { - for (int i = 0; i < 8; ++i) { - HVX_VectorPair p = Q6_W_vshuff_VVR(tmp[b + i + 8], tmp[b + i], -32); - m[b + 2*i + 0] = Q6_V_lo_W(p); - m[b + 2*i + 1] = Q6_V_hi_W(p); - } - } + for (uint32_t c = 0; c < n_col_tiles; c += 2) { + HVX_Vector vr0 = hvx_vmem(p0 + c * 32); + HVX_Vector vr1 = hvx_vmem(p1 + c * 32); + HVX_VectorPair vp = Q6_W_vshuff_VVR(vr1, vr0, -2); + HVX_Vector vh0 = Q6_V_lo_W(vp); + HVX_Vector vh1 = Q6_V_hi_W(vp); - for (int i = 0; i < 16; ++i) { - HVX_VectorPair p = Q6_W_vshuff_VVR(m[i + 16], m[i], -64); - tmp[2 * i + 0] = Q6_V_lo_W(p); - tmp[2 * i + 1] = Q6_V_hi_W(p); - } + __fp16 * tile0 = dst_tiles + (r0 * n_col_tiles + c + 0) * HMX_FP16_TILE_N_ELMS; + __fp16 * tile1 = dst_tiles + (r0 * n_col_tiles + c + 1) * HMX_FP16_TILE_N_ELMS; + ((HVX_Vector *) tile0)[r1] = vh0; + ((HVX_Vector *) tile1)[r1] = vh1; - for (int i = 0; i < 32; ++i) { - m[i] = tmp[i]; + HVX_Vector vh0_s = hvx_vec_mul_f16_f16(vh0, v_scale); + HVX_Vector vh1_s = hvx_vec_mul_f16_f16(vh1, v_scale); + __fp16 * tile0_s = dst_prime_tiles + (r0 * n_col_tiles + c + 0) * HMX_FP16_TILE_N_ELMS; + __fp16 * tile1_s = dst_prime_tiles + (r0 * n_col_tiles + c + 1) * HMX_FP16_TILE_N_ELMS; + ((HVX_Vector *) tile0_s)[r1] = vh0_s; + ((HVX_Vector *) tile1_s)[r1] = vh1_s; + } } } -static inline void gdn_pack_d_t_row_tiles( - __fp16 * restrict dst_tiles, - const __fp16 * restrict src_d, - uint32_t S_v, - HVX_Vector * restrict m, - HVX_Vector * restrict tmp +// Solve (I + L) * A = I for 32x32 unit lower-triangular L in L1-cached stack, writing A rows to VTCM +static __attribute__((noinline)) void gdn_invert_lower_32x32( + HVX_Vector * restrict a_rows, + const uint16_t * restrict l_l2 ) { - for (uint32_t col_half = 0; col_half < S_v / 64; ++col_half) { - uint32_t r0_base = col_half * 2; - for (uint32_t c0 = 0; c0 < 2; ++c0) { - for (uint32_t s_local = 0; s_local < 32; ++s_local) { - uint32_t s = c0 * 32 + s_local; - m[s_local] = hvx_vmem(src_d + s * S_v + col_half * 64); - } - - hvx_transpose_32x32_words(m, tmp); - - uint32_t tile0_idx = (r0_base + 0) * 2 + c0; - uint32_t tile1_idx = (r0_base + 1) * 2 + c0; - HVX_Vector * t0 = (HVX_Vector *)(dst_tiles + tile0_idx * HMX_FP16_TILE_N_ELMS); - HVX_Vector * t1 = (HVX_Vector *)(dst_tiles + tile1_idx * HMX_FP16_TILE_N_ELMS); + const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f); + const HVX_VectorPred q_mask64 = Q6_Q_vsetq2_R(64); - for (uint32_t r = 0; r < 16; ++r) { - t0[r] = m[r]; - t1[r] = m[16 + r]; - } + for (uint32_t t = 0; t < 32; ++t) { + const uint32_t * restrict l_row_u32 = (const uint32_t *) (l_l2 + t * 32u); + HVX_Vector v_inv0 = Q6_V_vzero(); + HVX_Vector v_inv1 = Q6_V_vzero(); + uint32_t k = 0; + #pragma nounroll + for (; k + 1u < t; k += 2u) { + const uint32_t w = l_row_u32[k >> 1]; + HVX_Vector v_lk0 = Q6_Vh_vsplat_R(w & 0xFFFFu); + HVX_Vector v_lk1 = Q6_Vh_vsplat_R(w >> 16); + v_inv0 = hvx_vec_sub_f16_f16(v_inv0, hvx_vec_mul_f16_f16(v_lk0, a_rows[k + 0u])); + v_inv1 = hvx_vec_sub_f16_f16(v_inv1, hvx_vec_mul_f16_f16(v_lk1, a_rows[k + 1u])); } + HVX_Vector v_inv = hvx_vec_add_f16_f16(v_inv0, v_inv1); + if (k < t) { + HVX_Vector v_lk = Q6_Vh_vsplat_R(l_l2[t * 32u + k]); + v_inv = hvx_vec_sub_f16_f16(v_inv, hvx_vec_mul_f16_f16(v_lk, a_rows[k])); + } + HVX_VectorPred q_diag = (t == 0) ? Q6_Q_vsetq2_R(2) : Q6_Q_and_QQn(Q6_Q_vsetq2_R(2 * (t + 1)), Q6_Q_vsetq2_R(2 * t)); + a_rows[t] = Q6_V_vand_QV(q_mask64, Q6_V_vmux_QVV(q_diag, v_one_f16, v_inv)); } } @@ -1373,22 +2269,21 @@ static __attribute__((noinline)) void gdn_build_inv_l_blocks( const __fp16 * restrict decay_m, const float * restrict beta, __fp16 * restrict l10_tile, - __fp16 * restrict neg_a11_tile + __fp16 * restrict neg_a11_tile, + HVX_Vector * restrict a_rows_vtcm ) { - const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f); - const HVX_VectorPred q_mask64 = Q6_Q_vsetq2_R(64); - - uint16_t beta_u16[64] __attribute__((aligned(128))); - uint16_t l00[32][32] __attribute__((aligned(128))); - uint16_t l11[32][32] __attribute__((aligned(128))); + // Keep l00, l11, and beta_u16 in L1-cached stack to avoid scalar VTCM loads in inversion + uint16_t l_l2_buf[2048 + 64] __attribute__((aligned(128))); - HVX_Vector * restrict p_l00 = (HVX_Vector *) l00; - HVX_Vector * restrict p_l11 = (HVX_Vector *) l11; + HVX_Vector * restrict a_rows = a_rows_vtcm; + HVX_Vector * restrict p_l00 = (HVX_Vector *) (l_l2_buf + 0); + HVX_Vector * restrict p_l11 = (HVX_Vector *) (l_l2_buf + 1024); + uint16_t * restrict beta_u16 = l_l2_buf + 2048; HVX_Vector * restrict p_l10_tile = (HVX_Vector *) l10_tile; - HVX_Vector * restrict tile00 = (HVX_Vector *) (inv_row_tiles + 0 * HMX_FP16_TILE_N_ELMS); - HVX_Vector * restrict tile01 = (HVX_Vector *) (inv_row_tiles + 1 * HMX_FP16_TILE_N_ELMS); - HVX_Vector * restrict tile11 = (HVX_Vector *) (inv_row_tiles + 3 * HMX_FP16_TILE_N_ELMS); + HVX_Vector * restrict tile00 = (HVX_Vector *) (inv_row_tiles + 0 * HMX_FP16_TILE_N_ELMS); + HVX_Vector * restrict tile01 = (HVX_Vector *) (inv_row_tiles + 1 * HMX_FP16_TILE_N_ELMS); + HVX_Vector * restrict tile11 = (HVX_Vector *) (inv_row_tiles + 3 * HMX_FP16_TILE_N_ELMS); HVX_Vector * restrict p_neg_a11 = (HVX_Vector *) neg_a11_tile; hvx_vmem(beta_u16) = hvx_vec_f32_to_f16(hvx_vmem(beta + 0), hvx_vmem(beta + 32)); @@ -1397,63 +2292,53 @@ static __attribute__((noinline)) void gdn_build_inv_l_blocks( tile01[r] = Q6_V_vzero(); } - for (uint32_t r = 0; r < 16; ++r) { - uint32_t t0 = 2 * r; - uint32_t t1 = t0 + 1; + { + const HVX_VectorPred q_mask64 = Q6_Q_vsetq2_R(64); + const uint32_t * restrict beta_u32 = (const uint32_t *) beta_u16; - HVX_Vector v_d0 = hvx_vmem(decay_m + t0 * 64); - HVX_Vector v_d1 = hvx_vmem(decay_m + t1 * 64); - HVX_Vector v_b0 = Q6_Vh_vsplat_R(beta_u16[t0]); - HVX_Vector v_b1 = Q6_Vh_vsplat_R(beta_u16[t1]); + for (uint32_t r = 0; r < 16; ++r) { + uint32_t t0 = 2 * r; + uint32_t t1 = t0 + 1; - HVX_Vector r0 = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(rows_kk[t0], v_d0), v_b0); - HVX_Vector r1 = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(rows_kk[t1], v_d1), v_b1); + HVX_Vector v_d0 = hvx_vmem(decay_m + t0 * 64); + HVX_Vector v_d1 = hvx_vmem(decay_m + t1 * 64); + const uint32_t bw = beta_u32[r]; + HVX_Vector v_b0 = Q6_Vh_vsplat_R(bw & 0xFFFFu); + HVX_Vector v_b1 = Q6_Vh_vsplat_R(bw >> 16); - p_l00[r] = Q6_V_vmux_QVV(q_mask64, r0, Q6_V_vror_VR(r1, 64)); - } + HVX_Vector r0 = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(rows_kk[t0], v_d0), v_b0); + HVX_Vector r1 = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(rows_kk[t1], v_d1), v_b1); - for (uint32_t r = 0; r < 16; ++r) { - uint32_t t0 = 32 + 2 * r; - uint32_t t1 = t0 + 1; + p_l00[r] = Q6_V_vmux_QVV(q_mask64, r0, Q6_V_vror_VR(r1, 64)); + } - HVX_Vector v_d0 = hvx_vmem(decay_m + t0 * 64); - HVX_Vector v_d1 = hvx_vmem(decay_m + t1 * 64); - HVX_Vector v_b0 = Q6_Vh_vsplat_R(beta_u16[t0]); - HVX_Vector v_b1 = Q6_Vh_vsplat_R(beta_u16[t1]); + for (uint32_t r = 0; r < 16; ++r) { + uint32_t t0 = 32 + 2 * r; + uint32_t t1 = t0 + 1; - HVX_Vector r0 = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(rows_kk[t0], v_d0), v_b0); - HVX_Vector r1 = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(rows_kk[t1], v_d1), v_b1); + HVX_Vector v_d0 = hvx_vmem(decay_m + t0 * 64); + HVX_Vector v_d1 = hvx_vmem(decay_m + t1 * 64); + const uint32_t bw = beta_u32[16 + r]; + HVX_Vector v_b0 = Q6_Vh_vsplat_R(bw & 0xFFFFu); + HVX_Vector v_b1 = Q6_Vh_vsplat_R(bw >> 16); - HVX_VectorPair vp_l10 = Q6_W_vshuff_VVR(r1, r0, -2); - p_l10_tile[r] = Q6_V_lo_W(vp_l10); - p_l11[r] = Q6_V_vmux_QVV(q_mask64, Q6_V_vror_VR(r0, 64), r1); - } + HVX_Vector r0 = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(rows_kk[t0], v_d0), v_b0); + HVX_Vector r1 = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(rows_kk[t1], v_d1), v_b1); - HVX_Vector a_rows[32]; - for (uint32_t t = 0; t < 32; ++t) { - HVX_Vector v_inv = Q6_V_vzero(); - for (uint32_t k = 0; k < t; ++k) { - HVX_Vector v_lk = Q6_Vh_vsplat_R(l00[t][k]); - v_inv = hvx_vec_sub_f16_f16(v_inv, hvx_vec_mul_f16_f16(v_lk, a_rows[k])); + HVX_VectorPair vp_l10 = Q6_W_vshuff_VVR(r1, r0, -2); + p_l10_tile[r] = Q6_V_lo_W(vp_l10); + p_l11[r] = Q6_V_vmux_QVV(q_mask64, Q6_V_vror_VR(r0, 64), r1); } - HVX_VectorPred q_diag = (t == 0) ? Q6_Q_vsetq2_R(2) : Q6_Q_and_QQn(Q6_Q_vsetq2_R(2 * (t + 1)), Q6_Q_vsetq2_R(2 * t)); - a_rows[t] = Q6_V_vand_QV(q_mask64, Q6_V_vmux_QVV(q_diag, v_one_f16, v_inv)); } + gdn_invert_lower_32x32(a_rows, l_l2_buf + 0); + for (uint32_t r = 0; r < 16; ++r) { HVX_VectorPair vp = Q6_W_vshuff_VVR(a_rows[2 * r + 1], a_rows[2 * r + 0], -2); tile00[r] = Q6_V_lo_W(vp); } - for (uint32_t t = 0; t < 32; ++t) { - HVX_Vector v_inv = Q6_V_vzero(); - for (uint32_t k = 0; k < t; ++k) { - HVX_Vector v_lk = Q6_Vh_vsplat_R(l11[t][k]); - v_inv = hvx_vec_sub_f16_f16(v_inv, hvx_vec_mul_f16_f16(v_lk, a_rows[k])); - } - HVX_VectorPred q_diag = (t == 0) ? Q6_Q_vsetq2_R(2) : Q6_Q_and_QQn(Q6_Q_vsetq2_R(2 * (t + 1)), Q6_Q_vsetq2_R(2 * t)); - a_rows[t] = Q6_V_vand_QV(q_mask64, Q6_V_vmux_QVV(q_diag, v_one_f16, v_inv)); - } + gdn_invert_lower_32x32(a_rows, l_l2_buf + 1024); for (uint32_t r = 0; r < 16; ++r) { HVX_VectorPair vp = Q6_W_vshuff_VVR(a_rows[2 * r + 1], a_rows[2 * r + 0], -2); @@ -1466,7 +2351,6 @@ static __attribute__((noinline)) void gdn_build_inv_l_blocks( } } - static inline void gdn_dma_push_chunk_inputs( dma_queue * dma_q, float * vtcm_q, @@ -1476,122 +2360,76 @@ static inline void gdn_dma_push_chunk_inputs( const struct htp_tensor * k, const struct htp_tensor * v, uint32_t iq3, uint32_t iq1, - uint32_t ik3, uint32_t ik1, - uint32_t iv3, uint32_t iv1, - uint32_t t_chunk, - uint32_t chunk_size, - uint32_t S_v -) { - const dma_addr_t q_dma = q->data + (uint64_t) iq3 * q->nb[3] + (uint64_t) t_chunk * q->nb[2] + (uint64_t) iq1 * q->nb[1]; - const dma_addr_t k_dma = k->data + (uint64_t) ik3 * k->nb[3] + (uint64_t) t_chunk * k->nb[2] + (uint64_t) ik1 * k->nb[1]; - const dma_addr_t v_dma = v->data + (uint64_t) iv3 * v->nb[3] + (uint64_t) t_chunk * v->nb[2] + (uint64_t) iv1 * v->nb[1]; - - dma_queue_push(dma_q, dma_make_data(vtcm_q, q_dma), S_v * sizeof(float), q->nb[2], S_v * sizeof(float), chunk_size); - dma_queue_push(dma_q, dma_make_data(vtcm_k, k_dma), S_v * sizeof(float), k->nb[2], S_v * sizeof(float), chunk_size); - dma_queue_push(dma_q, dma_make_data(vtcm_v, v_dma), S_v * sizeof(float), v->nb[2], S_v * sizeof(float), chunk_size); -} - -static inline void gdn_dma_push_chunk_gb( - dma_queue * dma_q, - float * vtcm_g_raw, - float * vtcm_b_raw, - const struct htp_tensor * g, - const struct htp_tensor * beta, - uint32_t iv3, - uint32_t iv1, - uint32_t t_chunk, - uint32_t chunk_size, - uint32_t n_batch -) { - const dma_addr_t g_dma = g->data + (uint64_t) iv3 * g->nb[3] + (uint64_t) t_chunk * g->nb[2] + (uint64_t) iv1 * g->nb[1]; - const dma_addr_t beta_dma = beta->data + (uint64_t) iv3 * beta->nb[3] + (uint64_t) t_chunk * beta->nb[2] + (uint64_t) iv1 * beta->nb[1]; - const uint32_t row_bytes = n_batch * sizeof(float); - const uint32_t dst_stride = (n_batch > 1) ? row_bytes + sizeof(float) : row_bytes; - - dma_queue_push(dma_q, dma_make_data(vtcm_g_raw, g_dma), dst_stride, g->nb[2], row_bytes, chunk_size); - dma_queue_push(dma_q, dma_make_data(vtcm_b_raw, beta_dma), dst_stride, beta->nb[2], row_bytes, chunk_size); -} - -static inline void gdn_pack_s_col_tiles( - __fp16 * restrict vtcm_s_col_tiles, - __fp16 * restrict vtcm_s_f16, - const float * restrict vtcm_s_state, - uint32_t S_v -) { - for (uint32_t j = 0; j < S_v; ++j) { - for (uint32_t i = 0; i < S_v; i += 64) { - HVX_Vector v0 = hvx_vmem(vtcm_s_state + j * S_v + i + 0); - HVX_Vector v1 = (i + 32 < S_v) ? hvx_vmem(vtcm_s_state + j * S_v + i + 32) : Q6_V_vzero(); - hvx_vmem(vtcm_s_f16 + j * S_v + i) = hvx_vec_f32_to_f16(v0, v1); - } - } - hmx_interleave_rows_to_tiles(vtcm_s_col_tiles, vtcm_s_f16, S_v, S_v, S_v, 0, S_v); -} - -struct htp_gdn_head_ptrs { - float * s_state; - __fp16 * s_f16; - __fp16 * s_col_tiles; - float * s_update_f32; - __fp16 * s_update_tiles; - - float * q_f32[2]; - float * k_f32[2]; - float * v_f32[2]; - float * g_f32[2]; - float * b_f32[2]; - float * o_f32[2]; - - float * v_inter_f32; - float * o_inter_f32; - float * o_intra_f32; - - __fp16 * k_f16; - __fp16 * v_prime_f16; - __fp16 * delta_f16; - __fp16 * d_f16; - - __fp16 * q_row_tiles; - __fp16 * q_prime_row_tiles; - __fp16 * k_row_tiles; - __fp16 * k_col_tiles; - __fp16 * k_prime_row_tiles; - __fp16 * k_col_tiles_64x128; - __fp16 * kk_tiles; - __fp16 * qk_tiles; - __fp16 * v_inter_tiles; - __fp16 * o_inter_tiles; - __fp16 * inv_row_tiles; - __fp16 * a_row_tiles; - __fp16 * v_prime_col_tiles; - __fp16 * delta_tiles; - __fp16 * delta_col_tiles; - __fp16 * o_intra_tiles; - __fp16 * d_row_tiles; + uint32_t ik3, uint32_t ik1, + uint32_t iv3, uint32_t iv1, + uint32_t t_chunk, + uint32_t chunk_size, + uint32_t S_v +) { + const dma_addr_t q_dma = q->data + (iq3 * q->nb[3] + t_chunk * q->nb[2] + iq1 * q->nb[1]); + const dma_addr_t k_dma = k->data + (ik3 * k->nb[3] + t_chunk * k->nb[2] + ik1 * k->nb[1]); + const dma_addr_t v_dma = v->data + (iv3 * v->nb[3] + t_chunk * v->nb[2] + iv1 * v->nb[1]); - __fp16 * gamma; - float * lambda_init; - __fp16 * lambda_init_f16; - __fp16 * decay_m; - __fp16 * decay_a; + const uint32_t q_row_bytes = S_v * ((q->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float)); + const uint32_t k_row_bytes = S_v * ((k->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float)); + const uint32_t v_row_bytes = S_v * ((v->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float)); - HVX_Vector * rows_kk; - HVX_Vector * rows_qk; - HVX_Vector * rows_inv; - HVX_Vector * rows_a; + dma_queue_push(dma_q, dma_make_data(vtcm_q, q_dma), q_row_bytes, q->nb[2], q_row_bytes, chunk_size); + dma_queue_push(dma_q, dma_make_data(vtcm_k, k_dma), k_row_bytes, k->nb[2], k_row_bytes, chunk_size); + dma_queue_push(dma_q, dma_make_data(vtcm_v, v_dma), v_row_bytes, v->nb[2], v_row_bytes, chunk_size); +} - HVX_Vector * vtcm_m; - HVX_Vector * vtcm_tmp; +static inline void gdn_dma_push_chunk_gb( + dma_queue * dma_q, + float * vtcm_g_raw, + float * vtcm_b_raw, + const struct htp_tensor * g, + const struct htp_tensor * beta, + uint32_t iv3, + uint32_t iv1, + uint32_t t_chunk, + uint32_t chunk_size, + uint32_t n_batch +) { + const dma_addr_t g_dma = g->data + (iv3 * g->nb[3] + t_chunk * g->nb[2] + iv1 * g->nb[1]); + const dma_addr_t beta_dma = beta->data + (iv3 * beta->nb[3] + t_chunk * beta->nb[2] + iv1 * beta->nb[1]); + const uint32_t row_bytes = n_batch * sizeof(float); + const uint32_t dst_stride = (n_batch > 1) ? row_bytes + sizeof(float) : row_bytes; - uint32_t iv1; - uint32_t iv3; - uint32_t iq1; - uint32_t ik1; - uint32_t iq3; - uint32_t ik3; - dma_addr_t state_in_dma; - dma_addr_t state_out_dma; -}; + dma_queue_push(dma_q, dma_make_data(vtcm_g_raw, g_dma), dst_stride, g->nb[2], row_bytes, chunk_size); + dma_queue_push(dma_q, dma_make_data(vtcm_b_raw, beta_dma), dst_stride, beta->nb[2], row_bytes, chunk_size); +} + +static inline void gdn_pack_s_col_tiles( + __fp16 * restrict vtcm_s_col_tiles, + const float * restrict vtcm_s_state, + uint32_t S_v +) { + const uint32_t n_k_tiles = S_v >> 5; + const HVX_Vector v_scat_base = hvx_vmem(hmx_transpose_scatter_offsets); + const HVX_Vector v_scat_step = Q6_V_vsplat_R(4); + const size_t pair_region = (size_t) (2 * HMX_FP16_TILE_SIZE - 1); + + for (uint32_t r = 0; r < S_v; r += 2) { + const uint32_t ct = r >> 5; + const uint32_t local_r = r & 31u; + const HVX_Vector v_off0 = Q6_Vw_vadd_VwVw(v_scat_base, Q6_V_vsplat_R(local_r * 4)); + const HVX_Vector v_off1 = Q6_Vw_vadd_VwVw(v_off0, v_scat_step); + + __fp16 * tile_base = vtcm_s_col_tiles + (size_t) ct * n_k_tiles * HMX_FP16_TILE_N_ELMS; + const float * s0 = vtcm_s_state + (r + 0) * S_v; + const float * s1 = vtcm_s_state + (r + 1) * S_v; + + for (uint32_t d = 0; d < (S_v >> 6); ++d) { + const HVX_Vector v0 = hvx_vec_f32_to_f16(hvx_vmem(s0 + d * 64 + 0), hvx_vmem(s0 + d * 64 + 32)); + const HVX_Vector v1 = hvx_vec_f32_to_f16(hvx_vmem(s1 + d * 64 + 0), hvx_vmem(s1 + d * 64 + 32)); + Q6_vscatter_RMVwV((size_t) tile_base, pair_region, v_off0, v0); + Q6_vscatter_RMVwV((size_t) tile_base, pair_region, v_off1, v1); + tile_base += 2 * HMX_FP16_TILE_N_ELMS; + } + } + hvx_gather_sync(vtcm_s_col_tiles); +} static inline void gdn_init_head_ptrs( struct htp_gdn_head_ptrs * head, @@ -1600,6 +2438,7 @@ static inline void gdn_init_head_ptrs( uint32_t h, uint32_t base_iv1, uint32_t iv3, + uint32_t is3, const struct htp_tensor * q, const struct htp_tensor * k, const struct htp_tensor * v, @@ -1612,61 +2451,54 @@ static inline void gdn_init_head_ptrs( uint32_t n_tokens, uint32_t chunk_size ) { + (void) v; const size_t dma_scalar_sz = hex_round_up(chunk_size * sizeof(float), 128); const size_t decay_sz = 64 * 64 * sizeof(__fp16); const size_t row_vecs_sz = 64 * 128; head->s_state = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_s_state + h * L->state_f32_bytes); - head->s_f16 = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_s_f16 + h * L->state_f16_bytes); head->s_col_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_s_col_tiles + h * L->state_tiles_bytes); - head->s_update_f32 = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_s_update_f32 + h * L->state_f32_bytes); head->s_update_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_s_update_tiles + h * L->state_tiles_bytes); head->q_f32[0] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_q_f32[0] + h * L->dma_chunk_bytes); - head->q_f32[1] = L->pipeline ? VTCM_LAYOUT_PTR(float, vtcm_base, L->off_q_f32[1] + h * L->dma_chunk_bytes) : head->q_f32[0]; + head->q_f32[1] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_q_f32[1] + h * L->dma_chunk_bytes); head->k_f32[0] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_k_f32[0] + h * L->dma_chunk_bytes); - head->k_f32[1] = L->pipeline ? VTCM_LAYOUT_PTR(float, vtcm_base, L->off_k_f32[1] + h * L->dma_chunk_bytes) : head->k_f32[0]; + head->k_f32[1] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_k_f32[1] + h * L->dma_chunk_bytes); head->v_f32[0] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_v_f32[0] + h * L->dma_chunk_bytes); - head->v_f32[1] = L->pipeline ? VTCM_LAYOUT_PTR(float, vtcm_base, L->off_v_f32[1] + h * L->dma_chunk_bytes) : head->v_f32[0]; + head->v_f32[1] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_v_f32[1] + h * L->dma_chunk_bytes); head->g_f32[0] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_g_f32[0] + h * dma_scalar_sz); - head->g_f32[1] = L->pipeline ? VTCM_LAYOUT_PTR(float, vtcm_base, L->off_g_f32[1] + h * dma_scalar_sz) : head->g_f32[0]; + head->g_f32[1] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_g_f32[1] + h * dma_scalar_sz); head->b_f32[0] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_b_f32[0] + h * dma_scalar_sz); - head->b_f32[1] = L->pipeline ? VTCM_LAYOUT_PTR(float, vtcm_base, L->off_b_f32[1] + h * dma_scalar_sz) : head->b_f32[0]; + head->b_f32[1] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_b_f32[1] + h * dma_scalar_sz); head->o_f32[0] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_o_f32[0] + h * L->dma_chunk_bytes); - head->o_f32[1] = L->pipeline ? VTCM_LAYOUT_PTR(float, vtcm_base, L->off_o_f32[1] + h * L->dma_chunk_bytes) : head->o_f32[0]; - - head->v_inter_f32 = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_v_inter_f32 + h * L->dma_chunk_bytes); - head->o_inter_f32 = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_o_inter_f32 + h * L->dma_chunk_bytes); - head->o_intra_f32 = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_o_intra_f32 + h * L->dma_chunk_bytes); - - head->k_f16 = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_f16 + h * L->act_f16_bytes); - head->v_prime_f16 = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_v_prime_f16 + h * L->act_f16_bytes); - head->delta_f16 = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_delta_f16 + h * L->act_f16_bytes); - head->d_f16 = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_d_f16 + h * L->act_f16_bytes); - - head->q_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_q_row_tiles + h * L->tile_64xSv_bytes); - head->q_prime_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_q_prime_row_tiles + h * L->tile_64xSv_bytes); - head->k_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_row_tiles + h * L->tile_64xSv_bytes); - head->k_col_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_col_tiles + h * L->tile_64xSv_bytes); - head->k_prime_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_prime_row_tiles + h * L->tile_64xSv_bytes); - head->k_col_tiles_64x128 = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_col_tiles_64x128 + h * L->tile_64xSv_bytes); - head->kk_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_kk_tiles + h * L->tile_64x64_bytes); - head->qk_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_qk_tiles + h * L->tile_64x64_bytes); - head->v_inter_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_v_inter_tiles + h * L->tile_64xSv_bytes); - head->o_inter_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_o_inter_tiles + h * L->tile_64xSv_bytes); - head->inv_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_inv_row_tiles + h * L->tile_64x64_bytes); - head->a_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_a_row_tiles + h * L->tile_64x64_bytes); - head->v_prime_col_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_v_prime_col_tiles + h * L->tile_64xSv_bytes); - head->delta_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_delta_tiles + h * L->tile_64xSv_bytes); - head->delta_col_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_delta_col_tiles + h * L->tile_64xSv_bytes); - head->o_intra_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_o_intra_tiles + h * L->tile_64xSv_bytes); - head->d_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_d_row_tiles + h * L->tile_64xSv_bytes); + head->o_f32[1] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_o_f32[1] + h * L->dma_chunk_bytes); + + head->k_f16 = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_f16 + h * L->act_f16_bytes); + + head->q_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_q_row_tiles + h * L->tile_64xSv_bytes); + head->q_prime_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_q_prime_row_tiles + h * L->tile_64xSv_bytes); + head->k_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_row_tiles + h * L->tile_64xSv_bytes); + head->k_col_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_col_tiles + h * L->tile_64xSv_bytes); + head->k_prime_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_prime_row_tiles + h * L->tile_64xSv_bytes); + head->k_col_tiles_64x128[0] = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_col_tiles_64x128[0] + h * L->tile_64xSv_bytes); + head->k_col_tiles_64x128[1] = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_k_col_tiles_64x128[1] + h * L->tile_64xSv_bytes); + head->kk_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_kk_tiles + h * L->tile_64x64_bytes); + head->qk_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_qk_tiles + h * L->tile_64x64_bytes); + head->v_inter_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_v_inter_tiles + h * L->tile_64xSv_bytes); + head->o_inter_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_o_inter_tiles + h * L->tile_64xSv_bytes); + head->inv_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_inv_row_tiles + h * L->tile_64x64_bytes); + head->a_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_a_row_tiles + h * L->tile_64x64_bytes); + head->v_prime_col_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_v_prime_col_tiles + h * L->tile_64xSv_bytes); + head->delta_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_delta_tiles + h * L->tile_64xSv_bytes); + head->o_intra_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_o_intra_tiles + h * L->tile_64xSv_bytes); + head->d_row_tiles = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_d_row_tiles + h * L->tile_64xSv_bytes); head->gamma = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_gamma + h * dma_scalar_sz); head->lambda_init_f16 = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_gamma + h * dma_scalar_sz + 128); - head->lambda_init = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_lambda_init + h * dma_scalar_sz); - head->decay_m = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_decay_m + h * decay_sz); - head->decay_a = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_decay_a + h * decay_sz); + head->lambda_init[0] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_lambda_init[0] + h * dma_scalar_sz); + head->lambda_init[1] = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_lambda_init[1] + h * dma_scalar_sz); + head->decay_m = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_decay_m + h * decay_sz); + head->decay_a = VTCM_LAYOUT_PTR(__fp16, vtcm_base, L->off_decay_a + h * decay_sz); head->rows_kk = VTCM_LAYOUT_PTR(HVX_Vector, vtcm_base, L->off_rows_kk + h * row_vecs_sz); head->rows_qk = VTCM_LAYOUT_PTR(HVX_Vector, vtcm_base, L->off_rows_qk + h * row_vecs_sz); @@ -1684,38 +2516,90 @@ static inline void gdn_init_head_ptrs( head->ik3 = fastdiv(head->iv3, &kparams->div_rk3); head->state_in_dma = state->data + - ((uint64_t) head->iv3 * kparams->state_seq_stride + (uint64_t) head->iv1 * S_v * S_v) * sizeof(float); + ((size_t) is3 * kparams->state_seq_stride + (size_t) head->iv1 * S_v * S_v) * sizeof(float); head->state_out_dma = dst_cache ? - (dst_cache->data + ((uint64_t) head->iv3 * H + head->iv1) * S_v * S_v * sizeof(float)) : - (dst->data + ((uint64_t) S_v * H * n_tokens * kparams->n_seqs + (uint64_t) (head->iv3 * H + head->iv1) * S_v * S_v) * sizeof(float)); + (dst_cache->data + (head->iv3 * H + head->iv1) * S_v * S_v * sizeof(float)) : + (dst->data + (S_v * H * n_tokens * kparams->n_seqs + (head->iv3 * H + head->iv1) * S_v * S_v) * sizeof(float)); } -struct htp_gdn_batch_context { - struct htp_gdn_head_ptrs * heads; - const float * vtcm_g_raw; - const float * vtcm_b_raw; - uint32_t curr_buf; - uint32_t c; - uint32_t n_batch; - uint32_t S_v; - float scale; - struct htp_ops_context * octx; - const struct htp_gdn_kernel_params * kparams; -}; - -static void gdn_hvx_replay_init_state_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { +static void gdn_hvx_prologue_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_batch_context * bctx = (struct htp_gdn_batch_context *) data; + struct htp_ops_context * octx = bctx->octx; + const struct htp_gdn_kernel_params * kparams = bctx->kparams; + struct htp_thread_trace * tr = th->trace; + dma_queue * dma_q = th->dma_q; + struct htp_gdn_head_ptrs * head = &bctx->heads[i]; + + const struct htp_tensor * q = octx->src[0]; + const struct htp_tensor * k = octx->src[1]; + const struct htp_tensor * v = octx->src[2]; + const struct htp_tensor * g = octx->src[3]; + const struct htp_tensor * beta = octx->src[4]; + + const uint32_t S_v = bctx->S_v; + const uint32_t chunk_size = kparams->chunk_size; + const uint32_t n_tokens = kparams->n_tokens; + const uint32_t n_chunks = kparams->n_chunks; - 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); + dma_queue_push(dma_q, dma_make_data(head->s_state, head->state_in_dma), + S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v); + + if (bctx->replay) { + dma_queue_pop(dma_q); + const int32_t raw_n_rep = bctx->n_rep_data[head->iv3]; + const uint32_t n_steps = raw_n_rep <= 0 ? 0 : hex_smin((uint32_t) raw_n_rep, bctx->n_pend); + if (n_steps > 0) { + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, 0); + gdn_replay_f32(octx, dma_q, head->s_state, + head->k_f32[0], head->v_f32[0], head->g_f32[0], head->b_f32[0], + head->vtcm_m, chunk_size, + head->ik1, head->iv1, head->iv3, n_steps, bctx->n_pend, + kparams->kda != 0, S_v); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, 0); + } + if (bctx->keep) { + dma_queue_push(dma_q, dma_make_data(head->state_out_dma, head->s_state), + S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v); + dma_queue_pop(dma_q); + } + } + + const uint32_t chunk0_tokens = hex_smin(chunk_size, n_tokens); + gdn_dma_push_chunk_inputs(dma_q, head->q_f32[0], head->k_f32[0], head->v_f32[0], + q, k, v, head->iq3, head->iq1, head->ik3, head->ik1, + head->iv3, head->iv1, 0u, chunk0_tokens, S_v); + if (i == 0u) { + gdn_dma_push_chunk_gb(dma_q, bctx->vtcm_g_raw[0], bctx->vtcm_b_raw[0], + g, beta, bctx->iv3, bctx->head_in_seq, 0u, chunk0_tokens, bctx->n_batch); + } + if (!bctx->replay) { + dma_queue_pop(dma_q); + } + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, 0); + gdn_pack_s_col_tiles(head->s_col_tiles, head->s_state, S_v); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, 0); + + dma_queue_pop(dma_q); + dma_queue_pop(dma_q); + dma_queue_pop(dma_q); + if (i == 0u) { + dma_queue_pop(dma_q); + dma_queue_pop(dma_q); + } + + if (n_chunks > 1u) { + const uint32_t c1_tokens = hex_smin(chunk_size, n_tokens - chunk_size); + gdn_dma_push_chunk_inputs(dma_q, head->q_f32[1], head->k_f32[1], head->v_f32[1], + q, k, v, head->iq3, head->iq1, head->ik3, head->ik1, + head->iv3, head->iv1, chunk_size, c1_tokens, S_v); + if (i == 0u) { + gdn_dma_push_chunk_gb(dma_q, bctx->vtcm_g_raw[1], bctx->vtcm_b_raw[1], + g, beta, bctx->iv3, bctx->head_in_seq, chunk_size, c1_tokens, bctx->n_batch); + } + } } static inline __attribute__((unused)) HVX_Vector hvx_clamp_neg20_0(HVX_Vector v, HVX_Vector v_zero, HVX_Vector v_neg20) { @@ -1753,38 +2637,55 @@ static void gdn_hvx_phase1a_worker(const htp_thread_t * th, unsigned int n, unsi const uint32_t curr_buf = bctx->curr_buf; const uint32_t S_v = bctx->S_v; const uint32_t n_batch = bctx->n_batch; + const float * vtcm_g_raw = bctx->vtcm_g_raw[curr_buf]; + const float * vtcm_b_raw = bctx->vtcm_b_raw[curr_buf]; if (n_batch == 1) { - hvx_vmem(head->g_f32[curr_buf] + 0) = hvx_vmem(bctx->vtcm_g_raw + 0); - hvx_vmem(head->g_f32[curr_buf] + 32) = hvx_vmem(bctx->vtcm_g_raw + 32); - hvx_vmem(head->b_f32[curr_buf] + 0) = hvx_vmem(bctx->vtcm_b_raw + 0); - hvx_vmem(head->b_f32[curr_buf] + 32) = hvx_vmem(bctx->vtcm_b_raw + 32); + hvx_vmem(head->g_f32[curr_buf] + 0) = hvx_vmem(vtcm_g_raw + 0); + hvx_vmem(head->g_f32[curr_buf] + 32) = hvx_vmem(vtcm_g_raw + 32); + hvx_vmem(head->b_f32[curr_buf] + 0) = hvx_vmem(vtcm_b_raw + 0); + hvx_vmem(head->b_f32[curr_buf] + 32) = hvx_vmem(vtcm_b_raw + 32); } else { const uint32_t vtcm_stride = (n_batch + 1) * sizeof(float); const HVX_Vector vv = hvx_vec_gather_offsets_w(vtcm_stride); - const size_t rt_g = (size_t) ((const uint8_t *) bctx->vtcm_g_raw + i * sizeof(float)); - const size_t rt_b = (size_t) ((const uint8_t *) bctx->vtcm_b_raw + i * sizeof(float)); - const size_t mu = 64 * vtcm_stride; + const size_t rt_g = (size_t) ((const uint8_t *) vtcm_g_raw + i * sizeof(float)); + const size_t rt_b = (size_t) ((const uint8_t *) vtcm_b_raw + i * sizeof(float)); + const size_t mu = 32 * vtcm_stride - 1; Q6_vgather_ARMVw((HVX_Vector *) (head->g_f32[curr_buf] + 0), rt_g, mu, vv); Q6_vgather_ARMVw((HVX_Vector *) (head->g_f32[curr_buf] + 32), rt_g + 32 * vtcm_stride, mu, vv); Q6_vgather_ARMVw((HVX_Vector *) (head->b_f32[curr_buf] + 0), rt_b, mu, vv); Q6_vgather_ARMVw((HVX_Vector *) (head->b_f32[curr_buf] + 32), rt_b + 32 * vtcm_stride, mu, vv); + hvx_gather_sync(head->b_f32[curr_buf] + 32); } const uint32_t t_chunk = bctx->c * 64; const uint32_t valid_tokens = hex_smin(64, bctx->kparams->n_tokens - t_chunk); if (valid_tokens < 64) { - for (uint32_t t = valid_tokens; t < 64; ++t) { - head->g_f32[curr_buf][t] = 0.0f; - head->b_f32[curr_buf][t] = 0.0f; - } const HVX_Vector vzero = Q6_V_vzero(); + if (valid_tokens <= 32) { + const HVX_VectorPred mask = Q6_Q_vsetq2_R(valid_tokens * sizeof(float)); + hvx_vmem(head->g_f32[curr_buf] + 0) = Q6_V_vand_QV(mask, hvx_vmem(head->g_f32[curr_buf] + 0)); + hvx_vmem(head->b_f32[curr_buf] + 0) = Q6_V_vand_QV(mask, hvx_vmem(head->b_f32[curr_buf] + 0)); + hvx_vmem(head->g_f32[curr_buf] + 32) = vzero; + hvx_vmem(head->b_f32[curr_buf] + 32) = vzero; + } else { + const HVX_VectorPred mask = Q6_Q_vsetq2_R((valid_tokens - 32) * sizeof(float)); + hvx_vmem(head->g_f32[curr_buf] + 32) = Q6_V_vand_QV(mask, hvx_vmem(head->g_f32[curr_buf] + 32)); + hvx_vmem(head->b_f32[curr_buf] + 32) = Q6_V_vand_QV(mask, hvx_vmem(head->b_f32[curr_buf] + 32)); + } + const uint32_t q_words = (bctx->octx->src[0]->type == HTP_TYPE_F16) ? (S_v / 2) : S_v; + const uint32_t k_words = (bctx->octx->src[1]->type == HTP_TYPE_F16) ? (S_v / 2) : S_v; + const uint32_t v_words = (bctx->octx->src[2]->type == HTP_TYPE_F16) ? (S_v / 2) : S_v; for (uint32_t t = valid_tokens; t < 64; ++t) { - for (uint32_t j = 0; j < S_v; j += 32) { - hvx_vmem(head->q_f32[curr_buf] + t * S_v + j) = vzero; - hvx_vmem(head->k_f32[curr_buf] + t * S_v + j) = vzero; - hvx_vmem(head->v_f32[curr_buf] + t * S_v + j) = vzero; + for (uint32_t j = 0; j < q_words; j += 32) { + hvx_vmem(head->q_f32[curr_buf] + t * q_words + j) = vzero; + } + for (uint32_t j = 0; j < k_words; j += 32) { + hvx_vmem(head->k_f32[curr_buf] + t * k_words + j) = vzero; + } + for (uint32_t j = 0; j < v_words; j += 32) { + hvx_vmem(head->v_f32[curr_buf] + t * v_words + j) = vzero; } } } @@ -1804,13 +2705,20 @@ static void gdn_hvx_phase1a_worker(const htp_thread_t * th, unsigned int n, unsi HVX_Vector v_l0 = hvx_vec_exp_f32(hvx_clamp_neg20_0(v_gamma0, v_zero, v_neg20)); HVX_Vector v_l1 = hvx_vec_exp_f32(hvx_clamp_neg20_0(v_gamma1, v_zero, v_neg20)); - hvx_vmem(head->lambda_init + 0) = v_l0; - hvx_vmem(head->lambda_init + 32) = v_l1; - hvx_vmem(head->lambda_init_f16) = hvx_vec_f32_to_f16(v_l0, v_l1); + hvx_vmem(head->lambda_init[curr_buf] + 0) = v_l0; + hvx_vmem(head->lambda_init[curr_buf] + 32) = v_l1; + hvx_vmem(head->lambda_init_f16) = hvx_vec_f32_to_f16(v_l0, v_l1); - gdn_f32_to_hmx_row_tiles_and_f16(head->k_row_tiles, head->k_prime_row_tiles, head->k_f16, - head->k_f32[curr_buf], head->lambda_init_f16, 64, S_v); - hmx_interleave_rows_to_tiles(head->k_col_tiles, head->k_f16, 64, S_v, S_v, 0, 64); + if (bctx->octx->src[1]->type == HTP_TYPE_F16) { + const __fp16 * k_f16 = (const __fp16 *) head->k_f32[curr_buf]; + gdn_f16_to_hmx_row_tiles(head->k_row_tiles, head->k_prime_row_tiles, + k_f16, head->lambda_init_f16, 64, S_v); + hmx_interleave_rows_to_tiles(head->k_col_tiles, k_f16, 64, S_v, S_v, 0, 64); + } else { + gdn_f32_to_hmx_row_tiles_and_f16(head->k_row_tiles, head->k_prime_row_tiles, head->k_f16, + head->k_f32[curr_buf], head->lambda_init_f16, 64, S_v, true); + hmx_interleave_rows_to_tiles(head->k_col_tiles, head->k_f16, 64, S_v, S_v, 0, 64); + } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_GDN_PREP, info); } @@ -1826,13 +2734,20 @@ static void gdn_hvx_phase1b_worker(const htp_thread_t * th, unsigned int n, unsi const uint32_t curr_buf = bctx->curr_buf; const uint32_t S_v = bctx->S_v; - gdn_f32_to_hmx_row_tiles_and_f16(head->q_row_tiles, head->q_prime_row_tiles, NULL, - head->q_f32[curr_buf], head->lambda_init_f16, 64, S_v); + if (bctx->octx->src[0]->type == HTP_TYPE_F16) { + gdn_f16_to_hmx_row_tiles(head->q_row_tiles, head->q_prime_row_tiles, + (const __fp16 *) head->q_f32[curr_buf], head->lambda_init_f16, 64, S_v); + } else { + gdn_f32_to_hmx_row_tiles_and_f16(head->q_row_tiles, head->q_prime_row_tiles, NULL, + head->q_f32[curr_buf], head->lambda_init_f16, 64, S_v, false); + } - hmx_interleave_cols_to_tiles(head->k_col_tiles_64x128, head->k_f16, 64, S_v, S_v, 2, 0, 64); + const __fp16 * k_f16_src = (bctx->octx->src[1]->type == HTP_TYPE_F16) + ? (const __fp16 *) head->k_f32[curr_buf] + : head->k_f16; + hmx_interleave_cols_to_tiles(head->k_col_tiles_64x128[curr_buf], k_f16_src, 64, S_v, S_v, 2, 0, 64); - const uint16_t * gamma_u16 = (const uint16_t *) head->gamma; - const HVX_Vector v_gamma = hvx_vmem(head->gamma); + const HVX_Vector v_gamma = hvx_vmem(head->gamma); const HVX_Vector v_zero_f16 = Q6_V_vzero(); const HVX_Vector v_neg20_f16 = hvx_vec_splat_f16(-20.0f); @@ -1846,8 +2761,8 @@ static void gdn_hvx_phase1b_worker(const htp_thread_t * th, unsigned int n, unsi uint32_t t0 = t; uint32_t t1 = t + 1; - HVX_Vector v_gamma_t0 = Q6_Vh_vsplat_R(gamma_u16[t0]); - HVX_Vector v_gamma_t1 = Q6_Vh_vsplat_R(gamma_u16[t1]); + HVX_Vector v_gamma_t0 = Q6_Vh_vsplat_R(gdn_hvx_extract_u16(v_gamma, t0)); + HVX_Vector v_gamma_t1 = Q6_Vh_vsplat_R(gdn_hvx_extract_u16(v_gamma, t1)); HVX_Vector diff0 = hvx_vec_sub_f16_f16(v_gamma_t0, v_gamma); HVX_Vector diff1 = hvx_vec_sub_f16_f16(v_gamma_t1, v_gamma); @@ -1864,8 +2779,8 @@ static void gdn_hvx_phase1b_worker(const htp_thread_t * th, unsigned int n, unsi HVX_Vector diff_log2e0 = hvx_vec_mul_f16_f16(diff0, v_log2e_f16); HVX_Vector diff_log2e1 = hvx_vec_mul_f16_f16(diff1, v_log2e_f16); - HVX_Vector v_exp0 = hvx_vec_exp2_f16(diff_log2e0); - HVX_Vector v_exp1 = hvx_vec_exp2_f16(diff_log2e1); + HVX_Vector v_exp0 = hvx_vec_exp2_neg_f16(diff_log2e0); + HVX_Vector v_exp1 = hvx_vec_exp2_neg_f16(diff_log2e1); HVX_VectorPred mask_lt0 = Q6_Q_vsetq2_R(2 * t0); HVX_VectorPred mask_lt1 = Q6_Q_vsetq2_R(2 * t1); @@ -1889,14 +2804,14 @@ static void gdn_hvx_phase1b_worker(const htp_thread_t * th, unsigned int n, unsi } { - HVX_Vector v_gamma_t = Q6_Vh_vsplat_R(gamma_u16[63]); + HVX_Vector v_gamma_t = Q6_Vh_vsplat_R(gdn_hvx_extract_u16(v_gamma, 63)); HVX_Vector diff = hvx_vec_sub_f16_f16(v_gamma_t, v_gamma); HVX_VectorPred p_gt = Q6_Q_vcmp_gt_VhfVhf(diff, v_zero_f16); diff = Q6_V_vmux_QVV(p_gt, v_zero_f16, diff); diff = Q6_Vhf_vmax_VhfVhf(v_neg20_f16, diff); HVX_Vector diff_log2e = hvx_vec_mul_f16_f16(diff, v_log2e_f16); - HVX_Vector v_exp = hvx_vec_exp2_f16(diff_log2e); + HVX_Vector v_exp = hvx_vec_exp2_neg_f16(diff_log2e); HVX_VectorPred mask_lt_t = Q6_Q_vsetq2_R(2 * 63); HVX_Vector v_m = Q6_V_vand_QV(mask_lt_t, v_exp); @@ -1930,7 +2845,8 @@ static void gdn_hvx_phase2_worker(const htp_thread_t * th, unsigned int n, unsig head->decay_m, head->b_f32[curr_buf], (__fp16 *) head->vtcm_m, - (__fp16 *) head->vtcm_m + HMX_FP16_TILE_N_ELMS + (__fp16 *) head->vtcm_m + HMX_FP16_TILE_N_ELMS, + head->rows_inv ); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_GDN_SOLVE, info); @@ -1938,38 +2854,87 @@ static void gdn_hvx_phase2_worker(const htp_thread_t * th, unsigned int n, unsig static void gdn_hvx_phase3_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; - const uint16_t info = (uint16_t) bctx->c; + struct htp_gdn_batch_context * bctx = (struct htp_gdn_batch_context *) data; + struct htp_ops_context * octx = bctx->octx; + const struct htp_gdn_kernel_params * kparams = bctx->kparams; + struct htp_thread_trace * tr = th->trace; + const uint32_t c = bctx->c; + const uint16_t info = (uint16_t) c; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_GDN_V_PREP, info); struct htp_gdn_head_ptrs * head = &bctx->heads[i]; - const uint32_t curr_buf = bctx->curr_buf; - const uint32_t S_v = bctx->S_v; - - gdn_unpack_64xS_tiles_to_f32(head->v_inter_f32, head->v_inter_tiles, S_v); - - HVX_VectorAlias local_b[2]; - local_b[0].v = hvx_vmem(head->b_f32[curr_buf] + 0); - local_b[1].v = hvx_vmem(head->b_f32[curr_buf] + 32); - - for (uint32_t t = 0; t < 64; ++t) { - HVX_Vector vb = hvx_vec_splat_f32(local_b[t / 32].fp32[t % 32]); - for (uint32_t j = 0; j < S_v; j += 64) { - HVX_Vector vv0 = hvx_vmem(head->v_f32[curr_buf] + t * S_v + j + 0); - HVX_Vector vv1 = (j + 32 < S_v) ? hvx_vmem(head->v_f32[curr_buf] + t * S_v + j + 32) : Q6_V_vzero(); - HVX_Vector vi0 = hvx_vmem(head->v_inter_f32 + t * S_v + j + 0); - HVX_Vector vi1 = (j + 32 < S_v) ? hvx_vmem(head->v_inter_f32 + t * S_v + j + 32) : Q6_V_vzero(); - - HVX_Vector vp0 = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv0, vi0), vb); - HVX_Vector vp1 = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv1, vi1), vb); - - hvx_vmem(head->v_prime_f16 + t * S_v + j) = hvx_vec_f32_to_f16(vp0, vp1); + const uint32_t curr_buf = bctx->curr_buf; + const uint32_t S_v = bctx->S_v; + const uint32_t n_col_tiles = S_v >> 5; + const HVX_Vector v_b_lo = hvx_vmem(head->b_f32[curr_buf] + 0); + const HVX_Vector v_b_hi = hvx_vmem(head->b_f32[curr_buf] + 32); + + if (octx->src[2]->type == HTP_TYPE_F16) { + const __fp16 * v_f16 = (const __fp16 *) head->v_f32[curr_buf]; + for (uint32_t r = 0; r < 64; r += 2) { + const uint32_t r0 = r >> 5; + const uint32_t r1 = (r & 31u) >> 1; + const HVX_Vector v_b = r0 ? v_b_hi : v_b_lo; + const HVX_Vector vb0 = Q6_V_vsplat_R(Q6_R_vextract_VR(v_b, ((r + 0u) & 31u) * 4u)); + const HVX_Vector vb1 = Q6_V_vsplat_R(Q6_R_vextract_VR(v_b, ((r + 1u) & 31u) * 4u)); + + for (uint32_t d = 0; d < (S_v >> 6); ++d) { + const uint32_t c0 = 2 * d; + const HVX_Vector * t_vi0 = (const HVX_Vector *) (head->v_inter_tiles + (r0 * n_col_tiles + c0 + 0) * HMX_FP16_TILE_N_ELMS); + const HVX_Vector * t_vi1 = (const HVX_Vector *) (head->v_inter_tiles + (r0 * n_col_tiles + c0 + 1) * HMX_FP16_TILE_N_ELMS); + const HVX_VectorPair vp_vi = Q6_W_vdeal_VVR(t_vi1[r1], t_vi0[r1], -2); + + const HVX_VectorPair p_vi0 = hvx_vec_f16_to_f32(Q6_V_lo_W(vp_vi)); + const HVX_VectorPair p_vv0 = hvx_vec_f16_to_f32(hvx_vmem(v_f16 + (r + 0) * S_v + d * 64)); + const HVX_Vector vp0_lo = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(Q6_V_lo_W(p_vv0), Q6_V_lo_W(p_vi0)), vb0); + const HVX_Vector vp0_hi = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(Q6_V_hi_W(p_vv0), Q6_V_hi_W(p_vi0)), vb0); + + const HVX_VectorPair p_vi1 = hvx_vec_f16_to_f32(Q6_V_hi_W(vp_vi)); + const HVX_VectorPair p_vv1 = hvx_vec_f16_to_f32(hvx_vmem(v_f16 + (r + 1) * S_v + d * 64)); + const HVX_Vector vp1_lo = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(Q6_V_lo_W(p_vv1), Q6_V_lo_W(p_vi1)), vb1); + const HVX_Vector vp1_hi = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(Q6_V_hi_W(p_vv1), Q6_V_hi_W(p_vi1)), vb1); + + HVX_Vector * t_vp0 = (HVX_Vector *) (head->v_prime_col_tiles + ((c0 + 0) * 2 + r0) * HMX_FP16_TILE_N_ELMS); + HVX_Vector * t_vp1 = (HVX_Vector *) (head->v_prime_col_tiles + ((c0 + 1) * 2 + r0) * HMX_FP16_TILE_N_ELMS); + t_vp0[r1] = hvx_vec_f32_to_f16_shuff(vp0_lo, vp1_lo); + t_vp1[r1] = hvx_vec_f32_to_f16_shuff(vp0_hi, vp1_hi); + } + } + } else { + const float * v_f32 = head->v_f32[curr_buf]; + for (uint32_t r = 0; r < 64; r += 2) { + const uint32_t r0 = r >> 5; + const uint32_t r1 = (r & 31u) >> 1; + const HVX_Vector v_b = r0 ? v_b_hi : v_b_lo; + const HVX_Vector vb0 = Q6_V_vsplat_R(Q6_R_vextract_VR(v_b, ((r + 0u) & 31u) * 4u)); + const HVX_Vector vb1 = Q6_V_vsplat_R(Q6_R_vextract_VR(v_b, ((r + 1u) & 31u) * 4u)); + + for (uint32_t d = 0; d < (S_v >> 6); ++d) { + const uint32_t c0 = 2 * d; + const HVX_Vector * t_vi0 = (const HVX_Vector *) (head->v_inter_tiles + (r0 * n_col_tiles + c0 + 0) * HMX_FP16_TILE_N_ELMS); + const HVX_Vector * t_vi1 = (const HVX_Vector *) (head->v_inter_tiles + (r0 * n_col_tiles + c0 + 1) * HMX_FP16_TILE_N_ELMS); + const HVX_VectorPair vp_vi = Q6_W_vdeal_VVR(t_vi1[r1], t_vi0[r1], -2); + + const HVX_VectorPair p_vi0 = hvx_vec_f16_to_f32(Q6_V_lo_W(vp_vi)); + const HVX_Vector vv0_lo = hvx_vmem(v_f32 + (r + 0) * S_v + d * 64 + 0); + const HVX_Vector vv0_hi = hvx_vmem(v_f32 + (r + 0) * S_v + d * 64 + 32); + const HVX_Vector vp0_lo = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv0_lo, Q6_V_lo_W(p_vi0)), vb0); + const HVX_Vector vp0_hi = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv0_hi, Q6_V_hi_W(p_vi0)), vb0); + + const HVX_VectorPair p_vi1 = hvx_vec_f16_to_f32(Q6_V_hi_W(vp_vi)); + const HVX_Vector vv1_lo = hvx_vmem(v_f32 + (r + 1) * S_v + d * 64 + 0); + const HVX_Vector vv1_hi = hvx_vmem(v_f32 + (r + 1) * S_v + d * 64 + 32); + const HVX_Vector vp1_lo = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv1_lo, Q6_V_lo_W(p_vi1)), vb1); + const HVX_Vector vp1_hi = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(vv1_hi, Q6_V_hi_W(p_vi1)), vb1); + + HVX_Vector * t_vp0 = (HVX_Vector *) (head->v_prime_col_tiles + ((c0 + 0) * 2 + r0) * HMX_FP16_TILE_N_ELMS); + HVX_Vector * t_vp1 = (HVX_Vector *) (head->v_prime_col_tiles + ((c0 + 1) * 2 + r0) * HMX_FP16_TILE_N_ELMS); + t_vp0[r1] = hvx_vec_f32_to_f16_shuff(vp0_lo, vp1_lo); + t_vp1[r1] = hvx_vec_f32_to_f16_shuff(vp0_hi, vp1_hi); + } } } - hmx_interleave_cols_to_tiles(head->v_prime_col_tiles, head->v_prime_f16, 64, S_v, S_v, 2, 0, 64); - gdn_unpack_64x64_tiles_to_vectors(head->rows_qk, head->qk_tiles); for (uint32_t t = 0; t < 64; ++t) { HVX_Vector v_decay_a = hvx_vmem(head->decay_a + t * 64); @@ -1978,6 +2943,35 @@ static void gdn_hvx_phase3_worker(const htp_thread_t * th, unsigned int n, unsig gdn_pack_64x64_vectors_to_tiles(head->a_row_tiles, head->rows_a); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_GDN_V_PREP, info); + + dma_queue * dma_q = th->dma_q; + const uint32_t n_chunks = kparams->n_chunks; + if (c + 1u < n_chunks) { + dma_queue_pop(dma_q); + dma_queue_pop(dma_q); + dma_queue_pop(dma_q); + if (i == 0u) { + dma_queue_pop(dma_q); + dma_queue_pop(dma_q); + } + } + if (c > 0u) { + dma_queue_pop(dma_q); + } + if (c + 2u < n_chunks) { + const uint32_t chunk_size = kparams->chunk_size; + const uint32_t t_c2 = (c + 2u) * chunk_size; + const uint32_t c2_tokens = hex_smin(chunk_size, kparams->n_tokens - t_c2); + gdn_dma_push_chunk_inputs(dma_q, head->q_f32[curr_buf], head->k_f32[curr_buf], head->v_f32[curr_buf], + octx->src[0], octx->src[1], octx->src[2], + head->iq3, head->iq1, head->ik3, head->ik1, + head->iv3, head->iv1, t_c2, c2_tokens, S_v); + if (i == 0u) { + gdn_dma_push_chunk_gb(dma_q, bctx->vtcm_g_raw[curr_buf], bctx->vtcm_b_raw[curr_buf], + octx->src[3], octx->src[4], bctx->iv3, bctx->head_in_seq, + t_c2, c2_tokens, bctx->n_batch); + } + } } static void gdn_hvx_phase4_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { @@ -1990,50 +2984,140 @@ static void gdn_hvx_phase4_worker(const htp_thread_t * th, unsigned int n, unsig struct htp_gdn_head_ptrs * head = &bctx->heads[i]; const uint32_t S_v = bctx->S_v; - gdn_unpack_64xS_tiles_to_f16(head->delta_f16, head->delta_tiles, S_v); - hmx_interleave_cols_to_tiles(head->delta_col_tiles, head->delta_f16, 64, S_v, S_v, 2, 0, 64); + const HVX_Vector v_decay_last = hvx_vmem(head->decay_a + 63 * 64); + const HVX_Vector vzero = Q6_V_vzero(); + HVX_Vector * restrict m = head->vtcm_m; + HVX_Vector * restrict tmp = head->vtcm_tmp; + + for (uint32_t col_half = 0; col_half < (S_v >> 6); ++col_half) { + const uint32_t r0_base = col_half * 2; + for (uint32_t c0 = 0; c0 < 2; ++c0) { + // delta_tiles is stored in col-major tile order [col_tile][row_tile] + const HVX_Vector * src0 = (const HVX_Vector *) (head->delta_tiles + ((2 * col_half + 0) * 2 + c0) * HMX_FP16_TILE_N_ELMS); + const HVX_Vector * src1 = (const HVX_Vector *) (head->delta_tiles + ((2 * col_half + 1) * 2 + c0) * HMX_FP16_TILE_N_ELMS); + + for (uint32_t r = 0; r < 16; ++r) { + const uint32_t s0 = c0 * 32 + 2 * r + 0; + const uint32_t s1 = c0 * 32 + 2 * r + 1; + const HVX_VectorPair vp = Q6_W_vdeal_VVR(src1[r], src0[r], -2); + + const HVX_Vector vs0 = Q6_Vh_vsplat_R(gdn_hvx_extract_u16(v_decay_last, s0)); + const HVX_Vector vs1 = Q6_Vh_vsplat_R(gdn_hvx_extract_u16(v_decay_last, s1)); + const HVX_VectorPred p_z0 = Q6_Q_vcmp_eq_VhVh(vs0, vzero); + const HVX_VectorPred p_z1 = Q6_Q_vcmp_eq_VhVh(vs1, vzero); + + m[2 * r + 0] = Q6_V_vmux_QVV(p_z0, vzero, hvx_vec_mul_f16_f16(Q6_V_lo_W(vp), vs0)); + m[2 * r + 1] = Q6_V_vmux_QVV(p_z1, vzero, hvx_vec_mul_f16_f16(Q6_V_hi_W(vp), vs1)); + } + + hvx_transpose_32x32_w_shuff_inplace(m, tmp); - const uint16_t * decay_last = (const uint16_t *) (head->decay_a + 63 * 64); - const HVX_Vector vzero = Q6_V_vzero(); + const uint32_t tile0_idx = (r0_base + 0) * 2 + c0; + const uint32_t tile1_idx = (r0_base + 1) * 2 + c0; + HVX_Vector * dst0 = (HVX_Vector *) (head->d_row_tiles + tile0_idx * HMX_FP16_TILE_N_ELMS); + HVX_Vector * dst1 = (HVX_Vector *) (head->d_row_tiles + tile1_idx * HMX_FP16_TILE_N_ELMS); - for (uint32_t s = 0; s < 64; ++s) { - HVX_Vector vs = Q6_Vh_vsplat_R(decay_last[s]); - HVX_VectorPred p_zero = Q6_Q_vcmp_eq_VhVh(vs, vzero); - for (uint32_t j = 0; j < S_v; j += 64) { - HVX_Vector vd = hvx_vmem(head->delta_f16 + s * S_v + j); - HVX_Vector prod = hvx_vec_mul_f16_f16(vd, vs); - hvx_vmem(head->d_f16 + s * S_v + j) = Q6_V_vmux_QVV(p_zero, vzero, prod); + for (uint32_t r = 0; r < 16; ++r) { + dst0[r] = m[r]; + dst1[r] = m[16 + r]; + } } } - gdn_pack_d_t_row_tiles(head->d_row_tiles, head->d_f16, S_v, head->vtcm_m, head->vtcm_tmp); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_GDN_D_PREP, info); } static void gdn_hvx_phase5_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; - const uint16_t info = (uint16_t) bctx->c; + struct htp_gdn_batch_context * bctx = (struct htp_gdn_batch_context *) data; + const struct htp_gdn_kernel_params * kparams = bctx->kparams; + const struct htp_tensor * dst = bctx->octx->dst; + struct htp_thread_trace * tr = th->trace; + const uint32_t c = bctx->c; + const uint16_t info = (uint16_t) c; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_GDN_OUT, info); struct htp_gdn_head_ptrs * head = &bctx->heads[i]; - const uint32_t curr_buf = bctx->curr_buf; - const uint32_t S_v = bctx->S_v; - const float scale = bctx->scale; - - gdn_unpack_64xS_tiles_to_f32(head->o_inter_f32, head->o_inter_tiles, S_v); - gdn_unpack_64xS_tiles_to_f32(head->o_intra_f32, head->o_intra_tiles, S_v); - - HVX_Vector vscale = hvx_vec_splat_f32(scale); - for (uint32_t j = 0; j < 64 * S_v / 32; ++j) { - HVX_Vector vi = hvx_vmem(head->o_inter_f32 + j * 32); - HVX_Vector va = hvx_vmem(head->o_intra_f32 + j * 32); - hvx_vmem(head->o_f32[curr_buf] + j * 32) = hvx_vec_mul_f32_f32(hvx_vec_add_f32_f32(vi, va), vscale); + const uint32_t curr_buf = bctx->curr_buf; + const uint32_t S_v = bctx->S_v; + const uint32_t n_col_tiles = S_v >> 5; + const HVX_Vector vscale = hvx_vec_splat_f32(bctx->scale); + + if (dst->type == HTP_TYPE_F16) { + __fp16 * o_f16 = (__fp16 *) head->o_f32[curr_buf]; + const HVX_Vector v_min = hvx_vec_splat_f32(-65504.0f); + const HVX_Vector v_max = hvx_vec_splat_f32(65504.0f); + + for (uint32_t r0 = 0; r0 < 2; ++r0) { + for (uint32_t d = 0; d < (S_v >> 6); ++d) { + const HVX_Vector * ti0 = (const HVX_Vector *) (head->o_inter_tiles + (r0 * n_col_tiles + 2 * d + 0) * HMX_FP16_TILE_N_ELMS); + const HVX_Vector * ti1 = (const HVX_Vector *) (head->o_inter_tiles + (r0 * n_col_tiles + 2 * d + 1) * HMX_FP16_TILE_N_ELMS); + const HVX_Vector * ta0 = (const HVX_Vector *) (head->o_intra_tiles + (r0 * n_col_tiles + 2 * d + 0) * HMX_FP16_TILE_N_ELMS); + const HVX_Vector * ta1 = (const HVX_Vector *) (head->o_intra_tiles + (r0 * n_col_tiles + 2 * d + 1) * HMX_FP16_TILE_N_ELMS); + + for (uint32_t r = 0; r < 16; ++r) { + const HVX_VectorPair vp_i = Q6_W_vdeal_VVR(ti1[r], ti0[r], -2); + const HVX_VectorPair vp_a = Q6_W_vdeal_VVR(ta1[r], ta0[r], -2); + + const HVX_VectorPair pi0 = hvx_vec_f16_to_f32(Q6_V_lo_W(vp_i)); + const HVX_VectorPair pa0 = hvx_vec_f16_to_f32(Q6_V_lo_W(vp_a)); + const HVX_Vector vo0_lo = gdn_clamp_f16_range_f32(hvx_vec_mul_f32_f32(hvx_vec_add_f32_f32(Q6_V_lo_W(pi0), Q6_V_lo_W(pa0)), vscale), v_min, v_max); + const HVX_Vector vo0_hi = gdn_clamp_f16_range_f32(hvx_vec_mul_f32_f32(hvx_vec_add_f32_f32(Q6_V_hi_W(pi0), Q6_V_hi_W(pa0)), vscale), v_min, v_max); + + const HVX_VectorPair pi1 = hvx_vec_f16_to_f32(Q6_V_hi_W(vp_i)); + const HVX_VectorPair pa1 = hvx_vec_f16_to_f32(Q6_V_hi_W(vp_a)); + const HVX_Vector vo1_lo = gdn_clamp_f16_range_f32(hvx_vec_mul_f32_f32(hvx_vec_add_f32_f32(Q6_V_lo_W(pi1), Q6_V_lo_W(pa1)), vscale), v_min, v_max); + const HVX_Vector vo1_hi = gdn_clamp_f16_range_f32(hvx_vec_mul_f32_f32(hvx_vec_add_f32_f32(Q6_V_hi_W(pi1), Q6_V_hi_W(pa1)), vscale), v_min, v_max); + + __fp16 * out0 = o_f16 + (r0 * 32 + 2 * r + 0) * S_v + d * 64; + __fp16 * out1 = o_f16 + (r0 * 32 + 2 * r + 1) * S_v + d * 64; + + hvx_vmem(out0) = hvx_vec_f32_to_f16(vo0_lo, vo0_hi); + hvx_vmem(out1) = hvx_vec_f32_to_f16(vo1_lo, vo1_hi); + } + } + } + } else { + float * o_f32 = head->o_f32[curr_buf]; + + for (uint32_t r0 = 0; r0 < 2; ++r0) { + for (uint32_t d = 0; d < (S_v >> 6); ++d) { + const HVX_Vector * ti0 = (const HVX_Vector *) (head->o_inter_tiles + (r0 * n_col_tiles + 2 * d + 0) * HMX_FP16_TILE_N_ELMS); + const HVX_Vector * ti1 = (const HVX_Vector *) (head->o_inter_tiles + (r0 * n_col_tiles + 2 * d + 1) * HMX_FP16_TILE_N_ELMS); + const HVX_Vector * ta0 = (const HVX_Vector *) (head->o_intra_tiles + (r0 * n_col_tiles + 2 * d + 0) * HMX_FP16_TILE_N_ELMS); + const HVX_Vector * ta1 = (const HVX_Vector *) (head->o_intra_tiles + (r0 * n_col_tiles + 2 * d + 1) * HMX_FP16_TILE_N_ELMS); + + for (uint32_t r = 0; r < 16; ++r) { + const HVX_VectorPair vp_i = Q6_W_vdeal_VVR(ti1[r], ti0[r], -2); + const HVX_VectorPair vp_a = Q6_W_vdeal_VVR(ta1[r], ta0[r], -2); + + const HVX_VectorPair pi0 = hvx_vec_f16_to_f32(Q6_V_lo_W(vp_i)); + const HVX_VectorPair pa0 = hvx_vec_f16_to_f32(Q6_V_lo_W(vp_a)); + const HVX_VectorPair pi1 = hvx_vec_f16_to_f32(Q6_V_hi_W(vp_i)); + const HVX_VectorPair pa1 = hvx_vec_f16_to_f32(Q6_V_hi_W(vp_a)); + + float * out0 = o_f32 + (r0 * 32 + 2 * r + 0) * S_v + d * 64; + float * out1 = o_f32 + (r0 * 32 + 2 * r + 1) * S_v + d * 64; + + hvx_vmem(out0 + 0) = hvx_vec_mul_f32_f32(hvx_vec_add_f32_f32(Q6_V_lo_W(pi0), Q6_V_lo_W(pa0)), vscale); + hvx_vmem(out0 + 32) = hvx_vec_mul_f32_f32(hvx_vec_add_f32_f32(Q6_V_hi_W(pi0), Q6_V_hi_W(pa0)), vscale); + hvx_vmem(out1 + 0) = hvx_vec_mul_f32_f32(hvx_vec_add_f32_f32(Q6_V_lo_W(pi1), Q6_V_lo_W(pa1)), vscale); + hvx_vmem(out1 + 32) = hvx_vec_mul_f32_f32(hvx_vec_add_f32_f32(Q6_V_hi_W(pi1), Q6_V_hi_W(pa1)), vscale); + } + } + } } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_GDN_OUT, info); + + const uint32_t chunk_size = kparams->chunk_size; + const uint32_t t_chunk = c * chunk_size; + const uint32_t valid_tokens = hex_smin(chunk_size, kparams->n_tokens - t_chunk); + const uint32_t row_out_bytes = S_v * ((dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float)); + const dma_addr_t attn_chunk_dma = dst->data + + ((size_t) head->iv3 * kparams->n_tokens * kparams->H + (size_t) t_chunk * kparams->H + head->iv1) * row_out_bytes; + dma_queue_push(th->dma_q, dma_make_data(attn_chunk_dma, head->o_f32[curr_buf]), + dst->nb[1], row_out_bytes, row_out_bytes, valid_tokens); } static void gdn_hvx_phase6_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { @@ -2044,29 +3128,74 @@ static void gdn_hvx_phase6_worker(const htp_thread_t * th, unsigned int n, unsig htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_GDN_STATE, info); struct htp_gdn_head_ptrs * head = &bctx->heads[i]; - const uint32_t S_v = bctx->S_v; - const uint32_t c = bctx->c; - const uint32_t n_chunks = bctx->kparams->n_chunks; + const uint32_t curr_buf = bctx->curr_buf; + const uint32_t S_v = bctx->S_v; + const uint32_t c = bctx->c; + const uint32_t n_chunks = bctx->kparams->n_chunks; + const uint32_t n_tiles = S_v >> 5; + const HVX_Vector v_l_final = hvx_vec_splat_f32(gdn_vtcm_load_f32(head->lambda_init[curr_buf], 63)); + const bool pack_next = (c + 1 < n_chunks); + const HVX_Vector v_scat_base = hvx_vmem(hmx_transpose_scatter_offsets); + const HVX_Vector v_scat_step = Q6_V_vsplat_R(4); + const size_t pair_region = (size_t) (2 * HMX_FP16_TILE_SIZE - 1); - gdn_unpack_SxS_tiles_to_f32(head->s_update_f32, head->s_update_tiles, S_v); - - HVX_VectorAlias last_lambda; - last_lambda.v = hvx_vmem(head->lambda_init + 32); - HVX_Vector v_l_final = hvx_vec_splat_f32(last_lambda.fp32[31]); + for (uint32_t r0 = 0; r0 < n_tiles; ++r0) { + for (uint32_t d = 0; d < (S_v >> 6); ++d) { + const HVX_Vector * t0 = (const HVX_Vector *) (head->s_update_tiles + (r0 * n_tiles + 2 * d + 0) * HMX_FP16_TILE_N_ELMS); + const HVX_Vector * t1 = (const HVX_Vector *) (head->s_update_tiles + (r0 * n_tiles + 2 * d + 1) * HMX_FP16_TILE_N_ELMS); + __fp16 * tile_base = head->s_col_tiles + (size_t) (r0 * n_tiles + 2 * d) * HMX_FP16_TILE_N_ELMS; - for (uint32_t j = 0; j < S_v * S_v / 32; ++j) { - HVX_Vector vs_old = hvx_vmem(head->s_state + j * 32); - HVX_Vector vsu = hvx_vmem(head->s_update_f32 + j * 32); - hvx_vmem(head->s_state + j * 32) = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(vs_old, v_l_final), vsu); + for (uint32_t r = 0; r < 16; ++r) { + const HVX_VectorPair vp01 = Q6_W_vdeal_VVR(t1[r], t0[r], -2); + const HVX_VectorPair p0 = hvx_vec_f16_to_f32(Q6_V_lo_W(vp01)); + const HVX_VectorPair p1 = hvx_vec_f16_to_f32(Q6_V_hi_W(vp01)); + + float * s0 = head->s_state + (r0 * 32 + 2 * r + 0) * S_v + d * 64; + float * s1 = head->s_state + (r0 * 32 + 2 * r + 1) * S_v + d * 64; + + const HVX_Vector ns0_lo = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmem(s0 + 0), v_l_final), Q6_V_lo_W(p0)); + const HVX_Vector ns0_hi = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmem(s0 + 32), v_l_final), Q6_V_hi_W(p0)); + const HVX_Vector ns1_lo = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmem(s1 + 0), v_l_final), Q6_V_lo_W(p1)); + const HVX_Vector ns1_hi = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(hvx_vmem(s1 + 32), v_l_final), Q6_V_hi_W(p1)); + + hvx_vmem(s0 + 0) = ns0_lo; + hvx_vmem(s0 + 32) = ns0_hi; + hvx_vmem(s1 + 0) = ns1_lo; + hvx_vmem(s1 + 32) = ns1_hi; + + if (pack_next) { + const HVX_Vector v_off0 = Q6_Vw_vadd_VwVw(v_scat_base, Q6_V_vsplat_R(2 * r * 4)); + const HVX_Vector v_off1 = Q6_Vw_vadd_VwVw(v_off0, v_scat_step); + const HVX_Vector v0_f16 = hvx_vec_f32_to_f16(ns0_lo, ns0_hi); + const HVX_Vector v1_f16 = hvx_vec_f32_to_f16(ns1_lo, ns1_hi); + Q6_vscatter_RMVwV((size_t) tile_base, pair_region, v_off0, v0_f16); + Q6_vscatter_RMVwV((size_t) tile_base, pair_region, v_off1, v1_f16); + } + } + } } - if (c + 1 < n_chunks) { - gdn_pack_s_col_tiles(head->s_col_tiles, head->s_f16, head->s_state, S_v); + if (pack_next) { + hvx_gather_sync(head->s_col_tiles); } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_GDN_STATE, info); } +static void gdn_hvx_epilogue_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_gdn_head_ptrs * head = &bctx->heads[i]; + dma_queue * dma_q = th->dma_q; + const uint32_t S_v = bctx->S_v; + + dma_queue_pop(dma_q); + if (!bctx->keep) { + dma_queue_push(dma_q, dma_make_data(head->state_out_dma, head->s_state), + S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v); + } + dma_queue_flush(dma_q); +} static int gated_delta_net_f32_hmx_chunked( struct htp_ops_context * octx, @@ -2074,12 +3203,17 @@ static int gated_delta_net_f32_hmx_chunked( uint32_t row_start, uint32_t nrows ) { + if (kparams->n_chunks == 0) { + return HTP_STATUS_OK; + } + const struct htp_tensor * q = octx->src[0]; const struct htp_tensor * k = octx->src[1]; const struct htp_tensor * v = octx->src[2]; - const struct htp_tensor * g = octx->src[3]; - const struct htp_tensor * beta = octx->src[4]; const struct htp_tensor * state = octx->src[5]; + const bool replay = gdn_has_replay(octx); + const struct htp_tensor * ids = replay ? NULL : octx->src[6]; + const struct htp_tensor * n_rep = replay ? octx->src[9] : NULL; const struct htp_tensor * dst = octx->dst; const struct htp_tensor * dst_cache = octx->dsts[1]; @@ -2089,265 +3223,195 @@ static int gated_delta_net_f32_hmx_chunked( const float scale = kparams->scale; 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; + const uint32_t n_pend = replay ? (uint32_t) octx->op_params[1] : 0; + const bool keep = replay && 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); + htp_gdn_hmx_vtcm_layout_build(&L, S_v, chunk_size, kparams->n_heads_batch, kparams->n_hvx); if (L.total_bytes > octx->ctx->vtcm_size) { return HTP_STATUS_VTCM_TOO_SMALL; } uint8_t * const vtcm_base = (uint8_t *) octx->ctx->vtcm_base; - - float * vtcm_g_raw[2] = { - VTCM_LAYOUT_PTR(float, vtcm_base, L.off_g_raw[0]), - L.pipeline ? VTCM_LAYOUT_PTR(float, vtcm_base, L.off_g_raw[1]) : VTCM_LAYOUT_PTR(float, vtcm_base, L.off_g_raw[0]) - }; - float * vtcm_b_raw[2] = { - VTCM_LAYOUT_PTR(float, vtcm_base, L.off_b_raw[0]), - L.pipeline ? VTCM_LAYOUT_PTR(float, vtcm_base, L.off_b_raw[1]) : VTCM_LAYOUT_PTR(float, vtcm_base, L.off_b_raw[0]) - }; + void * aux_buf = NULL; + const int aux_err = gdn_prepare_aux_data(octx, replay ? n_rep : ids, &aux_buf); + if (aux_err != HTP_STATUS_OK) { + return aux_err; + } + const void * ids_buf = replay ? NULL : aux_buf; + const int32_t * n_rep_buf = replay ? (const int32_t *) aux_buf : NULL; + const uint32_t ids_type = ids ? ids->type : 0; uint8_t * vtcm_scales_1 = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, L.off_scales_1); hmx_init_column_scales(vtcm_scales_1, Q6_V_vsplat_R(0x3c00)); hmx_queue_t hmx_q = octx->ctx->hmx_queue; - dma_queue * dma_q = octx->ctx->dma[0]; work_queue_t wp = octx->ctx->hvx_queue; struct htp_gdn_head_ptrs heads[8]; - struct htp_gdn_hmx_gemm_task gemm_tasks[8][9]; + + struct htp_gdn_batch_context bctx; + bctx.heads = heads; + bctx.vtcm_g_raw[0] = VTCM_LAYOUT_PTR(float, vtcm_base, L.off_g_raw[0]); + bctx.vtcm_g_raw[1] = VTCM_LAYOUT_PTR(float, vtcm_base, L.off_g_raw[1]); + bctx.vtcm_b_raw[0] = VTCM_LAYOUT_PTR(float, vtcm_base, L.off_b_raw[0]); + bctx.vtcm_b_raw[1] = VTCM_LAYOUT_PTR(float, vtcm_base, L.off_b_raw[1]); + bctx.hmx_scales = vtcm_scales_1; + bctx.n_rep_data = n_rep_buf; + bctx.n_pend = n_pend; + bctx.replay = replay; + bctx.keep = keep; + bctx.S_v = S_v; + bctx.scale = scale; + bctx.octx = octx; + bctx.kparams = kparams; uint32_t n_batch = 1; for (uint32_t r = row_start; r < row_start + nrows; r += n_batch) { const uint32_t head_in_seq = fastmodulo(r, H, &kparams->div_H); const uint32_t iv3 = fastdiv(r, &kparams->div_H); + const uint32_t is3 = gdn_read_seq_idx(ids_buf, ids_type, iv3); const uint32_t heads_left_in_seq = H - head_in_seq; const uint32_t heads_left_in_range = (row_start + nrows) - r; n_batch = hex_smin((uint32_t) kparams->n_heads_batch, hex_smin(heads_left_in_seq, heads_left_in_range)); for (uint32_t h = 0; h < n_batch; ++h) { - gdn_init_head_ptrs(&heads[h], &L, vtcm_base, h, head_in_seq, iv3, + gdn_init_head_ptrs(&heads[h], &L, vtcm_base, h, head_in_seq, iv3, is3, q, k, v, state, dst, dst_cache, kparams, S_v, H, n_tokens, chunk_size); } - struct htp_gdn_batch_context bctx; - bctx.heads = heads; - bctx.vtcm_g_raw = NULL; - bctx.vtcm_b_raw = NULL; - bctx.curr_buf = 0; - bctx.c = 0; - bctx.n_batch = n_batch; - bctx.S_v = S_v; - bctx.scale = scale; - bctx.octx = octx; - bctx.kparams = kparams; - - for (uint32_t h = 0; h < n_batch; ++h) { - dma_queue_push(dma_q, dma_make_data(heads[h].s_state, heads[h].state_in_dma), - 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 (n_chunks > 0) { - 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) { - gdn_dma_push_chunk_inputs(dma_q, heads[h].q_f32[0], heads[h].k_f32[0], heads[h].v_f32[0], - q, k, v, heads[h].iq3, heads[h].iq1, heads[h].ik3, heads[h].ik1, - heads[h].iv3, heads[h].iv1, 0, chunk0_tokens, S_v); - } - gdn_dma_push_chunk_gb(dma_q, vtcm_g_raw[0], vtcm_b_raw[0], g, beta, iv3, head_in_seq, 0, chunk0_tokens, n_batch); - } - - for (uint32_t c = 0; c < n_chunks; ++c) { - const uint32_t curr_buf = c & 1; - const uint32_t next_buf = (c + 1) & 1; - const uint32_t t_chunk = c * chunk_size; - - bctx.curr_buf = curr_buf; - bctx.c = c; - bctx.vtcm_g_raw = vtcm_g_raw[curr_buf]; - bctx.vtcm_b_raw = vtcm_b_raw[curr_buf]; - - for (uint32_t h = 0; h < n_batch; ++h) { - dma_queue_pop(dma_q); - dma_queue_pop(dma_q); - dma_queue_pop(dma_q); - } - dma_queue_pop(dma_q); - dma_queue_pop(dma_q); - - if (c + 1 < n_chunks) { - const uint32_t next_t_chunk = (c + 1) * chunk_size; - const uint32_t next_tokens = hex_smin(chunk_size, n_tokens - next_t_chunk); - for (uint32_t h = 0; h < n_batch; ++h) { - gdn_dma_push_chunk_inputs(dma_q, heads[h].q_f32[next_buf], heads[h].k_f32[next_buf], heads[h].v_f32[next_buf], - q, k, v, heads[h].iq3, heads[h].iq1, heads[h].ik3, heads[h].ik1, - heads[h].iv3, heads[h].iv1, next_t_chunk, next_tokens, S_v); - } - gdn_dma_push_chunk_gb(dma_q, vtcm_g_raw[next_buf], vtcm_b_raw[next_buf], - g, beta, iv3, head_in_seq, next_t_chunk, next_tokens, n_batch); - } - - if (c > 0) { - for (uint32_t h = 0; h < n_batch; ++h) { - dma_queue_pop(dma_q); - } - } - - work_queue_run(wp, gdn_hvx_phase1a_worker, &bctx, n_batch); + bctx.head_in_seq = head_in_seq; + bctx.iv3 = iv3; + bctx.n_batch = n_batch; - for (uint32_t h = 0; h < n_batch; ++h) { - htp_gdn_push_hmx_gemm_task(hmx_q, &gemm_tasks[h][0], heads[h].k_row_tiles, heads[h].k_col_tiles, heads[h].kk_tiles, 2, 2, n_sv_tiles, vtcm_scales_1); - } - for (uint32_t h = 0; h < n_batch; ++h) { - htp_gdn_push_hmx_gemm_task(hmx_q, &gemm_tasks[h][2], heads[h].k_prime_row_tiles, heads[h].s_col_tiles, heads[h].v_inter_tiles, 2, n_sv_tiles, n_sv_tiles, vtcm_scales_1); - } + work_queue_run(wp, gdn_hvx_prologue_worker, &bctx, n_batch); - work_queue_run(wp, gdn_hvx_phase1b_worker, &bctx, n_batch); + // Prologue: prepare chunk 0 (phase1a, KK, phase1b, QK + KS in-flight) + bctx.c = 0u; + bctx.curr_buf = 0u; + work_queue_run(wp, gdn_hvx_phase1a_worker, &bctx, n_batch); + hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_kk_worker, &bctx)); - for (uint32_t h = 0; h < n_batch; ++h) { - hmx_queue_pop(hmx_q); - } + work_queue_run(wp, gdn_hvx_phase1b_worker, &bctx, n_batch); + hmx_queue_pop(hmx_q); + hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_qk_worker, &bctx)); + hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_ks_worker, &bctx)); - for (uint32_t h = 0; h < n_batch; ++h) { - htp_gdn_push_hmx_gemm_task(hmx_q, &gemm_tasks[h][1], heads[h].q_row_tiles, heads[h].k_col_tiles, heads[h].qk_tiles, 2, 2, n_sv_tiles, vtcm_scales_1); - } - for (uint32_t h = 0; h < n_batch; ++h) { - htp_gdn_push_hmx_gemm_task(hmx_q, &gemm_tasks[h][3], heads[h].q_prime_row_tiles, heads[h].s_col_tiles, heads[h].o_inter_tiles, 2, n_sv_tiles, n_sv_tiles, vtcm_scales_1); - } + // Pipelined chunk loop: overlap chunk c tail with chunk c+1 prep + for (uint32_t c = 0u; c < n_chunks; ++c) { + const uint32_t curr_buf = c & 1u; + const uint32_t next_buf = (c + 1u) & 1u; + const bool has_next = (c + 1u < n_chunks); + // Step 1: HMX QK(c) + KS(c) || HVX phase2(c) + bctx.c = c; + bctx.curr_buf = curr_buf; work_queue_run(wp, gdn_hvx_phase2_worker, &bctx, n_batch); + hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_inv10_worker, &bctx)); + hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_qs_worker, &bctx)); + hmx_queue_pop(hmx_q); // QK(c) + hmx_queue_pop(hmx_q); // KS(c) - for (uint32_t h = 0; h < n_batch; ++h) { - hmx_queue_pop(hmx_q); - } - for (uint32_t h = 0; h < n_batch; ++h) { - hmx_queue_pop(hmx_q); - } - - for (uint32_t h = 0; h < n_batch; ++h) { - htp_gdn_push_hmx_gemm_task( - hmx_q, &gemm_tasks[h][7], - (__fp16 *) heads[h].vtcm_m, - heads[h].inv_row_tiles + 0 * HMX_FP16_TILE_N_ELMS, - (__fp16 *) heads[h].vtcm_tmp, - 1, 1, 1, vtcm_scales_1 - ); - } - for (uint32_t h = 0; h < n_batch; ++h) { - htp_gdn_push_hmx_gemm_task( - hmx_q, &gemm_tasks[h][8], - (__fp16 *) heads[h].vtcm_m + HMX_FP16_TILE_N_ELMS, - (__fp16 *) heads[h].vtcm_tmp, - heads[h].inv_row_tiles + 2 * HMX_FP16_TILE_N_ELMS, - 1, 1, 1, vtcm_scales_1 - ); - } - + // Step 2: HMX INV_10(c) + QS(c) || HVX phase3(c) + DMA pop(c+1)/push(c+2) work_queue_run(wp, gdn_hvx_phase3_worker, &bctx, n_batch); - - for (uint32_t h = 0; h < n_batch; ++h) { - hmx_queue_pop(hmx_q); - } - for (uint32_t h = 0; h < n_batch; ++h) { - hmx_queue_pop(hmx_q); - } - for (uint32_t h = 0; h < n_batch; ++h) { - hmx_queue_pop(hmx_q); - } - - for (uint32_t h = 0; h < n_batch; ++h) { - htp_gdn_push_hmx_gemm_task(hmx_q, &gemm_tasks[h][4], heads[h].inv_row_tiles, heads[h].v_prime_col_tiles, heads[h].delta_tiles, 2, n_sv_tiles, 2, vtcm_scales_1); + hmx_queue_pop(hmx_q); // INV_10(c) + hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_delta_worker, &bctx)); + + // Step 3: HMX QS(c) tail + DELTA(c) || HVX phase1a(c+1) + if (has_next) { + bctx.c = c + 1u; + bctx.curr_buf = next_buf; + work_queue_run(wp, gdn_hvx_phase1a_worker, &bctx, n_batch); } - - for (uint32_t h = 0; h < n_batch; ++h) { - hmx_queue_pop(hmx_q); + hmx_queue_pop(hmx_q); // QS(c) + hmx_queue_pop(hmx_q); // DELTA(c) + if (has_next) { + hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_kk_worker, &bctx)); } + // Step 4: HMX KK(c+1) || HVX phase4(c) + bctx.c = c; + bctx.curr_buf = curr_buf; + bctx.s_update_buf = curr_buf; work_queue_run(wp, gdn_hvx_phase4_worker, &bctx, n_batch); - - for (uint32_t h = 0; h < n_batch; ++h) { - htp_gdn_push_hmx_gemm_task(hmx_q, &gemm_tasks[h][5], heads[h].a_row_tiles, heads[h].delta_col_tiles, heads[h].o_intra_tiles, 2, n_sv_tiles, 2, vtcm_scales_1); - } - for (uint32_t h = 0; h < n_batch; ++h) { - htp_gdn_push_hmx_gemm_task(hmx_q, &gemm_tasks[h][6], heads[h].d_row_tiles, heads[h].k_col_tiles_64x128, heads[h].s_update_tiles, n_sv_tiles, n_sv_tiles, 2, vtcm_scales_1); - } - - for (uint32_t h = 0; h < n_batch; ++h) { - hmx_queue_pop(hmx_q); + hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_o_intra_worker, &bctx)); + hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_s_update_worker, &bctx)); + + // Step 5: HMX O_INTRA(c) + S_UPDATE(c) || HVX phase1b(c+1) + if (has_next) { + bctx.c = c + 1u; + bctx.curr_buf = next_buf; + work_queue_run(wp, gdn_hvx_phase1b_worker, &bctx, n_batch); + hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_qk_worker, &bctx)); + hmx_queue_pop(hmx_q); // KK(c+1) } + hmx_queue_pop(hmx_q); // O_INTRA(c) + // Step 6: HMX S_UPDATE(c) tail + QK(c+1) || HVX phase5(c) + DMA store O(c) + bctx.c = c; + bctx.curr_buf = curr_buf; work_queue_run(wp, gdn_hvx_phase5_worker, &bctx, n_batch); + hmx_queue_pop(hmx_q); // S_UPDATE(c) - const uint32_t valid_tokens = hex_smin(chunk_size, n_tokens - t_chunk); - for (uint32_t h = 0; h < n_batch; ++h) { - const dma_addr_t attn_chunk_dma = dst->data + - ((uint64_t) heads[h].iv3 * n_tokens * H + (uint64_t) t_chunk * H + heads[h].iv1) * S_v * sizeof(float); - dma_queue_push(dma_q, dma_make_data(attn_chunk_dma, heads[h].o_f32[curr_buf]), - dst->nb[1], S_v * sizeof(float), S_v * sizeof(float), valid_tokens); - } - - for (uint32_t h = 0; h < n_batch; ++h) { - hmx_queue_pop(hmx_q); - } - + // Step 7: HMX QK(c+1) tail || HVX phase6(c) work_queue_run(wp, gdn_hvx_phase6_worker, &bctx, n_batch); - } - - if (n_chunks > 0) { - for (uint32_t h = 0; h < n_batch; ++h) { - dma_queue_pop(dma_q); + if (has_next) { + hmx_queue_push(hmx_q, hmx_queue_make_desc(gdn_hmx_ks_worker, &bctx)); } } - 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); - } - } + work_queue_run(wp, gdn_hvx_epilogue_worker, &bctx, n_batch); } - dma_queue_flush(dma_q); + if (aux_buf && aux_buf != octx->ctx->ddr_spad_base) { + free(aux_buf); + } return HTP_STATUS_OK; } int op_gated_delta_net(struct htp_ops_context * octx) { - const struct htp_tensor * dst = octx->dst; + const struct htp_tensor * dst = octx->dst; + const struct htp_tensor * dst_cache = octx->dsts[1]; - for (int i = 0; i < 10; i++) { - if (htp_tensor_is_extended(octx->src[i])) { + for (int i = 0; i < 3; i++) { + if (octx->src[i]->type != HTP_TYPE_F32 && octx->src[i]->type != HTP_TYPE_F16) { return HTP_STATUS_NO_SUPPORT; } } - if (htp_tensor_is_extended(octx->dst)) { - return HTP_STATUS_NO_SUPPORT; + for (int i = 3; i < 6; i++) { + if (octx->src[i]->type != HTP_TYPE_F32) { + return HTP_STATUS_NO_SUPPORT; + } + } + const bool replay = gdn_has_replay(octx); + const struct htp_tensor * ids = replay ? NULL : octx->src[6]; + const struct htp_tensor * n_rep = replay ? octx->src[9] : NULL; + if (replay) { + if (!octx->src[8] || !octx->src[9] || + octx->src[6]->type != HTP_TYPE_F32 || + octx->src[7]->type != HTP_TYPE_F32 || + octx->src[8]->type != HTP_TYPE_F32 || + octx->src[9]->type != HTP_TYPE_I32) { + return HTP_STATUS_NO_SUPPORT; + } + } else { + if (octx->src[7] || octx->src[8] || octx->src[9]) { + return HTP_STATUS_NO_SUPPORT; + } + if (ids && ids->type != HTP_TYPE_I32 && ids->type != HTP_TYPE_I64) { + return HTP_STATUS_NO_SUPPORT; + } } - if (octx->dsts[1]) { - const struct htp_tensor * dst_cache = octx->dsts[1]; - if (dst_cache->type != HTP_TYPE_F32 || htp_tensor_is_extended(dst_cache)) { + if (dst_cache) { + if (dst_cache->type != HTP_TYPE_F32) { + return HTP_STATUS_NO_SUPPORT; + } + if (dst->type != HTP_TYPE_F32 && dst->type != HTP_TYPE_F16) { return HTP_STATUS_NO_SUPPORT; } + } else if (dst->type != HTP_TYPE_F32) { + return HTP_STATUS_NO_SUPPORT; } const struct htp_gdn_kernel_params * kparams = (const struct htp_gdn_kernel_params *) octx->kernel_params; @@ -2362,11 +3426,9 @@ int op_gated_delta_net(struct htp_ops_context * octx) { uint32_t nrows = total_rows; if (octx->ctx->mdev.count > 1) { - const bool can_split = htp_tensor_mdev_data_aligned(dst) && - ((dst->nb[1] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0); const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( total_rows, - can_split ? 1 : 0, + 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div @@ -2390,6 +3452,11 @@ int op_gated_delta_net(struct htp_ops_context * octx) { gctx.kparams = kparams; gctx.row_start = row_start; gctx.nrows = nrows; + gctx.load_q = (octx->src[0]->type == HTP_TYPE_F16) ? gdn_load_vec_f16_to_f32 : gdn_load_vec_f32; + gctx.load_k = (octx->src[1]->type == HTP_TYPE_F16) ? gdn_load_vec_f16_to_f32 : gdn_load_vec_f32; + gctx.load_v = (octx->src[2]->type == HTP_TYPE_F16) ? gdn_load_vec_f16_to_f32 : gdn_load_vec_f32; + gctx.store_out = (dst->type == HTP_TYPE_F16) ? gdn_store_vec_f16 : gdn_store_vec_f32; + gctx.step_fn = kparams->kda ? gdn_step_kda_f32 : gdn_step_scalar_f32; htp_gdn_vtcm_layout_build(&gctx.layout, S_v, n_hvx); gctx.vtcm_base = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, gctx.layout.off_state); @@ -2398,6 +3465,18 @@ int op_gated_delta_net(struct htp_ops_context * octx) { return HTP_STATUS_VTCM_TOO_SMALL; } + void * aux_buf = NULL; + const int aux_err = gdn_prepare_aux_data(octx, replay ? n_rep : ids, &aux_buf); + if (aux_err != HTP_STATUS_OK) { + return aux_err; + } + gctx.ids_type = ids ? ids->type : 0; + gctx.ids_data = replay ? NULL : aux_buf; + gctx.n_rep_data = replay ? (const int32_t *) aux_buf : NULL; + gctx.n_pend = replay ? (uint32_t) octx->op_params[1] : 0; + gctx.replay = replay; + gctx.keep = replay && octx->op_params[2] != 0; + FARF(HIGH, "gated-delta-net-f32: q(%ux%ux%ux%u) k(%ux%ux%ux%u) v(%ux%ux%ux%u) state(%ux%ux%ux%u) -> (%ux%ux%ux%u) : " "vtcm-size %zu n_hvx %u\n", octx->src[0]->ne[0], octx->src[0]->ne[1], octx->src[0]->ne[2], octx->src[0]->ne[3], @@ -2407,11 +3486,25 @@ int op_gated_delta_net(struct htp_ops_context * octx) { dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3], gctx.layout.total_bytes, n_hvx); - if (n_tokens == 1) { + bool has_replay_work = gctx.keep; + if (replay && !has_replay_work) { + for (uint32_t s = 0; s < kparams->n_seqs; ++s) { + if (gctx.n_rep_data[s] > 0) { + has_replay_work = true; + break; + } + } + } + + if (n_tokens == 1 && !has_replay_work) { work_queue_run(octx->ctx->hvx_queue, gated_delta_net_f32_tg_thread, &gctx, n_hvx); } else { work_queue_run(octx->ctx->hvx_queue, gated_delta_net_f32_pp_thread, &gctx, n_hvx); } + if (aux_buf && aux_buf != octx->ctx->ddr_spad_base) { + free(aux_buf); + } + return HTP_STATUS_OK; } diff --git a/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.h b/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.h index aff1eb645b5b..930881c178e5 100644 --- a/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.h +++ b/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.h @@ -12,6 +12,7 @@ #define HTP_GDN_MAX_SV 128 #define HTP_GDN_CHUNK_SIZE 64 #define HTP_GDN_MIN_TOKENS 8 +#define HTP_GDN_TOKEN_TILE 16 #ifndef HMX_FP16_TILE_SIZE #define HMX_FP16_TILE_SIZE 2048 @@ -24,7 +25,7 @@ enum htp_gdn_kernel_type { struct htp_gdn_kernel_params { uint8_t kernel_type; - uint8_t pipeline; + uint8_t reserved0; uint16_t chunk_size; uint16_t n_chunks; uint16_t n_heads_batch; @@ -59,6 +60,12 @@ _Static_assert(sizeof(struct htp_gdn_kernel_params) <= 128, "htp_gdn_kernel_para struct htp_gdn_vtcm_layout { size_t state_aligned; + size_t scratch_bytes; + size_t tile_vec_bytes; + size_t tile_scalar_bytes; + size_t spad_stride; + size_t off_scratch; + size_t off_spad; size_t bytes_per_hvx; size_t off_state; size_t total_bytes; @@ -69,9 +76,16 @@ static inline void htp_gdn_vtcm_layout_build( uint32_t S_v, uint32_t n_hvx ) { - size_t state_bytes = (size_t) S_v * S_v * sizeof(float); - L->state_aligned = hex_round_up(state_bytes, 128); - L->bytes_per_hvx = 2 * L->state_aligned; + const size_t state_bytes = (size_t) S_v * S_v * sizeof(float); + const size_t vec_aligned = hex_round_up((size_t) S_v * sizeof(float), 128); + L->state_aligned = hex_round_up(state_bytes, 128); + L->scratch_bytes = 24 * 128; + L->tile_vec_bytes = HTP_GDN_TOKEN_TILE * vec_aligned; + L->tile_scalar_bytes = hex_round_up(HTP_GDN_TOKEN_TILE * sizeof(float), 128); + L->spad_stride = 5 * L->tile_vec_bytes + L->tile_scalar_bytes; + L->off_scratch = 2 * L->state_aligned; + L->off_spad = L->off_scratch + L->scratch_bytes; + L->bytes_per_hvx = L->off_spad + 2 * L->spad_stride + 128; size_t off = 0; VTCM_LAYOUT_ALLOC(off, off_state, L->bytes_per_hvx * n_hvx); L->total_bytes = off; @@ -79,9 +93,7 @@ static inline void htp_gdn_vtcm_layout_build( struct htp_gdn_hmx_vtcm_layout { size_t off_s_state; - size_t off_s_f16; size_t off_s_col_tiles; - size_t off_s_update_f32; size_t off_s_update_tiles; size_t off_q_f32[2]; @@ -93,20 +105,14 @@ struct htp_gdn_hmx_vtcm_layout { size_t off_b_raw[2]; size_t off_o_f32[2]; - size_t off_v_inter_f32; - size_t off_o_inter_f32; - size_t off_o_intra_f32; size_t off_k_f16; - size_t off_v_prime_f16; - size_t off_delta_f16; - size_t off_d_f16; size_t off_q_row_tiles; size_t off_q_prime_row_tiles; size_t off_k_row_tiles; size_t off_k_col_tiles; size_t off_k_prime_row_tiles; - size_t off_k_col_tiles_64x128; + size_t off_k_col_tiles_64x128[2]; size_t off_kk_tiles; size_t off_qk_tiles; size_t off_v_inter_tiles; @@ -115,12 +121,11 @@ struct htp_gdn_hmx_vtcm_layout { size_t off_a_row_tiles; size_t off_v_prime_col_tiles; size_t off_delta_tiles; - size_t off_delta_col_tiles; size_t off_o_intra_tiles; size_t off_d_row_tiles; size_t off_gamma; - size_t off_lambda_init; + size_t off_lambda_init[2]; size_t off_decay_m; size_t off_decay_a; size_t off_rows_kk; @@ -132,7 +137,6 @@ struct htp_gdn_hmx_vtcm_layout { size_t off_scales_1; size_t state_f32_bytes; - size_t state_f16_bytes; size_t state_tiles_bytes; size_t dma_chunk_bytes; size_t act_f16_bytes; @@ -141,7 +145,6 @@ struct htp_gdn_hmx_vtcm_layout { uint32_t n_heads_batch; uint32_t n_hvx; - bool pipeline; size_t total_bytes; }; @@ -150,19 +153,16 @@ static inline void htp_gdn_hmx_vtcm_layout_build( uint32_t S_v, uint32_t chunk_size, uint32_t n_heads_batch, - uint32_t n_hvx, - bool pipeline + uint32_t n_hvx ) { memset(L, 0, sizeof(*L)); L->n_heads_batch = n_heads_batch; L->n_hvx = n_hvx; - L->pipeline = pipeline; const size_t bh = (size_t) n_heads_batch; const size_t nth = (size_t) (n_hvx > 0 ? n_hvx : 1); const size_t state_f32_sz = hex_round_up(S_v * S_v * sizeof(float), 2048); - const size_t state_f16_sz = hex_round_up(S_v * S_v * sizeof(__fp16), 2048); const size_t n_sv_tiles = S_v / 32; const size_t state_tiles_sz = n_sv_tiles * n_sv_tiles * 2048; @@ -177,7 +177,6 @@ static inline void htp_gdn_hmx_vtcm_layout_build( const size_t row_vecs_sz = 64 * 128; L->state_f32_bytes = state_f32_sz; - L->state_f16_bytes = state_f16_sz; L->state_tiles_bytes = state_tiles_sz; L->dma_chunk_bytes = dma_chunk_sz; L->act_f16_bytes = act_f16_sz; @@ -187,60 +186,52 @@ static inline void htp_gdn_hmx_vtcm_layout_build( size_t off = 0; VTCM_LAYOUT_ALLOC(off, off_s_state, bh * state_f32_sz); - VTCM_LAYOUT_ALLOC(off, off_s_f16, bh * state_f16_sz); off = hex_align_up(off, HMX_FP16_TILE_SIZE); VTCM_LAYOUT_ALLOC(off, off_s_col_tiles, bh * state_tiles_sz); - VTCM_LAYOUT_ALLOC(off, off_s_update_f32, bh * state_f32_sz); - off = hex_align_up(off, HMX_FP16_TILE_SIZE); VTCM_LAYOUT_ALLOC(off, off_s_update_tiles, bh * state_tiles_sz); VTCM_LAYOUT_ALLOC(off, off_q_f32[0], bh * dma_chunk_sz); - VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_q_f32[1], bh * dma_chunk_sz, pipeline); + VTCM_LAYOUT_ALLOC(off, off_q_f32[1], bh * dma_chunk_sz); VTCM_LAYOUT_ALLOC(off, off_k_f32[0], bh * dma_chunk_sz); - VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_k_f32[1], bh * dma_chunk_sz, pipeline); + VTCM_LAYOUT_ALLOC(off, off_k_f32[1], bh * dma_chunk_sz); VTCM_LAYOUT_ALLOC(off, off_v_f32[0], bh * dma_chunk_sz); - VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_v_f32[1], bh * dma_chunk_sz, pipeline); + VTCM_LAYOUT_ALLOC(off, off_v_f32[1], bh * dma_chunk_sz); VTCM_LAYOUT_ALLOC(off, off_g_f32[0], bh * dma_scalar_sz); - VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_g_f32[1], bh * dma_scalar_sz, pipeline); + VTCM_LAYOUT_ALLOC(off, off_g_f32[1], bh * dma_scalar_sz); VTCM_LAYOUT_ALLOC(off, off_b_f32[0], bh * dma_scalar_sz); - VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_b_f32[1], bh * dma_scalar_sz, pipeline); + VTCM_LAYOUT_ALLOC(off, off_b_f32[1], bh * dma_scalar_sz); const size_t raw_gb_sz = hex_round_up((bh + 1) * chunk_size * sizeof(float), 128); VTCM_LAYOUT_ALLOC(off, off_g_raw[0], raw_gb_sz); - VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_g_raw[1], raw_gb_sz, pipeline); + VTCM_LAYOUT_ALLOC(off, off_g_raw[1], raw_gb_sz); VTCM_LAYOUT_ALLOC(off, off_b_raw[0], raw_gb_sz); - VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_b_raw[1], raw_gb_sz, pipeline); + VTCM_LAYOUT_ALLOC(off, off_b_raw[1], raw_gb_sz); VTCM_LAYOUT_ALLOC(off, off_o_f32[0], bh * dma_chunk_sz); - VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_o_f32[1], bh * dma_chunk_sz, pipeline); + VTCM_LAYOUT_ALLOC(off, off_o_f32[1], bh * dma_chunk_sz); - VTCM_LAYOUT_ALLOC(off, off_v_inter_f32, bh * dma_chunk_sz); - VTCM_LAYOUT_ALLOC(off, off_o_inter_f32, bh * dma_chunk_sz); - VTCM_LAYOUT_ALLOC(off, off_o_intra_f32, bh * dma_chunk_sz); VTCM_LAYOUT_ALLOC(off, off_k_f16, bh * act_f16_sz); - VTCM_LAYOUT_ALLOC(off, off_v_prime_f16, bh * act_f16_sz); - VTCM_LAYOUT_ALLOC(off, off_delta_f16, bh * act_f16_sz); - VTCM_LAYOUT_ALLOC(off, off_d_f16, bh * act_f16_sz); off = hex_align_up(off, HMX_FP16_TILE_SIZE); VTCM_LAYOUT_ALLOC(off, off_q_row_tiles, bh * tile_64xSv_sz); VTCM_LAYOUT_ALLOC(off, off_q_prime_row_tiles, bh * tile_64xSv_sz); VTCM_LAYOUT_ALLOC(off, off_k_row_tiles, bh * tile_64xSv_sz); VTCM_LAYOUT_ALLOC(off, off_k_col_tiles, bh * tile_64xSv_sz); - VTCM_LAYOUT_ALLOC(off, off_k_prime_row_tiles, bh * tile_64xSv_sz); - VTCM_LAYOUT_ALLOC(off, off_k_col_tiles_64x128, bh * tile_64xSv_sz); - VTCM_LAYOUT_ALLOC(off, off_kk_tiles, bh * tile_64x64_sz); - VTCM_LAYOUT_ALLOC(off, off_qk_tiles, bh * tile_64x64_sz); - VTCM_LAYOUT_ALLOC(off, off_v_inter_tiles, bh * tile_64xSv_sz); - VTCM_LAYOUT_ALLOC(off, off_o_inter_tiles, bh * tile_64xSv_sz); - VTCM_LAYOUT_ALLOC(off, off_inv_row_tiles, bh * tile_64x64_sz); - VTCM_LAYOUT_ALLOC(off, off_a_row_tiles, bh * tile_64x64_sz); - VTCM_LAYOUT_ALLOC(off, off_v_prime_col_tiles, bh * tile_64xSv_sz); - VTCM_LAYOUT_ALLOC(off, off_delta_tiles, bh * tile_64xSv_sz); - VTCM_LAYOUT_ALLOC(off, off_delta_col_tiles, bh * tile_64xSv_sz); - VTCM_LAYOUT_ALLOC(off, off_o_intra_tiles, bh * tile_64xSv_sz); - VTCM_LAYOUT_ALLOC(off, off_d_row_tiles, bh * tile_64xSv_sz); - - VTCM_LAYOUT_ALLOC(off, off_gamma, bh * hex_round_up(chunk_size * sizeof(float), 128)); - VTCM_LAYOUT_ALLOC(off, off_lambda_init, bh * hex_round_up(chunk_size * sizeof(float), 128)); + VTCM_LAYOUT_ALLOC(off, off_k_prime_row_tiles, bh * tile_64xSv_sz); + VTCM_LAYOUT_ALLOC(off, off_k_col_tiles_64x128[0], bh * tile_64xSv_sz); + VTCM_LAYOUT_ALLOC(off, off_k_col_tiles_64x128[1], bh * tile_64xSv_sz); + VTCM_LAYOUT_ALLOC(off, off_kk_tiles, bh * tile_64x64_sz); + VTCM_LAYOUT_ALLOC(off, off_qk_tiles, bh * tile_64x64_sz); + VTCM_LAYOUT_ALLOC(off, off_v_inter_tiles, bh * tile_64xSv_sz); + VTCM_LAYOUT_ALLOC(off, off_o_inter_tiles, bh * tile_64xSv_sz); + VTCM_LAYOUT_ALLOC(off, off_inv_row_tiles, bh * tile_64x64_sz); + VTCM_LAYOUT_ALLOC(off, off_a_row_tiles, bh * tile_64x64_sz); + VTCM_LAYOUT_ALLOC(off, off_v_prime_col_tiles, bh * tile_64xSv_sz); + VTCM_LAYOUT_ALLOC(off, off_delta_tiles, bh * tile_64xSv_sz); + VTCM_LAYOUT_ALLOC(off, off_o_intra_tiles, bh * tile_64xSv_sz); + VTCM_LAYOUT_ALLOC(off, off_d_row_tiles, bh * tile_64xSv_sz); + + VTCM_LAYOUT_ALLOC(off, off_gamma, bh * hex_round_up(chunk_size * sizeof(float), 128)); + VTCM_LAYOUT_ALLOC(off, off_lambda_init[0], bh * hex_round_up(chunk_size * sizeof(float), 128)); + VTCM_LAYOUT_ALLOC(off, off_lambda_init[1], bh * hex_round_up(chunk_size * sizeof(float), 128)); VTCM_LAYOUT_ALLOC(off, off_decay_m, bh * decay_sz); VTCM_LAYOUT_ALLOC(off, off_decay_a, bh * decay_sz); VTCM_LAYOUT_ALLOC(off, off_rows_kk, bh * row_vecs_sz); @@ -264,7 +255,6 @@ static inline bool htp_gdn_hmx_solve_layout( uint32_t total_rows, size_t vtcm_budget, uint32_t n_hvx, - bool pipeline, uint32_t * n_heads_batch_out ) { uint32_t max_batch = 8; @@ -281,16 +271,13 @@ static inline bool htp_gdn_hmx_solve_layout( continue; } struct htp_gdn_hmx_vtcm_layout L; - htp_gdn_hmx_vtcm_layout_build(&L, S_v, chunk_size, bh, n_hvx, pipeline); + htp_gdn_hmx_vtcm_layout_build(&L, S_v, chunk_size, bh, n_hvx); if (L.total_bytes <= vtcm_budget) { *layout_out = L; *n_heads_batch_out = bh; return true; } } - if (pipeline) { - return htp_gdn_hmx_solve_layout(layout_out, S_v, chunk_size, total_rows, vtcm_budget, n_hvx, false, n_heads_batch_out); - } return false; } diff --git a/ggml/src/ggml-hexagon/htp/gather-rows.c b/ggml/src/ggml-hexagon/htp/gather-rows.c index 02804db27034..66bad4f1ecad 100644 --- a/ggml/src/ggml-hexagon/htp/gather-rows.c +++ b/ggml/src/ggml-hexagon/htp/gather-rows.c @@ -24,6 +24,7 @@ struct gather_rows_task { uint32_t r_start; uint32_t rows; uint32_t rows_per_hvx; + uint32_t dst_es; const struct htp_gather_rows_params * kparams; gather_rows_compute_fn_t compute; }; @@ -72,7 +73,10 @@ static __attribute__((noinline)) void gather_rows_init_tables_f32( int32_t s_buf[32] __attribute__((aligned(128))); for (uint32_t k = 0; k < kparams->vg; k++) { for (uint32_t lane = 0; lane < 32; lane++) { - if (col < kparams->na) { + if (row >= kparams->nr_max) { + t_buf[lane] = 0; + s_buf[lane] = 0; + } else if (col < kparams->na) { t_buf[lane] = row * a->nb[1] + col * 4; s_buf[lane] = s_a; } else { @@ -103,7 +107,10 @@ static __attribute__((noinline)) void gather_rows_init_tables_f16( int16_t s_buf[64] __attribute__((aligned(128))); for (uint32_t k = 0; k < kparams->vg; k++) { for (uint32_t lane = 0; lane < 64; lane++) { - if (col < kparams->na) { + if (row >= kparams->nr_max) { + t_buf[lane] = 0; + s_buf[lane] = 0; + } else if (col < kparams->na) { t_buf[lane] = (int16_t) (row * a->nb[1] + col * 2); s_buf[lane] = s_a; } else { @@ -120,6 +127,26 @@ static __attribute__((noinline)) void gather_rows_init_tables_f16( } } +static __attribute__((noinline)) void gather_rows_widen_f16_to_f32(uint8_t * restrict buf, uint32_t nvec) { + HVX_Vector * restrict vbuf = (HVX_Vector *) buf; + for (int32_t v = (int32_t) nvec - 1; v >= 0; v--) { + const HVX_VectorPair vp = hvx_vec_f16_to_f32(vbuf[v]); + vbuf[2 * v + 0] = Q6_V_lo_W(vp); + vbuf[2 * v + 1] = Q6_V_hi_W(vp); + } +} + +static __attribute__((noinline)) void gather_rows_pack_f32_to_f16(uint8_t * restrict buf, uint32_t nvec) { + HVX_Vector * restrict vbuf = (HVX_Vector *) buf; + uint32_t v = 0; + for (; v + 1 < nvec; v += 2) { + vbuf[v >> 1] = hvx_vec_f32_to_f16(vbuf[v], vbuf[v + 1]); + } + if (v < nvec) { + vbuf[v >> 1] = hvx_vec_f32_to_f16(vbuf[v], Q6_V_vzero()); + } +} + static void gather_rows_compute_f32_vg1( uint8_t * restrict out, const uint8_t * restrict region, uint32_t nvec, const struct htp_gather_rows_params * restrict kparams, @@ -133,6 +160,7 @@ static void gather_rows_compute_f32_vg1( Q6_vgather_ARMVw((HVX_Vector *) (out + v * 128), (size_t) region, region_size, vcur); vcur = Q6_Vw_vadd_VwVw(vcur, vinc); } + hvx_gather_sync(out); } static void gather_rows_compute_f32_vgn( @@ -153,6 +181,7 @@ static void gather_rows_compute_f32_vgn( k = 0; } } + hvx_gather_sync(out); } static void gather_rows_compute_f16_vg1( @@ -168,6 +197,7 @@ static void gather_rows_compute_f16_vg1( Q6_vgather_ARMVh((HVX_Vector *) (out + v * 128), (size_t) region, region_size, vcur); vcur = Q6_Vh_vadd_VhVh(vcur, vinc); } + hvx_gather_sync(out); } static void gather_rows_compute_f16_vgn( @@ -188,6 +218,7 @@ static void gather_rows_compute_f16_vgn( k = 0; } } + hvx_gather_sync(out); } static void gather_rows_thread_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { @@ -207,7 +238,7 @@ static void gather_rows_thread_f32(const htp_thread_t * th, unsigned int nth, un struct htp_thread_trace * tr = th->trace; struct htp_gather_rows_vtcm_layout layout; - htp_gather_rows_vtcm_layout_build(&layout, kparams->vg, kparams->region_size, kparams->nr_max, kparams->ne, 4); + htp_gather_rows_vtcm_layout_build(&layout, kparams->vg, kparams->region_size, kparams->nr_max, kparams->ne, 4, task->dst_es); uint8_t * base = VTCM_LAYOUT_PTR(uint8_t, task->octx->ctx->vtcm_base, (size_t) ith * kparams->slice); HVX_Vector * tab = VTCM_LAYOUT_PTR(HVX_Vector, base, layout.off_tab); @@ -255,10 +286,12 @@ static void gather_rows_thread_f32(const htp_thread_t * th, unsigned int nth, un htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r); const uint32_t nvec = (nr * kparams->ne + 31) >> 5; task->compute(out[buf], region[buf], nvec, kparams, tab, inc, cur); - hvx_gather_sync(out[buf]); + if (task->dst_es == 2) { + gather_rows_pack_f32_to_f16(out[buf], nvec); + } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r); - gather_rows_dma_out(q, task, out[buf], r, nr, 4); + gather_rows_dma_out(q, task, out[buf], r, nr, task->dst_es); const uint32_t r_prefetch = r + 2 * nr_max; if (r_prefetch < r_end) { @@ -288,7 +321,7 @@ static void gather_rows_thread_f16(const htp_thread_t * th, unsigned int nth, un struct htp_thread_trace * tr = th->trace; struct htp_gather_rows_vtcm_layout layout; - htp_gather_rows_vtcm_layout_build(&layout, kparams->vg, kparams->region_size, kparams->nr_max, kparams->ne, 2); + htp_gather_rows_vtcm_layout_build(&layout, kparams->vg, kparams->region_size, kparams->nr_max, kparams->ne, 2, task->dst_es); uint8_t * base = VTCM_LAYOUT_PTR(uint8_t, task->octx->ctx->vtcm_base, (size_t) ith * kparams->slice); HVX_Vector * tab = VTCM_LAYOUT_PTR(HVX_Vector, base, layout.off_tab); @@ -336,10 +369,12 @@ static void gather_rows_thread_f16(const htp_thread_t * th, unsigned int nth, un htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r); const uint32_t nvec = (nr * kparams->ne + 63) >> 6; task->compute(out[buf], region[buf], nvec, kparams, tab, inc, cur); - hvx_gather_sync(out[buf]); + if (task->dst_es == 4) { + gather_rows_widen_f16_to_f32(out[buf], nvec); + } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r); - gather_rows_dma_out(q, task, out[buf], r, nr, 2); + gather_rows_dma_out(q, task, out[buf], r, nr, task->dst_es); const uint32_t r_prefetch = r + 2 * nr_max; if (r_prefetch < r_end) { @@ -379,25 +414,27 @@ int htp_gather_rows( return HTP_STATUS_OK; } - const uint32_t elem_size = (a->type == HTP_TYPE_F16) ? 2 : 4; + const uint32_t src_es = (a->type == HTP_TYPE_F16) ? 2 : 4; + const uint32_t dst_es = (octx->dst->type == HTP_TYPE_F16) ? 2 : 4; struct gather_rows_task task; - task.octx = octx; - task.a = a; - task.b = b; - task.dst = octx->dst->data; - task.r_start = r_start; - task.rows = r_count; - task.kparams = kparams; - task.rows_per_hvx = kparams->rows_per_hvx; - - if (elem_size == 2) { + task.octx = octx; + task.a = a; + task.b = b; + task.dst = octx->dst->data; + task.r_start = r_start; + task.rows = r_count; + task.rows_per_hvx = kparams->rows_per_hvx; + task.dst_es = dst_es; + task.kparams = kparams; + + if (src_es == 2) { task.compute = (kparams->vg == 1) ? gather_rows_compute_f16_vg1 : gather_rows_compute_f16_vgn; } else { task.compute = (kparams->vg == 1) ? gather_rows_compute_f32_vg1 : gather_rows_compute_f32_vgn; } - work_queue_func_t worker_func = (elem_size == 2) ? gather_rows_thread_f16 : gather_rows_thread_f32; + work_queue_func_t worker_func = (src_es == 2) ? gather_rows_thread_f16 : gather_rows_thread_f32; work_queue_run(octx->ctx->hvx_queue, worker_func, &task, octx->n_hvx); return HTP_STATUS_OK; } diff --git a/ggml/src/ggml-hexagon/htp/gather-rows.h b/ggml/src/ggml-hexagon/htp/gather-rows.h index 9ca215ac3864..4f360865203b 100644 --- a/ggml/src/ggml-hexagon/htp/gather-rows.h +++ b/ggml/src/ggml-hexagon/htp/gather-rows.h @@ -44,11 +44,13 @@ static inline void htp_gather_rows_vtcm_layout_build( uint32_t region_size, uint32_t nr_max, uint32_t ne, - uint32_t elem_size) { + uint32_t src_es, + uint32_t dst_es) { const size_t vec_bytes = (size_t) vg * 128; const size_t region_aligned = hex_round_up(region_size, 128); - const size_t out_aligned = hex_round_up(region_aligned + (size_t) nr_max * ne * elem_size, 128) - region_aligned; + const size_t gather_bytes = hex_round_up((size_t) nr_max * ne * src_es, 128); + const size_t out_aligned = (dst_es > src_es) ? (2 * gather_bytes) : gather_bytes; size_t off = 0; VTCM_LAYOUT_ALLOC(off, off_tab, vec_bytes); @@ -65,23 +67,23 @@ static inline bool htp_gather_rows_solve_layout( struct htp_gather_rows_params * kparams, uint32_t na, uint32_t a_nb1, uint32_t nb, uint32_t b_nb1, bool b_dense, - uint32_t elem_size, + uint32_t src_es, uint32_t dst_es, uint32_t total_rows, uint32_t n_hvx, uint32_t mdev_count, uint32_t vtcm_size) { - const uint32_t max_ne0 = 128 / elem_size; + const uint32_t max_ne0 = 128 / src_es; const uint32_t ne = na + nb; if (ne == 0 || ne > max_ne0) { return false; } - if (elem_size != 4 && elem_size != 2) { + if ((src_es != 4 && src_es != 2) || (dst_es != 4 && dst_es != 2)) { return false; } - const uint32_t v_lanes = 128 / elem_size; + const uint32_t v_lanes = 128 / src_es; const uint32_t g = hex_gcd_u32(ne, v_lanes); const uint32_t rg = v_lanes / g; const uint32_t vg = ne / g; @@ -94,34 +96,37 @@ static inline bool htp_gather_rows_solve_layout( : total_rows; const uint32_t rows_per_hvx = hex_round_up((max_rows_per_dev + n_hvx - 1) / n_hvx, rg); - const uint32_t fixed = 3 * vg * 128; - const uint32_t per_row = a_nb1 + (nb > 0 ? (b_dense ? b_nb1 : nb * b_nb1) : 0) + ne * elem_size; - if (slice <= fixed + 2 * per_row * rg) { + const uint32_t max_es = MAX(src_es, dst_es); + const uint32_t fixed = 3 * vg * 128; + const uint32_t per_row = a_nb1 + (nb > 0 ? (b_dense ? b_nb1 : nb * b_nb1) : 0) + ne * max_es; + if (slice <= fixed + 2 * per_row) { return false; } const uint32_t avail_per_buf = (slice - fixed) / 2; uint32_t nr_max = MIN(avail_per_buf / per_row, rows_per_hvx); - if (elem_size == 2) { + if (src_es == 2) { const uint32_t per_row_region = a_nb1 + (nb > 0 ? (b_dense ? b_nb1 : nb * b_nb1) : 0); if (per_row_region > 0) { - nr_max = MIN(nr_max, (32768u - 256u) / per_row_region); + nr_max = MIN(nr_max, 1 + 32768u / per_row_region); } } - nr_max = (nr_max / rg) * rg; + if (nr_max >= rg) { + nr_max = (nr_max / rg) * rg; + } uint32_t v1 = 0; uint32_t span1 = 0; uint32_t region_size = 0; while (nr_max > 0) { - v1 = hex_round_up((nr_max - 1) * a_nb1 + na * elem_size, 128); + v1 = hex_round_up((nr_max - 1) * a_nb1 + na * src_es, 128); if (nb > 0) { if (b_dense) { - span1 = elem_size; - region_size = v1 + (nr_max - 1) * b_nb1 + nb * elem_size; + span1 = src_es; + region_size = v1 + (nr_max - 1) * b_nb1 + nb * src_es; } else { - span1 = (nr_max - 1) * b_nb1 + elem_size; + span1 = (nr_max - 1) * b_nb1 + src_es; region_size = v1 + nb * span1; } } else { @@ -130,13 +135,13 @@ static inline bool htp_gather_rows_solve_layout( } struct htp_gather_rows_vtcm_layout layout; - htp_gather_rows_vtcm_layout_build(&layout, vg, region_size, nr_max, ne, elem_size); + htp_gather_rows_vtcm_layout_build(&layout, vg, region_size, nr_max, ne, src_es, dst_es); - if ((elem_size != 2 || region_size <= 32768) && layout.total_per_hvx <= slice) { + if ((src_es != 2 || region_size <= 32768) && layout.total_per_hvx <= slice) { break; } - nr_max -= rg; + nr_max = (nr_max > rg) ? (nr_max - rg) : (nr_max - 1); } if (nr_max == 0) { diff --git a/ggml/src/ggml-hexagon/htp/get-rows-ops.c b/ggml/src/ggml-hexagon/htp/get-rows-ops.c index 83e85f005243..7ab526b186d7 100644 --- a/ggml/src/ggml-hexagon/htp/get-rows-ops.c +++ b/ggml/src/ggml-hexagon/htp/get-rows-ops.c @@ -1,17 +1,15 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include #include +#include #include #define GGML_COMMON_DECL_C #include "ggml-common.h" #include "hex-common.h" #include "dma-queue.h" +#include "dma-pipeline.h" #include "htp-ctx.h" #include "htp-ops.h" #include "htp-tensor.h" @@ -22,9 +20,8 @@ struct get_rows_context; -typedef uint32_t (*get_rows_read_index_fn_t)(const void * src1, uint32_t idx, int idx_type); typedef void (*get_rows_flat_compute_fn_t)(float * dst_spad, const void * src_spad, uint32_t cur_elems); -typedef void (*get_rows_tiled_compute_fn_t)(float * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row); +typedef void (*get_rows_tiled_compute_fn_t)(void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row); struct get_rows_context { struct htp_ops_context * octx; @@ -32,7 +29,6 @@ struct get_rows_context { struct htp_get_rows_vtcm_layout vtcm_layout; uint8_t * vtcm_base; const void * src1_data; - get_rows_read_index_fn_t read_index; get_rows_flat_compute_fn_t compute_flat; get_rows_tiled_compute_fn_t compute_tiled; uint32_t task_start; @@ -45,37 +41,37 @@ struct get_rows_context { int idx_type; }; -#define get_rows_preamble \ - const uint32_t ne00 = octx->src[0]->ne[0]; \ - const uint32_t ne01 = octx->src[0]->ne[1]; \ - const uint32_t ne02 = octx->src[0]->ne[2]; \ - const uint32_t ne03 = octx->src[0]->ne[3]; \ - \ - const uint32_t ne10 = octx->src[1]->ne[0]; \ - const uint32_t ne11 = octx->src[1]->ne[1]; \ - const uint32_t ne12 = octx->src[1]->ne[2]; \ - const uint32_t ne13 = octx->src[1]->ne[3]; \ - \ - const uint32_t ne0 = octx->dst->ne[0]; \ - const uint32_t ne1 = octx->dst->ne[1]; \ - const uint32_t ne2 = octx->dst->ne[2]; \ - const uint32_t ne3 = octx->dst->ne[3]; \ - \ - const uint32_t nb01 = octx->src[0]->nb[1]; \ - const uint32_t nb02 = octx->src[0]->nb[2]; \ - const uint32_t nb03 = octx->src[0]->nb[3]; \ - \ - const uint32_t nb10 = octx->src[1]->nb[0]; \ - const uint32_t nb11 = octx->src[1]->nb[1]; \ - const uint32_t nb12 = octx->src[1]->nb[2]; \ - \ - const uint32_t nb1 = octx->dst->nb[1]; \ - const uint32_t nb2 = octx->dst->nb[2]; \ - const uint32_t nb3 = octx->dst->nb[3]; \ - \ - const uint32_t nr = ne10 * ne11 * ne12; - -static uint32_t get_rows_read_index_ddr( +#define get_rows_preamble \ + const uint32_t __attribute__((unused)) ne00 = octx->src[0]->ne[0]; \ + const uint32_t __attribute__((unused)) ne01 = octx->src[0]->ne[1]; \ + const uint32_t __attribute__((unused)) ne02 = octx->src[0]->ne[2]; \ + const uint32_t __attribute__((unused)) ne03 = octx->src[0]->ne[3]; \ + \ + const uint32_t __attribute__((unused)) ne10 = octx->src[1]->ne[0]; \ + const uint32_t __attribute__((unused)) ne11 = octx->src[1]->ne[1]; \ + const uint32_t __attribute__((unused)) ne12 = octx->src[1]->ne[2]; \ + const uint32_t __attribute__((unused)) ne13 = octx->src[1]->ne[3]; \ + \ + const uint32_t __attribute__((unused)) ne0 = octx->dst->ne[0]; \ + const uint32_t __attribute__((unused)) ne1 = octx->dst->ne[1]; \ + const uint32_t __attribute__((unused)) ne2 = octx->dst->ne[2]; \ + const uint32_t __attribute__((unused)) ne3 = octx->dst->ne[3]; \ + \ + const uint32_t __attribute__((unused)) nb01 = octx->src[0]->nb[1]; \ + const uint32_t __attribute__((unused)) nb02 = octx->src[0]->nb[2]; \ + const uint32_t __attribute__((unused)) nb03 = octx->src[0]->nb[3]; \ + \ + const uint32_t __attribute__((unused)) nb10 = octx->src[1]->nb[0]; \ + const uint32_t __attribute__((unused)) nb11 = octx->src[1]->nb[1]; \ + const uint32_t __attribute__((unused)) nb12 = octx->src[1]->nb[2]; \ + \ + const uint32_t __attribute__((unused)) nb1 = octx->dst->nb[1]; \ + const uint32_t __attribute__((unused)) nb2 = octx->dst->nb[2]; \ + const uint32_t __attribute__((unused)) nb3 = octx->dst->nb[3]; \ + \ + const uint32_t __attribute__((unused)) nr = ne10 * ne11 * ne12; + +static inline uint32_t get_rows_read_index( const void * src1, uint32_t idx, int idx_type @@ -84,17 +80,6 @@ static uint32_t get_rows_read_index_ddr( return *(const uint32_t *) ((const uint8_t *) src1 + off); } -static __attribute__((noinline)) uint32_t get_rows_read_index_vtcm( - const void * src1, - uint32_t idx, - int idx_type -) { - const uint32_t off = idx * ((idx_type == HTP_TYPE_I64) ? sizeof(int64_t) : sizeof(int32_t)); - const HVX_Vector v = hvx_vmem((const uint8_t *) src1 + off); // off & ~127u in HW - // vextract is normally slow, but here it avoids an HVX->L2 store and L1D miss - return (uint32_t) Q6_R_vextract_VR(v, off); -} - static void get_rows_thread_sametype(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { struct get_rows_context * grctx = (struct get_rows_context *) data; struct htp_ops_context * octx = grctx->octx; @@ -116,7 +101,7 @@ static void get_rows_thread_sametype(const htp_thread_t * th, unsigned int nth, const uint32_t i11 = fastdiv(rem, &kparams->div_ne10); const uint32_t i10 = rem - i11 * ne10; - const uint32_t i01 = grctx->read_index(grctx->src1_data, i, grctx->idx_type); + const uint32_t i01 = get_rows_read_index(grctx->src1_data, i, grctx->idx_type); assert(i01 < ne01); const uint32_t q02 = fastdiv(i11, &kparams->div_ne02); @@ -136,6 +121,102 @@ static void get_rows_thread_sametype(const htp_thread_t * th, unsigned int nth, +static inline HVX_Vector get_rows_clamp_f16_finite(HVX_Vector v) { + const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); + const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); + const HVX_Vector inf = hvx_vec_splat_f32(INFINITY); + const HVX_VectorPred finite = Q6_Q_vcmp_gt_VsfVsf(inf, hvx_vec_abs_f32(v)); + const HVX_VectorPred high = Q6_Q_and_QQ(finite, Q6_Q_vcmp_gt_VsfVsf(v, max_f16)); + const HVX_VectorPred low = Q6_Q_and_QQ(finite, Q6_Q_vcmp_gt_VsfVsf(min_f16, v)); + v = Q6_V_vmux_QVV(high, max_f16, v); + return Q6_V_vmux_QVV(low, min_f16, v); +} + +static __attribute__((noinline)) void get_rows_flat_f32_to_f16( + float * restrict dst_ptr, + const void * restrict src_ptr, + uint32_t n +) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src_ptr; + HVX_Vector * restrict vdst = (HVX_Vector *) dst_ptr; + + const uint32_t n_vec = n / 64; + const uint32_t n_rem = n % 64; + + for (uint32_t i = 0; i < n_vec; i++) { + const HVX_Vector v0 = get_rows_clamp_f16_finite(vsrc[2 * i + 0]); + const HVX_Vector v1 = get_rows_clamp_f16_finite(vsrc[2 * i + 1]); + vdst[i] = hvx_vec_f32_to_f16(v0, v1); + } + + if (n_rem > 0) { + const HVX_Vector v0 = get_rows_clamp_f16_finite(vsrc[2 * n_vec + 0]); + const HVX_Vector v1 = (n_rem > 32) ? get_rows_clamp_f16_finite(vsrc[2 * n_vec + 1]) : Q6_V_vzero(); + const HVX_Vector v = hvx_vec_f32_to_f16(v0, v1); + hvx_vec_store_a(&vdst[n_vec], n_rem * sizeof(__fp16), v); + } +} + +static inline void get_rows_pack_f32_to_f16_inplace( + void * spad_ptr, + uint32_t n +) { + HVX_Vector * vec = (HVX_Vector *) spad_ptr; + + const uint32_t n_vec = n / 64; + const uint32_t n_rem = n % 64; + + for (uint32_t i = 0; i < n_vec; i++) { + const HVX_Vector v0 = get_rows_clamp_f16_finite(vec[2 * i + 0]); + const HVX_Vector v1 = get_rows_clamp_f16_finite(vec[2 * i + 1]); + vec[i] = hvx_vec_f32_to_f16(v0, v1); + } + + if (n_rem > 0) { + const HVX_Vector v0 = get_rows_clamp_f16_finite(vec[2 * n_vec + 0]); + const HVX_Vector v1 = (n_rem > 32) ? get_rows_clamp_f16_finite(vec[2 * n_vec + 1]) : Q6_V_vzero(); + const HVX_Vector v = hvx_vec_f32_to_f16(v0, v1); + hvx_vec_store_a(&vec[n_vec], n_rem * sizeof(__fp16), v); + } +} + +#define DEFINE_GET_ROWS_FLAT_F16(type) \ + static void get_rows_flat_##type##_f16( \ + float * dst_spad, const void * src_spad, uint32_t n) { \ + hvx_dequantize_row_flat_##type##_f32(dst_spad, src_spad, n); \ + get_rows_pack_f32_to_f16_inplace(dst_spad, n); \ + } + +DEFINE_GET_ROWS_FLAT_F16(bf16) +DEFINE_GET_ROWS_FLAT_F16(q1_0) +DEFINE_GET_ROWS_FLAT_F16(q2_0) +DEFINE_GET_ROWS_FLAT_F16(q8_0) +DEFINE_GET_ROWS_FLAT_F16(q4_0) +DEFINE_GET_ROWS_FLAT_F16(q4_k) +DEFINE_GET_ROWS_FLAT_F16(q5_k) +DEFINE_GET_ROWS_FLAT_F16(q6_k) + +#undef DEFINE_GET_ROWS_FLAT_F16 + +#define DEFINE_GET_ROWS_TILED_F16(type, tile_k) \ + static void get_rows_tiled_##type##_f16( \ + void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, \ + uint32_t tile_stride, uint32_t row) { \ + hvx_dequantize_row_tiled_##type##_f32( \ + dst_spad, src_spad, n_k_tiles, tile_stride, row); \ + get_rows_pack_f32_to_f16_inplace(dst_spad, n_k_tiles * (tile_k)); \ + } + +DEFINE_GET_ROWS_TILED_F16(q1_0, HTP_TENSOR_TILE_K_Q1_0) +DEFINE_GET_ROWS_TILED_F16(q2_0, HTP_TENSOR_TILE_K_Q2_0) +DEFINE_GET_ROWS_TILED_F16(q8_0, HTP_TENSOR_TILE_N_COLS) +DEFINE_GET_ROWS_TILED_F16(q4_0, HTP_TENSOR_TILE_N_COLS) +DEFINE_GET_ROWS_TILED_F16(q4_k, HTP_TENSOR_TILE_N_COLS) +DEFINE_GET_ROWS_TILED_F16(q5_k, HTP_TENSOR_TILE_N_COLS) +DEFINE_GET_ROWS_TILED_F16(q6_k, HTP_TENSOR_TILE_N_COLS) + +#undef DEFINE_GET_ROWS_TILED_F16 + struct get_rows_flat_task { dma_addr_t src0_data; dma_addr_t dst_data; @@ -160,7 +241,7 @@ static inline struct get_rows_flat_task get_rows_flat_calc_task( task.dst_data = octx->dst->data + i10*nb1 + i11*nb2 + i12*nb3; if (need_src0) { - const uint32_t i01 = grctx->read_index(grctx->src1_data, i, grctx->idx_type); + const uint32_t i01 = get_rows_read_index(grctx->src1_data, i, grctx->idx_type); assert(i01 < ne01); const uint32_t q02 = fastdiv(i11, &kparams->div_ne02); @@ -174,7 +255,53 @@ static inline struct get_rows_flat_task get_rows_flat_calc_task( return task; } +struct get_rows_flat_pipe_state { + const struct htp_ops_context * octx; + const struct get_rows_context * grctx; + get_rows_flat_compute_fn_t compute; + uint32_t ne00; + uint32_t src0_bytes; + uint32_t dst_bytes; + size_t src0_spad_half; + size_t dst_spad_half; + uint32_t ir; + uint32_t ir_end; +}; + +static bool get_rows_flat_next_task(void * ctx, struct dma_pipe_task * task) { + struct get_rows_flat_pipe_state * s = (struct get_rows_flat_pipe_state *) ctx; + if (s->ir >= s->ir_end) { + return false; + } + task->row = s->ir++; + task->off = 0; + task->len = 0; + task->aux = 0; + return true; +} + +static void get_rows_flat_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct get_rows_flat_pipe_state * s = (struct get_rows_flat_pipe_state *) ctx; + struct get_rows_flat_task t = get_rows_flat_calc_task(s->octx, s->grctx, task->row, true); + dma_queue_push(dma_q, dma_make_data(in_spad, t.src0_data), + s->src0_spad_half, s->src0_bytes, s->src0_bytes, 1); +} + +static void get_rows_flat_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + (void) task; + struct get_rows_flat_pipe_state * s = (struct get_rows_flat_pipe_state *) ctx; + s->compute((float *) out_spad, in_spad, s->ne00); +} + +static void get_rows_flat_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) { + struct get_rows_flat_pipe_state * s = (struct get_rows_flat_pipe_state *) ctx; + struct get_rows_flat_task t = get_rows_flat_calc_task(s->octx, s->grctx, task->row, false); + dma_queue_push(dma_q, dma_make_data(t.dst_data, out_spad), + s->dst_bytes, s->dst_spad_half, s->dst_bytes, 1); +} + static void get_rows_thread_flat(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; struct get_rows_context * grctx = (struct get_rows_context *) data; struct htp_ops_context * octx = grctx->octx; get_rows_preamble; @@ -186,54 +313,27 @@ static void get_rows_thread_flat(const htp_thread_t * th, unsigned int nth, unsi } const uint32_t ir1 = MIN(ir0 + dr, grctx->task_start + grctx->tasks); - dma_queue * dma_q = th->dma_q; - struct htp_thread_trace * tr = th->trace; const struct htp_get_rows_vtcm_layout * vtcm_layout = &grctx->vtcm_layout; uint8_t * vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, grctx->vtcm_base, vtcm_layout->off_src0) + ith * vtcm_layout->src0_bytes_per_hvx; uint8_t * vtcm_dst = VTCM_LAYOUT_PTR(uint8_t, grctx->vtcm_base, vtcm_layout->off_dst) + ith * vtcm_layout->dst_bytes_per_hvx; - const uint32_t src0_bytes = grctx->src0_row_size; - const uint32_t dst_bytes = grctx->dst_row_size; - get_rows_flat_compute_fn_t compute = grctx->compute_flat; - - for (uint32_t step = 0, spad_idx = 0; step < ir1 - ir0 && spad_idx < 2; ++step, spad_idx++) { - const uint32_t i = ir0 + step; - struct get_rows_flat_task task = get_rows_flat_calc_task(octx, grctx, i, true); - - dma_queue_push(dma_q, - dma_make_data(octx->dst->data, - vtcm_dst + spad_idx * vtcm_layout->dst_spad_half_size), - dst_bytes, vtcm_layout->dst_spad_half_size, dst_bytes, 0); - dma_queue_push(dma_q, - dma_make_data(vtcm_src0 + spad_idx * vtcm_layout->src0_spad_half_size, task.src0_data), - vtcm_layout->src0_spad_half_size, src0_bytes, src0_bytes, 1); - } - - for (uint32_t step = 0; step < ir1 - ir0; ++step) { - const uint32_t i = ir0 + step; - void * dst_spad = (void *) dma_queue_pop(dma_q).src; - void * src_spad = (void *) dma_queue_pop(dma_q).dst; - - struct get_rows_flat_task task = get_rows_flat_calc_task(octx, grctx, i, false); - - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i); - compute((float *) dst_spad, src_spad, ne00); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i); - - dma_queue_push(dma_q, - dma_make_data(task.dst_data, dst_spad), - dst_bytes, vtcm_layout->dst_spad_half_size, dst_bytes, 1); - - const uint32_t next_step = step + 2; - if (next_step < ir1 - ir0) { - const uint32_t pi = ir0 + next_step; - struct get_rows_flat_task next_task = get_rows_flat_calc_task(octx, grctx, pi, true); - dma_queue_push(dma_q, - dma_make_data(src_spad, next_task.src0_data), - vtcm_layout->src0_spad_half_size, src0_bytes, src0_bytes, 1); - } - } - - dma_queue_flush(dma_q); + void * in_buf[2] = { vtcm_src0, vtcm_src0 + vtcm_layout->src0_spad_half_size }; + void * out_buf[2] = { vtcm_dst, vtcm_dst + vtcm_layout->dst_spad_half_size }; + + struct get_rows_flat_pipe_state s = { + .octx = octx, + .grctx = grctx, + .compute = grctx->compute_flat, + .ne00 = ne00, + .src0_bytes = grctx->src0_row_size, + .dst_bytes = grctx->dst_row_size, + .src0_spad_half = vtcm_layout->src0_spad_half_size, + .dst_spad_half = vtcm_layout->dst_spad_half_size, + .ir = ir0, + .ir_end = ir1, + }; + + dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, + get_rows_flat_next_task, get_rows_flat_push_in, get_rows_flat_compute, get_rows_flat_push_out); } @@ -258,7 +358,7 @@ static inline struct get_rows_tiled_task get_rows_tiled_calc_task( const uint32_t rem = i - i12 * ne11 * ne10; const uint32_t i11 = fastdiv(rem, &kparams->div_ne10); const uint32_t i10 = rem - i11 * ne10; - const uint32_t i01 = grctx->read_index(grctx->src1_data, i, grctx->idx_type); + const uint32_t i01 = get_rows_read_index(grctx->src1_data, i, grctx->idx_type); assert(i01 < ne01); const uint32_t q02 = fastdiv(i11, &kparams->div_ne02); @@ -276,7 +376,53 @@ static inline struct get_rows_tiled_task get_rows_tiled_calc_task( return task; } +struct get_rows_tiled_pipe_state { + const struct htp_ops_context * octx; + const struct get_rows_context * grctx; + get_rows_tiled_compute_fn_t compute_tiled; + uint32_t n_k_tiles; + uint32_t tile_size; + uint32_t tile_stride; + uint32_t dst_bytes; + size_t dst_spad_half; + uint32_t ir; + uint32_t ir_end; +}; + +static bool get_rows_tiled_next_task(void * ctx, struct dma_pipe_task * task) { + struct get_rows_tiled_pipe_state * s = (struct get_rows_tiled_pipe_state *) ctx; + if (s->ir >= s->ir_end) { + return false; + } + task->row = s->ir++; + task->off = 0; + task->len = 0; + task->aux = 0; + return true; +} + +static void get_rows_tiled_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct get_rows_tiled_pipe_state * s = (struct get_rows_tiled_pipe_state *) ctx; + struct get_rows_tiled_task t = get_rows_tiled_calc_task(s->octx, s->grctx, task->row, s->n_k_tiles, s->tile_size); + dma_queue_push(dma_q, dma_make_data(in_spad, t.tile_src_base), + s->tile_stride, s->tile_size, s->tile_size, s->n_k_tiles); +} + +static void get_rows_tiled_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct get_rows_tiled_pipe_state * s = (struct get_rows_tiled_pipe_state *) ctx; + struct get_rows_tiled_task t = get_rows_tiled_calc_task(s->octx, s->grctx, task->row, s->n_k_tiles, s->tile_size); + s->compute_tiled(out_spad, (const uint8_t *) in_spad, s->n_k_tiles, s->tile_stride, t.row); +} + +static void get_rows_tiled_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) { + struct get_rows_tiled_pipe_state * s = (struct get_rows_tiled_pipe_state *) ctx; + struct get_rows_tiled_task t = get_rows_tiled_calc_task(s->octx, s->grctx, task->row, s->n_k_tiles, s->tile_size); + dma_queue_push(dma_q, dma_make_data(t.dst_data, out_spad), + s->dst_bytes, s->dst_spad_half, s->dst_bytes, 1); +} + static void get_rows_thread_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; struct get_rows_context * grctx = (struct get_rows_context *) data; struct htp_ops_context * octx = grctx->octx; get_rows_preamble; @@ -292,84 +438,24 @@ static void get_rows_thread_tiled(const htp_thread_t * th, unsigned int nth, uns const struct htp_get_rows_vtcm_layout * vtcm_layout = &grctx->vtcm_layout; uint8_t * src_spad_base = VTCM_LAYOUT_PTR(uint8_t, grctx->vtcm_base, vtcm_layout->off_src0) + ith * vtcm_layout->src0_bytes_per_hvx; uint8_t * dst_spad_base = VTCM_LAYOUT_PTR(uint8_t, grctx->vtcm_base, vtcm_layout->off_dst) + ith * vtcm_layout->dst_bytes_per_hvx; - dma_queue * dma_q = th->dma_q; - struct htp_thread_trace * tr = th->trace; - - const uint32_t tile_size = grctx->tile_size; - const uint32_t tile_stride = grctx->tile_stride; - const uint32_t dst_bytes = grctx->dst_row_size; - get_rows_tiled_compute_fn_t compute_tiled = grctx->compute_tiled; - - for (uint32_t step = 0, spad_idx = 0; step < ir1 - ir0 && spad_idx < 2; ++step, ++spad_idx) { - const uint32_t i = ir0 + step; - struct get_rows_tiled_task task = get_rows_tiled_calc_task(octx, grctx, i, n_k_tiles, tile_size); - - // Dummy writeback to prime the queue with dst descriptor - dma_queue_push(dma_q, - dma_make_data(task.dst_data, dst_spad_base + spad_idx * vtcm_layout->dst_spad_half_size), - dst_bytes, vtcm_layout->dst_spad_half_size, dst_bytes, 0); - - // Prefetch row tiles - dma_queue_push(dma_q, - dma_make_data(src_spad_base + spad_idx * vtcm_layout->src0_spad_half_size, task.tile_src_base), - tile_stride, tile_size, tile_size, n_k_tiles); - } - - for (uint32_t step = 0; step < ir1 - ir0; ++step) { - const uint32_t i = ir0 + step; - float * dst_spad = (float *) dma_queue_pop(dma_q).src; - uint8_t * src_spad = (uint8_t *) dma_queue_pop(dma_q).dst; - - struct get_rows_tiled_task task = get_rows_tiled_calc_task(octx, grctx, i, n_k_tiles, tile_size); - - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i); - compute_tiled(dst_spad, src_spad, n_k_tiles, tile_stride, task.row); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i); - - // Real writeback of dst_spad - dma_queue_push(dma_q, - dma_make_data(task.dst_data, dst_spad), - dst_bytes, vtcm_layout->dst_spad_half_size, dst_bytes, 1); - - const uint32_t next_step = step + 2; - if (next_step < ir1 - ir0) { - const uint32_t ni = ir0 + next_step; - struct get_rows_tiled_task next_task = get_rows_tiled_calc_task(octx, grctx, ni, n_k_tiles, tile_size); - dma_queue_push(dma_q, - dma_make_data(src_spad, next_task.tile_src_base), - tile_stride, tile_size, tile_size, n_k_tiles); - } - } - - dma_queue_flush(dma_q); -} - -static __attribute__((noinline)) void get_rows_dma_src1( - struct htp_ops_context * octx, - uint8_t * vtcm_src1, - uint32_t elem_size -) { - const uint32_t ne10 = octx->src[1]->ne[0]; - const uint32_t ne11 = octx->src[1]->ne[1]; - const uint32_t ne12 = octx->src[1]->ne[2]; - const uint32_t ne13 = octx->src[1]->ne[3]; - const uint32_t nb11 = octx->src[1]->nb[1]; - const uint32_t nb12 = octx->src[1]->nb[2]; - const uint32_t nb13 = octx->src[1]->nb[3]; - - dma_queue * dma_q = octx->ctx->dma[0]; - uint8_t * cur_dst = vtcm_src1; - for (uint32_t i13 = 0; i13 < ne13; ++i13) { - for (uint32_t i12 = 0; i12 < ne12; ++i12) { - const dma_addr_t src_plane = octx->src[1]->data + i12 * nb12 + i13 * nb13; - while (!dma_queue_push(dma_q, dma_make_data(cur_dst, src_plane), - ne10 * elem_size, nb11, ne10 * elem_size, ne11)) { - dma_queue_pop(dma_q); - } - cur_dst += ne10 * ne11 * elem_size; - } - } - dma_queue_flush(dma_q); + void * in_buf[2] = { src_spad_base, src_spad_base + vtcm_layout->src0_spad_half_size }; + void * out_buf[2] = { dst_spad_base, dst_spad_base + vtcm_layout->dst_spad_half_size }; + + struct get_rows_tiled_pipe_state s = { + .octx = octx, + .grctx = grctx, + .compute_tiled = grctx->compute_tiled, + .n_k_tiles = n_k_tiles, + .tile_size = grctx->tile_size, + .tile_stride = grctx->tile_stride, + .dst_bytes = grctx->dst_row_size, + .dst_spad_half = vtcm_layout->dst_spad_half_size, + .ir = ir0, + .ir_end = ir1, + }; + + dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, + get_rows_tiled_next_task, get_rows_tiled_push_in, get_rows_tiled_compute, get_rows_tiled_push_out); } int op_get_rows(struct htp_ops_context * octx) { @@ -377,7 +463,8 @@ int op_get_rows(struct htp_ops_context * octx) { const uint32_t ne00 = octx->src[0]->ne[0]; const uint32_t src0_row_size = htp_tensor_get_row_size(octx->src[0]->type, ne00); - if (src0_row_size == 0) { + const uint32_t dst_row_size = htp_tensor_get_row_size(octx->dst->type, ne00); + if (src0_row_size == 0 || dst_row_size == 0) { return HTP_STATUS_NO_SUPPORT; } @@ -385,27 +472,22 @@ int op_get_rows(struct htp_ops_context * octx) { if (octx->src[0]->type != octx->dst->type) { return HTP_STATUS_NO_SUPPORT; } - } else { - if (octx->dst->type != HTP_TYPE_F32) { - return HTP_STATUS_NO_SUPPORT; - } + } else if ((octx->dst->type != HTP_TYPE_F32 && octx->dst->type != HTP_TYPE_F16) || + (octx->src[0]->type == HTP_TYPE_F32 && octx->dst->type == HTP_TYPE_F32)) { + return HTP_STATUS_NO_SUPPORT; } if (octx->src[1]->type != HTP_TYPE_I32 && octx->src[1]->type != HTP_TYPE_I64) { return HTP_STATUS_NO_SUPPORT; } - const struct htp_tensor * dst = octx->dst; const uint32_t total_tasks = kparams->total_tasks; - const uint32_t dst_row_size = (kparams->kernel_type == HTP_GET_ROWS_KERNEL_SAMETYPE) ? src0_row_size : ne00 * sizeof(float); uint32_t task_start = 0; uint32_t tasks = total_tasks; if (octx->ctx->mdev.count > 1) { - uint32_t tasks_per_chunk = 1; - htp_tensor_mdev_rows_per_chunk(dst, (uint32_t) dst->nb[0], dst_row_size, &tasks_per_chunk); - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_tasks, tasks_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_tasks, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); task_start = range.start; tasks = range.count; } @@ -435,7 +517,7 @@ int op_get_rows(struct htp_ops_context * octx) { grctx.dst_row_size = dst_row_size; grctx.idx_type = octx->src[1]->type; - htp_get_rows_vtcm_layout_build(&grctx.vtcm_layout, kparams->kernel_type, octx->src[0]->type, ne00, total_tasks, grctx.idx_type, n_hvx); + htp_get_rows_vtcm_layout_build(&grctx.vtcm_layout, kparams->kernel_type, octx->src[0]->type, octx->dst->type, ne00, n_hvx); if (grctx.vtcm_layout.total_bytes > octx->ctx->vtcm_size) { FARF(ERROR, "get-rows: VTCM reservation %zu is too small, needed %zu\n", @@ -449,33 +531,62 @@ int op_get_rows(struct htp_ops_context * octx) { q_func = get_rows_thread_sametype; break; case HTP_GET_ROWS_KERNEL_TILED: - switch (octx->src[0]->type) { - case HTP_TYPE_F16: grctx.compute_tiled = hvx_dequantize_row_tiled_f16_f32; break; - case HTP_TYPE_Q1_0: grctx.compute_tiled = hvx_dequantize_row_tiled_q1_0_f32; break; - case HTP_TYPE_Q2_0: grctx.compute_tiled = hvx_dequantize_row_tiled_q2_0_f32; break; - case HTP_TYPE_Q8_0: grctx.compute_tiled = hvx_dequantize_row_tiled_q8_0_f32; break; - case HTP_TYPE_Q4_0: grctx.compute_tiled = hvx_dequantize_row_tiled_q4_0_f32; break; - case HTP_TYPE_Q4_K: grctx.compute_tiled = hvx_dequantize_row_tiled_q4_k_f32; break; - case HTP_TYPE_Q5_K: grctx.compute_tiled = hvx_dequantize_row_tiled_q5_k_f32; break; - case HTP_TYPE_Q6_K: grctx.compute_tiled = hvx_dequantize_row_tiled_q6_k_f32; break; - default: return HTP_STATUS_NO_SUPPORT; + if (octx->dst->type == HTP_TYPE_F16) { + switch (octx->src[0]->type) { + case HTP_TYPE_F16: grctx.compute_tiled = hvx_dequantize_row_tiled_f16_f16; break; + case HTP_TYPE_Q1_0: grctx.compute_tiled = get_rows_tiled_q1_0_f16; break; + case HTP_TYPE_Q2_0: grctx.compute_tiled = get_rows_tiled_q2_0_f16; break; + case HTP_TYPE_Q8_0: grctx.compute_tiled = get_rows_tiled_q8_0_f16; break; + case HTP_TYPE_Q4_0: grctx.compute_tiled = get_rows_tiled_q4_0_f16; break; + case HTP_TYPE_Q4_K: grctx.compute_tiled = get_rows_tiled_q4_k_f16; break; + case HTP_TYPE_Q5_K: grctx.compute_tiled = get_rows_tiled_q5_k_f16; break; + case HTP_TYPE_Q6_K: grctx.compute_tiled = get_rows_tiled_q6_k_f16; break; + default: return HTP_STATUS_NO_SUPPORT; + } + } else { + switch (octx->src[0]->type) { + case HTP_TYPE_F16: grctx.compute_tiled = hvx_dequantize_row_tiled_f16_f32; break; + case HTP_TYPE_Q1_0: grctx.compute_tiled = hvx_dequantize_row_tiled_q1_0_f32; break; + case HTP_TYPE_Q2_0: grctx.compute_tiled = hvx_dequantize_row_tiled_q2_0_f32; break; + case HTP_TYPE_Q8_0: grctx.compute_tiled = hvx_dequantize_row_tiled_q8_0_f32; break; + case HTP_TYPE_Q4_0: grctx.compute_tiled = hvx_dequantize_row_tiled_q4_0_f32; break; + case HTP_TYPE_Q4_K: grctx.compute_tiled = hvx_dequantize_row_tiled_q4_k_f32; break; + case HTP_TYPE_Q5_K: grctx.compute_tiled = hvx_dequantize_row_tiled_q5_k_f32; break; + case HTP_TYPE_Q6_K: grctx.compute_tiled = hvx_dequantize_row_tiled_q6_k_f32; break; + default: return HTP_STATUS_NO_SUPPORT; + } } grctx.tile_size = htp_tensor_get_tile_size(octx->src[0]->type); grctx.tile_stride = htp_tensor_get_tile_padded_size(octx->src[0]->type); q_func = get_rows_thread_tiled; break; case HTP_GET_ROWS_KERNEL_FLAT: - switch (octx->src[0]->type) { - case HTP_TYPE_F16: grctx.compute_flat = hvx_dequantize_row_flat_f16_f32; break; - case HTP_TYPE_BF16: grctx.compute_flat = hvx_dequantize_row_flat_bf16_f32; break; - case HTP_TYPE_Q1_0: grctx.compute_flat = hvx_dequantize_row_flat_q1_0_f32; break; - case HTP_TYPE_Q2_0: grctx.compute_flat = hvx_dequantize_row_flat_q2_0_f32; break; - case HTP_TYPE_Q8_0: grctx.compute_flat = hvx_dequantize_row_flat_q8_0_f32; break; - case HTP_TYPE_Q4_0: grctx.compute_flat = hvx_dequantize_row_flat_q4_0_f32; break; - case HTP_TYPE_Q4_K: grctx.compute_flat = hvx_dequantize_row_flat_q4_k_f32; break; - case HTP_TYPE_Q5_K: grctx.compute_flat = hvx_dequantize_row_flat_q5_k_f32; break; - case HTP_TYPE_Q6_K: grctx.compute_flat = hvx_dequantize_row_flat_q6_k_f32; break; - default: return HTP_STATUS_NO_SUPPORT; + if (octx->dst->type == HTP_TYPE_F16) { + switch (octx->src[0]->type) { + case HTP_TYPE_F32: grctx.compute_flat = get_rows_flat_f32_to_f16; break; + case HTP_TYPE_BF16: grctx.compute_flat = get_rows_flat_bf16_f16; break; + case HTP_TYPE_Q1_0: grctx.compute_flat = get_rows_flat_q1_0_f16; break; + case HTP_TYPE_Q2_0: grctx.compute_flat = get_rows_flat_q2_0_f16; break; + case HTP_TYPE_Q8_0: grctx.compute_flat = get_rows_flat_q8_0_f16; break; + case HTP_TYPE_Q4_0: grctx.compute_flat = get_rows_flat_q4_0_f16; break; + case HTP_TYPE_Q4_K: grctx.compute_flat = get_rows_flat_q4_k_f16; break; + case HTP_TYPE_Q5_K: grctx.compute_flat = get_rows_flat_q5_k_f16; break; + case HTP_TYPE_Q6_K: grctx.compute_flat = get_rows_flat_q6_k_f16; break; + default: return HTP_STATUS_NO_SUPPORT; + } + } else { + switch (octx->src[0]->type) { + case HTP_TYPE_F16: grctx.compute_flat = hvx_dequantize_row_flat_f16_f32; break; + case HTP_TYPE_BF16: grctx.compute_flat = hvx_dequantize_row_flat_bf16_f32; break; + case HTP_TYPE_Q1_0: grctx.compute_flat = hvx_dequantize_row_flat_q1_0_f32; break; + case HTP_TYPE_Q2_0: grctx.compute_flat = hvx_dequantize_row_flat_q2_0_f32; break; + case HTP_TYPE_Q8_0: grctx.compute_flat = hvx_dequantize_row_flat_q8_0_f32; break; + case HTP_TYPE_Q4_0: grctx.compute_flat = hvx_dequantize_row_flat_q4_0_f32; break; + case HTP_TYPE_Q4_K: grctx.compute_flat = hvx_dequantize_row_flat_q4_k_f32; break; + case HTP_TYPE_Q5_K: grctx.compute_flat = hvx_dequantize_row_flat_q5_k_f32; break; + case HTP_TYPE_Q6_K: grctx.compute_flat = hvx_dequantize_row_flat_q6_k_f32; break; + default: return HTP_STATUS_NO_SUPPORT; + } } q_func = get_rows_thread_flat; break; @@ -483,19 +594,18 @@ int op_get_rows(struct htp_ops_context * octx) { return HTP_STATUS_NO_SUPPORT; } - const uint32_t elem_size = (grctx.idx_type == HTP_TYPE_I64) ? sizeof(int64_t) : sizeof(int32_t); - const size_t src1_bytes = (size_t) total_tasks * elem_size; - - if (!htp_tensor_is_extended(octx->src[1]) && src1_bytes <= 128 && - htp_tensor_is_contiguous(octx->src[1], elem_size)) { - grctx.src1_data = (const void *) (uintptr_t) octx->src[1]->data; - grctx.read_index = get_rows_read_index_ddr; - } else { - uint8_t * vtcm_src1 = VTCM_LAYOUT_PTR(uint8_t, grctx.vtcm_base, grctx.vtcm_layout.off_src1); - get_rows_dma_src1(octx, vtcm_src1, elem_size); - grctx.src1_data = vtcm_src1; - grctx.read_index = get_rows_read_index_vtcm; + const size_t src1_bytes = hex_round_up(htp_tensor_nbytes(octx->src[1]), 128); + void * src1_buf = (src1_bytes <= octx->ctx->ddr_spad_size) ? octx->ctx->ddr_spad_base : memalign(128, src1_bytes); + if (!src1_buf) { + return HTP_STATUS_INTERNAL_ERR; } + if (htp_tensor_read(&octx->ctx->main_th, src1_buf, src1_bytes, octx->src[1]) == 0) { + if (src1_buf != octx->ctx->ddr_spad_base) { + free(src1_buf); + } + return HTP_STATUS_INTERNAL_ERR; + } + grctx.src1_data = src1_buf; FARF(HIGH, "get-rows: (%ux%ux%ux%u) x (%ux%ux%ux%u) -> (%ux%ux%ux%u) : src0-vtcm-size %zu dst-vtcm-size %zu kernel-type %d n-hvx %d\n", octx->src[0]->ne[0], octx->src[0]->ne[1], octx->src[0]->ne[2], octx->src[0]->ne[3], @@ -506,5 +616,8 @@ int op_get_rows(struct htp_ops_context * octx) { kparams->kernel_type, n_hvx); work_queue_run(octx->ctx->hvx_queue, q_func, &grctx, n_hvx); + if (src1_buf != octx->ctx->ddr_spad_base) { + free(src1_buf); + } return HTP_STATUS_OK; } diff --git a/ggml/src/ggml-hexagon/htp/get-rows-ops.h b/ggml/src/ggml-hexagon/htp/get-rows-ops.h index 986966f11f11..3c724d98146e 100644 --- a/ggml/src/ggml-hexagon/htp/get-rows-ops.h +++ b/ggml/src/ggml-hexagon/htp/get-rows-ops.h @@ -29,8 +29,6 @@ struct htp_get_rows_kernel_params { struct htp_get_rows_vtcm_layout { size_t total_bytes; - size_t off_src1; - size_t src1_bytes; size_t off_src0; size_t off_dst; @@ -44,39 +42,35 @@ struct htp_get_rows_vtcm_layout { static inline void htp_get_rows_vtcm_layout_build( struct htp_get_rows_vtcm_layout * L, int kernel_type, - int type, + int src0_type, + int dst_type, uint32_t ne00, - uint32_t total_tasks, - int idx_type, uint32_t n_hvx) { memset(L, 0, sizeof(*L)); - const size_t elem_size = (idx_type == HTP_TYPE_I64) ? sizeof(int64_t) : sizeof(int32_t); - const size_t src1_raw_bytes = total_tasks * elem_size; - const size_t src1_bytes = ((src1_raw_bytes + 127) & ~127) + 128; - - L->src1_bytes = src1_bytes; - const size_t src1_alloc_bytes = (src1_bytes + 255) & ~255; - if (kernel_type != HTP_GET_ROWS_KERNEL_SAMETYPE) { size_t src0_row_size = 0; if (kernel_type == HTP_GET_ROWS_KERNEL_TILED) { - const size_t tile_stride = htp_tensor_get_tile_padded_size(type); - const uint32_t n_k_tiles = ne00 / htp_tensor_get_tile_k(type); + const size_t tile_stride = htp_tensor_get_tile_padded_size(src0_type); + const uint32_t n_k_tiles = ne00 / htp_tensor_get_tile_k(src0_type); src0_row_size = n_k_tiles > 0 ? (n_k_tiles * tile_stride) : tile_stride; } else { - src0_row_size = htp_tensor_get_row_size(type, ne00); + src0_row_size = htp_tensor_get_row_size(src0_type, ne00); } + const bool direct_f16_spad = + (kernel_type == HTP_GET_ROWS_KERNEL_TILED && src0_type == HTP_TYPE_F16 && dst_type == HTP_TYPE_F16) || + (kernel_type == HTP_GET_ROWS_KERNEL_FLAT && src0_type == HTP_TYPE_F32 && dst_type == HTP_TYPE_F16); + const size_t dst_spad_row_size = htp_tensor_get_row_size(direct_f16_spad ? dst_type : HTP_TYPE_F32, ne00); + L->src0_spad_half_size = (src0_row_size + 255) & ~255; - L->dst_spad_half_size = (ne00 * sizeof(float) + 255) & ~255; + L->dst_spad_half_size = (dst_spad_row_size + 255) & ~255; L->src0_bytes_per_hvx = 2 * L->src0_spad_half_size; L->dst_bytes_per_hvx = 2 * L->dst_spad_half_size; } size_t off = 0; - VTCM_LAYOUT_ALLOC(off, off_src1, src1_alloc_bytes); VTCM_LAYOUT_ALLOC(off, off_src0, L->src0_bytes_per_hvx * n_hvx); VTCM_LAYOUT_ALLOC(off, off_dst, L->dst_bytes_per_hvx * n_hvx); L->total_bytes = off; diff --git a/ggml/src/ggml-hexagon/htp/glu-ops.c b/ggml/src/ggml-hexagon/htp/glu-ops.c index 223c1829f232..cecc0e538cc0 100644 --- a/ggml/src/ggml-hexagon/htp/glu-ops.c +++ b/ggml/src/ggml-hexagon/htp/glu-ops.c @@ -1,13 +1,10 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include #include #include "dma-queue.h" +#include "dma-pipeline.h" #include "hvx-utils.h" #define GGML_COMMON_DECL_C @@ -475,6 +472,7 @@ static __attribute__((noinline)) void hvx_sigglu_f32_vec(HVX_Vector * restrict v const HVX_Vector v_max_exp = hvx_vec_splat_f32(87.0f); const HVX_Vector v_min_exp = hvx_vec_splat_f32(-87.0f); + _Pragma("unroll(2)") for (uint32_t i = 0; i < nvec; i++) { HVX_Vector sig = hvx_vec_fast_sigmoid_f32_guard(vsrc0[i], v_one, v_max_exp, v_min_exp); vdst[i] = hvx_vec_mul_f32_f32(sig, vsrc1[i]); @@ -523,6 +521,11 @@ static void sigglu_f32(const float * restrict src0, const struct htp_glu_context * gctx) { htp_glu_op_preamble; + if ((size_t) nc * sizeof(float) == src0_row_size_aligned) { + hvx_sigglu_f32_aa((uint8_t *) dst, (const uint8_t *) src0, (const uint8_t *) src1, num_rows * (uint32_t) nc); + return; + } + for (uint32_t ib = 0; ib < num_rows; ib++) { const uint8_t * restrict src0_ptr = (const uint8_t *) src0 + (ib * src0_row_size_aligned); const uint8_t * restrict src1_ptr = (const uint8_t *) src1 + (ib * src1_row_size_aligned); @@ -532,7 +535,58 @@ static void sigglu_f32(const float * restrict src0, } } -// swiglu(x) = x1 * sigmoid(x0) +static __attribute__((noinline)) void hvx_swiglu_f16_vec(HVX_Vector * restrict vdst, + const HVX_Vector * restrict vsrc0, + const HVX_Vector * restrict vsrc1, + uint32_t nvec) { + _Pragma("clang loop pipeline(disable) unroll(disable)") + for (uint32_t i = 0; i + 1 < nvec; i += 2) { + HVX_Vector x0 = vsrc0[i + 0]; + HVX_Vector x1 = vsrc0[i + 1]; + HVX_VectorPair sigp = hvx_vec_fast_sigmoid_f16_pair(x0, x1); + vdst[i + 0] = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(x0, Q6_V_lo_W(sigp)), vsrc1[i + 0]); + vdst[i + 1] = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(x1, Q6_V_hi_W(sigp)), vsrc1[i + 1]); + } +} + +static __attribute__((noinline)) void hvx_swiglu_f16_tail(HVX_Vector * restrict vdst, + const HVX_Vector * restrict vsrc0, + const HVX_Vector * restrict vsrc1, + uint32_t nloe) { + HVX_Vector x = vsrc0[0]; + HVX_Vector sig = hvx_vec_fast_sigmoid_f16(x); + HVX_Vector res = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(x, sig), vsrc1[0]); + hvx_vec_store_a((void *) vdst, nloe * sizeof(_Float16), res); +} + +static inline void hvx_swiglu_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src0, const uint8_t * restrict src1, uint32_t n) { + assert((unsigned long) dst % 128 == 0); + assert((unsigned long) src0 % 128 == 0); + assert((unsigned long) src1 % 128 == 0); + + HVX_Vector * restrict vdst = (HVX_Vector *) dst; + const HVX_Vector * restrict vsrc0 = (const HVX_Vector *) src0; + const HVX_Vector * restrict vsrc1 = (const HVX_Vector *) src1; + + const uint32_t epv = 128 / sizeof(_Float16); + const uint32_t nvec = n / epv; + const uint32_t nloe = n % epv; + uint32_t i = 0; + + if (nvec >= 2) { + const uint32_t nvec2 = nvec & ~1u; + hvx_swiglu_f16_vec(vdst, vsrc0, vsrc1, nvec2); + i = nvec2; + } + if (i < nvec) { + hvx_swiglu_f16_tail(vdst + i, vsrc0 + i, vsrc1 + i, epv); + } + if (nloe) { + hvx_swiglu_f16_tail(vdst + nvec, vsrc0 + nvec, vsrc1 + nvec, nloe); + } +} + +// swiglu(x, g) = x * sigmoid(x) * g static void swiglu_f16(const _Float16 * restrict src0, const _Float16 * restrict src1, _Float16 * restrict dst, @@ -540,13 +594,17 @@ static void swiglu_f16(const _Float16 * restrict src0, const struct htp_glu_context * gctx) { htp_glu_op_preamble; + if ((size_t) nc * sizeof(_Float16) == src0_row_size_aligned) { + hvx_swiglu_f16_aa((uint8_t *) dst, (const uint8_t *) src0, (const uint8_t *) src1, num_rows * (uint32_t) nc); + return; + } + for (uint32_t ib = 0; ib < num_rows; ib++) { const uint8_t * restrict src0_ptr = (const uint8_t *) src0 + (ib * src0_row_size_aligned); const uint8_t * restrict src1_ptr = (const uint8_t *) src1 + (ib * src1_row_size_aligned); uint8_t * restrict dst_ptr = (uint8_t *) dst + (ib * dst_row_size_aligned); - hvx_sigmoid_f16_aa(dst_ptr, src0_ptr, nc); - hvx_mul_mul_f16_aa(dst_ptr, src0_ptr, dst_ptr, src1_ptr, nc); + hvx_swiglu_f16_aa(dst_ptr, src0_ptr, src1_ptr, nc); } } @@ -668,9 +726,13 @@ static __attribute__((noinline)) void hvx_sigglu_f16_vec(HVX_Vector * restrict v const HVX_Vector * restrict vsrc0, const HVX_Vector * restrict vsrc1, uint32_t nvec) { - for (uint32_t i = 0; i < nvec; i++) { - HVX_Vector sig = hvx_vec_fast_sigmoid_f16(vsrc0[i]); - vdst[i] = hvx_vec_mul_f16_f16(sig, vsrc1[i]); + for (uint32_t i = 0; i + 2 < nvec; i += 3) { + HVX_Vector sig0 = hvx_vec_fast_sigmoid_f16(vsrc0[i + 0]); + HVX_Vector sig1 = hvx_vec_fast_sigmoid_f16(vsrc0[i + 1]); + HVX_Vector sig2 = hvx_vec_fast_sigmoid_f16(vsrc0[i + 2]); + vdst[i + 0] = hvx_vec_mul_f16_f16(sig0, vsrc1[i + 0]); + vdst[i + 1] = hvx_vec_mul_f16_f16(sig1, vsrc1[i + 1]); + vdst[i + 2] = hvx_vec_mul_f16_f16(sig2, vsrc1[i + 2]); } } @@ -695,9 +757,15 @@ static inline void hvx_sigglu_f16_aa(uint8_t * restrict dst, const uint8_t * res const uint32_t epv = 128 / sizeof(_Float16); const uint32_t nvec = n / epv; const uint32_t nloe = n % epv; + uint32_t i = 0; - if (nvec) { - hvx_sigglu_f16_vec(vdst, vsrc0, vsrc1, nvec); + if (nvec >= 3) { + const uint32_t nvec3 = nvec - (nvec % 3); + hvx_sigglu_f16_vec(vdst, vsrc0, vsrc1, nvec3); + i = nvec3; + } + for (; i < nvec; i++) { + hvx_sigglu_f16_tail(vdst + i, vsrc0 + i, vsrc1 + i, epv); } if (nloe) { hvx_sigglu_f16_tail(vdst + nvec, vsrc0 + nvec, vsrc1 + nvec, nloe); @@ -712,6 +780,11 @@ static void sigglu_f16(const _Float16 * restrict src0, const struct htp_glu_context * gctx) { htp_glu_op_preamble; + if ((size_t) nc * sizeof(_Float16) == src0_row_size_aligned) { + hvx_sigglu_f16_aa((uint8_t *) dst, (const uint8_t *) src0, (const uint8_t *) src1, num_rows * (uint32_t) nc); + return; + } + for (uint32_t ib = 0; ib < num_rows; ib++) { const uint8_t * restrict src0_ptr = (const uint8_t *) src0 + (ib * src0_row_size_aligned); const uint8_t * restrict src1_ptr = (const uint8_t *) src1 + (ib * src1_row_size_aligned); @@ -721,99 +794,85 @@ static void sigglu_f16(const _Float16 * restrict src0, } } -#define DEFINE_GLU_PER_THREAD(TYPE, SUFFIX) \ - static void glu_##SUFFIX##_per_hvx(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { \ - struct htp_glu_context * gctx = (struct htp_glu_context *) data; \ - htp_glu_preamble; \ - \ - struct htp_thread_trace * tr = th->trace; \ - \ - size_t src0_row_size = gctx->src0_row_size; \ - size_t src1_row_size = gctx->src1_row_size; \ - size_t dst_row_size = gctx->dst_row_size; \ - \ - size_t src0_row_stride = gctx->src0_row_stride; \ - size_t src1_row_stride = gctx->src1_row_stride; \ - \ - const uint32_t src0_nrows = gctx->src0_nrows; \ - const uint32_t src0_nrows_per_hvx = gctx->src0_nrows_per_hvx; \ - \ - const uint32_t src0_start_row = gctx->row_start + src0_nrows_per_hvx * ith; \ - const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, gctx->row_start + src0_nrows); \ - \ - /* no work for this thread */ \ - if (src0_start_row >= src0_end_row) { \ - return; \ - } \ - \ - const dma_addr_t data_src0 = gctx->data_src0; \ - const dma_addr_t data_src1 = gctx->data_src1; \ - const dma_addr_t data_dst = gctx->data_dst; \ - \ - const size_t src0_row_size_aligned = gctx->src0_row_size_aligned; \ - const size_t src1_row_size_aligned = gctx->src1_row_size_aligned; \ - const size_t dst_row_size_aligned = gctx->dst_row_size_aligned; \ - \ - uint8_t * restrict src0_spad_data = gctx->vtcm_src0 + (ith * gctx->vtcm_src0_size_per_hvx); \ - uint8_t * restrict src1_spad_data = gctx->vtcm_src1 + (ith * gctx->vtcm_src1_size_per_hvx); \ - uint8_t * restrict dst_spad_data = gctx->vtcm_dst + (ith * gctx->vtcm_dst_size_per_hvx); \ - \ - size_t src0_spad_half_size = gctx->src0_spad_half_size; \ - size_t src1_spad_half_size = gctx->src1_spad_half_size; \ - size_t dst_spad_half_size = gctx->dst_spad_half_size; \ - \ - const int BLOCK = gctx->block; \ - \ - dma_queue * dma_q = th->dma_q; \ - glu_compute_##SUFFIX##_fn_t compute = (glu_compute_##SUFFIX##_fn_t) gctx->compute; \ - \ - for (uint32_t ir = src0_start_row, spad_idx = 0; ir < src0_end_row && spad_idx < 2; ir += BLOCK, spad_idx++) { \ - const uint32_t block_size = MIN(BLOCK, src0_end_row - ir); \ - \ - /* Dummy DMA transation for sequencing (interleaving dst,src,dst,...) */ \ - dma_queue_push(dma_q, \ - dma_make_data(data_dst, dst_spad_data + (spad_idx * dst_spad_half_size)), \ - dst_row_size, dst_row_size_aligned, dst_row_size, 0); \ - \ - dma_queue_push(dma_q, \ - dma_make_data(src0_spad_data + (spad_idx * src0_spad_half_size), data_src0 + (ir * src0_row_stride)), \ - src0_row_size_aligned, src0_row_stride, src0_row_size, block_size); \ - \ - dma_queue_push(dma_q, \ - dma_make_data(src1_spad_data + (spad_idx * src1_spad_half_size), data_src1 + (ir * src1_row_stride)), \ - src1_row_size_aligned, src1_row_stride, src1_row_size, block_size); \ - } \ - \ - for (uint32_t ir = src0_start_row; ir < src0_end_row; ir += BLOCK) { \ - const uint32_t block_size = MIN(BLOCK, src0_end_row - ir); \ - \ - TYPE * dst_spad = (TYPE *) dma_queue_pop(dma_q).src; \ - TYPE * src0_spad = (TYPE *) dma_queue_pop(dma_q).dst; \ - TYPE * src1_spad = (TYPE *) dma_queue_pop(dma_q).dst; \ - \ - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir); \ - compute(src0_spad, src1_spad, dst_spad, block_size, gctx); \ - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir); \ - \ - dma_queue_push(dma_q, dma_make_data(data_dst + (ir * dst_row_size), dst_spad), \ - dst_row_size, dst_row_size_aligned, dst_row_size, block_size); \ - \ - /* prefetch N+2 loop iteration if any */ \ - const uint32_t pref_block = (ir + BLOCK * 2); \ - if (pref_block < src0_end_row) { \ - const uint32_t pref_block_size = MIN(BLOCK, src0_end_row - pref_block); \ - dma_queue_push(dma_q, dma_make_data(src0_spad, data_src0 + (pref_block * src0_row_stride)), \ - src0_row_size_aligned, src0_row_stride, src0_row_size, pref_block_size); \ - dma_queue_push(dma_q, dma_make_data(src1_spad, data_src1 + (pref_block * src1_row_stride)), \ - src1_row_size_aligned, src1_row_stride, src1_row_size, pref_block_size); \ - } \ - } \ - \ - dma_queue_flush(dma_q); \ +struct glu_pipe_state { + const struct htp_glu_context * gctx; + uint32_t ir; + uint32_t ir_end; +}; + +static bool glu_next_task(void * ctx, struct dma_pipe_task * task) { + struct glu_pipe_state * s = (struct glu_pipe_state *) ctx; + if (s->ir >= s->ir_end) { + return false; } + const uint32_t block_size = MIN((uint32_t) s->gctx->block, s->ir_end - s->ir); + task->row = s->ir; + task->off = 0; + task->len = block_size; + task->aux = 0; + s->ir += block_size; + return true; +} -DEFINE_GLU_PER_THREAD(float, f32) -DEFINE_GLU_PER_THREAD(_Float16, f16) +static void glu_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in0_spad, void * in1_spad) { + const struct htp_glu_context * gctx = ((struct glu_pipe_state *) ctx)->gctx; + dma_queue_push(dma_q, dma_make_data(in0_spad, gctx->data_src0 + (size_t) task->row * gctx->src0_row_stride), + gctx->src0_row_size_aligned, gctx->src0_row_stride, gctx->src0_row_size, task->len); + dma_queue_push(dma_q, dma_make_data(in1_spad, gctx->data_src1 + (size_t) task->row * gctx->src1_row_stride), + gctx->src1_row_size_aligned, gctx->src1_row_stride, gctx->src1_row_size, task->len); +} + +static void glu_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) { + const struct htp_glu_context * gctx = ((struct glu_pipe_state *) ctx)->gctx; + dma_queue_push(dma_q, dma_make_data(gctx->data_dst + (size_t) task->row * gctx->dst_row_size, out_spad), + gctx->dst_row_size, gctx->dst_row_size_aligned, gctx->dst_row_size, task->len); +} + +static void glu_compute_f32(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in0_spad, void * in1_spad) { + const struct htp_glu_context * gctx = ((struct glu_pipe_state *) ctx)->gctx; + glu_compute_f32_fn_t compute = (glu_compute_f32_fn_t) gctx->compute; + compute((const float *) in0_spad, (const float *) in1_spad, (float *) out_spad, task->len, gctx); +} + +static void glu_compute_f16(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in0_spad, void * in1_spad) { + const struct htp_glu_context * gctx = ((struct glu_pipe_state *) ctx)->gctx; + glu_compute_f16_fn_t compute = (glu_compute_f16_fn_t) gctx->compute; + compute((const _Float16 *) in0_spad, (const _Float16 *) in1_spad, (_Float16 *) out_spad, task->len, gctx); +} + +static void glu_thread_run(const htp_thread_t * th, unsigned int ith, const struct htp_glu_context * gctx, dma_pipe_compute_io2_fn compute) { + const uint32_t src0_start_row = gctx->row_start + gctx->src0_nrows_per_hvx * ith; + const uint32_t src0_end_row = MIN(src0_start_row + gctx->src0_nrows_per_hvx, gctx->row_start + gctx->src0_nrows); + if (src0_start_row >= src0_end_row) { + return; + } + + uint8_t * src0_spad_data = gctx->vtcm_src0 + (ith * gctx->vtcm_src0_size_per_hvx); + uint8_t * src1_spad_data = gctx->vtcm_src1 + (ith * gctx->vtcm_src1_size_per_hvx); + uint8_t * dst_spad_data = gctx->vtcm_dst + (ith * gctx->vtcm_dst_size_per_hvx); + void * in0_buf[2] = { src0_spad_data, src0_spad_data + gctx->src0_spad_half_size }; + void * in1_buf[2] = { src1_spad_data, src1_spad_data + gctx->src1_spad_half_size }; + void * out_buf[2] = { dst_spad_data, dst_spad_data + gctx->dst_spad_half_size }; + + struct glu_pipe_state s = { + .gctx = gctx, + .ir = src0_start_row, + .ir_end = src0_end_row, + }; + + dma_pipe_io2_run(th->dma_q, th->trace, &s, in0_buf, in1_buf, out_buf, + glu_next_task, glu_push_in, compute, glu_push_out); +} + +static void glu_f32_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; + glu_thread_run(th, ith, (const struct htp_glu_context *) data, glu_compute_f32); +} + +static void glu_f16_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; + glu_thread_run(th, ith, (const struct htp_glu_context *) data, glu_compute_f16); +} static int execute_op_glu_f32(struct htp_ops_context * octx) { const struct htp_tensor * src0 = octx->src[0]; @@ -882,9 +941,7 @@ static int execute_op_glu_f32(struct htp_ops_context * octx) { uint32_t nrows = src0_nrows; if (octx->ctx->mdev.count > 1) { - uint32_t rows_per_chunk = 0; - htp_tensor_mdev_rows_per_chunk(dst, sizeof(float), (uint32_t) dst_row_size, &rows_per_chunk); - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); row_start = range.start; nrows = range.count; } @@ -987,7 +1044,7 @@ static int execute_op_glu_f32(struct htp_ops_context * octx) { gctx.data_src1 = data_src1; gctx.data_dst = dst->data; - work_queue_run(octx->ctx->hvx_queue, (work_queue_func_t)glu_f32_per_hvx, &gctx, n_hvx); + work_queue_run(octx->ctx->hvx_queue, glu_f32_thread, &gctx, n_hvx); return HTP_STATUS_OK; } @@ -1048,9 +1105,7 @@ static int execute_op_glu_f16(struct htp_ops_context * octx) { uint32_t nrows = src0_nrows; if (octx->ctx->mdev.count > 1) { - uint32_t rows_per_chunk = 0; - htp_tensor_mdev_rows_per_chunk(dst, sizeof(_Float16), (uint32_t) dst_row_size, &rows_per_chunk); - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); row_start = range.start; nrows = range.count; } @@ -1153,7 +1208,7 @@ static int execute_op_glu_f16(struct htp_ops_context * octx) { gctx.data_src1 = data_src1; gctx.data_dst = dst->data; - work_queue_run(octx->ctx->hvx_queue, (work_queue_func_t)glu_f16_per_hvx, &gctx, n_hvx); + work_queue_run(octx->ctx->hvx_queue, glu_f16_thread, &gctx, n_hvx); return HTP_STATUS_OK; } diff --git a/ggml/src/ggml-hexagon/htp/hex-utils.h b/ggml/src/ggml-hexagon/htp/hex-utils.h index cb3093dece48..af3a938ac266 100644 --- a/ggml/src/ggml-hexagon/htp/hex-utils.h +++ b/ggml/src/ggml-hexagon/htp/hex-utils.h @@ -65,11 +65,14 @@ static inline void hex_l2fetch_block(const void * addr, size_t size) { static inline void hex_l2flush(void * addr, size_t size) { if (size == 0) return; - const uint32_t s = ((uint32_t) addr) & ~(HEX_L2_LINE_SIZE - 1); - const uint32_t e = (((uint32_t) addr) + size + HEX_L2_LINE_SIZE - 1) & ~(HEX_L2_LINE_SIZE - 1); - for (uint32_t i = s; i < e; i += HEX_L2_LINE_SIZE) { + // Step by 64B (L1D line size on v73+ and L2 line size on v73) so no L1D lines are skipped. + const uint32_t line = 64; + const uint32_t s = ((uint32_t) addr) & ~(line - 1); + const uint32_t e = (((uint32_t) addr) + size + line - 1) & ~(line - 1); + for (uint32_t i = s; i < e; i += line) { Q6_dccleaninva_A((void *) i); } + asm volatile(" syncht\n" : : : "memory"); } static inline void hex_pause() { diff --git a/ggml/src/ggml-hexagon/htp/hmx-fa-kernels.h b/ggml/src/ggml-hexagon/htp/hmx-fa-kernels.h index d5fb48ad9c61..3f061c0b6409 100644 --- a/ggml/src/ggml-hexagon/htp/hmx-fa-kernels.h +++ b/ggml/src/ggml-hexagon/htp/hmx-fa-kernels.h @@ -623,83 +623,4 @@ static inline void hmx_fa_q_prep_fp16_pad(__fp16 * vtcm_q_t } } -static inline void hmx_fa_q_prep_fallback( - __fp16 * vtcm_q_tiles, uintptr_t q_data, - size_t q_nb1, size_t q_nb2, size_t q_nb3, - uint32_t q_start, uint32_t kv_head, uint32_t ib3, - size_t start, size_t end, size_t n_rows_g, - size_t G, size_t dk_in, size_t dk_out, bool is_q_fp32, - const struct fastdiv_values * div_G -) { - for (size_t r = start; r < end; r += 2) { - const size_t q_idx0 = fastdiv(r + 0, div_G); - const size_t h_idx0 = fastmodulo(r + 0, G, div_G); - const size_t q_idx1 = fastdiv(r + 1, div_G); - const size_t h_idx1 = fastmodulo(r + 1, G, div_G); - - const uint8_t * q_ptr0 = (r + 0 < n_rows_g) ? ((const uint8_t *) q_data + (q_start + q_idx0) * q_nb1 + - (kv_head * G + h_idx0) * q_nb2 + ib3 * q_nb3) : - NULL; - const uint8_t * q_ptr1 = (r + 1 < n_rows_g) ? ((const uint8_t *) q_data + (q_start + q_idx1) * q_nb1 + - (kv_head * G + h_idx1) * q_nb2 + ib3 * q_nb3) : - NULL; - - size_t r0 = r / HMX_FP16_TILE_N_ROWS; - size_t r1 = r % HMX_FP16_TILE_N_ROWS; - __fp16 * out_base = vtcm_q_tiles + r0 * HMX_FP16_TILE_N_ROWS * dk_out; - - if (is_q_fp32) { - const HVX_UVector * pv_in0 = q_ptr0 ? (const HVX_UVector *) q_ptr0 : NULL; - const HVX_UVector * pv_in1 = q_ptr1 ? (const HVX_UVector *) q_ptr1 : NULL; - - for (uint32_t d = 0; d < dk_out / 32; ++d) { - HVX_Vector * out_tile = (HVX_Vector *) (out_base + d * HMX_FP16_TILE_N_ELMS); - const size_t base_lane = (size_t) d * 32; - const size_t real_lanes = (base_lane < dk_in) ? hex_smin(32, dk_in - base_lane) : 0; - - if (real_lanes == 0) { - out_tile[r1 / 2] = Q6_V_vzero(); - continue; - } - HVX_Vector v0 = pv_in0 ? pv_in0[d] : Q6_V_vzero(); - HVX_Vector v1 = pv_in1 ? pv_in1[d] : Q6_V_vzero(); - if (real_lanes < 32) { - const HVX_VectorPred keep = Q6_Q_vsetq_R((uint32_t) (real_lanes * sizeof(float))); - v0 = Q6_V_vmux_QVV(keep, v0, Q6_V_vzero()); - v1 = Q6_V_vmux_QVV(keep, v1, Q6_V_vzero()); - } - out_tile[r1 / 2] = hvx_vec_f32_to_f16_shuff(v0, v1); - } - } else { - const HVX_UVector * pv_in0 = q_ptr0 ? (const HVX_UVector *) q_ptr0 : NULL; - const HVX_UVector * pv_in1 = q_ptr1 ? (const HVX_UVector *) q_ptr1 : NULL; - - for (uint32_t d = 0; d < dk_out / 64; ++d) { - __fp16 * out_dtile = out_base + d * HMX_FP16_TILE_N_ELMS * 2; - HVX_Vector * pv_out0 = ((HVX_Vector *) out_dtile) + r1 / 2; - HVX_Vector * pv_out1 = pv_out0 + 16; - - const size_t base_lane = (size_t) d * 64; - const size_t real_lanes = (base_lane < dk_in) ? hex_smin(64, dk_in - base_lane) : 0; - - if (real_lanes == 0) { - *pv_out0 = Q6_V_vzero(); - *pv_out1 = Q6_V_vzero(); - continue; - } - HVX_Vector v0 = pv_in0 ? pv_in0[d] : Q6_V_vzero(); - HVX_Vector v1 = pv_in1 ? pv_in1[d] : Q6_V_vzero(); - if (real_lanes < 64) { - const HVX_VectorPred keep = Q6_Q_vsetq_R((uint32_t) (real_lanes * sizeof(__fp16))); - v0 = Q6_V_vmux_QVV(keep, v0, Q6_V_vzero()); - v1 = Q6_V_vmux_QVV(keep, v1, Q6_V_vzero()); - } - HVX_VectorPair vp = Q6_W_vshuff_VVR(v1, v0, -2); - *pv_out0 = Q6_V_lo_W(vp); - *pv_out1 = Q6_V_hi_W(vp); - } - } - } -} - #endif /* HMX_FA_KERNELS_H */ diff --git a/ggml/src/ggml-hexagon/htp/hmx-fa-w8a8-kernels.h b/ggml/src/ggml-hexagon/htp/hmx-fa-w8a8-kernels.h new file mode 100644 index 000000000000..06bc147cb0c0 --- /dev/null +++ b/ggml/src/ggml-hexagon/htp/hmx-fa-w8a8-kernels.h @@ -0,0 +1,801 @@ +#ifndef HMX_FA_W8A8_KERNELS_H +#define HMX_FA_W8A8_KERNELS_H + +#include +#include +#include + +#include "hex-fastdiv.h" +#include "hmx-int-utils.h" +#include "hmx-utils.h" +#include "hvx-utils.h" + +// Quantize one 4-row quad of FP32 Q into W8A8 U8 SM 64x32 tiles and emit d_q (with scale folded). +static __attribute__((noinline)) void hmx_fa_w8a8_q_prep_quad_f32( + uint8_t * restrict tile_row_base, + float * restrict d_q_out, + const float * restrict p0, + const float * restrict p1, + const float * restrict p2, + const float * restrict p3, + uint32_t rg, + uint32_t n_dot, + uint32_t valid_rows, + float scale_f32) { + + HVX_Vector vmax0 = Q6_V_vzero(); + HVX_Vector vmax1 = Q6_V_vzero(); + HVX_Vector vmax2 = Q6_V_vzero(); + HVX_Vector vmax3 = Q6_V_vzero(); + + for (uint32_t kt = 0; kt < n_dot; ++kt) { + const uint32_t off = kt * 32; + HVX_Vector vx0 = *(const HVX_UVector *) (p0 + off); + HVX_Vector vx1 = *(const HVX_UVector *) (p1 + off); + HVX_Vector vx2 = *(const HVX_UVector *) (p2 + off); + HVX_Vector vx3 = *(const HVX_UVector *) (p3 + off); + vmax0 = Q6_Vsf_vmax_VsfVsf(vmax0, hvx_vec_abs_f32(vx0)); + vmax1 = Q6_Vsf_vmax_VsfVsf(vmax1, hvx_vec_abs_f32(vx1)); + vmax2 = Q6_Vsf_vmax_VsfVsf(vmax2, hvx_vec_abs_f32(vx2)); + vmax3 = Q6_Vsf_vmax_VsfVsf(vmax3, hvx_vec_abs_f32(vx3)); + } + + vmax0 = (valid_rows > 0) ? hvx_vec_reduce_max_f32(vmax0) : Q6_V_vzero(); + vmax1 = (valid_rows > 1) ? hvx_vec_reduce_max_f32(vmax1) : Q6_V_vzero(); + vmax2 = (valid_rows > 2) ? hvx_vec_reduce_max_f32(vmax2) : Q6_V_vzero(); + vmax3 = (valid_rows > 3) ? hvx_vec_reduce_max_f32(vmax3) : Q6_V_vzero(); + + const HVX_Vector v_sc_inv127 = hvx_vec_splat_f32(scale_f32 * (1.0f / 127.0f)); + const HVX_Vector v_127 = hvx_vec_splat_f32(127.0f); + const HVX_Vector v_eps = hvx_vec_splat_f32(1e-30f); + + HVX_Vector vd0 = hvx_vec_mul_f32_f32(vmax0, v_sc_inv127); + HVX_Vector vd1 = hvx_vec_mul_f32_f32(vmax1, v_sc_inv127); + HVX_Vector vd2 = hvx_vec_mul_f32_f32(vmax2, v_sc_inv127); + HVX_Vector vd3 = hvx_vec_mul_f32_f32(vmax3, v_sc_inv127); + HVX_Vector v_d02 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd2, vd0, -4)); + HVX_Vector v_d13 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd3, vd1, -4)); + HVX_Vector v_d = Q6_V_lo_W(Q6_W_vshuff_VVR(v_d13, v_d02, -4)); + hvx_vec_store_u(d_q_out, 4 * sizeof(float), v_d); + + HVX_Vector v_inv0 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax0, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax0), v_127), Q6_V_vzero()); + HVX_Vector v_inv1 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax1, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax1), v_127), Q6_V_vzero()); + HVX_Vector v_inv2 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax2, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax2), v_127), Q6_V_vzero()); + HVX_Vector v_inv3 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax3, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax3), v_127), Q6_V_vzero()); + +#if __HVX_ARCH__ >= 81 + const uint32_t n_pairs = n_dot >> 1; + for (uint32_t step = 0; step < n_pairs; ++step) { + const uint32_t off = step * 64; + HVX_Vector hf0 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p0 + off + 32), v_inv0), + Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p0 + off + 0), v_inv0)))); + HVX_Vector hf1 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p1 + off + 32), v_inv1), + Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p1 + off + 0), v_inv1)))); + HVX_Vector hf2 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p2 + off + 32), v_inv2), + Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p2 + off + 0), v_inv2)))); + HVX_Vector hf3 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p3 + off + 32), v_inv3), + Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p3 + off + 0), v_inv3)))); + + pack_hf_quad_to_u8_sm_pair(tile_row_base, step * 2, rg, hf0, hf1, hf2, hf3); + } + if (n_dot & 1u) { + const uint32_t kt = n_dot - 1u; + const uint32_t off = kt * 32; + const HVX_Vector v_zp_u8 = Q6_Vb_vsplat_R(0x80); + const HVX_Vector v_min_u8b = Q6_Vb_vsplat_R(1); + HVX_Vector hf0 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_V_vzero(), Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p0 + off), v_inv0)))); + HVX_Vector hf1 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_V_vzero(), Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p1 + off), v_inv1)))); + HVX_Vector hf2 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_V_vzero(), Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p2 + off), v_inv2)))); + HVX_Vector hf3 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_V_vzero(), Q6_Vqf32_vmpy_VsfVsf(*(const HVX_UVector *) (p3 + off), v_inv3)))); + + HVX_Vector vb02 = Q6_Vb_vshuff_Vb(Q6_Vb_vpack_VhVh_sat(Q6_Vh_equals_Vhf_rnd(hf2), Q6_Vh_equals_Vhf_rnd(hf0))); + HVX_Vector vb13 = Q6_Vb_vshuff_Vb(Q6_Vb_vpack_VhVh_sat(Q6_Vh_equals_Vhf_rnd(hf3), Q6_Vh_equals_Vhf_rnd(hf1))); + HVX_VectorPair w_u8 = Q6_W_vshuff_VVR(vb13, vb02, -1); + ((HVX_Vector *) (tile_row_base + (size_t) kt * HMX_W8A8_ACT_TILE_SIZE))[rg] = + Q6_Vub_vmax_VubVub(Q6_V_vxor_VV(Q6_V_lo_W(w_u8), v_zp_u8), v_min_u8b); + } +#else + const HVX_Vector v_bias_u8 = Q6_V_vsplat_R(0x4B400080); // 12582912.0f + 128.0f + const HVX_Vector v_min_u8 = Q6_Vh_vsplat_R(1); + const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255); + + for (uint32_t kt = 0; kt < n_dot; ++kt) { + const uint32_t off = kt * 32; + HVX_Vector vx0 = *(const HVX_UVector *) (p0 + off); + HVX_Vector vx1 = *(const HVX_UVector *) (p1 + off); + HVX_Vector vx2 = *(const HVX_UVector *) (p2 + off); + HVX_Vector vx3 = *(const HVX_UVector *) (p3 + off); + + HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0), v_bias_u8)); + HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1), v_bias_u8)); + HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2), v_bias_u8)); + HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3), v_bias_u8)); + + HVX_Vector vh02 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y2, y0), v_min_u8), v_max_u8); + HVX_Vector vh13 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y3, y1), v_min_u8), v_max_u8); + ((HVX_Vector *) (tile_row_base + (size_t) kt * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_Vb_vshuffe_VbVb(vh13, vh02); + } +#endif +} + +// Quantize one 4-row quad of FP16 Q into W8A8 U8 SM 64x32 tiles and emit d_q (with scale folded). +static __attribute__((noinline)) void hmx_fa_w8a8_q_prep_quad_f16( + uint8_t * restrict tile_row_base, + float * restrict d_q_out, + const __fp16 * restrict p0, + const __fp16 * restrict p1, + const __fp16 * restrict p2, + const __fp16 * restrict p3, + uint32_t rg, + uint32_t n_dot, + uint32_t valid_rows, + float scale_f32) { + + const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f); + const HVX_Vector v_abs_f16 = Q6_Vh_vsplat_R(0x7fff); + HVX_Vector vmax_hf0 = Q6_V_vzero(); + HVX_Vector vmax_hf1 = Q6_V_vzero(); + HVX_Vector vmax_hf2 = Q6_V_vzero(); + HVX_Vector vmax_hf3 = Q6_V_vzero(); + + const uint32_t n_pairs = n_dot >> 1; + for (uint32_t step = 0; step < n_pairs; ++step) { + const uint32_t off = step * 64; + HVX_Vector vh0 = *(const HVX_UVector *) (p0 + off); + HVX_Vector vh1 = *(const HVX_UVector *) (p1 + off); + HVX_Vector vh2 = *(const HVX_UVector *) (p2 + off); + HVX_Vector vh3 = *(const HVX_UVector *) (p3 + off); + vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vand_VV(vh0, v_abs_f16)); + vmax_hf1 = Q6_Vhf_vmax_VhfVhf(vmax_hf1, Q6_V_vand_VV(vh1, v_abs_f16)); + vmax_hf2 = Q6_Vhf_vmax_VhfVhf(vmax_hf2, Q6_V_vand_VV(vh2, v_abs_f16)); + vmax_hf3 = Q6_Vhf_vmax_VhfVhf(vmax_hf3, Q6_V_vand_VV(vh3, v_abs_f16)); + } + if (n_dot & 1u) { + const uint32_t off = (n_dot - 1u) * 32; + const HVX_VectorPred q_32h = Q6_Q_vsetq2_R(32 * sizeof(__fp16)); + HVX_Vector vh0 = Q6_V_vmux_QVV(q_32h, *(const HVX_UVector *) (p0 + off), Q6_V_vzero()); + HVX_Vector vh1 = Q6_V_vmux_QVV(q_32h, *(const HVX_UVector *) (p1 + off), Q6_V_vzero()); + HVX_Vector vh2 = Q6_V_vmux_QVV(q_32h, *(const HVX_UVector *) (p2 + off), Q6_V_vzero()); + HVX_Vector vh3 = Q6_V_vmux_QVV(q_32h, *(const HVX_UVector *) (p3 + off), Q6_V_vzero()); + vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vand_VV(vh0, v_abs_f16)); + vmax_hf1 = Q6_Vhf_vmax_VhfVhf(vmax_hf1, Q6_V_vand_VV(vh1, v_abs_f16)); + vmax_hf2 = Q6_Vhf_vmax_VhfVhf(vmax_hf2, Q6_V_vand_VV(vh2, v_abs_f16)); + vmax_hf3 = Q6_Vhf_vmax_VhfVhf(vmax_hf3, Q6_V_vand_VV(vh3, v_abs_f16)); + } + + vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vror_VR(vmax_hf0, 64)); + vmax_hf1 = Q6_Vhf_vmax_VhfVhf(vmax_hf1, Q6_V_vror_VR(vmax_hf1, 64)); + vmax_hf2 = Q6_Vhf_vmax_VhfVhf(vmax_hf2, Q6_V_vror_VR(vmax_hf2, 64)); + vmax_hf3 = Q6_Vhf_vmax_VhfVhf(vmax_hf3, Q6_V_vror_VR(vmax_hf3, 64)); + + HVX_Vector vmax0 = (valid_rows > 0) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf0), v_one_f16)))) : Q6_V_vzero(); + HVX_Vector vmax1 = (valid_rows > 1) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf1), v_one_f16)))) : Q6_V_vzero(); + HVX_Vector vmax2 = (valid_rows > 2) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf2), v_one_f16)))) : Q6_V_vzero(); + HVX_Vector vmax3 = (valid_rows > 3) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf3), v_one_f16)))) : Q6_V_vzero(); + + const HVX_Vector v_sc_inv127 = hvx_vec_splat_f32(scale_f32 * (1.0f / 127.0f)); + const HVX_Vector v_127 = hvx_vec_splat_f32(127.0f); + const HVX_Vector v_eps = hvx_vec_splat_f32(1e-30f); + + HVX_Vector vd0 = hvx_vec_mul_f32_f32(vmax0, v_sc_inv127); + HVX_Vector vd1 = hvx_vec_mul_f32_f32(vmax1, v_sc_inv127); + HVX_Vector vd2 = hvx_vec_mul_f32_f32(vmax2, v_sc_inv127); + HVX_Vector vd3 = hvx_vec_mul_f32_f32(vmax3, v_sc_inv127); + HVX_Vector v_d02 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd2, vd0, -4)); + HVX_Vector v_d13 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd3, vd1, -4)); + HVX_Vector v_d = Q6_V_lo_W(Q6_W_vshuff_VVR(v_d13, v_d02, -4)); + hvx_vec_store_u(d_q_out, 4 * sizeof(float), v_d); + + HVX_Vector v_inv0_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax0, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax0), v_127), Q6_V_vzero())); + HVX_Vector v_inv1_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax1, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax1), v_127), Q6_V_vzero())); + HVX_Vector v_inv2_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax2, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax2), v_127), Q6_V_vzero())); + HVX_Vector v_inv3_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax3, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax3), v_127), Q6_V_vzero())); + +#if __HVX_ARCH__ >= 81 + for (uint32_t step = 0; step < n_pairs; ++step) { + const uint32_t off = step * 64; + HVX_VectorPair vp0 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_UVector *) (p0 + off), v_one_f16); + HVX_VectorPair vp1 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_UVector *) (p1 + off), v_one_f16); + HVX_VectorPair vp2 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_UVector *) (p2 + off), v_one_f16); + HVX_VectorPair vp3 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_UVector *) (p3 + off), v_one_f16); + + HVX_Vector hf0 = Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp0), v_inv0_qf), + Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf))); + HVX_Vector hf1 = Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp1), v_inv1_qf), + Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf))); + HVX_Vector hf2 = Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp2), v_inv2_qf), + Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf))); + HVX_Vector hf3 = Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp3), v_inv3_qf), + Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf))); + + pack_hf_quad_to_u8_sm_pair(tile_row_base, step * 2, rg, hf0, hf1, hf2, hf3); + } + if (n_dot & 1u) { + const uint32_t kt = n_dot - 1u; + const uint32_t off = kt * 32; + const HVX_Vector v_zp_u8 = Q6_Vb_vsplat_R(0x80); + const HVX_Vector v_min_u8b = Q6_Vb_vsplat_R(1); + HVX_VectorPair vp0 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p0 + off)), v_one_f16); + HVX_VectorPair vp1 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p1 + off)), v_one_f16); + HVX_VectorPair vp2 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p2 + off)), v_one_f16); + HVX_VectorPair vp3 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p3 + off)), v_one_f16); + + HVX_Vector hf0 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_V_vzero(), Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf)))); + HVX_Vector hf1 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_V_vzero(), Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf)))); + HVX_Vector hf2 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_V_vzero(), Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf)))); + HVX_Vector hf3 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_V_vzero(), Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf)))); + + HVX_Vector vb02 = Q6_Vb_vshuff_Vb(Q6_Vb_vpack_VhVh_sat(Q6_Vh_equals_Vhf_rnd(hf2), Q6_Vh_equals_Vhf_rnd(hf0))); + HVX_Vector vb13 = Q6_Vb_vshuff_Vb(Q6_Vb_vpack_VhVh_sat(Q6_Vh_equals_Vhf_rnd(hf3), Q6_Vh_equals_Vhf_rnd(hf1))); + HVX_VectorPair w_u8 = Q6_W_vshuff_VVR(vb13, vb02, -1); + ((HVX_Vector *) (tile_row_base + (size_t) kt * HMX_W8A8_ACT_TILE_SIZE))[rg] = + Q6_Vub_vmax_VubVub(Q6_V_vxor_VV(Q6_V_lo_W(w_u8), v_zp_u8), v_min_u8b); + } +#else + const HVX_Vector v_bias_u8 = Q6_V_vsplat_R(0x4B400080); + const HVX_Vector v_min_u8 = Q6_Vh_vsplat_R(1); + const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255); + + for (uint32_t step = 0; step < n_pairs; ++step) { + const uint32_t off = step * 64; + const uint32_t kt = step * 2; + HVX_VectorPair vp0 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p0 + off)), v_one_f16); + HVX_VectorPair vp1 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p1 + off)), v_one_f16); + HVX_VectorPair vp2 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p2 + off)), v_one_f16); + HVX_VectorPair vp3 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p3 + off)), v_one_f16); + + { + HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf), v_bias_u8)); + HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf), v_bias_u8)); + HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf), v_bias_u8)); + HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf), v_bias_u8)); + HVX_Vector vh02 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y2, y0), v_min_u8), v_max_u8); + HVX_Vector vh13 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y3, y1), v_min_u8), v_max_u8); + ((HVX_Vector *) (tile_row_base + (size_t) (kt + 0) * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_Vb_vshuffe_VbVb(vh13, vh02); + } + { + HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp0), v_inv0_qf), v_bias_u8)); + HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp1), v_inv1_qf), v_bias_u8)); + HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp2), v_inv2_qf), v_bias_u8)); + HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp3), v_inv3_qf), v_bias_u8)); + HVX_Vector vh02 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y2, y0), v_min_u8), v_max_u8); + HVX_Vector vh13 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y3, y1), v_min_u8), v_max_u8); + ((HVX_Vector *) (tile_row_base + (size_t) (kt + 1) * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_Vb_vshuffe_VbVb(vh13, vh02); + } + } + if (n_dot & 1u) { + const uint32_t kt = n_dot - 1u; + const uint32_t off = kt * 32; + HVX_VectorPair vp0 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p0 + off)), v_one_f16); + HVX_VectorPair vp1 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p1 + off)), v_one_f16); + HVX_VectorPair vp2 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p2 + off)), v_one_f16); + HVX_VectorPair vp3 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p3 + off)), v_one_f16); + + HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf), v_bias_u8)); + HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf), v_bias_u8)); + HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf), v_bias_u8)); + HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf), v_bias_u8)); + HVX_Vector vh02 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y2, y0), v_min_u8), v_max_u8); + HVX_Vector vh13 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y3, y1), v_min_u8), v_max_u8); + ((HVX_Vector *) (tile_row_base + (size_t) kt * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_Vb_vshuffe_VbVb(vh13, vh02); + } +#endif +} + +static inline void hmx_fa_w8a8_q_prep_f32( + uint8_t * restrict vtcm_q_tiles, + float * restrict vtcm_q_scales, + const uint8_t * restrict temp_q_vtcm, + size_t start, + size_t end, + size_t g_rows_end, + size_t DK, + size_t G, + size_t n_rows_q, + const struct fastdiv_values * div_G, + bool q_transposed, + float scale_f32) { + + const uint32_t n_dot = (uint32_t) (DK / 32); + const HVX_Vector v_zp_u8 = Q6_Vb_vsplat_R(0x80); + + for (size_t r = start; r < end; r += 4) { + const size_t r0 = r >> 6; + const uint32_t rg = (uint32_t) ((r & 63) >> 2); + uint8_t * tile_row_base = vtcm_q_tiles + r0 * n_dot * HMX_W8A8_ACT_TILE_SIZE; + + if (r >= g_rows_end) { + for (uint32_t kt = 0; kt < n_dot; ++kt) { + ((HVX_Vector *) (tile_row_base + (size_t) kt * HMX_W8A8_ACT_TILE_SIZE))[rg] = v_zp_u8; + } + hvx_vec_store_u(vtcm_q_scales + r, 4 * sizeof(float), Q6_V_vzero()); + continue; + } + + const uint32_t valid_rows = (uint32_t) hex_smin(4, g_rows_end - r); + const float * ptrs[4]; + for (uint32_t k = 0; k < 4; ++k) { + if (k < valid_rows) { + const size_t q_idx = fastdiv(r + k, div_G); + const size_t h_idx = fastmodulo(r + k, G, div_G); + const size_t offset = q_transposed ? (h_idx * n_rows_q + q_idx) : (q_idx * G + h_idx); + ptrs[k] = (const float *) (temp_q_vtcm + offset * DK * sizeof(float)); + } else { + ptrs[k] = ptrs[0]; + } + } + + hmx_fa_w8a8_q_prep_quad_f32( + tile_row_base, vtcm_q_scales + r, + ptrs[0], ptrs[1], ptrs[2], ptrs[3], + rg, n_dot, valid_rows, scale_f32); + } +} + +static inline void hmx_fa_w8a8_q_prep_f16( + uint8_t * restrict vtcm_q_tiles, + float * restrict vtcm_q_scales, + const uint8_t * restrict temp_q_vtcm, + size_t start, + size_t end, + size_t g_rows_end, + size_t DK, + size_t G, + size_t n_rows_q, + const struct fastdiv_values * div_G, + bool q_transposed, + float scale_f32) { + + const uint32_t n_dot = (uint32_t) (DK / 32); + const HVX_Vector v_zp_u8 = Q6_Vb_vsplat_R(0x80); + + for (size_t r = start; r < end; r += 4) { + const size_t r0 = r >> 6; + const uint32_t rg = (uint32_t) ((r & 63) >> 2); + uint8_t * tile_row_base = vtcm_q_tiles + r0 * n_dot * HMX_W8A8_ACT_TILE_SIZE; + + if (r >= g_rows_end) { + for (uint32_t kt = 0; kt < n_dot; ++kt) { + ((HVX_Vector *) (tile_row_base + (size_t) kt * HMX_W8A8_ACT_TILE_SIZE))[rg] = v_zp_u8; + } + hvx_vec_store_u(vtcm_q_scales + r, 4 * sizeof(float), Q6_V_vzero()); + continue; + } + + const uint32_t valid_rows = (uint32_t) hex_smin(4, g_rows_end - r); + const __fp16 * ptrs[4]; + for (uint32_t k = 0; k < 4; ++k) { + if (k < valid_rows) { + const size_t q_idx = fastdiv(r + k, div_G); + const size_t h_idx = fastmodulo(r + k, G, div_G); + const size_t offset = q_transposed ? (h_idx * n_rows_q + q_idx) : (q_idx * G + h_idx); + ptrs[k] = (const __fp16 *) (temp_q_vtcm + offset * DK * sizeof(__fp16)); + } else { + ptrs[k] = ptrs[0]; + } + } + + hmx_fa_w8a8_q_prep_quad_f16( + tile_row_base, vtcm_q_scales + r, + ptrs[0], ptrs[1], ptrs[2], ptrs[3], + rg, n_dot, valid_rows, scale_f32); + } +} + +static inline HVX_Vector hmx_fa_w8a8_k_pack4(const uint8_t * p, size_t stride) { + HVX_Vector v0 = *(const HVX_UVector *) (p + 0 * stride); + HVX_Vector v1 = *(const HVX_UVector *) (p + 1 * stride); + HVX_Vector v2 = *(const HVX_UVector *) (p + 2 * stride); + HVX_Vector v3 = *(const HVX_UVector *) (p + 3 * stride); + HVX_Vector p01 = Q6_V_lo_W(Q6_W_vshuff_VVR(v1, v0, -4)); + HVX_Vector p23 = Q6_V_lo_W(Q6_W_vshuff_VVR(v3, v2, -4)); + return Q6_V_lo_W(Q6_W_vshuff_VVR(p23, p01, -8)); +} + +// Same math as int_hmx_rescale_pair_wb, using vadd(-1) instead of vcombine+vmpyacc to avoid Vdd pair spills. +static inline void hmx_fa_w8a8_k_rescale_pair( + HVX_Vector v_q0, + HVX_Vector v_q1, + HVX_Vector v_m_b4, + HVX_Vector * restrict tile_dst, + int pair_idx, + HVX_Vector * restrict v_sum_w, + HVX_Vector * restrict v_l1_w) { + + const HVX_Vector v_neg1_h = Q6_Vh_vsplat_R(-1); + HVX_VectorPair vp_p01 = Q6_Wh_vmpy_VbVb(v_q0, v_m_b4); + HVX_VectorPair vp_p23 = Q6_Wh_vmpy_VbVb(v_q1, v_m_b4); + HVX_Vector v_p23_lo = Q6_Vh_vadd_VhVh(Q6_V_lo_W(vp_p23), v_neg1_h); + HVX_Vector v_p23_hi = Q6_Vh_vadd_VhVh(Q6_V_hi_W(vp_p23), v_neg1_h); + +#if __HVX_ARCH__ >= 79 + HVX_Vector v_W0 = Q6_Vb_vasr_VhVhR_rnd_sat(Q6_V_hi_W(vp_p01), Q6_V_lo_W(vp_p01), 7); + HVX_Vector v_W1 = Q6_Vb_vasr_VhVhR_rnd_sat(v_p23_hi, v_p23_lo, 7); +#else + HVX_Vector v_W0 = Q6_Vb_vround_VhVh_sat(Q6_Vh_vasl_VhR(Q6_V_hi_W(vp_p01), 1), + Q6_Vh_vasl_VhR(Q6_V_lo_W(vp_p01), 1)); + HVX_Vector v_W1 = Q6_Vb_vround_VhVh_sat(Q6_Vh_vasl_VhR(v_p23_hi, 1), + Q6_Vh_vasl_VhR(v_p23_lo, 1)); +#endif + int_hmx_store_and_accum_pair(tile_dst, pair_idx, v_W0, v_W1, v_sum_w, v_l1_w); +} + +// Q8_0 K -> S8 weight.b 32x32 tiles for one column tile (32 KV rows). +static __attribute__((noinline)) void hmx_fa_w8a8_k_prep_tile( + const uint8_t * restrict k_raw, + uint8_t * restrict dst_wt, + float * restrict dst_scales, + HVX_Vector * restrict bias_out, + uint32_t valid_rows, + uint32_t n_dot, + size_t k_raw_row_padded) { + + uint16_t off_l1[64] __attribute__((aligned(128))); + for (uint32_t c = 0; c < 32; ++c) { + off_l1[c] = (c < valid_rows) ? (uint16_t) (c * k_raw_row_padded) : 0; + off_l1[c + 32] = 0; + } + const HVX_Vector v_off_h = *(const HVX_Vector *) off_l1; + const uint32_t mu = (uint32_t) (32 * k_raw_row_padded - 1); + const HVX_VectorPred q_valid_h = Q6_Q_vsetq2_R(valid_rows * sizeof(uint16_t)); + + // Step 1: gather Q8_0 block scales into tile_dst[kt * 8 + 7] and compute per-channel max + HVX_Vector * tile_dst_all = (HVX_Vector *) dst_wt; + for (uint32_t kt = 0; kt < n_dot; ++kt) { + Q6_vgather_ARMVh(&tile_dst_all[kt * 8 + 7], (size_t) (k_raw + kt * 34), mu, v_off_h); + } + hvx_gather_sync(&tile_dst_all[(n_dot - 1) * 8 + 7]); + + const HVX_Vector v_abs_mask = Q6_Vh_vsplat_R(0x7fff); + HVX_Vector v_max_sc = Q6_V_vzero(); + for (uint32_t kt = 0; kt < n_dot; ++kt) { + HVX_Vector v_sc = Q6_V_vmux_QVV(q_valid_h, tile_dst_all[kt * 8 + 7], Q6_V_vzero()); + tile_dst_all[kt * 8 + 7] = v_sc; + v_max_sc = Q6_Vhf_vmax_VhfVhf(v_max_sc, Q6_V_vand_VV(v_sc, v_abs_mask)); + } + + HVX_Vector v_max_sf, v_inv127_qf; + int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf); + + for (uint32_t kt = 0; kt < n_dot; ++kt) { + tile_dst_all[kt * 8 + 7] = int_hmx_m_b4_from_f16(tile_dst_all[kt * 8 + 7], v_inv127_qf); + } + + // Step 2: 32x32-byte vshuffvdd transpose of int8 quants and rescale in-place to weight.b + // Invalid rows (r >= valid_rows) have zeroed scales so v_m_b4 == 0 zeroes their weights. + HVX_Vector v_sum_w = Q6_V_vzero(); + HVX_Vector v_l1_w = Q6_V_vzero(); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t kt = 0; kt < n_dot; ++kt) { + HVX_Vector * tile_dst = tile_dst_all + kt * 8; + const uint8_t * qs_base = k_raw + kt * 34 + 2; + + HVX_Vector b0, b1, b4, b5; + { + HVX_Vector t0 = hmx_fa_w8a8_k_pack4(qs_base + 0 * k_raw_row_padded, k_raw_row_padded); + HVX_Vector t1 = hmx_fa_w8a8_k_pack4(qs_base + 4 * k_raw_row_padded, k_raw_row_padded); + HVX_VectorPair w01 = Q6_W_vshuff_VVR(t1, t0, -16); + HVX_Vector t2 = hmx_fa_w8a8_k_pack4(qs_base + 8 * k_raw_row_padded, k_raw_row_padded); + HVX_Vector t3 = hmx_fa_w8a8_k_pack4(qs_base + 12 * k_raw_row_padded, k_raw_row_padded); + HVX_VectorPair w23 = Q6_W_vshuff_VVR(t3, t2, -16); + + HVX_VectorPair u0 = Q6_W_vshuff_VVR(Q6_V_lo_W(w23), Q6_V_lo_W(w01), -32); + HVX_VectorPair u2 = Q6_W_vshuff_VVR(Q6_V_hi_W(w23), Q6_V_hi_W(w01), -32); + b0 = Q6_V_lo_W(u0); + b1 = Q6_V_hi_W(u0); + b4 = Q6_V_lo_W(u2); + b5 = Q6_V_hi_W(u2); + } + + { + HVX_Vector t4 = hmx_fa_w8a8_k_pack4(qs_base + 16 * k_raw_row_padded, k_raw_row_padded); + HVX_Vector t5 = hmx_fa_w8a8_k_pack4(qs_base + 20 * k_raw_row_padded, k_raw_row_padded); + HVX_VectorPair w45 = Q6_W_vshuff_VVR(t5, t4, -16); + HVX_Vector t6 = hmx_fa_w8a8_k_pack4(qs_base + 24 * k_raw_row_padded, k_raw_row_padded); + HVX_Vector t7 = hmx_fa_w8a8_k_pack4(qs_base + 28 * k_raw_row_padded, k_raw_row_padded); + HVX_VectorPair w67 = Q6_W_vshuff_VVR(t7, t6, -16); + + const HVX_Vector v_m_b4 = tile_dst[7]; + + HVX_VectorPair u1 = Q6_W_vshuff_VVR(Q6_V_lo_W(w67), Q6_V_lo_W(w45), -32); + HVX_VectorPair q01 = Q6_W_vshuff_VVR(Q6_V_lo_W(u1), b0, -64); + hmx_fa_w8a8_k_rescale_pair(Q6_V_lo_W(q01), Q6_V_hi_W(q01), v_m_b4, tile_dst, 0, &v_sum_w, &v_l1_w); + HVX_VectorPair q23 = Q6_W_vshuff_VVR(Q6_V_hi_W(u1), b1, -64); + hmx_fa_w8a8_k_rescale_pair(Q6_V_lo_W(q23), Q6_V_hi_W(q23), v_m_b4, tile_dst, 1, &v_sum_w, &v_l1_w); + + HVX_VectorPair u3 = Q6_W_vshuff_VVR(Q6_V_hi_W(w67), Q6_V_hi_W(w45), -32); + HVX_VectorPair q45 = Q6_W_vshuff_VVR(Q6_V_lo_W(u3), b4, -64); + hmx_fa_w8a8_k_rescale_pair(Q6_V_lo_W(q45), Q6_V_hi_W(q45), v_m_b4, tile_dst, 2, &v_sum_w, &v_l1_w); + HVX_VectorPair q67 = Q6_W_vshuff_VVR(Q6_V_hi_W(u3), b5, -64); + hmx_fa_w8a8_k_rescale_pair(Q6_V_lo_W(q67), Q6_V_hi_W(q67), v_m_b4, tile_dst, 3, &v_sum_w, &v_l1_w); + } + } + + // Step 3: emit per-channel scales and HMX bias banks + emit_int_hmx_scales_and_bias(v_max_sf, 128.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out); +} + +// Decode one 4-row x 32-col W8A8 S tile (out_hi + out_lo) into 4 FP32 vectors. +static inline void hmx_fa_w8a8_eval_s_tile_quad( + const uint8_t * restrict tile_base, + const float * restrict dw_base, + size_t c, + uint32_t da0, + uint32_t da1, + uint32_t da2, + uint32_t da3, + HVX_Vector sign_80, + HVX_Vector * v_out0, + HVX_Vector * v_out1, + HVX_Vector * v_out2, + HVX_Vector * v_out3) { + + const size_t c0 = c >> 5; + const uint8_t * tp = tile_base + c0 * 2 * HMX_W8A8_ACT_TILE_SIZE; + const HVX_Vector v_hi_s8 = Q6_V_vxor_VV(*(const HVX_Vector *) tp, sign_80); + const HVX_Vector v_lo_u8 = *(const HVX_Vector *) (tp + HMX_W8A8_ACT_TILE_SIZE); + const HVX_Vector v_dw_qf = hvx_vec_f32_to_qf32(*(const HVX_Vector *) (dw_base + c)); + HVX_VectorPair vp_i16 = Q6_W_vshuff_VVR(v_hi_s8, v_lo_u8, -1); + HVX_VectorPair vp_i32_01 = Q6_Ww_vunpack_Vh(Q6_V_lo_W(vp_i16)); + HVX_VectorPair vp_i32_23 = Q6_Ww_vunpack_Vh(Q6_V_hi_W(vp_i16)); + + *v_out0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_lo_W(vp_i32_01)), da0), v_dw_qf)); + *v_out1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_hi_W(vp_i32_01)), da1), v_dw_qf)); + *v_out2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_lo_W(vp_i32_23)), da2), v_dw_qf)); + *v_out3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_hi_W(vp_i32_23)), da3), v_dw_qf)); +} + +// Pack 4 rows x 64 FP16 values in [0, 255] (zp = 0) into 1 or 2 U8 SM 64x32 tiles. +static inline void hmx_fa_w8a8_pack_p_quad_u8_sm( + uint8_t * restrict tile_base, + uint32_t kt, + uint32_t rg, + bool write_hi, + HVX_Vector hf0, + HVX_Vector hf1, + HVX_Vector hf2, + HVX_Vector hf3) { +#if __HVX_ARCH__ >= 81 + HVX_Vector vb02 = Q6_Vb_vshuff_Vb(Q6_Vub_vpack_VhVh_sat(Q6_Vh_equals_Vhf_rnd(hf2), Q6_Vh_equals_Vhf_rnd(hf0))); + HVX_Vector vb13 = Q6_Vb_vshuff_Vb(Q6_Vub_vpack_VhVh_sat(Q6_Vh_equals_Vhf_rnd(hf3), Q6_Vh_equals_Vhf_rnd(hf1))); + HVX_VectorPair w_u8 = Q6_W_vshuff_VVR(vb13, vb02, -1); + + ((HVX_Vector *) (tile_base + (size_t) (kt + 0) * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_V_lo_W(w_u8); + if (write_hi) { + ((HVX_Vector *) (tile_base + (size_t) (kt + 1) * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_V_hi_W(w_u8); + } +#else + const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f); + const HVX_Vector v_bias_zp0 = Q6_V_vsplat_R(0x4B400000); // 12582912.0f + const HVX_Vector v_zero = Q6_V_vzero(); + const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255); + + HVX_VectorPair vp0 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(hf0), v_one_f16); + HVX_VectorPair vp1 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(hf1), v_one_f16); + HVX_VectorPair vp2 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(hf2), v_one_f16); + HVX_VectorPair vp3 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(hf3), v_one_f16); + + { + HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_lo_W(vp0), v_bias_zp0)); + HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_lo_W(vp1), v_bias_zp0)); + HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_lo_W(vp2), v_bias_zp0)); + HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_lo_W(vp3), v_bias_zp0)); + HVX_Vector vh02 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y2, y0), v_zero), v_max_u8); + HVX_Vector vh13 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y3, y1), v_zero), v_max_u8); + ((HVX_Vector *) (tile_base + (size_t) (kt + 0) * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_Vb_vshuffe_VbVb(vh13, vh02); + } + if (write_hi) { + HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_hi_W(vp0), v_bias_zp0)); + HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_hi_W(vp1), v_bias_zp0)); + HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_hi_W(vp2), v_bias_zp0)); + HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_hi_W(vp3), v_bias_zp0)); + HVX_Vector vh02 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y2, y0), v_zero), v_max_u8); + HVX_Vector vh13 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y3, y1), v_zero), v_max_u8); + ((HVX_Vector *) (tile_base + (size_t) (kt + 1) * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_Vb_vshuffe_VbVb(vh13, vh02); + } +#endif +} + +// Zero-gather Q8_0 V -> S8 weight.b 32x32 tiles for one DV tile (32 output cols) across kv_rows. +static __attribute__((noinline)) void hmx_fa_w8a8_v_prep_tile( + const uint8_t * restrict v_base, + uint8_t * restrict dst_wt, + float * restrict dst_scales, + HVX_Vector * restrict bias_out, + uint32_t kv_rows, + uint32_t n_col_tiles, + size_t v_raw_row_padded) { + + uint16_t off_full[64] __attribute__((aligned(128))); + for (uint32_t c = 0; c < 32; ++c) { + off_full[c] = (uint16_t) (c * v_raw_row_padded); + off_full[c + 32] = 0; + } + const HVX_Vector v_off_full = *(const HVX_Vector *) off_full; + const uint32_t mu = (uint32_t) (32 * v_raw_row_padded - 1); + + // Pass 1: gather Q8_0 block scales into tile_dst[kt * 8 + 7] and reduce max across kv_rows + HVX_Vector * tile_dst_all = (HVX_Vector *) dst_wt; + for (uint32_t kt = 0; kt < n_col_tiles; ++kt) { + const uint32_t valid = (uint32_t) hex_smin(32, kv_rows - kt * 32); + HVX_Vector v_off = v_off_full; + if (valid < 32) { + uint16_t off_tail[64] __attribute__((aligned(128))); + for (uint32_t c = 0; c < 32; ++c) { + off_tail[c] = (c < valid) ? (uint16_t) (c * v_raw_row_padded) : 0; + off_tail[c + 32] = 0; + } + v_off = *(const HVX_Vector *) off_tail; + } + Q6_vgather_ARMVh(&tile_dst_all[kt * 8 + 7], (size_t) (v_base + (size_t) kt * 32 * v_raw_row_padded), mu, v_off); + } + hvx_gather_sync(&tile_dst_all[(n_col_tiles - 1) * 8 + 7]); + + const HVX_Vector v_abs_mask = Q6_Vh_vsplat_R(0x7fff); + HVX_Vector v_max_sc = Q6_V_vzero(); + for (uint32_t kt = 0; kt < n_col_tiles; ++kt) { + const uint32_t valid = (uint32_t) hex_smin(32, kv_rows - kt * 32); + const HVX_VectorPred q_valid = Q6_Q_vsetq2_R(valid * sizeof(uint16_t)); + HVX_Vector v_sc = Q6_V_vmux_QVV(q_valid, tile_dst_all[kt * 8 + 7], Q6_V_vzero()); + tile_dst_all[kt * 8 + 7] = v_sc; + v_max_sc = Q6_Vhf_vmax_VhfVhf(v_max_sc, Q6_V_vand_VV(v_sc, v_abs_mask)); + } + v_max_sc = hvx_vec_reduce_max_f16(v_max_sc); + + HVX_Vector v_max_sf, v_inv127_qf; + int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf); + + // Pass 2: 4-row vshuff interleave + per-KV-row int8 scale multiply -> S8 weight.b + const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f); + const HVX_Vector v12M_sf = Q6_V_vsplat_R(0x4B400000); + const HVX_Vector v_ones_s8 = Q6_Vb_vsplat_R(1); + HVX_Vector v_l1_w = Q6_V_vzero(); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t kt = 0; kt < n_col_tiles; ++kt) { + HVX_Vector * tile_dst = tile_dst_all + kt * 8; + + HVX_Vector v_sc_qf = Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(tile_dst[7]), v_one_f16)); + HVX_Vector v_m_biased = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(v_sc_qf, v_inv127_qf), v12M_sf)); + HVX_Vector v_m_h = Q6_Vh_vpacke_VwVw(v_m_biased, v_m_biased); + HVX_Vector v_m_b = Q6_Vb_vpacke_VhVh(v_m_h, v_m_h); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t g = 0; g < 8; ++g) { + const uint32_t k0 = kt * 32 + g * 4; + const uint8_t * p0 = v_base + (size_t) k0 * v_raw_row_padded + 2; + HVX_Vector r0 = (k0 + 0 < kv_rows) ? *(const HVX_UVector *) (p0 + 0 * v_raw_row_padded) : Q6_V_vzero(); + HVX_Vector r1 = (k0 + 1 < kv_rows) ? *(const HVX_UVector *) (p0 + 1 * v_raw_row_padded) : Q6_V_vzero(); + HVX_Vector r2 = (k0 + 2 < kv_rows) ? *(const HVX_UVector *) (p0 + 2 * v_raw_row_padded) : Q6_V_vzero(); + HVX_Vector r3 = (k0 + 3 < kv_rows) ? *(const HVX_UVector *) (p0 + 3 * v_raw_row_padded) : Q6_V_vzero(); + + HVX_Vector v02 = Q6_V_lo_W(Q6_W_vshuff_VVR(r2, r0, -1)); + HVX_Vector v13 = Q6_V_lo_W(Q6_W_vshuff_VVR(r3, r1, -1)); + HVX_Vector v_q = Q6_V_lo_W(Q6_W_vshuff_VVR(v13, v02, -1)); + + HVX_Vector v_m = Q6_V_vsplat_R(Q6_R_vextract_VR(v_m_b, (int) (g * 4))); + HVX_VectorPair vp = Q6_Wh_vmpy_VbVb(v_q, v_m); +#if __HVX_ARCH__ >= 79 + HVX_Vector v_W = Q6_Vb_vasr_VhVhR_rnd_sat(Q6_V_hi_W(vp), Q6_V_lo_W(vp), 7); +#else + HVX_Vector v_W = Q6_Vb_vround_VhVh_sat(Q6_Vh_vasl_VhR(Q6_V_hi_W(vp), 1), + Q6_Vh_vasl_VhR(Q6_V_lo_W(vp), 1)); +#endif + tile_dst[g] = v_W; + v_l1_w = Q6_Vw_vrmpyacc_VwVubVb(v_l1_w, Q6_Vb_vabs_Vb(v_W), v_ones_s8); + } + } + + // Pass 3: emit zp=0 per-channel scales and HMX bias banks + emit_int_hmx_scales_and_bias_zp0(v_max_sf, 128.0f / 127.0f, v_l1_w, dst_scales, bias_out); +} + +static inline void hmx_fa_w8a8_gemm_run( + const uint8_t * restrict act_tiles, + const uint8_t * restrict wt_tiles, + const uint8_t * restrict wt_bias, + uint8_t * restrict out_tiles, + uint32_t n_row_tiles_64, + uint32_t n_col_tiles, + uint32_t n_dot_tiles) { + + __builtin_assume(n_row_tiles_64 > 0); + __builtin_assume(n_col_tiles > 0); + __builtin_assume(n_dot_tiles > 0); + + const uint32_t cvt_ctrl_hi = hmx_cvt_ctrl(0, 0, 0, 1); +#if __HVX_ARCH__ >= 79 + const uint32_t cvt_ctrl_lo = hmx_cvt_ctrl(1, 0, 1, 0); +#else + const uint32_t cvt_ctrl_lo = hmx_cvt_ctrl(0, 0, 1, 0); +#endif + const uint32_t a_rng = hmx_act_sm_range(n_dot_tiles); + const uint32_t w_rng = hmx_wt_b_range(n_dot_tiles * HMX_W8A8_WT_TILE_SIZE); + const uint32_t out_cm_rng = hmx_out_cm_range(); + + for (uint32_t j = 0; j < n_col_tiles; ++j) { + const uint8_t * wt_base = wt_tiles + (size_t) j * n_dot_tiles * HMX_W8A8_WT_TILE_SIZE; + const uint8_t * bias_hi = wt_bias + ((size_t) j * 2 + 0) * HMX_W8A8_BIAS_BANK_SIZE; + const uint8_t * bias_lo = wt_bias + ((size_t) j * 2 + 1) * HMX_W8A8_BIAS_BANK_SIZE; +#if __HVX_ARCH__ >= 79 + hmx_load_bias_bank(bias_hi, 0); + hmx_load_bias_bank(bias_lo, 1); +#endif + + for (uint32_t i = 0; i < n_row_tiles_64; ++i) { + const uint8_t * act_base = act_tiles + (size_t) i * n_dot_tiles * HMX_W8A8_ACT_TILE_SIZE; + const size_t out_idx = ((size_t) i * n_col_tiles + j) * 2; + uint8_t * out_hi = out_tiles + (out_idx + 0) * HMX_W8A8_ACT_TILE_SIZE; + uint8_t * out_lo = out_tiles + (out_idx + 1) * HMX_W8A8_ACT_TILE_SIZE; + + asm volatile(HMX_CLRACC_INT()); + asm volatile(HMX_LOAD_MPY_DEEP_U8_S8_SM("%0", "%1", "%2", "%3") + : : "r"(act_base), "r"(a_rng), "r"(wt_base), "r"(w_rng) : "memory"); + +#if __HVX_ARCH__ < 79 + hmx_load_bias_bank(bias_hi, 0); +#endif + asm volatile(HMX_CVT_UB_ACC("%0") : : "r"(cvt_ctrl_hi) : "memory"); + asm volatile(HMX_STORE_CVT_CM("%0", "%1") : : "r"(out_hi), "r"(out_cm_rng) : "memory"); + +#if __HVX_ARCH__ < 79 + hmx_load_bias_bank(bias_lo, 0); +#endif + asm volatile(HMX_CVT_UB_ACC("%0") : : "r"(cvt_ctrl_lo) : "memory"); + asm volatile(HMX_STORE_CVT_CM("%0", "%1") : : "r"(out_lo), "r"(out_cm_rng) : "memory"); + } + } +} + +typedef struct { + const uint8_t * q_tiles; + const uint8_t * k_tiles; + const uint8_t * k_bias; + uint8_t * s_tiles; + uint32_t n_row_tiles_64; + uint32_t n_col_tiles; + uint32_t n_dot_tiles; // DK / 32 +} hmx_fa_w8a8_qk_job_t; + +static void hmx_fa_w8a8_qk_dot_worker(const htp_thread_t * th, void * data) { + (void) th; + hmx_fa_w8a8_qk_job_t * job = (hmx_fa_w8a8_qk_job_t *) data; + hmx_fa_w8a8_gemm_run(job->q_tiles, job->k_tiles, job->k_bias, job->s_tiles, + job->n_row_tiles_64, job->n_col_tiles, job->n_dot_tiles); +} + +typedef struct { + const uint8_t * p_tiles; + const uint8_t * v_tiles; + const uint8_t * v_bias; + uint8_t * do_tiles; + uint32_t n_row_tiles_64; + uint32_t n_v_tiles; // DV / 32 + uint32_t n_dot_tiles; // ceil(kv_rows / 32) +} hmx_fa_w8a8_pv_job_t; + +static void hmx_fa_w8a8_pv_worker(const htp_thread_t * th, void * data) { + (void) th; + hmx_fa_w8a8_pv_job_t * job = (hmx_fa_w8a8_pv_job_t *) data; + hmx_fa_w8a8_gemm_run(job->p_tiles, job->v_tiles, job->v_bias, job->do_tiles, + job->n_row_tiles_64, job->n_v_tiles, job->n_dot_tiles); +} + +#endif /* HMX_FA_W8A8_KERNELS_H */ diff --git a/ggml/src/ggml-hexagon/htp/hmx-int-utils.h b/ggml/src/ggml-hexagon/htp/hmx-int-utils.h new file mode 100644 index 000000000000..8011a36d1be7 --- /dev/null +++ b/ggml/src/ggml-hexagon/htp/hmx-int-utils.h @@ -0,0 +1,209 @@ +#ifndef HMX_INT_UTILS_H +#define HMX_INT_UTILS_H + +#include +#include + +#include "hvx-utils.h" + +#ifndef HMX_W8A8_ACT_TILE_SIZE +#define HMX_W8A8_ACT_TILE_SIZE 2048 +#endif + +static inline HVX_Vector hvx_vec_f32_to_qf32(HVX_Vector v) { +#if __HVX_ARCH__ >= 81 + return Q6_Vqf32_equals_Vsf(v); +#else + return Q6_Vqf32_vadd_VsfVsf(v, Q6_V_vzero()); +#endif +} + +static inline HVX_Vector hvx_qf32_mul_sf_scalar(HVX_Vector v_sf, uint32_t scalar_sf_bits) { +#if __HVX_ARCH__ >= 79 + return Q6_Vqf32_vmpy_VsfRsf(v_sf, (int32_t) scalar_sf_bits); +#else + return Q6_Vqf32_vmpy_VsfVsf(v_sf, Q6_V_vsplat_R((int32_t) scalar_sf_bits)); +#endif +} + +static inline void emit_int_hmx_scales_and_bias( + HVX_Vector v_max_sf, + float scale_const, + HVX_Vector v_sum_w, + HVX_Vector v_l1_w, + float * restrict dst_scales, + HVX_Vector * restrict bias_out) { + + // |sum_k (a - zp) * w_hat| < 128 * l1_w = (l1_w << 7) <= 32768 * 2^p + HVX_Vector v_max_mag = Q6_Vw_vasl_VwR(v_l1_w, 7); + HVX_Vector v_p = Q6_Vw_vmax_VwVw(Q6_V_vzero(), Q6_Vw_vsub_VwVw(Q6_V_vsplat_R(17), Q6_Vuw_vcl0_Vuw(v_max_mag))); + HVX_Vector v_ib = Q6_Vw_vsub_VwVw(Q6_Vw_vasl_VwVw(Q6_V_vsplat_R(32768), v_p), Q6_Vw_vasl_VwR(v_sum_w, 7)); + + HVX_Vector v_dw_base = hvx_vec_mul_f32_f32(v_max_sf, hvx_vec_splat_f32(scale_const)); + HVX_Vector v_pow2_sf = Q6_Vsf_equals_Vw(Q6_Vw_vasl_VwVw(Q6_V_vsplat_R(1), v_p)); + *(HVX_Vector *) dst_scales = hvx_vec_mul_f32_f32(v_dw_base, v_pow2_sf); + + HVX_Vector v_exp_hi = Q6_Vw_vsub_VwVw(Q6_V_vsplat_R(16), v_p); + HVX_Vector v_exp_lo = Q6_Vw_vsub_VwVw(Q6_V_vsplat_R(24), v_p); + bias_out[0] = Q6_Vw_vasl_VwR(v_exp_hi, 10); + bias_out[1] = v_ib; + bias_out[2] = Q6_Vw_vasl_VwR(v_exp_lo, 10); + bias_out[3] = v_ib; +} + +static inline void emit_int_hmx_scales_and_bias_zp0( + HVX_Vector v_max_sf, + float scale_const, + HVX_Vector v_l1_w, + float * restrict dst_scales, + HVX_Vector * restrict bias_out) { + + // Unsigned a_u8 in [0, 255] (zp = 0): |sum_k a_u8 * w_hat| <= 255 * l1_w < (l1_w << 8) <= 32768 * 2^p + HVX_Vector v_max_mag = Q6_Vw_vasl_VwR(v_l1_w, 8); + HVX_Vector v_p = Q6_Vw_vmax_VwVw(Q6_V_vzero(), Q6_Vw_vsub_VwVw(Q6_V_vsplat_R(17), Q6_Vuw_vcl0_Vuw(v_max_mag))); + HVX_Vector v_ib = Q6_Vw_vasl_VwVw(Q6_V_vsplat_R(32768), v_p); + + HVX_Vector v_dw_base = hvx_vec_mul_f32_f32(v_max_sf, hvx_vec_splat_f32(scale_const)); + HVX_Vector v_pow2_sf = Q6_Vsf_equals_Vw(Q6_Vw_vasl_VwVw(Q6_V_vsplat_R(1), v_p)); + *(HVX_Vector *) dst_scales = hvx_vec_mul_f32_f32(v_dw_base, v_pow2_sf); + + HVX_Vector v_exp_hi = Q6_Vw_vsub_VwVw(Q6_V_vsplat_R(16), v_p); + HVX_Vector v_exp_lo = Q6_Vw_vsub_VwVw(Q6_V_vsplat_R(24), v_p); + bias_out[0] = Q6_Vw_vasl_VwR(v_exp_hi, 10); + bias_out[1] = v_ib; + bias_out[2] = Q6_Vw_vasl_VwR(v_exp_lo, 10); + bias_out[3] = v_ib; +} + +static inline HVX_Vector int_hmx_scale_qf_from_max_f32(HVX_Vector v_max_sf, float num) { + HVX_VectorPred q_pos = Q6_Q_vcmp_gt_VsfVsf(v_max_sf, hvx_vec_splat_f32(1e-30f)); + HVX_Vector v_inv_raw = hvx_vec_inverse_f32(v_max_sf); + HVX_Vector v_scale_sf = Q6_V_vmux_QVV(q_pos, hvx_vec_mul_f32_f32(v_inv_raw, hvx_vec_splat_f32(num)), Q6_V_vzero()); + return hvx_vec_f32_to_qf32(v_scale_sf); +} + +static inline HVX_Vector int_hmx_inv127_from_max_f32(HVX_Vector v_max_sf) { + return int_hmx_scale_qf_from_max_f32(v_max_sf, 127.0f); +} + +static inline void int_hmx_inv127_from_max_f16( + HVX_Vector v_max_sc, + HVX_Vector * restrict v_max_sf_out, + HVX_Vector * restrict v_inv127_qf_out) { + const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f); + HVX_Vector v_max_sf = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_max_sc), v_one_f16))); + *v_max_sf_out = v_max_sf; + *v_inv127_qf_out = int_hmx_inv127_from_max_f32(v_max_sf); +} + +static inline HVX_Vector int_hmx_m_b4_from_sc_qf(HVX_Vector v_sc_qf, HVX_Vector v_inv127_qf) { + const HVX_Vector v12M_sf = Q6_V_vsplat_R(0x4B400000); + HVX_Vector v_m_biased = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(v_sc_qf, v_inv127_qf), v12M_sf)); + HVX_Vector v_m_h = Q6_Vh_vpacke_VwVw(v_m_biased, v_m_biased); + return Q6_Vh_vshuff_Vh(Q6_Vb_vshuff_Vb(Q6_Vb_vpacke_VhVh(v_m_h, v_m_h))); +} + +static inline HVX_Vector int_hmx_m_b4_from_f16(HVX_Vector v_sc, HVX_Vector v_inv127_qf) { + const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f); + HVX_Vector v_sc_qf = Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_sc), v_one_f16)); + return int_hmx_m_b4_from_sc_qf(v_sc_qf, v_inv127_qf); +} + +static inline void int_hmx_m_b4_pair_from_f16( + HVX_Vector v_sc, + HVX_Vector v_inv127_qf, + HVX_Vector * restrict v_m_b0_out, + HVX_Vector * restrict v_m_b1_out) { + const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f); + HVX_VectorPair vp_sc_qf = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_sc), v_one_f16); + *v_m_b0_out = int_hmx_m_b4_from_sc_qf(Q6_V_lo_W(vp_sc_qf), v_inv127_qf); + *v_m_b1_out = int_hmx_m_b4_from_sc_qf(Q6_V_hi_W(vp_sc_qf), v_inv127_qf); +} + +static inline void int_hmx_store_and_accum_pair( + HVX_Vector * restrict tile_dst, + int pair_idx, + HVX_Vector v_W0, + HVX_Vector v_W1, + HVX_Vector * restrict v_sum_w, + HVX_Vector * restrict v_l1_w) { + + const HVX_Vector v_ones_s8 = Q6_Vb_vsplat_R(1); + tile_dst[2 * pair_idx + 0] = v_W0; + tile_dst[2 * pair_idx + 1] = v_W1; + + *v_sum_w = Q6_Vw_vrmpyacc_VwVbVb(Q6_Vw_vrmpyacc_VwVbVb(*v_sum_w, v_W0, v_ones_s8), v_W1, v_ones_s8); + *v_l1_w = Q6_Vw_vrmpyacc_VwVubVb(Q6_Vw_vrmpyacc_VwVubVb(*v_l1_w, Q6_Vb_vabs_Vb(v_W0), v_ones_s8), Q6_Vb_vabs_Vb(v_W1), v_ones_s8); +} + +static inline void int_hmx_rescale_pair_wb( + HVX_Vector v_q0, + HVX_Vector v_q1, + HVX_Vector v_m_b4, + HVX_Vector * restrict tile_dst, + int pair_idx, + HVX_Vector * restrict v_sum_w, + HVX_Vector * restrict v_l1_w) { + + HVX_Vector v_neg1_h = Q6_Vh_vsplat_R(-1); + HVX_VectorPair vp_tie_adj = Q6_W_vcombine_VV(v_neg1_h, v_neg1_h); + HVX_VectorPair vp_p01 = Q6_Wh_vmpy_VbVb(v_q0, v_m_b4); + HVX_VectorPair vp_p23 = Q6_Wh_vmpyacc_WhVbVb(vp_tie_adj, v_q1, v_m_b4); + +#if __HVX_ARCH__ >= 79 + HVX_Vector v_W0 = Q6_Vb_vasr_VhVhR_rnd_sat(Q6_V_hi_W(vp_p01), Q6_V_lo_W(vp_p01), 7); + HVX_Vector v_W1 = Q6_Vb_vasr_VhVhR_rnd_sat(Q6_V_hi_W(vp_p23), Q6_V_lo_W(vp_p23), 7); +#else + HVX_Vector v_W0 = Q6_Vb_vround_VhVh_sat(Q6_Vh_vasl_VhR(Q6_V_hi_W(vp_p01), 1), + Q6_Vh_vasl_VhR(Q6_V_lo_W(vp_p01), 1)); + HVX_Vector v_W1 = Q6_Vb_vround_VhVh_sat(Q6_Vh_vasl_VhR(Q6_V_hi_W(vp_p23), 1), + Q6_Vh_vasl_VhR(Q6_V_lo_W(vp_p23), 1)); +#endif + int_hmx_store_and_accum_pair(tile_dst, pair_idx, v_W0, v_W1, v_sum_w, v_l1_w); +} + +#if __HVX_ARCH__ >= 81 +static inline void pack_hf_quad_to_u8_sm_pair( + uint8_t * restrict tile_base, + uint32_t kt, + uint32_t rg, + HVX_Vector hf0, + HVX_Vector hf1, + HVX_Vector hf2, + HVX_Vector hf3) { + const HVX_Vector v_zp_u8 = Q6_Vb_vsplat_R(0x80); + const HVX_Vector v_min_u8b = Q6_Vb_vsplat_R(1); + + HVX_Vector vb02 = Q6_Vb_vshuff_Vb(Q6_Vb_vpack_VhVh_sat(Q6_Vh_equals_Vhf_rnd(hf2), Q6_Vh_equals_Vhf_rnd(hf0))); + HVX_Vector vb13 = Q6_Vb_vshuff_Vb(Q6_Vb_vpack_VhVh_sat(Q6_Vh_equals_Vhf_rnd(hf3), Q6_Vh_equals_Vhf_rnd(hf1))); + HVX_VectorPair w_u8 = Q6_W_vshuff_VVR(vb13, vb02, -1); + + ((HVX_Vector *) (tile_base + (size_t) (kt + 0) * HMX_W8A8_ACT_TILE_SIZE))[rg] = + Q6_Vub_vmax_VubVub(Q6_V_vxor_VV(Q6_V_lo_W(w_u8), v_zp_u8), v_min_u8b); + ((HVX_Vector *) (tile_base + (size_t) (kt + 1) * HMX_W8A8_ACT_TILE_SIZE))[rg] = + Q6_Vub_vmax_VubVub(Q6_V_vxor_VV(Q6_V_hi_W(w_u8), v_zp_u8), v_min_u8b); +} + +static inline void hmx_pack_hf_quad_to_u8_cm_pair( + uint8_t * restrict tile_base, + uint32_t kt, + uint32_t rg, + HVX_Vector hf0, + HVX_Vector hf1, + HVX_Vector hf2, + HVX_Vector hf3) { + const HVX_Vector v_zp_u8 = Q6_Vb_vsplat_R(0x80); + const HVX_Vector v_min_u8b = Q6_Vb_vsplat_R(1); + + HVX_Vector vb01 = Q6_Vb_vpack_VhVh_sat(Q6_Vh_equals_Vhf_rnd(hf1), Q6_Vh_equals_Vhf_rnd(hf0)); + HVX_Vector vb23 = Q6_Vb_vpack_VhVh_sat(Q6_Vh_equals_Vhf_rnd(hf3), Q6_Vh_equals_Vhf_rnd(hf2)); + HVX_VectorPair w_u8 = Q6_W_vdeal_VVR(vb23, vb01, -32); + + ((HVX_Vector *) (tile_base + (size_t) (kt + 0) * HMX_W8A8_ACT_TILE_SIZE))[rg] = + Q6_Vub_vmax_VubVub(Q6_V_vxor_VV(Q6_V_lo_W(w_u8), v_zp_u8), v_min_u8b); + ((HVX_Vector *) (tile_base + (size_t) (kt + 1) * HMX_W8A8_ACT_TILE_SIZE))[rg] = + Q6_Vub_vmax_VubVub(Q6_V_vxor_VV(Q6_V_hi_W(w_u8), v_zp_u8), v_min_u8b); +} +#endif + +#endif /* HMX_INT_UTILS_H */ diff --git a/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled-fp.h b/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled-fp.h new file mode 100644 index 000000000000..05eb3ebfc093 --- /dev/null +++ b/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled-fp.h @@ -0,0 +1,2035 @@ +#include "hmx-utils.h" +#include "hmx-queue.h" + +// MXFP4 dequantization LUT: maps 4-bit index to fp16 mantissa value +// kvalues: 0, 0.5, 1, 1.5, 2, 3, 4, 6, 0, -0.5, -1, -1.5, -2, -3, -4, -6 +static const __fp16 mxfp4_to_fp16_lut[64] __attribute__((aligned(VLEN))) = { + 0, 0, 0.5, 0, 1, 0, 1.5, 0, 2, 0, 3, 0, 4, 0, 6, 0, 0, 0, -0.5, 0, -1, 0, -1.5, 0, -2, 0, -3, 0, -4, 0, -6, 0, +}; + +static const __fp16 iq4_nl_to_fp16_lut[64] __attribute__((aligned(VLEN))) = { + -127, 0, -104, 0, -83, 0, -65, 0, -49, 0, -35, 0, -22, 0, -10, 0, + 1, 0, 13, 0, 25, 0, 38, 0, 53, 0, 69, 0, 89, 0, 113, 0, +}; + +// --- tiled format dequantizers --- + +typedef struct tiled_dequantize_state tiled_dequantize_state_t; +typedef void (*tiled_dequant_task_fn_t)(const tiled_dequantize_state_t * state, uint32_t start_tile, uint32_t end_tile); + +struct tiled_dequantize_state { + __fp16 * dst; + const uint8_t * src; + tiled_dequant_task_fn_t task_fn; + + struct fastdiv_values n_k_tiles_div; + uint32_t n_k_tiles; + uint32_t n_weight_tiles; + uint32_t n_tot_tiles; + uint32_t n_tiles_per_task; + uint32_t tile_size; + uint32_t aligned_tile_size; + uint32_t n_tasks; + uint32_t n_cols; + uint32_t k_block; + size_t row_stride; + uint32_t weight_type; +}; + +static void dequantize_tiled_weight_to_fp16_task_q1_0( + const tiled_dequantize_state_t *state, + uint32_t start_tile, uint32_t end_tile) { + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q1_0); + const HVX_Vector v_neg_one = Q6_Vb_vsplat_R(-1); + const HVX_Vector v_pos_one = Q6_Vb_vsplat_R(1); + const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride; + __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * (4 * HTP_MM_HMX_TILE_N_ELMS); + + for (uint32_t t = start_tile; t < end_tile; t++) { + const HVX_Vector v_sc = hvx_vmem(tile_src + 512); + const HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); + + for (uint32_t q = 0; q < 4; q++) { + const HVX_Vector v_plane = hvx_vmem(tile_src + q * 128); + __fp16 * quarter_dst = dst_ptr + q * HTP_MM_HMX_TILE_N_ELMS; + + #pragma unroll + for (int g = 0; g < 8; g++) { + const HVX_Vector v_q = unpack_q1_0_group(v_plane, g, v_neg_one, v_pos_one); + const HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_q); + const HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4); + + hvx_vmem(quarter_dst + (2 * g + 0) * 64) = + Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale)); + hvx_vmem(quarter_dst + (2 * g + 1) * 64) = + Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale)); + } + } + tile_src += tile_stride; + dst_ptr += 4 * HTP_MM_HMX_TILE_N_ELMS; + } +} + +static inline void dequantize_q4_0_fp16_tile_step( + const uint8_t * restrict tile_src, + __fp16 * restrict dst_ptr, + HVX_Vector v_scale, + HVX_Vector mask_h4, + HVX_Vector i8) { + + #pragma unroll + for (int i = 0; i < 4; ++i) { + HVX_Vector vq = hvx_vmem(tile_src + i * 128); + HVX_Vector v_lo = Q6_Vb_vsub_VbVb(Q6_V_vand_VV(vq, mask_h4), i8); + HVX_Vector v_hi = Q6_Vb_vsub_VbVb(Q6_Vub_vlsr_VubR(vq, 4), i8); + HVX_VectorPair vp_lo = Q6_Wh_vunpack_Vb(v_lo); + HVX_VectorPair vp_k0 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_lo), Q6_V_lo_W(vp_lo), -4); + HVX_VectorPair vp_hi = Q6_Wh_vunpack_Vb(v_hi); + HVX_VectorPair vp_k1 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_hi), Q6_V_lo_W(vp_hi), -4); + + hvx_vmem(dst_ptr + (4 * i + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k0)), v_scale)); + hvx_vmem(dst_ptr + (4 * i + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k0)), v_scale)); + hvx_vmem(dst_ptr + (4 * i + 2) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k1)), v_scale)); + hvx_vmem(dst_ptr + (4 * i + 3) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k1)), v_scale)); + } +} + +// Dequantize a single tile from tiled weight data (already in VTCM) to tile-major FP16. +static void dequantize_tiled_weight_to_fp16_task_q4_0( + const tiled_dequantize_state_t *state, + uint32_t start_tile, uint32_t end_tile) { + + if (start_tile >= end_tile) { + return; + } + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q4_0); + const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F); + const HVX_Vector i8 = Q6_Vb_vsplat_R(8); + const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride; + __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS; + + HVX_Vector v_sc = hvx_vmem(tile_src + 512); + HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t t = start_tile; t + 1 < end_tile; t++) { + HVX_Vector v_sc_next = hvx_vmem(tile_src + tile_stride + 512); + HVX_Vector v_scale_next = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc_next, v_sc_next, -2)); + dequantize_q4_0_fp16_tile_step(tile_src, dst_ptr, v_scale, mask_h4, i8); + v_scale = v_scale_next; + tile_src += tile_stride; + dst_ptr += HTP_MM_HMX_TILE_N_ELMS; + } + dequantize_q4_0_fp16_tile_step(tile_src, dst_ptr, v_scale, mask_h4, i8); +} + +static inline void dequantize_q4_1_fp16_tile_step( + const uint8_t * restrict tile_src, + __fp16 * restrict dst_ptr, + HVX_Vector v_scale, + HVX_Vector v_offset, + HVX_Vector mask_h4) { + + #pragma unroll + for (int i = 0; i < 4; ++i) { + HVX_Vector vq = hvx_vmem(tile_src + i * 128); + HVX_Vector v_lo = Q6_V_vand_VV(vq, mask_h4); + HVX_Vector v_hi = Q6_Vub_vlsr_VubR(vq, 4); + HVX_VectorPair vp_lo = Q6_Wh_vunpack_Vb(v_lo); + HVX_VectorPair vp_k0 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_lo), Q6_V_lo_W(vp_lo), -4); + HVX_VectorPair vp_hi = Q6_Wh_vunpack_Vb(v_hi); + HVX_VectorPair vp_k1 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_hi), Q6_V_lo_W(vp_hi), -4); + + hvx_vmem(dst_ptr + (4 * i + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k0)), v_scale), v_offset)); + hvx_vmem(dst_ptr + (4 * i + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k0)), v_scale), v_offset)); + hvx_vmem(dst_ptr + (4 * i + 2) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k1)), v_scale), v_offset)); + hvx_vmem(dst_ptr + (4 * i + 3) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k1)), v_scale), v_offset)); + } +} + +static void dequantize_tiled_weight_to_fp16_task_q4_1( + const tiled_dequantize_state_t *state, + uint32_t start_tile, uint32_t end_tile) { + + if (start_tile >= end_tile) { + return; + } + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q4_1); + const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F); + const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride; + __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS; + + HVX_Vector v_dm = hvx_vmem(tile_src + 512); + HVX_VectorPair dm_deal = Q6_W_vdeal_VVR(v_dm, v_dm, -2); + HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_lo_W(dm_deal), Q6_V_lo_W(dm_deal), -2)); + HVX_Vector v_offset = Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_hi_W(dm_deal), Q6_V_hi_W(dm_deal), -2)); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t t = start_tile; t + 1 < end_tile; t++) { + HVX_Vector v_dm_next = hvx_vmem(tile_src + tile_stride + 512); + HVX_VectorPair dm_deal_next = Q6_W_vdeal_VVR(v_dm_next, v_dm_next, -2); + HVX_Vector v_scale_next = Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_lo_W(dm_deal_next), Q6_V_lo_W(dm_deal_next), -2)); + HVX_Vector v_offset_next = Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_hi_W(dm_deal_next), Q6_V_hi_W(dm_deal_next), -2)); + dequantize_q4_1_fp16_tile_step(tile_src, dst_ptr, v_scale, v_offset, mask_h4); + v_scale = v_scale_next; + v_offset = v_offset_next; + tile_src += tile_stride; + dst_ptr += HTP_MM_HMX_TILE_N_ELMS; + } + dequantize_q4_1_fp16_tile_step(tile_src, dst_ptr, v_scale, v_offset, mask_h4); +} + +static inline void dequantize_4bit_lut_fp16_tile_step( + const uint8_t * restrict tile_src, + __fp16 * restrict dst_ptr, + HVX_Vector v_scale, + HVX_Vector vlut_cvt, + HVX_Vector mask_h4) { + + #pragma unroll + for (int i = 0; i < 4; ++i) { + HVX_Vector vq = hvx_vmem(tile_src + i * 128); + HVX_Vector v_lo = Q6_V_vand_VV(vq, mask_h4); + HVX_Vector v_hi = Q6_Vub_vlsr_VubR(vq, 4); + HVX_VectorPair vp_d = Q6_W_vdeal_VVR(v_hi, v_lo, -2); + HVX_VectorPair vp_s = Q6_W_vshuff_VVR(Q6_V_hi_W(vp_d), Q6_V_lo_W(vp_d), -1); + HVX_VectorPair vp_lo = Q6_Wh_vlut16_VbVhR(Q6_V_lo_W(vp_s), vlut_cvt, 0); + HVX_VectorPair vp_hi = Q6_Wh_vlut16_VbVhR(Q6_V_hi_W(vp_s), vlut_cvt, 0); + + hvx_vmem(dst_ptr + (4 * i + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo), v_scale)); + hvx_vmem(dst_ptr + (4 * i + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo), v_scale)); + hvx_vmem(dst_ptr + (4 * i + 2) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi), v_scale)); + hvx_vmem(dst_ptr + (4 * i + 3) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi), v_scale)); + } +} + +static void dequantize_tiled_weight_to_fp16_task_iq4_nl( + const tiled_dequantize_state_t *state, + uint32_t start_tile, uint32_t end_tile) { + + if (start_tile >= end_tile) { + return; + } + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_IQ4_NL); + const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F); + const HVX_Vector vlut_cvt = hvx_vmem(iq4_nl_to_fp16_lut); + const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride; + __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS; + + HVX_Vector v_sc = hvx_vmem(tile_src + 512); + HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t t = start_tile; t + 1 < end_tile; t++) { + HVX_Vector v_sc_next = hvx_vmem(tile_src + tile_stride + 512); + HVX_Vector v_scale_next = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc_next, v_sc_next, -2)); + dequantize_4bit_lut_fp16_tile_step(tile_src, dst_ptr, v_scale, vlut_cvt, mask_h4); + v_scale = v_scale_next; + tile_src += tile_stride; + dst_ptr += HTP_MM_HMX_TILE_N_ELMS; + } + dequantize_4bit_lut_fp16_tile_step(tile_src, dst_ptr, v_scale, vlut_cvt, mask_h4); +} + +static inline HVX_Vector mxfp4_e8m0_to_f16_scale(HVX_Vector v_raw) { + HVX_Vector vh = Q6_V_lo_W(Q6_Wuh_vunpack_Vub(v_raw)); + vh = Q6_Vh_vsub_VhVh(vh, Q6_Vh_vsplat_R(112)); + vh = Q6_Vh_vmax_VhVh(vh, Q6_V_vzero()); + vh = Q6_Vh_vmin_VhVh(vh, Q6_Vh_vsplat_R(30)); + vh = Q6_Vh_vasl_VhR(vh, 10); + return Q6_V_lo_W(Q6_W_vshuff_VVR(vh, vh, -2)); +} + +static void dequantize_tiled_weight_to_fp16_task_mxfp4( + const tiled_dequantize_state_t *state, + uint32_t start_tile, uint32_t end_tile) { + + if (start_tile >= end_tile) { + return; + } + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_MXFP4); + const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F); + const HVX_Vector vlut_cvt = hvx_vmem(mxfp4_to_fp16_lut); + const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride; + __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS; + + HVX_Vector v_scale = mxfp4_e8m0_to_f16_scale(hvx_vmem(tile_src + 512)); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t t = start_tile; t + 1 < end_tile; t++) { + HVX_Vector v_scale_next = mxfp4_e8m0_to_f16_scale(hvx_vmem(tile_src + tile_stride + 512)); + dequantize_4bit_lut_fp16_tile_step(tile_src, dst_ptr, v_scale, vlut_cvt, mask_h4); + v_scale = v_scale_next; + tile_src += tile_stride; + dst_ptr += HTP_MM_HMX_TILE_N_ELMS; + } + dequantize_4bit_lut_fp16_tile_step(tile_src, dst_ptr, v_scale, vlut_cvt, mask_h4); +} + +static inline void dequantize_q8_0_fp16_tile_step( + const uint8_t * restrict tile_src, + __fp16 * restrict dst_ptr, + HVX_Vector v_scale) { + + #pragma unroll + for (int i = 0; i < 8; ++i) { + HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(hvx_vmem(tile_src + i * 128)); + HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4); + hvx_vmem(dst_ptr + (2 * i + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale)); + hvx_vmem(dst_ptr + (2 * i + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale)); + } +} + +static void dequantize_tiled_weight_to_fp16_task_q8_0( + const tiled_dequantize_state_t *state, + uint32_t start_tile, uint32_t end_tile) { + + if (start_tile >= end_tile) { + return; + } + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q8_0); + const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride; + __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS; + + HVX_Vector v_sc = hvx_vmem(tile_src + 1024); + HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t t = start_tile; t + 1 < end_tile; t++) { + HVX_Vector v_sc_next = hvx_vmem(tile_src + tile_stride + 1024); + HVX_Vector v_scale_next = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc_next, v_sc_next, -2)); + dequantize_q8_0_fp16_tile_step(tile_src, dst_ptr, v_scale); + v_scale = v_scale_next; + tile_src += tile_stride; + dst_ptr += HTP_MM_HMX_TILE_N_ELMS; + } + dequantize_q8_0_fp16_tile_step(tile_src, dst_ptr, v_scale); +} + +static inline void dequantize_q5_k_fp16_tile_step( + const uint8_t * restrict tile_src, + __fp16 * restrict dst_ptr, + HVX_Vector v_scale, + HVX_Vector v_offset, + HVX_Vector mask_h4) { + + HVX_Vector v_plane = hvx_vmem(tile_src + 640); + #pragma unroll + for (int i = 0; i < 4; ++i) { + HVX_Vector vq = hvx_vmem(tile_src + i * 128); + HVX_Vector v_lo = hvx_q5k_or_hibit(Q6_V_vand_VV(vq, mask_h4), v_plane, 2 * i + 0); + HVX_Vector v_hi = hvx_q5k_or_hibit(Q6_Vub_vlsr_VubR(vq, 4), v_plane, 2 * i + 1); + HVX_VectorPair vp_lo = Q6_Wh_vunpack_Vb(v_lo); + HVX_VectorPair vp_k0 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_lo), Q6_V_lo_W(vp_lo), -4); + HVX_VectorPair vp_hi = Q6_Wh_vunpack_Vb(v_hi); + HVX_VectorPair vp_k1 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_hi), Q6_V_lo_W(vp_hi), -4); + + hvx_vmem(dst_ptr + (4 * i + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k0)), v_scale), v_offset)); + hvx_vmem(dst_ptr + (4 * i + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k0)), v_scale), v_offset)); + hvx_vmem(dst_ptr + (4 * i + 2) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k1)), v_scale), v_offset)); + hvx_vmem(dst_ptr + (4 * i + 3) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k1)), v_scale), v_offset)); + } +} + +static void dequantize_tiled_weight_to_fp16_task_q5_k( + const tiled_dequantize_state_t *state, + uint32_t start_tile, uint32_t end_tile) { + + if (start_tile >= end_tile) { + return; + } + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q5_K); + const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F); + const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride; + __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS; + + HVX_Vector v_dm = hvx_vmem(tile_src + 512); + HVX_VectorPair dm_deal = Q6_W_vdeal_VVR(v_dm, v_dm, -2); + HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_lo_W(dm_deal), Q6_V_lo_W(dm_deal), -2)); + HVX_Vector v_offset = Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_hi_W(dm_deal), Q6_V_hi_W(dm_deal), -2)); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t t = start_tile; t + 1 < end_tile; t++) { + HVX_Vector v_dm_next = hvx_vmem(tile_src + tile_stride + 512); + HVX_VectorPair dm_deal_next = Q6_W_vdeal_VVR(v_dm_next, v_dm_next, -2); + HVX_Vector v_scale_next = Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_lo_W(dm_deal_next), Q6_V_lo_W(dm_deal_next), -2)); + HVX_Vector v_offset_next = Q6_V_lo_W(Q6_W_vshuff_VVR(Q6_V_hi_W(dm_deal_next), Q6_V_hi_W(dm_deal_next), -2)); + dequantize_q5_k_fp16_tile_step(tile_src, dst_ptr, v_scale, v_offset, mask_h4); + v_scale = v_scale_next; + v_offset = v_offset_next; + tile_src += tile_stride; + dst_ptr += HTP_MM_HMX_TILE_N_ELMS; + } + dequantize_q5_k_fp16_tile_step(tile_src, dst_ptr, v_scale, v_offset, mask_h4); +} + +static inline void dequantize_q5_0_fp16_tile_step( + const uint8_t * restrict tile_src, + __fp16 * restrict dst_ptr, + HVX_Vector v_scale, + HVX_Vector mask_h4) { + + HVX_Vector v_plane = hvx_vmem(tile_src + 512); + #pragma unroll + for (int i = 0; i < 4; ++i) { + HVX_Vector vq = hvx_vmem(tile_src + i * 128); + HVX_Vector v_lo = hvx_q5_0_or_neg(Q6_V_vand_VV(vq, mask_h4), v_plane, 2 * i + 0); + HVX_Vector v_hi = hvx_q5_0_or_neg(Q6_Vub_vlsr_VubR(vq, 4), v_plane, 2 * i + 1); + HVX_VectorPair vp_lo = Q6_Wh_vunpack_Vb(v_lo); + HVX_VectorPair vp_k0 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_lo), Q6_V_lo_W(vp_lo), -4); + HVX_VectorPair vp_hi = Q6_Wh_vunpack_Vb(v_hi); + HVX_VectorPair vp_k1 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp_hi), Q6_V_lo_W(vp_hi), -4); + + hvx_vmem(dst_ptr + (4 * i + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k0)), v_scale)); + hvx_vmem(dst_ptr + (4 * i + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k0)), v_scale)); + hvx_vmem(dst_ptr + (4 * i + 2) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k1)), v_scale)); + hvx_vmem(dst_ptr + (4 * i + 3) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k1)), v_scale)); + } +} + +static void dequantize_tiled_weight_to_fp16_task_q5_0( + const tiled_dequantize_state_t *state, + uint32_t start_tile, uint32_t end_tile) { + + if (start_tile >= end_tile) { + return; + } + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q5_0); + const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F); + const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride; + __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS; + + HVX_Vector v_sc = hvx_vmem(tile_src + 640); + HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t t = start_tile; t + 1 < end_tile; t++) { + HVX_Vector v_sc_next = hvx_vmem(tile_src + tile_stride + 640); + HVX_Vector v_scale_next = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc_next, v_sc_next, -2)); + dequantize_q5_0_fp16_tile_step(tile_src, dst_ptr, v_scale, mask_h4); + v_scale = v_scale_next; + tile_src += tile_stride; + dst_ptr += HTP_MM_HMX_TILE_N_ELMS; + } + dequantize_q5_0_fp16_tile_step(tile_src, dst_ptr, v_scale, mask_h4); +} + +// Q6_K stores 6-bit weights and one fp16 scale per 16 k, see HTP_TENSOR_TILE_SIZE_Q6_K. +// A k-group holds 4 k per row, the HMX tile holds 2, so each group is dealt into two tiles. +static void dequantize_tiled_weight_to_fp16_task_q6_k( + const tiled_dequantize_state_t *state, + uint32_t start_tile, uint32_t end_tile) { + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q6_K); + const HVX_Vector mask_0f = Q6_Vb_vsplat_R(0x0F); + const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03); + const HVX_Vector i32 = Q6_Vb_vsplat_R(32); + const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride; + __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS; + + for (uint32_t t = start_tile; t < end_tile; t++) { + const HVX_Vector * vptr = (const HVX_Vector *) tile_src; + + HVX_Vector v_sc = vptr[6]; + HVX_Vector v_sc_k16 = Q6_V_vror_VR(v_sc, 64); + HVX_Vector v_scale_k0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); + HVX_Vector v_scale_k16 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc_k16, v_sc_k16, -2)); + + #pragma unroll + for (int g = 0; g < 8; g++) { + const HVX_Vector v_scale = (g < 4) ? v_scale_k0 : v_scale_k16; + HVX_Vector v_q = unpack_q6_k_group(vptr, g, mask_0f, mask_03, i32); + HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_q); + HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4); + + hvx_vmem(dst_ptr + (2 * g + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale)); + hvx_vmem(dst_ptr + (2 * g + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale)); + } + tile_src += tile_stride; + dst_ptr += HTP_MM_HMX_TILE_N_ELMS; + } +} + +#define NVFP4_UE4M3_F16_MAN_SHIFT 7 // 10 - 3 mantissa bits +#define NVFP4_UE4M3_F16_REBIAS 0x2000 // (15 - 7) << 10 +#define NVFP4_UE4M3_F16_SUB_SCALE 0x1800 // 2^-9 as fp16 bits +#define IQ2XXS_D_SCALE_F16 0x3000 // 0.125 as fp16 bits + +// UE4M3 codes in the low byte of each halfword -> fp16 +static inline HVX_Vector nvfp4_ue4m3_to_f16(HVX_Vector v_code) { + HVX_Vector v_mask = Q6_Vh_vsplat_R(NVFP4_UE4M3_MASK); + HVX_Vector v_x = Q6_V_vand_VV(v_code, v_mask); + + HVX_Vector v_norm = Q6_Vh_vadd_VhVh(Q6_Vh_vasl_VhR(v_x, NVFP4_UE4M3_F16_MAN_SHIFT), Q6_Vh_vsplat_R(NVFP4_UE4M3_F16_REBIAS)); + HVX_Vector v_sub = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(v_x), Q6_Vh_vsplat_R(NVFP4_UE4M3_F16_SUB_SCALE))); + + HVX_VectorPred q_sub = Q6_Q_vcmp_gt_VhVh(Q6_Vh_vsplat_R(NVFP4_UE4M3_MIN_NORMAL), v_x); + HVX_VectorPred q_nan = Q6_Q_vcmp_eq_VhVh(v_x, v_mask); + + return Q6_V_vmux_QVV(q_nan, Q6_V_vzero(), Q6_V_vmux_QVV(q_sub, v_sub, v_norm)); +} + +// NVFP4 tiles are MXFP4 quants with one UE4M3 scale per 16 k (sub-block 0: k 0..15, sub-block 1: k 16..31) +static void dequantize_tiled_weight_to_fp16_task_nvfp4( + const tiled_dequantize_state_t *state, + uint32_t start_tile, uint32_t end_tile) { + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_NVFP4); + const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F); + const HVX_Vector vlut_cvt = hvx_vmem(mxfp4_to_fp16_lut); + const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride; + __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS; + + for (uint32_t t = start_tile; t < end_tile; t++) { + HVX_Vector v_d = nvfp4_ue4m3_to_f16(Q6_V_lo_W(Q6_Wuh_vunpack_Vub(hvx_vmem(tile_src + NVFP4_SCALE_OFF)))); + HVX_VectorPair vp_d = Q6_W_vshuff_VVR(v_d, v_d, -2); + HVX_Vector v_scale_k0 = Q6_V_lo_W(vp_d); + HVX_Vector v_scale_k16 = Q6_V_hi_W(vp_d); + + #pragma unroll + for (int g = 0; g < 4; g++) { + const HVX_Vector v_scale = (g < 2) ? v_scale_k0 : v_scale_k16; + + HVX_Vector vq = hvx_vmem(tile_src + g * 128); + HVX_Vector v_lo = Q6_V_vand_VV(vq, mask_h4); + HVX_Vector v_hi = Q6_Vub_vlsr_VubR(vq, 4); + HVX_VectorPair vp_d = Q6_W_vdeal_VVR(v_hi, v_lo, -2); + HVX_VectorPair vp_s = Q6_W_vshuff_VVR(Q6_V_hi_W(vp_d), Q6_V_lo_W(vp_d), -1); + HVX_VectorPair vp_lo = Q6_Wh_vlut16_VbVhR(Q6_V_lo_W(vp_s), vlut_cvt, 0); + HVX_VectorPair vp_hi = Q6_Wh_vlut16_VbVhR(Q6_V_hi_W(vp_s), vlut_cvt, 0); + + hvx_vmem(dst_ptr + (4 * g + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo), v_scale)); + hvx_vmem(dst_ptr + (4 * g + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo), v_scale)); + hvx_vmem(dst_ptr + (4 * g + 2) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi), v_scale)); + hvx_vmem(dst_ptr + (4 * g + 3) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi), v_scale)); + } + tile_src += tile_stride; + dst_ptr += HTP_MM_HMX_TILE_N_ELMS; + } +} + +// IQ2_XXS: int8 grid weights from the VTCM LUT, scaled by d / 8 * (2 * scale + 1) per row +static void dequantize_tiled_weight_to_fp16_task_iq2_xxs( + const tiled_dequantize_state_t *state, + uint32_t start_tile, uint32_t end_tile) { + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_IQ2_XXS); + HVX_Vector v_d = Q6_V_vzero(); + const HVX_Vector v_eighth = Q6_Vh_vsplat_R(IQ2XXS_D_SCALE_F16); + const uint8_t * restrict tile = state->src + (size_t) start_tile * tile_stride; + __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS; + + HVX_Vector v_sgn = Q6_V_vzero(); + if (start_tile < end_tile) { + v_sgn = iq2xxs_gather_issue(tile); + } + + for (uint32_t t = start_tile; t < end_tile; t++) { + // rows hold all k tiles and n_k_tiles is a multiple of 8, so t % 8 is the tile within its super-block + if (t == start_tile || (t & (IQ2XXS_TILES_PER_SB - 1)) == 0) { + v_d = iq2xxs_gather_d(tile - (size_t) (t & (IQ2XXS_TILES_PER_SB - 1)) * tile_stride); + } + + HVX_Vector v_c[2], v_w[2 * IQ2XXS_GROUPS], v_ls; + iq2xxs_gather_wait(tile, v_c); + const HVX_Vector v_sgn_cur = v_sgn; + if (t + 1 < end_tile) { + v_sgn = iq2xxs_gather_issue(tile + tile_stride); + } + iq2xxs_decode_expand(v_c, v_sgn_cur, v_w, &v_ls); + + HVX_Vector v_ls_h = Q6_Vhf_equals_Vh(Q6_Vh_vpacke_VwVw(v_ls, v_ls)); + HVX_Vector v_sc = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(v_d, v_ls_h)); + HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); + + #pragma unroll + for (int g = 0; g < 2 * IQ2XXS_GROUPS; g++) { + HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_w[g]); + HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4); + + // d / 8 is subnormal in fp16 for real weights, so apply the 1/8 after the multiply by d * ls + HVX_Vector v_lo = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale)); + HVX_Vector v_hi = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale)); + hvx_vmem(dst_ptr + (2 * g + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(v_lo, v_eighth)); + hvx_vmem(dst_ptr + (2 * g + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(v_hi, v_eighth)); + } + tile += tile_stride; + dst_ptr += HTP_MM_HMX_TILE_N_ELMS; + } +} + +// Q3_K stores 3-bit weights and one fp16 scale per 16 k, see HTP_TENSOR_TILE_SIZE_Q3_K. +static void dequantize_tiled_weight_to_fp16_task_q3_k( + const tiled_dequantize_state_t *state, + uint32_t start_tile, uint32_t end_tile) { + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q3_K); + const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03); + const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride; + __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS; + + for (uint32_t t = start_tile; t < end_tile; t++) { + const HVX_Vector * vptr = (const HVX_Vector *) tile_src; + + HVX_Vector v_sc = vptr[3]; + HVX_Vector v_sc_k16 = Q6_V_vror_VR(v_sc, 64); + HVX_Vector v_scale_k0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); + HVX_Vector v_scale_k16 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc_k16, v_sc_k16, -2)); + + #pragma unroll + for (int g = 0; g < 8; g++) { + const HVX_Vector v_scale = (g < 4) ? v_scale_k0 : v_scale_k16; + + HVX_Vector v_q = unpack_q3_k_group(vptr, g, mask_03); + HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_q); + HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4); + + hvx_vmem(dst_ptr + (2 * g + 0) * 64) = + Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale)); + hvx_vmem(dst_ptr + (2 * g + 1) * 64) = + Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale)); + } + tile_src += tile_stride; + dst_ptr += HTP_MM_HMX_TILE_N_ELMS; + } +} + +// Q2_K stores 2-bit weights, the ggml scale bytes and d / -dmin per super-block, see HTP_TENSOR_TILE_SIZE_Q2_K. +static void dequantize_tiled_weight_to_fp16_task_q2_k( + const tiled_dequantize_state_t *state, + uint32_t start_tile, uint32_t end_tile) { + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q2_K); + const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03); + HVX_Vector v_d = Q6_V_vzero(); + HVX_Vector v_dm = Q6_V_vzero(); + const uint8_t * restrict tile = state->src + (size_t) start_tile * tile_stride; + __fp16 * restrict dst_ptr = state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS; + + for (uint32_t t = start_tile; t < end_tile; t++) { + const HVX_Vector * vptr = (const HVX_Vector *) tile; + + // rows hold all k tiles and n_k_tiles is a multiple of 8, so t % 8 is the tile within its super-block + if (t == start_tile || (t & 7) == 0) { + q2_k_load_dmin(tile - (size_t) (t & 7) * tile_stride, &v_d, &v_dm); + } + + HVX_Vector v_sc, v_m; + q2_k_unpack_scales(tile, v_d, v_dm, &v_sc, &v_m); + HVX_Vector v_sc_k16 = Q6_V_vror_VR(v_sc, 64); + HVX_Vector v_m_k16 = Q6_V_vror_VR(v_m, 64); + HVX_Vector v_scale_k0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); + HVX_Vector v_scale_k16 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc_k16, v_sc_k16, -2)); + HVX_Vector v_offset_k0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_m, v_m, -2)); + HVX_Vector v_offset_k16 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_m_k16, v_m_k16, -2)); + + #pragma unroll + for (int g = 0; g < 8; g++) { + const HVX_Vector v_scale = (g < 4) ? v_scale_k0 : v_scale_k16; + const HVX_Vector v_offset = (g < 4) ? v_offset_k0 : v_offset_k16; + + HVX_Vector v_q = unpack_q3_k_low2(vptr, g, mask_03); + HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_q); + HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4); + + hvx_vmem(dst_ptr + (2 * g + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf( + Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale), v_offset)); + hvx_vmem(dst_ptr + (2 * g + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf( + Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale), v_offset)); + } + tile += tile_stride; + dst_ptr += HTP_MM_HMX_TILE_N_ELMS; + } +} + +// Q2_0 stores codes 0..3 (value code - 1) and one fp16 scale per row, see HTP_MM_WEIGHT_TILE_SIZE_Q2_0. +// One packed 64-k tile expands into two consecutive 32-k fp16 tiles. +static void dequantize_tiled_weight_to_fp16_task_q2_0( + const tiled_dequantize_state_t *state, + uint32_t start_tile, uint32_t end_tile) { + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q2_0); + const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03); + const HVX_Vector i1 = Q6_Vb_vsplat_R(1); + const uint8_t * restrict tile_src = state->src + (size_t) start_tile * tile_stride; + __fp16 * restrict dst_base = state->dst + (size_t) start_tile * (2 * HTP_MM_HMX_TILE_N_ELMS); + + for (uint32_t t = start_tile; t < end_tile; t++) { + const HVX_Vector * vptr = (const HVX_Vector *) tile_src; + + HVX_Vector v_sc = vptr[4]; + HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); + + for (int half = 0; half < 2; half++) { + __fp16 * dst_ptr = dst_base + half * HTP_MM_HMX_TILE_N_ELMS; + + #pragma unroll + for (int g = 0; g < 8; g++) { + HVX_Vector v_q = Q6_Vb_vsub_VbVb(unpack_q3_k_low2(vptr + 2 * half, g, mask_03), i1); + HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_q); + HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4); + + hvx_vmem(dst_ptr + (2 * g + 0) * 64) = + Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale)); + hvx_vmem(dst_ptr + (2 * g + 1) * 64) = + Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale)); + } + } + tile_src += tile_stride; + dst_base += 2 * HTP_MM_HMX_TILE_N_ELMS; + } +} + +static __attribute__((noinline)) +void convert_f16_weight_to_fp16_tiles_task( + const tiled_dequantize_state_t *state, + uint32_t start_tile, uint32_t end_tile) { + + const uint32_t n_k_tiles = state->n_k_tiles; + const struct fastdiv_values n_k_tiles_div = state->n_k_tiles_div; + + const HVX_Vector v_scat_base = hvx_vmem(hmx_transpose_scatter_offsets); + const HVX_Vector v_scat_step = Q6_V_vsplat_R(4); + const HVX_VectorPred q_mask64 = Q6_Q_vsetq_R(64); + + unsigned ct = fastdiv((unsigned)start_tile, &n_k_tiles_div); + unsigned kt = fastmodulo((unsigned)start_tile, n_k_tiles, &n_k_tiles_div); + + for (unsigned t = start_tile; t < (unsigned)end_tile; ) { + if (kt >= (unsigned)n_k_tiles) { kt = 0; ct++; } + + __fp16 *tile_base = state->dst + t * HTP_MM_HMX_TILE_N_ELMS; + { + uint32_t byte_off = kt * 32 * sizeof(__fp16); + + HVX_Vector v_off = v_scat_base; + for (uint32_t r = 0; r < HTP_MM_HMX_TILE_N_ROWS; r += 2) { + uint32_t row0 = ct * HTP_MM_HMX_TILE_N_COLS + r; + uint32_t row1 = row0 + 1; + + const uint8_t *r0 = state->src + row0 * state->row_stride; + const uint8_t *r1 = state->src + row1 * state->row_stride; + + HVX_Vector v0 = (row0 < state->n_cols) ? hvx_vmemu((const __fp16 *)(r0 + byte_off)) : Q6_V_vzero(); + HVX_Vector v1 = (row1 < state->n_cols) ? hvx_vmemu((const __fp16 *)(r1 + byte_off)) : Q6_V_vzero(); + + Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v0); + v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step); + Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v1); + v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step); + } + } + ++t; ++kt; + } + hvx_gather_sync(state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS); +} + +static __attribute__((noinline)) +void quantize_f32_weight_to_fp16_tiles_task( + const tiled_dequantize_state_t *state, + uint32_t start_tile, uint32_t end_tile) { + + const uint32_t n_k_tiles = state->n_k_tiles; + const struct fastdiv_values n_k_tiles_div = state->n_k_tiles_div; + + const HVX_Vector v_scat_base = hvx_vmem(hmx_transpose_scatter_offsets); + const HVX_Vector v_scat_step = Q6_V_vsplat_R(4); + const HVX_VectorPred q_mask64 = Q6_Q_vsetq_R(64); + + unsigned ct = fastdiv((unsigned)start_tile, &n_k_tiles_div); + unsigned kt = fastmodulo((unsigned)start_tile, n_k_tiles, &n_k_tiles_div); + + for (unsigned t = start_tile; t < (unsigned)end_tile; ) { + if (kt >= (unsigned)n_k_tiles) { kt = 0; ct++; } + + __fp16 *tile_base = state->dst + t * HTP_MM_HMX_TILE_N_ELMS; + { + uint32_t byte_off = kt * 32 * sizeof(float); + + HVX_Vector v_off = v_scat_base; + for (uint32_t r = 0; r < HTP_MM_HMX_TILE_N_ROWS; r += 2) { + uint32_t row0 = ct * HTP_MM_HMX_TILE_N_COLS + r; + uint32_t row1 = row0 + 1; + + const uint8_t *r0 = state->src + row0 * state->row_stride; + const uint8_t *r1 = state->src + row1 * state->row_stride; + + HVX_Vector v0_f32 = (row0 < state->n_cols) ? hvx_vmem((const float *)(r0 + byte_off)) : Q6_V_vzero(); + HVX_Vector v1_f32 = (row1 < state->n_cols) ? hvx_vmem((const float *)(r1 + byte_off)) : Q6_V_vzero(); + + HVX_Vector v_out = hvx_vec_f32_to_f16(v0_f32, v1_f32); + + Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v_out); + v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step); + + HVX_Vector v_out_hi = Q6_V_vror_VR(v_out, 64); + Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v_out_hi); + v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step); + } + } + ++t; ++kt; + } + hvx_gather_sync(state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS); +} + +static __attribute__((noinline)) +void convert_bf16_weight_to_fp16_tiles_task( + const tiled_dequantize_state_t *state, + uint32_t start_tile, uint32_t end_tile) { + + const uint32_t n_k_tiles = state->n_k_tiles; + const struct fastdiv_values n_k_tiles_div = state->n_k_tiles_div; + + const HVX_Vector v_scat_base = hvx_vmem(hmx_transpose_scatter_offsets); + const HVX_Vector v_scat_step = Q6_V_vsplat_R(4); + const HVX_VectorPred q_mask64 = Q6_Q_vsetq_R(64); + + unsigned ct = fastdiv((unsigned)start_tile, &n_k_tiles_div); + unsigned kt = fastmodulo((unsigned)start_tile, n_k_tiles, &n_k_tiles_div); + + for (unsigned t = start_tile; t < (unsigned)end_tile; ) { + if (kt >= (unsigned)n_k_tiles) { kt = 0; ct++; } + + __fp16 *tile_base = state->dst + t * HTP_MM_HMX_TILE_N_ELMS; + { + uint32_t byte_off = kt * 32 * sizeof(uint16_t); + + HVX_Vector v_off = v_scat_base; + for (uint32_t r = 0; r < HTP_MM_HMX_TILE_N_ROWS; r += 2) { + uint32_t row0 = ct * HTP_MM_HMX_TILE_N_COLS + r; + uint32_t row1 = row0 + 1; + + const uint8_t *r0 = state->src + row0 * state->row_stride; + const uint8_t *r1 = state->src + row1 * state->row_stride; + + HVX_Vector v0_raw = (row0 < state->n_cols) ? hvx_vmemu((const void *)(r0 + byte_off)) : Q6_V_vzero(); + HVX_Vector v1_raw = (row1 < state->n_cols) ? hvx_vmemu((const void *)(r1 + byte_off)) : Q6_V_vzero(); + + HVX_Vector v0_f32 = Q6_Vw_vasl_VwR(Q6_V_lo_W(Q6_Ww_vunpack_Vh(v0_raw)), 16); + HVX_Vector v1_f32 = Q6_Vw_vasl_VwR(Q6_V_lo_W(Q6_Ww_vunpack_Vh(v1_raw)), 16); + + HVX_Vector v_out = hvx_vec_f32_to_f16(v0_f32, v1_f32); + + Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v_out); + v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step); + + HVX_Vector v_out_hi = Q6_V_vror_VR(v_out, 64); + Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v_out_hi); + v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step); + } + } + ++t; ++kt; + } + hvx_gather_sync(state->dst + (size_t) start_tile * HTP_MM_HMX_TILE_N_ELMS); +} + +// --- End tiled dequantizers --- + +// dot-chunk functions require external HMX lock + +static void core_dot_chunk_fp16_short(__fp16 *restrict output, const __fp16 *restrict activation, + const __fp16 *restrict weight, const __fp16 *restrict scales, + uint32_t n_row_tiles, uint32_t n_col_tiles, uint32_t n_dot_tiles) { + __builtin_assume(n_row_tiles > 0); + __builtin_assume(n_col_tiles > 0); + __builtin_assume(n_dot_tiles > 0); + __builtin_assume(n_dot_tiles <= 32); + + asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int)scales)); + + const size_t dot_stride = n_dot_tiles * HTP_MM_HMX_TILE_N_ELMS; + const uint32_t range = 2048u * n_dot_tiles - 1; + + for (uint32_t r = 0; r < n_row_tiles; ++r) { + const __fp16 *row_base = activation + r * dot_stride; + const __fp16 *col_base = weight; + __fp16 *out_tile = output + r * n_col_tiles * HTP_MM_HMX_TILE_N_ELMS; + + for (size_t c = 0; c < n_col_tiles; ++c) { + asm volatile(HMX_CLRACC_F16()); + asm volatile(HMX_LOAD_MPY_DEEP_F16("%1", "%2", "%0") : : "r"(range), "r"(row_base), "r"(col_base)); + asm volatile(HMX_STORE_AFTER_F16("%0", "%1") : : "r"(out_tile), "r"(0) : "memory"); + col_base += dot_stride; + out_tile += HTP_MM_HMX_TILE_N_ELMS; + } + } +} + +static void core_dot_chunk_fp16(__fp16 *restrict output, const __fp16 *restrict activation, + const __fp16 *restrict weight, const __fp16 *restrict scales, + uint32_t n_row_tiles, uint32_t n_col_tiles, uint32_t n_dot_tiles) { + if (n_dot_tiles <= 32) { + core_dot_chunk_fp16_short(output, activation, weight, scales, n_row_tiles, n_col_tiles, n_dot_tiles); + return; + } + __builtin_assume(n_row_tiles > 0); + __builtin_assume(n_col_tiles > 0); + __builtin_assume(n_dot_tiles > 32); + + asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int)scales)); + + const size_t dot_stride = n_dot_tiles * HTP_MM_HMX_TILE_N_ELMS; + + for (uint32_t r = 0; r < n_row_tiles; ++r) { + const __fp16 *row_base = activation + r * dot_stride; + const __fp16 *col_base = weight; + __fp16 *out_tile = output + r * n_col_tiles * HTP_MM_HMX_TILE_N_ELMS; + + for (size_t c = 0; c < n_col_tiles; ++c) { + const __fp16 *row_tiles = row_base; + const __fp16 *col_tiles = col_base; + + asm volatile(HMX_CLRACC_F16()); + + const uint32_t n_loops = n_dot_tiles / 32; + const uint32_t rem = n_dot_tiles % 32; + + for (uint32_t l = 0; l < n_loops; ++l) { + asm volatile(HMX_LOAD_MPY_DEEP_F16("%1", "%2", "%0") : : "r"(65535), "r"(row_tiles), "r"(col_tiles)); + row_tiles += 32 * HTP_MM_HMX_TILE_N_ELMS; + col_tiles += 32 * HTP_MM_HMX_TILE_N_ELMS; + } + + if (rem > 0) { + const uint32_t range = 2048u * rem - 1; + asm volatile(HMX_LOAD_MPY_DEEP_F16("%1", "%2", "%0") : : "r"(range), "r"(row_tiles), "r"(col_tiles)); + } + + asm volatile(HMX_STORE_AFTER_F16("%0", "%1") : : "r"(out_tile), "r"(0) : "memory"); + + col_base += dot_stride; + out_tile += HTP_MM_HMX_TILE_N_ELMS; + } + } +} + +// output : fp16 -> f32 / f16 + +static inline HVX_Vector hmx_load_bias_f32_32_f16(const void * bias_row_base, size_t c) { + const __fp16 * p = (const __fp16 *) bias_row_base + c; + return Q6_V_lo_W(hvx_vec_f16_to_f32(hvx_vmemu(p))); +} + +static inline HVX_Vector hmx_load_bias_f32_32_f32(const void * bias_row_base, size_t c) { + const float * p = (const float *) bias_row_base + c; + return hvx_vmemu(p); +} + +static inline HVX_VectorPair hmx_load_bias_f32_64_f16(const void * bias_row_base, size_t c) { + const __fp16 * p = (const __fp16 *) bias_row_base + c; + return hvx_vec_f16_to_f32(hvx_vmemu(p)); +} + +static inline HVX_VectorPair hmx_load_bias_f32_64_f32(const void * bias_row_base, size_t c) { + const float * p = (const float *) bias_row_base + c; + return Q6_W_vcombine_VV(hvx_vmemu(p + 32), hvx_vmemu(p)); +} + +static inline HVX_Vector hmx_pack_f32_to_f16_clamped(HVX_Vector v0, HVX_Vector v1) { + const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); + const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); + v0 = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v0)); + v1 = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v1)); + return hvx_vec_f32_to_f16(v0, v1); +} + +static inline HVX_Vector hmx_add_bias_to_f16_vec64_f16(HVX_Vector v_f16, const void * bias_row_base, size_t c) { + HVX_VectorPair vp_dst = hvx_vec_f16_to_f32(v_f16); + HVX_VectorPair vp_bias = hmx_load_bias_f32_64_f16(bias_row_base, c); + HVX_Vector v0 = hvx_vec_add_f32_f32(Q6_V_lo_W(vp_dst), Q6_V_lo_W(vp_bias)); + HVX_Vector v1 = hvx_vec_add_f32_f32(Q6_V_hi_W(vp_dst), Q6_V_hi_W(vp_bias)); + return hmx_pack_f32_to_f16_clamped(v0, v1); +} + +static inline HVX_Vector hmx_add_bias_to_f16_vec64_f32(HVX_Vector v_f16, const void * bias_row_base, size_t c) { + HVX_VectorPair vp_dst = hvx_vec_f16_to_f32(v_f16); + HVX_VectorPair vp_bias = hmx_load_bias_f32_64_f32(bias_row_base, c); + HVX_Vector v0 = hvx_vec_add_f32_f32(Q6_V_lo_W(vp_dst), Q6_V_lo_W(vp_bias)); + HVX_Vector v1 = hvx_vec_add_f32_f32(Q6_V_hi_W(vp_dst), Q6_V_hi_W(vp_bias)); + return hmx_pack_f32_to_f16_clamped(v0, v1); +} + +static inline HVX_Vector hmx_add_bias_to_f16_tail_f16(HVX_Vector v_f16, const void * bias_row_base, size_t c, size_t valid_c) { + HVX_VectorPair vp_dst = hvx_vec_f16_to_f32(v_f16); + HVX_VectorPair vp_bias = hmx_load_bias_f32_64_f16(bias_row_base, c); + HVX_Vector v0 = hvx_vec_add_f32_f32(Q6_V_lo_W(vp_dst), Q6_V_lo_W(vp_bias)); + HVX_Vector v1 = (valid_c > 32) ? hvx_vec_add_f32_f32(Q6_V_hi_W(vp_dst), Q6_V_hi_W(vp_bias)) : Q6_V_vzero(); + return hmx_pack_f32_to_f16_clamped(v0, v1); +} + +static inline HVX_Vector hmx_add_bias_to_f16_tail_f32(HVX_Vector v_f16, const void * bias_row_base, size_t c, size_t valid_c) { + HVX_VectorPair vp_dst = hvx_vec_f16_to_f32(v_f16); + HVX_Vector v0 = hvx_vec_add_f32_f32(Q6_V_lo_W(vp_dst), hmx_load_bias_f32_32_f32(bias_row_base, c)); + HVX_Vector v1 = (valid_c > 32) ? hvx_vec_add_f32_f32(Q6_V_hi_W(vp_dst), hmx_load_bias_f32_32_f32(bias_row_base, c + 32)) : Q6_V_vzero(); + return hmx_pack_f32_to_f16_clamped(v0, v1); +} + +#define HMX_FP16_ADD_BIAS_F32_NONE(v_out, row_ptr, c) (v_out) +#define HMX_FP16_ADD_BIAS_F32_F16(v_out, row_ptr, c) hvx_vec_add_f32_f32((v_out), hmx_load_bias_f32_32_f16((row_ptr), (c))) +#define HMX_FP16_ADD_BIAS_F32_F32(v_out, row_ptr, c) hvx_vec_add_f32_f32((v_out), hmx_load_bias_f32_32_f32((row_ptr), (c))) + +#define HMX_FP16_ADD_BIAS_F16_64_NONE(v_out, row_ptr, c) (v_out) +#define HMX_FP16_ADD_BIAS_F16_64_F16(v_out, row_ptr, c) hmx_add_bias_to_f16_vec64_f16((v_out), (row_ptr), (c)) +#define HMX_FP16_ADD_BIAS_F16_64_F32(v_out, row_ptr, c) hmx_add_bias_to_f16_vec64_f32((v_out), (row_ptr), (c)) + +#define HMX_FP16_ADD_BIAS_F16_TAIL_NONE(v_out, row_ptr, c, vc) (v_out) +#define HMX_FP16_ADD_BIAS_F16_TAIL_F16(v_out, row_ptr, c, vc) hmx_add_bias_to_f16_tail_f16((v_out), (row_ptr), (c), (vc)) +#define HMX_FP16_ADD_BIAS_F16_TAIL_F32(v_out, row_ptr, c, vc) hmx_add_bias_to_f16_tail_f32((v_out), (row_ptr), (c), (vc)) + +#define HMX_FP16_BIAS_ROW0_none(bias, off) NULL +#define HMX_FP16_BIAS_ROW0_f16(bias, off) ((const uint8_t *) (bias) + (off)) +#define HMX_FP16_BIAS_ROW0_f32(bias, off) ((const uint8_t *) (bias) + (off)) + +#define HMX_FP16_BIAS_ROW1_none(row0, rb) NULL +#define HMX_FP16_BIAS_ROW1_f16(row0, rb) ((row0) + (rb)) +#define HMX_FP16_BIAS_ROW1_f32(row0, rb) ((row0) + (rb)) + +#define HMX_FP16_BIAS_STEP_none(ptr, step) (void) 0 +#define HMX_FP16_BIAS_STEP_f16(ptr, step) ((ptr) += (step)) +#define HMX_FP16_BIAS_STEP_f32(ptr, step) ((ptr) += (step)) + +#define HMX_STORE_VEC_nt(PTR, VEC) hvx_vmem_store_nt((PTR), (VEC)) +#define HMX_STORE_VEC_u(PTR, VEC) (hvx_vmemu((PTR)) = (VEC)) + +#define HMX_FP16_TO_FP32_PAIR_STEP(STORE_MODE, ADD_BIAS) \ + do { \ + _Pragma("unroll(4)") \ + for (size_t c = 0; c < limit_c_aligned; c += HTP_MM_HMX_TILE_N_COLS) { \ + const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS; \ + const __fp16 *tile = row_base + c0 * HTP_MM_HMX_TILE_N_ELMS; \ + HVX_Vector v = ((const HVX_Vector *) tile)[r1]; \ + HVX_VectorPair vp = Q6_Wqf32_vmpy_VhfVhf(v, one); \ + HVX_Vector v_out0 = ADD_BIAS(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(vp)), bias_row0, c); \ + HVX_Vector v_out1 = ADD_BIAS(Q6_Vsf_equals_Vqf32(Q6_V_hi_W(vp)), bias_row1, c); \ + HMX_STORE_VEC_##STORE_MODE(output_row_base + c, v_out0); \ + HMX_STORE_VEC_##STORE_MODE(output_row_base + c + dst_stride, v_out1); \ + } \ + if (limit_c_aligned < limit_c) { \ + size_t c = limit_c_aligned; \ + size_t valid_c = limit_c - c; \ + const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS; \ + const __fp16 *tile = row_base + c0 * HTP_MM_HMX_TILE_N_ELMS; \ + HVX_Vector v = ((const HVX_Vector *) tile)[r1]; \ + HVX_VectorPair vp = Q6_Wqf32_vmpy_VhfVhf(v, one); \ + HVX_Vector v_out0 = ADD_BIAS(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(vp)), bias_row0, c); \ + HVX_Vector v_out1 = ADD_BIAS(Q6_Vsf_equals_Vqf32(Q6_V_hi_W(vp)), bias_row1, c); \ + hvx_vec_store_u(output_row_base + c, valid_c * sizeof(float), v_out0); \ + hvx_vec_store_u(output_row_base + c + dst_stride, valid_c * sizeof(float), v_out1); \ + } \ + } while (0) + +#define HMX_FP16_TO_FP32_SINGLE_STEP(STORE_MODE, ADD_BIAS) \ + do { \ + _Pragma("unroll(4)") \ + for (size_t c = 0; c < limit_c_aligned; c += HTP_MM_HMX_TILE_N_COLS) { \ + const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS; \ + const __fp16 *tile = row_base + c0 * HTP_MM_HMX_TILE_N_ELMS; \ + HVX_Vector v = ((const HVX_Vector *) tile)[r1]; \ + HVX_VectorPair vp = Q6_Wqf32_vmpy_VhfVhf(v, one); \ + HVX_Vector v_out0 = ADD_BIAS(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(vp)), bias_row0, c); \ + HMX_STORE_VEC_##STORE_MODE(output_row_base + c, v_out0); \ + } \ + if (limit_c_aligned < limit_c) { \ + size_t c = limit_c_aligned; \ + size_t valid_c = limit_c - c; \ + const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS; \ + const __fp16 *tile = row_base + c0 * HTP_MM_HMX_TILE_N_ELMS; \ + HVX_Vector v = ((const HVX_Vector *) tile)[r1]; \ + HVX_VectorPair vp = Q6_Wqf32_vmpy_VhfVhf(v, one); \ + HVX_Vector v_out0 = ADD_BIAS(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(vp)), bias_row0, c); \ + hvx_vec_store_u(output_row_base + c, valid_c * sizeof(float), v_out0); \ + } \ + } while (0) + +#define DEFINE_FP16_TO_FP32_COL_CHUNK_MODE(SFX, ADD_BIAS, STORE_MODE) \ +static __attribute__((noinline)) void transfer_output_chunk_fp16_to_fp32_col_chunk_##SFX##_##STORE_MODE( \ + void * restrict dst_ptr, \ + const void * restrict bias, \ + const __fp16 * restrict vtcm_src, \ + uint32_t start_row, \ + uint32_t n_rows, \ + uint32_t c_len, \ + uint32_t total_n_cols, \ + uint32_t dst_stride, \ + uint32_t bias_stride, \ + uint32_t dst_cols, \ + size_t bias_elem_size \ +) { \ + float * restrict dst = (float *) dst_ptr; \ + const size_t tile_row_stride = hmx_ceil_div(total_n_cols, \ + HTP_MM_HMX_TILE_N_COLS) * HTP_MM_HMX_TILE_N_ELMS; \ + const HVX_Vector one = hvx_vec_splat_f16(1.0); \ + const size_t limit_c = hex_smin(c_len, dst_cols); \ + const size_t limit_c_aligned = (limit_c & ~31u); \ + const size_t bias_row_bytes = (size_t) bias_stride * bias_elem_size; \ + const size_t dst_pair_stride = 2 * (size_t) dst_stride; \ + const size_t __attribute__((unused)) bias_pair_bytes = 2 * bias_row_bytes; \ + float * output_row_base = dst; \ + const uint8_t * __attribute__((unused)) bias_row0 = HMX_FP16_BIAS_ROW0_##SFX(bias, 0); \ + const uint8_t * __attribute__((unused)) bias_row1 = HMX_FP16_BIAS_ROW1_##SFX(bias_row0, \ + bias_row_bytes); \ + size_t r_idx0 = start_row; \ + const __fp16 * row_base = vtcm_src + (r_idx0 >> 5) * tile_row_stride; \ + size_t r1 = (r_idx0 & 31u) >> 1; \ + size_t r = 0; \ + for (; r + 1 < n_rows; r += 2) { \ + HMX_FP16_TO_FP32_PAIR_STEP(STORE_MODE, ADD_BIAS); \ + output_row_base += dst_pair_stride; \ + HMX_FP16_BIAS_STEP_##SFX(bias_row0, bias_pair_bytes); \ + HMX_FP16_BIAS_STEP_##SFX(bias_row1, bias_pair_bytes); \ + if (++r1 == 16) { \ + r1 = 0; \ + row_base += tile_row_stride; \ + } \ + } \ + if (r < n_rows) { \ + HMX_FP16_TO_FP32_SINGLE_STEP(STORE_MODE, ADD_BIAS); \ + } \ +} + +#define DEFINE_FP16_TO_FP32_COL_CHUNK(SFX, ADD_BIAS) \ + DEFINE_FP16_TO_FP32_COL_CHUNK_MODE(SFX, ADD_BIAS, nt) \ + DEFINE_FP16_TO_FP32_COL_CHUNK_MODE(SFX, ADD_BIAS, u) + +DEFINE_FP16_TO_FP32_COL_CHUNK(none, HMX_FP16_ADD_BIAS_F32_NONE) +DEFINE_FP16_TO_FP32_COL_CHUNK(f16, HMX_FP16_ADD_BIAS_F32_F16) +DEFINE_FP16_TO_FP32_COL_CHUNK(f32, HMX_FP16_ADD_BIAS_F32_F32) + +#define HMX_FP16_TO_FP16_PAIR_STEP(STORE_MODE, ADD_BIAS_64, ADD_BIAS_TAIL) \ + do { \ + for (size_t c = 0; c < limit_c_aligned64; c += 64) { \ + const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS; \ + const __fp16 *tile0 = row_base + (c0 + 0) * HTP_MM_HMX_TILE_N_ELMS; \ + const __fp16 *tile1 = row_base + (c0 + 1) * HTP_MM_HMX_TILE_N_ELMS; \ + HVX_Vector v_t0 = ((const HVX_Vector *) tile0)[r1]; \ + HVX_Vector v_t1 = ((const HVX_Vector *) tile1)[r1]; \ + HVX_VectorPair vp = Q6_W_vdeal_VVR(v_t1, v_t0, -2); \ + HVX_Vector v_out0 = ADD_BIAS_64(Q6_V_lo_W(vp), bias_row0, c); \ + HVX_Vector v_out1 = ADD_BIAS_64(Q6_V_hi_W(vp), bias_row1, c); \ + HMX_STORE_VEC_##STORE_MODE(output_row_base + c, v_out0); \ + HMX_STORE_VEC_##STORE_MODE(output_row_base + dst_stride + c, v_out1); \ + } \ + if (limit_c_aligned64 < limit_c) { \ + const size_t c = limit_c_aligned64; \ + const size_t valid_c = limit_c - c; \ + const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS; \ + const __fp16 *tile0 = row_base + (c0 + 0) * HTP_MM_HMX_TILE_N_ELMS; \ + HVX_Vector v_t0 = ((const HVX_Vector *) tile0)[r1]; \ + HVX_Vector v_t1 = (valid_c > 32) \ + ? ((const HVX_Vector *) (row_base + (c0 + 1) * HTP_MM_HMX_TILE_N_ELMS))[r1] \ + : Q6_V_vzero(); \ + HVX_VectorPair vp = Q6_W_vdeal_VVR(v_t1, v_t0, -2); \ + HVX_Vector v_out0 = ADD_BIAS_TAIL(Q6_V_lo_W(vp), bias_row0, c, valid_c); \ + HVX_Vector v_out1 = ADD_BIAS_TAIL(Q6_V_hi_W(vp), bias_row1, c, valid_c); \ + hvx_vec_store_u(output_row_base + c, valid_c * sizeof(__fp16), v_out0); \ + hvx_vec_store_u(output_row_base + dst_stride + c, valid_c * sizeof(__fp16), v_out1); \ + } \ + } while (0) + +#define HMX_FP16_TO_FP16_SINGLE_STEP(STORE_MODE, ADD_BIAS_64, ADD_BIAS_TAIL) \ + do { \ + for (size_t c = 0; c < limit_c_aligned64; c += 64) { \ + const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS; \ + const __fp16 *tile0 = row_base + (c0 + 0) * HTP_MM_HMX_TILE_N_ELMS; \ + const __fp16 *tile1 = row_base + (c0 + 1) * HTP_MM_HMX_TILE_N_ELMS; \ + HVX_Vector v_t0 = ((const HVX_Vector *) tile0)[r1]; \ + HVX_Vector v_t1 = ((const HVX_Vector *) tile1)[r1]; \ + HVX_VectorPair vp = Q6_W_vdeal_VVR(v_t1, v_t0, -2); \ + HVX_Vector v_out0 = ADD_BIAS_64(Q6_V_lo_W(vp), bias_row0, c); \ + HMX_STORE_VEC_##STORE_MODE(output_row_base + c, v_out0); \ + } \ + if (limit_c_aligned64 < limit_c) { \ + const size_t c = limit_c_aligned64; \ + const size_t valid_c = limit_c - c; \ + const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS; \ + const __fp16 *tile0 = row_base + (c0 + 0) * HTP_MM_HMX_TILE_N_ELMS; \ + HVX_Vector v_t0 = ((const HVX_Vector *) tile0)[r1]; \ + HVX_Vector v_t1 = (valid_c > 32) \ + ? ((const HVX_Vector *) (row_base + (c0 + 1) * HTP_MM_HMX_TILE_N_ELMS))[r1] \ + : Q6_V_vzero(); \ + HVX_VectorPair vp = Q6_W_vdeal_VVR(v_t1, v_t0, -2); \ + HVX_Vector v_out0 = ADD_BIAS_TAIL(Q6_V_lo_W(vp), bias_row0, c, valid_c); \ + hvx_vec_store_u(output_row_base + c, valid_c * sizeof(__fp16), v_out0); \ + } \ + } while (0) + +#define DEFINE_FP16_TO_FP16_COL_CHUNK_MODE(SFX, ADD_BIAS_64, ADD_BIAS_TAIL, STORE_MODE) \ +static __attribute__((noinline)) void transfer_output_chunk_fp16_to_fp16_col_chunk_##SFX##_##STORE_MODE( \ + void * restrict dst_ptr, \ + const void * restrict bias, \ + const __fp16 * restrict vtcm_src, \ + uint32_t start_row, \ + uint32_t n_rows, \ + uint32_t c_len, \ + uint32_t total_n_cols, \ + uint32_t dst_stride, \ + uint32_t bias_stride, \ + uint32_t dst_cols, \ + size_t bias_elem_size \ +) { \ + __fp16 * restrict dst = (__fp16 *) dst_ptr; \ + const size_t tile_row_stride = hmx_ceil_div(total_n_cols, \ + HTP_MM_HMX_TILE_N_COLS) * HTP_MM_HMX_TILE_N_ELMS; \ + const size_t limit_c = hex_smin(c_len, dst_cols); \ + const size_t limit_c_aligned64 = (limit_c & ~63u); \ + const size_t bias_row_bytes = (size_t) bias_stride * bias_elem_size; \ + const size_t dst_pair_stride = 2 * (size_t) dst_stride; \ + const size_t __attribute__((unused)) bias_pair_bytes = 2 * bias_row_bytes; \ + __fp16 * output_row_base = dst; \ + const uint8_t * __attribute__((unused)) bias_row0 = HMX_FP16_BIAS_ROW0_##SFX(bias, 0); \ + const uint8_t * __attribute__((unused)) bias_row1 = HMX_FP16_BIAS_ROW1_##SFX(bias_row0, \ + bias_row_bytes); \ + size_t r_idx0 = start_row; \ + const __fp16 * row_base = vtcm_src + (r_idx0 >> 5) * tile_row_stride; \ + size_t r1 = (r_idx0 & 31u) >> 1; \ + size_t r = 0; \ + for (; r + 1 < n_rows; r += 2) { \ + HMX_FP16_TO_FP16_PAIR_STEP(STORE_MODE, ADD_BIAS_64, ADD_BIAS_TAIL); \ + output_row_base += dst_pair_stride; \ + HMX_FP16_BIAS_STEP_##SFX(bias_row0, bias_pair_bytes); \ + HMX_FP16_BIAS_STEP_##SFX(bias_row1, bias_pair_bytes); \ + if (++r1 == 16) { \ + r1 = 0; \ + row_base += tile_row_stride; \ + } \ + } \ + if (r < n_rows) { \ + HMX_FP16_TO_FP16_SINGLE_STEP(STORE_MODE, ADD_BIAS_64, ADD_BIAS_TAIL); \ + } \ +} + +#define DEFINE_FP16_TO_FP16_COL_CHUNK(SFX, ADD_BIAS_64, ADD_BIAS_TAIL) \ + DEFINE_FP16_TO_FP16_COL_CHUNK_MODE(SFX, ADD_BIAS_64, ADD_BIAS_TAIL, nt) \ + DEFINE_FP16_TO_FP16_COL_CHUNK_MODE(SFX, ADD_BIAS_64, ADD_BIAS_TAIL, u) + +DEFINE_FP16_TO_FP16_COL_CHUNK(none, HMX_FP16_ADD_BIAS_F16_64_NONE, HMX_FP16_ADD_BIAS_F16_TAIL_NONE) +DEFINE_FP16_TO_FP16_COL_CHUNK(f16, HMX_FP16_ADD_BIAS_F16_64_F16, HMX_FP16_ADD_BIAS_F16_TAIL_F16) +DEFINE_FP16_TO_FP16_COL_CHUNK(f32, HMX_FP16_ADD_BIAS_F16_64_F32, HMX_FP16_ADD_BIAS_F16_TAIL_F32) + +typedef void (*hmx_fp16_output_col_chunk_fn_t)( + void * restrict dst, + const void * restrict bias, + const __fp16 * restrict vtcm_src, + uint32_t start_row, + uint32_t n_rows, + uint32_t c_len, + uint32_t total_n_cols, + uint32_t dst_stride, + uint32_t bias_stride, + uint32_t dst_cols, + size_t bias_elem_size +); + +static inline hmx_fp16_output_col_chunk_fn_t resolve_fp16_output_col_chunk_fn( + size_t dst_elem_size, + const void * bias, + size_t bias_elem_size, + bool dst_aligned_nt +) { + const bool dst_f16 = (dst_elem_size == sizeof(__fp16)); + const bool bias_f16 = (bias_elem_size == sizeof(__fp16)); + if (dst_f16) { + if (dst_aligned_nt) { + return !bias ? transfer_output_chunk_fp16_to_fp16_col_chunk_none_nt + : (bias_f16 ? transfer_output_chunk_fp16_to_fp16_col_chunk_f16_nt + : transfer_output_chunk_fp16_to_fp16_col_chunk_f32_nt); + } + return !bias ? transfer_output_chunk_fp16_to_fp16_col_chunk_none_u + : (bias_f16 ? transfer_output_chunk_fp16_to_fp16_col_chunk_f16_u + : transfer_output_chunk_fp16_to_fp16_col_chunk_f32_u); + } + if (dst_aligned_nt) { + return !bias ? transfer_output_chunk_fp16_to_fp32_col_chunk_none_nt + : (bias_f16 ? transfer_output_chunk_fp16_to_fp32_col_chunk_f16_nt + : transfer_output_chunk_fp16_to_fp32_col_chunk_f32_nt); + } + return !bias ? transfer_output_chunk_fp16_to_fp32_col_chunk_none_u + : (bias_f16 ? transfer_output_chunk_fp16_to_fp32_col_chunk_f16_u + : transfer_output_chunk_fp16_to_fp32_col_chunk_f32_u); +} + +typedef struct { + hmx_fp16_output_col_chunk_fn_t col_chunk_fn; + const __fp16 *vtcm_src; + void *dst; + const void *bias; + size_t dst_elem_size; + size_t bias_elem_size; + uint32_t n_tasks; + uint32_t n_tot_chunks; + uint32_t n_chunks_per_task; + uint32_t n_cols; + uint32_t dst_stride; // DDR row stride + uint32_t bias_stride; // DDR row stride for residual + uint32_t dst_cols; // Actual output columns +} output_transfer_task_state_t; + +// activations : fp32 -> fp16 + +static void transfer_activation_row_pair_fp32_to_fp16( + __fp16 *restrict vtcm_dst, + const float *restrict row0, + const float *restrict row1, + uint32_t r, + uint32_t k_block, + uint32_t k_valid, + bool row0_valid, + bool row1_valid) { + + uint32_t r0 = r / HTP_MM_HMX_TILE_N_ROWS; // tile row index + uint32_t r1 = r % HTP_MM_HMX_TILE_N_ROWS; // intra-tile row idx + + uint32_t c = 0; + for (; c + 32 <= k_valid; c += 32) { + HVX_Vector v0 = Q6_V_vzero(); + HVX_Vector v1 = Q6_V_vzero(); + if (row0_valid) v0 = *(const HVX_Vector *)(row0 + c); + if (row1_valid) v1 = *(const HVX_Vector *)(row1 + c); + + HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1); + + uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS; // tile column index + uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0; + + HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS); + tile[r1 / 2] = v_out; + } + for (; c < k_block; c += 32) { + HVX_Vector v0 = Q6_V_vzero(); + HVX_Vector v1 = Q6_V_vzero(); + if (c < k_valid) { + if (row0_valid) v0 = *(const HVX_Vector *)(row0 + c); + if (row1_valid) v1 = *(const HVX_Vector *)(row1 + c); + + uint32_t rem = k_valid - c; + HVX_VectorPred mask = Q6_Q_vsetq2_R(rem * sizeof(float)); + v0 = Q6_V_vmux_QVV(mask, v0, Q6_V_vzero()); + v1 = Q6_V_vmux_QVV(mask, v1, Q6_V_vzero()); + } + + HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1); + + uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS; // tile column index + uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0; + + HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS); + tile[r1 / 2] = v_out; + } +} + +// F16-input variant of transfer_activation_row_pair_fp32_to_fp16, for F16 activation +// (src1). Same shape as the F16 Q-prep in hmx-fa-kernels.h: one 128-byte load carries 64 f16 +// = two tile columns, and Q6_W_vshuff_VVR interleaves the two rows straight into the HMX tile +// layout, so no F32 round-trip is needed. Rows are only 64-byte aligned when k_block is an odd +// multiple of the tile width, hence the unaligned load type. +static void transfer_activation_row_pair_f16_to_f16(__fp16 * restrict vtcm_dst, + const __fp16 * restrict row0, + const __fp16 * restrict row1, + uint32_t r, + uint32_t k_block, + uint32_t k_valid, + bool row0_valid, + bool row1_valid) { + uint32_t r0 = r / HTP_MM_HMX_TILE_N_ROWS; // tile row index + uint32_t r1 = r % HTP_MM_HMX_TILE_N_ROWS; // intra-tile row idx + + const uint32_t n_tile_cols = k_block / HTP_MM_HMX_TILE_N_COLS; + __fp16 * restrict tile_row = vtcm_dst + (size_t) r0 * n_tile_cols * HTP_MM_HMX_TILE_N_ELMS; + + const HVX_UVector * pv0 = row0_valid ? (const HVX_UVector *) row0 : NULL; + const HVX_UVector * pv1 = row1_valid ? (const HVX_UVector *) row1 : NULL; + + uint32_t c = 0; + for (; c + 64 <= k_valid; c += 64) { + HVX_Vector v0 = pv0 ? pv0[c / 64] : Q6_V_vzero(); + HVX_Vector v1 = pv1 ? pv1[c / 64] : Q6_V_vzero(); + HVX_VectorPair vp = Q6_W_vshuff_VVR(v1, v0, -2); + + uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS; + + HVX_Vector * tile0 = (HVX_Vector *) (tile_row + (size_t) c0 * HTP_MM_HMX_TILE_N_ELMS); + HVX_Vector * tile1 = (HVX_Vector *) (tile_row + (size_t) (c0 + 1) * HTP_MM_HMX_TILE_N_ELMS); + + tile0[r1 / 2] = Q6_V_lo_W(vp); + tile1[r1 / 2] = Q6_V_hi_W(vp); + } + // Tail: fewer than 64 valid columns left, plus the k_valid..k_block padding that HMX will + // still multiply, so it has to be written as zeros. + for (; c < k_block; c += 64) { + HVX_Vector v0 = Q6_V_vzero(); + HVX_Vector v1 = Q6_V_vzero(); + + if (c < k_valid) { + uint32_t rem = k_valid - c; // 1..63 valid f16 lanes + HVX_VectorPred mask = Q6_Q_vsetq2_R(rem * sizeof(__fp16)); + if (pv0) { + v0 = Q6_V_vmux_QVV(mask, pv0[c / 64], Q6_V_vzero()); + } + if (pv1) { + v1 = Q6_V_vmux_QVV(mask, pv1[c / 64], Q6_V_vzero()); + } + } + + HVX_VectorPair vp = Q6_W_vshuff_VVR(v1, v0, -2); + + uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS; + + HVX_Vector * tile0 = (HVX_Vector *) (tile_row + (size_t) c0 * HTP_MM_HMX_TILE_N_ELMS); + tile0[r1 / 2] = Q6_V_lo_W(vp); + + if (c0 + 1 < n_tile_cols) { + HVX_Vector * tile1 = (HVX_Vector *) (tile_row + (size_t) (c0 + 1) * HTP_MM_HMX_TILE_N_ELMS); + tile1[r1 / 2] = Q6_V_hi_W(vp); + } + } +} + +static void transfer_activation_row_pair_fp32_to_fp16_col_chunk( + __fp16 *restrict vtcm_dst, + const float *restrict row0, // offset by c_first + const float *restrict row1, // offset by c_first + uint32_t r, + uint32_t k_block, + uint32_t c_first, + uint32_t c_len, + uint32_t k_chunk_valid, + bool row0_valid, + bool row1_valid) { + + uint32_t r0 = r / HTP_MM_HMX_TILE_N_ROWS; // tile row index + uint32_t r1 = r % HTP_MM_HMX_TILE_N_ROWS; // intra-tile row idx + + uint32_t c = 0; + for (; c + 32 <= k_chunk_valid; c += 32) { + HVX_Vector v0 = Q6_V_vzero(); + HVX_Vector v1 = Q6_V_vzero(); + if (row0_valid) v0 = *(const HVX_Vector *)(row0 + c); + if (row1_valid) v1 = *(const HVX_Vector *)(row1 + c); + + HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1); + + uint32_t c0 = (c_first + c) / HTP_MM_HMX_TILE_N_COLS; // tile column index + uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0; + + HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS); + tile[r1 / 2] = v_out; + } + if (c < c_len) { + HVX_Vector v0 = Q6_V_vzero(); + HVX_Vector v1 = Q6_V_vzero(); + if (row0_valid) v0 = *(const HVX_Vector *)(row0 + c); + if (row1_valid) v1 = *(const HVX_Vector *)(row1 + c); + + uint32_t rem = (k_chunk_valid > c) ? (k_chunk_valid - c) : 0; + HVX_VectorPred mask = Q6_Q_vsetq2_R(rem > 0 ? rem * sizeof(float) : 0); + v0 = Q6_V_vmux_QVV(mask, v0, Q6_V_vzero()); + v1 = Q6_V_vmux_QVV(mask, v1, Q6_V_vzero()); + + HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1); + + uint32_t c0 = (c_first + c) / HTP_MM_HMX_TILE_N_COLS; // tile column index + uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0; + + HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS); + tile[r1 / 2] = v_out; + } +} + +static void transfer_activation_row_pair_f16_to_f16_col_chunk( + __fp16 *restrict vtcm_dst, + const __fp16 *restrict row0, + const __fp16 *restrict row1, + uint32_t r, + uint32_t k_block, + uint32_t c_first, + uint32_t c_len, + uint32_t k_chunk_valid, + bool row0_valid, + bool row1_valid) { + + const uint32_t r0 = r / HTP_MM_HMX_TILE_N_ROWS; + const uint32_t r1 = r % HTP_MM_HMX_TILE_N_ROWS; + const uint32_t n_tile_cols = k_block / HTP_MM_HMX_TILE_N_COLS; + __fp16 * restrict tile_row = vtcm_dst + (size_t) r0 * n_tile_cols * HTP_MM_HMX_TILE_N_ELMS; + + const HVX_UVector * pv0 = row0_valid ? (const HVX_UVector *) row0 : NULL; + const HVX_UVector * pv1 = row1_valid ? (const HVX_UVector *) row1 : NULL; + + uint32_t c = 0; + for (; c + 64 <= k_chunk_valid; c += 64) { + HVX_Vector v0 = pv0 ? pv0[c / 64] : Q6_V_vzero(); + HVX_Vector v1 = pv1 ? pv1[c / 64] : Q6_V_vzero(); + HVX_VectorPair vp = Q6_W_vshuff_VVR(v1, v0, -2); + + const uint32_t c0 = (c_first + c) / HTP_MM_HMX_TILE_N_COLS; + HVX_Vector * tile0 = (HVX_Vector *) (tile_row + (size_t) c0 * HTP_MM_HMX_TILE_N_ELMS); + HVX_Vector * tile1 = (HVX_Vector *) (tile_row + (size_t) (c0 + 1) * HTP_MM_HMX_TILE_N_ELMS); + + tile0[r1 / 2] = Q6_V_lo_W(vp); + tile1[r1 / 2] = Q6_V_hi_W(vp); + } + for (; c < c_len; c += 64) { + HVX_Vector v0 = Q6_V_vzero(); + HVX_Vector v1 = Q6_V_vzero(); + + if (c < k_chunk_valid) { + const uint32_t rem = k_chunk_valid - c; + HVX_VectorPred mask = Q6_Q_vsetq2_R(rem * sizeof(__fp16)); + if (pv0) { + v0 = Q6_V_vmux_QVV(mask, pv0[c / 64], Q6_V_vzero()); + } + if (pv1) { + v1 = Q6_V_vmux_QVV(mask, pv1[c / 64], Q6_V_vzero()); + } + } + + HVX_VectorPair vp = Q6_W_vshuff_VVR(v1, v0, -2); + const uint32_t c0 = (c_first + c) / HTP_MM_HMX_TILE_N_COLS; + + HVX_Vector * tile0 = (HVX_Vector *) (tile_row + (size_t) c0 * HTP_MM_HMX_TILE_N_ELMS); + tile0[r1 / 2] = Q6_V_lo_W(vp); + + if (c + 32 < c_len && c0 + 1 < n_tile_cols) { + HVX_Vector * tile1 = (HVX_Vector *) (tile_row + (size_t) (c0 + 1) * HTP_MM_HMX_TILE_N_ELMS); + tile1[r1 / 2] = Q6_V_hi_W(vp); + } + } +} + +static inline HVX_Vector hvx_vec_load_u(const void * restrict src, uint32_t n) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) ((uintptr_t) src & ~(uintptr_t) 127); + const uint32_t left_off = (uint32_t) ((uintptr_t) src & 127); + const uint32_t right_off = left_off + n; + HVX_Vector v = (right_off > 128) ? Q6_V_valign_VVR(vsrc[1], vsrc[0], left_off) : Q6_V_vror_VR(vsrc[0], left_off); + return Q6_V_vand_QV(Q6_Q_vsetq2_R(n), v); +} + +// --- Shared HMX GLU Store Helpers & FP16-HMX GLU Epilogue --- + +static inline HVX_Vector hmx_glu_geglu_arg_f16(HVX_Vector x) { + // 0.5 * x * (1 + tanh(inner)) = x * sigmoid(2 * inner) + const HVX_Vector v_c0 = hvx_vec_splat_f16(2.0f * 0.7978845608028654f * 0.044715f); + const HVX_Vector v_c1 = hvx_vec_splat_f16(2.0f * 0.7978845608028654f); + const HVX_Vector x2 = hvx_vec_mul_f16_f16(x, x); + const HVX_Vector poly = hvx_vec_add_f16_f16(hvx_vec_mul_f16_f16(x2, v_c0), v_c1); + return hvx_vec_mul_f16_f16(x, poly); +} + +static inline HVX_Vector hmx_glu_geglu_arg_f32(HVX_Vector x) { + const HVX_Vector v_c0 = hvx_vec_splat_f32(2.0f * 0.7978845608028654f * 0.044715f); + const HVX_Vector v_c1 = hvx_vec_splat_f32(2.0f * 0.7978845608028654f); + const HVX_Vector x2 = hvx_vec_mul_f32_f32(x, x); + const HVX_Vector poly = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x2, v_c0), v_c1); + return hvx_vec_mul_f32_f32(x, poly); +} + +#define HMX_GLU_ARG_SWIGLU_F16(x) (x) +#define HMX_GLU_ARG_SWIGLU_F32(x) (x) +#define HMX_GLU_ARG_GEGLU_F16(x) hmx_glu_geglu_arg_f16(x) +#define HMX_GLU_ARG_GEGLU_F32(x) hmx_glu_geglu_arg_f32(x) +#define HMX_GLU_ARG_GEGLU_QUICK_F16(x) hvx_vec_mul_f16_f16((x), hvx_vec_splat_f16(1.702f)) +#define HMX_GLU_ARG_GEGLU_QUICK_F32(x) hvx_vec_mul_f32_f32((x), hvx_vec_splat_f32(1.702f)) + +// Sigmoid-based GLU stores: out = g * sigmoid(ARG(g)) * u (vtcm_res_out is always 128B aligned). +#define DEFINE_HMX_SIG_GLU_STORE(NAME, ARG_F16, ARG_F32) \ +static __attribute__((noinline)) void hmx_glu_##NAME##_store_tail_fp16( \ + void * restrict dst_ptr, \ + size_t dst_stride, \ + const HVX_Vector * restrict g_hf, \ + const HVX_Vector * restrict u_hf, \ + uint32_t rows_and_bytes) { \ + __fp16 * restrict dst = (__fp16 *) dst_ptr; \ + const uint32_t valid_rows = rows_and_bytes >> 16; \ + const size_t valid_bytes = rows_and_bytes & 0xffffu; \ + _Pragma("clang loop pipeline(disable) unroll(disable)") \ + for (uint32_t k = 0; k < valid_rows; ++k) { \ + const HVX_Vector g = g_hf[k]; \ + const HVX_Vector sig = hvx_vec_fast_sigmoid_f16(ARG_F16(g)); \ + const HVX_Vector out = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(g, sig), u_hf[k]); \ + hvx_vec_store_u(dst + k * dst_stride, valid_bytes, out); \ + } \ +} \ +static __attribute__((noinline)) void hmx_glu_##NAME##_store_quad_fp16( \ + void * restrict dst_ptr, \ + size_t dst_stride, \ + const HVX_Vector * restrict g_hf, \ + const HVX_Vector * restrict u_hf, \ + uint32_t valid_rows) { \ + __fp16 * restrict dst = (__fp16 *) dst_ptr; \ + if (valid_rows == 4u) { \ + const HVX_Vector g0 = g_hf[0]; \ + const HVX_Vector g1 = g_hf[1]; \ + const HVX_VectorPair s01 = hvx_vec_fast_sigmoid_f16_pair(ARG_F16(g0), ARG_F16(g1)); \ + hvx_vmem(dst + 0 * dst_stride) = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(g0, Q6_V_lo_W(s01)), u_hf[0]); \ + hvx_vmem(dst + 1 * dst_stride) = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(g1, Q6_V_hi_W(s01)), u_hf[1]); \ + const HVX_Vector g2 = g_hf[2]; \ + const HVX_Vector g3 = g_hf[3]; \ + const HVX_VectorPair s23 = hvx_vec_fast_sigmoid_f16_pair(ARG_F16(g2), ARG_F16(g3)); \ + hvx_vmem(dst + 2 * dst_stride) = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(g2, Q6_V_lo_W(s23)), u_hf[2]); \ + hvx_vmem(dst + 3 * dst_stride) = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(g3, Q6_V_hi_W(s23)), u_hf[3]); \ + return; \ + } \ + hmx_glu_##NAME##_store_tail_fp16(dst, dst_stride, g_hf, u_hf, (valid_rows << 16) | 128u); \ +} \ +static __attribute__((noinline)) void hmx_glu_##NAME##_store_tail_fp32( \ + void * restrict dst_ptr, \ + size_t dst_stride, \ + const HVX_Vector * restrict g_q, \ + const HVX_Vector * restrict u_q, \ + uint32_t rows_and_bytes) { \ + float * restrict dst = (float *) dst_ptr; \ + const uint32_t valid_rows = rows_and_bytes >> 16; \ + const size_t valid_bytes = rows_and_bytes & 0xffffu; \ + const HVX_Vector v_one = hvx_vec_splat_f32(1.0f); \ + const HVX_Vector v_max_exp = hvx_vec_splat_f32(87.0f); \ + const HVX_Vector v_min_exp = hvx_vec_splat_f32(-87.0f); \ + _Pragma("clang loop unroll(disable)") \ + for (uint32_t k = 0; k < valid_rows; ++k) { \ + const HVX_Vector g = g_q[k]; \ + const HVX_Vector sig = hvx_vec_fast_sigmoid_f32_guard(ARG_F32(g), v_one, v_max_exp, v_min_exp); \ + const HVX_Vector out = hvx_vec_mul_f32_f32(hvx_vec_mul_f32_f32(g, sig), u_q[k]); \ + hvx_vec_store_u(dst + k * dst_stride, valid_bytes, out); \ + } \ +} \ +static __attribute__((noinline)) void hmx_glu_##NAME##_store_quad_fp32( \ + void * restrict dst_ptr, \ + size_t dst_stride, \ + const HVX_Vector * restrict g_q, \ + const HVX_Vector * restrict u_q, \ + uint32_t valid_rows) { \ + float * restrict dst = (float *) dst_ptr; \ + const HVX_Vector v_one = hvx_vec_splat_f32(1.0f); \ + const HVX_Vector v_max_exp = hvx_vec_splat_f32(87.0f); \ + const HVX_Vector v_min_exp = hvx_vec_splat_f32(-87.0f); \ + if (valid_rows == 4u) { \ + const HVX_Vector g0 = g_q[0]; \ + const HVX_Vector g1 = g_q[1]; \ + const HVX_VectorPair s01 = hvx_vec_fast_sigmoid_f32_guard_pair(ARG_F32(g0), ARG_F32(g1), \ + v_one, v_max_exp, v_min_exp); \ + hvx_vmem(dst + 0 * dst_stride) = hvx_vec_mul_f32_f32(hvx_vec_mul_f32_f32(g0, Q6_V_lo_W(s01)), u_q[0]); \ + hvx_vmem(dst + 1 * dst_stride) = hvx_vec_mul_f32_f32(hvx_vec_mul_f32_f32(g1, Q6_V_hi_W(s01)), u_q[1]); \ + const HVX_Vector g2 = g_q[2]; \ + const HVX_Vector g3 = g_q[3]; \ + const HVX_VectorPair s23 = hvx_vec_fast_sigmoid_f32_guard_pair(ARG_F32(g2), ARG_F32(g3), \ + v_one, v_max_exp, v_min_exp); \ + hvx_vmem(dst + 2 * dst_stride) = hvx_vec_mul_f32_f32(hvx_vec_mul_f32_f32(g2, Q6_V_lo_W(s23)), u_q[2]); \ + hvx_vmem(dst + 3 * dst_stride) = hvx_vec_mul_f32_f32(hvx_vec_mul_f32_f32(g3, Q6_V_hi_W(s23)), u_q[3]); \ + return; \ + } \ + hmx_glu_##NAME##_store_tail_fp32(dst, dst_stride, g_q, u_q, (valid_rows << 16) | 128u); \ +} + +DEFINE_HMX_SIG_GLU_STORE(swiglu, HMX_GLU_ARG_SWIGLU_F16, HMX_GLU_ARG_SWIGLU_F32) +DEFINE_HMX_SIG_GLU_STORE(geglu, HMX_GLU_ARG_GEGLU_F16, HMX_GLU_ARG_GEGLU_F32) +DEFINE_HMX_SIG_GLU_STORE(geglu_quick, HMX_GLU_ARG_GEGLU_QUICK_F16, HMX_GLU_ARG_GEGLU_QUICK_F32) + +#define DEFINE_HMX_SIG_GLU_STRIP_FP16(NAME, ARG_F16) \ +static __attribute__((noinline)) void hmx_glu_##NAME##_store_strip_fp16( \ + void * restrict dst_ptr, \ + size_t dst_stride, \ + const __fp16 * restrict u_buf, \ + size_t u_stride, \ + size_t n_pairs) { \ + __fp16 * restrict dst = (__fp16 *) dst_ptr; \ + _Pragma("clang loop unroll(disable)") \ + for (size_t p = 0; p < n_pairs; ++p) { \ + __fp16 * d0 = dst + (p << 6); \ + const __fp16 * u0 = u_buf + (p << 6); \ + const HVX_Vector g0 = hvx_vmem(d0 + 0 * dst_stride); \ + const HVX_Vector g1 = hvx_vmem(d0 + 1 * dst_stride); \ + const HVX_VectorPair s01 = hvx_vec_fast_sigmoid_f16_pair(ARG_F16(g0), ARG_F16(g1)); \ + hvx_vmem(d0 + 0 * dst_stride) = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(g0, Q6_V_lo_W(s01)), \ + hvx_vmem(u0 + 0 * u_stride)); \ + hvx_vmem(d0 + 1 * dst_stride) = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(g1, Q6_V_hi_W(s01)), \ + hvx_vmem(u0 + 1 * u_stride)); \ + const HVX_Vector g2 = hvx_vmem(d0 + 2 * dst_stride); \ + const HVX_Vector g3 = hvx_vmem(d0 + 3 * dst_stride); \ + const HVX_VectorPair s23 = hvx_vec_fast_sigmoid_f16_pair(ARG_F16(g2), ARG_F16(g3)); \ + hvx_vmem(d0 + 2 * dst_stride) = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(g2, Q6_V_lo_W(s23)), \ + hvx_vmem(u0 + 2 * u_stride)); \ + hvx_vmem(d0 + 3 * dst_stride) = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(g3, Q6_V_hi_W(s23)), \ + hvx_vmem(u0 + 3 * u_stride)); \ + } \ +} + +DEFINE_HMX_SIG_GLU_STRIP_FP16(swiglu, HMX_GLU_ARG_SWIGLU_F16) +DEFINE_HMX_SIG_GLU_STRIP_FP16(geglu, HMX_GLU_ARG_GEGLU_F16) +DEFINE_HMX_SIG_GLU_STRIP_FP16(geglu_quick, HMX_GLU_ARG_GEGLU_QUICK_F16) + +static __attribute__((noinline)) void hmx_glu_reglu_store_tail_fp16( + void * restrict dst_ptr, + size_t dst_stride, + const HVX_Vector * restrict g_hf, + const HVX_Vector * restrict u_hf, + uint32_t rows_and_bytes) { + __fp16 * restrict dst = (__fp16 *) dst_ptr; + const uint32_t valid_rows = rows_and_bytes >> 16; + const size_t valid_bytes = rows_and_bytes & 0xffffu; + const HVX_Vector v_zero = Q6_V_vzero(); + for (uint32_t k = 0; k < valid_rows; ++k) { + const HVX_Vector out = hvx_vec_mul_f16_f16(Q6_Vhf_vmax_VhfVhf(g_hf[k], v_zero), u_hf[k]); + hvx_vec_store_u(dst + k * dst_stride, valid_bytes, out); + } +} + +static __attribute__((noinline)) void hmx_glu_reglu_store_quad_fp16( + void * restrict dst_ptr, + size_t dst_stride, + const HVX_Vector * restrict g_hf, + const HVX_Vector * restrict u_hf, + uint32_t valid_rows) { + __fp16 * restrict dst = (__fp16 *) dst_ptr; + const HVX_Vector v_zero = Q6_V_vzero(); + for (uint32_t k = 0; k < valid_rows; ++k) { + hvx_vmem(dst + k * dst_stride) = hvx_vec_mul_f16_f16(Q6_Vhf_vmax_VhfVhf(g_hf[k], v_zero), u_hf[k]); + } +} + +static __attribute__((noinline)) void hmx_glu_reglu_store_strip_fp16( + void * restrict dst_ptr, + size_t dst_stride, + const __fp16 * restrict u_buf, + size_t u_stride, + size_t n_pairs) { + __fp16 * restrict dst = (__fp16 *) dst_ptr; + const HVX_Vector v_zero = Q6_V_vzero(); + _Pragma("clang loop unroll(disable)") + for (size_t p = 0; p < n_pairs; ++p) { + __fp16 * d0 = dst + (p << 6); + const __fp16 * u0 = u_buf + (p << 6); + hvx_vmem(d0 + 0 * dst_stride) = hvx_vec_mul_f16_f16(Q6_Vhf_vmax_VhfVhf(hvx_vmem(d0 + 0 * dst_stride), v_zero), hvx_vmem(u0 + 0 * u_stride)); + hvx_vmem(d0 + 1 * dst_stride) = hvx_vec_mul_f16_f16(Q6_Vhf_vmax_VhfVhf(hvx_vmem(d0 + 1 * dst_stride), v_zero), hvx_vmem(u0 + 1 * u_stride)); + hvx_vmem(d0 + 2 * dst_stride) = hvx_vec_mul_f16_f16(Q6_Vhf_vmax_VhfVhf(hvx_vmem(d0 + 2 * dst_stride), v_zero), hvx_vmem(u0 + 2 * u_stride)); + hvx_vmem(d0 + 3 * dst_stride) = hvx_vec_mul_f16_f16(Q6_Vhf_vmax_VhfVhf(hvx_vmem(d0 + 3 * dst_stride), v_zero), hvx_vmem(u0 + 3 * u_stride)); + } +} + +static __attribute__((noinline)) void hmx_glu_reglu_store_tail_fp32( + void * restrict dst_ptr, + size_t dst_stride, + const HVX_Vector * restrict g_q, + const HVX_Vector * restrict u_q, + uint32_t rows_and_bytes) { + float * restrict dst = (float *) dst_ptr; + const uint32_t valid_rows = rows_and_bytes >> 16; + const size_t valid_bytes = rows_and_bytes & 0xffffu; + const HVX_Vector v_zero = Q6_V_vzero(); + for (uint32_t k = 0; k < valid_rows; ++k) { + const HVX_Vector out = hvx_vec_mul_f32_f32(Q6_Vsf_vmax_VsfVsf(g_q[k], v_zero), u_q[k]); + hvx_vec_store_u(dst + k * dst_stride, valid_bytes, out); + } +} + +static __attribute__((noinline)) void hmx_glu_reglu_store_quad_fp32( + void * restrict dst_ptr, + size_t dst_stride, + const HVX_Vector * restrict g_q, + const HVX_Vector * restrict u_q, + uint32_t valid_rows) { + float * restrict dst = (float *) dst_ptr; + const HVX_Vector v_zero = Q6_V_vzero(); + for (uint32_t k = 0; k < valid_rows; ++k) { + hvx_vmem(dst + k * dst_stride) = hvx_vec_mul_f32_f32(Q6_Vsf_vmax_VsfVsf(g_q[k], v_zero), u_q[k]); + } +} + +typedef void (*hmx_glu_store_quad_fn_t)( + void * restrict dst_ptr, + size_t dst_stride, + const HVX_Vector * restrict g_vec, + const HVX_Vector * restrict u_vec, + uint32_t valid_rows); + +typedef void (*hmx_glu_store_tail_fn_t)( + void * restrict dst_ptr, + size_t dst_stride, + const HVX_Vector * restrict g_vec, + const HVX_Vector * restrict u_vec, + uint32_t rows_and_bytes); + +typedef void (*hmx_glu_store_strip_fn_t)( + void * restrict dst_ptr, + size_t dst_stride, + const __fp16 * restrict u_buf, + size_t u_stride, + size_t n_pairs); + +typedef void (*hmx_output_glu_col_chunk_fn_t)( + const void * st_void, + void * restrict dst_ptr, + uint32_t start_row, + uint32_t n_rows, + uint32_t c_first, + uint32_t c_len_and_dst_cols); + +typedef struct { + void * dst; + const uint8_t * vtcm_gate; + const uint8_t * vtcm_up; + const float * vtcm_act_scales; + const float * vtcm_wt_scales_gate; + const float * vtcm_wt_scales_up; + uint32_t n_rows; + uint32_t mc_pad; + uint32_t n_cols; + uint32_t n_groups; + uint32_t dst_stride; + uint32_t dst_cols; + size_t dst_elem_size; + uint32_t n_tasks; + uint32_t n_chunks_per_task; + struct fastdiv_values n_hvx_div; + hmx_output_glu_col_chunk_fn_t col_chunk_fn; + hmx_glu_store_quad_fn_t store_quad_fn; + hmx_glu_store_tail_fn_t store_tail_fn; + hmx_glu_store_strip_fn_t store_strip_fn; +} hmx_output_glu_state_t; + +static inline bool resolve_hmx_glu_store_fns( + uint8_t glu_op, + size_t dst_elem_size, + hmx_glu_store_quad_fn_t * store_quad_fn, + hmx_glu_store_tail_fn_t * store_tail_fn, + hmx_glu_store_strip_fn_t * store_strip_fn) { + if (dst_elem_size == sizeof(__fp16)) { + switch (glu_op) { + case HTP_OP_GLU_SWIGLU: + *store_quad_fn = hmx_glu_swiglu_store_quad_fp16; + *store_tail_fn = hmx_glu_swiglu_store_tail_fp16; + *store_strip_fn = hmx_glu_swiglu_store_strip_fp16; + return true; + case HTP_OP_GLU_GEGLU: + *store_quad_fn = hmx_glu_geglu_store_quad_fp16; + *store_tail_fn = hmx_glu_geglu_store_tail_fp16; + *store_strip_fn = hmx_glu_geglu_store_strip_fp16; + return true; + case HTP_OP_GLU_GEGLU_QUICK: + *store_quad_fn = hmx_glu_geglu_quick_store_quad_fp16; + *store_tail_fn = hmx_glu_geglu_quick_store_tail_fp16; + *store_strip_fn = hmx_glu_geglu_quick_store_strip_fp16; + return true; + case HTP_OP_GLU_REGLU: + *store_quad_fn = hmx_glu_reglu_store_quad_fp16; + *store_tail_fn = hmx_glu_reglu_store_tail_fp16; + *store_strip_fn = hmx_glu_reglu_store_strip_fp16; + return true; + default: + return false; + } + } + *store_strip_fn = NULL; + switch (glu_op) { + case HTP_OP_GLU_SWIGLU: + *store_quad_fn = hmx_glu_swiglu_store_quad_fp32; + *store_tail_fn = hmx_glu_swiglu_store_tail_fp32; + return true; + case HTP_OP_GLU_GEGLU: + *store_quad_fn = hmx_glu_geglu_store_quad_fp32; + *store_tail_fn = hmx_glu_geglu_store_tail_fp32; + return true; + case HTP_OP_GLU_GEGLU_QUICK: + *store_quad_fn = hmx_glu_geglu_quick_store_quad_fp32; + *store_tail_fn = hmx_glu_geglu_quick_store_tail_fp32; + return true; + case HTP_OP_GLU_REGLU: + *store_quad_fn = hmx_glu_reglu_store_quad_fp32; + *store_tail_fn = hmx_glu_reglu_store_tail_fp32; + return true; + default: + return false; + } +} + +static __attribute__((noinline)) void transfer_output_chunk_fp16_glu_fp16( + const void * st_void, + void * restrict dst_ptr, + uint32_t start_row, + uint32_t n_rows, + uint32_t c_first, + uint32_t c_len_and_dst_cols) { + const hmx_output_glu_state_t * st = (const hmx_output_glu_state_t *) st_void; + __fp16 * restrict dst = (__fp16 *) dst_ptr; + const __fp16 * vtcm_gate = (const __fp16 *) st->vtcm_gate; + const __fp16 * vtcm_up = (const __fp16 *) st->vtcm_up; + const size_t tile_row_stride = hmx_ceil_div(st->n_cols, HTP_MM_HMX_TILE_N_COLS) * HTP_MM_HMX_TILE_N_ELMS; + const size_t c0_first = c_first >> 5; + const size_t limit_c = hex_smin(c_len_and_dst_cols >> 16, c_len_and_dst_cols & 0xffffu); + const size_t limit_c_aligned = limit_c & ~63u; + const size_t dst_stride = st->dst_stride; + + HVX_Vector g_hf[4] __attribute__((aligned(128))); + HVX_Vector u_hf[4] __attribute__((aligned(128))); + + for (size_t r_base = 0; r_base < n_rows; ) { + const size_t r_idx_base = start_row + r_base; + const size_t r_step = hex_smin((size_t) n_rows - r_base, (size_t) (32u - (r_idx_base & 31u))); + const size_t r_end = r_base + r_step; + const size_t tile_off = (r_idx_base >> 5) * tile_row_stride + c0_first * HTP_MM_HMX_TILE_N_ELMS; + const __fp16 * g_row = vtcm_gate + tile_off; + const __fp16 * u_row = vtcm_up + tile_off; + + for (size_t r = r_base; r < r_end; r += 4) { + const size_t r_idx0 = start_row + r; + const size_t r1 = (r_idx0 & 31u) >> 1; + const uint32_t valid_rows = (uint32_t) hex_smin((size_t) 4u, r_end - r); + __fp16 * out_row0 = dst + r * dst_stride; + + #pragma clang loop unroll(disable) + for (size_t c = 0; c < limit_c_aligned; c += 64) { + const size_t c0 = c >> 5; + const size_t off0 = c0 * HTP_MM_HMX_TILE_N_ELMS; + const size_t off1 = off0 + HTP_MM_HMX_TILE_N_ELMS; + const HVX_VectorPair gp0 = Q6_W_vdeal_VVR(((const HVX_Vector *) (g_row + off1))[r1], + ((const HVX_Vector *) (g_row + off0))[r1], -2); + const HVX_VectorPair up0 = Q6_W_vdeal_VVR(((const HVX_Vector *) (u_row + off1))[r1], + ((const HVX_Vector *) (u_row + off0))[r1], -2); + g_hf[0] = Q6_V_lo_W(gp0); + g_hf[1] = Q6_V_hi_W(gp0); + u_hf[0] = Q6_V_lo_W(up0); + u_hf[1] = Q6_V_hi_W(up0); + if (valid_rows > 2u) { + const HVX_VectorPair gp1 = Q6_W_vdeal_VVR(((const HVX_Vector *) (g_row + off1))[r1 + 1], + ((const HVX_Vector *) (g_row + off0))[r1 + 1], -2); + const HVX_VectorPair up1 = Q6_W_vdeal_VVR(((const HVX_Vector *) (u_row + off1))[r1 + 1], + ((const HVX_Vector *) (u_row + off0))[r1 + 1], -2); + g_hf[2] = Q6_V_lo_W(gp1); + g_hf[3] = Q6_V_hi_W(gp1); + u_hf[2] = Q6_V_lo_W(up1); + u_hf[3] = Q6_V_hi_W(up1); + } + st->store_quad_fn(out_row0 + c, dst_stride, g_hf, u_hf, valid_rows); + } + if (limit_c_aligned < limit_c) { + const size_t c = limit_c_aligned; + const size_t c0 = c >> 5; + const size_t off0 = c0 * HTP_MM_HMX_TILE_N_ELMS; + const size_t off1 = off0 + HTP_MM_HMX_TILE_N_ELMS; + const size_t valid_c = limit_c - c; + const uint32_t valid_bytes = (uint32_t) (valid_c * sizeof(__fp16)); + const HVX_Vector g_t1_0 = (valid_c > 32) ? ((const HVX_Vector *) (g_row + off1))[r1] : Q6_V_vzero(); + const HVX_Vector u_t1_0 = (valid_c > 32) ? ((const HVX_Vector *) (u_row + off1))[r1] : Q6_V_vzero(); + const HVX_VectorPair gp0 = Q6_W_vdeal_VVR(g_t1_0, ((const HVX_Vector *) (g_row + off0))[r1], -2); + const HVX_VectorPair up0 = Q6_W_vdeal_VVR(u_t1_0, ((const HVX_Vector *) (u_row + off0))[r1], -2); + g_hf[0] = Q6_V_lo_W(gp0); + g_hf[1] = Q6_V_hi_W(gp0); + u_hf[0] = Q6_V_lo_W(up0); + u_hf[1] = Q6_V_hi_W(up0); + if (valid_rows > 2u) { + const HVX_Vector g_t1_1 = (valid_c > 32) ? ((const HVX_Vector *) (g_row + off1))[r1 + 1] : Q6_V_vzero(); + const HVX_Vector u_t1_1 = (valid_c > 32) ? ((const HVX_Vector *) (u_row + off1))[r1 + 1] : Q6_V_vzero(); + const HVX_VectorPair gp1 = Q6_W_vdeal_VVR(g_t1_1, ((const HVX_Vector *) (g_row + off0))[r1 + 1], -2); + const HVX_VectorPair up1 = Q6_W_vdeal_VVR(u_t1_1, ((const HVX_Vector *) (u_row + off0))[r1 + 1], -2); + g_hf[2] = Q6_V_lo_W(gp1); + g_hf[3] = Q6_V_hi_W(gp1); + u_hf[2] = Q6_V_lo_W(up1); + u_hf[3] = Q6_V_hi_W(up1); + } + st->store_tail_fn(out_row0 + c, dst_stride, g_hf, u_hf, (valid_rows << 16) | valid_bytes); + } + } + r_base = r_end; + } +} + +static __attribute__((noinline)) void transfer_output_chunk_fp16_glu_fp32( + const void * st_void, + void * restrict dst_ptr, + uint32_t start_row, + uint32_t n_rows, + uint32_t c_first, + uint32_t c_len_and_dst_cols) { + const hmx_output_glu_state_t * st = (const hmx_output_glu_state_t *) st_void; + float * restrict dst = (float *) dst_ptr; + const __fp16 * vtcm_gate = (const __fp16 *) st->vtcm_gate; + const __fp16 * vtcm_up = (const __fp16 *) st->vtcm_up; + const size_t tile_row_stride = hmx_ceil_div(st->n_cols, HTP_MM_HMX_TILE_N_COLS) * HTP_MM_HMX_TILE_N_ELMS; + const size_t c0_first = c_first >> 5; + const size_t limit_c = hex_smin(c_len_and_dst_cols >> 16, c_len_and_dst_cols & 0xffffu); + const size_t limit_c_aligned = limit_c & ~31u; + const size_t dst_stride = st->dst_stride; + const HVX_Vector one = hvx_vec_splat_f16(1.0f); + + HVX_Vector g_q[4] __attribute__((aligned(128))); + HVX_Vector u_q[4] __attribute__((aligned(128))); + + for (size_t r_base = 0; r_base < n_rows; ) { + const size_t r_idx_base = start_row + r_base; + const size_t r_step = hex_smin((size_t) n_rows - r_base, (size_t) (32u - (r_idx_base & 31u))); + const size_t r_end = r_base + r_step; + const size_t tile_off = (r_idx_base >> 5) * tile_row_stride + c0_first * HTP_MM_HMX_TILE_N_ELMS; + const __fp16 * g_row = vtcm_gate + tile_off; + const __fp16 * u_row = vtcm_up + tile_off; + + for (size_t r = r_base; r < r_end; r += 4) { + const size_t r_idx0 = start_row + r; + const size_t r1 = (r_idx0 & 31u) >> 1; + const uint32_t valid_rows = (uint32_t) hex_smin((size_t) 4u, r_end - r); + float * out_row0 = dst + r * dst_stride; + + #pragma clang loop unroll(disable) + for (size_t c = 0; c < limit_c_aligned; c += 32) { + const size_t off0 = (c >> 5) * HTP_MM_HMX_TILE_N_ELMS; + const HVX_VectorPair gp0 = Q6_Wqf32_vmpy_VhfVhf(((const HVX_Vector *) (g_row + off0))[r1], one); + const HVX_VectorPair up0 = Q6_Wqf32_vmpy_VhfVhf(((const HVX_Vector *) (u_row + off0))[r1], one); + g_q[0] = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(gp0)); + g_q[1] = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(gp0)); + u_q[0] = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(up0)); + u_q[1] = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(up0)); + if (valid_rows > 2u) { + const HVX_VectorPair gp1 = Q6_Wqf32_vmpy_VhfVhf(((const HVX_Vector *) (g_row + off0))[r1 + 1], one); + const HVX_VectorPair up1 = Q6_Wqf32_vmpy_VhfVhf(((const HVX_Vector *) (u_row + off0))[r1 + 1], one); + g_q[2] = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(gp1)); + g_q[3] = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(gp1)); + u_q[2] = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(up1)); + u_q[3] = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(up1)); + } + st->store_quad_fn(out_row0 + c, dst_stride, g_q, u_q, valid_rows); + } + if (limit_c_aligned < limit_c) { + const size_t c = limit_c_aligned; + const size_t off0 = (c >> 5) * HTP_MM_HMX_TILE_N_ELMS; + const uint32_t valid_bytes = (uint32_t) ((limit_c - c) * sizeof(float)); + const HVX_VectorPair gp0 = Q6_Wqf32_vmpy_VhfVhf(((const HVX_Vector *) (g_row + off0))[r1], one); + const HVX_VectorPair up0 = Q6_Wqf32_vmpy_VhfVhf(((const HVX_Vector *) (u_row + off0))[r1], one); + g_q[0] = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(gp0)); + g_q[1] = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(gp0)); + u_q[0] = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(up0)); + u_q[1] = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(up0)); + if (valid_rows > 2u) { + const HVX_VectorPair gp1 = Q6_Wqf32_vmpy_VhfVhf(((const HVX_Vector *) (g_row + off0))[r1 + 1], one); + const HVX_VectorPair up1 = Q6_Wqf32_vmpy_VhfVhf(((const HVX_Vector *) (u_row + off0))[r1 + 1], one); + g_q[2] = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(gp1)); + g_q[3] = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(gp1)); + u_q[2] = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(up1)); + u_q[3] = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(up1)); + } + st->store_tail_fn(out_row0 + c, dst_stride, g_q, u_q, (valid_rows << 16) | valid_bytes); + } + } + r_base = r_end; + } +} + +static inline bool resolve_fp16_output_glu_fns( + uint8_t glu_op, + size_t dst_elem_size, + hmx_output_glu_col_chunk_fn_t * col_chunk_fn, + hmx_glu_store_quad_fn_t * store_quad_fn, + hmx_glu_store_tail_fn_t * store_tail_fn, + hmx_glu_store_strip_fn_t * store_strip_fn) { + if (!resolve_hmx_glu_store_fns(glu_op, dst_elem_size, store_quad_fn, store_tail_fn, store_strip_fn)) { + return false; + } + *col_chunk_fn = (dst_elem_size == sizeof(__fp16)) ? transfer_output_chunk_fp16_glu_fp16 + : transfer_output_chunk_fp16_glu_fp32; + return true; +} + diff --git a/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled-int.h b/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled-int.h new file mode 100644 index 000000000000..5e06f11fbfb9 --- /dev/null +++ b/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled-int.h @@ -0,0 +1,3464 @@ +// --- INT HMX W8A8 SM kernels --- + +#include "hmx-int-utils.h" + +typedef void (*int_rescale_superblock_fn_t)( + const uint8_t * restrict src_base, + uint8_t * restrict dst_wt, + float * restrict dst_scales, + HVX_Vector * restrict bias_out, + uint32_t tiles_per_group, + size_t dst_tile_stride); + +typedef struct { + int_rescale_superblock_fn_t rescale_2k_fn; + int_rescale_superblock_fn_t rescale_tail_fn; + uint8_t * dst_wt_base; + uint8_t * dst_bias_base; + float * dst_scales_base; + const uint8_t * src_raw; + uint32_t n_col_tiles; + uint32_t n_k_tiles; + uint32_t n_groups; + uint32_t tail_tiles; + uint32_t aligned_tile_size; + uint32_t raw_shift; + uint32_t n_tot_units; + uint32_t n_units_per_task; + uint32_t n_tasks; + struct fastdiv_values n_groups_div; +} int_weight_rescale_state_t; + +static const uint8_t __attribute__((aligned(VLEN))) kvalues_mxfp4_x8_lut[128] = { + 0, 0, 8, 0, 16, 0, 24, 0, 32, 0, 48, 0, 64, 0, 96, 0, + 0, 0, 0xf8, 0, 0xf0, 0, 0xe8, 0, 0xe0, 0, 0xd0, 0, 0xc0, 0, 0xa0, 0, +}; + +static inline void int_hmx_rescale_4bit_lut_step( + HVX_Vector vq, + HVX_Vector v_lut, + HVX_Vector v_m_b4, + HVX_Vector * restrict tile_dst, + int pair_idx, + HVX_Vector * restrict v_sum_w, + HVX_Vector * restrict v_l1_w) { + + const HVX_Vector mask_0f = Q6_Vb_vsplat_R(0x0F); + HVX_Vector v_lo = Q6_V_vand_VV(vq, mask_0f); + HVX_Vector v_hi = Q6_Vub_vlsr_VubR(vq, 4); + HVX_Vector v_q0 = Q6_Vb_vlut32_VbVbI(v_lo, v_lut, 0); + HVX_Vector v_q1 = Q6_Vb_vlut32_VbVbI(v_hi, v_lut, 0); + int_hmx_rescale_pair_wb(v_q0, v_q1, v_m_b4, tile_dst, pair_idx, v_sum_w, v_l1_w); +} + +#define DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(NAME) \ +static __attribute__((noinline)) void rescale_##NAME##_weight_superblock_2k( \ + const uint8_t * restrict src_base, \ + uint8_t * restrict dst_wt, \ + float * restrict dst_scales, \ + HVX_Vector * restrict bias_out, \ + uint32_t tiles_per_group, \ + size_t dst_tile_stride) { \ + (void) tiles_per_group; \ + rescale_##NAME##_weight_superblock_impl( \ + src_base, dst_wt, dst_scales, bias_out, HTP_MM_HMX_W8A8_KGROUP_TILES, dst_tile_stride); \ +} \ +static __attribute__((noinline)) void rescale_##NAME##_weight_superblock_tail( \ + const uint8_t * restrict src_base, \ + uint8_t * restrict dst_wt, \ + float * restrict dst_scales, \ + HVX_Vector * restrict bias_out, \ + uint32_t tiles_per_group, \ + size_t dst_tile_stride) { \ + rescale_##NAME##_weight_superblock_impl( \ + src_base, dst_wt, dst_scales, bias_out, tiles_per_group, dst_tile_stride); \ +} + +static inline HVX_Vector int_hmx_scan_max_f16_scales( + const uint8_t * restrict src_base, + size_t tile_stride, + size_t scale_offset, + uint32_t tiles_per_group) { + + assert(tiles_per_group >= 2 && (tiles_per_group & 1) == 0); + + const HVX_Vector v_abs_mask = Q6_Vh_vsplat_R(0x7fff); + HVX_Vector v_max0 = Q6_V_vzero(); + HVX_Vector v_max1 = Q6_V_vzero(); + const uint8_t * sc_ptr = src_base + scale_offset; + for (uint32_t kt = 0; kt < tiles_per_group; kt += 2) { + HVX_Vector v_sc0 = Q6_V_vand_VV(hvx_vmem(sc_ptr), v_abs_mask); + HVX_Vector v_sc1 = Q6_V_vand_VV(hvx_vmem(sc_ptr + tile_stride), v_abs_mask); + v_max0 = Q6_Vhf_vmax_VhfVhf(v_max0, v_sc0); + v_max1 = Q6_Vhf_vmax_VhfVhf(v_max1, v_sc1); + sc_ptr += 2 * tile_stride; + } + return Q6_Vhf_vmax_VhfVhf(v_max0, v_max1); +} + +static inline void rescale_q4_0_tile_step( + const uint8_t * restrict tile_src, + HVX_Vector * restrict tile_dst, + HVX_Vector v_m_b4, + HVX_Vector mask_f0, + HVX_Vector sign_88, + HVX_Vector * restrict v_sum_w, + HVX_Vector * restrict v_l1_w) { + + #pragma unroll + for (int i = 0; i < 4; ++i) { + HVX_Vector vq_s = Q6_V_vxor_VV(hvx_vmem(tile_src + i * 128), sign_88); + HVX_Vector v_lo = Q6_V_vand_VV(Q6_Vh_vasl_VhR(vq_s, 4), mask_f0); + HVX_Vector v_hi = Q6_V_vand_VV(vq_s, mask_f0); + int_hmx_rescale_pair_wb(v_lo, v_hi, v_m_b4, tile_dst, i, v_sum_w, v_l1_w); + } +} + +// Rescale one (ct, g) superblock of Q4_0 tiles into int8 weight.b tiles, +// compute sum_w and exact l1_w per output channel, and write the Bias Register bank(s) and D_w_eff. +static __attribute__((always_inline)) inline void rescale_q4_0_weight_superblock_impl( + const uint8_t * restrict src_base, + uint8_t * restrict dst_wt, + float * restrict dst_scales, + HVX_Vector * restrict bias_out, + uint32_t tiles_per_group, + size_t dst_tile_stride) { + + assert(tiles_per_group >= 2 && (tiles_per_group & 1) == 0); + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q4_0); + const size_t dst_stride_vecs = dst_tile_stride / sizeof(HVX_Vector); + const HVX_Vector mask_f0 = Q6_Vb_vsplat_R(0xF0); + const HVX_Vector sign_88 = Q6_Vb_vsplat_R(0x88); + + HVX_Vector v_max_sc = int_hmx_scan_max_f16_scales(src_base, tile_stride, 512, tiles_per_group); + + HVX_Vector v_max_sf, v_inv127_qf; + int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf); + + HVX_Vector v_sum_w = Q6_V_vzero(); + HVX_Vector v_l1_w = Q6_V_vzero(); + + const uint8_t * tile_src = src_base; + HVX_Vector * tile_dst = (HVX_Vector *) dst_wt; + HVX_Vector v_m_b4 = int_hmx_m_b4_from_f16(hvx_vmem(tile_src + 512), v_inv127_qf); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t kt = 0; kt + 1 < tiles_per_group; ++kt) { + HVX_Vector v_m_next = int_hmx_m_b4_from_f16(hvx_vmem(tile_src + tile_stride + 512), v_inv127_qf); + rescale_q4_0_tile_step(tile_src, tile_dst, v_m_b4, mask_f0, sign_88, &v_sum_w, &v_l1_w); + v_m_b4 = v_m_next; + tile_src += tile_stride; + tile_dst += dst_stride_vecs; + } + rescale_q4_0_tile_step(tile_src, tile_dst, v_m_b4, mask_f0, sign_88, &v_sum_w, &v_l1_w); + + emit_int_hmx_scales_and_bias(v_max_sf, 8.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out); +} +DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q4_0) + +static inline void rescale_q8_0_tile_step( + const uint8_t * restrict tile_src, + HVX_Vector * restrict tile_dst, + HVX_Vector v_m_b4, + HVX_Vector * restrict v_sum_w, + HVX_Vector * restrict v_l1_w) { + + #pragma unroll + for (int i = 0; i < 4; ++i) { + HVX_Vector vq0 = hvx_vmem(tile_src + (2 * i + 0) * 128); + HVX_Vector vq1 = hvx_vmem(tile_src + (2 * i + 1) * 128); + int_hmx_rescale_pair_wb(vq0, vq1, v_m_b4, tile_dst, i, v_sum_w, v_l1_w); + } +} + +static __attribute__((always_inline)) inline void rescale_q8_0_weight_superblock_impl( + const uint8_t * restrict src_base, + uint8_t * restrict dst_wt, + float * restrict dst_scales, + HVX_Vector * restrict bias_out, + uint32_t tiles_per_group, + size_t dst_tile_stride) { + + assert(tiles_per_group >= 2 && (tiles_per_group & 1) == 0); + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q8_0); + const size_t dst_stride_vecs = dst_tile_stride / sizeof(HVX_Vector); + HVX_Vector v_max_sc = int_hmx_scan_max_f16_scales(src_base, tile_stride, 1024, tiles_per_group); + + HVX_Vector v_max_sf, v_inv127_qf; + int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf); + + HVX_Vector v_sum_w = Q6_V_vzero(); + HVX_Vector v_l1_w = Q6_V_vzero(); + + const uint8_t * tile_src = src_base; + HVX_Vector * tile_dst = (HVX_Vector *) dst_wt; + HVX_Vector v_m_b4 = int_hmx_m_b4_from_f16(hvx_vmem(tile_src + 1024), v_inv127_qf); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t kt = 0; kt + 1 < tiles_per_group; ++kt) { + HVX_Vector v_m_next = int_hmx_m_b4_from_f16(hvx_vmem(tile_src + tile_stride + 1024), v_inv127_qf); + rescale_q8_0_tile_step(tile_src, tile_dst, v_m_b4, &v_sum_w, &v_l1_w); + v_m_b4 = v_m_next; + tile_src += tile_stride; + tile_dst += dst_stride_vecs; + } + rescale_q8_0_tile_step(tile_src, tile_dst, v_m_b4, &v_sum_w, &v_l1_w); + + emit_int_hmx_scales_and_bias(v_max_sf, 128.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out); +} +DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q8_0) + +static inline void rescale_4bit_lut_tile_step( + const uint8_t * restrict tile_src, + HVX_Vector * restrict tile_dst, + HVX_Vector v_lut, + HVX_Vector v_m_b4, + HVX_Vector * restrict v_sum_w, + HVX_Vector * restrict v_l1_w) { + + #pragma unroll + for (int i = 0; i < 4; ++i) { + int_hmx_rescale_4bit_lut_step(hvx_vmem(tile_src + i * 128), v_lut, v_m_b4, tile_dst, i, v_sum_w, v_l1_w); + } +} + +static inline HVX_Vector int_hmx_mxfp4_e8m0_to_f32(HVX_Vector v_raw) { + HVX_Vector v_e_h = Q6_V_lo_W(Q6_Wuh_vunpack_Vub(v_raw)); + HVX_Vector v_e_w = Q6_V_lo_W(Q6_Wuw_vunpack_Vuh(v_e_h)); + HVX_VectorPred q_nan = Q6_Q_vcmp_eq_VwVw(v_e_w, Q6_V_vsplat_R(0xff)); + return Q6_V_vmux_QVV(q_nan, Q6_V_vzero(), Q6_Vw_vasl_VwR(v_e_w, 23)); +} + +static __attribute__((always_inline)) inline void rescale_mxfp4_weight_superblock_impl( + const uint8_t * restrict src_base, + uint8_t * restrict dst_wt, + float * restrict dst_scales, + HVX_Vector * restrict bias_out, + uint32_t tiles_per_group, + size_t dst_tile_stride) { + + assert(tiles_per_group >= 2 && (tiles_per_group & 1) == 0); + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_MXFP4); + const HVX_Vector v_lut = *(const HVX_Vector *) kvalues_mxfp4_x8_lut; + HVX_Vector v_max0 = Q6_V_vzero(); + HVX_Vector v_max1 = Q6_V_vzero(); + const uint8_t * sc_ptr = src_base + 512; + for (uint32_t kt = 0; kt < tiles_per_group; kt += 2) { + v_max0 = Q6_Vsf_vmax_VsfVsf(v_max0, int_hmx_mxfp4_e8m0_to_f32(hvx_vmem(sc_ptr))); + v_max1 = Q6_Vsf_vmax_VsfVsf(v_max1, int_hmx_mxfp4_e8m0_to_f32(hvx_vmem(sc_ptr + tile_stride))); + sc_ptr += 2 * tile_stride; + } + HVX_Vector v_max_sf = Q6_Vsf_vmax_VsfVsf(v_max0, v_max1); + + HVX_Vector v_inv127_qf = int_hmx_inv127_from_max_f32(v_max_sf); + HVX_Vector v_sum_w = Q6_V_vzero(); + HVX_Vector v_l1_w = Q6_V_vzero(); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t kt = 0; kt < tiles_per_group; ++kt) { + const uint8_t * tile_src = src_base + (size_t) kt * tile_stride; + HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) kt * dst_tile_stride); + HVX_Vector v_sc_qf = hvx_vec_f32_to_qf32(int_hmx_mxfp4_e8m0_to_f32(hvx_vmem(tile_src + 512))); + HVX_Vector v_m_b4 = int_hmx_m_b4_from_sc_qf(v_sc_qf, v_inv127_qf); + rescale_4bit_lut_tile_step(tile_src, tile_dst, v_lut, v_m_b4, &v_sum_w, &v_l1_w); + } + + emit_int_hmx_scales_and_bias(v_max_sf, 8.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out); +} +DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(mxfp4) + +static inline void rescale_q5_0_tile_step( + const uint8_t * restrict tile_src, + HVX_Vector * restrict tile_dst, + HVX_Vector v_m_b4, + HVX_Vector mask_78, + HVX_Vector * restrict v_sum_w, + HVX_Vector * restrict v_l1_w) { + + HVX_Vector v_plane = hvx_vmem(tile_src + 512); + #pragma unroll + for (int i = 0; i < 4; ++i) { + HVX_Vector vq = hvx_vmem(tile_src + i * 128); + HVX_Vector v_lo = Q6_V_vand_VV(Q6_Vh_vasl_VhR(vq, 3), mask_78); + HVX_Vector v_hi = Q6_V_vand_VV(Q6_Vuh_vlsr_VuhR(vq, 1), mask_78); + v_lo = Q6_V_vandor_VQR(v_lo, Q6_Q_vand_VR(v_plane, 0x01010101u << (2 * i)), 0x80808080); + v_hi = Q6_V_vandor_VQR(v_hi, Q6_Q_vand_VR(v_plane, 0x01010101u << (2 * i + 1)), 0x80808080); + int_hmx_rescale_pair_wb(v_lo, v_hi, v_m_b4, tile_dst, i, v_sum_w, v_l1_w); + } +} + +static __attribute__((always_inline)) inline void rescale_q5_0_weight_superblock_impl( + const uint8_t * restrict src_base, + uint8_t * restrict dst_wt, + float * restrict dst_scales, + HVX_Vector * restrict bias_out, + uint32_t tiles_per_group, + size_t dst_tile_stride) { + + assert(tiles_per_group >= 2 && (tiles_per_group & 1) == 0); + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q5_0); + const size_t dst_stride_vecs = dst_tile_stride / sizeof(HVX_Vector); + const HVX_Vector mask_78 = Q6_Vb_vsplat_R(0x78); + HVX_Vector v_max_sc = int_hmx_scan_max_f16_scales(src_base, tile_stride, 640, tiles_per_group); + + HVX_Vector v_max_sf, v_inv127_qf; + int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf); + + HVX_Vector v_sum_w = Q6_V_vzero(); + HVX_Vector v_l1_w = Q6_V_vzero(); + + const uint8_t * tile_src = src_base; + HVX_Vector * tile_dst = (HVX_Vector *) dst_wt; + HVX_Vector v_m_b4 = int_hmx_m_b4_from_f16(hvx_vmem(tile_src + 640), v_inv127_qf); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t kt = 0; kt + 1 < tiles_per_group; ++kt) { + HVX_Vector v_m_next = int_hmx_m_b4_from_f16(hvx_vmem(tile_src + tile_stride + 640), v_inv127_qf); + rescale_q5_0_tile_step(tile_src, tile_dst, v_m_b4, mask_78, &v_sum_w, &v_l1_w); + v_m_b4 = v_m_next; + tile_src += tile_stride; + tile_dst += dst_stride_vecs; + } + rescale_q5_0_tile_step(tile_src, tile_dst, v_m_b4, mask_78, &v_sum_w, &v_l1_w); + + emit_int_hmx_scales_and_bias(v_max_sf, 16.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out); +} +DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q5_0) + +static __attribute__((always_inline)) inline void rescale_iq4_nl_weight_superblock_impl( + const uint8_t * restrict src_base, + uint8_t * restrict dst_wt, + float * restrict dst_scales, + HVX_Vector * restrict bias_out, + uint32_t tiles_per_group, + size_t dst_tile_stride) { + + assert(tiles_per_group >= 2 && (tiles_per_group & 1) == 0); + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_IQ4_NL); + const size_t dst_stride_vecs = dst_tile_stride / sizeof(HVX_Vector); + const HVX_Vector v_lut = *(const HVX_Vector *) kvalues_iq4nl_lut; + HVX_Vector v_max_sc = int_hmx_scan_max_f16_scales(src_base, tile_stride, 512, tiles_per_group); + + HVX_Vector v_max_sf, v_inv127_qf; + int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf); + + HVX_Vector v_sum_w = Q6_V_vzero(); + HVX_Vector v_l1_w = Q6_V_vzero(); + + const uint8_t * tile_src = src_base; + HVX_Vector * tile_dst = (HVX_Vector *) dst_wt; + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t kt = 0; kt < tiles_per_group; ++kt) { + HVX_Vector v_m_b4 = int_hmx_m_b4_from_f16(hvx_vmem(tile_src + 512), v_inv127_qf); + rescale_4bit_lut_tile_step(tile_src, tile_dst, v_lut, v_m_b4, &v_sum_w, &v_l1_w); + tile_src += tile_stride; + tile_dst += dst_stride_vecs; + } + + emit_int_hmx_scales_and_bias(v_max_sf, 128.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out); +} +DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(iq4_nl) + +static inline void rescale_q1_0_weight_superblock_impl( + const uint8_t * restrict src_base, + uint8_t * restrict dst_wt, + float * restrict dst_scales, + HVX_Vector * restrict bias_out, + uint32_t tiles_per_group, + size_t dst_tile_stride) { + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q1_0); + const uint32_t raw_tiles = tiles_per_group >> 2; + const HVX_Vector v_abs_mask = Q6_Vh_vsplat_R(0x7fff); + HVX_Vector v_max_sc = Q6_V_vzero(); + for (uint32_t rt = 0; rt < raw_tiles; ++rt) { + const uint8_t * tile_src = src_base + (size_t) rt * tile_stride; + v_max_sc = Q6_Vhf_vmax_VhfVhf(v_max_sc, Q6_V_vand_VV(hvx_vmem(tile_src + 512), v_abs_mask)); + } + + HVX_Vector v_max_sf, v_inv127_qf; + int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf); + + HVX_Vector v_sum_w = Q6_V_vzero(); + HVX_Vector v_l1_w = Q6_V_vzero(); + + for (uint32_t rt = 0; rt < raw_tiles; ++rt) { + const uint8_t * tile_src = src_base + (size_t) rt * tile_stride; + HVX_Vector v_pos_m = int_hmx_m_b4_from_f16(hvx_vmem(tile_src + 512), v_inv127_qf); + HVX_Vector v_neg_m = Q6_Vb_vsub_VbVb(Q6_V_vzero(), v_pos_m); + + for (uint32_t q = 0; q < 4; ++q) { + HVX_Vector v_plane = hvx_vmem(tile_src + q * 128); + HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) (4 * rt + q) * dst_tile_stride); + for (int i = 0; i < 4; ++i) { + HVX_Vector v_W0 = unpack_q1_0_group(v_plane, 2 * i + 0, v_neg_m, v_pos_m); + HVX_Vector v_W1 = unpack_q1_0_group(v_plane, 2 * i + 1, v_neg_m, v_pos_m); + int_hmx_store_and_accum_pair(tile_dst, i, v_W0, v_W1, &v_sum_w, &v_l1_w); + } + } + } + + emit_int_hmx_scales_and_bias(v_max_sf, 1.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out); +} +DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q1_0) + +static inline void rescale_q2_0_weight_superblock_impl( + const uint8_t * restrict src_base, + uint8_t * restrict dst_wt, + float * restrict dst_scales, + HVX_Vector * restrict bias_out, + uint32_t tiles_per_group, + size_t dst_tile_stride) { + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q2_0); + const uint32_t raw_tiles = tiles_per_group >> 1; + const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03); + const HVX_Vector i32 = Q6_Vb_vsplat_R(32); + const HVX_Vector v_abs_mask = Q6_Vh_vsplat_R(0x7fff); + HVX_Vector v_max_sc = Q6_V_vzero(); + for (uint32_t rt = 0; rt < raw_tiles; ++rt) { + const uint8_t * tile_src = src_base + (size_t) rt * tile_stride; + v_max_sc = Q6_Vhf_vmax_VhfVhf(v_max_sc, Q6_V_vand_VV(hvx_vmem(tile_src + 512), v_abs_mask)); + } + + HVX_Vector v_max_sf, v_inv127_qf; + int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf); + + HVX_Vector v_sum_w = Q6_V_vzero(); + HVX_Vector v_l1_w = Q6_V_vzero(); + + for (uint32_t rt = 0; rt < raw_tiles; ++rt) { + const HVX_Vector * vptr = (const HVX_Vector *) (src_base + (size_t) rt * tile_stride); + HVX_Vector v_m_b4 = int_hmx_m_b4_from_f16(vptr[4], v_inv127_qf); + + for (uint32_t half = 0; half < 2; ++half) { + HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) (2 * rt + half) * dst_tile_stride); + for (int i = 0; i < 4; ++i) { + HVX_Vector v_q0 = Q6_Vb_vsub_VbVb(Q6_Vh_vasl_VhR(unpack_q3_k_low2(vptr + 2 * half, 2 * i + 0, mask_03), 5), i32); + HVX_Vector v_q1 = Q6_Vb_vsub_VbVb(Q6_Vh_vasl_VhR(unpack_q3_k_low2(vptr + 2 * half, 2 * i + 1, mask_03), 5), i32); + int_hmx_rescale_pair_wb(v_q0, v_q1, v_m_b4, tile_dst, i, &v_sum_w, &v_l1_w); + } + } + } + + emit_int_hmx_scales_and_bias(v_max_sf, 4.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out); +} +DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q2_0) + +static inline void rescale_nvfp4_weight_superblock_impl( + const uint8_t * restrict src_base, + uint8_t * restrict dst_wt, + float * restrict dst_scales, + HVX_Vector * restrict bias_out, + uint32_t tiles_per_group, + size_t dst_tile_stride) { + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_NVFP4); + const HVX_Vector v_lut = *(const HVX_Vector *) kvalues_mxfp4_x8_lut; + HVX_Vector v_max_sc = Q6_V_vzero(); + for (uint32_t kt = 0; kt < tiles_per_group; ++kt) { + const uint8_t * tile_src = src_base + (size_t) kt * tile_stride; + HVX_Vector v_sc = nvfp4_ue4m3_to_f16(Q6_V_lo_W(Q6_Wuh_vunpack_Vub(hvx_vmem(tile_src + NVFP4_SCALE_OFF)))); + v_max_sc = Q6_Vhf_vmax_VhfVhf(v_max_sc, v_sc); + } + v_max_sc = Q6_Vhf_vmax_VhfVhf(v_max_sc, Q6_V_vror_VR(v_max_sc, 64)); + + HVX_Vector v_max_sf, v_inv127_qf; + int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf); + + HVX_Vector v_sum_w = Q6_V_vzero(); + HVX_Vector v_l1_w = Q6_V_vzero(); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t kt = 0; kt < tiles_per_group; ++kt) { + const uint8_t * tile_src = src_base + (size_t) kt * tile_stride; + HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) kt * dst_tile_stride); + HVX_Vector v_sc = nvfp4_ue4m3_to_f16(Q6_V_lo_W(Q6_Wuh_vunpack_Vub(hvx_vmem(tile_src + NVFP4_SCALE_OFF)))); + HVX_Vector v_m_b0, v_m_b1; + int_hmx_m_b4_pair_from_f16(v_sc, v_inv127_qf, &v_m_b0, &v_m_b1); + + #pragma clang loop pipeline(disable) unroll(disable) + for (int i = 0; i < 4; ++i) { + HVX_Vector v_m_b4 = (i < 2) ? v_m_b0 : v_m_b1; + int_hmx_rescale_4bit_lut_step(hvx_vmem(tile_src + i * 128), v_lut, v_m_b4, tile_dst, i, &v_sum_w, &v_l1_w); + } + } + + emit_int_hmx_scales_and_bias(v_max_sf, 8.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out); +} +DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(nvfp4) + +static inline HVX_Vector unpack_q3_k_group_shl5(const HVX_Vector * restrict vptr, int g, HVX_Vector mask_03) { + HVX_VectorPred q_neg = Q6_Q_vand_VR(vptr[2], 0x01010101u << g); + HVX_Vector v_lo2 = Q6_Vh_vasl_VhR(unpack_q3_k_low2(vptr, g, mask_03), 5); + return Q6_V_vandor_VQR(v_lo2, q_neg, 0x80808080); +} + +static inline void rescale_q3_k_weight_superblock_impl( + const uint8_t * restrict src_base, + uint8_t * restrict dst_wt, + float * restrict dst_scales, + HVX_Vector * restrict bias_out, + uint32_t tiles_per_group, + size_t dst_tile_stride) { + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q3_K); + const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03); + const HVX_Vector v_abs_mask = Q6_Vh_vsplat_R(0x7fff); + HVX_Vector v_max_sc = Q6_V_vzero(); + for (uint32_t kt = 0; kt < tiles_per_group; ++kt) { + const uint8_t * tile_src = src_base + (size_t) kt * tile_stride; + v_max_sc = Q6_Vhf_vmax_VhfVhf(v_max_sc, Q6_V_vand_VV(hvx_vmem(tile_src + 384), v_abs_mask)); + } + v_max_sc = Q6_Vhf_vmax_VhfVhf(v_max_sc, Q6_V_vror_VR(v_max_sc, 64)); + + HVX_Vector v_max_sf, v_inv127_qf; + int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf); + + HVX_Vector v_sum_w = Q6_V_vzero(); + HVX_Vector v_l1_w = Q6_V_vzero(); + + for (uint32_t kt = 0; kt < tiles_per_group; ++kt) { + const HVX_Vector * vptr = (const HVX_Vector *) (src_base + (size_t) kt * tile_stride); + HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) kt * dst_tile_stride); + HVX_Vector v_m_b0, v_m_b1; + int_hmx_m_b4_pair_from_f16(vptr[3], v_inv127_qf, &v_m_b0, &v_m_b1); + + for (int i = 0; i < 4; ++i) { + HVX_Vector v_m_b4 = (i < 2) ? v_m_b0 : v_m_b1; + HVX_Vector v_q0 = unpack_q3_k_group_shl5(vptr, 2 * i + 0, mask_03); + HVX_Vector v_q1 = unpack_q3_k_group_shl5(vptr, 2 * i + 1, mask_03); + int_hmx_rescale_pair_wb(v_q0, v_q1, v_m_b4, tile_dst, i, &v_sum_w, &v_l1_w); + } + } + + emit_int_hmx_scales_and_bias(v_max_sf, 4.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out); +} +DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q3_k) + +static inline void rescale_q6_k_weight_superblock_impl( + const uint8_t * restrict src_base, + uint8_t * restrict dst_wt, + float * restrict dst_scales, + HVX_Vector * restrict bias_out, + uint32_t tiles_per_group, + size_t dst_tile_stride) { + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q6_K); + const HVX_Vector mask_0f = Q6_Vb_vsplat_R(0x0F); + const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03); + const HVX_Vector sign_80 = Q6_Vb_vsplat_R(0x80); + const HVX_Vector v_abs_mask = Q6_Vh_vsplat_R(0x7fff); + HVX_Vector v_max_sc = Q6_V_vzero(); + for (uint32_t kt = 0; kt < tiles_per_group; ++kt) { + const uint8_t * tile_src = src_base + (size_t) kt * tile_stride; + v_max_sc = Q6_Vhf_vmax_VhfVhf(v_max_sc, Q6_V_vand_VV(hvx_vmem(tile_src + 768), v_abs_mask)); + } + v_max_sc = Q6_Vhf_vmax_VhfVhf(v_max_sc, Q6_V_vror_VR(v_max_sc, 64)); + + HVX_Vector v_max_sf, v_inv127_qf; + int_hmx_inv127_from_max_f16(v_max_sc, &v_max_sf, &v_inv127_qf); + + HVX_Vector v_sum_w = Q6_V_vzero(); + HVX_Vector v_l1_w = Q6_V_vzero(); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t kt = 0; kt < tiles_per_group; ++kt) { + const HVX_Vector * vptr = (const HVX_Vector *) (src_base + (size_t) kt * tile_stride); + HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) kt * dst_tile_stride); + HVX_Vector v_m_b0, v_m_b1; + int_hmx_m_b4_pair_from_f16(vptr[6], v_inv127_qf, &v_m_b0, &v_m_b1); + + #pragma clang loop pipeline(disable) unroll(disable) + for (int i = 0; i < 4; ++i) { + HVX_Vector v_m_b4 = (i < 2) ? v_m_b0 : v_m_b1; + HVX_Vector v_q0 = Q6_V_vxor_VV(Q6_Vh_vasl_VhR(unpack_q6_k_group(vptr, 2 * i + 0, mask_0f, mask_03, Q6_V_vzero()), 2), sign_80); + HVX_Vector v_q1 = Q6_V_vxor_VV(Q6_Vh_vasl_VhR(unpack_q6_k_group(vptr, 2 * i + 1, mask_0f, mask_03, Q6_V_vzero()), 2), sign_80); + int_hmx_rescale_pair_wb(v_q0, v_q1, v_m_b4, tile_dst, i, &v_sum_w, &v_l1_w); + } + } + + emit_int_hmx_scales_and_bias(v_max_sf, 32.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out); +} +DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q6_k) + +static inline void int_hmx_pack_q6_pair( + HVX_Vector v_hi0, + HVX_Vector v_lo0, + HVX_Vector v_hi1, + HVX_Vector v_lo1, + HVX_Vector * restrict v_W0_out, + HVX_Vector * restrict v_W1_out) { +#if __HVX_ARCH__ >= 79 + *v_W0_out = Q6_Vb_vasr_VhVhR_rnd_sat(v_hi0, v_lo0, 6); + *v_W1_out = Q6_Vb_vasr_VhVhR_rnd_sat(v_hi1, v_lo1, 6); +#else + *v_W0_out = Q6_Vb_vround_VhVh_sat(Q6_Vh_vasl_VhR(v_hi0, 2), Q6_Vh_vasl_VhR(v_lo0, 2)); + *v_W1_out = Q6_Vb_vround_VhVh_sat(Q6_Vh_vasl_VhR(v_hi1, 2), Q6_Vh_vasl_VhR(v_lo1, 2)); +#endif +} + +static inline HVX_Vector int_hmx_asym_update_wmax_qf( + HVX_Vector v_wmax_sf, + HVX_Vector vd_qf, + HVX_Vector vm_qf, + HVX_Vector v_qmax_qf) { + + const HVX_Vector v_abs_mask_sf = Q6_V_vsplat_R(0x7fffffff); + HVX_Vector vm_sf = Q6_Vsf_equals_Vqf32(vm_qf); + HVX_Vector v_end = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(vd_qf, v_qmax_qf), vm_qf)); + HVX_Vector v_ext0 = Q6_V_vand_VV(vm_sf, v_abs_mask_sf); + HVX_Vector v_ext1 = Q6_V_vand_VV(v_end, v_abs_mask_sf); + return Q6_Vsf_vmax_VsfVsf(v_wmax_sf, Q6_Vsf_vmax_VsfVsf(v_ext0, v_ext1)); +} + +static inline void int_hmx_asym_alpha_beta_wb( + HVX_Vector vd_qf, + HVX_Vector vm_qf, + HVX_Vector v_scale_q6_qf, + HVX_Vector * restrict v_alpha_h_out, + HVX_Vector * restrict v_beta_h_out) { + + const HVX_Vector v12M_sf = Q6_V_vsplat_R(0x4B400000); + HVX_Vector v_a_bias = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(vd_qf, v_scale_q6_qf), v12M_sf)); + HVX_Vector v_b_bias = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(vm_qf, v_scale_q6_qf), v12M_sf)); + *v_alpha_h_out = Q6_Vh_vshuffe_VhVh(v_a_bias, v_a_bias); + *v_beta_h_out = Q6_Vh_vshuffe_VhVh(v_b_bias, v_b_bias); +} + +static inline void int_hmx_rescale_asym_pair_wb( + HVX_Vector v_q0, + HVX_Vector v_q1, + HVX_Vector v_alpha_h, + HVX_Vector v_beta_h, + HVX_Vector * restrict tile_dst, + int pair_idx, + HVX_Vector * restrict v_sum_w, + HVX_Vector * restrict v_l1_w) { + + const HVX_Vector v_one_s8 = Q6_Vb_vsplat_R(1); + HVX_VectorPair vp0 = Q6_Wh_vmpy_VbVb(v_q0, v_one_s8); + HVX_VectorPair vp1 = Q6_Wh_vmpy_VbVb(v_q1, v_one_s8); + HVX_Vector v_p0_e = Q6_Vh_vmpyiacc_VhVhVh(v_beta_h, Q6_V_lo_W(vp0), v_alpha_h); + HVX_Vector v_p0_o = Q6_Vh_vmpyiacc_VhVhVh(v_beta_h, Q6_V_hi_W(vp0), v_alpha_h); + HVX_Vector v_p1_e = Q6_Vh_vmpyiacc_VhVhVh(v_beta_h, Q6_V_lo_W(vp1), v_alpha_h); + HVX_Vector v_p1_o = Q6_Vh_vmpyiacc_VhVhVh(v_beta_h, Q6_V_hi_W(vp1), v_alpha_h); + HVX_Vector v_W0, v_W1; + int_hmx_pack_q6_pair(v_p0_o, v_p0_e, v_p1_o, v_p1_e, &v_W0, &v_W1); + int_hmx_store_and_accum_pair(tile_dst, pair_idx, v_W0, v_W1, v_sum_w, v_l1_w); +} + +static inline void int_hmx_iq2xxs_decode_pair( + HVX_Vector v_c2, + HVX_Vector v_sgn, + int l, + HVX_Vector v_nib_lut, + HVX_Vector * restrict v_w0_out, + HVX_Vector * restrict v_w1_out) { + + const HVX_Vector v_zero = Q6_V_vzero(); + const HVX_Vector v_one = Q6_V_vsplat_R(1); + const HVX_Vector v_sgn_mask = Q6_V_vsplat_R(IQ2XXS_SIGN_MASK); + + HVX_Vector v_s7 = Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_sgn, IQ2XXS_SIGN_BITS * l), v_sgn_mask); + HVX_Vector v_t = Q6_Vh_vpopcount_Vh(v_s7); + HVX_Vector v_s = Q6_V_vor_VV(v_s7, Q6_Vw_vasl_VwR(Q6_V_vand_VV(v_t, v_one), IQ2XXS_PARITY_SHIFT)); + HVX_Vector v_s16 = Q6_V_vor_VV(v_s, Q6_Vw_vasl_VwR(v_s, 8)); + HVX_Vector v_rep = Q6_V_vor_VV(v_s16, Q6_Vw_vasl_VwR(v_s16, 16)); + HVX_VectorPred q_lo = Q6_Q_vand_VR(v_rep, IQ2XXS_SIGN_PRED_LO); + HVX_VectorPred q_hi = Q6_Q_vand_VR(v_rep, IQ2XXS_SIGN_PRED_HI); + + HVX_Vector v_d = (l & 1) ? Q6_Vh_vshuffo_VhVh(v_c2, v_c2) : Q6_Vh_vshuffe_VhVh(v_c2, v_c2); + HVX_Vector v_n = Q6_V_vor_VV(Q6_V_vand_VV(v_d, Q6_V_vsplat_R(IQ2XXS_NIB_LO_MASK)), + Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_d, 4), Q6_V_vsplat_R(IQ2XXS_NIB_HI_MASK))); + HVX_VectorPair p_g = Q6_Wh_vlut16_VbVhR(v_n, v_nib_lut, 0); + HVX_Vector v_g0 = Q6_V_lo_W(p_g); + HVX_Vector v_g1 = Q6_V_hi_W(p_g); + + *v_w0_out = Q6_V_vmux_QVV(q_lo, Q6_Vb_vsub_VbVb(v_zero, v_g0), v_g0); + *v_w1_out = Q6_V_vmux_QVV(q_hi, Q6_Vb_vsub_VbVb(v_zero, v_g1), v_g1); +} + +static inline HVX_Vector int_hmx_iq2xxs_gather_d(const uint8_t * restrict sb) { + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_IQ2_XXS); + HVX_Vector v_dd = Q6_V_vzero(); + #pragma clang loop pipeline(disable) unroll(disable) + for (int j = 0; j < IQ2XXS_TILES_PER_SB; j++) { + HVX_Vector v = hvx_vmem(sb + (size_t) j * tile_stride + IQ2XXS_D_SLICE_OFF); + v_dd = Q6_V_vmux_QVV(Q6_Q_vsetq_R(IQ2XXS_D_SLICE_BYTES * j), v_dd, + Q6_V_vror_VR(v, (VLEN - IQ2XXS_D_SLICE_BYTES * j) & (VLEN - 1))); + } + return v_dd; +} + +static inline void rescale_iq2_xxs_weight_superblock_impl( + const uint8_t * restrict src_base, + uint8_t * restrict dst_wt, + float * restrict dst_scales, + HVX_Vector * restrict bias_out, + uint32_t tiles_per_group, + size_t dst_tile_stride) { + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_IQ2_XXS); + const HVX_Vector v_abs_mask_sf = Q6_V_vsplat_R(0x7fffffff); + const HVX_Vector v_one_w = Q6_V_vsplat_R(1); + const HVX_Vector v_one_s8 = Q6_Vb_vsplat_R(1); + const HVX_Vector v12M_sf = Q6_V_vsplat_R(0x4B400000); + const HVX_Vector v_nib_lut = hvx_vmem(iq2xxs_vtcm_lut); + + HVX_Vector v_max_sf = Q6_V_vzero(); + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t sb_kt = 0; sb_kt < tiles_per_group; sb_kt += IQ2XXS_TILES_PER_SB) { + const uint8_t * sb = src_base + (size_t) sb_kt * tile_stride; + HVX_Vector v_d_sf = Q6_V_lo_W(hvx_vec_f16_to_f32(int_hmx_iq2xxs_gather_d(sb))); + HVX_Vector v_d_abs_sf = Q6_V_vand_VV(v_d_sf, v_abs_mask_sf); + HVX_Vector v_max_sc_u32 = Q6_V_vzero(); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t j = 0; j < IQ2XXS_TILES_PER_SB; ++j) { + const uint8_t * tile_src = sb + (size_t) j * tile_stride; + HVX_Vector v_sgn = Q6_V_hi_W(Q6_W_vdeal_VVR(hvx_vmem(tile_src + VLEN), hvx_vmem(tile_src), -IQ2XXS_WORD_BYTES)); + v_max_sc_u32 = Q6_Vw_vmax_VwVw(v_max_sc_u32, Q6_Vuw_vlsr_VuwR(v_sgn, IQ2XXS_SCALE_SHIFT)); + } + + HVX_Vector v_max_ls = Q6_Vw_vadd_VwVw(Q6_Vw_vasl_VwR(v_max_sc_u32, 1), v_one_w); + v_max_sf = Q6_Vsf_vmax_VsfVsf(v_max_sf, hvx_vec_mul_f32_f32(v_d_abs_sf, Q6_Vsf_equals_Vw(v_max_ls))); + } + + HVX_Vector v_scale_q6_qf = int_hmx_scale_qf_from_max_f32(v_max_sf, 8128.0f / 43.0f); + HVX_Vector v_sum_w = Q6_V_vzero(); + HVX_Vector v_l1_w = Q6_V_vzero(); + HVX_Vector v_sgn = iq2xxs_gather_issue(src_base); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t sb_kt = 0; sb_kt < tiles_per_group; sb_kt += IQ2XXS_TILES_PER_SB) { + const uint8_t * sb = src_base + (size_t) sb_kt * tile_stride; + HVX_Vector v_d_qf = hvx_vec_f32_to_qf32(Q6_V_lo_W(hvx_vec_f16_to_f32(int_hmx_iq2xxs_gather_d(sb)))); + HVX_Vector v_d_sc_qf = Q6_Vqf32_vmpy_Vqf32Vqf32(v_d_qf, v_scale_q6_qf); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t j = 0; j < IQ2XXS_TILES_PER_SB; ++j) { + const uint32_t kt = sb_kt + j; + const uint8_t * tile_src = sb + (size_t) j * tile_stride; + HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) kt * dst_tile_stride); + + HVX_Vector v_c[2]; + iq2xxs_gather_wait(tile_src, v_c); + const HVX_Vector v_sgn_cur = v_sgn; + if (kt + 1 < tiles_per_group) { + v_sgn = iq2xxs_gather_issue(tile_src + tile_stride); + } + + HVX_Vector v_ls = Q6_Vw_vadd_VwVw(Q6_Vw_vasl_VwR(Q6_Vuw_vlsr_VuwR(v_sgn_cur, IQ2XXS_SCALE_SHIFT), 1), v_one_w); + HVX_Vector v_ls_qf = hvx_vec_f32_to_qf32(Q6_Vsf_equals_Vw(v_ls)); + HVX_Vector v_m_bias = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(v_d_sc_qf, v_ls_qf), v12M_sf)); + HVX_Vector v_alpha_h = Q6_Vh_vshuffe_VhVh(v_m_bias, v_m_bias); + + #pragma clang loop pipeline(disable) unroll(disable) + for (int i = 0; i < 4; ++i) { + HVX_Vector v_w0, v_w1; + int_hmx_iq2xxs_decode_pair((i < 2) ? v_c[0] : v_c[1], v_sgn_cur, i, v_nib_lut, &v_w0, &v_w1); + HVX_VectorPair vp0 = Q6_Wh_vmpy_VbVb(v_w0, v_one_s8); + HVX_VectorPair vp1 = Q6_Wh_vmpy_VbVb(v_w1, v_one_s8); + HVX_Vector v_p0_e = Q6_Vh_vmpyi_VhVh(Q6_V_lo_W(vp0), v_alpha_h); + HVX_Vector v_p0_o = Q6_Vh_vmpyi_VhVh(Q6_V_hi_W(vp0), v_alpha_h); + HVX_Vector v_p1_e = Q6_Vh_vmpyi_VhVh(Q6_V_lo_W(vp1), v_alpha_h); + HVX_Vector v_p1_o = Q6_Vh_vmpyi_VhVh(Q6_V_hi_W(vp1), v_alpha_h); + HVX_Vector v_W0, v_W1; + int_hmx_pack_q6_pair(v_p0_o, v_p0_e, v_p1_o, v_p1_e, &v_W0, &v_W1); + int_hmx_store_and_accum_pair(tile_dst, i, v_W0, v_W1, &v_sum_w, &v_l1_w); + } + } + } + + emit_int_hmx_scales_and_bias(v_max_sf, 0.125f * 43.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out); +} +DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(iq2_xxs) + +static inline void rescale_q4_1_weight_superblock_impl( + const uint8_t * restrict src_base, + uint8_t * restrict dst_wt, + float * restrict dst_scales, + HVX_Vector * restrict bias_out, + uint32_t tiles_per_group, + size_t dst_tile_stride) { + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q4_1); + const HVX_Vector mask_0f = Q6_Vb_vsplat_R(0x0F); + const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f); + const HVX_Vector v_qmax_qf = hvx_vec_f32_to_qf32(hvx_vec_splat_f32(15.0f)); + + HVX_Vector v_wmax_sf = Q6_V_vzero(); + for (uint32_t kt = 0; kt < tiles_per_group; ++kt) { + const uint8_t * tile_src = src_base + (size_t) kt * tile_stride; + HVX_VectorPair vp_dm_qf = Q6_Wqf32_vmpy_VhfVhf(hvx_vmem(tile_src + 512), v_one_f16); + v_wmax_sf = int_hmx_asym_update_wmax_qf(v_wmax_sf, Q6_V_lo_W(vp_dm_qf), Q6_V_hi_W(vp_dm_qf), v_qmax_qf); + } + + HVX_Vector v_scale_q6_qf = int_hmx_scale_qf_from_max_f32(v_wmax_sf, 8128.0f); + HVX_Vector v_sum_w = Q6_V_vzero(); + HVX_Vector v_l1_w = Q6_V_vzero(); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t kt = 0; kt < tiles_per_group; ++kt) { + const uint8_t * tile_src = src_base + (size_t) kt * tile_stride; + HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) kt * dst_tile_stride); + HVX_VectorPair vp_dm_qf = Q6_Wqf32_vmpy_VhfVhf(hvx_vmem(tile_src + 512), v_one_f16); + HVX_Vector v_alpha_h, v_beta_h; + int_hmx_asym_alpha_beta_wb(Q6_V_lo_W(vp_dm_qf), Q6_V_hi_W(vp_dm_qf), v_scale_q6_qf, &v_alpha_h, &v_beta_h); + + #pragma clang loop pipeline(disable) unroll(disable) + for (int i = 0; i < 4; ++i) { + HVX_Vector vq = hvx_vmem(tile_src + i * 128); + HVX_Vector v_lo = Q6_V_vand_VV(vq, mask_0f); + HVX_Vector v_hi = Q6_Vub_vlsr_VubR(vq, 4); + int_hmx_rescale_asym_pair_wb(v_lo, v_hi, v_alpha_h, v_beta_h, tile_dst, i, &v_sum_w, &v_l1_w); + } + } + + emit_int_hmx_scales_and_bias(v_wmax_sf, 1.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out); +} +DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q4_1) + +static inline void rescale_q5_k_weight_superblock_impl( + const uint8_t * restrict src_base, + uint8_t * restrict dst_wt, + float * restrict dst_scales, + HVX_Vector * restrict bias_out, + uint32_t tiles_per_group, + size_t dst_tile_stride) { + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q5_K); + const HVX_Vector mask_0f = Q6_Vb_vsplat_R(0x0F); + const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f); + const HVX_Vector v_qmax_qf = hvx_vec_f32_to_qf32(hvx_vec_splat_f32(31.0f)); + + HVX_Vector v_wmax_sf = Q6_V_vzero(); + for (uint32_t kt = 0; kt < tiles_per_group; ++kt) { + const uint8_t * tile_src = src_base + (size_t) kt * tile_stride; + HVX_VectorPair vp_dm_qf = Q6_Wqf32_vmpy_VhfVhf(hvx_vmem(tile_src + 512), v_one_f16); + v_wmax_sf = int_hmx_asym_update_wmax_qf(v_wmax_sf, Q6_V_lo_W(vp_dm_qf), Q6_V_hi_W(vp_dm_qf), v_qmax_qf); + } + + HVX_Vector v_scale_q6_qf = int_hmx_scale_qf_from_max_f32(v_wmax_sf, 8128.0f); + HVX_Vector v_sum_w = Q6_V_vzero(); + HVX_Vector v_l1_w = Q6_V_vzero(); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t kt = 0; kt < tiles_per_group; ++kt) { + const uint8_t * tile_src = src_base + (size_t) kt * tile_stride; + HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) kt * dst_tile_stride); + HVX_Vector v_plane = hvx_vmem(tile_src + 640); + HVX_VectorPair vp_dm_qf = Q6_Wqf32_vmpy_VhfVhf(hvx_vmem(tile_src + 512), v_one_f16); + HVX_Vector v_alpha_h, v_beta_h; + int_hmx_asym_alpha_beta_wb(Q6_V_lo_W(vp_dm_qf), Q6_V_hi_W(vp_dm_qf), v_scale_q6_qf, &v_alpha_h, &v_beta_h); + + #pragma clang loop pipeline(disable) unroll(disable) + for (int i = 0; i < 4; ++i) { + HVX_Vector vq = hvx_vmem(tile_src + i * 128); + HVX_Vector v_lo = hvx_q5k_or_hibit(Q6_V_vand_VV(vq, mask_0f), v_plane, 2 * i + 0); + HVX_Vector v_hi = hvx_q5k_or_hibit(Q6_Vub_vlsr_VubR(vq, 4), v_plane, 2 * i + 1); + int_hmx_rescale_asym_pair_wb(v_lo, v_hi, v_alpha_h, v_beta_h, tile_dst, i, &v_sum_w, &v_l1_w); + } + } + + emit_int_hmx_scales_and_bias(v_wmax_sf, 1.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out); +} +DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q5_k) + +static inline void int_hmx_q2_k_load_dmin( + const uint8_t * restrict sb, + HVX_Vector * restrict v_d, + HVX_Vector * restrict v_m) { + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q2_K); + HVX_Vector v_dd = Q6_V_vzero(); + #pragma clang loop pipeline(disable) unroll(disable) + for (int j = 0; j < 8; j++) { + HVX_Vector v = hvx_vmem(sb + (size_t) j * tile_stride + 256); + v_dd = Q6_V_vmux_QVV(Q6_Q_vsetq_R(16 * j), v_dd, Q6_V_vror_VR(v, (64 - 16 * j) & 127)); + } + HVX_VectorPred q_lo = Q6_Q_vsetq_R(64); + HVX_Vector v_r = Q6_V_vror_VR(v_dd, 64); + *v_d = Q6_V_vmux_QVV(q_lo, v_dd, v_r); + *v_m = Q6_V_vmux_QVV(q_lo, v_r, v_dd); +} + +static inline void rescale_q2_k_weight_superblock_impl( + const uint8_t * restrict src_base, + uint8_t * restrict dst_wt, + float * restrict dst_scales, + HVX_Vector * restrict bias_out, + uint32_t tiles_per_group, + size_t dst_tile_stride) { + + const size_t tile_stride = htp_tensor_get_tile_padded_size(HTP_TYPE_Q2_K); + const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f); + const HVX_Vector v_qmax_qf = hvx_vec_f32_to_qf32(hvx_vec_splat_f32(3.0f)); + + HVX_Vector v_wmax_sf = Q6_V_vzero(); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t sb_kt = 0; sb_kt < tiles_per_group; sb_kt += 8) { + const uint8_t * sb = src_base + (size_t) sb_kt * tile_stride; + HVX_Vector v_d, v_dm; + int_hmx_q2_k_load_dmin(sb, &v_d, &v_dm); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t j = 0; j < 8; ++j) { + const uint8_t * tile_src = sb + (size_t) j * tile_stride; + HVX_Vector v_D, v_M; + q2_k_unpack_scales(tile_src, v_d, v_dm, &v_D, &v_M); + HVX_VectorPair vp_d_qf = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_D), v_one_f16); + HVX_VectorPair vp_m_qf = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_M), v_one_f16); + v_wmax_sf = int_hmx_asym_update_wmax_qf(v_wmax_sf, Q6_V_lo_W(vp_d_qf), Q6_V_lo_W(vp_m_qf), v_qmax_qf); + v_wmax_sf = int_hmx_asym_update_wmax_qf(v_wmax_sf, Q6_V_hi_W(vp_d_qf), Q6_V_hi_W(vp_m_qf), v_qmax_qf); + } + } + + HVX_Vector v_scale_q6_qf = int_hmx_scale_qf_from_max_f32(v_wmax_sf, 8128.0f); + HVX_Vector v_sum_w = Q6_V_vzero(); + HVX_Vector v_l1_w = Q6_V_vzero(); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t sb_kt = 0; sb_kt < tiles_per_group; sb_kt += 8) { + const uint8_t * sb = src_base + (size_t) sb_kt * tile_stride; + HVX_Vector v_d, v_dm; + int_hmx_q2_k_load_dmin(sb, &v_d, &v_dm); + + #pragma clang loop pipeline(disable) unroll(disable) + for (uint32_t j = 0; j < 8; ++j) { + const uint32_t kt = sb_kt + j; + const uint8_t * tile_src = sb + (size_t) j * tile_stride; + const HVX_Vector * vptr = (const HVX_Vector *) tile_src; + HVX_Vector * tile_dst = (HVX_Vector *) (dst_wt + (size_t) kt * dst_tile_stride); + + HVX_Vector v_D, v_M; + q2_k_unpack_scales(tile_src, v_d, v_dm, &v_D, &v_M); + + #pragma clang loop pipeline(disable) unroll(disable) + for (int sub = 0; sub < 2; ++sub) { + HVX_Vector v_D_sub = (sub == 0) ? v_D : Q6_V_vror_VR(v_D, 64); + HVX_Vector v_M_sub = (sub == 0) ? v_M : Q6_V_vror_VR(v_M, 64); + HVX_Vector v_d_qf = Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_D_sub), v_one_f16)); + HVX_Vector v_m_qf = Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_M_sub), v_one_f16)); + HVX_Vector v_alpha_h, v_beta_h; + int_hmx_asym_alpha_beta_wb(v_d_qf, v_m_qf, v_scale_q6_qf, &v_alpha_h, &v_beta_h); + + const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03); + for (int p = 0; p < 2; ++p) { + const int i = 2 * sub + p; + HVX_Vector v_q0 = unpack_q3_k_low2(vptr, 2 * i + 0, mask_03); + HVX_Vector v_q1 = unpack_q3_k_low2(vptr, 2 * i + 1, mask_03); + int_hmx_rescale_asym_pair_wb(v_q0, v_q1, v_alpha_h, v_beta_h, tile_dst, i, &v_sum_w, &v_l1_w); + } + } + } + } + + emit_int_hmx_scales_and_bias(v_wmax_sf, 1.0f / 127.0f, v_sum_w, v_l1_w, dst_scales, bias_out); +} +DEFINE_RESCALE_WEIGHT_SUPERBLOCK_ENTRY(q2_k) + +static inline void resolve_int_weight_rescale_fns( + int32_t weight_type, + int_rescale_superblock_fn_t * restrict fn_2k, + int_rescale_superblock_fn_t * restrict fn_tail) { + switch (weight_type) { + case HTP_TYPE_Q4_0: *fn_2k = rescale_q4_0_weight_superblock_2k; *fn_tail = rescale_q4_0_weight_superblock_tail; break; + case HTP_TYPE_Q8_0: *fn_2k = rescale_q8_0_weight_superblock_2k; *fn_tail = rescale_q8_0_weight_superblock_tail; break; + case HTP_TYPE_IQ4_NL: *fn_2k = rescale_iq4_nl_weight_superblock_2k; *fn_tail = rescale_iq4_nl_weight_superblock_tail; break; + case HTP_TYPE_MXFP4: *fn_2k = rescale_mxfp4_weight_superblock_2k; *fn_tail = rescale_mxfp4_weight_superblock_tail; break; + case HTP_TYPE_Q5_0: *fn_2k = rescale_q5_0_weight_superblock_2k; *fn_tail = rescale_q5_0_weight_superblock_tail; break; + case HTP_TYPE_Q1_0: *fn_2k = rescale_q1_0_weight_superblock_2k; *fn_tail = rescale_q1_0_weight_superblock_tail; break; + case HTP_TYPE_Q2_0: *fn_2k = rescale_q2_0_weight_superblock_2k; *fn_tail = rescale_q2_0_weight_superblock_tail; break; + case HTP_TYPE_NVFP4: *fn_2k = rescale_nvfp4_weight_superblock_2k; *fn_tail = rescale_nvfp4_weight_superblock_tail; break; + case HTP_TYPE_Q3_K: *fn_2k = rescale_q3_k_weight_superblock_2k; *fn_tail = rescale_q3_k_weight_superblock_tail; break; + case HTP_TYPE_Q6_K: *fn_2k = rescale_q6_k_weight_superblock_2k; *fn_tail = rescale_q6_k_weight_superblock_tail; break; + case HTP_TYPE_IQ2_XXS: *fn_2k = rescale_iq2_xxs_weight_superblock_2k; *fn_tail = rescale_iq2_xxs_weight_superblock_tail; break; + case HTP_TYPE_Q4_1: + case HTP_TYPE_Q4_K: *fn_2k = rescale_q4_1_weight_superblock_2k; *fn_tail = rescale_q4_1_weight_superblock_tail; break; + case HTP_TYPE_Q5_1: + case HTP_TYPE_Q5_K: *fn_2k = rescale_q5_k_weight_superblock_2k; *fn_tail = rescale_q5_k_weight_superblock_tail; break; + case HTP_TYPE_Q2_K: *fn_2k = rescale_q2_k_weight_superblock_2k; *fn_tail = rescale_q2_k_weight_superblock_tail; break; + default: *fn_2k = NULL; *fn_tail = NULL; break; + } +} + +static void rescale_int_weight_to_int8_task( + const int_weight_rescale_state_t * state, + uint32_t start_unit, + uint32_t end_unit) { + + const uint32_t n_k_tiles = state->n_k_tiles; + const uint32_t n_groups = state->n_groups; + const uint32_t tail_tiles = state->tail_tiles; + const uint32_t aligned_tile_size = state->aligned_tile_size; + const uint32_t raw_shift = state->raw_shift; + const int_rescale_superblock_fn_t rescale_2k_fn = state->rescale_2k_fn; + const int_rescale_superblock_fn_t tail_fn = (tail_tiles == HTP_MM_HMX_W8A8_KGROUP_TILES) + ? rescale_2k_fn + : state->rescale_tail_fn; + + uint32_t ct = fastdiv(start_unit, &state->n_groups_div); + uint32_t g = start_unit - ct * n_groups; + const uint32_t n_col_paired = state->n_col_tiles & ~1u; + + for (uint32_t u = start_unit; u < end_unit; ++u) { + const bool is_full_group = (g + 1u < n_groups); + const size_t kt_group_start = (size_t) g * HTP_MM_HMX_W8A8_KGROUP_TILES; + const size_t kt_start = (size_t) ct * n_k_tiles + kt_group_start; + const uint32_t tiles_in_group = is_full_group ? HTP_MM_HMX_W8A8_KGROUP_TILES : tail_tiles; + const int_rescale_superblock_fn_t fn = is_full_group ? rescale_2k_fn : tail_fn; + const uint8_t * src_base = state->src_raw + (kt_start >> raw_shift) * aligned_tile_size; + uint8_t * dst_wt; + size_t dst_tile_stride; + if (ct < n_col_paired) { + // Interleave paired column tiles (2*jp, 2*jp+1) into 2048B K-tiles for weight.b:deep. + dst_wt = state->dst_wt_base + + ((size_t) (ct & ~1u) * n_k_tiles + kt_group_start * 2 + (ct & 1u)) * HTP_MM_HMX_WEIGHT_B_TILE_SIZE; + dst_tile_stride = 2 * HTP_MM_HMX_WEIGHT_B_TILE_SIZE; + } else { + dst_wt = state->dst_wt_base + kt_start * HTP_MM_HMX_WEIGHT_B_TILE_SIZE; + dst_tile_stride = HTP_MM_HMX_WEIGHT_B_TILE_SIZE; + } + float * dst_scales = state->dst_scales_base + (size_t) u * 32; + HVX_Vector * bias_out = (HVX_Vector *) (state->dst_bias_base + (size_t) u * (2 * HTP_MM_HMX_BIAS_BANK_SIZE)); + + fn(src_base, dst_wt, dst_scales, bias_out, tiles_in_group, dst_tile_stride); + + if (++g == n_groups) { + g = 0; + ++ct; + } + } +} + +static inline void quantize_f16_quad_step_to_u8_sm( + uint8_t * restrict tile_row_base, + uint32_t kt, + uint32_t rg, + HVX_Vector vh0, + HVX_Vector vh1, + HVX_Vector vh2, + HVX_Vector vh3, + HVX_Vector v_inv0_qf, + HVX_Vector v_inv1_qf, + HVX_Vector v_inv2_qf, + HVX_Vector v_inv3_qf, + HVX_Vector v_one_f16, + HVX_Vector v_bias_u8, + HVX_Vector v_min_u8, + HVX_Vector v_max_u8) { + +#if __HVX_ARCH__ >= 81 + (void) v_bias_u8; + (void) v_min_u8; + (void) v_max_u8; + + HVX_VectorPair vp0 = Q6_Wqf32_vmpy_VhfVhf(vh0, v_one_f16); + HVX_VectorPair vp1 = Q6_Wqf32_vmpy_VhfVhf(vh1, v_one_f16); + HVX_VectorPair vp2 = Q6_Wqf32_vmpy_VhfVhf(vh2, v_one_f16); + HVX_VectorPair vp3 = Q6_Wqf32_vmpy_VhfVhf(vh3, v_one_f16); + + HVX_Vector hf0 = Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp0), v_inv0_qf), + Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf))); + HVX_Vector hf1 = Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp1), v_inv1_qf), + Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf))); + HVX_Vector hf2 = Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp2), v_inv2_qf), + Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf))); + HVX_Vector hf3 = Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp3), v_inv3_qf), + Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf))); + + hmx_pack_hf_quad_to_u8_cm_pair(tile_row_base, kt, rg, hf0, hf1, hf2, hf3); +#else + HVX_VectorPair vp0 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vh0), v_one_f16); + HVX_VectorPair vp1 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vh1), v_one_f16); + HVX_VectorPair vp2 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vh2), v_one_f16); + HVX_VectorPair vp3 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vh3), v_one_f16); + + { + HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf), v_bias_u8)); + HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf), v_bias_u8)); + HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf), v_bias_u8)); + HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf), v_bias_u8)); + HVX_Vector vh01 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y1, y0), v_min_u8), v_max_u8); + HVX_Vector vh23 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y3, y2), v_min_u8), v_max_u8); + ((HVX_Vector *) (tile_row_base + (size_t) (kt + 0) * HTP_MM_HMX_TILE_SIZE))[rg] = Q6_Vb_vpacke_VhVh(vh23, vh01); + } + { + HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp0), v_inv0_qf), v_bias_u8)); + HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp1), v_inv1_qf), v_bias_u8)); + HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp2), v_inv2_qf), v_bias_u8)); + HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp3), v_inv3_qf), v_bias_u8)); + HVX_Vector vh01 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y1, y0), v_min_u8), v_max_u8); + HVX_Vector vh23 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y3, y2), v_min_u8), v_max_u8); + ((HVX_Vector *) (tile_row_base + (size_t) (kt + 1) * HTP_MM_HMX_TILE_SIZE))[rg] = Q6_Vb_vpacke_VhVh(vh23, vh01); + } +#endif +} + +static __attribute__((noinline)) void quantize_act_superblock_quad_f32_to_u8_sm_2k( + uint8_t * restrict tile_row_base, + float * restrict d_a_out, + const float * restrict p0, + const float * restrict p1, + const float * restrict p2, + const float * restrict p3, + uint32_t rg, + uint32_t k_start, + uint32_t valid_rows) { + + const float * p0_base = p0 + k_start; + const float * p1_base = p1 + k_start; + const float * p2_base = p2 + k_start; + const float * p3_base = p3 + k_start; + uint8_t * tile_dst_base = tile_row_base + (size_t) (k_start >> 5) * HTP_MM_HMX_TILE_SIZE; + + assert(hex_is_aligned(p0_base, 128)); + assert(hex_is_aligned(p1_base, 128)); + assert(hex_is_aligned(p2_base, 128)); + assert(hex_is_aligned(p3_base, 128)); + + HVX_Vector vmax0 = Q6_V_vzero(); + HVX_Vector vmax1 = Q6_V_vzero(); + HVX_Vector vmax2 = Q6_V_vzero(); + HVX_Vector vmax3 = Q6_V_vzero(); + + for (uint32_t kt = 0; kt < HTP_MM_HMX_W8A8_KGROUP_TILES; ++kt) { + const uint32_t off = kt * 32; + HVX_Vector vx0 = hvx_vmem(p0_base + off); + HVX_Vector vx1 = hvx_vmem(p1_base + off); + HVX_Vector vx2 = hvx_vmem(p2_base + off); + HVX_Vector vx3 = hvx_vmem(p3_base + off); + vmax0 = Q6_Vsf_vmax_VsfVsf(vmax0, hvx_vec_abs_f32(vx0)); + vmax1 = Q6_Vsf_vmax_VsfVsf(vmax1, hvx_vec_abs_f32(vx1)); + vmax2 = Q6_Vsf_vmax_VsfVsf(vmax2, hvx_vec_abs_f32(vx2)); + vmax3 = Q6_Vsf_vmax_VsfVsf(vmax3, hvx_vec_abs_f32(vx3)); + } + + vmax0 = (valid_rows > 0) ? hvx_vec_reduce_max_f32(vmax0) : Q6_V_vzero(); + vmax1 = (valid_rows > 1) ? hvx_vec_reduce_max_f32(vmax1) : Q6_V_vzero(); + vmax2 = (valid_rows > 2) ? hvx_vec_reduce_max_f32(vmax2) : Q6_V_vzero(); + vmax3 = (valid_rows > 3) ? hvx_vec_reduce_max_f32(vmax3) : Q6_V_vzero(); + + const HVX_Vector v_inv_127 = hvx_vec_splat_f32(1.0f / 127.0f); + const HVX_Vector v_127 = hvx_vec_splat_f32(127.0f); + const HVX_Vector v_eps = hvx_vec_splat_f32(1e-30f); + + HVX_Vector vd0 = hvx_vec_mul_f32_f32(vmax0, v_inv_127); + HVX_Vector vd1 = hvx_vec_mul_f32_f32(vmax1, v_inv_127); + HVX_Vector vd2 = hvx_vec_mul_f32_f32(vmax2, v_inv_127); + HVX_Vector vd3 = hvx_vec_mul_f32_f32(vmax3, v_inv_127); + HVX_Vector v_d02 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd2, vd0, -4)); + HVX_Vector v_d13 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd3, vd1, -4)); + HVX_Vector v_d0123 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_d13, v_d02, -4)); + hvx_vec_store_u(d_a_out, 4 * sizeof(float), v_d0123); + + HVX_Vector v_inv0 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax0, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax0), v_127), Q6_V_vzero()); + HVX_Vector v_inv1 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax1, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax1), v_127), Q6_V_vzero()); + HVX_Vector v_inv2 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax2, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax2), v_127), Q6_V_vzero()); + HVX_Vector v_inv3 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax3, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax3), v_127), Q6_V_vzero()); + +#if __HVX_ARCH__ >= 81 + for (uint32_t step = 0; step < HTP_MM_HMX_W8A8_KGROUP_TILES / 2; ++step) { + const uint32_t off = step * 64; + HVX_Vector hf0 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p0_base + off + 32), v_inv0), + Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p0_base + off + 0), v_inv0)))); + HVX_Vector hf1 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p1_base + off + 32), v_inv1), + Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p1_base + off + 0), v_inv1)))); + HVX_Vector hf2 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p2_base + off + 32), v_inv2), + Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p2_base + off + 0), v_inv2)))); + HVX_Vector hf3 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV( + Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p3_base + off + 32), v_inv3), + Q6_Vqf32_vmpy_VsfVsf(hvx_vmem(p3_base + off + 0), v_inv3)))); + + hmx_pack_hf_quad_to_u8_cm_pair(tile_dst_base, step * 2, rg, hf0, hf1, hf2, hf3); + } +#else + const HVX_Vector v_bias_u8 = Q6_V_vsplat_R(0x4B400080); // 12582912.0f + 128.0f + const HVX_Vector v_min_u8 = Q6_Vh_vsplat_R(1); + const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255); + + for (uint32_t kt = 0; kt < HTP_MM_HMX_W8A8_KGROUP_TILES; ++kt) { + const uint32_t off = kt * 32; + HVX_Vector vx0 = hvx_vmem(p0_base + off); + HVX_Vector vx1 = hvx_vmem(p1_base + off); + HVX_Vector vx2 = hvx_vmem(p2_base + off); + HVX_Vector vx3 = hvx_vmem(p3_base + off); + + HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0), v_bias_u8)); + HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1), v_bias_u8)); + HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2), v_bias_u8)); + HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3), v_bias_u8)); + + HVX_Vector vh01 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y1, y0), v_min_u8), v_max_u8); + HVX_Vector vh23 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y3, y2), v_min_u8), v_max_u8); + HVX_Vector v_u8 = Q6_Vb_vpacke_VhVh(vh23, vh01); + + ((HVX_Vector *) (tile_dst_base + (size_t) kt * HTP_MM_HMX_TILE_SIZE))[rg] = v_u8; + } +#endif +} + +// Quantize one superblock g (k_group columns, multiple of 32) of a 4-row FP32 group into W8A8 SM 64x32 tiles. +static __attribute__((noinline)) void quantize_act_superblock_quad_f32_to_u8_sm( + uint8_t * restrict tile_row_base, + float * restrict d_a_out, + const float * restrict p0, + const float * restrict p1, + const float * restrict p2, + const float * restrict p3, + uint32_t rg, + uint32_t k_start, + uint32_t k_group, + uint32_t k_valid, + uint32_t valid_rows) { + + assert(hex_is_aligned(p0 + k_start, 128)); + assert(hex_is_aligned(p1 + k_start, 128)); + assert(hex_is_aligned(p2 + k_start, 128)); + assert(hex_is_aligned(p3 + k_start, 128)); + + const uint32_t k_end = k_start + k_group; + const uint32_t c_end_full = (k_end <= k_valid) ? k_end + : ((k_valid > k_start) ? (k_start + ((k_valid - k_start) & ~31u)) : k_start); + HVX_Vector vmax0 = Q6_V_vzero(); + HVX_Vector vmax1 = Q6_V_vzero(); + HVX_Vector vmax2 = Q6_V_vzero(); + HVX_Vector vmax3 = Q6_V_vzero(); + + for (uint32_t c = k_start; c < c_end_full; c += 32) { + HVX_Vector vx0 = hvx_vmem(p0 + c); + HVX_Vector vx1 = hvx_vmem(p1 + c); + HVX_Vector vx2 = hvx_vmem(p2 + c); + HVX_Vector vx3 = hvx_vmem(p3 + c); + vmax0 = Q6_Vsf_vmax_VsfVsf(vmax0, hvx_vec_abs_f32(vx0)); + vmax1 = Q6_Vsf_vmax_VsfVsf(vmax1, hvx_vec_abs_f32(vx1)); + vmax2 = Q6_Vsf_vmax_VsfVsf(vmax2, hvx_vec_abs_f32(vx2)); + vmax3 = Q6_Vsf_vmax_VsfVsf(vmax3, hvx_vec_abs_f32(vx3)); + } + if (c_end_full < k_end && c_end_full < k_valid) { + const uint32_t c = c_end_full; + const uint32_t rem = k_valid - c; + HVX_VectorPred mask = Q6_Q_vsetq2_R(rem * sizeof(float)); + HVX_Vector vx0 = Q6_V_vmux_QVV(mask, hvx_vmem(p0 + c), Q6_V_vzero()); + HVX_Vector vx1 = Q6_V_vmux_QVV(mask, hvx_vmem(p1 + c), Q6_V_vzero()); + HVX_Vector vx2 = Q6_V_vmux_QVV(mask, hvx_vmem(p2 + c), Q6_V_vzero()); + HVX_Vector vx3 = Q6_V_vmux_QVV(mask, hvx_vmem(p3 + c), Q6_V_vzero()); + vmax0 = Q6_Vsf_vmax_VsfVsf(vmax0, hvx_vec_abs_f32(vx0)); + vmax1 = Q6_Vsf_vmax_VsfVsf(vmax1, hvx_vec_abs_f32(vx1)); + vmax2 = Q6_Vsf_vmax_VsfVsf(vmax2, hvx_vec_abs_f32(vx2)); + vmax3 = Q6_Vsf_vmax_VsfVsf(vmax3, hvx_vec_abs_f32(vx3)); + } + + vmax0 = (valid_rows > 0) ? hvx_vec_reduce_max_f32(vmax0) : Q6_V_vzero(); + vmax1 = (valid_rows > 1) ? hvx_vec_reduce_max_f32(vmax1) : Q6_V_vzero(); + vmax2 = (valid_rows > 2) ? hvx_vec_reduce_max_f32(vmax2) : Q6_V_vzero(); + vmax3 = (valid_rows > 3) ? hvx_vec_reduce_max_f32(vmax3) : Q6_V_vzero(); + + const HVX_Vector v_inv_127 = hvx_vec_splat_f32(1.0f / 127.0f); + const HVX_Vector v_127 = hvx_vec_splat_f32(127.0f); + const HVX_Vector v_eps = hvx_vec_splat_f32(1e-30f); + + HVX_Vector vd0 = hvx_vec_mul_f32_f32(vmax0, v_inv_127); + HVX_Vector vd1 = hvx_vec_mul_f32_f32(vmax1, v_inv_127); + HVX_Vector vd2 = hvx_vec_mul_f32_f32(vmax2, v_inv_127); + HVX_Vector vd3 = hvx_vec_mul_f32_f32(vmax3, v_inv_127); + HVX_Vector v_d02 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd2, vd0, -4)); + HVX_Vector v_d13 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd3, vd1, -4)); + HVX_Vector v_d0123 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_d13, v_d02, -4)); + hvx_vec_store_u(d_a_out, 4 * sizeof(float), v_d0123); + + HVX_Vector v_inv0 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax0, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax0), v_127), Q6_V_vzero()); + HVX_Vector v_inv1 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax1, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax1), v_127), Q6_V_vzero()); + HVX_Vector v_inv2 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax2, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax2), v_127), Q6_V_vzero()); + HVX_Vector v_inv3 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax3, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax3), v_127), Q6_V_vzero()); + + const HVX_Vector v_bias_u8 = Q6_V_vsplat_R(0x4B400080); // 12582912.0f + 128.0f + const HVX_Vector v_min_u8 = Q6_Vh_vsplat_R(1); + const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255); + + for (uint32_t c = k_start; c < c_end_full; c += 32) { + HVX_Vector vx0 = hvx_vmem(p0 + c); + HVX_Vector vx1 = hvx_vmem(p1 + c); + HVX_Vector vx2 = hvx_vmem(p2 + c); + HVX_Vector vx3 = hvx_vmem(p3 + c); + + HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0), v_bias_u8)); + HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1), v_bias_u8)); + HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2), v_bias_u8)); + HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3), v_bias_u8)); + + HVX_Vector vh01 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y1, y0), v_min_u8), v_max_u8); + HVX_Vector vh23 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y3, y2), v_min_u8), v_max_u8); + HVX_Vector v_u8 = Q6_Vb_vpacke_VhVh(vh23, vh01); + + uint32_t kt = c >> 5; + ((HVX_Vector *) (tile_row_base + (size_t) kt * HTP_MM_HMX_TILE_SIZE))[rg] = v_u8; + } + for (uint32_t c = c_end_full; c < k_end; c += 32) { + HVX_Vector vx0 = Q6_V_vzero(); + HVX_Vector vx1 = Q6_V_vzero(); + HVX_Vector vx2 = Q6_V_vzero(); + HVX_Vector vx3 = Q6_V_vzero(); + if (c < k_valid) { + uint32_t rem = k_valid - c; + HVX_VectorPred mask = Q6_Q_vsetq2_R(rem * sizeof(float)); + vx0 = Q6_V_vmux_QVV(mask, hvx_vmem(p0 + c), Q6_V_vzero()); + vx1 = Q6_V_vmux_QVV(mask, hvx_vmem(p1 + c), Q6_V_vzero()); + vx2 = Q6_V_vmux_QVV(mask, hvx_vmem(p2 + c), Q6_V_vzero()); + vx3 = Q6_V_vmux_QVV(mask, hvx_vmem(p3 + c), Q6_V_vzero()); + } + HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0), v_bias_u8)); + HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1), v_bias_u8)); + HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2), v_bias_u8)); + HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3), v_bias_u8)); + + HVX_Vector vh01 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y1, y0), v_min_u8), v_max_u8); + HVX_Vector vh23 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y3, y2), v_min_u8), v_max_u8); + HVX_Vector v_u8 = Q6_Vb_vpacke_VhVh(vh23, vh01); + + uint32_t kt = c >> 5; + ((HVX_Vector *) (tile_row_base + (size_t) kt * HTP_MM_HMX_TILE_SIZE))[rg] = v_u8; + } +} + +static __attribute__((noinline)) void quantize_act_superblock_quad_f16_to_u8_sm_2k( + uint8_t * restrict tile_row_base, + float * restrict d_a_out, + const __fp16 * restrict p0, + const __fp16 * restrict p1, + const __fp16 * restrict p2, + const __fp16 * restrict p3, + uint32_t rg, + uint32_t k_start, + uint32_t valid_rows) { + + const __fp16 * p0_base = p0 + k_start; + const __fp16 * p1_base = p1 + k_start; + const __fp16 * p2_base = p2 + k_start; + const __fp16 * p3_base = p3 + k_start; + uint8_t * tile_dst_base = tile_row_base + (size_t) (k_start >> 5) * HTP_MM_HMX_TILE_SIZE; + + assert(hex_is_aligned(p0_base, 128)); + assert(hex_is_aligned(p1_base, 128)); + assert(hex_is_aligned(p2_base, 128)); + assert(hex_is_aligned(p3_base, 128)); + + const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f); + const HVX_Vector v_abs_f16 = Q6_Vh_vsplat_R(0x7fff); + HVX_Vector vmax_hf0 = Q6_V_vzero(); + HVX_Vector vmax_hf1 = Q6_V_vzero(); + HVX_Vector vmax_hf2 = Q6_V_vzero(); + HVX_Vector vmax_hf3 = Q6_V_vzero(); + + for (uint32_t step = 0; step < HTP_MM_HMX_W8A8_KGROUP_TILES / 2; ++step) { + const uint32_t off = step * 64; + HVX_Vector vh0 = hvx_vmem(p0_base + off); + HVX_Vector vh1 = hvx_vmem(p1_base + off); + HVX_Vector vh2 = hvx_vmem(p2_base + off); + HVX_Vector vh3 = hvx_vmem(p3_base + off); + vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vand_VV(vh0, v_abs_f16)); + vmax_hf1 = Q6_Vhf_vmax_VhfVhf(vmax_hf1, Q6_V_vand_VV(vh1, v_abs_f16)); + vmax_hf2 = Q6_Vhf_vmax_VhfVhf(vmax_hf2, Q6_V_vand_VV(vh2, v_abs_f16)); + vmax_hf3 = Q6_Vhf_vmax_VhfVhf(vmax_hf3, Q6_V_vand_VV(vh3, v_abs_f16)); + } + + vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vror_VR(vmax_hf0, 64)); + vmax_hf1 = Q6_Vhf_vmax_VhfVhf(vmax_hf1, Q6_V_vror_VR(vmax_hf1, 64)); + vmax_hf2 = Q6_Vhf_vmax_VhfVhf(vmax_hf2, Q6_V_vror_VR(vmax_hf2, 64)); + vmax_hf3 = Q6_Vhf_vmax_VhfVhf(vmax_hf3, Q6_V_vror_VR(vmax_hf3, 64)); + + HVX_Vector vmax0 = (valid_rows > 0) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf0), v_one_f16)))) : Q6_V_vzero(); + HVX_Vector vmax1 = (valid_rows > 1) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf1), v_one_f16)))) : Q6_V_vzero(); + HVX_Vector vmax2 = (valid_rows > 2) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf2), v_one_f16)))) : Q6_V_vzero(); + HVX_Vector vmax3 = (valid_rows > 3) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf3), v_one_f16)))) : Q6_V_vzero(); + + const HVX_Vector v_inv_127 = hvx_vec_splat_f32(1.0f / 127.0f); + const HVX_Vector v_127 = hvx_vec_splat_f32(127.0f); + const HVX_Vector v_eps = hvx_vec_splat_f32(1e-30f); + + HVX_Vector vd0 = hvx_vec_mul_f32_f32(vmax0, v_inv_127); + HVX_Vector vd1 = hvx_vec_mul_f32_f32(vmax1, v_inv_127); + HVX_Vector vd2 = hvx_vec_mul_f32_f32(vmax2, v_inv_127); + HVX_Vector vd3 = hvx_vec_mul_f32_f32(vmax3, v_inv_127); + HVX_Vector v_d02 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd2, vd0, -4)); + HVX_Vector v_d13 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd3, vd1, -4)); + HVX_Vector v_d0123 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_d13, v_d02, -4)); + hvx_vec_store_u(d_a_out, 4 * sizeof(float), v_d0123); + + HVX_Vector v_inv0_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax0, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax0), v_127), Q6_V_vzero())); + HVX_Vector v_inv1_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax1, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax1), v_127), Q6_V_vzero())); + HVX_Vector v_inv2_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax2, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax2), v_127), Q6_V_vzero())); + HVX_Vector v_inv3_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax3, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax3), v_127), Q6_V_vzero())); + + const HVX_Vector v_bias_u8 = Q6_V_vsplat_R(0x4B400080); + const HVX_Vector v_min_u8 = Q6_Vh_vsplat_R(1); + const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255); + + for (uint32_t step = 0; step < HTP_MM_HMX_W8A8_KGROUP_TILES / 2; ++step) { + const uint32_t off = step * 64; + HVX_Vector vh0 = hvx_vmem(p0_base + off); + HVX_Vector vh1 = hvx_vmem(p1_base + off); + HVX_Vector vh2 = hvx_vmem(p2_base + off); + HVX_Vector vh3 = hvx_vmem(p3_base + off); + quantize_f16_quad_step_to_u8_sm(tile_dst_base, step * 2, rg, vh0, vh1, vh2, vh3, + v_inv0_qf, v_inv1_qf, v_inv2_qf, v_inv3_qf, + v_one_f16, v_bias_u8, v_min_u8, v_max_u8); + } +} + +// Quantize one superblock g (k_group columns, multiple of 128) of a 4-row FP16 group into W8A8 SM 64x32 tiles. +static __attribute__((noinline)) void quantize_act_superblock_quad_f16_to_u8_sm( + uint8_t * restrict tile_row_base, + float * restrict d_a_out, + const __fp16 * restrict p0, + const __fp16 * restrict p1, + const __fp16 * restrict p2, + const __fp16 * restrict p3, + uint32_t rg, + uint32_t k_start, + uint32_t k_group, + uint32_t k_valid, + uint32_t valid_rows) { + + assert(hex_is_aligned(p0 + k_start, 128)); + assert(hex_is_aligned(p1 + k_start, 128)); + assert(hex_is_aligned(p2 + k_start, 128)); + assert(hex_is_aligned(p3 + k_start, 128)); + + const uint32_t k_end = k_start + k_group; + const uint32_t c_end_full = (k_end <= k_valid) ? k_end + : ((k_valid > k_start) ? (k_start + ((k_valid - k_start) & ~63u)) : k_start); + const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f); + const HVX_Vector v_abs_f16 = Q6_Vh_vsplat_R(0x7fff); + HVX_Vector vmax_hf0 = Q6_V_vzero(); + HVX_Vector vmax_hf1 = Q6_V_vzero(); + HVX_Vector vmax_hf2 = Q6_V_vzero(); + HVX_Vector vmax_hf3 = Q6_V_vzero(); + + for (uint32_t c = k_start; c < c_end_full; c += 64) { + HVX_Vector vh0 = hvx_vmem(p0 + c); + HVX_Vector vh1 = hvx_vmem(p1 + c); + HVX_Vector vh2 = hvx_vmem(p2 + c); + HVX_Vector vh3 = hvx_vmem(p3 + c); + vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vand_VV(vh0, v_abs_f16)); + vmax_hf1 = Q6_Vhf_vmax_VhfVhf(vmax_hf1, Q6_V_vand_VV(vh1, v_abs_f16)); + vmax_hf2 = Q6_Vhf_vmax_VhfVhf(vmax_hf2, Q6_V_vand_VV(vh2, v_abs_f16)); + vmax_hf3 = Q6_Vhf_vmax_VhfVhf(vmax_hf3, Q6_V_vand_VV(vh3, v_abs_f16)); + } + if (c_end_full < k_end && c_end_full < k_valid) { + const uint32_t c = c_end_full; + const uint32_t rem_b = (k_valid - c) * sizeof(__fp16); + HVX_VectorPred mask = Q6_Q_vsetq2_R(rem_b); + HVX_Vector vh0 = Q6_V_vmux_QVV(mask, hvx_vmem(p0 + c), Q6_V_vzero()); + HVX_Vector vh1 = Q6_V_vmux_QVV(mask, hvx_vmem(p1 + c), Q6_V_vzero()); + HVX_Vector vh2 = Q6_V_vmux_QVV(mask, hvx_vmem(p2 + c), Q6_V_vzero()); + HVX_Vector vh3 = Q6_V_vmux_QVV(mask, hvx_vmem(p3 + c), Q6_V_vzero()); + vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vand_VV(vh0, v_abs_f16)); + vmax_hf1 = Q6_Vhf_vmax_VhfVhf(vmax_hf1, Q6_V_vand_VV(vh1, v_abs_f16)); + vmax_hf2 = Q6_Vhf_vmax_VhfVhf(vmax_hf2, Q6_V_vand_VV(vh2, v_abs_f16)); + vmax_hf3 = Q6_Vhf_vmax_VhfVhf(vmax_hf3, Q6_V_vand_VV(vh3, v_abs_f16)); + } + + vmax_hf0 = Q6_Vhf_vmax_VhfVhf(vmax_hf0, Q6_V_vror_VR(vmax_hf0, 64)); + vmax_hf1 = Q6_Vhf_vmax_VhfVhf(vmax_hf1, Q6_V_vror_VR(vmax_hf1, 64)); + vmax_hf2 = Q6_Vhf_vmax_VhfVhf(vmax_hf2, Q6_V_vror_VR(vmax_hf2, 64)); + vmax_hf3 = Q6_Vhf_vmax_VhfVhf(vmax_hf3, Q6_V_vror_VR(vmax_hf3, 64)); + + HVX_Vector vmax0 = (valid_rows > 0) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf0), v_one_f16)))) : Q6_V_vzero(); + HVX_Vector vmax1 = (valid_rows > 1) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf1), v_one_f16)))) : Q6_V_vzero(); + HVX_Vector vmax2 = (valid_rows > 2) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf2), v_one_f16)))) : Q6_V_vzero(); + HVX_Vector vmax3 = (valid_rows > 3) ? hvx_vec_reduce_max_f32(Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vmax_hf3), v_one_f16)))) : Q6_V_vzero(); + + const HVX_Vector v_inv_127 = hvx_vec_splat_f32(1.0f / 127.0f); + const HVX_Vector v_127 = hvx_vec_splat_f32(127.0f); + const HVX_Vector v_eps = hvx_vec_splat_f32(1e-30f); + + HVX_Vector vd0 = hvx_vec_mul_f32_f32(vmax0, v_inv_127); + HVX_Vector vd1 = hvx_vec_mul_f32_f32(vmax1, v_inv_127); + HVX_Vector vd2 = hvx_vec_mul_f32_f32(vmax2, v_inv_127); + HVX_Vector vd3 = hvx_vec_mul_f32_f32(vmax3, v_inv_127); + HVX_Vector v_d02 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd2, vd0, -4)); + HVX_Vector v_d13 = Q6_V_lo_W(Q6_W_vshuff_VVR(vd3, vd1, -4)); + HVX_Vector v_d0123 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_d13, v_d02, -4)); + hvx_vec_store_u(d_a_out, 4 * sizeof(float), v_d0123); + + HVX_Vector v_inv0_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax0, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax0), v_127), Q6_V_vzero())); + HVX_Vector v_inv1_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax1, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax1), v_127), Q6_V_vzero())); + HVX_Vector v_inv2_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax2, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax2), v_127), Q6_V_vzero())); + HVX_Vector v_inv3_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax3, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax3), v_127), Q6_V_vzero())); + + const HVX_Vector v_bias_u8 = Q6_V_vsplat_R(0x4B400080); + const HVX_Vector v_min_u8 = Q6_Vh_vsplat_R(1); + const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255); + + for (uint32_t c = k_start; c < c_end_full; c += 64) { + HVX_Vector vh0 = hvx_vmem(p0 + c); + HVX_Vector vh1 = hvx_vmem(p1 + c); + HVX_Vector vh2 = hvx_vmem(p2 + c); + HVX_Vector vh3 = hvx_vmem(p3 + c); + quantize_f16_quad_step_to_u8_sm(tile_row_base, c >> 5, rg, vh0, vh1, vh2, vh3, v_inv0_qf, v_inv1_qf, v_inv2_qf, v_inv3_qf, v_one_f16, v_bias_u8, v_min_u8, v_max_u8); + } + for (uint32_t c = c_end_full; c < k_end; c += 64) { + HVX_Vector vh0 = Q6_V_vzero(); + HVX_Vector vh1 = Q6_V_vzero(); + HVX_Vector vh2 = Q6_V_vzero(); + HVX_Vector vh3 = Q6_V_vzero(); + if (c < k_valid) { + uint32_t rem_b = (k_valid - c) * sizeof(__fp16); + HVX_VectorPred mask = Q6_Q_vsetq2_R(rem_b); + vh0 = Q6_V_vmux_QVV(mask, hvx_vmem(p0 + c), Q6_V_vzero()); + vh1 = Q6_V_vmux_QVV(mask, hvx_vmem(p1 + c), Q6_V_vzero()); + vh2 = Q6_V_vmux_QVV(mask, hvx_vmem(p2 + c), Q6_V_vzero()); + vh3 = Q6_V_vmux_QVV(mask, hvx_vmem(p3 + c), Q6_V_vzero()); + } + quantize_f16_quad_step_to_u8_sm(tile_row_base, c >> 5, rg, vh0, vh1, vh2, vh3, v_inv0_qf, v_inv1_qf, v_inv2_qf, v_inv3_qf, v_one_f16, v_bias_u8, v_min_u8, v_max_u8); + } +} + +#define DEFINE_QUANTIZE_ACT_STEP_ROWS_W8A8(SFX, ACT_T, QUANT_SB_2K_FN, QUANT_SB_TAIL_FN) \ +static __attribute__((noinline)) void quantize_act_step_rows_##SFX( \ + uint8_t * restrict vtcm_act_dst, \ + float * restrict vtcm_act_scales, \ + const uint8_t * restrict curr_buf, \ + size_t row_bytes, \ + uint32_t r, \ + uint32_t valid_rows, \ + uint32_t mc_pad, \ + uint32_t n_k_tiles, \ + uint32_t n_groups, \ + uint32_t k_valid) { \ + const uint32_t r0 = r >> 6; \ + const uint32_t rg = (r & 63u) >> 2; \ + uint8_t * tile_row_base = vtcm_act_dst + (size_t) r0 * n_k_tiles * HTP_MM_HMX_TILE_SIZE; \ + if (valid_rows == 0) { \ + const HVX_Vector v_zero = Q6_V_vzero(); \ + const HVX_Vector v_zp = Q6_Vb_vsplat_R(0x80); \ + for (uint32_t g = 0; g < n_groups; ++g) { \ + hvx_vec_store_u(vtcm_act_scales + (size_t) g * mc_pad + r, 4 * sizeof(float), v_zero); \ + } \ + for (uint32_t kt = 0; kt < n_k_tiles; ++kt) { \ + ((HVX_Vector *) (tile_row_base + (size_t) kt * HTP_MM_HMX_TILE_SIZE))[rg] = v_zp; \ + } \ + } else { \ + const uint32_t k_block = n_k_tiles << 5; \ + const ACT_T * p0 = (const ACT_T *) curr_buf; \ + const ACT_T * p1 = (valid_rows > 1) ? (const ACT_T *) (curr_buf + 1 * row_bytes) : p0; \ + const ACT_T * p2 = (valid_rows > 2) ? (const ACT_T *) (curr_buf + 2 * row_bytes) : p0; \ + const ACT_T * p3 = (valid_rows > 3) ? (const ACT_T *) (curr_buf + 3 * row_bytes) : p0; \ + for (uint32_t g = 0; g < n_groups; ++g) { \ + const uint32_t k_start = g * HTP_MM_HMX_W8A8_KGROUP; \ + const uint32_t k_group = (g + 1u < n_groups) ? HTP_MM_HMX_W8A8_KGROUP : (k_block - k_start); \ + float * d_a_out = vtcm_act_scales + (size_t) g * mc_pad + r; \ + if (k_group == HTP_MM_HMX_W8A8_KGROUP && k_start + HTP_MM_HMX_W8A8_KGROUP <= k_valid) { \ + QUANT_SB_2K_FN(tile_row_base, d_a_out, p0, p1, p2, p3, rg, k_start, valid_rows); \ + } else { \ + QUANT_SB_TAIL_FN(tile_row_base, d_a_out, p0, p1, p2, p3, rg, k_start, k_group, k_valid, \ + valid_rows); \ + } \ + } \ + } \ +} + +DEFINE_QUANTIZE_ACT_STEP_ROWS_W8A8(f16_w8a8, __fp16, quantize_act_superblock_quad_f16_to_u8_sm_2k, quantize_act_superblock_quad_f16_to_u8_sm) +DEFINE_QUANTIZE_ACT_STEP_ROWS_W8A8(f32_w8a8, float, quantize_act_superblock_quad_f32_to_u8_sm_2k, quantize_act_superblock_quad_f32_to_u8_sm) + +// Core HMX W8A8 SM dot-product kernel over all superblocks g = 0..n_groups-1. +static void core_dot_chunk_w8a8_sm( + uint8_t * restrict vtcm_out, + const uint8_t * restrict vtcm_act, + const uint8_t * restrict vtcm_weight_tiles, + const uint8_t * restrict vtcm_weight_bias, + uint32_t n_row_tiles_64, + uint32_t n_col_tiles, + uint32_t n_k_tiles, + uint32_t n_groups) { + + assert(hex_is_aligned(vtcm_out, HTP_MM_HMX_TILE_SIZE)); + assert(hex_is_aligned(vtcm_act, HTP_MM_HMX_TILE_SIZE)); + assert(hex_is_aligned(vtcm_weight_tiles, HTP_MM_HMX_TILE_SIZE)); + + const uint32_t out_cm_rng = hmx_out_cm_range(); + const uint32_t tail_tiles = n_k_tiles - (n_groups - 1u) * HTP_MM_HMX_W8A8_KGROUP_TILES; + + // Clearing convert (retain_acc = 0) clears the active accumulator and implicitly swaps primary/secondary. +#if __HVX_ARCH__ >= 79 + const uint32_t cvt_p_hi = hmx_cvt_ctrl(0, 0, 0, 1); + const uint32_t cvt_p_lo = hmx_cvt_ctrl(1, 0, 1, 0); + const uint32_t cvt_s_hi = hmx_cvt_ctrl(2, 0, 0, 1); + const uint32_t cvt_s_lo = hmx_cvt_ctrl(3, 0, 1, 0); +#else + const uint32_t cvt_p_hi = hmx_cvt_ctrl(0, 0, 0, 1); + const uint32_t cvt_p_lo = hmx_cvt_ctrl(0, 0, 1, 0); + const uint32_t cvt_s_hi = cvt_p_hi; + const uint32_t cvt_s_lo = cvt_p_lo; +#endif + + for (uint32_t g = 0; g < n_groups; ++g) { + const uint32_t kt_base = g * HTP_MM_HMX_W8A8_KGROUP_TILES; + const bool is_tail = (g + 1u == n_groups && tail_tiles < HTP_MM_HMX_W8A8_KGROUP_TILES); + const uint32_t tiles_in_group = is_tail ? tail_tiles : HTP_MM_HMX_W8A8_KGROUP_TILES; + const uint32_t a_rng = hmx_act_sm_range(tiles_in_group); + + for (uint32_t j = 0; j + 1u < n_col_tiles; j += 2) { + const uint8_t * wt_pair_base = vtcm_weight_tiles + + ((size_t) (j >> 1) * n_k_tiles + kt_base) * (2 * HTP_MM_HMX_WEIGHT_B_TILE_SIZE); + const uint8_t * bias_p_hi = vtcm_weight_bias + (((size_t) (j + 0) * n_groups + g) * 2 + 0) * HTP_MM_HMX_BIAS_BANK_SIZE; + const uint8_t * bias_p_lo = vtcm_weight_bias + (((size_t) (j + 0) * n_groups + g) * 2 + 1) * HTP_MM_HMX_BIAS_BANK_SIZE; + const uint8_t * bias_s_hi = vtcm_weight_bias + (((size_t) (j + 1) * n_groups + g) * 2 + 0) * HTP_MM_HMX_BIAS_BANK_SIZE; + const uint8_t * bias_s_lo = vtcm_weight_bias + (((size_t) (j + 1) * n_groups + g) * 2 + 1) * HTP_MM_HMX_BIAS_BANK_SIZE; + +#if __HVX_ARCH__ >= 79 + hmx_load_bias_bank(bias_p_hi, 0); + hmx_load_bias_bank(bias_p_lo, 1); + hmx_load_bias_bank(bias_s_hi, 2); + hmx_load_bias_bank(bias_s_lo, 3); +#endif + + for (uint32_t i = 0; i < n_row_tiles_64; ++i) { + const uint8_t * act_base = vtcm_act + ((size_t) i * n_k_tiles + kt_base) * HTP_MM_HMX_TILE_SIZE; + + const size_t out_idx = (((size_t) g * n_row_tiles_64 + i) * n_col_tiles + j) * 2; + uint8_t * out_p_hi = vtcm_out + (out_idx + 0) * HTP_MM_HMX_TILE_SIZE; + uint8_t * out_p_lo = vtcm_out + (out_idx + 1) * HTP_MM_HMX_TILE_SIZE; + uint8_t * out_s_hi = vtcm_out + (out_idx + 2) * HTP_MM_HMX_TILE_SIZE; + uint8_t * out_s_lo = vtcm_out + (out_idx + 3) * HTP_MM_HMX_TILE_SIZE; + + asm volatile(HMX_CLRACC_INT() : : : "memory"); + // weight.b:deep processes 2048B/tile; cap each single-packet range to 32 tiles (64KB). + for (uint32_t kt = 0; kt < tiles_in_group; kt += 32u) { + const uint32_t n_kt = hex_smin(tiles_in_group - kt, 32u); + const uint32_t a_r = hmx_act_sm_range(n_kt); + const uint32_t w_r = hmx_wt_b_range(n_kt * (2 * HTP_MM_HMX_WEIGHT_B_TILE_SIZE)); + const uint8_t * a_ptr = act_base + (size_t) kt * HTP_MM_HMX_TILE_SIZE; + const uint8_t * w_ptr = wt_pair_base + (size_t) kt * (2 * HTP_MM_HMX_WEIGHT_B_TILE_SIZE); + asm volatile(HMX_LOAD_MPY_DEEP_U8_S8_CM_64C("%0", "%1", "%2", "%3") + : : "r"(a_ptr), "r"(a_r), "r"(w_ptr), "r"(w_r) : "memory"); + } + +#if __HVX_ARCH__ >= 79 + asm volatile( + HMX_CVT_UB_ACC("%0") + HMX_STORE_CVT_CM("%4", "%8") + HMX_CVT_UB_ACC("%1") + HMX_STORE_CVT_CM("%5", "%8") + HMX_CVT_UB_ACC("%2") + HMX_STORE_CVT_CM("%6", "%8") + HMX_CVT_UB_ACC("%3") + HMX_STORE_CVT_CM("%7", "%8") + : + : "r"(cvt_p_hi), "r"(cvt_p_lo), "r"(cvt_s_hi), "r"(cvt_s_lo), + "r"(out_p_hi), "r"(out_p_lo), "r"(out_s_hi), "r"(out_s_lo), + "r"(out_cm_rng) + : "memory"); +#else + hmx_load_bias_bank(bias_p_hi, 0); + asm volatile(HMX_CVT_UB_ACC("%0") HMX_STORE_CVT_CM("%1", "%2") + : : "r"(cvt_p_hi), "r"(out_p_hi), "r"(out_cm_rng) : "memory"); + hmx_load_bias_bank(bias_p_lo, 0); + asm volatile(HMX_CVT_UB_ACC("%0") HMX_STORE_CVT_CM("%1", "%2") + : : "r"(cvt_p_lo), "r"(out_p_lo), "r"(out_cm_rng) : "memory"); + hmx_load_bias_bank(bias_s_hi, 0); + asm volatile(HMX_CVT_UB_ACC("%0") HMX_STORE_CVT_CM("%1", "%2") + : : "r"(cvt_s_hi), "r"(out_s_hi), "r"(out_cm_rng) : "memory"); + hmx_load_bias_bank(bias_s_lo, 0); + asm volatile(HMX_CVT_UB_ACC("%0") HMX_STORE_CVT_CM("%1", "%2") + : : "r"(cvt_s_lo), "r"(out_s_lo), "r"(out_cm_rng) : "memory"); +#endif + } + } + + if (n_col_tiles & 1u) { + const uint32_t j = n_col_tiles - 1u; + const uint32_t w_rng = hmx_wt_b_range(tiles_in_group * HTP_MM_HMX_WEIGHT_B_TILE_SIZE); + const uint8_t * wt_base = vtcm_weight_tiles + ((size_t) j * n_k_tiles + kt_base) * HTP_MM_HMX_WEIGHT_B_TILE_SIZE; + const uint8_t * bias_hi = vtcm_weight_bias + (((size_t) j * n_groups + g) * 2 + 0) * HTP_MM_HMX_BIAS_BANK_SIZE; + const uint8_t * bias_lo = vtcm_weight_bias + (((size_t) j * n_groups + g) * 2 + 1) * HTP_MM_HMX_BIAS_BANK_SIZE; + +#if __HVX_ARCH__ >= 79 + hmx_load_bias_bank(bias_hi, 0); + hmx_load_bias_bank(bias_lo, 1); +#endif + + for (uint32_t i = 0; i < n_row_tiles_64; ++i) { + const uint8_t * act_base = vtcm_act + ((size_t) i * n_k_tiles + kt_base) * HTP_MM_HMX_TILE_SIZE; + + const size_t out_idx = (((size_t) g * n_row_tiles_64 + i) * n_col_tiles + j) * 2; + uint8_t * out_hi = vtcm_out + (out_idx + 0) * HTP_MM_HMX_TILE_SIZE; + uint8_t * out_lo = vtcm_out + (out_idx + 1) * HTP_MM_HMX_TILE_SIZE; + + asm volatile(HMX_CLRACC_INT() : : : "memory"); + asm volatile(HMX_LOAD_MPY_DEEP_U8_S8_CM("%0", "%1", "%2", "%3") + : : "r"(act_base), "r"(a_rng), "r"(wt_base), "r"(w_rng) : "memory"); +#if __HVX_ARCH__ < 79 + hmx_load_bias_bank(bias_hi, 0); +#endif + asm volatile(HMX_CVT_UB_ACC("%0") : : "r"(cvt_p_hi) : "memory"); + asm volatile(HMX_STORE_CVT_CM("%0", "%1") : : "r"(out_hi), "r"(out_cm_rng) : "memory"); +#if __HVX_ARCH__ < 79 + hmx_load_bias_bank(bias_lo, 0); +#endif + asm volatile(HMX_CVT_UB_ACC("%0") : : "r"(cvt_p_lo) : "memory"); + asm volatile(HMX_STORE_CVT_CM("%0", "%1") : : "r"(out_lo), "r"(out_cm_rng) : "memory"); + } + } + } +} + +// Stage activation scales from VTCM to 128B-aligned L1D stack memory so scalar Rsf loads avoid VTCM stalls and SROA vextract spills. +static inline uint32_t (*stage_act_scales_to_l1d( + uint32_t (* restrict dst)[32], + const float * restrict vtcm_scales, + size_t group_stride, + uint32_t n_groups))[32] { + asm("" : "+r"(dst)); + for (uint32_t g = 0; g < n_groups; ++g) { + *(HVX_Vector *) dst[g] = hvx_vmem(vtcm_scales + g * group_stride); + } + return dst; +} + +#define HMX_INT_FIN_ROW_NONE(acc_qf, row_idx, bias_base, bias_rb, c) \ + Q6_Vsf_equals_Vqf32(acc_qf) + +#define HMX_INT_FIN_ROW_F16(acc_qf, row_idx, bias_base, bias_rb, c) \ + Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf((acc_qf), hmx_load_bias_f32_32_f16((bias_base) + (row_idx) * (bias_rb), (c)))) + +#define HMX_INT_FIN_ROW_F32(acc_qf, row_idx, bias_base, bias_rb, c) \ + Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf((acc_qf), hmx_load_bias_f32_32_f32((bias_base) + (row_idx) * (bias_rb), (c)))) + +#define HMX_INT_BIAS_ROW_none(bias, off) NULL +#define HMX_INT_BIAS_ROW_f16(bias, off) ((const uint8_t *) (bias) + (off)) +#define HMX_INT_BIAS_ROW_f32(bias, off) ((const uint8_t *) (bias) + (off)) + +static inline HVX_Vector hmx_pack_f32_to_f16_bias_f16( + HVX_Vector v_lo, HVX_Vector v_hi, const uint8_t * bias_row, size_t c) { + const HVX_VectorPair vp_b = hmx_load_bias_f32_64_f16(bias_row, c); + return hmx_pack_f32_to_f16_clamped( + hvx_vec_add_f32_f32(v_lo, Q6_V_lo_W(vp_b)), + hvx_vec_add_f32_f32(v_hi, Q6_V_hi_W(vp_b))); +} + +static inline HVX_Vector hmx_pack_f32_to_f16_bias_f32( + HVX_Vector v_lo, HVX_Vector v_hi, const uint8_t * bias_row, size_t c) { + return hmx_pack_f32_to_f16_clamped( + hvx_vec_add_f32_f32(v_lo, hmx_load_bias_f32_32_f32(bias_row, c)), + hvx_vec_add_f32_f32(v_hi, hmx_load_bias_f32_32_f32(bias_row, c + 32))); +} + +static inline HVX_Vector hmx_pack_f32_to_f16_tail_bias_f16( + HVX_Vector v_lo, HVX_Vector v_hi, const uint8_t * bias_row, size_t c, size_t valid_c) { + const HVX_VectorPair vp_b = hmx_load_bias_f32_64_f16(bias_row, c); + const HVX_Vector s0 = hvx_vec_add_f32_f32(v_lo, Q6_V_lo_W(vp_b)); + const HVX_Vector s1 = (valid_c > 32) ? hvx_vec_add_f32_f32(v_hi, Q6_V_hi_W(vp_b)) : Q6_V_vzero(); + return hmx_pack_f32_to_f16_clamped(s0, s1); +} + +static inline HVX_Vector hmx_pack_f32_to_f16_tail_bias_f32( + HVX_Vector v_lo, HVX_Vector v_hi, const uint8_t * bias_row, size_t c, size_t valid_c) { + const HVX_Vector s0 = hvx_vec_add_f32_f32(v_lo, hmx_load_bias_f32_32_f32(bias_row, c)); + const HVX_Vector s1 = (valid_c > 32) ? hvx_vec_add_f32_f32(v_hi, hmx_load_bias_f32_32_f32(bias_row, c + 32)) : Q6_V_vzero(); + return hmx_pack_f32_to_f16_clamped(s0, s1); +} + +#define HMX_INT_PACK_FP16_ROW_none(v_lo, v_hi, bias_base, bias_rb, row_idx, c) \ + hmx_pack_f32_to_f16_clamped((v_lo), (v_hi)) +#define HMX_INT_PACK_FP16_ROW_f16(v_lo, v_hi, bias_base, bias_rb, row_idx, c) \ + hmx_pack_f32_to_f16_bias_f16((v_lo), (v_hi), (bias_base) + (row_idx) * (bias_rb), (c)) +#define HMX_INT_PACK_FP16_ROW_f32(v_lo, v_hi, bias_base, bias_rb, row_idx, c) \ + hmx_pack_f32_to_f16_bias_f32((v_lo), (v_hi), (bias_base) + (row_idx) * (bias_rb), (c)) + +#define HMX_INT_PACK_FP16_TAIL_none(v_lo, v_hi, bias_base, bias_rb, row_idx, c, valid_c) \ + hmx_pack_f32_to_f16_clamped((v_lo), (v_hi)) +#define HMX_INT_PACK_FP16_TAIL_f16(v_lo, v_hi, bias_base, bias_rb, row_idx, c, valid_c) \ + hmx_pack_f32_to_f16_tail_bias_f16((v_lo), (v_hi), (bias_base) + (row_idx) * (bias_rb), (c), (valid_c)) +#define HMX_INT_PACK_FP16_TAIL_f32(v_lo, v_hi, bias_base, bias_rb, row_idx, c, valid_c) \ + hmx_pack_f32_to_f16_tail_bias_f32((v_lo), (v_hi), (bias_base) + (row_idx) * (bias_rb), (c), (valid_c)) + +#define DEFINE_W8A8_EVAL_TILE_QUAD(SFX, FIN_ROW) \ +static inline void w8a8_sm_eval_tile_quad_1g_##SFX( \ + const uint8_t * restrict tile_base, \ + const float * restrict dw_base, \ + size_t c, \ + const uint32_t * restrict da, \ + const uint8_t * restrict bias_row0, \ + size_t bias_row_bytes, \ + uint32_t n_rows, \ + size_t r, \ + bool full_quad, \ + HVX_Vector * v_out0, \ + HVX_Vector * v_out1, \ + HVX_Vector * v_out2, \ + HVX_Vector * v_out3) { \ + (void) bias_row0; \ + (void) bias_row_bytes; \ + const HVX_Vector sign_80 = Q6_Vb_vsplat_R(0x80); \ + const size_t c0 = c >> 5; \ + const uint8_t * tp = tile_base + c0 * 2 * HTP_MM_HMX_TILE_SIZE; \ + const HVX_Vector v_hi_s8 = Q6_V_vxor_VV(*(const HVX_Vector *) tp, sign_80); \ + const HVX_Vector v_lo_u8 = *(const HVX_Vector *) (tp + HTP_MM_HMX_TILE_SIZE); \ + const HVX_Vector v_dw_qf = hvx_vec_f32_to_qf32(*(const HVX_Vector *) (dw_base + c)); \ + HVX_VectorPair vp_i16 = Q6_W_vshuff_VVR(v_hi_s8, v_lo_u8, -1); \ + HVX_VectorPair vp_i32_01 = Q6_Ww_vunpack_Vh(Q6_V_lo_W(vp_i16)); \ + HVX_VectorPair vp_i32_23 = Q6_Ww_vunpack_Vh(Q6_V_hi_W(vp_i16)); \ + HVX_Vector v_f32_0 = Q6_Vsf_equals_Vw(Q6_V_lo_W(vp_i32_01)); \ + HVX_Vector v_acc0_qf = Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_0, da[0]), v_dw_qf); \ + *v_out0 = FIN_ROW(v_acc0_qf, 0, bias_row0, bias_row_bytes, c); \ + if (full_quad || r + 1 < n_rows) { \ + HVX_Vector v_f32_1 = Q6_Vsf_equals_Vw(Q6_V_hi_W(vp_i32_01)); \ + HVX_Vector v_acc1_qf = Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_1, da[1]), v_dw_qf); \ + *v_out1 = FIN_ROW(v_acc1_qf, 1, bias_row0, bias_row_bytes, c); \ + } \ + if (full_quad || r + 2 < n_rows) { \ + HVX_Vector v_f32_2 = Q6_Vsf_equals_Vw(Q6_V_lo_W(vp_i32_23)); \ + HVX_Vector v_acc2_qf = Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_2, da[2]), v_dw_qf); \ + *v_out2 = FIN_ROW(v_acc2_qf, 2, bias_row0, bias_row_bytes, c); \ + } \ + if (full_quad || r + 3 < n_rows) { \ + HVX_Vector v_f32_3 = Q6_Vsf_equals_Vw(Q6_V_hi_W(vp_i32_23)); \ + HVX_Vector v_acc3_qf = Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_3, da[3]), v_dw_qf); \ + *v_out3 = FIN_ROW(v_acc3_qf, 3, bias_row0, bias_row_bytes, c); \ + } \ +} \ +static inline void w8a8_sm_eval_tile_quad_2g_##SFX( \ + const uint8_t * restrict tile_base0, \ + const uint8_t * restrict tile_base1, \ + const float * restrict dw_base, \ + size_t c, \ + const uint32_t * restrict da0, \ + const uint32_t * restrict da1, \ + const uint8_t * restrict bias_row0, \ + size_t bias_row_bytes, \ + uint32_t n_rows, \ + size_t r, \ + bool full_quad, \ + HVX_Vector * v_out0, \ + HVX_Vector * v_out1, \ + HVX_Vector * v_out2, \ + HVX_Vector * v_out3) { \ + (void) bias_row0; \ + (void) bias_row_bytes; \ + const HVX_Vector sign_80 = Q6_Vb_vsplat_R(0x80); \ + const size_t c0 = c >> 5; \ + const size_t tile_off = c0 * 2 * HTP_MM_HMX_TILE_SIZE; \ + const uint8_t * tp0 = tile_base0 + tile_off; \ + const uint8_t * tp1 = tile_base1 + tile_off; \ + const float * dwp = dw_base + c0 * 64; \ + const HVX_Vector v_hi0_s8 = Q6_V_vxor_VV(*(const HVX_Vector *) tp0, sign_80); \ + const HVX_Vector v_lo0_u8 = *(const HVX_Vector *) (tp0 + HTP_MM_HMX_TILE_SIZE); \ + const HVX_Vector v_dw0_qf = hvx_vec_f32_to_qf32(*(const HVX_Vector *) dwp); \ + HVX_VectorPair vp0_i16 = Q6_W_vshuff_VVR(v_hi0_s8, v_lo0_u8, -1); \ + HVX_VectorPair vp0_01 = Q6_Ww_vunpack_Vh(Q6_V_lo_W(vp0_i16)); \ + HVX_VectorPair vp0_23 = Q6_Ww_vunpack_Vh(Q6_V_hi_W(vp0_i16)); \ + const HVX_Vector v_hi1_s8 = Q6_V_vxor_VV(*(const HVX_Vector *) tp1, sign_80); \ + const HVX_Vector v_lo1_u8 = *(const HVX_Vector *) (tp1 + HTP_MM_HMX_TILE_SIZE); \ + const HVX_Vector v_dw1_qf = hvx_vec_f32_to_qf32(*(const HVX_Vector *) (dwp + 32)); \ + HVX_VectorPair vp1_i16 = Q6_W_vshuff_VVR(v_hi1_s8, v_lo1_u8, -1); \ + HVX_VectorPair vp1_01 = Q6_Ww_vunpack_Vh(Q6_V_lo_W(vp1_i16)); \ + HVX_VectorPair vp1_23 = Q6_Ww_vunpack_Vh(Q6_V_hi_W(vp1_i16)); \ + HVX_Vector v_acc0_qf = Q6_Vqf32_vadd_Vqf32Vqf32( \ + Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_lo_W(vp0_01)), da0[0]), v_dw0_qf), \ + Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_lo_W(vp1_01)), da1[0]), v_dw1_qf)); \ + *v_out0 = FIN_ROW(v_acc0_qf, 0, bias_row0, bias_row_bytes, c); \ + if (full_quad || r + 1 < n_rows) { \ + HVX_Vector v_acc1_qf = Q6_Vqf32_vadd_Vqf32Vqf32( \ + Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_hi_W(vp0_01)), da0[1]), v_dw0_qf), \ + Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_hi_W(vp1_01)), da1[1]), v_dw1_qf)); \ + *v_out1 = FIN_ROW(v_acc1_qf, 1, bias_row0, bias_row_bytes, c); \ + } \ + if (full_quad || r + 2 < n_rows) { \ + HVX_Vector v_acc2_qf = Q6_Vqf32_vadd_Vqf32Vqf32( \ + Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_lo_W(vp0_23)), da0[2]), v_dw0_qf), \ + Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_lo_W(vp1_23)), da1[2]), v_dw1_qf)); \ + *v_out2 = FIN_ROW(v_acc2_qf, 2, bias_row0, bias_row_bytes, c); \ + } \ + if (full_quad || r + 3 < n_rows) { \ + HVX_Vector v_acc3_qf = Q6_Vqf32_vadd_Vqf32Vqf32( \ + Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_hi_W(vp0_23)), da0[3]), v_dw0_qf), \ + Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(Q6_Vsf_equals_Vw(Q6_V_hi_W(vp1_23)), da1[3]), v_dw1_qf)); \ + *v_out3 = FIN_ROW(v_acc3_qf, 3, bias_row0, bias_row_bytes, c); \ + } \ +} \ +static inline void w8a8_sm_eval_tile_quad_ng_##SFX( \ + const uint8_t * restrict tile_base, \ + const float * restrict dw_base, \ + size_t group_stride, \ + uint32_t n_groups, \ + const uint32_t * restrict da_quad_base, \ + HVX_Vector sign_80, \ + const uint8_t * restrict bias_row_base, \ + size_t c, \ + size_t bias_row_bytes, \ + uint32_t n_rows, \ + size_t r, \ + bool full_quad, \ + HVX_Vector * v_out0, \ + HVX_Vector * v_out1, \ + HVX_Vector * v_out2, \ + HVX_Vector * v_out3) { \ + (void) bias_row_base; \ + (void) bias_row_bytes; \ + const size_t c0 = c >> 5; \ + const uint8_t * tp = tile_base + c0 * 2 * HTP_MM_HMX_TILE_SIZE; \ + const float * dw = dw_base + c0 * (size_t) n_groups * 32; \ + const uint32_t * da = da_quad_base; \ + HVX_Vector v_acc0_qf = Q6_V_vzero(); \ + HVX_Vector v_acc1_qf = Q6_V_vzero(); \ + HVX_Vector v_acc2_qf = Q6_V_vzero(); \ + HVX_Vector v_acc3_qf = Q6_V_vzero(); \ + for (uint32_t g = 0; g < n_groups; ++g) { \ + const HVX_Vector v_hi_s8 = Q6_V_vxor_VV(*(const HVX_Vector *) tp, sign_80); \ + const HVX_Vector v_lo_u8 = *(const HVX_Vector *) (tp + HTP_MM_HMX_TILE_SIZE); \ + const HVX_Vector v_dw_qf = hvx_vec_f32_to_qf32(*(const HVX_Vector *) dw); \ + HVX_VectorPair vp_i16 = Q6_W_vshuff_VVR(v_hi_s8, v_lo_u8, -1); \ + HVX_VectorPair vp_i32_01 = Q6_Ww_vunpack_Vh(Q6_V_lo_W(vp_i16)); \ + HVX_VectorPair vp_i32_23 = Q6_Ww_vunpack_Vh(Q6_V_hi_W(vp_i16)); \ + HVX_Vector v_f32_0 = Q6_Vsf_equals_Vw(Q6_V_lo_W(vp_i32_01)); \ + HVX_Vector v_f32_1 = Q6_Vsf_equals_Vw(Q6_V_hi_W(vp_i32_01)); \ + HVX_Vector v_f32_2 = Q6_Vsf_equals_Vw(Q6_V_lo_W(vp_i32_23)); \ + HVX_Vector v_f32_3 = Q6_Vsf_equals_Vw(Q6_V_hi_W(vp_i32_23)); \ + v_acc0_qf = Q6_Vqf32_vadd_Vqf32Vqf32(v_acc0_qf, Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_0, da[0]), v_dw_qf)); \ + v_acc1_qf = Q6_Vqf32_vadd_Vqf32Vqf32(v_acc1_qf, Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_1, da[1]), v_dw_qf)); \ + v_acc2_qf = Q6_Vqf32_vadd_Vqf32Vqf32(v_acc2_qf, Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_2, da[2]), v_dw_qf)); \ + v_acc3_qf = Q6_Vqf32_vadd_Vqf32Vqf32(v_acc3_qf, Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_3, da[3]), v_dw_qf)); \ + tp += group_stride; \ + dw += 32; \ + da += 32; \ + } \ + *v_out0 = FIN_ROW(v_acc0_qf, 0, bias_row_base, bias_row_bytes, c); \ + if (full_quad || r + 1 < n_rows) { \ + *v_out1 = FIN_ROW(v_acc1_qf, 1, bias_row_base, bias_row_bytes, c); \ + } \ + if (full_quad || r + 2 < n_rows) { \ + *v_out2 = FIN_ROW(v_acc2_qf, 2, bias_row_base, bias_row_bytes, c); \ + } \ + if (full_quad || r + 3 < n_rows) { \ + *v_out3 = FIN_ROW(v_acc3_qf, 3, bias_row_base, bias_row_bytes, c); \ + } \ +} \ +static inline void w8a8_sm_eval_tile_quad_chunked_##SFX( \ + const uint8_t * restrict tile_base, \ + const float * restrict dw_base, \ + const float * restrict act_scales_blk_base, \ + size_t group_stride, \ + uint32_t mc_pad, \ + uint32_t n_groups, \ + size_t lane, \ + uint32_t (*da_ptr)[32], \ + HVX_Vector sign_80, \ + const uint8_t * restrict bias_row_base, \ + size_t c, \ + size_t bias_row_bytes, \ + uint32_t n_rows, \ + size_t r, \ + bool full_quad, \ + HVX_Vector * v_out0, \ + HVX_Vector * v_out1, \ + HVX_Vector * v_out2, \ + HVX_Vector * v_out3) { \ + (void) bias_row_base; \ + (void) bias_row_bytes; \ + const size_t c0 = c >> 5; \ + const uint8_t * tp = tile_base + c0 * 2 * HTP_MM_HMX_TILE_SIZE; \ + const float * dw = dw_base + c0 * (size_t) n_groups * 32; \ + HVX_Vector v_acc0_qf = Q6_V_vzero(); \ + HVX_Vector v_acc1_qf = Q6_V_vzero(); \ + HVX_Vector v_acc2_qf = Q6_V_vzero(); \ + HVX_Vector v_acc3_qf = Q6_V_vzero(); \ + for (uint32_t g_base = 0; g_base < n_groups; g_base += 16u) { \ + const uint32_t g_cnt = hex_smin(n_groups - g_base, 16u); \ + da_ptr = stage_act_scales_to_l1d(da_ptr, act_scales_blk_base + (size_t) g_base * mc_pad, mc_pad, g_cnt); \ + const uint32_t * da = &da_ptr[0][lane]; \ + for (uint32_t gi = 0; gi < g_cnt; ++gi) { \ + const HVX_Vector v_hi_s8 = Q6_V_vxor_VV(*(const HVX_Vector *) tp, sign_80); \ + const HVX_Vector v_lo_u8 = *(const HVX_Vector *) (tp + HTP_MM_HMX_TILE_SIZE); \ + const HVX_Vector v_dw_qf = hvx_vec_f32_to_qf32(*(const HVX_Vector *) dw); \ + HVX_VectorPair vp_i16 = Q6_W_vshuff_VVR(v_hi_s8, v_lo_u8, -1); \ + HVX_VectorPair vp_i32_01 = Q6_Ww_vunpack_Vh(Q6_V_lo_W(vp_i16)); \ + HVX_VectorPair vp_i32_23 = Q6_Ww_vunpack_Vh(Q6_V_hi_W(vp_i16)); \ + HVX_Vector v_f32_0 = Q6_Vsf_equals_Vw(Q6_V_lo_W(vp_i32_01)); \ + HVX_Vector v_f32_1 = Q6_Vsf_equals_Vw(Q6_V_hi_W(vp_i32_01)); \ + HVX_Vector v_f32_2 = Q6_Vsf_equals_Vw(Q6_V_lo_W(vp_i32_23)); \ + HVX_Vector v_f32_3 = Q6_Vsf_equals_Vw(Q6_V_hi_W(vp_i32_23)); \ + v_acc0_qf = Q6_Vqf32_vadd_Vqf32Vqf32(v_acc0_qf, Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_0, da[0]), v_dw_qf)); \ + v_acc1_qf = Q6_Vqf32_vadd_Vqf32Vqf32(v_acc1_qf, Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_1, da[1]), v_dw_qf)); \ + v_acc2_qf = Q6_Vqf32_vadd_Vqf32Vqf32(v_acc2_qf, Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_2, da[2]), v_dw_qf)); \ + v_acc3_qf = Q6_Vqf32_vadd_Vqf32Vqf32(v_acc3_qf, Q6_Vqf32_vmpy_Vqf32Vqf32(hvx_qf32_mul_sf_scalar(v_f32_3, da[3]), v_dw_qf)); \ + tp += group_stride; \ + dw += 32; \ + da += 32; \ + } \ + } \ + *v_out0 = FIN_ROW(v_acc0_qf, 0, bias_row_base, bias_row_bytes, c); \ + if (full_quad || r + 1 < n_rows) { \ + *v_out1 = FIN_ROW(v_acc1_qf, 1, bias_row_base, bias_row_bytes, c); \ + } \ + if (full_quad || r + 2 < n_rows) { \ + *v_out2 = FIN_ROW(v_acc2_qf, 2, bias_row_base, bias_row_bytes, c); \ + } \ + if (full_quad || r + 3 < n_rows) { \ + *v_out3 = FIN_ROW(v_acc3_qf, 3, bias_row_base, bias_row_bytes, c); \ + } \ +} + +DEFINE_W8A8_EVAL_TILE_QUAD(none, HMX_INT_FIN_ROW_NONE) +DEFINE_W8A8_EVAL_TILE_QUAD(f16, HMX_INT_FIN_ROW_F16) +DEFINE_W8A8_EVAL_TILE_QUAD(f32, HMX_INT_FIN_ROW_F32) + +#define HMX_INT_STORE_VEC_nt(ptr, val) hvx_vmem_store_nt((ptr), (val)) +#define HMX_INT_STORE_VEC_u(ptr, val) (hvx_vmemu((ptr)) = (val)) + +#define W8A8_COL_FULL_QUAD_1G_FP32(SFX, STORE_MODE) \ + for (size_t c = 0; c < limit_c_aligned; c += 32) { \ + HVX_Vector v0, v1, v2, v3; \ + w8a8_sm_eval_tile_quad_1g_##SFX(tile_base, dw_base, c, da, \ + bias_row0, bias_row_bytes, n_rows, r, true, &v0, &v1, &v2, &v3); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 0 * dst_stride, v0); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 1 * dst_stride, v1); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 2 * dst_stride, v2); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 3 * dst_stride, v3); \ + } + +#define W8A8_COL_STEP_1G_FP32(SFX, STORE_MODE) \ + if (r + 3 < n_rows) { \ + W8A8_COL_FULL_QUAD_1G_FP32(SFX, STORE_MODE) \ + } else { \ + for (size_t c = 0; c < limit_c_aligned; c += 32) { \ + HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_1g_##SFX(tile_base, dw_base, c, da, \ + bias_row0, bias_row_bytes, n_rows, r, false, &v0, &v1, &v2, &v3); \ + hvx_vmemu(out_row0 + c + 0 * dst_stride) = v0; \ + if (r + 1 < n_rows) hvx_vmemu(out_row0 + c + 1 * dst_stride) = v1; \ + if (r + 2 < n_rows) hvx_vmemu(out_row0 + c + 2 * dst_stride) = v2; \ + if (r + 3 < n_rows) hvx_vmemu(out_row0 + c + 3 * dst_stride) = v3; \ + } \ + } \ + if (limit_c_aligned < limit_c) { \ + const size_t c = limit_c_aligned; \ + const size_t valid_bytes = (limit_c - c) * sizeof(float); \ + HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_1g_##SFX(tile_base, dw_base, c, da, \ + bias_row0, bias_row_bytes, n_rows, r, false, &v0, &v1, &v2, &v3); \ + hvx_vec_store_u(out_row0 + c + 0 * dst_stride, valid_bytes, v0); \ + if (r + 1 < n_rows) hvx_vec_store_u(out_row0 + c + 1 * dst_stride, valid_bytes, v1); \ + if (r + 2 < n_rows) hvx_vec_store_u(out_row0 + c + 2 * dst_stride, valid_bytes, v2); \ + if (r + 3 < n_rows) hvx_vec_store_u(out_row0 + c + 3 * dst_stride, valid_bytes, v3); \ + } + +#define W8A8_COL_FULL_QUAD_2G_FP32(SFX, STORE_MODE) \ + for (size_t c = 0; c < limit_c_aligned; c += 32) { \ + HVX_Vector v0, v1, v2, v3; \ + w8a8_sm_eval_tile_quad_2g_##SFX(tile_base0, tile_base1, dw_base, c, da0, da1, \ + bias_row0, bias_row_bytes, n_rows, r, true, &v0, &v1, &v2, &v3); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 0 * dst_stride, v0); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 1 * dst_stride, v1); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 2 * dst_stride, v2); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 3 * dst_stride, v3); \ + } + +#define W8A8_COL_STEP_2G_FP32(SFX, STORE_MODE) \ + if (r + 3 < n_rows) { \ + W8A8_COL_FULL_QUAD_2G_FP32(SFX, STORE_MODE) \ + } else { \ + for (size_t c = 0; c < limit_c_aligned; c += 32) { \ + HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_2g_##SFX(tile_base0, tile_base1, dw_base, c, da0, da1, \ + bias_row0, bias_row_bytes, n_rows, r, false, &v0, &v1, &v2, &v3); \ + hvx_vmemu(out_row0 + c + 0 * dst_stride) = v0; \ + if (r + 1 < n_rows) hvx_vmemu(out_row0 + c + 1 * dst_stride) = v1; \ + if (r + 2 < n_rows) hvx_vmemu(out_row0 + c + 2 * dst_stride) = v2; \ + if (r + 3 < n_rows) hvx_vmemu(out_row0 + c + 3 * dst_stride) = v3; \ + } \ + } \ + if (limit_c_aligned < limit_c) { \ + const size_t c = limit_c_aligned; \ + const size_t valid_bytes = (limit_c - c) * sizeof(float); \ + HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_2g_##SFX(tile_base0, tile_base1, dw_base, c, da0, da1, \ + bias_row0, bias_row_bytes, n_rows, r, false, &v0, &v1, &v2, &v3); \ + hvx_vec_store_u(out_row0 + c + 0 * dst_stride, valid_bytes, v0); \ + if (r + 1 < n_rows) hvx_vec_store_u(out_row0 + c + 1 * dst_stride, valid_bytes, v1); \ + if (r + 2 < n_rows) hvx_vec_store_u(out_row0 + c + 2 * dst_stride, valid_bytes, v2); \ + if (r + 3 < n_rows) hvx_vec_store_u(out_row0 + c + 3 * dst_stride, valid_bytes, v3); \ + } + +#define W8A8_COL_FULL_QUAD_NG_FP32(SFX, STORE_MODE) \ + for (size_t c = 0; c < limit_c_aligned; c += 32) { \ + HVX_Vector v0, v1, v2, v3; \ + w8a8_sm_eval_tile_quad_ng_##SFX(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \ + bias_row_base, c, bias_row_bytes, n_rows, r, true, &v0, &v1, &v2, &v3); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 0 * dst_stride, v0); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 1 * dst_stride, v1); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 2 * dst_stride, v2); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 3 * dst_stride, v3); \ + } + +#define W8A8_COL_STEP_NG_FP32(SFX, STORE_MODE) \ + if (r + 3 < n_rows) { \ + W8A8_COL_FULL_QUAD_NG_FP32(SFX, STORE_MODE) \ + } else { \ + for (size_t c = 0; c < limit_c_aligned; c += 32) { \ + HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_ng_##SFX(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \ + bias_row_base, c, bias_row_bytes, n_rows, r, false, &v0, &v1, &v2, &v3); \ + hvx_vmemu(out_row_base + c + 0 * dst_stride) = v0; \ + if (r + 1 < n_rows) hvx_vmemu(out_row_base + c + 1 * dst_stride) = v1; \ + if (r + 2 < n_rows) hvx_vmemu(out_row_base + c + 2 * dst_stride) = v2; \ + if (r + 3 < n_rows) hvx_vmemu(out_row_base + c + 3 * dst_stride) = v3; \ + } \ + } \ + if (limit_c_aligned < limit_c) { \ + const size_t c = limit_c_aligned; \ + const size_t valid_bytes = (limit_c - c) * sizeof(float); \ + HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_ng_##SFX(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \ + bias_row_base, c, bias_row_bytes, n_rows, r, false, &v0, &v1, &v2, &v3); \ + hvx_vec_store_u(out_row_base + c + 0 * dst_stride, valid_bytes, v0); \ + if (r + 1 < n_rows) hvx_vec_store_u(out_row_base + c + 1 * dst_stride, valid_bytes, v1); \ + if (r + 2 < n_rows) hvx_vec_store_u(out_row_base + c + 2 * dst_stride, valid_bytes, v2); \ + if (r + 3 < n_rows) hvx_vec_store_u(out_row_base + c + 3 * dst_stride, valid_bytes, v3); \ + } + +#define W8A8_COL_FULL_QUAD_CHUNKED_FP32(SFX, STORE_MODE) \ + for (size_t c = 0; c < limit_c_aligned; c += 32) { \ + HVX_Vector v0, v1, v2, v3; \ + w8a8_sm_eval_tile_quad_chunked_##SFX(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \ + n_groups, lane, da_ptr, sign_80, \ + bias_row_base, c, bias_row_bytes, n_rows, r, true, &v0, &v1, &v2, &v3); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 0 * dst_stride, v0); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 1 * dst_stride, v1); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 2 * dst_stride, v2); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 3 * dst_stride, v3); \ + } + +#define W8A8_COL_STEP_CHUNKED_FP32(SFX, STORE_MODE) \ + if (r + 3 < n_rows) { \ + W8A8_COL_FULL_QUAD_CHUNKED_FP32(SFX, STORE_MODE) \ + } else { \ + for (size_t c = 0; c < limit_c_aligned; c += 32) { \ + HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_chunked_##SFX(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \ + n_groups, lane, da_ptr, sign_80, \ + bias_row_base, c, bias_row_bytes, n_rows, r, false, &v0, &v1, &v2, &v3); \ + hvx_vmemu(out_row_base + c + 0 * dst_stride) = v0; \ + if (r + 1 < n_rows) hvx_vmemu(out_row_base + c + 1 * dst_stride) = v1; \ + if (r + 2 < n_rows) hvx_vmemu(out_row_base + c + 2 * dst_stride) = v2; \ + if (r + 3 < n_rows) hvx_vmemu(out_row_base + c + 3 * dst_stride) = v3; \ + } \ + } \ + if (limit_c_aligned < limit_c) { \ + const size_t c = limit_c_aligned; \ + const size_t valid_bytes = (limit_c - c) * sizeof(float); \ + HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_chunked_##SFX(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \ + n_groups, lane, da_ptr, sign_80, \ + bias_row_base, c, bias_row_bytes, n_rows, r, false, &v0, &v1, &v2, &v3); \ + hvx_vec_store_u(out_row_base + c + 0 * dst_stride, valid_bytes, v0); \ + if (r + 1 < n_rows) hvx_vec_store_u(out_row_base + c + 1 * dst_stride, valid_bytes, v1); \ + if (r + 2 < n_rows) hvx_vec_store_u(out_row_base + c + 2 * dst_stride, valid_bytes, v2); \ + if (r + 3 < n_rows) hvx_vec_store_u(out_row_base + c + 3 * dst_stride, valid_bytes, v3); \ + } + +#define W8A8_COL_FULL_QUAD_1G_FP16(SFX, STORE_MODE) \ + for (size_t c = 0; c < limit_c_aligned; c += 64) { \ + HVX_Vector v0_lo, v1_lo, v2_lo, v3_lo; \ + HVX_Vector v0_hi, v1_hi, v2_hi, v3_hi; \ + w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c, da, NULL, 0, n_rows, r, true, \ + &v0_lo, &v1_lo, &v2_lo, &v3_lo); \ + w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c + 32, da, NULL, 0, n_rows, r, true, \ + &v0_hi, &v1_hi, &v2_hi, &v3_hi); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 0 * dst_stride, \ + HMX_INT_PACK_FP16_ROW_##SFX(v0_lo, v0_hi, bias_row0, bias_row_bytes, 0, c)); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 1 * dst_stride, \ + HMX_INT_PACK_FP16_ROW_##SFX(v1_lo, v1_hi, bias_row0, bias_row_bytes, 1, c)); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 2 * dst_stride, \ + HMX_INT_PACK_FP16_ROW_##SFX(v2_lo, v2_hi, bias_row0, bias_row_bytes, 2, c)); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 3 * dst_stride, \ + HMX_INT_PACK_FP16_ROW_##SFX(v3_lo, v3_hi, bias_row0, bias_row_bytes, 3, c)); \ + } + +#define W8A8_COL_STEP_1G_FP16(SFX, STORE_MODE) \ + (void) bias_row0; \ + (void) bias_row_bytes; \ + if (r + 3 < n_rows) { \ + W8A8_COL_FULL_QUAD_1G_FP16(SFX, STORE_MODE) \ + } else { \ + for (size_t c = 0; c < limit_c_aligned; c += 64) { \ + HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \ + HVX_Vector v0_hi, v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c, da, NULL, 0, n_rows, r, false, \ + &v0_lo, &v1_lo, &v2_lo, &v3_lo); \ + w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c + 32, da, NULL, 0, n_rows, r, false, \ + &v0_hi, &v1_hi, &v2_hi, &v3_hi); \ + hvx_vmemu(out_row0 + c + 0 * dst_stride) = \ + HMX_INT_PACK_FP16_ROW_##SFX(v0_lo, v0_hi, bias_row0, bias_row_bytes, 0, c); \ + if (r + 1 < n_rows) { \ + hvx_vmemu(out_row0 + c + 1 * dst_stride) = \ + HMX_INT_PACK_FP16_ROW_##SFX(v1_lo, v1_hi, bias_row0, bias_row_bytes, 1, c); \ + } \ + if (r + 2 < n_rows) { \ + hvx_vmemu(out_row0 + c + 2 * dst_stride) = \ + HMX_INT_PACK_FP16_ROW_##SFX(v2_lo, v2_hi, bias_row0, bias_row_bytes, 2, c); \ + } \ + if (r + 3 < n_rows) { \ + hvx_vmemu(out_row0 + c + 3 * dst_stride) = \ + HMX_INT_PACK_FP16_ROW_##SFX(v3_lo, v3_hi, bias_row0, bias_row_bytes, 3, c); \ + } \ + } \ + } \ + if (limit_c_aligned < limit_c) { \ + const size_t c = limit_c_aligned; \ + const size_t valid_c = limit_c - c; \ + const size_t valid_bytes = valid_c * sizeof(__fp16); \ + HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \ + HVX_Vector v0_hi = Q6_V_vzero(), v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c, da, NULL, 0, n_rows, r, false, \ + &v0_lo, &v1_lo, &v2_lo, &v3_lo); \ + if (valid_c > 32) { \ + w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c + 32, da, NULL, 0, n_rows, r, false, \ + &v0_hi, &v1_hi, &v2_hi, &v3_hi); \ + } \ + hvx_vec_store_u(out_row0 + c + 0 * dst_stride, valid_bytes, \ + HMX_INT_PACK_FP16_TAIL_##SFX(v0_lo, v0_hi, bias_row0, bias_row_bytes, 0, c, valid_c)); \ + if (r + 1 < n_rows) { \ + hvx_vec_store_u(out_row0 + c + 1 * dst_stride, valid_bytes, \ + HMX_INT_PACK_FP16_TAIL_##SFX(v1_lo, v1_hi, bias_row0, bias_row_bytes, 1, c, valid_c)); \ + } \ + if (r + 2 < n_rows) { \ + hvx_vec_store_u(out_row0 + c + 2 * dst_stride, valid_bytes, \ + HMX_INT_PACK_FP16_TAIL_##SFX(v2_lo, v2_hi, bias_row0, bias_row_bytes, 2, c, valid_c)); \ + } \ + if (r + 3 < n_rows) { \ + hvx_vec_store_u(out_row0 + c + 3 * dst_stride, valid_bytes, \ + HMX_INT_PACK_FP16_TAIL_##SFX(v3_lo, v3_hi, bias_row0, bias_row_bytes, 3, c, valid_c)); \ + } \ + } + +#define W8A8_COL_FULL_QUAD_2G_FP16(SFX, STORE_MODE) \ + for (size_t c = 0; c < limit_c_aligned; c += 64) { \ + HVX_Vector v0_lo, v1_lo, v2_lo, v3_lo; \ + HVX_Vector v0_hi, v1_hi, v2_hi, v3_hi; \ + w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c, da0, da1, NULL, 0, n_rows, r, true, \ + &v0_lo, &v1_lo, &v2_lo, &v3_lo); \ + w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c + 32, da0, da1, NULL, 0, n_rows, r, true,\ + &v0_hi, &v1_hi, &v2_hi, &v3_hi); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 0 * dst_stride, \ + HMX_INT_PACK_FP16_ROW_##SFX(v0_lo, v0_hi, bias_row0, bias_row_bytes, 0, c));\ + HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 1 * dst_stride, \ + HMX_INT_PACK_FP16_ROW_##SFX(v1_lo, v1_hi, bias_row0, bias_row_bytes, 1, c));\ + HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 2 * dst_stride, \ + HMX_INT_PACK_FP16_ROW_##SFX(v2_lo, v2_hi, bias_row0, bias_row_bytes, 2, c));\ + HMX_INT_STORE_VEC_##STORE_MODE(out_row0 + c + 3 * dst_stride, \ + HMX_INT_PACK_FP16_ROW_##SFX(v3_lo, v3_hi, bias_row0, bias_row_bytes, 3, c));\ + } + +#define W8A8_COL_STEP_2G_FP16(SFX, STORE_MODE) \ + (void) bias_row0; \ + (void) bias_row_bytes; \ + if (r + 3 < n_rows) { \ + W8A8_COL_FULL_QUAD_2G_FP16(SFX, STORE_MODE) \ + } else { \ + for (size_t c = 0; c < limit_c_aligned; c += 64) { \ + HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \ + HVX_Vector v0_hi, v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c, da0, da1, NULL, 0, n_rows, r, false,\ + &v0_lo, &v1_lo, &v2_lo, &v3_lo); \ + w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c + 32, da0, da1, NULL, 0, n_rows, r, \ + false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \ + hvx_vmemu(out_row0 + c + 0 * dst_stride) = \ + HMX_INT_PACK_FP16_ROW_##SFX(v0_lo, v0_hi, bias_row0, bias_row_bytes, 0, c); \ + if (r + 1 < n_rows) { \ + hvx_vmemu(out_row0 + c + 1 * dst_stride) = \ + HMX_INT_PACK_FP16_ROW_##SFX(v1_lo, v1_hi, bias_row0, bias_row_bytes, 1, c); \ + } \ + if (r + 2 < n_rows) { \ + hvx_vmemu(out_row0 + c + 2 * dst_stride) = \ + HMX_INT_PACK_FP16_ROW_##SFX(v2_lo, v2_hi, bias_row0, bias_row_bytes, 2, c); \ + } \ + if (r + 3 < n_rows) { \ + hvx_vmemu(out_row0 + c + 3 * dst_stride) = \ + HMX_INT_PACK_FP16_ROW_##SFX(v3_lo, v3_hi, bias_row0, bias_row_bytes, 3, c); \ + } \ + } \ + } \ + if (limit_c_aligned < limit_c) { \ + const size_t c = limit_c_aligned; \ + const size_t valid_c = limit_c - c; \ + const size_t valid_bytes = valid_c * sizeof(__fp16); \ + HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \ + HVX_Vector v0_hi = Q6_V_vzero(), v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c, da0, da1, NULL, 0, n_rows, r, false, \ + &v0_lo, &v1_lo, &v2_lo, &v3_lo); \ + if (valid_c > 32) { \ + w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c + 32, da0, da1, NULL, 0, n_rows, r, \ + false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \ + } \ + hvx_vec_store_u(out_row0 + c + 0 * dst_stride, valid_bytes, \ + HMX_INT_PACK_FP16_TAIL_##SFX(v0_lo, v0_hi, bias_row0, bias_row_bytes, 0, c, valid_c)); \ + if (r + 1 < n_rows) { \ + hvx_vec_store_u(out_row0 + c + 1 * dst_stride, valid_bytes, \ + HMX_INT_PACK_FP16_TAIL_##SFX(v1_lo, v1_hi, bias_row0, bias_row_bytes, 1, c, valid_c)); \ + } \ + if (r + 2 < n_rows) { \ + hvx_vec_store_u(out_row0 + c + 2 * dst_stride, valid_bytes, \ + HMX_INT_PACK_FP16_TAIL_##SFX(v2_lo, v2_hi, bias_row0, bias_row_bytes, 2, c, valid_c)); \ + } \ + if (r + 3 < n_rows) { \ + hvx_vec_store_u(out_row0 + c + 3 * dst_stride, valid_bytes, \ + HMX_INT_PACK_FP16_TAIL_##SFX(v3_lo, v3_hi, bias_row0, bias_row_bytes, 3, c, valid_c)); \ + } \ + } + +#define W8A8_COL_FULL_QUAD_NG_FP16(SFX, STORE_MODE) \ + for (size_t c = 0; c < limit_c_aligned; c += 64) { \ + HVX_Vector v0_lo, v1_lo, v2_lo, v3_lo; \ + HVX_Vector v0_hi, v1_hi, v2_hi, v3_hi; \ + w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \ + NULL, c, 0, n_rows, r, true, &v0_lo, &v1_lo, &v2_lo, &v3_lo); \ + w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \ + NULL, c + 32, 0, n_rows, r, true, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 0 * dst_stride, \ + HMX_INT_PACK_FP16_ROW_##SFX(v0_lo, v0_hi, bias_row_base, bias_row_bytes, 0, c));\ + HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 1 * dst_stride, \ + HMX_INT_PACK_FP16_ROW_##SFX(v1_lo, v1_hi, bias_row_base, bias_row_bytes, 1, c));\ + HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 2 * dst_stride, \ + HMX_INT_PACK_FP16_ROW_##SFX(v2_lo, v2_hi, bias_row_base, bias_row_bytes, 2, c));\ + HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 3 * dst_stride, \ + HMX_INT_PACK_FP16_ROW_##SFX(v3_lo, v3_hi, bias_row_base, bias_row_bytes, 3, c));\ + } + +#define W8A8_COL_STEP_NG_FP16(SFX, STORE_MODE) \ + (void) bias_row_base; \ + (void) bias_row_bytes; \ + if (r + 3 < n_rows) { \ + W8A8_COL_FULL_QUAD_NG_FP16(SFX, STORE_MODE) \ + } else { \ + for (size_t c = 0; c < limit_c_aligned; c += 64) { \ + HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \ + HVX_Vector v0_hi, v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \ + NULL, c, 0, n_rows, r, false, &v0_lo, &v1_lo, &v2_lo, &v3_lo); \ + w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \ + NULL, c + 32, 0, n_rows, r, false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \ + hvx_vmemu(out_row_base + c + 0 * dst_stride) = \ + HMX_INT_PACK_FP16_ROW_##SFX(v0_lo, v0_hi, bias_row_base, bias_row_bytes, 0, c); \ + if (r + 1 < n_rows) { \ + hvx_vmemu(out_row_base + c + 1 * dst_stride) = \ + HMX_INT_PACK_FP16_ROW_##SFX(v1_lo, v1_hi, bias_row_base, bias_row_bytes, 1, c); \ + } \ + if (r + 2 < n_rows) { \ + hvx_vmemu(out_row_base + c + 2 * dst_stride) = \ + HMX_INT_PACK_FP16_ROW_##SFX(v2_lo, v2_hi, bias_row_base, bias_row_bytes, 2, c); \ + } \ + if (r + 3 < n_rows) { \ + hvx_vmemu(out_row_base + c + 3 * dst_stride) = \ + HMX_INT_PACK_FP16_ROW_##SFX(v3_lo, v3_hi, bias_row_base, bias_row_bytes, 3, c); \ + } \ + } \ + } \ + if (limit_c_aligned < limit_c) { \ + const size_t c = limit_c_aligned; \ + const size_t valid_c = limit_c - c; \ + const size_t valid_bytes = valid_c * sizeof(__fp16); \ + HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \ + HVX_Vector v0_hi = Q6_V_vzero(), v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \ + NULL, c, 0, n_rows, r, false, &v0_lo, &v1_lo, &v2_lo, &v3_lo); \ + if (valid_c > 32) { \ + w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \ + NULL, c + 32, 0, n_rows, r, false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \ + } \ + hvx_vec_store_u(out_row_base + c + 0 * dst_stride, valid_bytes, \ + HMX_INT_PACK_FP16_TAIL_##SFX(v0_lo, v0_hi, bias_row_base, bias_row_bytes, 0, c, valid_c)); \ + if (r + 1 < n_rows) { \ + hvx_vec_store_u(out_row_base + c + 1 * dst_stride, valid_bytes, \ + HMX_INT_PACK_FP16_TAIL_##SFX(v1_lo, v1_hi, bias_row_base, bias_row_bytes, 1, c, valid_c)); \ + } \ + if (r + 2 < n_rows) { \ + hvx_vec_store_u(out_row_base + c + 2 * dst_stride, valid_bytes, \ + HMX_INT_PACK_FP16_TAIL_##SFX(v2_lo, v2_hi, bias_row_base, bias_row_bytes, 2, c, valid_c)); \ + } \ + if (r + 3 < n_rows) { \ + hvx_vec_store_u(out_row_base + c + 3 * dst_stride, valid_bytes, \ + HMX_INT_PACK_FP16_TAIL_##SFX(v3_lo, v3_hi, bias_row_base, bias_row_bytes, 3, c, valid_c)); \ + } \ + } + +#define W8A8_COL_FULL_QUAD_CHUNKED_FP16(SFX, STORE_MODE) \ + for (size_t c = 0; c < limit_c_aligned; c += 64) { \ + HVX_Vector v0_lo, v1_lo, v2_lo, v3_lo; \ + HVX_Vector v0_hi, v1_hi, v2_hi, v3_hi; \ + w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \ + n_groups, lane, da_ptr, sign_80, NULL, c, 0, n_rows, r, true, \ + &v0_lo, &v1_lo, &v2_lo, &v3_lo); \ + w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \ + n_groups, lane, da_ptr, sign_80, NULL, c + 32, 0, n_rows, r, true, \ + &v0_hi, &v1_hi, &v2_hi, &v3_hi); \ + HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 0 * dst_stride, \ + HMX_INT_PACK_FP16_ROW_##SFX(v0_lo, v0_hi, bias_row_base, bias_row_bytes, 0, c));\ + HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 1 * dst_stride, \ + HMX_INT_PACK_FP16_ROW_##SFX(v1_lo, v1_hi, bias_row_base, bias_row_bytes, 1, c));\ + HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 2 * dst_stride, \ + HMX_INT_PACK_FP16_ROW_##SFX(v2_lo, v2_hi, bias_row_base, bias_row_bytes, 2, c));\ + HMX_INT_STORE_VEC_##STORE_MODE(out_row_base + c + 3 * dst_stride, \ + HMX_INT_PACK_FP16_ROW_##SFX(v3_lo, v3_hi, bias_row_base, bias_row_bytes, 3, c));\ + } + +#define W8A8_COL_STEP_CHUNKED_FP16(SFX, STORE_MODE) \ + (void) bias_row_base; \ + (void) bias_row_bytes; \ + if (r + 3 < n_rows) { \ + W8A8_COL_FULL_QUAD_CHUNKED_FP16(SFX, STORE_MODE) \ + } else { \ + for (size_t c = 0; c < limit_c_aligned; c += 64) { \ + HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \ + HVX_Vector v0_hi, v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \ + n_groups, lane, da_ptr, sign_80, NULL, c, 0, n_rows, r, false, \ + &v0_lo, &v1_lo, &v2_lo, &v3_lo); \ + w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \ + n_groups, lane, da_ptr, sign_80, NULL, c + 32, 0, n_rows, r, false, \ + &v0_hi, &v1_hi, &v2_hi, &v3_hi); \ + hvx_vmemu(out_row_base + c + 0 * dst_stride) = \ + HMX_INT_PACK_FP16_ROW_##SFX(v0_lo, v0_hi, bias_row_base, bias_row_bytes, 0, c); \ + if (r + 1 < n_rows) { \ + hvx_vmemu(out_row_base + c + 1 * dst_stride) = \ + HMX_INT_PACK_FP16_ROW_##SFX(v1_lo, v1_hi, bias_row_base, bias_row_bytes, 1, c); \ + } \ + if (r + 2 < n_rows) { \ + hvx_vmemu(out_row_base + c + 2 * dst_stride) = \ + HMX_INT_PACK_FP16_ROW_##SFX(v2_lo, v2_hi, bias_row_base, bias_row_bytes, 2, c); \ + } \ + if (r + 3 < n_rows) { \ + hvx_vmemu(out_row_base + c + 3 * dst_stride) = \ + HMX_INT_PACK_FP16_ROW_##SFX(v3_lo, v3_hi, bias_row_base, bias_row_bytes, 3, c); \ + } \ + } \ + } \ + if (limit_c_aligned < limit_c) { \ + const size_t c = limit_c_aligned; \ + const size_t valid_c = limit_c - c; \ + const size_t valid_bytes = valid_c * sizeof(__fp16); \ + HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \ + HVX_Vector v0_hi = Q6_V_vzero(), v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \ + n_groups, lane, da_ptr, sign_80, NULL, c, 0, n_rows, r, false, \ + &v0_lo, &v1_lo, &v2_lo, &v3_lo); \ + if (valid_c > 32) { \ + w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \ + n_groups, lane, da_ptr, sign_80, NULL, c + 32, 0, n_rows, r, false, \ + &v0_hi, &v1_hi, &v2_hi, &v3_hi); \ + } \ + hvx_vec_store_u(out_row_base + c + 0 * dst_stride, valid_bytes, \ + HMX_INT_PACK_FP16_TAIL_##SFX(v0_lo, v0_hi, bias_row_base, bias_row_bytes, 0, c, valid_c)); \ + if (r + 1 < n_rows) { \ + hvx_vec_store_u(out_row_base + c + 1 * dst_stride, valid_bytes, \ + HMX_INT_PACK_FP16_TAIL_##SFX(v1_lo, v1_hi, bias_row_base, bias_row_bytes, 1, c, valid_c)); \ + } \ + if (r + 2 < n_rows) { \ + hvx_vec_store_u(out_row_base + c + 2 * dst_stride, valid_bytes, \ + HMX_INT_PACK_FP16_TAIL_##SFX(v2_lo, v2_hi, bias_row_base, bias_row_bytes, 2, c, valid_c)); \ + } \ + if (r + 3 < n_rows) { \ + hvx_vec_store_u(out_row_base + c + 3 * dst_stride, valid_bytes, \ + HMX_INT_PACK_FP16_TAIL_##SFX(v3_lo, v3_hi, bias_row_base, bias_row_bytes, 3, c, valid_c)); \ + } \ + } + +#define DEFINE_W8A8_COL_CHUNK_MODE(DST_SFX, DST_T, ALIGN_MASK, STEP_1G, STEP_2G, STEP_NG, STEP_CHUNKED, SFX, STORE_MODE) \ +static __attribute__((noinline)) void transfer_output_chunk_w8a8_sm_to_##DST_SFX##_col_chunk_1g_##SFX##_##STORE_MODE( \ + void * restrict dst_ptr, \ + const void * restrict bias, \ + const void * restrict vtcm_src_void, \ + const float * restrict vtcm_act_scales, \ + const float * restrict vtcm_weight_scales, \ + uint32_t start_row, \ + uint32_t n_rows, \ + uint32_t mc_pad, \ + uint32_t c_first, \ + uint32_t c_len, \ + uint32_t total_n_cols, \ + uint32_t n_groups, \ + uint32_t dst_stride, \ + uint32_t bias_stride, \ + uint32_t dst_cols, \ + size_t bias_elem_size) { \ + (void) mc_pad; \ + (void) n_groups; \ + DST_T * restrict dst = (DST_T *) dst_ptr; \ + const uint8_t * restrict vtcm_src = (const uint8_t *) vtcm_src_void; \ + const size_t total_col_tiles = hmx_ceil_div(total_n_cols, 32); \ + const size_t row_tile_stride = total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \ + const size_t c0_first = c_first / 32; \ + const size_t limit_c = hex_smin(c_len, dst_cols); \ + const size_t limit_c_aligned = (limit_c & (ALIGN_MASK)); \ + const size_t bias_row_bytes = (size_t) bias_stride * bias_elem_size; \ + uint32_t da_buf[1][32] __attribute__((aligned(128))); \ + for (size_t r_base = 0; r_base < n_rows; ) { \ + const size_t r_idx_base = start_row + r_base; \ + const size_t r_blk = r_idx_base >> 5; \ + const size_t r0 = r_idx_base >> 6; \ + const size_t r_step = hex_smin((size_t) n_rows - r_base, (size_t) (32u - (r_idx_base & 31u))); \ + const size_t r_end = r_base + r_step; \ + uint32_t (*da_ptr)[32] = stage_act_scales_to_l1d(da_buf, vtcm_act_scales + (r_blk << 5), 0, 1); \ + for (size_t r = r_base; r < r_end; r += 4) { \ + const size_t r_idx0 = start_row + r; \ + const size_t rg = (r_idx0 & 63u) >> 2; \ + const size_t lane = r_idx0 & 31u; \ + const uint32_t * da = &da_ptr[0][lane]; \ + const uint8_t * tile_base = vtcm_src + r0 * row_tile_stride + c0_first * 2 * HTP_MM_HMX_TILE_SIZE + rg * 128; \ + const float * dw_base = vtcm_weight_scales + c0_first * 32; \ + DST_T * out_row0 = dst + r * dst_stride; \ + const uint8_t * bias_row0 = HMX_INT_BIAS_ROW_##SFX(bias, r * bias_row_bytes); \ + STEP_1G(SFX, STORE_MODE) \ + } \ + r_base = r_end; \ + } \ +} \ +static __attribute__((noinline)) void transfer_output_chunk_w8a8_sm_to_##DST_SFX##_col_chunk_2g_##SFX##_##STORE_MODE( \ + void * restrict dst_ptr, \ + const void * restrict bias, \ + const void * restrict vtcm_src_void, \ + const float * restrict vtcm_act_scales, \ + const float * restrict vtcm_weight_scales, \ + uint32_t start_row, \ + uint32_t n_rows, \ + uint32_t mc_pad, \ + uint32_t c_first, \ + uint32_t c_len, \ + uint32_t total_n_cols, \ + uint32_t n_groups, \ + uint32_t dst_stride, \ + uint32_t bias_stride, \ + uint32_t dst_cols, \ + size_t bias_elem_size) { \ + (void) n_groups; \ + DST_T * restrict dst = (DST_T *) dst_ptr; \ + const uint8_t * restrict vtcm_src = (const uint8_t *) vtcm_src_void; \ + const size_t total_col_tiles = hmx_ceil_div(total_n_cols, 32); \ + const size_t n_row_tiles_64 = mc_pad / 64; \ + const size_t group_stride = n_row_tiles_64 * total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \ + const size_t row_tile_stride = total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \ + const size_t c0_first = c_first / 32; \ + const size_t limit_c = hex_smin(c_len, dst_cols); \ + const size_t limit_c_aligned = (limit_c & (ALIGN_MASK)); \ + const size_t bias_row_bytes = (size_t) bias_stride * bias_elem_size; \ + uint32_t da_buf[2][32] __attribute__((aligned(128))); \ + for (size_t r_base = 0; r_base < n_rows; ) { \ + const size_t r_idx_base = start_row + r_base; \ + const size_t r_blk = r_idx_base >> 5; \ + const size_t r0 = r_idx_base >> 6; \ + const size_t r_step = hex_smin((size_t) n_rows - r_base, (size_t) (32u - (r_idx_base & 31u))); \ + const size_t r_end = r_base + r_step; \ + uint32_t (*da_ptr)[32] = stage_act_scales_to_l1d(da_buf, vtcm_act_scales + (r_blk << 5), mc_pad, 2); \ + for (size_t r = r_base; r < r_end; r += 4) { \ + const size_t r_idx0 = start_row + r; \ + const size_t rg = (r_idx0 & 63u) >> 2; \ + const size_t lane = r_idx0 & 31u; \ + const uint32_t * da0 = &da_ptr[0][lane]; \ + const uint32_t * da1 = &da_ptr[1][lane]; \ + const uint8_t * tile_base0 = vtcm_src + r0 * row_tile_stride + c0_first * 2 * HTP_MM_HMX_TILE_SIZE + rg * 128; \ + const uint8_t * tile_base1 = tile_base0 + group_stride; \ + const float * dw_base = vtcm_weight_scales + c0_first * 64; \ + DST_T * out_row0 = dst + r * dst_stride; \ + const uint8_t * bias_row0 = HMX_INT_BIAS_ROW_##SFX(bias, r * bias_row_bytes); \ + STEP_2G(SFX, STORE_MODE) \ + } \ + r_base = r_end; \ + } \ +} \ +static __attribute__((noinline)) void transfer_output_chunk_w8a8_sm_to_##DST_SFX##_col_chunk_ng_##SFX##_##STORE_MODE( \ + void * restrict dst_ptr, \ + const void * restrict bias, \ + const void * restrict vtcm_src_void, \ + const float * restrict vtcm_act_scales, \ + const float * restrict vtcm_weight_scales, \ + uint32_t start_row, \ + uint32_t n_rows, \ + uint32_t mc_pad, \ + uint32_t c_first, \ + uint32_t c_len, \ + uint32_t total_n_cols, \ + uint32_t n_groups, \ + uint32_t dst_stride, \ + uint32_t bias_stride, \ + uint32_t dst_cols, \ + size_t bias_elem_size) { \ + DST_T * restrict dst = (DST_T *) dst_ptr; \ + const uint8_t * restrict vtcm_src = (const uint8_t *) vtcm_src_void; \ + const size_t total_col_tiles = hmx_ceil_div(total_n_cols, 32); \ + const size_t n_row_tiles_64 = mc_pad / 64; \ + const size_t group_stride = n_row_tiles_64 * total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \ + const size_t row_tile_stride = total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \ + const size_t c0_first = c_first / 32; \ + const HVX_Vector sign_80 = Q6_Vb_vsplat_R(0x80); \ + const size_t limit_c = hex_smin(c_len, dst_cols); \ + const size_t limit_c_aligned = (limit_c & (ALIGN_MASK)); \ + const size_t bias_row_bytes = (size_t) bias_stride * bias_elem_size; \ + const float * dw_base = vtcm_weight_scales + c0_first * (size_t) n_groups * 32; \ + uint32_t da_buf[16][32] __attribute__((aligned(128))); \ + for (size_t r_base = 0; r_base < n_rows; ) { \ + const size_t r_idx_base = start_row + r_base; \ + const size_t r_blk = r_idx_base >> 5; \ + const size_t r0 = r_idx_base >> 6; \ + const size_t r_step = hex_smin((size_t) n_rows - r_base, (size_t) (32u - (r_idx_base & 31u))); \ + const size_t r_end = r_base + r_step; \ + uint32_t (*da_ptr)[32] = stage_act_scales_to_l1d(da_buf, vtcm_act_scales + (r_blk << 5), mc_pad, n_groups); \ + for (size_t r = r_base; r < r_end; r += 4) { \ + const size_t r_idx0 = start_row + r; \ + const size_t rg = (r_idx0 & 63u) >> 2; \ + const size_t lane = r_idx0 & 31u; \ + const uint8_t * tile_base = vtcm_src + r0 * row_tile_stride + c0_first * 2 * HTP_MM_HMX_TILE_SIZE + \ + rg * 128; \ + const uint32_t * da_quad_base = &da_ptr[0][lane]; \ + DST_T * out_row_base = dst + r * dst_stride; \ + const uint8_t * bias_row_base = HMX_INT_BIAS_ROW_##SFX(bias, r * bias_row_bytes); \ + STEP_NG(SFX, STORE_MODE) \ + } \ + r_base = r_end; \ + } \ +} \ +static __attribute__((noinline)) void transfer_output_chunk_w8a8_sm_to_##DST_SFX##_col_chunk_chunked_##SFX##_##STORE_MODE( \ + void * restrict dst_ptr, \ + const void * restrict bias, \ + const void * restrict vtcm_src_void, \ + const float * restrict vtcm_act_scales, \ + const float * restrict vtcm_weight_scales, \ + uint32_t start_row, \ + uint32_t n_rows, \ + uint32_t mc_pad, \ + uint32_t c_first, \ + uint32_t c_len, \ + uint32_t total_n_cols, \ + uint32_t n_groups, \ + uint32_t dst_stride, \ + uint32_t bias_stride, \ + uint32_t dst_cols, \ + size_t bias_elem_size) { \ + DST_T * restrict dst = (DST_T *) dst_ptr; \ + const uint8_t * restrict vtcm_src = (const uint8_t *) vtcm_src_void; \ + const size_t total_col_tiles = hmx_ceil_div(total_n_cols, 32); \ + const size_t n_row_tiles_64 = mc_pad / 64; \ + const size_t group_stride = n_row_tiles_64 * total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \ + const size_t row_tile_stride = total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \ + const size_t c0_first = c_first / 32; \ + const HVX_Vector sign_80 = Q6_Vb_vsplat_R(0x80); \ + const size_t limit_c = hex_smin(c_len, dst_cols); \ + const size_t limit_c_aligned = (limit_c & (ALIGN_MASK)); \ + const size_t bias_row_bytes = (size_t) bias_stride * bias_elem_size; \ + const float * dw_base = vtcm_weight_scales + c0_first * (size_t) n_groups * 32; \ + uint32_t da_buf[16][32] __attribute__((aligned(128))); \ + uint32_t (*da_ptr)[32] = da_buf; \ + for (size_t r_base = 0; r_base < n_rows; ) { \ + const size_t r_idx_base = start_row + r_base; \ + const size_t r_blk = r_idx_base >> 5; \ + const size_t r0 = r_idx_base >> 6; \ + const size_t r_step = hex_smin((size_t) n_rows - r_base, (size_t) (32u - (r_idx_base & 31u))); \ + const size_t r_end = r_base + r_step; \ + const float * act_scales_blk_base = vtcm_act_scales + (r_blk << 5); \ + for (size_t r = r_base; r < r_end; r += 4) { \ + const size_t r_idx0 = start_row + r; \ + const size_t rg = (r_idx0 & 63u) >> 2; \ + const size_t lane = r_idx0 & 31u; \ + const uint8_t * tile_base = vtcm_src + r0 * row_tile_stride + c0_first * 2 * HTP_MM_HMX_TILE_SIZE + rg * 128; \ + DST_T * out_row_base = dst + r * dst_stride; \ + const uint8_t * bias_row_base = HMX_INT_BIAS_ROW_##SFX(bias, r * bias_row_bytes); \ + STEP_CHUNKED(SFX, STORE_MODE) \ + } \ + r_base = r_end; \ + } \ +} + +#define DEFINE_W8A8_COL_CHUNK(DST_SFX, DST_T, ALIGN_MASK, STEP_1G, STEP_2G, STEP_NG, STEP_CHUNKED, SFX) \ + DEFINE_W8A8_COL_CHUNK_MODE(DST_SFX, DST_T, ALIGN_MASK, STEP_1G, STEP_2G, STEP_NG, STEP_CHUNKED, SFX, nt) \ + DEFINE_W8A8_COL_CHUNK_MODE(DST_SFX, DST_T, ALIGN_MASK, STEP_1G, STEP_2G, STEP_NG, STEP_CHUNKED, SFX, u) + +DEFINE_W8A8_COL_CHUNK(fp32, float, ~31u, W8A8_COL_STEP_1G_FP32, W8A8_COL_STEP_2G_FP32, W8A8_COL_STEP_NG_FP32, W8A8_COL_STEP_CHUNKED_FP32, none) +DEFINE_W8A8_COL_CHUNK(fp32, float, ~31u, W8A8_COL_STEP_1G_FP32, W8A8_COL_STEP_2G_FP32, W8A8_COL_STEP_NG_FP32, W8A8_COL_STEP_CHUNKED_FP32, f16) +DEFINE_W8A8_COL_CHUNK(fp32, float, ~31u, W8A8_COL_STEP_1G_FP32, W8A8_COL_STEP_2G_FP32, W8A8_COL_STEP_NG_FP32, W8A8_COL_STEP_CHUNKED_FP32, f32) +DEFINE_W8A8_COL_CHUNK(fp16, __fp16, ~63u, W8A8_COL_STEP_1G_FP16, W8A8_COL_STEP_2G_FP16, W8A8_COL_STEP_NG_FP16, W8A8_COL_STEP_CHUNKED_FP16, none) +DEFINE_W8A8_COL_CHUNK(fp16, __fp16, ~63u, W8A8_COL_STEP_1G_FP16, W8A8_COL_STEP_2G_FP16, W8A8_COL_STEP_NG_FP16, W8A8_COL_STEP_CHUNKED_FP16, f16) +DEFINE_W8A8_COL_CHUNK(fp16, __fp16, ~63u, W8A8_COL_STEP_1G_FP16, W8A8_COL_STEP_2G_FP16, W8A8_COL_STEP_NG_FP16, W8A8_COL_STEP_CHUNKED_FP16, f32) + +#define W8A8_SCAT_STEP_1G_FP32 \ + for (size_t c = 0; c < limit_c_aligned; c += 32) { \ + HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c, da, \ + NULL, 0, n_rows, r, false, &v0, &v1, &v2, &v3); \ + hvx_vmemu(out_row0 + c) = v0; \ + if (out_row1) hvx_vmemu(out_row1 + c) = v1; \ + if (out_row2) hvx_vmemu(out_row2 + c) = v2; \ + if (out_row3) hvx_vmemu(out_row3 + c) = v3; \ + } \ + if (limit_c_aligned < limit_c) { \ + const size_t c = limit_c_aligned; \ + const size_t valid_bytes = (limit_c - c) * sizeof(float); \ + HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c, da, \ + NULL, 0, n_rows, r, false, &v0, &v1, &v2, &v3); \ + hvx_vec_store_u(out_row0 + c, valid_bytes, v0); \ + if (out_row1) hvx_vec_store_u(out_row1 + c, valid_bytes, v1); \ + if (out_row2) hvx_vec_store_u(out_row2 + c, valid_bytes, v2); \ + if (out_row3) hvx_vec_store_u(out_row3 + c, valid_bytes, v3); \ + } + +#define W8A8_SCAT_STEP_2G_FP32 \ + for (size_t c = 0; c < limit_c_aligned; c += 32) { \ + HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c, da0, da1, \ + NULL, 0, n_rows, r, false, &v0, &v1, &v2, &v3); \ + hvx_vmemu(out_row0 + c) = v0; \ + if (out_row1) hvx_vmemu(out_row1 + c) = v1; \ + if (out_row2) hvx_vmemu(out_row2 + c) = v2; \ + if (out_row3) hvx_vmemu(out_row3 + c) = v3; \ + } \ + if (limit_c_aligned < limit_c) { \ + const size_t c = limit_c_aligned; \ + const size_t valid_bytes = (limit_c - c) * sizeof(float); \ + HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c, da0, da1, \ + NULL, 0, n_rows, r, false, &v0, &v1, &v2, &v3); \ + hvx_vec_store_u(out_row0 + c, valid_bytes, v0); \ + if (out_row1) hvx_vec_store_u(out_row1 + c, valid_bytes, v1); \ + if (out_row2) hvx_vec_store_u(out_row2 + c, valid_bytes, v2); \ + if (out_row3) hvx_vec_store_u(out_row3 + c, valid_bytes, v3); \ + } + +#define W8A8_SCAT_STEP_NG_FP32 \ + for (size_t c = 0; c < limit_c_aligned; c += 32) { \ + HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, \ + sign_80, NULL, c, 0, n_rows, r, false, &v0, &v1, &v2, &v3); \ + hvx_vmemu(out_row0 + c) = v0; \ + if (out_row1) hvx_vmemu(out_row1 + c) = v1; \ + if (out_row2) hvx_vmemu(out_row2 + c) = v2; \ + if (out_row3) hvx_vmemu(out_row3 + c) = v3; \ + } \ + if (limit_c_aligned < limit_c) { \ + const size_t c = limit_c_aligned; \ + const size_t valid_bytes = (limit_c - c) * sizeof(float); \ + HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, \ + sign_80, NULL, c, 0, n_rows, r, false, &v0, &v1, &v2, &v3); \ + hvx_vec_store_u(out_row0 + c, valid_bytes, v0); \ + if (out_row1) hvx_vec_store_u(out_row1 + c, valid_bytes, v1); \ + if (out_row2) hvx_vec_store_u(out_row2 + c, valid_bytes, v2); \ + if (out_row3) hvx_vec_store_u(out_row3 + c, valid_bytes, v3); \ + } + +#define W8A8_SCAT_STEP_CHUNKED_FP32 \ + for (size_t c = 0; c < limit_c_aligned; c += 32) { \ + HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \ + n_groups, lane, da_ptr, sign_80, NULL, c, 0, n_rows, r, false, \ + &v0, &v1, &v2, &v3); \ + hvx_vmemu(out_row0 + c) = v0; \ + if (out_row1) hvx_vmemu(out_row1 + c) = v1; \ + if (out_row2) hvx_vmemu(out_row2 + c) = v2; \ + if (out_row3) hvx_vmemu(out_row3 + c) = v3; \ + } \ + if (limit_c_aligned < limit_c) { \ + const size_t c = limit_c_aligned; \ + const size_t valid_bytes = (limit_c - c) * sizeof(float); \ + HVX_Vector v0, v1 = Q6_V_vzero(), v2 = Q6_V_vzero(), v3 = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \ + n_groups, lane, da_ptr, sign_80, NULL, c, 0, n_rows, r, false, \ + &v0, &v1, &v2, &v3); \ + hvx_vec_store_u(out_row0 + c, valid_bytes, v0); \ + if (out_row1) hvx_vec_store_u(out_row1 + c, valid_bytes, v1); \ + if (out_row2) hvx_vec_store_u(out_row2 + c, valid_bytes, v2); \ + if (out_row3) hvx_vec_store_u(out_row3 + c, valid_bytes, v3); \ + } + +#define W8A8_SCAT_STEP_1G_FP16 \ + for (size_t c = 0; c < limit_c_aligned; c += 64) { \ + HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \ + HVX_Vector v0_hi, v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c, da, \ + NULL, 0, n_rows, r, false, &v0_lo, &v1_lo, &v2_lo, &v3_lo); \ + w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c + 32, da, \ + NULL, 0, n_rows, r, false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \ + hvx_vmemu(out_row0 + c) = hmx_pack_f32_to_f16_clamped(v0_lo, v0_hi); \ + if (out_row1) hvx_vmemu(out_row1 + c) = hmx_pack_f32_to_f16_clamped(v1_lo, v1_hi); \ + if (out_row2) hvx_vmemu(out_row2 + c) = hmx_pack_f32_to_f16_clamped(v2_lo, v2_hi); \ + if (out_row3) hvx_vmemu(out_row3 + c) = hmx_pack_f32_to_f16_clamped(v3_lo, v3_hi); \ + } \ + if (limit_c_aligned < limit_c) { \ + const size_t c = limit_c_aligned; \ + const size_t valid_c = limit_c - c; \ + const size_t valid_bytes = valid_c * sizeof(__fp16); \ + HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \ + HVX_Vector v0_hi = Q6_V_vzero(), v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c, da, \ + NULL, 0, n_rows, r, false, &v0_lo, &v1_lo, &v2_lo, &v3_lo); \ + if (valid_c > 32) { \ + w8a8_sm_eval_tile_quad_1g_none(tile_base, dw_base, c + 32, da, \ + NULL, 0, n_rows, r, false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \ + } \ + hvx_vec_store_u(out_row0 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v0_lo, v0_hi)); \ + if (out_row1) hvx_vec_store_u(out_row1 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v1_lo, v1_hi)); \ + if (out_row2) hvx_vec_store_u(out_row2 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v2_lo, v2_hi)); \ + if (out_row3) hvx_vec_store_u(out_row3 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v3_lo, v3_hi)); \ + } + +#define W8A8_SCAT_STEP_2G_FP16 \ + for (size_t c = 0; c < limit_c_aligned; c += 64) { \ + HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \ + HVX_Vector v0_hi, v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c, da0, da1, \ + NULL, 0, n_rows, r, false, &v0_lo, &v1_lo, &v2_lo, &v3_lo); \ + w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c + 32, da0, da1, \ + NULL, 0, n_rows, r, false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \ + hvx_vmemu(out_row0 + c) = hmx_pack_f32_to_f16_clamped(v0_lo, v0_hi); \ + if (out_row1) hvx_vmemu(out_row1 + c) = hmx_pack_f32_to_f16_clamped(v1_lo, v1_hi); \ + if (out_row2) hvx_vmemu(out_row2 + c) = hmx_pack_f32_to_f16_clamped(v2_lo, v2_hi); \ + if (out_row3) hvx_vmemu(out_row3 + c) = hmx_pack_f32_to_f16_clamped(v3_lo, v3_hi); \ + } \ + if (limit_c_aligned < limit_c) { \ + const size_t c = limit_c_aligned; \ + const size_t valid_c = limit_c - c; \ + const size_t valid_bytes = valid_c * sizeof(__fp16); \ + HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \ + HVX_Vector v0_hi = Q6_V_vzero(), v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c, da0, da1, \ + NULL, 0, n_rows, r, false, &v0_lo, &v1_lo, &v2_lo, &v3_lo); \ + if (valid_c > 32) { \ + w8a8_sm_eval_tile_quad_2g_none(tile_base0, tile_base1, dw_base, c + 32, da0, da1, \ + NULL, 0, n_rows, r, false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \ + } \ + hvx_vec_store_u(out_row0 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v0_lo, v0_hi)); \ + if (out_row1) hvx_vec_store_u(out_row1 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v1_lo, v1_hi)); \ + if (out_row2) hvx_vec_store_u(out_row2 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v2_lo, v2_hi)); \ + if (out_row3) hvx_vec_store_u(out_row3 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v3_lo, v3_hi)); \ + } + +#define W8A8_SCAT_STEP_NG_FP16 \ + for (size_t c = 0; c < limit_c_aligned; c += 64) { \ + HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \ + HVX_Vector v0_hi, v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \ + NULL, c, 0, n_rows, r, false, &v0_lo, &v1_lo, &v2_lo, &v3_lo); \ + w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \ + NULL, c + 32, 0, n_rows, r, false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \ + hvx_vmemu(out_row0 + c) = hmx_pack_f32_to_f16_clamped(v0_lo, v0_hi); \ + if (out_row1) hvx_vmemu(out_row1 + c) = hmx_pack_f32_to_f16_clamped(v1_lo, v1_hi); \ + if (out_row2) hvx_vmemu(out_row2 + c) = hmx_pack_f32_to_f16_clamped(v2_lo, v2_hi); \ + if (out_row3) hvx_vmemu(out_row3 + c) = hmx_pack_f32_to_f16_clamped(v3_lo, v3_hi); \ + } \ + if (limit_c_aligned < limit_c) { \ + const size_t c = limit_c_aligned; \ + const size_t valid_c = limit_c - c; \ + const size_t valid_bytes = valid_c * sizeof(__fp16); \ + HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \ + HVX_Vector v0_hi = Q6_V_vzero(), v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \ + NULL, c, 0, n_rows, r, false, &v0_lo, &v1_lo, &v2_lo, &v3_lo); \ + if (valid_c > 32) { \ + w8a8_sm_eval_tile_quad_ng_none(tile_base, dw_base, group_stride, n_groups, da_quad_base, sign_80, \ + NULL, c + 32, 0, n_rows, r, false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \ + } \ + hvx_vec_store_u(out_row0 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v0_lo, v0_hi)); \ + if (out_row1) hvx_vec_store_u(out_row1 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v1_lo, v1_hi)); \ + if (out_row2) hvx_vec_store_u(out_row2 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v2_lo, v2_hi)); \ + if (out_row3) hvx_vec_store_u(out_row3 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v3_lo, v3_hi)); \ + } + +#define W8A8_SCAT_STEP_CHUNKED_FP16 \ + for (size_t c = 0; c < limit_c_aligned; c += 64) { \ + HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \ + HVX_Vector v0_hi, v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \ + n_groups, lane, da_ptr, sign_80, NULL, c, 0, n_rows, r, false, \ + &v0_lo, &v1_lo, &v2_lo, &v3_lo); \ + w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \ + n_groups, lane, da_ptr, sign_80, NULL, c + 32, 0, n_rows, r, false, \ + &v0_hi, &v1_hi, &v2_hi, &v3_hi); \ + hvx_vmemu(out_row0 + c) = hmx_pack_f32_to_f16_clamped(v0_lo, v0_hi); \ + if (out_row1) hvx_vmemu(out_row1 + c) = hmx_pack_f32_to_f16_clamped(v1_lo, v1_hi); \ + if (out_row2) hvx_vmemu(out_row2 + c) = hmx_pack_f32_to_f16_clamped(v2_lo, v2_hi); \ + if (out_row3) hvx_vmemu(out_row3 + c) = hmx_pack_f32_to_f16_clamped(v3_lo, v3_hi); \ + } \ + if (limit_c_aligned < limit_c) { \ + const size_t c = limit_c_aligned; \ + const size_t valid_c = limit_c - c; \ + const size_t valid_bytes = valid_c * sizeof(__fp16); \ + HVX_Vector v0_lo, v1_lo = Q6_V_vzero(), v2_lo = Q6_V_vzero(), v3_lo = Q6_V_vzero(); \ + HVX_Vector v0_hi = Q6_V_vzero(), v1_hi = Q6_V_vzero(), v2_hi = Q6_V_vzero(), v3_hi = Q6_V_vzero(); \ + w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \ + n_groups, lane, da_ptr, sign_80, NULL, c, 0, n_rows, r, false, \ + &v0_lo, &v1_lo, &v2_lo, &v3_lo); \ + if (valid_c > 32) { \ + w8a8_sm_eval_tile_quad_chunked_none(tile_base, dw_base, act_scales_blk_base, group_stride, mc_pad, \ + n_groups, lane, da_ptr, sign_80, NULL, c + 32, 0, n_rows, r, \ + false, &v0_hi, &v1_hi, &v2_hi, &v3_hi); \ + } \ + hvx_vec_store_u(out_row0 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v0_lo, v0_hi)); \ + if (out_row1) hvx_vec_store_u(out_row1 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v1_lo, v1_hi)); \ + if (out_row2) hvx_vec_store_u(out_row2 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v2_lo, v2_hi)); \ + if (out_row3) hvx_vec_store_u(out_row3 + c, valid_bytes, hmx_pack_f32_to_f16_clamped(v3_lo, v3_hi)); \ + } + +typedef void (*int_output_col_chunk_fn_t)( + void * restrict dst, + const void * restrict bias, + const void * restrict vtcm_src, + const float * restrict vtcm_act_scales, + const float * restrict vtcm_weight_scales, + uint32_t start_row, + uint32_t n_rows, + uint32_t mc_pad, + uint32_t c_first, + uint32_t c_len, + uint32_t total_n_cols, + uint32_t n_groups, + uint32_t dst_stride, + uint32_t bias_stride, + uint32_t dst_cols, + size_t bias_elem_size); + +#define HMX_SELECT_INT_COL_FN(DST_SFX, GRP_SFX, bias, bias_f16, dst_aligned_nt) \ + ((dst_aligned_nt) \ + ? (!(bias) ? transfer_output_chunk_w8a8_sm_to_##DST_SFX##_col_chunk_##GRP_SFX##_none_nt \ + : ((bias_f16) ? transfer_output_chunk_w8a8_sm_to_##DST_SFX##_col_chunk_##GRP_SFX##_f16_nt \ + : transfer_output_chunk_w8a8_sm_to_##DST_SFX##_col_chunk_##GRP_SFX##_f32_nt)) \ + : (!(bias) ? transfer_output_chunk_w8a8_sm_to_##DST_SFX##_col_chunk_##GRP_SFX##_none_u \ + : ((bias_f16) ? transfer_output_chunk_w8a8_sm_to_##DST_SFX##_col_chunk_##GRP_SFX##_f16_u \ + : transfer_output_chunk_w8a8_sm_to_##DST_SFX##_col_chunk_##GRP_SFX##_f32_u))) + +static inline int_output_col_chunk_fn_t resolve_int_output_col_chunk_fn( + uint32_t n_groups, + size_t dst_elem_size, + const void * bias, + size_t bias_elem_size, + bool dst_aligned_nt) { + const bool dst_f16 = (dst_elem_size == sizeof(__fp16)); + const bool bias_f16 = (bias_elem_size == sizeof(__fp16)); + if (dst_f16) { + if (n_groups <= 1u) { + return HMX_SELECT_INT_COL_FN(fp16, 1g, bias, bias_f16, dst_aligned_nt); + } + if (n_groups == 2u) { + return HMX_SELECT_INT_COL_FN(fp16, 2g, bias, bias_f16, dst_aligned_nt); + } + if (n_groups <= 16u) { + return HMX_SELECT_INT_COL_FN(fp16, ng, bias, bias_f16, dst_aligned_nt); + } + return HMX_SELECT_INT_COL_FN(fp16, chunked, bias, bias_f16, dst_aligned_nt); + } + if (n_groups <= 1u) { + return HMX_SELECT_INT_COL_FN(fp32, 1g, bias, bias_f16, dst_aligned_nt); + } + if (n_groups == 2u) { + return HMX_SELECT_INT_COL_FN(fp32, 2g, bias, bias_f16, dst_aligned_nt); + } + if (n_groups <= 16u) { + return HMX_SELECT_INT_COL_FN(fp32, ng, bias, bias_f16, dst_aligned_nt); + } + return HMX_SELECT_INT_COL_FN(fp32, chunked, bias, bias_f16, dst_aligned_nt); +} + +// --- Fused W8A8 GLU Epilogue (paired gate/up -> f(gate) * up) --- + +typedef struct { + const float * act_scales_blk_base; + uint32_t (*da_ptr)[32]; + size_t group_stride; + uint32_t mc_pad; + uint32_t n_groups; + uint32_t lane; +} w8a8_sm_chunked_eval_args_t; + +// Thin noinline wrappers around w8a8_sm_eval_tile_quad_*_none to bound live ranges in GLU loops. +static __attribute__((noinline)) void w8a8_sm_glu_eval_1g_quad( + const uint8_t * restrict tp, + const float * restrict dwp, + const uint32_t * restrict da0, + HVX_Vector * restrict out) { + w8a8_sm_eval_tile_quad_1g_none(tp, dwp, 0, da0, NULL, 0, 4, 0, true, &out[0], &out[1], &out[2], &out[3]); +} + +static __attribute__((noinline)) void w8a8_sm_glu_eval_1g_pair_hf( + const uint8_t * restrict tp, + const float * restrict dwp, + const uint32_t * restrict da0, + HVX_Vector * restrict out_hf) { + HVX_Vector lo0, lo1, lo2, lo3, hi0, hi1, hi2, hi3; + w8a8_sm_eval_tile_quad_1g_none(tp, dwp, 0, da0, NULL, 0, 4, 0, true, &lo0, &lo1, &lo2, &lo3); + w8a8_sm_eval_tile_quad_1g_none(tp, dwp, 32, da0, NULL, 0, 4, 0, true, &hi0, &hi1, &hi2, &hi3); + out_hf[0] = hmx_pack_f32_to_f16_clamped(lo0, hi0); + out_hf[1] = hmx_pack_f32_to_f16_clamped(lo1, hi1); + out_hf[2] = hmx_pack_f32_to_f16_clamped(lo2, hi2); + out_hf[3] = hmx_pack_f32_to_f16_clamped(lo3, hi3); +} + +static __attribute__((noinline)) void w8a8_sm_glu_eval_1g_strip_hf( + const uint8_t * restrict tp, + const float * restrict dwp, + const uint32_t * restrict da0, + __fp16 * restrict dst, + size_t dst_stride, + size_t n_pairs) { + _Pragma("clang loop unroll(disable)") + for (size_t p = 0; p < n_pairs; ++p) { + const size_t c = p << 6; + HVX_Vector lo0, lo1, lo2, lo3, hi0, hi1, hi2, hi3; + w8a8_sm_eval_tile_quad_1g_none(tp, dwp, c, da0, NULL, 0, 4, 0, true, &lo0, &lo1, &lo2, &lo3); + w8a8_sm_eval_tile_quad_1g_none(tp, dwp, c + 32, da0, NULL, 0, 4, 0, true, &hi0, &hi1, &hi2, &hi3); + hvx_vmem(dst + c + 0 * dst_stride) = hmx_pack_f32_to_f16_clamped(lo0, hi0); + hvx_vmem(dst + c + 1 * dst_stride) = hmx_pack_f32_to_f16_clamped(lo1, hi1); + hvx_vmem(dst + c + 2 * dst_stride) = hmx_pack_f32_to_f16_clamped(lo2, hi2); + hvx_vmem(dst + c + 3 * dst_stride) = hmx_pack_f32_to_f16_clamped(lo3, hi3); + } +} + +static __attribute__((noinline)) void w8a8_sm_glu_eval_2g_quad( + const uint8_t * restrict tp0, + const uint8_t * restrict tp1, + const float * restrict dwp, + const uint32_t * restrict da0, + const uint32_t * restrict da1, + HVX_Vector * restrict out) { + w8a8_sm_eval_tile_quad_2g_none(tp0, tp1, dwp, 0, da0, da1, NULL, 0, 4, 0, true, &out[0], &out[1], &out[2], &out[3]); +} + +static __attribute__((noinline)) void w8a8_sm_glu_eval_2g_pair_hf( + const uint8_t * restrict tp0, + const uint8_t * restrict tp1, + const float * restrict dwp, + const uint32_t * restrict da0, + const uint32_t * restrict da1, + HVX_Vector * restrict out_hf) { + HVX_Vector lo0, lo1, lo2, lo3, hi0, hi1, hi2, hi3; + w8a8_sm_eval_tile_quad_2g_none(tp0, tp1, dwp, 0, da0, da1, NULL, 0, 4, 0, true, &lo0, &lo1, &lo2, &lo3); + w8a8_sm_eval_tile_quad_2g_none(tp0, tp1, dwp, 32, da0, da1, NULL, 0, 4, 0, true, &hi0, &hi1, &hi2, &hi3); + out_hf[0] = hmx_pack_f32_to_f16_clamped(lo0, hi0); + out_hf[1] = hmx_pack_f32_to_f16_clamped(lo1, hi1); + out_hf[2] = hmx_pack_f32_to_f16_clamped(lo2, hi2); + out_hf[3] = hmx_pack_f32_to_f16_clamped(lo3, hi3); +} + +static __attribute__((noinline)) void w8a8_sm_glu_eval_2g_strip_hf( + const uint8_t * restrict tp0, + const uint8_t * restrict tp1, + const float * restrict dwp, + const uint32_t * restrict da0, + const uint32_t * restrict da1, + __fp16 * restrict dst, + size_t dst_stride, + size_t n_pairs) { + _Pragma("clang loop unroll(disable)") + for (size_t p = 0; p < n_pairs; ++p) { + const size_t c = p << 6; + HVX_Vector lo0, lo1, lo2, lo3, hi0, hi1, hi2, hi3; + w8a8_sm_eval_tile_quad_2g_none(tp0, tp1, dwp, c, da0, da1, NULL, 0, 4, 0, true, &lo0, &lo1, &lo2, &lo3); + w8a8_sm_eval_tile_quad_2g_none(tp0, tp1, dwp, c + 32, da0, da1, NULL, 0, 4, 0, true, &hi0, &hi1, &hi2, &hi3); + hvx_vmem(dst + c + 0 * dst_stride) = hmx_pack_f32_to_f16_clamped(lo0, hi0); + hvx_vmem(dst + c + 1 * dst_stride) = hmx_pack_f32_to_f16_clamped(lo1, hi1); + hvx_vmem(dst + c + 2 * dst_stride) = hmx_pack_f32_to_f16_clamped(lo2, hi2); + hvx_vmem(dst + c + 3 * dst_stride) = hmx_pack_f32_to_f16_clamped(lo3, hi3); + } +} + +static __attribute__((noinline)) void w8a8_sm_glu_eval_ng_quad( + const uint8_t * restrict tp, + const float * restrict dw, + size_t group_stride, + uint32_t n_groups, + const uint32_t * restrict da, + HVX_Vector * restrict out) { + const HVX_Vector sign_80 = Q6_Vb_vsplat_R(0x80); + w8a8_sm_eval_tile_quad_ng_none(tp, dw, group_stride, n_groups, da, sign_80, NULL, 0, 0, 4, 0, true, + &out[0], &out[1], &out[2], &out[3]); +} + +static __attribute__((noinline)) void w8a8_sm_glu_eval_chunked_quad( + const uint8_t * restrict tp, + const float * restrict dw, + const w8a8_sm_chunked_eval_args_t * args, + HVX_Vector * restrict out) { + const HVX_Vector sign_80 = Q6_Vb_vsplat_R(0x80); + w8a8_sm_eval_tile_quad_chunked_none(tp, dw, args->act_scales_blk_base, args->group_stride, args->mc_pad, + args->n_groups, args->lane, args->da_ptr, sign_80, NULL, 0, 0, 4, 0, true, + &out[0], &out[1], &out[2], &out[3]); +} + +static __attribute__((noinline)) void w8a8_sm_glu_pack_quad_hf(const HVX_Vector * restrict q, HVX_Vector * restrict out_hf) { + out_hf[0] = hmx_pack_f32_to_f16_clamped(q[0], q[4]); + out_hf[1] = hmx_pack_f32_to_f16_clamped(q[1], q[5]); + out_hf[2] = hmx_pack_f32_to_f16_clamped(q[2], q[6]); + out_hf[3] = hmx_pack_f32_to_f16_clamped(q[3], q[7]); +} + +static __attribute__((noinline)) void w8a8_sm_glu_pack_and_store_tail_fp16( + const hmx_output_glu_state_t * st, + __fp16 * restrict dst, + size_t dst_stride, + const HVX_Vector * restrict g_q, + const HVX_Vector * restrict u_q, + uint32_t valid_rows, + size_t valid_c) { + HVX_Vector g_hf[4] __attribute__((aligned(128))); + HVX_Vector u_hf[4] __attribute__((aligned(128))); + if (valid_c > 32) { + g_hf[0] = hmx_pack_f32_to_f16_clamped(g_q[0], g_q[4]); + g_hf[1] = hmx_pack_f32_to_f16_clamped(g_q[1], g_q[5]); + g_hf[2] = hmx_pack_f32_to_f16_clamped(g_q[2], g_q[6]); + g_hf[3] = hmx_pack_f32_to_f16_clamped(g_q[3], g_q[7]); + u_hf[0] = hmx_pack_f32_to_f16_clamped(u_q[0], u_q[4]); + u_hf[1] = hmx_pack_f32_to_f16_clamped(u_q[1], u_q[5]); + u_hf[2] = hmx_pack_f32_to_f16_clamped(u_q[2], u_q[6]); + u_hf[3] = hmx_pack_f32_to_f16_clamped(u_q[3], u_q[7]); + } else { + const HVX_Vector z = Q6_V_vzero(); + g_hf[0] = hmx_pack_f32_to_f16_clamped(g_q[0], z); + g_hf[1] = hmx_pack_f32_to_f16_clamped(g_q[1], z); + g_hf[2] = hmx_pack_f32_to_f16_clamped(g_q[2], z); + g_hf[3] = hmx_pack_f32_to_f16_clamped(g_q[3], z); + u_hf[0] = hmx_pack_f32_to_f16_clamped(u_q[0], z); + u_hf[1] = hmx_pack_f32_to_f16_clamped(u_q[1], z); + u_hf[2] = hmx_pack_f32_to_f16_clamped(u_q[2], z); + u_hf[3] = hmx_pack_f32_to_f16_clamped(u_q[3], z); + } + const uint32_t valid_bytes = (uint32_t) (valid_c * sizeof(__fp16)); + st->store_tail_fn(dst, dst_stride, g_hf, u_hf, (valid_rows << 16) | valid_bytes); +} + +#define W8A8_GLU_EVAL_TILE_1G(tp_g, tp_u, dw_g, dw_u, out_g, out_u) \ + w8a8_sm_glu_eval_1g_quad((tp_g), (dw_g), da0, (out_g)); \ + w8a8_sm_glu_eval_1g_quad((tp_u), (dw_u), da0, (out_u)); + +#define W8A8_GLU_EVAL_TILE_2G(tp_g, tp_u, dw_g, dw_u, out_g, out_u) \ + w8a8_sm_glu_eval_2g_quad((tp_g), (tp_g) + group_stride, (dw_g), da0, da1, (out_g)); \ + w8a8_sm_glu_eval_2g_quad((tp_u), (tp_u) + group_stride, (dw_u), da0, da1, (out_u)); + +#define W8A8_GLU_EVAL_TILE_NG(tp_g, tp_u, dw_g, dw_u, out_g, out_u) \ + w8a8_sm_glu_eval_ng_quad((tp_g), (dw_g), group_stride, n_groups, da_quad_base, (out_g)); \ + w8a8_sm_glu_eval_ng_quad((tp_u), (dw_u), group_stride, n_groups, da_quad_base, (out_u)); + +#define W8A8_GLU_EVAL_TILE_CHK(tp_g, tp_u, dw_g, dw_u, out_g, out_u) \ + w8a8_sm_glu_eval_chunked_quad((tp_g), (dw_g), &cargs, (out_g)); \ + w8a8_sm_glu_eval_chunked_quad((tp_u), (dw_u), &cargs, (out_u)); + +#define W8A8_GLU_EVAL_PAIR_1G(tp_g, tp_u, dw_g, dw_u, out_g, out_u) \ + w8a8_sm_glu_eval_1g_pair_hf((tp_g), (dw_g), da0, (out_g)); \ + w8a8_sm_glu_eval_1g_pair_hf((tp_u), (dw_u), da0, (out_u)); + +#define W8A8_GLU_EVAL_PAIR_2G(tp_g, tp_u, dw_g, dw_u, out_g, out_u) \ + w8a8_sm_glu_eval_2g_pair_hf((tp_g), (tp_g) + group_stride, (dw_g), da0, da1, (out_g)); \ + w8a8_sm_glu_eval_2g_pair_hf((tp_u), (tp_u) + group_stride, (dw_u), da0, da1, (out_u)); + +#define W8A8_GLU_EVAL_STRIP_1G(tp_g, tp_u, dw_g, dw_u, dst_g, dst_s, dst_u, u_s, n_p) \ + w8a8_sm_glu_eval_1g_strip_hf((tp_g), (dw_g), da0, (dst_g), (dst_s), (n_p)); \ + w8a8_sm_glu_eval_1g_strip_hf((tp_u), (dw_u), da0, (dst_u), (u_s), (n_p)); + +#define W8A8_GLU_EVAL_STRIP_2G(tp_g, tp_u, dw_g, dw_u, dst_g, dst_s, dst_u, u_s, n_p) \ + w8a8_sm_glu_eval_2g_strip_hf((tp_g), (tp_g) + group_stride, (dw_g), da0, da1, (dst_g), (dst_s), (n_p)); \ + w8a8_sm_glu_eval_2g_strip_hf((tp_u), (tp_u) + group_stride, (dw_u), da0, da1, (dst_u), (u_s), (n_p)); + +#define W8A8_GLU_TAIL_FP16(EVAL_TILE, DW_STRIDE_ELEMS) \ + if (limit_c_aligned < limit_c) { \ + HVX_Vector g_q[8] __attribute__((aligned(128))); \ + HVX_Vector u_q[8] __attribute__((aligned(128))); \ + const size_t c = limit_c_aligned; \ + const size_t c0 = c >> 5; \ + const size_t off0 = c0 * 2 * HTP_MM_HMX_TILE_SIZE; \ + const size_t dw0 = c0 * (DW_STRIDE_ELEMS); \ + const size_t valid_c = limit_c - c; \ + EVAL_TILE(g_base + off0, u_base + off0, dw_g_base + dw0, dw_u_base + dw0, &g_q[0], &u_q[0]) \ + if (valid_c > 32) { \ + const size_t off1 = off0 + 2 * HTP_MM_HMX_TILE_SIZE; \ + const size_t dw1 = dw0 + (DW_STRIDE_ELEMS); \ + EVAL_TILE(g_base + off1, u_base + off1, dw_g_base + dw1, dw_u_base + dw1, &g_q[4], &u_q[4]) \ + } \ + w8a8_sm_glu_pack_and_store_tail_fp16(st, out_row0 + c, dst_stride, g_q, u_q, valid_rows, valid_c); \ + } + +#define W8A8_GLU_LOOP_FP16_PAIR(EVAL_STRIP, EVAL_PAIR, EVAL_TILE, DW_STRIDE_ELEMS) \ + { \ + const uint32_t valid_rows = (uint32_t) hex_smin((size_t) 4u, (size_t) n_rows - r); \ + if (valid_rows == 4u) { \ + __fp16 u_buf[4 * 256] __attribute__((aligned(128))); \ + _Pragma("clang loop unroll(disable)") \ + for (size_t c = 0; c < limit_c_aligned; c += 256) { \ + const size_t n_pairs = hex_smin((limit_c_aligned - c) >> 6, (size_t) 4u); \ + const size_t c0 = c >> 5; \ + const size_t off0 = c0 * 2 * HTP_MM_HMX_TILE_SIZE; \ + const size_t dw0 = c0 * (DW_STRIDE_ELEMS); \ + EVAL_STRIP(g_base + off0, u_base + off0, dw_g_base + dw0, dw_u_base + dw0, \ + out_row0 + c, dst_stride, u_buf, 256, n_pairs) \ + st->store_strip_fn(out_row0 + c, dst_stride, u_buf, 256, n_pairs); \ + } \ + } else { \ + HVX_Vector g_hf[4] __attribute__((aligned(128))); \ + HVX_Vector u_hf[4] __attribute__((aligned(128))); \ + _Pragma("clang loop unroll(disable)") \ + for (size_t c = 0; c < limit_c_aligned; c += 64) { \ + const size_t c0 = c >> 5; \ + const size_t off0 = c0 * 2 * HTP_MM_HMX_TILE_SIZE; \ + const size_t dw0 = c0 * (DW_STRIDE_ELEMS); \ + EVAL_PAIR(g_base + off0, u_base + off0, dw_g_base + dw0, dw_u_base + dw0, g_hf, u_hf) \ + st->store_quad_fn(out_row0 + c, dst_stride, g_hf, u_hf, valid_rows); \ + } \ + } \ + W8A8_GLU_TAIL_FP16(EVAL_TILE, DW_STRIDE_ELEMS) \ + } + +#define W8A8_GLU_LOOP_FP16_GEN(EVAL_TILE, DW_STRIDE_ELEMS) \ + { \ + const uint32_t valid_rows = (uint32_t) hex_smin((size_t) 4u, (size_t) n_rows - r); \ + HVX_Vector g_q[8] __attribute__((aligned(128))); \ + HVX_Vector u_q[8] __attribute__((aligned(128))); \ + HVX_Vector g_hf[4] __attribute__((aligned(128))); \ + HVX_Vector u_hf[4] __attribute__((aligned(128))); \ + _Pragma("clang loop unroll(disable)") \ + for (size_t c = 0; c < limit_c_aligned; c += 64) { \ + const size_t c0 = c >> 5; \ + const size_t off0 = c0 * 2 * HTP_MM_HMX_TILE_SIZE; \ + const size_t off1 = off0 + 2 * HTP_MM_HMX_TILE_SIZE; \ + const size_t dw0 = c0 * (DW_STRIDE_ELEMS); \ + const size_t dw1 = dw0 + (DW_STRIDE_ELEMS); \ + EVAL_TILE(g_base + off0, u_base + off0, dw_g_base + dw0, dw_u_base + dw0, &g_q[0], &u_q[0]) \ + EVAL_TILE(g_base + off1, u_base + off1, dw_g_base + dw1, dw_u_base + dw1, &g_q[4], &u_q[4]) \ + w8a8_sm_glu_pack_quad_hf(g_q, g_hf); \ + w8a8_sm_glu_pack_quad_hf(u_q, u_hf); \ + st->store_quad_fn(out_row0 + c, dst_stride, g_hf, u_hf, valid_rows); \ + } \ + W8A8_GLU_TAIL_FP16(EVAL_TILE, DW_STRIDE_ELEMS) \ + } + +#define W8A8_GLU_LOOP_FP32(EVAL_TILE, DW_STRIDE_ELEMS) \ + { \ + const uint32_t valid_rows = (uint32_t) hex_smin((size_t) 4u, (size_t) n_rows - r); \ + HVX_Vector g_q[4] __attribute__((aligned(128))); \ + HVX_Vector u_q[4] __attribute__((aligned(128))); \ + _Pragma("clang loop unroll(disable)") \ + for (size_t c = 0; c < limit_c_aligned; c += 32) { \ + const size_t c0 = c >> 5; \ + const size_t off0 = c0 * 2 * HTP_MM_HMX_TILE_SIZE; \ + const size_t dw0 = c0 * (DW_STRIDE_ELEMS); \ + EVAL_TILE(g_base + off0, u_base + off0, dw_g_base + dw0, dw_u_base + dw0, &g_q[0], &u_q[0]) \ + st->store_quad_fn(out_row0 + c, dst_stride, g_q, u_q, valid_rows); \ + } \ + if (limit_c_aligned < limit_c) { \ + const size_t c = limit_c_aligned; \ + const size_t c0 = c >> 5; \ + const size_t off0 = c0 * 2 * HTP_MM_HMX_TILE_SIZE; \ + const size_t dw0 = c0 * (DW_STRIDE_ELEMS); \ + const uint32_t valid_bytes = (uint32_t) ((limit_c - c) * sizeof(float)); \ + EVAL_TILE(g_base + off0, u_base + off0, dw_g_base + dw0, dw_u_base + dw0, &g_q[0], &u_q[0]) \ + st->store_tail_fn(out_row0 + c, dst_stride, g_q, u_q, (valid_rows << 16) | valid_bytes); \ + } \ + } + +#define W8A8_GLU_LOOP_FP16_1G W8A8_GLU_LOOP_FP16_PAIR(W8A8_GLU_EVAL_STRIP_1G, W8A8_GLU_EVAL_PAIR_1G, W8A8_GLU_EVAL_TILE_1G, 32) +#define W8A8_GLU_LOOP_FP16_2G W8A8_GLU_LOOP_FP16_PAIR(W8A8_GLU_EVAL_STRIP_2G, W8A8_GLU_EVAL_PAIR_2G, W8A8_GLU_EVAL_TILE_2G, 64) +#define W8A8_GLU_LOOP_FP16_NG W8A8_GLU_LOOP_FP16_GEN(W8A8_GLU_EVAL_TILE_NG, dw_tile_elems) +#define W8A8_GLU_LOOP_FP16_CHK W8A8_GLU_LOOP_FP16_GEN(W8A8_GLU_EVAL_TILE_CHK, dw_tile_elems) + +#define W8A8_GLU_LOOP_FP32_1G W8A8_GLU_LOOP_FP32(W8A8_GLU_EVAL_TILE_1G, 32) +#define W8A8_GLU_LOOP_FP32_2G W8A8_GLU_LOOP_FP32(W8A8_GLU_EVAL_TILE_2G, 64) +#define W8A8_GLU_LOOP_FP32_NG W8A8_GLU_LOOP_FP32(W8A8_GLU_EVAL_TILE_NG, dw_tile_elems) +#define W8A8_GLU_LOOP_FP32_CHK W8A8_GLU_LOOP_FP32(W8A8_GLU_EVAL_TILE_CHK, dw_tile_elems) + +#define DEFINE_W8A8_GLU_COL_CHUNKS(DST_SFX, DST_T, ALIGN_MASK, LOOP_1G, LOOP_2G, LOOP_NG, LOOP_CHK) \ +static __attribute__((noinline)) void transfer_output_chunk_w8a8_sm_glu_##DST_SFX##_1g( \ + const void * st_void, void * restrict dst_ptr, \ + uint32_t start_row, uint32_t n_rows, uint32_t c_first, uint32_t c_len_and_dst_cols) { \ + const hmx_output_glu_state_t * st = (const hmx_output_glu_state_t *) st_void; \ + DST_T * restrict dst = (DST_T *) dst_ptr; \ + const size_t total_col_tiles = hmx_ceil_div(st->n_cols, 32); \ + const size_t row_tile_stride = total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \ + const size_t c0_first = c_first >> 5; \ + const size_t limit_c = hex_smin(c_len_and_dst_cols >> 16, c_len_and_dst_cols & 0xffffu); \ + const size_t limit_c_aligned = limit_c & (ALIGN_MASK); \ + const size_t dst_stride = st->dst_stride; \ + const float * dw_g_base = st->vtcm_wt_scales_gate + c0_first * 32; \ + const float * dw_u_base = st->vtcm_wt_scales_up + c0_first * 32; \ + uint32_t da_buf[1][32] __attribute__((aligned(128))); \ + for (size_t r_base = 0; r_base < n_rows; ) { \ + const size_t r_idx_base = start_row + r_base; \ + const size_t r_blk = r_idx_base >> 5; \ + const size_t r0 = r_idx_base >> 6; \ + const size_t r_step = hex_smin((size_t) n_rows - r_base, (size_t) (32u - (r_idx_base & 31u))); \ + const size_t r_end = r_base + r_step; \ + uint32_t (*da_ptr)[32] = stage_act_scales_to_l1d(da_buf, st->vtcm_act_scales + (r_blk << 5), 0, 1); \ + for (size_t r = r_base; r < r_end; r += 4) { \ + const size_t r_idx0 = start_row + r; \ + const size_t rg = (r_idx0 & 63u) >> 2; \ + const size_t lane = r_idx0 & 31u; \ + const uint32_t * da0 = &da_ptr[0][lane]; \ + const size_t tile_off = r0 * row_tile_stride + c0_first * 2 * HTP_MM_HMX_TILE_SIZE + rg * 128; \ + const uint8_t * g_base = st->vtcm_gate + tile_off; \ + const uint8_t * u_base = st->vtcm_up + tile_off; \ + DST_T * out_row0 = dst + r * dst_stride; \ + LOOP_1G \ + } \ + r_base = r_end; \ + } \ +} \ +static __attribute__((noinline)) void transfer_output_chunk_w8a8_sm_glu_##DST_SFX##_2g( \ + const void * st_void, void * restrict dst_ptr, \ + uint32_t start_row, uint32_t n_rows, uint32_t c_first, uint32_t c_len_and_dst_cols) { \ + const hmx_output_glu_state_t * st = (const hmx_output_glu_state_t *) st_void; \ + DST_T * restrict dst = (DST_T *) dst_ptr; \ + const size_t total_col_tiles = hmx_ceil_div(st->n_cols, 32); \ + const size_t n_row_tiles_64 = st->mc_pad >> 6; \ + const size_t row_tile_stride = total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \ + const size_t group_stride = n_row_tiles_64 * row_tile_stride; \ + const size_t c0_first = c_first >> 5; \ + const size_t limit_c = hex_smin(c_len_and_dst_cols >> 16, c_len_and_dst_cols & 0xffffu); \ + const size_t limit_c_aligned = limit_c & (ALIGN_MASK); \ + const size_t dst_stride = st->dst_stride; \ + const float * dw_g_base = st->vtcm_wt_scales_gate + c0_first * 64; \ + const float * dw_u_base = st->vtcm_wt_scales_up + c0_first * 64; \ + uint32_t da_buf[2][32] __attribute__((aligned(128))); \ + for (size_t r_base = 0; r_base < n_rows; ) { \ + const size_t r_idx_base = start_row + r_base; \ + const size_t r_blk = r_idx_base >> 5; \ + const size_t r0 = r_idx_base >> 6; \ + const size_t r_step = hex_smin((size_t) n_rows - r_base, (size_t) (32u - (r_idx_base & 31u))); \ + const size_t r_end = r_base + r_step; \ + const float * sc_base = st->vtcm_act_scales + (r_blk << 5); \ + uint32_t (*da_ptr)[32] = stage_act_scales_to_l1d(da_buf, sc_base, st->mc_pad, 2); \ + for (size_t r = r_base; r < r_end; r += 4) { \ + const size_t r_idx0 = start_row + r; \ + const size_t rg = (r_idx0 & 63u) >> 2; \ + const size_t lane = r_idx0 & 31u; \ + const uint32_t * da0 = &da_ptr[0][lane]; \ + const uint32_t * da1 = &da_ptr[1][lane]; \ + const size_t tile_off = r0 * row_tile_stride + c0_first * 2 * HTP_MM_HMX_TILE_SIZE + rg * 128; \ + const uint8_t * g_base = st->vtcm_gate + tile_off; \ + const uint8_t * u_base = st->vtcm_up + tile_off; \ + DST_T * out_row0 = dst + r * dst_stride; \ + LOOP_2G \ + } \ + r_base = r_end; \ + } \ +} \ +static __attribute__((noinline)) void transfer_output_chunk_w8a8_sm_glu_##DST_SFX##_ng( \ + const void * st_void, void * restrict dst_ptr, \ + uint32_t start_row, uint32_t n_rows, uint32_t c_first, uint32_t c_len_and_dst_cols) { \ + const hmx_output_glu_state_t * st = (const hmx_output_glu_state_t *) st_void; \ + DST_T * restrict dst = (DST_T *) dst_ptr; \ + const uint32_t n_groups = st->n_groups; \ + const size_t total_col_tiles = hmx_ceil_div(st->n_cols, 32); \ + const size_t n_row_tiles_64 = st->mc_pad >> 6; \ + const size_t row_tile_stride = total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \ + const size_t group_stride = n_row_tiles_64 * row_tile_stride; \ + const size_t dw_tile_elems = (size_t) n_groups * 32; \ + const size_t c0_first = c_first >> 5; \ + const size_t limit_c = hex_smin(c_len_and_dst_cols >> 16, c_len_and_dst_cols & 0xffffu); \ + const size_t limit_c_aligned = limit_c & (ALIGN_MASK); \ + const size_t dst_stride = st->dst_stride; \ + const float * dw_g_base = st->vtcm_wt_scales_gate + c0_first * dw_tile_elems; \ + const float * dw_u_base = st->vtcm_wt_scales_up + c0_first * dw_tile_elems; \ + uint32_t da_buf[16][32] __attribute__((aligned(128))); \ + for (size_t r_base = 0; r_base < n_rows; ) { \ + const size_t r_idx_base = start_row + r_base; \ + const size_t r_blk = r_idx_base >> 5; \ + const size_t r0 = r_idx_base >> 6; \ + const size_t r_step = hex_smin((size_t) n_rows - r_base, (size_t) (32u - (r_idx_base & 31u))); \ + const size_t r_end = r_base + r_step; \ + const float * sc_base = st->vtcm_act_scales + (r_blk << 5); \ + uint32_t (*da_ptr)[32] = stage_act_scales_to_l1d(da_buf, sc_base, st->mc_pad, n_groups); \ + for (size_t r = r_base; r < r_end; r += 4) { \ + const size_t r_idx0 = start_row + r; \ + const size_t rg = (r_idx0 & 63u) >> 2; \ + const size_t lane = r_idx0 & 31u; \ + const uint32_t * da_quad_base = &da_ptr[0][lane]; \ + const size_t tile_off = r0 * row_tile_stride + c0_first * 2 * HTP_MM_HMX_TILE_SIZE + rg * 128; \ + const uint8_t * g_base = st->vtcm_gate + tile_off; \ + const uint8_t * u_base = st->vtcm_up + tile_off; \ + DST_T * out_row0 = dst + r * dst_stride; \ + LOOP_NG \ + } \ + r_base = r_end; \ + } \ +} \ +static __attribute__((noinline)) void transfer_output_chunk_w8a8_sm_glu_##DST_SFX##_chunked( \ + const void * st_void, void * restrict dst_ptr, \ + uint32_t start_row, uint32_t n_rows, uint32_t c_first, uint32_t c_len_and_dst_cols) { \ + const hmx_output_glu_state_t * st = (const hmx_output_glu_state_t *) st_void; \ + DST_T * restrict dst = (DST_T *) dst_ptr; \ + const uint32_t n_groups = st->n_groups; \ + const size_t total_col_tiles = hmx_ceil_div(st->n_cols, 32); \ + const size_t n_row_tiles_64 = st->mc_pad >> 6; \ + const size_t row_tile_stride = total_col_tiles * 2 * HTP_MM_HMX_TILE_SIZE; \ + const size_t group_stride = n_row_tiles_64 * row_tile_stride; \ + const size_t dw_tile_elems = (size_t) n_groups * 32; \ + const size_t c0_first = c_first >> 5; \ + const size_t limit_c = hex_smin(c_len_and_dst_cols >> 16, c_len_and_dst_cols & 0xffffu); \ + const size_t limit_c_aligned = limit_c & (ALIGN_MASK); \ + const size_t dst_stride = st->dst_stride; \ + const float * dw_g_base = st->vtcm_wt_scales_gate + c0_first * dw_tile_elems; \ + const float * dw_u_base = st->vtcm_wt_scales_up + c0_first * dw_tile_elems; \ + uint32_t da_buf[16][32] __attribute__((aligned(128))); \ + for (size_t r_base = 0; r_base < n_rows; ) { \ + const size_t r_idx_base = start_row + r_base; \ + const size_t r_blk = r_idx_base >> 5; \ + const size_t r0 = r_idx_base >> 6; \ + const size_t r_step = hex_smin((size_t) n_rows - r_base, (size_t) (32u - (r_idx_base & 31u))); \ + const size_t r_end = r_base + r_step; \ + w8a8_sm_chunked_eval_args_t cargs; \ + cargs.act_scales_blk_base = st->vtcm_act_scales + (r_blk << 5); \ + cargs.da_ptr = da_buf; \ + cargs.group_stride = group_stride; \ + cargs.mc_pad = st->mc_pad; \ + cargs.n_groups = n_groups; \ + for (size_t r = r_base; r < r_end; r += 4) { \ + const size_t r_idx0 = start_row + r; \ + const size_t rg = (r_idx0 & 63u) >> 2; \ + cargs.lane = (uint32_t) (r_idx0 & 31u); \ + const size_t tile_off = r0 * row_tile_stride + c0_first * 2 * HTP_MM_HMX_TILE_SIZE + rg * 128; \ + const uint8_t * g_base = st->vtcm_gate + tile_off; \ + const uint8_t * u_base = st->vtcm_up + tile_off; \ + DST_T * out_row0 = dst + r * dst_stride; \ + LOOP_CHK \ + } \ + r_base = r_end; \ + } \ +} + +DEFINE_W8A8_GLU_COL_CHUNKS(fp16, __fp16, ~63u, W8A8_GLU_LOOP_FP16_1G, W8A8_GLU_LOOP_FP16_2G, W8A8_GLU_LOOP_FP16_NG, W8A8_GLU_LOOP_FP16_CHK) +DEFINE_W8A8_GLU_COL_CHUNKS(fp32, float, ~31u, W8A8_GLU_LOOP_FP32_1G, W8A8_GLU_LOOP_FP32_2G, W8A8_GLU_LOOP_FP32_NG, W8A8_GLU_LOOP_FP32_CHK) + +static inline bool resolve_int_output_glu_fns( + uint32_t n_groups, + uint8_t glu_op, + size_t dst_elem_size, + hmx_output_glu_col_chunk_fn_t * col_chunk_fn, + hmx_glu_store_quad_fn_t * store_quad_fn, + hmx_glu_store_tail_fn_t * store_tail_fn, + hmx_glu_store_strip_fn_t * store_strip_fn) { + if (!resolve_hmx_glu_store_fns(glu_op, dst_elem_size, store_quad_fn, store_tail_fn, store_strip_fn)) { + return false; + } + if (dst_elem_size == sizeof(__fp16)) { + if (n_groups <= 1u) *col_chunk_fn = transfer_output_chunk_w8a8_sm_glu_fp16_1g; + else if (n_groups == 2u) *col_chunk_fn = transfer_output_chunk_w8a8_sm_glu_fp16_2g; + else if (n_groups <= 16u) *col_chunk_fn = transfer_output_chunk_w8a8_sm_glu_fp16_ng; + else *col_chunk_fn = transfer_output_chunk_w8a8_sm_glu_fp16_chunked; + } else { + if (n_groups <= 1u) *col_chunk_fn = transfer_output_chunk_w8a8_sm_glu_fp32_1g; + else if (n_groups == 2u) *col_chunk_fn = transfer_output_chunk_w8a8_sm_glu_fp32_2g; + else if (n_groups <= 16u) *col_chunk_fn = transfer_output_chunk_w8a8_sm_glu_fp32_ng; + else *col_chunk_fn = transfer_output_chunk_w8a8_sm_glu_fp32_chunked; + } + return true; +} + diff --git a/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled.h b/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled.h deleted file mode 100644 index 37c529647ab9..000000000000 --- a/ggml/src/ggml-hexagon/htp/hmx-mm-kernels-tiled.h +++ /dev/null @@ -1,1909 +0,0 @@ -#include "hmx-utils.h" -#include "hmx-queue.h" - -// MXFP4 dequantization LUT: maps 4-bit index to fp16 mantissa value -// kvalues: 0, 0.5, 1, 1.5, 2, 3, 4, 6, 0, -0.5, -1, -1.5, -2, -3, -4, -6 -static const __fp16 mxfp4_to_fp16_lut[64] __attribute__((aligned(VLEN))) = { - 0, 0, 0.5, 0, 1, 0, 1.5, 0, 2, 0, 3, 0, 4, 0, 6, 0, 0, 0, -0.5, 0, -1, 0, -1.5, 0, -2, 0, -3, 0, -4, 0, -6, 0, -}; - -static const __fp16 iq4_nl_to_fp16_lut[64] __attribute__((aligned(VLEN))) = { - -127, 0, -104, 0, -83, 0, -65, 0, -49, 0, -35, 0, -22, 0, -10, 0, - 1, 0, 13, 0, 25, 0, 38, 0, 53, 0, 69, 0, 89, 0, 113, 0, -}; - -// --- tiled format dequantizers --- - -typedef struct tiled_dequantize_state tiled_dequantize_state_t; -typedef void (*tiled_dequant_task_fn_t)(const tiled_dequantize_state_t * state, uint32_t start_tile, uint32_t end_tile); - -struct tiled_dequantize_state { - __fp16 * dst; - const uint8_t * src; - tiled_dequant_task_fn_t task_fn; - - struct fastdiv_values n_k_tiles_div; - uint32_t n_k_tiles; - uint32_t n_weight_tiles; - uint32_t n_tot_tiles; - uint32_t n_tiles_per_task; - uint32_t tile_size; - uint32_t aligned_tile_size; - uint32_t n_tasks; - uint32_t n_cols; - uint32_t k_block; - size_t row_stride; - uint32_t weight_type; -}; - -static void dequantize_tiled_weight_to_fp16_task_q1_0( - const tiled_dequantize_state_t *state, - uint32_t start_tile, uint32_t end_tile) { - - const HVX_Vector v_neg_one = Q6_Vb_vsplat_R(-1); - const HVX_Vector v_pos_one = Q6_Vb_vsplat_R(1); - - for (uint32_t t = start_tile; t < end_tile; t++) { - const uint8_t * tile_src = state->src + t * state->aligned_tile_size; - __fp16 * dst_ptr = state->dst + 4 * t * HTP_MM_HMX_TILE_N_ELMS; - - const HVX_Vector v_sc = hvx_vmem(tile_src + 512); - const HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); - - for (uint32_t q = 0; q < 4; q++) { - const HVX_Vector v_plane = hvx_vmem(tile_src + q * 128); - __fp16 * quarter_dst = dst_ptr + q * HTP_MM_HMX_TILE_N_ELMS; - - #pragma unroll - for (int g = 0; g < 8; g++) { - const HVX_Vector v_q = unpack_q1_0_group(v_plane, g, v_neg_one, v_pos_one); - const HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_q); - const HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4); - - hvx_vmem(quarter_dst + (2 * g + 0) * 64) = - Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale)); - hvx_vmem(quarter_dst + (2 * g + 1) * 64) = - Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale)); - } - } - } -} - -// Dequantize a single tile from tiled weight data (already in VTCM) to tile-major FP16. -static void dequantize_tiled_weight_to_fp16_task_q4_0( - const tiled_dequantize_state_t *state, - uint32_t start_tile, uint32_t end_tile) { - - const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F); - const HVX_Vector i8 = Q6_Vb_vsplat_R(8); - - for (uint32_t t = start_tile; t < end_tile; t++) { - const uint8_t * tile_src = state->src + t * state->aligned_tile_size; - __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS; - - HVX_Vector v_sc = hvx_vmem(tile_src + 512); - HVX_Vector v_scale_duplicated = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); - - // Load all 4 groups in parallel - HVX_Vector vq0 = hvx_vmem(tile_src + 0 * 128); - HVX_Vector vq1 = hvx_vmem(tile_src + 1 * 128); - HVX_Vector vq2 = hvx_vmem(tile_src + 2 * 128); - HVX_Vector vq3 = hvx_vmem(tile_src + 3 * 128); - - // Nibble extraction - HVX_Vector v_lo0 = Q6_V_vand_VV(vq0, mask_h4); - HVX_Vector v_hi0 = Q6_Vub_vlsr_VubR(vq0, 4); - HVX_Vector v_lo1 = Q6_V_vand_VV(vq1, mask_h4); - HVX_Vector v_hi1 = Q6_Vub_vlsr_VubR(vq1, 4); - HVX_Vector v_lo2 = Q6_V_vand_VV(vq2, mask_h4); - HVX_Vector v_hi2 = Q6_Vub_vlsr_VubR(vq2, 4); - HVX_Vector v_lo3 = Q6_V_vand_VV(vq3, mask_h4); - HVX_Vector v_hi3 = Q6_Vub_vlsr_VubR(vq3, 4); - - // Offsetting (-8) - v_lo0 = Q6_Vb_vsub_VbVb(v_lo0, i8); - v_hi0 = Q6_Vb_vsub_VbVb(v_hi0, i8); - v_lo1 = Q6_Vb_vsub_VbVb(v_lo1, i8); - v_hi1 = Q6_Vb_vsub_VbVb(v_hi1, i8); - v_lo2 = Q6_Vb_vsub_VbVb(v_lo2, i8); - v_hi2 = Q6_Vb_vsub_VbVb(v_hi2, i8); - v_lo3 = Q6_Vb_vsub_VbVb(v_lo3, i8); - v_hi3 = Q6_Vb_vsub_VbVb(v_hi3, i8); - - // Shuffling - HVX_VectorPair vp_shuf0 = Q6_W_vshuff_VVR(v_hi0, v_lo0, -1); - HVX_VectorPair vp_shuf1 = Q6_W_vshuff_VVR(v_hi1, v_lo1, -1); - HVX_VectorPair vp_shuf2 = Q6_W_vshuff_VVR(v_hi2, v_lo2, -1); - HVX_VectorPair vp_shuf3 = Q6_W_vshuff_VVR(v_hi3, v_lo3, -1); - - // Unpack to 16-bit - HVX_VectorPair vp_int16_lo0 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf0)); - HVX_VectorPair vp_int16_hi0 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf0)); - HVX_VectorPair vp_int16_lo1 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf1)); - HVX_VectorPair vp_int16_hi1 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf1)); - HVX_VectorPair vp_int16_lo2 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf2)); - HVX_VectorPair vp_int16_hi2 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf2)); - HVX_VectorPair vp_int16_lo3 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf3)); - HVX_VectorPair vp_int16_hi3 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf3)); - - // Convert and scale multiplication - HVX_Vector v_grp0_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo0)), v_scale_duplicated)); - HVX_Vector v_grp0_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo0)), v_scale_duplicated)); - HVX_Vector v_grp0_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi0)), v_scale_duplicated)); - HVX_Vector v_grp0_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi0)), v_scale_duplicated)); - - HVX_Vector v_grp1_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo1)), v_scale_duplicated)); - HVX_Vector v_grp1_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo1)), v_scale_duplicated)); - HVX_Vector v_grp1_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi1)), v_scale_duplicated)); - HVX_Vector v_grp1_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi1)), v_scale_duplicated)); - - HVX_Vector v_grp2_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo2)), v_scale_duplicated)); - HVX_Vector v_grp2_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo2)), v_scale_duplicated)); - HVX_Vector v_grp2_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi2)), v_scale_duplicated)); - HVX_Vector v_grp2_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi2)), v_scale_duplicated)); - - HVX_Vector v_grp3_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo3)), v_scale_duplicated)); - HVX_Vector v_grp3_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo3)), v_scale_duplicated)); - HVX_Vector v_grp3_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi3)), v_scale_duplicated)); - HVX_Vector v_grp3_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi3)), v_scale_duplicated)); - - hvx_vmem(dst_ptr + 0 * 64) = v_grp0_0; - hvx_vmem(dst_ptr + 1 * 64) = v_grp0_1; - hvx_vmem(dst_ptr + 2 * 64) = v_grp0_2; - hvx_vmem(dst_ptr + 3 * 64) = v_grp0_3; - - hvx_vmem(dst_ptr + 4 * 64) = v_grp1_0; - hvx_vmem(dst_ptr + 5 * 64) = v_grp1_1; - hvx_vmem(dst_ptr + 6 * 64) = v_grp1_2; - hvx_vmem(dst_ptr + 7 * 64) = v_grp1_3; - - hvx_vmem(dst_ptr + 8 * 64) = v_grp2_0; - hvx_vmem(dst_ptr + 9 * 64) = v_grp2_1; - hvx_vmem(dst_ptr + 10 * 64) = v_grp2_2; - hvx_vmem(dst_ptr + 11 * 64) = v_grp2_3; - - hvx_vmem(dst_ptr + 12 * 64) = v_grp3_0; - hvx_vmem(dst_ptr + 13 * 64) = v_grp3_1; - hvx_vmem(dst_ptr + 14 * 64) = v_grp3_2; - hvx_vmem(dst_ptr + 15 * 64) = v_grp3_3; - } -} - -static void dequantize_tiled_weight_to_fp16_task_q4_1( - const tiled_dequantize_state_t *state, - uint32_t start_tile, uint32_t end_tile) { - - const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F); - - for (uint32_t t = start_tile; t < end_tile; t++) { - const uint8_t * tile_src = state->src + t * state->aligned_tile_size; - __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS; - - HVX_Vector vscale_offset = hvx_vmem(tile_src + 512); - HVX_VectorPair dm_deal = Q6_W_vdeal_VVR(vscale_offset, vscale_offset, -2); - HVX_Vector vd = Q6_V_lo_W(dm_deal); - HVX_Vector vm = Q6_V_hi_W(dm_deal); - - HVX_Vector v_scale_duplicated = Q6_V_lo_W(Q6_W_vshuff_VVR(vd, vd, -2)); - HVX_Vector v_offset_duplicated = Q6_V_lo_W(Q6_W_vshuff_VVR(vm, vm, -2)); - - // Load all 4 groups in parallel - HVX_Vector vq0 = hvx_vmem(tile_src + 0 * 128); - HVX_Vector vq1 = hvx_vmem(tile_src + 1 * 128); - HVX_Vector vq2 = hvx_vmem(tile_src + 2 * 128); - HVX_Vector vq3 = hvx_vmem(tile_src + 3 * 128); - - // Nibble extraction - HVX_Vector v_lo0 = Q6_V_vand_VV(vq0, mask_h4); - HVX_Vector v_hi0 = Q6_Vub_vlsr_VubR(vq0, 4); - HVX_Vector v_lo1 = Q6_V_vand_VV(vq1, mask_h4); - HVX_Vector v_hi1 = Q6_Vub_vlsr_VubR(vq1, 4); - HVX_Vector v_lo2 = Q6_V_vand_VV(vq2, mask_h4); - HVX_Vector v_hi2 = Q6_Vub_vlsr_VubR(vq2, 4); - HVX_Vector v_lo3 = Q6_V_vand_VV(vq3, mask_h4); - HVX_Vector v_hi3 = Q6_Vub_vlsr_VubR(vq3, 4); - - // Shuffling - HVX_VectorPair vp_shuf0 = Q6_W_vshuff_VVR(v_hi0, v_lo0, -1); - HVX_VectorPair vp_shuf1 = Q6_W_vshuff_VVR(v_hi1, v_lo1, -1); - HVX_VectorPair vp_shuf2 = Q6_W_vshuff_VVR(v_hi2, v_lo2, -1); - HVX_VectorPair vp_shuf3 = Q6_W_vshuff_VVR(v_hi3, v_lo3, -1); - - // Unpack to 16-bit - HVX_VectorPair vp_int16_lo0 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf0)); - HVX_VectorPair vp_int16_hi0 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf0)); - HVX_VectorPair vp_int16_lo1 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf1)); - HVX_VectorPair vp_int16_hi1 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf1)); - HVX_VectorPair vp_int16_lo2 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf2)); - HVX_VectorPair vp_int16_hi2 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf2)); - HVX_VectorPair vp_int16_lo3 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf3)); - HVX_VectorPair vp_int16_hi3 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf3)); - - // Convert, multiply, add offset - HVX_Vector v_grp0_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo0)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp0_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo0)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp0_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi0)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp0_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi0)), v_scale_duplicated), v_offset_duplicated)); - - HVX_Vector v_grp1_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo1)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp1_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo1)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp1_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi1)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp1_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi1)), v_scale_duplicated), v_offset_duplicated)); - - HVX_Vector v_grp2_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo2)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp2_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo2)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp2_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi2)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp2_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi2)), v_scale_duplicated), v_offset_duplicated)); - - HVX_Vector v_grp3_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo3)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp3_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo3)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp3_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi3)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp3_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi3)), v_scale_duplicated), v_offset_duplicated)); - - // Parallel Stores - hvx_vmem(dst_ptr + 0 * 64) = v_grp0_0; - hvx_vmem(dst_ptr + 1 * 64) = v_grp0_1; - hvx_vmem(dst_ptr + 2 * 64) = v_grp0_2; - hvx_vmem(dst_ptr + 3 * 64) = v_grp0_3; - - hvx_vmem(dst_ptr + 4 * 64) = v_grp1_0; - hvx_vmem(dst_ptr + 5 * 64) = v_grp1_1; - hvx_vmem(dst_ptr + 6 * 64) = v_grp1_2; - hvx_vmem(dst_ptr + 7 * 64) = v_grp1_3; - - hvx_vmem(dst_ptr + 8 * 64) = v_grp2_0; - hvx_vmem(dst_ptr + 9 * 64) = v_grp2_1; - hvx_vmem(dst_ptr + 10 * 64) = v_grp2_2; - hvx_vmem(dst_ptr + 11 * 64) = v_grp2_3; - - hvx_vmem(dst_ptr + 12 * 64) = v_grp3_0; - hvx_vmem(dst_ptr + 13 * 64) = v_grp3_1; - hvx_vmem(dst_ptr + 14 * 64) = v_grp3_2; - hvx_vmem(dst_ptr + 15 * 64) = v_grp3_3; - } -} - -static void dequantize_tiled_weight_to_fp16_task_iq4_nl( - const tiled_dequantize_state_t *state, - uint32_t start_tile, uint32_t end_tile) { - - const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F); - const HVX_Vector vlut_cvt = hvx_vmem(iq4_nl_to_fp16_lut); - - for (uint32_t t = start_tile; t < end_tile; t++) { - const uint8_t * tile_src = state->src + t * state->aligned_tile_size; - __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS; - - HVX_Vector v_sc = hvx_vmem(tile_src + 512); - HVX_Vector v_scale_duplicated = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); - - // Load all 4 groups in parallel - HVX_Vector vq0 = hvx_vmem(tile_src + 0 * 128); - HVX_Vector vq1 = hvx_vmem(tile_src + 1 * 128); - HVX_Vector vq2 = hvx_vmem(tile_src + 2 * 128); - HVX_Vector vq3 = hvx_vmem(tile_src + 3 * 128); - - // Nibble extraction - HVX_Vector v_lo0 = Q6_V_vand_VV(vq0, mask_h4); - HVX_Vector v_hi0 = Q6_Vub_vlsr_VubR(vq0, 4); - HVX_Vector v_lo1 = Q6_V_vand_VV(vq1, mask_h4); - HVX_Vector v_hi1 = Q6_Vub_vlsr_VubR(vq1, 4); - HVX_Vector v_lo2 = Q6_V_vand_VV(vq2, mask_h4); - HVX_Vector v_hi2 = Q6_Vub_vlsr_VubR(vq2, 4); - HVX_Vector v_lo3 = Q6_V_vand_VV(vq3, mask_h4); - HVX_Vector v_hi3 = Q6_Vub_vlsr_VubR(vq3, 4); - - // Shuffling - HVX_VectorPair vp_shuf0 = Q6_W_vshuff_VVR(v_hi0, v_lo0, -1); - HVX_VectorPair vp_shuf1 = Q6_W_vshuff_VVR(v_hi1, v_lo1, -1); - HVX_VectorPair vp_shuf2 = Q6_W_vshuff_VVR(v_hi2, v_lo2, -1); - HVX_VectorPair vp_shuf3 = Q6_W_vshuff_VVR(v_hi3, v_lo3, -1); - - // Shuffle for LUT lookup - HVX_Vector v_q_lo0 = Q6_Vb_vshuff_Vb(Q6_V_lo_W(vp_shuf0)); - HVX_Vector v_q_hi0 = Q6_Vb_vshuff_Vb(Q6_V_hi_W(vp_shuf0)); - HVX_Vector v_q_lo1 = Q6_Vb_vshuff_Vb(Q6_V_lo_W(vp_shuf1)); - HVX_Vector v_q_hi1 = Q6_Vb_vshuff_Vb(Q6_V_hi_W(vp_shuf1)); - HVX_Vector v_q_lo2 = Q6_Vb_vshuff_Vb(Q6_V_lo_W(vp_shuf2)); - HVX_Vector v_q_hi2 = Q6_Vb_vshuff_Vb(Q6_V_hi_W(vp_shuf2)); - HVX_Vector v_q_lo3 = Q6_Vb_vshuff_Vb(Q6_V_lo_W(vp_shuf3)); - HVX_Vector v_q_hi3 = Q6_Vb_vshuff_Vb(Q6_V_hi_W(vp_shuf3)); - - // LUT lookup - HVX_VectorPair vp_lo0 = Q6_Wh_vlut16_VbVhR(v_q_lo0, vlut_cvt, 0); - HVX_VectorPair vp_hi0 = Q6_Wh_vlut16_VbVhR(v_q_hi0, vlut_cvt, 0); - HVX_VectorPair vp_lo1 = Q6_Wh_vlut16_VbVhR(v_q_lo1, vlut_cvt, 0); - HVX_VectorPair vp_hi1 = Q6_Wh_vlut16_VbVhR(v_q_hi1, vlut_cvt, 0); - HVX_VectorPair vp_lo2 = Q6_Wh_vlut16_VbVhR(v_q_lo2, vlut_cvt, 0); - HVX_VectorPair vp_hi2 = Q6_Wh_vlut16_VbVhR(v_q_hi2, vlut_cvt, 0); - HVX_VectorPair vp_lo3 = Q6_Wh_vlut16_VbVhR(v_q_lo3, vlut_cvt, 0); - HVX_VectorPair vp_hi3 = Q6_Wh_vlut16_VbVhR(v_q_hi3, vlut_cvt, 0); - - // Convert and scale multiplication - HVX_Vector v_grp0_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo0), v_scale_duplicated)); - HVX_Vector v_grp0_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo0), v_scale_duplicated)); - HVX_Vector v_grp0_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi0), v_scale_duplicated)); - HVX_Vector v_grp0_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi0), v_scale_duplicated)); - - HVX_Vector v_grp1_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo1), v_scale_duplicated)); - HVX_Vector v_grp1_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo1), v_scale_duplicated)); - HVX_Vector v_grp1_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi1), v_scale_duplicated)); - HVX_Vector v_grp1_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi1), v_scale_duplicated)); - - HVX_Vector v_grp2_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo2), v_scale_duplicated)); - HVX_Vector v_grp2_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo2), v_scale_duplicated)); - HVX_Vector v_grp2_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi2), v_scale_duplicated)); - HVX_Vector v_grp2_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi2), v_scale_duplicated)); - - HVX_Vector v_grp3_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo3), v_scale_duplicated)); - HVX_Vector v_grp3_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo3), v_scale_duplicated)); - HVX_Vector v_grp3_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi3), v_scale_duplicated)); - HVX_Vector v_grp3_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi3), v_scale_duplicated)); - - hvx_vmem(dst_ptr + 0 * 64) = v_grp0_0; - hvx_vmem(dst_ptr + 1 * 64) = v_grp0_1; - hvx_vmem(dst_ptr + 2 * 64) = v_grp0_2; - hvx_vmem(dst_ptr + 3 * 64) = v_grp0_3; - - hvx_vmem(dst_ptr + 4 * 64) = v_grp1_0; - hvx_vmem(dst_ptr + 5 * 64) = v_grp1_1; - hvx_vmem(dst_ptr + 6 * 64) = v_grp1_2; - hvx_vmem(dst_ptr + 7 * 64) = v_grp1_3; - - hvx_vmem(dst_ptr + 8 * 64) = v_grp2_0; - hvx_vmem(dst_ptr + 9 * 64) = v_grp2_1; - hvx_vmem(dst_ptr + 10 * 64) = v_grp2_2; - hvx_vmem(dst_ptr + 11 * 64) = v_grp2_3; - - hvx_vmem(dst_ptr + 12 * 64) = v_grp3_0; - hvx_vmem(dst_ptr + 13 * 64) = v_grp3_1; - hvx_vmem(dst_ptr + 14 * 64) = v_grp3_2; - hvx_vmem(dst_ptr + 15 * 64) = v_grp3_3; - } -} - -static void dequantize_tiled_weight_to_fp16_task_mxfp4( - const tiled_dequantize_state_t *state, - uint32_t start_tile, uint32_t end_tile) { - - const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F); - const HVX_Vector vlut_cvt = hvx_vmem(mxfp4_to_fp16_lut); - - for (uint32_t t = start_tile; t < end_tile; t++) { - const uint8_t * tile_src = state->src + t * state->aligned_tile_size; - __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS; - - HVX_Vector v = hvx_vmem(tile_src + 512); - HVX_Vector vh = Q6_V_lo_W(Q6_Wuh_vunpack_Vub(v)); - vh = Q6_Vh_vsub_VhVh(vh, Q6_Vh_vsplat_R(112)); - vh = Q6_Vh_vmax_VhVh(vh, Q6_V_vzero()); - vh = Q6_Vh_vmin_VhVh(vh, Q6_Vh_vsplat_R(30)); - vh = Q6_Vh_vasl_VhR(vh, 10); - - HVX_Vector v_scale_duplicated = Q6_V_lo_W(Q6_W_vshuff_VVR(vh, vh, -2)); - - // Load all 4 groups in parallel - HVX_Vector vq0 = hvx_vmem(tile_src + 0 * 128); - HVX_Vector vq1 = hvx_vmem(tile_src + 1 * 128); - HVX_Vector vq2 = hvx_vmem(tile_src + 2 * 128); - HVX_Vector vq3 = hvx_vmem(tile_src + 3 * 128); - - // Nibble extraction - HVX_Vector v_lo0 = Q6_V_vand_VV(vq0, mask_h4); - HVX_Vector v_hi0 = Q6_Vub_vlsr_VubR(vq0, 4); - HVX_Vector v_lo1 = Q6_V_vand_VV(vq1, mask_h4); - HVX_Vector v_hi1 = Q6_Vub_vlsr_VubR(vq1, 4); - HVX_Vector v_lo2 = Q6_V_vand_VV(vq2, mask_h4); - HVX_Vector v_hi2 = Q6_Vub_vlsr_VubR(vq2, 4); - HVX_Vector v_lo3 = Q6_V_vand_VV(vq3, mask_h4); - HVX_Vector v_hi3 = Q6_Vub_vlsr_VubR(vq3, 4); - - // Shuffling - HVX_VectorPair vp_shuf0 = Q6_W_vshuff_VVR(v_hi0, v_lo0, -1); - HVX_VectorPair vp_shuf1 = Q6_W_vshuff_VVR(v_hi1, v_lo1, -1); - HVX_VectorPair vp_shuf2 = Q6_W_vshuff_VVR(v_hi2, v_lo2, -1); - HVX_VectorPair vp_shuf3 = Q6_W_vshuff_VVR(v_hi3, v_lo3, -1); - - // Shuffle for LUT lookup - HVX_Vector v_q_lo0 = Q6_Vb_vshuff_Vb(Q6_V_lo_W(vp_shuf0)); - HVX_Vector v_q_hi0 = Q6_Vb_vshuff_Vb(Q6_V_hi_W(vp_shuf0)); - HVX_Vector v_q_lo1 = Q6_Vb_vshuff_Vb(Q6_V_lo_W(vp_shuf1)); - HVX_Vector v_q_hi1 = Q6_Vb_vshuff_Vb(Q6_V_hi_W(vp_shuf1)); - HVX_Vector v_q_lo2 = Q6_Vb_vshuff_Vb(Q6_V_lo_W(vp_shuf2)); - HVX_Vector v_q_hi2 = Q6_Vb_vshuff_Vb(Q6_V_hi_W(vp_shuf2)); - HVX_Vector v_q_lo3 = Q6_Vb_vshuff_Vb(Q6_V_lo_W(vp_shuf3)); - HVX_Vector v_q_hi3 = Q6_Vb_vshuff_Vb(Q6_V_hi_W(vp_shuf3)); - - // LUT lookup - HVX_VectorPair vp_lo0 = Q6_Wh_vlut16_VbVhR(v_q_lo0, vlut_cvt, 0); - HVX_VectorPair vp_hi0 = Q6_Wh_vlut16_VbVhR(v_q_hi0, vlut_cvt, 0); - HVX_VectorPair vp_lo1 = Q6_Wh_vlut16_VbVhR(v_q_lo1, vlut_cvt, 0); - HVX_VectorPair vp_hi1 = Q6_Wh_vlut16_VbVhR(v_q_hi1, vlut_cvt, 0); - HVX_VectorPair vp_lo2 = Q6_Wh_vlut16_VbVhR(v_q_lo2, vlut_cvt, 0); - HVX_VectorPair vp_hi2 = Q6_Wh_vlut16_VbVhR(v_q_hi2, vlut_cvt, 0); - HVX_VectorPair vp_lo3 = Q6_Wh_vlut16_VbVhR(v_q_lo3, vlut_cvt, 0); - HVX_VectorPair vp_hi3 = Q6_Wh_vlut16_VbVhR(v_q_hi3, vlut_cvt, 0); - - // Convert and scale multiplication - HVX_Vector v_grp0_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo0), v_scale_duplicated)); - HVX_Vector v_grp0_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo0), v_scale_duplicated)); - HVX_Vector v_grp0_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi0), v_scale_duplicated)); - HVX_Vector v_grp0_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi0), v_scale_duplicated)); - - HVX_Vector v_grp1_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo1), v_scale_duplicated)); - HVX_Vector v_grp1_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo1), v_scale_duplicated)); - HVX_Vector v_grp1_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi1), v_scale_duplicated)); - HVX_Vector v_grp1_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi1), v_scale_duplicated)); - - HVX_Vector v_grp2_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo2), v_scale_duplicated)); - HVX_Vector v_grp2_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo2), v_scale_duplicated)); - HVX_Vector v_grp2_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi2), v_scale_duplicated)); - HVX_Vector v_grp2_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi2), v_scale_duplicated)); - - HVX_Vector v_grp3_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo3), v_scale_duplicated)); - HVX_Vector v_grp3_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo3), v_scale_duplicated)); - HVX_Vector v_grp3_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi3), v_scale_duplicated)); - HVX_Vector v_grp3_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi3), v_scale_duplicated)); - - hvx_vmem(dst_ptr + 0 * 64) = v_grp0_0; - hvx_vmem(dst_ptr + 1 * 64) = v_grp0_1; - hvx_vmem(dst_ptr + 2 * 64) = v_grp0_2; - hvx_vmem(dst_ptr + 3 * 64) = v_grp0_3; - - hvx_vmem(dst_ptr + 4 * 64) = v_grp1_0; - hvx_vmem(dst_ptr + 5 * 64) = v_grp1_1; - hvx_vmem(dst_ptr + 6 * 64) = v_grp1_2; - hvx_vmem(dst_ptr + 7 * 64) = v_grp1_3; - - hvx_vmem(dst_ptr + 8 * 64) = v_grp2_0; - hvx_vmem(dst_ptr + 9 * 64) = v_grp2_1; - hvx_vmem(dst_ptr + 10 * 64) = v_grp2_2; - hvx_vmem(dst_ptr + 11 * 64) = v_grp2_3; - - hvx_vmem(dst_ptr + 12 * 64) = v_grp3_0; - hvx_vmem(dst_ptr + 13 * 64) = v_grp3_1; - hvx_vmem(dst_ptr + 14 * 64) = v_grp3_2; - hvx_vmem(dst_ptr + 15 * 64) = v_grp3_3; - } -} - -static void dequantize_tiled_weight_to_fp16_task_q8_0( - const tiled_dequantize_state_t *state, - uint32_t start_tile, uint32_t end_tile) { - - for (uint32_t t = start_tile; t < end_tile; t++) { - const uint8_t * tile_src = state->src + t * state->aligned_tile_size; - __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS; - - HVX_Vector v_sc = hvx_vmem(tile_src + 1024); - HVX_Vector v_scale_duplicated = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); - - // Load groups 0-3 in parallel - HVX_Vector vq0 = hvx_vmem(tile_src + 0 * 128); - HVX_Vector vq1 = hvx_vmem(tile_src + 1 * 128); - HVX_Vector vq2 = hvx_vmem(tile_src + 2 * 128); - HVX_Vector vq3 = hvx_vmem(tile_src + 3 * 128); - - HVX_VectorPair vp_int16_0 = Q6_Wh_vunpack_Vb(vq0); - HVX_VectorPair vp_int16_1 = Q6_Wh_vunpack_Vb(vq1); - HVX_VectorPair vp_int16_2 = Q6_Wh_vunpack_Vb(vq2); - HVX_VectorPair vp_int16_3 = Q6_Wh_vunpack_Vb(vq3); - - // Load groups 4-7 in parallel - HVX_Vector vq4 = hvx_vmem(tile_src + 4 * 128); - HVX_Vector vq5 = hvx_vmem(tile_src + 5 * 128); - HVX_Vector vq6 = hvx_vmem(tile_src + 6 * 128); - HVX_Vector vq7 = hvx_vmem(tile_src + 7 * 128); - - HVX_VectorPair vp_int16_4 = Q6_Wh_vunpack_Vb(vq4); - HVX_VectorPair vp_int16_5 = Q6_Wh_vunpack_Vb(vq5); - HVX_VectorPair vp_int16_6 = Q6_Wh_vunpack_Vb(vq6); - HVX_VectorPair vp_int16_7 = Q6_Wh_vunpack_Vb(vq7); - - // Convert and scale multiply for groups 0-3 - HVX_Vector v_grp0_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_0)), v_scale_duplicated)); - HVX_Vector v_grp0_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_0)), v_scale_duplicated)); - HVX_Vector v_grp1_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_1)), v_scale_duplicated)); - HVX_Vector v_grp1_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_1)), v_scale_duplicated)); - HVX_Vector v_grp2_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_2)), v_scale_duplicated)); - HVX_Vector v_grp2_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_2)), v_scale_duplicated)); - HVX_Vector v_grp3_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_3)), v_scale_duplicated)); - HVX_Vector v_grp3_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_3)), v_scale_duplicated)); - - // Store groups 0-3 - hvx_vmem(dst_ptr + 0 * 64) = v_grp0_0; - hvx_vmem(dst_ptr + 1 * 64) = v_grp0_1; - hvx_vmem(dst_ptr + 2 * 64) = v_grp1_0; - hvx_vmem(dst_ptr + 3 * 64) = v_grp1_1; - hvx_vmem(dst_ptr + 4 * 64) = v_grp2_0; - hvx_vmem(dst_ptr + 5 * 64) = v_grp2_1; - hvx_vmem(dst_ptr + 6 * 64) = v_grp3_0; - hvx_vmem(dst_ptr + 7 * 64) = v_grp3_1; - - // Convert and scale multiply for groups 4-7 - HVX_Vector v_grp4_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_4)), v_scale_duplicated)); - HVX_Vector v_grp4_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_4)), v_scale_duplicated)); - HVX_Vector v_grp5_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_5)), v_scale_duplicated)); - HVX_Vector v_grp5_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_5)), v_scale_duplicated)); - HVX_Vector v_grp6_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_6)), v_scale_duplicated)); - HVX_Vector v_grp6_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_6)), v_scale_duplicated)); - HVX_Vector v_grp7_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_7)), v_scale_duplicated)); - HVX_Vector v_grp7_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_7)), v_scale_duplicated)); - - // Store groups 4-7 - hvx_vmem(dst_ptr + 8 * 64) = v_grp4_0; - hvx_vmem(dst_ptr + 9 * 64) = v_grp4_1; - hvx_vmem(dst_ptr + 10 * 64) = v_grp5_0; - hvx_vmem(dst_ptr + 11 * 64) = v_grp5_1; - hvx_vmem(dst_ptr + 12 * 64) = v_grp6_0; - hvx_vmem(dst_ptr + 13 * 64) = v_grp6_1; - hvx_vmem(dst_ptr + 14 * 64) = v_grp7_0; - hvx_vmem(dst_ptr + 15 * 64) = v_grp7_1; - } -} - -static void dequantize_tiled_weight_to_fp16_task_q5_k( - const tiled_dequantize_state_t *state, - uint32_t start_tile, uint32_t end_tile) { - - const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F); - - for (uint32_t t = start_tile; t < end_tile; t++) { - const uint8_t * tile_src = state->src + t * state->aligned_tile_size; - __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS; - - HVX_Vector vscale_offset = hvx_vmem(tile_src + 512); - HVX_VectorPair dm_deal = Q6_W_vdeal_VVR(vscale_offset, vscale_offset, -2); - HVX_Vector vd = Q6_V_lo_W(dm_deal); - HVX_Vector vm = Q6_V_hi_W(dm_deal); - - HVX_Vector v_scale_duplicated = Q6_V_lo_W(Q6_W_vshuff_VVR(vd, vd, -2)); - HVX_Vector v_offset_duplicated = Q6_V_lo_W(Q6_W_vshuff_VVR(vm, vm, -2)); - - // Load all 4 groups in parallel - HVX_Vector vq0 = hvx_vmem(tile_src + 0 * 128); - HVX_Vector vq1 = hvx_vmem(tile_src + 1 * 128); - HVX_Vector vq2 = hvx_vmem(tile_src + 2 * 128); - HVX_Vector vq3 = hvx_vmem(tile_src + 3 * 128); - - // Nibble extraction - HVX_Vector v_lo0 = Q6_V_vand_VV(vq0, mask_h4); - HVX_Vector v_hi0 = Q6_Vub_vlsr_VubR(vq0, 4); - HVX_Vector v_lo1 = Q6_V_vand_VV(vq1, mask_h4); - HVX_Vector v_hi1 = Q6_Vub_vlsr_VubR(vq1, 4); - HVX_Vector v_lo2 = Q6_V_vand_VV(vq2, mask_h4); - HVX_Vector v_hi2 = Q6_Vub_vlsr_VubR(vq2, 4); - HVX_Vector v_lo3 = Q6_V_vand_VV(vq3, mask_h4); - HVX_Vector v_hi3 = Q6_Vub_vlsr_VubR(vq3, 4); - - // Q5_K: OR in the 5th bit from the plane - HVX_Vector v_plane = hvx_vmem(tile_src + 640); - v_lo0 = hvx_q5k_or_hibit(v_lo0, v_plane, 0); - v_hi0 = hvx_q5k_or_hibit(v_hi0, v_plane, 1); - v_lo1 = hvx_q5k_or_hibit(v_lo1, v_plane, 2); - v_hi1 = hvx_q5k_or_hibit(v_hi1, v_plane, 3); - v_lo2 = hvx_q5k_or_hibit(v_lo2, v_plane, 4); - v_hi2 = hvx_q5k_or_hibit(v_hi2, v_plane, 5); - v_lo3 = hvx_q5k_or_hibit(v_lo3, v_plane, 6); - v_hi3 = hvx_q5k_or_hibit(v_hi3, v_plane, 7); - - // Shuffling - HVX_VectorPair vp_shuf0 = Q6_W_vshuff_VVR(v_hi0, v_lo0, -1); - HVX_VectorPair vp_shuf1 = Q6_W_vshuff_VVR(v_hi1, v_lo1, -1); - HVX_VectorPair vp_shuf2 = Q6_W_vshuff_VVR(v_hi2, v_lo2, -1); - HVX_VectorPair vp_shuf3 = Q6_W_vshuff_VVR(v_hi3, v_lo3, -1); - - // Unpack to 16-bit - HVX_VectorPair vp_int16_lo0 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf0)); - HVX_VectorPair vp_int16_hi0 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf0)); - HVX_VectorPair vp_int16_lo1 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf1)); - HVX_VectorPair vp_int16_hi1 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf1)); - HVX_VectorPair vp_int16_lo2 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf2)); - HVX_VectorPair vp_int16_hi2 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf2)); - HVX_VectorPair vp_int16_lo3 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf3)); - HVX_VectorPair vp_int16_hi3 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf3)); - - // Convert, multiply, add offset - HVX_Vector v_grp0_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo0)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp0_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo0)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp0_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi0)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp0_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi0)), v_scale_duplicated), v_offset_duplicated)); - - HVX_Vector v_grp1_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo1)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp1_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo1)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp1_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi1)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp1_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi1)), v_scale_duplicated), v_offset_duplicated)); - - HVX_Vector v_grp2_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo2)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp2_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo2)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp2_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi2)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp2_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi2)), v_scale_duplicated), v_offset_duplicated)); - - HVX_Vector v_grp3_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo3)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp3_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo3)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp3_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi3)), v_scale_duplicated), v_offset_duplicated)); - HVX_Vector v_grp3_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi3)), v_scale_duplicated), v_offset_duplicated)); - - // Parallel Stores - hvx_vmem(dst_ptr + 0 * 64) = v_grp0_0; - hvx_vmem(dst_ptr + 1 * 64) = v_grp0_1; - hvx_vmem(dst_ptr + 2 * 64) = v_grp0_2; - hvx_vmem(dst_ptr + 3 * 64) = v_grp0_3; - - hvx_vmem(dst_ptr + 4 * 64) = v_grp1_0; - hvx_vmem(dst_ptr + 5 * 64) = v_grp1_1; - hvx_vmem(dst_ptr + 6 * 64) = v_grp1_2; - hvx_vmem(dst_ptr + 7 * 64) = v_grp1_3; - - hvx_vmem(dst_ptr + 8 * 64) = v_grp2_0; - hvx_vmem(dst_ptr + 9 * 64) = v_grp2_1; - hvx_vmem(dst_ptr + 10 * 64) = v_grp2_2; - hvx_vmem(dst_ptr + 11 * 64) = v_grp2_3; - - hvx_vmem(dst_ptr + 12 * 64) = v_grp3_0; - hvx_vmem(dst_ptr + 13 * 64) = v_grp3_1; - hvx_vmem(dst_ptr + 14 * 64) = v_grp3_2; - hvx_vmem(dst_ptr + 15 * 64) = v_grp3_3; - } -} - -static void dequantize_tiled_weight_to_fp16_task_q5_0( - const tiled_dequantize_state_t *state, - uint32_t start_tile, uint32_t end_tile) { - - const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F); - - for (uint32_t t = start_tile; t < end_tile; t++) { - const uint8_t * tile_src = state->src + t * state->aligned_tile_size; - __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS; - - HVX_Vector v_sc = hvx_vmem(tile_src + 640); - HVX_Vector v_scale_duplicated = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); - - // Load all 4 groups in parallel - HVX_Vector vq0 = hvx_vmem(tile_src + 0 * 128); - HVX_Vector vq1 = hvx_vmem(tile_src + 1 * 128); - HVX_Vector vq2 = hvx_vmem(tile_src + 2 * 128); - HVX_Vector vq3 = hvx_vmem(tile_src + 3 * 128); - - // Nibble extraction - HVX_Vector v_lo0 = Q6_V_vand_VV(vq0, mask_h4); - HVX_Vector v_hi0 = Q6_Vub_vlsr_VubR(vq0, 4); - HVX_Vector v_lo1 = Q6_V_vand_VV(vq1, mask_h4); - HVX_Vector v_hi1 = Q6_Vub_vlsr_VubR(vq1, 4); - HVX_Vector v_lo2 = Q6_V_vand_VV(vq2, mask_h4); - HVX_Vector v_hi2 = Q6_Vub_vlsr_VubR(vq2, 4); - HVX_Vector v_lo3 = Q6_V_vand_VV(vq3, mask_h4); - HVX_Vector v_hi3 = Q6_Vub_vlsr_VubR(vq3, 4); - - // Q5_0: OR 0xF0 where the plane flags a clear 5th bit (q - 16) - HVX_Vector v_plane = hvx_vmem(tile_src + 512); - v_lo0 = hvx_q5_0_or_neg(v_lo0, v_plane, 0); - v_hi0 = hvx_q5_0_or_neg(v_hi0, v_plane, 1); - v_lo1 = hvx_q5_0_or_neg(v_lo1, v_plane, 2); - v_hi1 = hvx_q5_0_or_neg(v_hi1, v_plane, 3); - v_lo2 = hvx_q5_0_or_neg(v_lo2, v_plane, 4); - v_hi2 = hvx_q5_0_or_neg(v_hi2, v_plane, 5); - v_lo3 = hvx_q5_0_or_neg(v_lo3, v_plane, 6); - v_hi3 = hvx_q5_0_or_neg(v_hi3, v_plane, 7); - - // Shuffling - HVX_VectorPair vp_shuf0 = Q6_W_vshuff_VVR(v_hi0, v_lo0, -1); - HVX_VectorPair vp_shuf1 = Q6_W_vshuff_VVR(v_hi1, v_lo1, -1); - HVX_VectorPair vp_shuf2 = Q6_W_vshuff_VVR(v_hi2, v_lo2, -1); - HVX_VectorPair vp_shuf3 = Q6_W_vshuff_VVR(v_hi3, v_lo3, -1); - - // Unpack to 16-bit - HVX_VectorPair vp_int16_lo0 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf0)); - HVX_VectorPair vp_int16_hi0 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf0)); - HVX_VectorPair vp_int16_lo1 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf1)); - HVX_VectorPair vp_int16_hi1 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf1)); - HVX_VectorPair vp_int16_lo2 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf2)); - HVX_VectorPair vp_int16_hi2 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf2)); - HVX_VectorPair vp_int16_lo3 = Q6_Wh_vunpack_Vb(Q6_V_lo_W(vp_shuf3)); - HVX_VectorPair vp_int16_hi3 = Q6_Wh_vunpack_Vb(Q6_V_hi_W(vp_shuf3)); - - // Convert and scale multiplication - HVX_Vector v_grp0_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo0)), v_scale_duplicated)); - HVX_Vector v_grp0_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo0)), v_scale_duplicated)); - HVX_Vector v_grp0_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi0)), v_scale_duplicated)); - HVX_Vector v_grp0_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi0)), v_scale_duplicated)); - - HVX_Vector v_grp1_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo1)), v_scale_duplicated)); - HVX_Vector v_grp1_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo1)), v_scale_duplicated)); - HVX_Vector v_grp1_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi1)), v_scale_duplicated)); - HVX_Vector v_grp1_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi1)), v_scale_duplicated)); - - HVX_Vector v_grp2_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo2)), v_scale_duplicated)); - HVX_Vector v_grp2_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo2)), v_scale_duplicated)); - HVX_Vector v_grp2_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi2)), v_scale_duplicated)); - HVX_Vector v_grp2_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi2)), v_scale_duplicated)); - - HVX_Vector v_grp3_0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_lo3)), v_scale_duplicated)); - HVX_Vector v_grp3_1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_lo3)), v_scale_duplicated)); - HVX_Vector v_grp3_2 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_int16_hi3)), v_scale_duplicated)); - HVX_Vector v_grp3_3 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_int16_hi3)), v_scale_duplicated)); - - // Parallel Stores - hvx_vmem(dst_ptr + 0 * 64) = v_grp0_0; - hvx_vmem(dst_ptr + 1 * 64) = v_grp0_1; - hvx_vmem(dst_ptr + 2 * 64) = v_grp0_2; - hvx_vmem(dst_ptr + 3 * 64) = v_grp0_3; - - hvx_vmem(dst_ptr + 4 * 64) = v_grp1_0; - hvx_vmem(dst_ptr + 5 * 64) = v_grp1_1; - hvx_vmem(dst_ptr + 6 * 64) = v_grp1_2; - hvx_vmem(dst_ptr + 7 * 64) = v_grp1_3; - - hvx_vmem(dst_ptr + 8 * 64) = v_grp2_0; - hvx_vmem(dst_ptr + 9 * 64) = v_grp2_1; - hvx_vmem(dst_ptr + 10 * 64) = v_grp2_2; - hvx_vmem(dst_ptr + 11 * 64) = v_grp2_3; - - hvx_vmem(dst_ptr + 12 * 64) = v_grp3_0; - hvx_vmem(dst_ptr + 13 * 64) = v_grp3_1; - hvx_vmem(dst_ptr + 14 * 64) = v_grp3_2; - hvx_vmem(dst_ptr + 15 * 64) = v_grp3_3; - } -} - -// Q6_K stores 6-bit weights and one fp16 scale per 16 k, see HTP_TENSOR_TILE_SIZE_Q6_K. -// A k-group holds 4 k per row, the HMX tile holds 2, so each group is dealt into two tiles. -static void dequantize_tiled_weight_to_fp16_task_q6_k( - const tiled_dequantize_state_t *state, - uint32_t start_tile, uint32_t end_tile) { - - const HVX_Vector mask_0f = Q6_Vb_vsplat_R(0x0F); - const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03); - const HVX_Vector i32 = Q6_Vb_vsplat_R(32); - - for (uint32_t t = start_tile; t < end_tile; t++) { - const HVX_Vector * vptr = (const HVX_Vector *) (state->src + t * state->aligned_tile_size); - __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS; - - HVX_Vector v_sc = vptr[6]; - HVX_Vector v_sc_k16 = Q6_V_vror_VR(v_sc, 64); - HVX_Vector v_scale_k0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); - HVX_Vector v_scale_k16 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc_k16, v_sc_k16, -2)); - - #pragma unroll - for (int g = 0; g < 8; g += 4) { - const HVX_Vector v_scale = (g < 4) ? v_scale_k0 : v_scale_k16; - - HVX_Vector v_q0 = unpack_q6_k_group(vptr, g + 0, mask_0f, mask_03, i32); - HVX_Vector v_q1 = unpack_q6_k_group(vptr, g + 1, mask_0f, mask_03, i32); - HVX_Vector v_q2 = unpack_q6_k_group(vptr, g + 2, mask_0f, mask_03, i32); - HVX_Vector v_q3 = unpack_q6_k_group(vptr, g + 3, mask_0f, mask_03, i32); - - HVX_VectorPair vp16_0 = Q6_Wh_vunpack_Vb(v_q0); - HVX_VectorPair vp16_1 = Q6_Wh_vunpack_Vb(v_q1); - HVX_VectorPair vp16_2 = Q6_Wh_vunpack_Vb(v_q2); - HVX_VectorPair vp16_3 = Q6_Wh_vunpack_Vb(v_q3); - HVX_VectorPair vp_k0 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16_0), Q6_V_lo_W(vp16_0), -4); - HVX_VectorPair vp_k1 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16_1), Q6_V_lo_W(vp16_1), -4); - HVX_VectorPair vp_k2 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16_2), Q6_V_lo_W(vp16_2), -4); - HVX_VectorPair vp_k3 = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16_3), Q6_V_lo_W(vp16_3), -4); - - HVX_Vector v_out00 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k0)), v_scale)); - HVX_Vector v_out01 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k0)), v_scale)); - HVX_Vector v_out10 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k1)), v_scale)); - HVX_Vector v_out11 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k1)), v_scale)); - HVX_Vector v_out20 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k2)), v_scale)); - HVX_Vector v_out21 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k2)), v_scale)); - HVX_Vector v_out30 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k3)), v_scale)); - HVX_Vector v_out31 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k3)), v_scale)); - - hvx_vmem(dst_ptr + (2 * g + 0) * 64) = v_out00; - hvx_vmem(dst_ptr + (2 * g + 1) * 64) = v_out01; - hvx_vmem(dst_ptr + (2 * g + 2) * 64) = v_out10; - hvx_vmem(dst_ptr + (2 * g + 3) * 64) = v_out11; - hvx_vmem(dst_ptr + (2 * g + 4) * 64) = v_out20; - hvx_vmem(dst_ptr + (2 * g + 5) * 64) = v_out21; - hvx_vmem(dst_ptr + (2 * g + 6) * 64) = v_out30; - hvx_vmem(dst_ptr + (2 * g + 7) * 64) = v_out31; - } - } -} - -#define NVFP4_UE4M3_F16_MAN_SHIFT 7 // 10 - 3 mantissa bits -#define NVFP4_UE4M3_F16_REBIAS 0x2000 // (15 - 7) << 10 -#define NVFP4_UE4M3_F16_SUB_SCALE 0x1800 // 2^-9 as fp16 bits -#define IQ2XXS_D_SCALE_F16 0x3000 // 0.125 as fp16 bits - -// UE4M3 codes in the low byte of each halfword -> fp16 -static inline HVX_Vector nvfp4_ue4m3_to_f16(HVX_Vector v_code) { - HVX_Vector v_mask = Q6_Vh_vsplat_R(NVFP4_UE4M3_MASK); - HVX_Vector v_x = Q6_V_vand_VV(v_code, v_mask); - - HVX_Vector v_norm = Q6_Vh_vadd_VhVh(Q6_Vh_vasl_VhR(v_x, NVFP4_UE4M3_F16_MAN_SHIFT), Q6_Vh_vsplat_R(NVFP4_UE4M3_F16_REBIAS)); - HVX_Vector v_sub = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(v_x), Q6_Vh_vsplat_R(NVFP4_UE4M3_F16_SUB_SCALE))); - - HVX_VectorPred q_sub = Q6_Q_vcmp_gt_VhVh(Q6_Vh_vsplat_R(NVFP4_UE4M3_MIN_NORMAL), v_x); - HVX_VectorPred q_nan = Q6_Q_vcmp_eq_VhVh(v_x, v_mask); - - return Q6_V_vmux_QVV(q_nan, Q6_V_vzero(), Q6_V_vmux_QVV(q_sub, v_sub, v_norm)); -} - -// NVFP4 tiles are MXFP4 quants with one UE4M3 scale per 16 k (sub-block 0: k 0..15, sub-block 1: k 16..31) -static void dequantize_tiled_weight_to_fp16_task_nvfp4( - const tiled_dequantize_state_t *state, - uint32_t start_tile, uint32_t end_tile) { - - const HVX_Vector mask_h4 = Q6_Vb_vsplat_R(0x0F); - const HVX_Vector vlut_cvt = hvx_vmem(mxfp4_to_fp16_lut); - - for (uint32_t t = start_tile; t < end_tile; t++) { - const uint8_t * tile_src = state->src + t * state->aligned_tile_size; - __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS; - - HVX_Vector v_d = nvfp4_ue4m3_to_f16(Q6_V_lo_W(Q6_Wuh_vunpack_Vub(hvx_vmem(tile_src + NVFP4_SCALE_OFF)))); - HVX_VectorPair vp_d = Q6_W_vshuff_VVR(v_d, v_d, -2); - HVX_Vector v_scale_k0 = Q6_V_lo_W(vp_d); - HVX_Vector v_scale_k16 = Q6_V_hi_W(vp_d); - - #pragma unroll - for (int g = 0; g < 4; g++) { - const HVX_Vector v_scale = (g < 2) ? v_scale_k0 : v_scale_k16; - - HVX_Vector vq = hvx_vmem(tile_src + g * 128); - HVX_Vector v_lo = Q6_V_vand_VV(vq, mask_h4); - HVX_Vector v_hi = Q6_Vub_vlsr_VubR(vq, 4); - - HVX_VectorPair vp_shuf = Q6_W_vshuff_VVR(v_hi, v_lo, -1); - HVX_VectorPair vp_lo = Q6_Wh_vlut16_VbVhR(Q6_Vb_vshuff_Vb(Q6_V_lo_W(vp_shuf)), vlut_cvt, 0); - HVX_VectorPair vp_hi = Q6_Wh_vlut16_VbVhR(Q6_Vb_vshuff_Vb(Q6_V_hi_W(vp_shuf)), vlut_cvt, 0); - - hvx_vmem(dst_ptr + (4 * g + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_lo), v_scale)); - hvx_vmem(dst_ptr + (4 * g + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_lo), v_scale)); - hvx_vmem(dst_ptr + (4 * g + 2) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_lo_W(vp_hi), v_scale)); - hvx_vmem(dst_ptr + (4 * g + 3) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_V_hi_W(vp_hi), v_scale)); - } - } -} - -// IQ2_XXS: int8 grid weights from the VTCM LUT, scaled by d / 8 * (2 * scale + 1) per row -static void dequantize_tiled_weight_to_fp16_task_iq2_xxs( - const tiled_dequantize_state_t *state, - uint32_t start_tile, uint32_t end_tile) { - - HVX_Vector v_d = Q6_V_vzero(); - const HVX_Vector v_eighth = Q6_Vh_vsplat_R(IQ2XXS_D_SCALE_F16); - - HVX_Vector v_sgn = Q6_V_vzero(); - if (start_tile < end_tile) { - v_sgn = iq2xxs_gather_issue(state->src + start_tile * state->aligned_tile_size); - } - - for (uint32_t t = start_tile; t < end_tile; t++) { - const uint8_t * tile = state->src + t * state->aligned_tile_size; - __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS; - - // rows hold all k tiles and n_k_tiles is a multiple of 8, so t % 8 is the tile within its super-block - if (t == start_tile || (t & (IQ2XXS_TILES_PER_SB - 1)) == 0) { - v_d = iq2xxs_gather_d(tile - (t & (IQ2XXS_TILES_PER_SB - 1)) * state->aligned_tile_size); - } - - HVX_Vector v_c[2], v_w[2 * IQ2XXS_GROUPS], v_ls; - iq2xxs_gather_wait(tile, v_c); - const HVX_Vector v_sgn_cur = v_sgn; - if (t + 1 < end_tile) { - v_sgn = iq2xxs_gather_issue(tile + state->aligned_tile_size); - } - iq2xxs_decode_expand(v_c, v_sgn_cur, v_w, &v_ls); - - HVX_Vector v_ls_h = Q6_Vhf_equals_Vh(Q6_Vh_vpacke_VwVw(v_ls, v_ls)); - HVX_Vector v_sc = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(v_d, v_ls_h)); - HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); - - #pragma unroll - for (int g = 0; g < 2 * IQ2XXS_GROUPS; g++) { - HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_w[g]); - HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4); - - // d / 8 is subnormal in fp16 for real weights, so apply the 1/8 after the multiply by d * ls - HVX_Vector v_lo = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale)); - HVX_Vector v_hi = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale)); - hvx_vmem(dst_ptr + (2 * g + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(v_lo, v_eighth)); - hvx_vmem(dst_ptr + (2 * g + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(v_hi, v_eighth)); - } - } -} - -// Q3_K stores 3-bit weights and one fp16 scale per 16 k, see HTP_TENSOR_TILE_SIZE_Q3_K. -static void dequantize_tiled_weight_to_fp16_task_q3_k( - const tiled_dequantize_state_t *state, - uint32_t start_tile, uint32_t end_tile) { - - const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03); - - for (uint32_t t = start_tile; t < end_tile; t++) { - const HVX_Vector * vptr = (const HVX_Vector *) (state->src + t * state->aligned_tile_size); - __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS; - - HVX_Vector v_sc = vptr[3]; - HVX_Vector v_sc_k16 = Q6_V_vror_VR(v_sc, 64); - HVX_Vector v_scale_k0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); - HVX_Vector v_scale_k16 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc_k16, v_sc_k16, -2)); - - #pragma unroll - for (int g = 0; g < 8; g++) { - const HVX_Vector v_scale = (g < 4) ? v_scale_k0 : v_scale_k16; - - HVX_Vector v_q = unpack_q3_k_group(vptr, g, mask_03); - HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_q); - HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4); - - hvx_vmem(dst_ptr + (2 * g + 0) * 64) = - Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale)); - hvx_vmem(dst_ptr + (2 * g + 1) * 64) = - Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale)); - } - } -} - -// Q2_K stores 2-bit weights, the ggml scale bytes and d / -dmin per super-block, see HTP_TENSOR_TILE_SIZE_Q2_K. -static void dequantize_tiled_weight_to_fp16_task_q2_k( - const tiled_dequantize_state_t *state, - uint32_t start_tile, uint32_t end_tile) { - - const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03); - - HVX_Vector v_d = Q6_V_vzero(); - HVX_Vector v_dm = Q6_V_vzero(); - - for (uint32_t t = start_tile; t < end_tile; t++) { - const uint8_t * tile = state->src + t * state->aligned_tile_size; - const HVX_Vector * vptr = (const HVX_Vector *) tile; - __fp16 * dst_ptr = state->dst + t * HTP_MM_HMX_TILE_N_ELMS; - - // rows hold all k tiles and n_k_tiles is a multiple of 8, so t % 8 is the tile within its super-block - if (t == start_tile || (t & 7) == 0) { - q2_k_load_dmin(tile - (t & 7) * state->aligned_tile_size, &v_d, &v_dm); - } - - HVX_Vector v_sc, v_m; - q2_k_unpack_scales(tile, v_d, v_dm, &v_sc, &v_m); - HVX_Vector v_sc_k16 = Q6_V_vror_VR(v_sc, 64); - HVX_Vector v_m_k16 = Q6_V_vror_VR(v_m, 64); - HVX_Vector v_scale_k0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); - HVX_Vector v_scale_k16 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc_k16, v_sc_k16, -2)); - HVX_Vector v_offset_k0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_m, v_m, -2)); - HVX_Vector v_offset_k16 = Q6_V_lo_W(Q6_W_vshuff_VVR(v_m_k16, v_m_k16, -2)); - - #pragma unroll - for (int g = 0; g < 8; g++) { - const HVX_Vector v_scale = (g < 4) ? v_scale_k0 : v_scale_k16; - const HVX_Vector v_offset = (g < 4) ? v_offset_k0 : v_offset_k16; - - HVX_Vector v_q = unpack_q3_k_low2(vptr, g, mask_03); - HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_q); - HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4); - - hvx_vmem(dst_ptr + (2 * g + 0) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf( - Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale), v_offset)); - hvx_vmem(dst_ptr + (2 * g + 1) * 64) = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_Vqf16Vhf( - Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale), v_offset)); - } - } -} - -// Q2_0 stores codes 0..3 (value code - 1) and one fp16 scale per row, see HTP_MM_WEIGHT_TILE_SIZE_Q2_0. -// One packed 64-k tile expands into two consecutive 32-k fp16 tiles. -static void dequantize_tiled_weight_to_fp16_task_q2_0( - const tiled_dequantize_state_t *state, - uint32_t start_tile, uint32_t end_tile) { - - const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03); - const HVX_Vector i1 = Q6_Vb_vsplat_R(1); - - for (uint32_t t = start_tile; t < end_tile; t++) { - const HVX_Vector * vptr = (const HVX_Vector *) (state->src + t * state->aligned_tile_size); - __fp16 * dst_base = state->dst + 2 * t * HTP_MM_HMX_TILE_N_ELMS; - - HVX_Vector v_sc = vptr[4]; - HVX_Vector v_scale = Q6_V_lo_W(Q6_W_vshuff_VVR(v_sc, v_sc, -2)); - - for (int half = 0; half < 2; half++) { - __fp16 * dst_ptr = dst_base + half * HTP_MM_HMX_TILE_N_ELMS; - - #pragma unroll - for (int g = 0; g < 8; g++) { - HVX_Vector v_q = Q6_Vb_vsub_VbVb(unpack_q3_k_low2(vptr + 2 * half, g, mask_03), i1); - HVX_VectorPair vp16 = Q6_Wh_vunpack_Vb(v_q); - HVX_VectorPair vp_k = Q6_W_vdeal_VVR(Q6_V_hi_W(vp16), Q6_V_lo_W(vp16), -4); - - hvx_vmem(dst_ptr + (2 * g + 0) * 64) = - Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(vp_k)), v_scale)); - hvx_vmem(dst_ptr + (2 * g + 1) * 64) = - Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(vp_k)), v_scale)); - } - } - } -} - -static __attribute__((noinline)) -void convert_f16_weight_to_fp16_tiles_task( - const tiled_dequantize_state_t *state, - uint32_t start_tile, uint32_t end_tile) { - - const uint32_t n_k_tiles = state->n_k_tiles; - const struct fastdiv_values n_k_tiles_div = state->n_k_tiles_div; - - const HVX_Vector v_scat_base = hvx_vmem(hmx_transpose_scatter_offsets); - const HVX_Vector v_scat_step = Q6_V_vsplat_R(4); - const HVX_VectorPred q_mask64 = Q6_Q_vsetq_R(64); - - unsigned ct = fastdiv((unsigned)start_tile, &n_k_tiles_div); - unsigned kt = fastmodulo((unsigned)start_tile, n_k_tiles, &n_k_tiles_div); - - for (unsigned t = start_tile; t < (unsigned)end_tile; ) { - if (kt >= (unsigned)n_k_tiles) { kt = 0; ct++; } - - __fp16 *tile_base = state->dst + t * HTP_MM_HMX_TILE_N_ELMS; - { - uint32_t byte_off = kt * 32 * sizeof(__fp16); - - HVX_Vector v_off = v_scat_base; - for (uint32_t r = 0; r < HTP_MM_HMX_TILE_N_ROWS; r += 2) { - uint32_t row0 = ct * HTP_MM_HMX_TILE_N_COLS + r; - uint32_t row1 = row0 + 1; - - const uint8_t *r0 = state->src + row0 * state->row_stride; - const uint8_t *r1 = state->src + row1 * state->row_stride; - - HVX_Vector v0 = (row0 < state->n_cols) ? hvx_vmemu((const __fp16 *)(r0 + byte_off)) : Q6_V_vzero(); - HVX_Vector v1 = (row1 < state->n_cols) ? hvx_vmemu((const __fp16 *)(r1 + byte_off)) : Q6_V_vzero(); - - Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v0); - v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step); - Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v1); - v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step); - } - } - ++t; ++kt; - } -} - -static __attribute__((noinline)) -void quantize_f32_weight_to_fp16_tiles_task( - const tiled_dequantize_state_t *state, - uint32_t start_tile, uint32_t end_tile) { - - const uint32_t n_k_tiles = state->n_k_tiles; - const struct fastdiv_values n_k_tiles_div = state->n_k_tiles_div; - - const HVX_Vector v_scat_base = hvx_vmem(hmx_transpose_scatter_offsets); - const HVX_Vector v_scat_step = Q6_V_vsplat_R(4); - const HVX_VectorPred q_mask64 = Q6_Q_vsetq_R(64); - - unsigned ct = fastdiv((unsigned)start_tile, &n_k_tiles_div); - unsigned kt = fastmodulo((unsigned)start_tile, n_k_tiles, &n_k_tiles_div); - - for (unsigned t = start_tile; t < (unsigned)end_tile; ) { - if (kt >= (unsigned)n_k_tiles) { kt = 0; ct++; } - - __fp16 *tile_base = state->dst + t * HTP_MM_HMX_TILE_N_ELMS; - { - uint32_t byte_off = kt * 32 * sizeof(float); - - HVX_Vector v_off = v_scat_base; - for (uint32_t r = 0; r < HTP_MM_HMX_TILE_N_ROWS; r += 2) { - uint32_t row0 = ct * HTP_MM_HMX_TILE_N_COLS + r; - uint32_t row1 = row0 + 1; - - const uint8_t *r0 = state->src + row0 * state->row_stride; - const uint8_t *r1 = state->src + row1 * state->row_stride; - - HVX_Vector v0_f32 = (row0 < state->n_cols) ? hvx_vmem((const float *)(r0 + byte_off)) : Q6_V_vzero(); - HVX_Vector v1_f32 = (row1 < state->n_cols) ? hvx_vmem((const float *)(r1 + byte_off)) : Q6_V_vzero(); - - HVX_Vector v_out = hvx_vec_f32_to_f16(v0_f32, v1_f32); - - Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v_out); - v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step); - - HVX_Vector v_out_hi = Q6_V_vror_VR(v_out, 64); - Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v_out_hi); - v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step); - } - } - ++t; ++kt; - } -} - -static __attribute__((noinline)) -void convert_bf16_weight_to_fp16_tiles_task( - const tiled_dequantize_state_t *state, - uint32_t start_tile, uint32_t end_tile) { - - const uint32_t n_k_tiles = state->n_k_tiles; - const struct fastdiv_values n_k_tiles_div = state->n_k_tiles_div; - - const HVX_Vector v_scat_base = hvx_vmem(hmx_transpose_scatter_offsets); - const HVX_Vector v_scat_step = Q6_V_vsplat_R(4); - const HVX_VectorPred q_mask64 = Q6_Q_vsetq_R(64); - - unsigned ct = fastdiv((unsigned)start_tile, &n_k_tiles_div); - unsigned kt = fastmodulo((unsigned)start_tile, n_k_tiles, &n_k_tiles_div); - - for (unsigned t = start_tile; t < (unsigned)end_tile; ) { - if (kt >= (unsigned)n_k_tiles) { kt = 0; ct++; } - - __fp16 *tile_base = state->dst + t * HTP_MM_HMX_TILE_N_ELMS; - { - uint32_t byte_off = kt * 32 * sizeof(uint16_t); - - HVX_Vector v_off = v_scat_base; - for (uint32_t r = 0; r < HTP_MM_HMX_TILE_N_ROWS; r += 2) { - uint32_t row0 = ct * HTP_MM_HMX_TILE_N_COLS + r; - uint32_t row1 = row0 + 1; - - const uint8_t *r0 = state->src + row0 * state->row_stride; - const uint8_t *r1 = state->src + row1 * state->row_stride; - - HVX_Vector v0_raw = (row0 < state->n_cols) ? hvx_vmemu((const void *)(r0 + byte_off)) : Q6_V_vzero(); - HVX_Vector v1_raw = (row1 < state->n_cols) ? hvx_vmemu((const void *)(r1 + byte_off)) : Q6_V_vzero(); - - HVX_Vector v0_f32 = Q6_Vw_vasl_VwR(Q6_V_lo_W(Q6_Ww_vunpack_Vh(v0_raw)), 16); - HVX_Vector v1_f32 = Q6_Vw_vasl_VwR(Q6_V_lo_W(Q6_Ww_vunpack_Vh(v1_raw)), 16); - - HVX_Vector v_out = hvx_vec_f32_to_f16(v0_f32, v1_f32); - - Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v_out); - v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step); - - HVX_Vector v_out_hi = Q6_V_vror_VR(v_out, 64); - Q6_vscatter_QRMVwV(q_mask64, (size_t)tile_base, HTP_MM_HMX_TILE_SIZE - 1, v_off, v_out_hi); - v_off = Q6_Vw_vadd_VwVw(v_off, v_scat_step); - } - } - ++t; ++kt; - } -} - -// --- End tiled dequantizers --- - -// dot-chunk functions require external HMX lock - -static void core_dot_chunk_fp16_short(__fp16 *restrict output, const __fp16 *restrict activation, - const __fp16 *restrict weight, const __fp16 *restrict scales, - uint32_t n_row_tiles, uint32_t n_col_tiles, uint32_t n_dot_tiles) { - __builtin_assume(n_row_tiles > 0); - __builtin_assume(n_col_tiles > 0); - __builtin_assume(n_dot_tiles > 0); - __builtin_assume(n_dot_tiles <= 32); - - asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int)scales)); - - const size_t dot_stride = n_dot_tiles * HTP_MM_HMX_TILE_N_ELMS; - const uint32_t range = 2048u * n_dot_tiles - 1; - - for (uint32_t r = 0; r < n_row_tiles; ++r) { - const __fp16 *row_base = activation + r * dot_stride; - const __fp16 *col_base = weight; - __fp16 *out_tile = output + r * n_col_tiles * HTP_MM_HMX_TILE_N_ELMS; - - for (size_t c = 0; c < n_col_tiles; ++c) { - asm volatile(HMX_CLRACC_F16()); - asm volatile(HMX_LOAD_MPY_DEEP_F16("%1", "%2", "%0") : : "r"(range), "r"(row_base), "r"(col_base)); - asm volatile(HMX_STORE_AFTER_F16("%0", "%1") : : "r"(out_tile), "r"(0) : "memory"); - col_base += dot_stride; - out_tile += HTP_MM_HMX_TILE_N_ELMS; - } - } -} - -static void core_dot_chunk_fp16(__fp16 *restrict output, const __fp16 *restrict activation, - const __fp16 *restrict weight, const __fp16 *restrict scales, - uint32_t n_row_tiles, uint32_t n_col_tiles, uint32_t n_dot_tiles) { - if (n_dot_tiles <= 32) { - core_dot_chunk_fp16_short(output, activation, weight, scales, n_row_tiles, n_col_tiles, n_dot_tiles); - return; - } - __builtin_assume(n_row_tiles > 0); - __builtin_assume(n_col_tiles > 0); - __builtin_assume(n_dot_tiles > 32); - - asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int)scales)); - - const size_t dot_stride = n_dot_tiles * HTP_MM_HMX_TILE_N_ELMS; - - for (uint32_t r = 0; r < n_row_tiles; ++r) { - const __fp16 *row_base = activation + r * dot_stride; - const __fp16 *col_base = weight; - __fp16 *out_tile = output + r * n_col_tiles * HTP_MM_HMX_TILE_N_ELMS; - - for (size_t c = 0; c < n_col_tiles; ++c) { - const __fp16 *row_tiles = row_base; - const __fp16 *col_tiles = col_base; - - asm volatile(HMX_CLRACC_F16()); - - const uint32_t n_loops = n_dot_tiles / 32; - const uint32_t rem = n_dot_tiles % 32; - - for (uint32_t l = 0; l < n_loops; ++l) { - asm volatile(HMX_LOAD_MPY_DEEP_F16("%1", "%2", "%0") : : "r"(65535), "r"(row_tiles), "r"(col_tiles)); - row_tiles += 32 * HTP_MM_HMX_TILE_N_ELMS; - col_tiles += 32 * HTP_MM_HMX_TILE_N_ELMS; - } - - if (rem > 0) { - const uint32_t range = 2048u * rem - 1; - asm volatile(HMX_LOAD_MPY_DEEP_F16("%1", "%2", "%0") : : "r"(range), "r"(row_tiles), "r"(col_tiles)); - } - - asm volatile(HMX_STORE_AFTER_F16("%0", "%1") : : "r"(out_tile), "r"(0) : "memory"); - - col_base += dot_stride; - out_tile += HTP_MM_HMX_TILE_N_ELMS; - } - } -} - -static void core_mma_chunk_fp16_short(__fp16 *restrict c, const __fp16 *restrict a, const __fp16 *restrict b, - const __fp16 *restrict col_scales, const __fp16 *restrict eye_tile, - uint32_t n_row_tiles, uint32_t n_col_tiles, uint32_t n_dot_tiles, bool zero_init) { - __builtin_assume(n_row_tiles > 0); - __builtin_assume(n_col_tiles > 0); - __builtin_assume(n_dot_tiles > 0); - __builtin_assume(n_dot_tiles <= 32); - - asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int)col_scales)); - - const size_t dot_tile_stride = n_dot_tiles * HTP_MM_HMX_TILE_N_ELMS; - const uint32_t range = 2048u * n_dot_tiles - 1; - - for (size_t i = 0; i < n_row_tiles; ++i) { - const __fp16 *row_base = a + i * dot_tile_stride; - __fp16 *res_base = c + i * n_col_tiles * HTP_MM_HMX_TILE_N_ELMS; - const __fp16 *col_base = b; - __fp16 *accum_tile = res_base; - - for (size_t j = 0; j < n_col_tiles; ++j) { - asm volatile(HMX_CLRACC_F16()); - - if (!zero_init) { - asm volatile(HMX_LOAD_MPY_F16("%1", "%2", "%0") : : "r"(2047), "r"(accum_tile), "r"(eye_tile)); - } - - asm volatile(HMX_LOAD_MPY_DEEP_F16("%1", "%2", "%0") : : "r"(range), "r"(row_base), "r"(col_base)); - - asm volatile(HMX_STORE_AFTER_F16("%0", "%1") : : "r"(accum_tile), "r"(0) : "memory"); - - col_base += dot_tile_stride; - accum_tile += HTP_MM_HMX_TILE_N_ELMS; - } - } -} - -static void core_mma_chunk_fp16(__fp16 *restrict c, const __fp16 *restrict a, const __fp16 *restrict b, - const __fp16 *restrict col_scales, const __fp16 *restrict eye_tile, - uint32_t n_row_tiles, uint32_t n_col_tiles, uint32_t n_dot_tiles, bool zero_init) { - if (n_dot_tiles <= 32) { - core_mma_chunk_fp16_short(c, a, b, col_scales, eye_tile, n_row_tiles, n_col_tiles, n_dot_tiles, zero_init); - return; - } - __builtin_assume(n_row_tiles > 0); - __builtin_assume(n_col_tiles > 0); - __builtin_assume(n_dot_tiles > 32); - - asm volatile(HMX_SET_BIAS("%0") :: "r"((unsigned int)col_scales)); - - const size_t dot_tile_stride = n_dot_tiles * HTP_MM_HMX_TILE_N_ELMS; - - for (size_t i = 0; i < n_row_tiles; ++i) { - const __fp16 *row_base = a + i * dot_tile_stride; - __fp16 *res_base = c + i * n_col_tiles * HTP_MM_HMX_TILE_N_ELMS; - const __fp16 *col_base = b; - __fp16 *accum_tile = res_base; - - for (size_t j = 0; j < n_col_tiles; ++j) { - const __fp16 *col_tiles = col_base; - const __fp16 *row_tiles = row_base; - - asm volatile(HMX_CLRACC_F16()); - - if (!zero_init) { - asm volatile(HMX_LOAD_MPY_F16("%1", "%2", "%0") : : "r"(2047), "r"(accum_tile), "r"(eye_tile)); - } - - const uint32_t n_loops = n_dot_tiles / 32; - const uint32_t rem = n_dot_tiles % 32; - - for (uint32_t l = 0; l < n_loops; ++l) { - asm volatile(HMX_LOAD_MPY_DEEP_F16("%1", "%2", "%0") : : "r"(65535), "r"(row_tiles), "r"(col_tiles)); - row_tiles += 32 * HTP_MM_HMX_TILE_N_ELMS; - col_tiles += 32 * HTP_MM_HMX_TILE_N_ELMS; - } - - if (rem > 0) { - const uint32_t range = 2048u * rem - 1; - asm volatile(HMX_LOAD_MPY_DEEP_F16("%1", "%2", "%0") : : "r"(range), "r"(row_tiles), "r"(col_tiles)); - } - - asm volatile(HMX_STORE_AFTER_F16("%0", "%1") : : "r"(accum_tile), "r"(0) : "memory"); - - col_base += dot_tile_stride; - accum_tile += HTP_MM_HMX_TILE_N_ELMS; - } - } -} - -// output : fp16 -> f32p - -static void transfer_output_chunk_fp16_to_fp32_col_chunk( - float *restrict dst, - const float *restrict src2, - const __fp16 *restrict vtcm_src, - uint32_t start_row, - uint32_t n_rows, - uint32_t c_len, - uint32_t total_n_cols, - uint32_t dst_stride, - uint32_t src2_stride, - uint32_t dst_cols -) { - const size_t tile_row_stride = hmx_ceil_div(total_n_cols, HTP_MM_HMX_TILE_N_COLS) * HTP_MM_HMX_TILE_N_ELMS; - - const HVX_Vector one = hvx_vec_splat_f16(1.0); - - const size_t limit_c = hex_smin(c_len, dst_cols); - const size_t limit_c_aligned = (limit_c & ~31); - - for (size_t r = 0; r < n_rows; r += 2) { - const size_t r_idx0 = start_row + r + 0; - const size_t r0 = r_idx0 / HTP_MM_HMX_TILE_N_ROWS; - const size_t r1 = (r_idx0 % HTP_MM_HMX_TILE_N_ROWS) / 2; // index of the row pair within the tile - const __fp16 *row_base = vtcm_src + r0 * tile_row_stride; - float *output_row_base = dst + r * dst_stride; // global memory row base for row r (and r+1) - const float *src2_row_base = src2 ? (src2 + r * src2_stride) : NULL; - - #pragma unroll(4) - for (size_t c = 0; c < limit_c_aligned; c += HTP_MM_HMX_TILE_N_COLS) { - const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS; - const __fp16 *tile = row_base + c0 * HTP_MM_HMX_TILE_N_ELMS; - HVX_Vector v = ((const HVX_Vector *) tile)[r1]; - HVX_VectorPair vp = Q6_Wqf32_vmpy_VhfVhf(v, one); - - HVX_Vector v_out0 = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(vp)); - if (src2_row_base) { - HVX_Vector v_src2_0 = hvx_vmemu(src2_row_base + c + 0); - v_out0 = hvx_vec_add_f32_f32(v_out0, v_src2_0); - } - hvx_vmemu(output_row_base + c + 0) = v_out0; - - if (r + 1 < n_rows) { - HVX_Vector v_out1 = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(vp)); - if (src2_row_base) { - HVX_Vector v_src2_1 = hvx_vmemu(src2_row_base + c + src2_stride); - v_out1 = hvx_vec_add_f32_f32(v_out1, v_src2_1); - } - hvx_vmemu(output_row_base + c + dst_stride) = v_out1; - } - } - - if (limit_c_aligned < limit_c) { - size_t c = limit_c_aligned; - size_t valid_c = limit_c - c; - const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS; - const __fp16 *tile = row_base + c0 * HTP_MM_HMX_TILE_N_ELMS; - HVX_Vector v = ((const HVX_Vector *) tile)[r1]; - HVX_VectorPair vp = Q6_Wqf32_vmpy_VhfVhf(v, one); - - HVX_Vector v_out0 = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(vp)); - if (src2_row_base) { - HVX_Vector v_src2_0 = hvx_vmemu(src2_row_base + c + 0); - v_out0 = hvx_vec_add_f32_f32(v_out0, v_src2_0); - } - hvx_vec_store_u(output_row_base + c, valid_c * sizeof(float), v_out0); - - if (r + 1 < n_rows) { - HVX_Vector v_out1 = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(vp)); - if (src2_row_base) { - HVX_Vector v_src2_1 = hvx_vmemu(src2_row_base + c + src2_stride); - v_out1 = hvx_vec_add_f32_f32(v_out1, v_src2_1); - } - hvx_vec_store_u(output_row_base + c + dst_stride, valid_c * sizeof(float), v_out1); - } - } - } -} - -static inline void transfer_output_chunk_fp16_to_fp32( - float *restrict dst, - const float *restrict src2, - const __fp16 *restrict vtcm_src, - uint32_t start_row, - uint32_t n_rows, - uint32_t n_cols, - uint32_t dst_stride, - uint32_t src2_stride, - uint32_t dst_cols -) { - transfer_output_chunk_fp16_to_fp32_col_chunk( - dst, src2, vtcm_src, start_row, n_rows, n_cols, n_cols, dst_stride, src2_stride, dst_cols - ); -} - -typedef struct { - const __fp16 *vtcm_src; - float *dst; - const float *src2; - uint32_t n_tasks; - uint32_t n_tot_chunks; - uint32_t n_chunks_per_task; - uint32_t n_cols; - uint32_t dst_stride; // DDR row stride - uint32_t src2_stride; // DDR row stride for residual - uint32_t dst_cols; // Actual output columns -} output_transfer_task_state_t; - -// activations : fp32 -> fp16 - -static void transfer_activation_row_pair_fp32_to_fp16( - __fp16 *restrict vtcm_dst, - const float *restrict row0, - const float *restrict row1, - uint32_t r, - uint32_t k_block, - uint32_t k_valid, - bool row0_valid, - bool row1_valid) { - - uint32_t r0 = r / HTP_MM_HMX_TILE_N_ROWS; // tile row index - uint32_t r1 = r % HTP_MM_HMX_TILE_N_ROWS; // intra-tile row idx - - uint32_t c = 0; - for (; c + 32 <= k_valid; c += 32) { - HVX_Vector v0 = Q6_V_vzero(); - HVX_Vector v1 = Q6_V_vzero(); - if (row0_valid) v0 = *(const HVX_Vector *)(row0 + c); - if (row1_valid) v1 = *(const HVX_Vector *)(row1 + c); - - HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1); - - uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS; // tile column index - uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0; - - HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS); - tile[r1 / 2] = v_out; - } - if (c < k_block) { - HVX_Vector v0 = Q6_V_vzero(); - HVX_Vector v1 = Q6_V_vzero(); - if (row0_valid) v0 = *(const HVX_Vector *)(row0 + c); - if (row1_valid) v1 = *(const HVX_Vector *)(row1 + c); - - uint32_t rem = k_valid - c; - HVX_VectorPred mask = Q6_Q_vsetq2_R(rem > 0 ? rem * sizeof(float) : 0); - v0 = Q6_V_vmux_QVV(mask, v0, Q6_V_vzero()); - v1 = Q6_V_vmux_QVV(mask, v1, Q6_V_vzero()); - - HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1); - - uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS; // tile column index - uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0; - - HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS); - tile[r1 / 2] = v_out; - } -} - -// F16-input variant of transfer_activation_row_pair_fp32_to_fp16, for F16 activation -// (src1). Same shape as the F16 Q-prep in hmx-fa-kernels.h: one 128-byte load carries 64 f16 -// = two tile columns, and Q6_W_vshuff_VVR interleaves the two rows straight into the HMX tile -// layout, so no F32 round-trip is needed. Rows are only 64-byte aligned when k_block is an odd -// multiple of the tile width, hence the unaligned load type. -static void transfer_activation_row_pair_f16_to_f16(__fp16 * restrict vtcm_dst, - const __fp16 * restrict row0, - const __fp16 * restrict row1, - uint32_t r, - uint32_t k_block, - uint32_t k_valid, - bool row0_valid, - bool row1_valid) { - uint32_t r0 = r / HTP_MM_HMX_TILE_N_ROWS; // tile row index - uint32_t r1 = r % HTP_MM_HMX_TILE_N_ROWS; // intra-tile row idx - - const uint32_t n_tile_cols = k_block / HTP_MM_HMX_TILE_N_COLS; - __fp16 * restrict tile_row = vtcm_dst + (size_t) r0 * n_tile_cols * HTP_MM_HMX_TILE_N_ELMS; - - const HVX_UVector * pv0 = row0_valid ? (const HVX_UVector *) row0 : NULL; - const HVX_UVector * pv1 = row1_valid ? (const HVX_UVector *) row1 : NULL; - - uint32_t c = 0; - for (; c + 64 <= k_valid; c += 64) { - HVX_Vector v0 = pv0 ? pv0[c / 64] : Q6_V_vzero(); - HVX_Vector v1 = pv1 ? pv1[c / 64] : Q6_V_vzero(); - HVX_VectorPair vp = Q6_W_vshuff_VVR(v1, v0, -2); - - uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS; - - HVX_Vector * tile0 = (HVX_Vector *) (tile_row + (size_t) c0 * HTP_MM_HMX_TILE_N_ELMS); - HVX_Vector * tile1 = (HVX_Vector *) (tile_row + (size_t) (c0 + 1) * HTP_MM_HMX_TILE_N_ELMS); - - tile0[r1 / 2] = Q6_V_lo_W(vp); - tile1[r1 / 2] = Q6_V_hi_W(vp); - } - // Tail: fewer than 64 valid columns left, plus the k_valid..k_block padding that HMX will - // still multiply, so it has to be written as zeros. - for (; c < k_block; c += 64) { - HVX_Vector v0 = Q6_V_vzero(); - HVX_Vector v1 = Q6_V_vzero(); - - if (c < k_valid) { - uint32_t rem = k_valid - c; // 1..63 valid f16 lanes - HVX_VectorPred mask = Q6_Q_vsetq2_R(rem * sizeof(__fp16)); - if (pv0) { - v0 = Q6_V_vmux_QVV(mask, pv0[c / 64], Q6_V_vzero()); - } - if (pv1) { - v1 = Q6_V_vmux_QVV(mask, pv1[c / 64], Q6_V_vzero()); - } - } - - HVX_VectorPair vp = Q6_W_vshuff_VVR(v1, v0, -2); - - uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS; - - HVX_Vector * tile0 = (HVX_Vector *) (tile_row + (size_t) c0 * HTP_MM_HMX_TILE_N_ELMS); - tile0[r1 / 2] = Q6_V_lo_W(vp); - - if (c0 + 1 < n_tile_cols) { - HVX_Vector * tile1 = (HVX_Vector *) (tile_row + (size_t) (c0 + 1) * HTP_MM_HMX_TILE_N_ELMS); - tile1[r1 / 2] = Q6_V_hi_W(vp); - } - } -} - -static void transfer_activation_row_pair_fp32_to_fp16_col_chunk( - __fp16 *restrict vtcm_dst, - const float *restrict row0, // offset by c_first - const float *restrict row1, // offset by c_first - uint32_t r, - uint32_t k_block, - uint32_t c_first, - uint32_t c_len, - uint32_t k_chunk_valid, - bool row0_valid, - bool row1_valid) { - - uint32_t r0 = r / HTP_MM_HMX_TILE_N_ROWS; // tile row index - uint32_t r1 = r % HTP_MM_HMX_TILE_N_ROWS; // intra-tile row idx - - uint32_t c = 0; - for (; c + 32 <= k_chunk_valid; c += 32) { - HVX_Vector v0 = Q6_V_vzero(); - HVX_Vector v1 = Q6_V_vzero(); - if (row0_valid) v0 = *(const HVX_Vector *)(row0 + c); - if (row1_valid) v1 = *(const HVX_Vector *)(row1 + c); - - HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1); - - uint32_t c0 = (c_first + c) / HTP_MM_HMX_TILE_N_COLS; // tile column index - uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0; - - HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS); - tile[r1 / 2] = v_out; - } - if (c < c_len) { - HVX_Vector v0 = Q6_V_vzero(); - HVX_Vector v1 = Q6_V_vzero(); - if (row0_valid) v0 = *(const HVX_Vector *)(row0 + c); - if (row1_valid) v1 = *(const HVX_Vector *)(row1 + c); - - uint32_t rem = (k_chunk_valid > c) ? (k_chunk_valid - c) : 0; - HVX_VectorPred mask = Q6_Q_vsetq2_R(rem > 0 ? rem * sizeof(float) : 0); - v0 = Q6_V_vmux_QVV(mask, v0, Q6_V_vzero()); - v1 = Q6_V_vmux_QVV(mask, v1, Q6_V_vzero()); - - HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1); - - uint32_t c0 = (c_first + c) / HTP_MM_HMX_TILE_N_COLS; // tile column index - uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0; - - HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS); - tile[r1 / 2] = v_out; - } -} - -static void transfer_activation_chunk_fp32_to_fp16_gathered( - __fp16 *restrict vtcm_dst, - const float *restrict src, - uint32_t start_row, - uint32_t vtcm_start_row, - uint32_t n_rows, - uint32_t k_block, - const struct mmid_row_mapping *matrix_rows, - uint32_t cur_a, - uint32_t mapping_stride, - uint32_t ne11, - const struct fastdiv_values * ne11_div, - size_t nb11, - size_t nb12, - uint32_t cne1, - uint32_t k_valid) { - const uint32_t n_rows_padded = hex_align_up(n_rows, HTP_MM_HMX_TILE_N_ROWS); - const uint32_t n_rows_tiled = (n_rows / HTP_MM_HMX_TILE_N_ROWS) * HTP_MM_HMX_TILE_N_ROWS; - - uint32_t r = 0; - - #pragma unroll(2) - for (r = 0; r < n_rows_tiled; r += 2) { - uint32_t r_idx0 = start_row + r + 0; - uint32_t r_idx1 = start_row + r + 1; - uint32_t lr = vtcm_start_row + r; // vtcm-local row - uint32_t r0 = lr / HTP_MM_HMX_TILE_N_ROWS; // tile row index - uint32_t r1 = lr % HTP_MM_HMX_TILE_N_ROWS; // intra-tile row idx - - struct mmid_row_mapping mapping0 = matrix_rows[cur_a * mapping_stride + r_idx0]; - struct mmid_row_mapping mapping1 = matrix_rows[cur_a * mapping_stride + r_idx1]; - - uint32_t i11_0 = fastmodulo(mapping0.i1, ne11, ne11_div); - uint32_t i11_1 = fastmodulo(mapping1.i1, ne11, ne11_div); - - const float *row0_ptr = (const float *) ((const uint8_t *) src + i11_0 * nb11 + mapping0.i2 * nb12); - const float *row1_ptr = (const float *) ((const uint8_t *) src + i11_1 * nb11 + mapping1.i2 * nb12); - - uint32_t c = 0; - for (; c + 32 <= k_valid; c += 32) { - HVX_Vector v0 = *(const HVX_Vector *)(row0_ptr + c); - HVX_Vector v1 = *(const HVX_Vector *)(row1_ptr + c); - HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1); - - uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS; - uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0; - - HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS); - tile[r1 / 2] = v_out; - } - if (c < k_block) { - HVX_Vector v0 = *(const HVX_Vector *)(row0_ptr + c); - HVX_Vector v1 = *(const HVX_Vector *)(row1_ptr + c); - - uint32_t rem = k_valid - c; - HVX_VectorPred mask = Q6_Q_vsetq2_R(rem > 0 ? rem * sizeof(float) : 0); - v0 = Q6_V_vmux_QVV(mask, v0, Q6_V_vzero()); - v1 = Q6_V_vmux_QVV(mask, v1, Q6_V_vzero()); - - HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1); - - uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS; - uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0; - - HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS); - tile[r1 / 2] = v_out; - } - } - - for (; r < n_rows_padded; r += 2) { - uint32_t lr = vtcm_start_row + r; // vtcm-local row - uint32_t r0 = lr / HTP_MM_HMX_TILE_N_ROWS; // tile row index - uint32_t r1 = lr % HTP_MM_HMX_TILE_N_ROWS; // intra-tile row idx - - const bool row0_valid = (start_row + r + 0) < cne1; - const bool row1_valid = (start_row + r + 1) < cne1; - - const float *row0_ptr = NULL; - const float *row1_ptr = NULL; - - if (row0_valid) { - struct mmid_row_mapping mapping0 = matrix_rows[cur_a * mapping_stride + (start_row + r + 0)]; - uint32_t i11_0 = fastmodulo(mapping0.i1, ne11, ne11_div); - row0_ptr = (const float *) ((const uint8_t *) src + i11_0 * nb11 + mapping0.i2 * nb12); - } - if (row1_valid) { - struct mmid_row_mapping mapping1 = matrix_rows[cur_a * mapping_stride + (start_row + r + 1)]; - uint32_t i11_1 = fastmodulo(mapping1.i1, ne11, ne11_div); - row1_ptr = (const float *) ((const uint8_t *) src + i11_1 * nb11 + mapping1.i2 * nb12); - } - - uint32_t c = 0; - for (; c + 32 <= k_valid; c += 32) { - HVX_Vector v0 = Q6_V_vzero(); - HVX_Vector v1 = Q6_V_vzero(); - if (row0_valid) v0 = *(const HVX_Vector *)(row0_ptr + c); - if (row1_valid) v1 = *(const HVX_Vector *)(row1_ptr + c); - - HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1); - - uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS; - uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0; - - HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS); - tile[r1 / 2] = v_out; - } - if (c < k_block) { - HVX_Vector v0 = Q6_V_vzero(); - HVX_Vector v1 = Q6_V_vzero(); - if (row0_valid) v0 = *(const HVX_Vector *)(row0_ptr + c); - if (row1_valid) v1 = *(const HVX_Vector *)(row1_ptr + c); - - uint32_t rem = k_valid - c; - HVX_VectorPred mask = Q6_Q_vsetq2_R(rem > 0 ? rem * sizeof(float) : 0); - v0 = Q6_V_vmux_QVV(mask, v0, Q6_V_vzero()); - v1 = Q6_V_vmux_QVV(mask, v1, Q6_V_vzero()); - - HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1); - - uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS; - uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0; - - HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS); - tile[r1 / 2] = v_out; - } - } -} - -static void transfer_activation_chunk_fp32_to_fp16_gathered_flat( - __fp16 *restrict vtcm_dst, - const float *restrict src, - uint32_t start_row, - uint32_t vtcm_start_row, - uint32_t n_rows, - uint32_t k_block, - const struct mmid_row_mapping *matrix_rows, - uint32_t cur_a, - uint32_t mapping_stride, - size_t nb12, - uint32_t cne1, - uint32_t k_valid) { - const uint32_t n_rows_padded = hex_align_up(n_rows, HTP_MM_HMX_TILE_N_ROWS); - const uint32_t n_rows_tiled = (n_rows / HTP_MM_HMX_TILE_N_ROWS) * HTP_MM_HMX_TILE_N_ROWS; - - uint32_t r = 0; - - #pragma unroll(2) - for (r = 0; r < n_rows_tiled; r += 2) { - uint32_t r_idx0 = start_row + r + 0; - uint32_t r_idx1 = start_row + r + 1; - uint32_t lr = vtcm_start_row + r; // vtcm-local row - uint32_t r0 = lr / HTP_MM_HMX_TILE_N_ROWS; // tile row index - uint32_t r1 = lr % HTP_MM_HMX_TILE_N_ROWS; // intra-tile row idx - - struct mmid_row_mapping mapping0 = matrix_rows[cur_a * mapping_stride + r_idx0]; - struct mmid_row_mapping mapping1 = matrix_rows[cur_a * mapping_stride + r_idx1]; - - const float *row0_ptr = (const float *) ((const uint8_t *) src + mapping0.i2 * nb12); - const float *row1_ptr = (const float *) ((const uint8_t *) src + mapping1.i2 * nb12); - - uint32_t c = 0; - for (; c + 32 <= k_valid; c += 32) { - HVX_Vector v0 = *(const HVX_Vector *)(row0_ptr + c); - HVX_Vector v1 = *(const HVX_Vector *)(row1_ptr + c); - HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1); - - uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS; - uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0; - - HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS); - tile[r1 / 2] = v_out; - } - if (c < k_block) { - HVX_Vector v0 = *(const HVX_Vector *)(row0_ptr + c); - HVX_Vector v1 = *(const HVX_Vector *)(row1_ptr + c); - - uint32_t rem = k_valid - c; - HVX_VectorPred mask = Q6_Q_vsetq2_R(rem > 0 ? rem * sizeof(float) : 0); - v0 = Q6_V_vmux_QVV(mask, v0, Q6_V_vzero()); - v1 = Q6_V_vmux_QVV(mask, v1, Q6_V_vzero()); - - HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1); - - uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS; - uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0; - - HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS); - tile[r1 / 2] = v_out; - } - } - - for (; r < n_rows_padded; r += 2) { - uint32_t lr = vtcm_start_row + r; // vtcm-local row - uint32_t r0 = lr / HTP_MM_HMX_TILE_N_ROWS; // tile row index - uint32_t r1 = lr % HTP_MM_HMX_TILE_N_ROWS; // intra-tile row idx - - const bool row0_valid = (start_row + r + 0) < cne1; - const bool row1_valid = (start_row + r + 1) < cne1; - - const float *row0_ptr = NULL; - const float *row1_ptr = NULL; - - if (row0_valid) { - struct mmid_row_mapping mapping0 = matrix_rows[cur_a * mapping_stride + (start_row + r + 0)]; - row0_ptr = (const float *) ((const uint8_t *) src + mapping0.i2 * nb12); - } - if (row1_valid) { - struct mmid_row_mapping mapping1 = matrix_rows[cur_a * mapping_stride + (start_row + r + 1)]; - row1_ptr = (const float *) ((const uint8_t *) src + mapping1.i2 * nb12); - } - - uint32_t c = 0; - for (; c + 32 <= k_valid; c += 32) { - HVX_Vector v0 = Q6_V_vzero(); - HVX_Vector v1 = Q6_V_vzero(); - if (row0_valid) v0 = *(const HVX_Vector *)(row0_ptr + c); - if (row1_valid) v1 = *(const HVX_Vector *)(row1_ptr + c); - - HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1); - - uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS; - uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0; - - HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS); - tile[r1 / 2] = v_out; - } - if (c < k_block) { - HVX_Vector v0 = Q6_V_vzero(); - HVX_Vector v1 = Q6_V_vzero(); - if (row0_valid) v0 = *(const HVX_Vector *)(row0_ptr + c); - if (row1_valid) v1 = *(const HVX_Vector *)(row1_ptr + c); - - uint32_t rem = k_valid - c; - HVX_VectorPred mask = Q6_Q_vsetq2_R(rem > 0 ? rem * sizeof(float) : 0); - v0 = Q6_V_vmux_QVV(mask, v0, Q6_V_vzero()); - v1 = Q6_V_vmux_QVV(mask, v1, Q6_V_vzero()); - - HVX_Vector v_out = hvx_vec_f32_to_f16_shuff(v0, v1); - - uint32_t c0 = c / HTP_MM_HMX_TILE_N_COLS; - uint32_t tile_idx = r0 * (k_block / HTP_MM_HMX_TILE_N_COLS) + c0; - - HVX_Vector *tile = (HVX_Vector *) (vtcm_dst + tile_idx * HTP_MM_HMX_TILE_N_ELMS); - tile[r1 / 2] = v_out; - } - } -} - -static void transfer_output_chunk_fp16_to_fp32_scattered( - float *restrict dst, - const __fp16 *restrict vtcm_src, - uint32_t start_row, - uint32_t vtcm_start_row, - uint32_t n_rows, - uint32_t n_cols, - const struct mmid_row_mapping *matrix_rows, - uint32_t cur_a, - uint32_t mapping_stride, - size_t dst_nb1, - size_t dst_nb2, - uint32_t cne1) { - assert(n_cols % HTP_MM_HMX_TILE_N_COLS == 0); - const size_t tile_row_stride = (n_cols / HTP_MM_HMX_TILE_N_COLS) * HTP_MM_HMX_TILE_N_ELMS; - - const HVX_Vector one = hvx_vec_splat_f16(1.0); - - for (size_t r = 0; r < n_rows; r += 2) { - uint32_t r_idx0 = start_row + r + 0; - uint32_t r_idx1 = start_row + r + 1; - uint32_t lr = vtcm_start_row + r; // vtcm-local row - const size_t r0 = (lr / HTP_MM_HMX_TILE_N_ROWS); - const size_t r1 = (lr % HTP_MM_HMX_TILE_N_ROWS) / 2; // index of the row pair within the tile - const __fp16 *row_base = vtcm_src + r0 * tile_row_stride; - - if (r_idx0 >= cne1) break; - - struct mmid_row_mapping mapping0 = matrix_rows[cur_a * mapping_stride + r_idx0]; - float *output_row0 = (float *) ((uint8_t *) dst + mapping0.i1 * dst_nb1 + mapping0.i2 * dst_nb2); - - float *output_row1 = NULL; - if (r_idx1 < cne1) { - struct mmid_row_mapping mapping1 = matrix_rows[cur_a * mapping_stride + r_idx1]; - output_row1 = (float *) ((uint8_t *) dst + mapping1.i1 * dst_nb1 + mapping1.i2 * dst_nb2); - } - - #pragma unroll(4) - for (size_t c = 0; c < (size_t)n_cols; c += HTP_MM_HMX_TILE_N_COLS) { - const size_t c0 = c / HTP_MM_HMX_TILE_N_COLS; - const __fp16 *tile = row_base + c0 * HTP_MM_HMX_TILE_N_ELMS; - HVX_Vector v = ((const HVX_Vector *) tile)[r1]; - HVX_VectorPair vp = Q6_Wqf32_vmpy_VhfVhf(v, one); - - hvx_vmemu(output_row0 + c) = Q6_Vsf_equals_Vqf32(Q6_V_lo_W(vp)); - if (output_row1) { - hvx_vmemu(output_row1 + c) = Q6_Vsf_equals_Vqf32(Q6_V_hi_W(vp)); - } - } - } -} diff --git a/ggml/src/ggml-hexagon/htp/hmx-queue.c b/ggml/src/ggml-hexagon/htp/hmx-queue.c index e40a28bed74e..92dd3b360c81 100644 --- a/ggml/src/ggml-hexagon/htp/hmx-queue.c +++ b/ggml/src/ggml-hexagon/htp/hmx-queue.c @@ -1,5 +1,3 @@ -#pragma clang diagnostic ignored "-Wunused-function" - #include #include #include @@ -14,49 +12,59 @@ #define QURT_LOWEST_PRIO (254) -static inline void hmx_lock(hmx_queue_t q) -{ +static inline void hmx_lock(hmx_queue_t q) { if (!q->hmx_locked) { - HAP_compute_res_hmx_lock(q->hap_rctx); - q->hmx_locked = true; + if (HAP_compute_res_hmx_lock(q->hap_rctx) == 0) { + q->hmx_locked = true; + } else { + FARF(ERROR, "hmx-queue: HAP_compute_res_hmx_lock failed\n"); + } } } -static inline void hmx_unlock(hmx_queue_t q) -{ +static inline void hmx_unlock(hmx_queue_t q) { if (q->hmx_locked) { HAP_compute_res_hmx_unlock(q->hap_rctx); q->hmx_locked = false; } } -static inline void hmx_queue_process(hmx_queue_t q, bool* killed) { - unsigned int ir = atomic_load(&q->idx_read); - - while (ir != atomic_load(&q->idx_write)) { - struct hmx_queue_desc *d = &q->desc[ir]; - if (!d->done) { - FARF(HIGH, "hmx-queue-process: ir %u func %p data %p", ir, d->func, d->data); - - uintptr_t sig = (uintptr_t) d->func; - switch (sig) { - case HMX_QUEUE_NOOP: /* noop */; break; - case HMX_QUEUE_KILL: *killed = true; break; - case HMX_QUEUE_SUSPEND: hmx_unlock(q); break; - case HMX_QUEUE_WAKEUP: hmx_lock(q); break; - default: - hmx_lock(q); - htp_trace_event_start(q->th.trace, HTP_TRACE_EVT_HMX_COMP, ir); - d->func(&q->th, d->data); - htp_trace_event_stop(q->th.trace, HTP_TRACE_EVT_HMX_COMP, ir); - break; - } - - atomic_fetch_add(&d->done, 1); +static inline void hmx_queue_process(hmx_queue_t q, bool * killed) { + uint32_t ir = atomic_load_explicit(&q->idx_read, memory_order_relaxed); + + while (ir != atomic_load_explicit(&q->idx_write, memory_order_acquire)) { + struct hmx_queue_desc * d = &q->desc[ir & q->idx_mask]; + + FARF(HIGH, "hmx-queue-process: ir %u func %p data %p", ir, d->func, d->data); + + uintptr_t sig = (uintptr_t) d->func; + switch (sig) { + case HMX_QUEUE_KILL: + hmx_unlock(q); + *killed = true; + break; + case HMX_QUEUE_SUSPEND: + hmx_unlock(q); + break; + case HMX_QUEUE_WAKEUP: + hmx_lock(q); + break; + default: + hmx_lock(q); + htp_trace_event_start(q->th.trace, HTP_TRACE_EVT_HMX_COMP, ir); + d->func(&q->th, d->data); + // drain HMX VTCM stores before signaling completion to HVX workers + asm volatile("syncht" ::: "memory"); + htp_trace_event_stop(q->th.trace, HTP_TRACE_EVT_HMX_COMP, ir); + break; } - ir = (ir + 1) & q->idx_mask; - atomic_store(&q->idx_read, ir); + ir++; + atomic_store_explicit(&q->idx_read, ir, memory_order_release); + + if (*killed) { + break; + } } } @@ -70,13 +78,16 @@ static void hmx_queue_thread(void * arg) { unsigned int poll_cnt = HMX_QUEUE_POLL_COUNT; unsigned int prev_seqn = 0; while (!killed) { - unsigned int seqn = atomic_load(&q->seqn); + unsigned int seqn = atomic_load_explicit(&q->seqn, memory_order_acquire); if (seqn == prev_seqn) { - // drop HVX context while spinning - if (poll_cnt > 1 && poll_cnt == HMX_QUEUE_POLL_COUNT) { + // drop HVX context before spinning/sleeping + if (poll_cnt == HMX_QUEUE_POLL_COUNT) { qurt_hvx_unlock(); } - if (--poll_cnt) { hex_pause(); continue; } + if (--poll_cnt) { + hex_pause(); + continue; + } FARF(HIGH, "hmx-queue-thread: sleeping"); qurt_futex_wait(&q->seqn, prev_seqn); poll_cnt = HMX_QUEUE_POLL_COUNT; @@ -94,9 +105,9 @@ static void hmx_queue_thread(void * arg) { } size_t hmx_queue_sizeof(size_t capacity, uint32_t stack_size) { - capacity = hex_ceil_pow2(capacity); - size_t size_q = hex_align_up(sizeof(struct hmx_queue_s), HEX_L2_LINE_SIZE); - size_t size_desc = hex_align_up(capacity * sizeof(struct hmx_queue_desc), HEX_L2_LINE_SIZE); + capacity = hex_ceil_pow2(capacity > 0 ? capacity : 1); + size_t size_q = hex_align_up(sizeof(struct hmx_queue_s), HEX_L2_LINE_SIZE); + size_t size_desc = hex_align_up(capacity * sizeof(struct hmx_queue_desc), HEX_L2_LINE_SIZE); size_t size_stack = stack_size; return size_q + size_desc + size_stack; } @@ -106,21 +117,26 @@ size_t hmx_queue_alignof(void) { } hmx_queue_t hmx_queue_init(void * ptr, size_t capacity, uint32_t stack_size, uint32_t hap_rctx, dma_queue_t * dma, struct htp_thread_trace * trace) { - capacity = hex_ceil_pow2(capacity); - size_t size_q = hex_align_up(sizeof(struct hmx_queue_s), HEX_L2_LINE_SIZE); + capacity = hex_ceil_pow2(capacity > 0 ? capacity : 1); + size_t size_q = hex_align_up(sizeof(struct hmx_queue_s), HEX_L2_LINE_SIZE); size_t size_desc = hex_align_up(capacity * sizeof(struct hmx_queue_desc), HEX_L2_LINE_SIZE); uint8_t * block = (uint8_t *) ptr; - hmx_queue_t q = (hmx_queue_t) block; block += size_q; + hmx_queue_t q = (hmx_queue_t) block; + block += size_q; memset(q, 0, sizeof(struct hmx_queue_s)); q->capacity = capacity; q->idx_mask = capacity - 1; + q->idx_pop = 0; q->hap_rctx = hap_rctx; - q->external_mem = true; + atomic_init(&q->idx_write, 0); + atomic_init(&q->idx_read, 0); + atomic_init(&q->seqn, 0); - q->desc = (struct hmx_queue_desc *) block; block += size_desc; + q->desc = (struct hmx_queue_desc *) block; + block += size_desc; memset(q->desc, 0, capacity * sizeof(struct hmx_queue_desc)); q->stack = block; @@ -128,7 +144,7 @@ hmx_queue_t hmx_queue_init(void * ptr, size_t capacity, uint32_t stack_size, uin htp_thread_init(&q->th, dma, trace); - // Match caller thread priority (same pattern as worker-pool.c). + // Match caller thread priority (same pattern as work-queue.c). int prio = qurt_thread_get_priority(qurt_thread_get_id()); if (prio < 1) { prio = 1; diff --git a/ggml/src/ggml-hexagon/htp/hmx-queue.h b/ggml/src/ggml-hexagon/htp/hmx-queue.h index efefb1455b48..fb9c5ab53d3c 100644 --- a/ggml/src/ggml-hexagon/htp/hmx-queue.h +++ b/ggml/src/ggml-hexagon/htp/hmx-queue.h @@ -26,35 +26,33 @@ extern "C" { typedef void (*hmx_queue_func)(const htp_thread_t * th, void *); -// Dummy funcs used as signals +// Dummy funcs used as signals (non-zero so NULL remains the empty sentinel) enum hmx_queue_signal { - HMX_QUEUE_NOOP = 0, // aka NULL - HMX_QUEUE_WAKEUP, - HMX_QUEUE_SUSPEND, - HMX_QUEUE_KILL + HMX_QUEUE_WAKEUP = 1, + HMX_QUEUE_SUSPEND = 2, + HMX_QUEUE_KILL = 3, }; struct hmx_queue_desc { - hmx_queue_func func; - void * data; - atomic_uint done; + hmx_queue_func func; + void * data; }; struct hmx_queue_s { struct hmx_queue_desc * desc; - atomic_uint idx_write; // updated by producer (push) - atomic_uint idx_read; // updated by consumer (process) - unsigned int idx_pop; // updated by producer (pop) - uint32_t idx_mask; - uint32_t capacity; - - atomic_uint seqn; // incremented for all pushes, used with futex - qurt_thread_t thread; - htp_thread_t th; - void * stack; - uint32_t hap_rctx; - bool hmx_locked; - bool external_mem; // memory owned externally + atomic_uint idx_write; // monotonic, updated by producer (push) + uint32_t idx_pop; // monotonic, updated by producer (pop) + uint32_t idx_mask; + uint32_t capacity; + atomic_uint seqn; // incremented for all pushes, used with futex + + atomic_uint idx_read __attribute__((aligned(HEX_L2_LINE_SIZE))); // monotonic, updated by consumer + bool hmx_locked; + + qurt_thread_t thread; + htp_thread_t th; + void * stack; + uint32_t hap_rctx; }; typedef struct hmx_queue_s * hmx_queue_t; @@ -70,37 +68,37 @@ static inline struct hmx_queue_desc hmx_queue_make_desc(hmx_queue_func func, voi } static inline bool hmx_queue_push(hmx_queue_t q, struct hmx_queue_desc d) { - unsigned int ir = atomic_load(&q->idx_read); - unsigned int iw = atomic_load(&q->idx_write); + uint32_t iw = atomic_load_explicit(&q->idx_write, memory_order_relaxed); - if (((iw + 1) & q->idx_mask) == ir) { + if ((iw - q->idx_pop) >= q->capacity) { FARF(HIGH, "hmx-queue-push: queue is full\n"); return false; } - atomic_store(&d.done, 0); - FARF(HIGH, "hmx-queue-push: iw %u func %p data %p\n", iw, d.func, d.data); - q->desc[iw] = d; - atomic_store(&q->idx_write, (iw + 1) & q->idx_mask); + q->desc[iw & q->idx_mask] = d; + atomic_store_explicit(&q->idx_write, iw + 1, memory_order_release); + // wake up our thread - atomic_fetch_add(&q->seqn, 1); + unsigned int seqn = atomic_load_explicit(&q->seqn, memory_order_relaxed) + 1; + atomic_store_explicit(&q->seqn, seqn, memory_order_release); qurt_futex_wake(&q->seqn, 1); return true; } static inline bool hmx_queue_signal(hmx_queue_t q, enum hmx_queue_signal sig) { - return hmx_queue_push(q, hmx_queue_make_desc((hmx_queue_func) sig, NULL)); + return hmx_queue_push(q, hmx_queue_make_desc((hmx_queue_func) (uintptr_t) sig, NULL)); } static inline bool hmx_queue_empty(hmx_queue_t q) { - return q->idx_pop == atomic_load(&q->idx_write); + return q->idx_pop == atomic_load_explicit(&q->idx_write, memory_order_relaxed); } static inline uint32_t hmx_queue_depth(hmx_queue_t q) { - return (atomic_load(&q->idx_write) - atomic_load(&q->idx_read)) & q->idx_mask; + return atomic_load_explicit(&q->idx_write, memory_order_relaxed) - + atomic_load_explicit(&q->idx_read, memory_order_relaxed); } static inline uint32_t hmx_queue_capacity(hmx_queue_t q) { @@ -108,23 +106,23 @@ static inline uint32_t hmx_queue_capacity(hmx_queue_t q) { } static inline struct hmx_queue_desc hmx_queue_pop_one(hmx_queue_t q) { - unsigned int ip = q->idx_pop; - unsigned int iw = atomic_load(&q->idx_write); + uint32_t ip = q->idx_pop; + uint32_t iw = atomic_load_explicit(&q->idx_write, memory_order_relaxed); struct hmx_queue_desc rd = { NULL, NULL }; if (ip == iw) { return rd; } - // Wait for desc to complete - struct hmx_queue_desc * d = &q->desc[ip]; - while (!atomic_load(&d->done)) { + // Wait for consumer to finish slot ip + while ((int32_t) (atomic_load_explicit(&q->idx_read, memory_order_relaxed) - ip) <= 0) { FARF(HIGH, "hmx-queue-pop: waiting for HMX queue : %u\n", ip); hex_pause(); } + atomic_thread_fence(memory_order_acquire); - rd = *d; - q->idx_pop = (ip + 1) & q->idx_mask; + rd = q->desc[ip & q->idx_mask]; + q->idx_pop = ip + 1; FARF(HIGH, "hmx-queue-pop: ip %u func %p data %p\n", ip, rd.func, rd.data); return rd; @@ -134,9 +132,10 @@ static inline struct hmx_queue_desc hmx_queue_pop(hmx_queue_t q) { while (1) { struct hmx_queue_desc d = hmx_queue_pop_one(q); - uint32_t sig = (uint32_t) d.func; - if (sig && sig <= HMX_QUEUE_KILL) + uintptr_t sig = (uintptr_t) d.func; + if (sig && sig <= HMX_QUEUE_KILL) { continue; + } return d; } diff --git a/ggml/src/ggml-hexagon/htp/hmx-utils.h b/ggml/src/ggml-hexagon/htp/hmx-utils.h index 1952aaa2cbe2..2a64bd4428ce 100644 --- a/ggml/src/ggml-hexagon/htp/hmx-utils.h +++ b/ggml/src/ggml-hexagon/htp/hmx-utils.h @@ -35,6 +35,120 @@ static const int32_t hmx_transpose_scatter_offsets[32] __attribute__((aligned(VL 22 * 128, 23 * 128, 24 * 128, 25 * 128, 26 * 128, 27 * 128, 28 * 128, 29 * 128, 30 * 128, 31 * 128, }; +// 5-stage vshuffvdd transpose of a 32x64 FP16 block into two contiguous 32x32 HMX tiles. +// Stages 1-3 (-4, -8, -16) mix groups of 8 rows into a 4KB stack scratch; stages 4-5 (-32, -64) +// Stage in-place in dst_tile0/dst_tile1 (each 4-vector slot holds g=0..3), then +// combine across the 4 groups in-place with zero stack scratch. +static inline void hmx_transpose_k_pair_tiles_vshuff(HVX_Vector * restrict dst_tile0, + HVX_Vector * restrict dst_tile1, + const uint8_t * restrict src_base, + size_t row_byte_stride, + uint32_t valid_rows) { + if (valid_rows >= HMX_FP16_TILE_N_ROWS) { + for (uint32_t g = 0; g < 4; ++g) { + const uint8_t * p = src_base + (size_t) (8 * g) * row_byte_stride; + HVX_Vector r0 = hvx_vmem(p); p += row_byte_stride; + HVX_Vector r1 = hvx_vmem(p); p += row_byte_stride; + HVX_Vector r2 = hvx_vmem(p); p += row_byte_stride; + HVX_Vector r3 = hvx_vmem(p); p += row_byte_stride; + HVX_Vector r4 = hvx_vmem(p); p += row_byte_stride; + HVX_Vector r5 = hvx_vmem(p); p += row_byte_stride; + HVX_Vector r6 = hvx_vmem(p); p += row_byte_stride; + HVX_Vector r7 = hvx_vmem(p); + + HVX_VectorPair p01 = Q6_W_vshuff_VVR(r1, r0, -4); + HVX_VectorPair p23 = Q6_W_vshuff_VVR(r3, r2, -4); + HVX_VectorPair p45 = Q6_W_vshuff_VVR(r5, r4, -4); + HVX_VectorPair p67 = Q6_W_vshuff_VVR(r7, r6, -4); + r0 = Q6_V_lo_W(p01); r1 = Q6_V_hi_W(p01); + r2 = Q6_V_lo_W(p23); r3 = Q6_V_hi_W(p23); + r4 = Q6_V_lo_W(p45); r5 = Q6_V_hi_W(p45); + r6 = Q6_V_lo_W(p67); r7 = Q6_V_hi_W(p67); + + HVX_VectorPair p02 = Q6_W_vshuff_VVR(r2, r0, -8); + HVX_VectorPair p13 = Q6_W_vshuff_VVR(r3, r1, -8); + HVX_VectorPair p46 = Q6_W_vshuff_VVR(r6, r4, -8); + HVX_VectorPair p57 = Q6_W_vshuff_VVR(r7, r5, -8); + r0 = Q6_V_lo_W(p02); r2 = Q6_V_hi_W(p02); + r1 = Q6_V_lo_W(p13); r3 = Q6_V_hi_W(p13); + r4 = Q6_V_lo_W(p46); r6 = Q6_V_hi_W(p46); + r5 = Q6_V_lo_W(p57); r7 = Q6_V_hi_W(p57); + + HVX_VectorPair p04 = Q6_W_vshuff_VVR(r4, r0, -16); + HVX_VectorPair p15 = Q6_W_vshuff_VVR(r5, r1, -16); + HVX_VectorPair p26 = Q6_W_vshuff_VVR(r6, r2, -16); + HVX_VectorPair p37 = Q6_W_vshuff_VVR(r7, r3, -16); + + dst_tile0[ 0 + g] = Q6_V_lo_W(p04); dst_tile0[ 4 + g] = Q6_V_hi_W(p04); + dst_tile1[ 0 + g] = Q6_V_lo_W(p15); dst_tile1[ 4 + g] = Q6_V_hi_W(p15); + dst_tile0[ 8 + g] = Q6_V_lo_W(p26); dst_tile0[12 + g] = Q6_V_hi_W(p26); + dst_tile1[ 8 + g] = Q6_V_lo_W(p37); dst_tile1[12 + g] = Q6_V_hi_W(p37); + } + } else { + const HVX_Vector vzero = Q6_V_vzero(); + for (uint32_t g = 0; g < 4; ++g) { + const uint32_t base_r = 8 * g; + const uint8_t * p = src_base + (size_t) base_r * row_byte_stride; + HVX_Vector r0 = (base_r + 0 < valid_rows) ? hvx_vmem(p + 0 * row_byte_stride) : vzero; + HVX_Vector r1 = (base_r + 1 < valid_rows) ? hvx_vmem(p + 1 * row_byte_stride) : vzero; + HVX_Vector r2 = (base_r + 2 < valid_rows) ? hvx_vmem(p + 2 * row_byte_stride) : vzero; + HVX_Vector r3 = (base_r + 3 < valid_rows) ? hvx_vmem(p + 3 * row_byte_stride) : vzero; + HVX_Vector r4 = (base_r + 4 < valid_rows) ? hvx_vmem(p + 4 * row_byte_stride) : vzero; + HVX_Vector r5 = (base_r + 5 < valid_rows) ? hvx_vmem(p + 5 * row_byte_stride) : vzero; + HVX_Vector r6 = (base_r + 6 < valid_rows) ? hvx_vmem(p + 6 * row_byte_stride) : vzero; + HVX_Vector r7 = (base_r + 7 < valid_rows) ? hvx_vmem(p + 7 * row_byte_stride) : vzero; + + HVX_VectorPair p01 = Q6_W_vshuff_VVR(r1, r0, -4); + HVX_VectorPair p23 = Q6_W_vshuff_VVR(r3, r2, -4); + HVX_VectorPair p45 = Q6_W_vshuff_VVR(r5, r4, -4); + HVX_VectorPair p67 = Q6_W_vshuff_VVR(r7, r6, -4); + r0 = Q6_V_lo_W(p01); r1 = Q6_V_hi_W(p01); + r2 = Q6_V_lo_W(p23); r3 = Q6_V_hi_W(p23); + r4 = Q6_V_lo_W(p45); r5 = Q6_V_hi_W(p45); + r6 = Q6_V_lo_W(p67); r7 = Q6_V_hi_W(p67); + + HVX_VectorPair p02 = Q6_W_vshuff_VVR(r2, r0, -8); + HVX_VectorPair p13 = Q6_W_vshuff_VVR(r3, r1, -8); + HVX_VectorPair p46 = Q6_W_vshuff_VVR(r6, r4, -8); + HVX_VectorPair p57 = Q6_W_vshuff_VVR(r7, r5, -8); + r0 = Q6_V_lo_W(p02); r2 = Q6_V_hi_W(p02); + r1 = Q6_V_lo_W(p13); r3 = Q6_V_hi_W(p13); + r4 = Q6_V_lo_W(p46); r6 = Q6_V_hi_W(p46); + r5 = Q6_V_lo_W(p57); r7 = Q6_V_hi_W(p57); + + HVX_VectorPair p04 = Q6_W_vshuff_VVR(r4, r0, -16); + HVX_VectorPair p15 = Q6_W_vshuff_VVR(r5, r1, -16); + HVX_VectorPair p26 = Q6_W_vshuff_VVR(r6, r2, -16); + HVX_VectorPair p37 = Q6_W_vshuff_VVR(r7, r3, -16); + + dst_tile0[ 0 + g] = Q6_V_lo_W(p04); dst_tile0[ 4 + g] = Q6_V_hi_W(p04); + dst_tile1[ 0 + g] = Q6_V_lo_W(p15); dst_tile1[ 4 + g] = Q6_V_hi_W(p15); + dst_tile0[ 8 + g] = Q6_V_lo_W(p26); dst_tile0[12 + g] = Q6_V_hi_W(p26); + dst_tile1[ 8 + g] = Q6_V_lo_W(p37); dst_tile1[12 + g] = Q6_V_hi_W(p37); + } + } + + for (uint32_t t = 0; t < 2; ++t) { + HVX_Vector * dst = t ? dst_tile1 : dst_tile0; + for (uint32_t p0 = 0; p0 < 16; p0 += 4) { + HVX_Vector a = dst[p0 + 0]; + HVX_Vector b = dst[p0 + 1]; + HVX_Vector c = dst[p0 + 2]; + HVX_Vector d = dst[p0 + 3]; + + HVX_VectorPair pab = Q6_W_vshuff_VVR(b, a, -32); + HVX_VectorPair pcd = Q6_W_vshuff_VVR(d, c, -32); + HVX_VectorPair out0 = Q6_W_vshuff_VVR(Q6_V_lo_W(pcd), Q6_V_lo_W(pab), -64); + HVX_VectorPair out1 = Q6_W_vshuff_VVR(Q6_V_hi_W(pcd), Q6_V_hi_W(pab), -64); + + dst[p0 + 0] = Q6_V_lo_W(out0); + dst[p0 + 1] = Q6_V_hi_W(out0); + dst[p0 + 2] = Q6_V_lo_W(out1); + dst[p0 + 3] = Q6_V_hi_W(out1); + } + } +} + // Scatter row-major FP16 data (in VTCM scratch) into transposed [K][N] tiles. // vtcm_src: [n_cols][src_stride] row-major fp16 (only first k elements per row are used) // vtcm_dst: [n_col_tiles][n_k_tiles][HMX_FP16_TILE_N_ELMS] tile-major interleaved fp16 @@ -50,18 +164,36 @@ static inline void hmx_interleave_rows_to_tiles(__fp16 * restrict vtcm_dst, assert(k % HMX_FP16_TILE_N_COLS == 0); const uint32_t n_k_tiles = k / HMX_FP16_TILE_N_COLS; + const bool pair_scatter = (n_k_tiles & 1) == 0; + __builtin_assume(k > 0); + __builtin_assume(end_row > start_row); + + if (pair_scatter && ((start_row & 31) == 0) && ((end_row & 31) == 0) && + hex_is_aligned(vtcm_src, 128) && ((src_stride & 63) == 0)) { + const uint32_t n_c_iters = n_k_tiles >> 1; + const size_t row_byte_stride = src_stride * sizeof(__fp16); + const size_t tile_pair_vecs = 2 * (HMX_FP16_TILE_SIZE / sizeof(HVX_Vector)); + + for (uint32_t r_base = start_row; r_base < end_row; r_base += HMX_FP16_TILE_N_ROWS) { + const uint32_t ct = r_base / HMX_FP16_TILE_N_ROWS; + const uint32_t valid_rows = (r_base < n_cols) ? (n_cols - r_base) : 0; + HVX_Vector * tile_base = (HVX_Vector *) (vtcm_dst + (size_t) ct * n_k_tiles * HMX_FP16_TILE_N_ELMS); + const uint8_t * row_src = (const uint8_t *) (vtcm_src + (size_t) r_base * src_stride); + + for (uint32_t i = 0; i < n_c_iters; ++i) { + hmx_transpose_k_pair_tiles_vshuff(tile_base, tile_base + 16, row_src + (size_t) i * 128, + row_byte_stride, valid_rows); + tile_base += tile_pair_vecs; + } + } + return; + } + const HVX_Vector v_scat_base = hvx_vmem(hmx_transpose_scatter_offsets); const HVX_Vector v_scat_step = Q6_V_vsplat_R(4); const HVX_VectorPred q_mask64 = Q6_Q_vsetq_R(64); - // Each hvx_vmemu load brings 64 fp16 = 128 bytes covering 2 adjacent K-tiles. - // When n_k_tiles is even, scatter into 2 K-tiles per call (region 4095, no mask) - // using the upper half of hmx_transpose_scatter_offsets. Tail one K-tile (when - // n_k_tiles is odd) falls back to single-tile masked scatter. - const bool pair_scatter = (n_k_tiles & 1) == 0; const size_t pair_region = (size_t) (2 * HMX_FP16_TILE_SIZE - 1); const size_t single_region = (size_t) (HMX_FP16_TILE_SIZE - 1); - __builtin_assume(k > 0); - __builtin_assume(end_row > start_row); if (pair_scatter) { // Step c by 64 fp16 (two K-tiles per scatter), advance dst by 2 tiles per iter. @@ -148,6 +280,7 @@ static inline void hmx_interleave_rows_to_tiles(__fp16 * restrict vtcm_dst, } } } + hvx_gather_sync(vtcm_dst); } // Interleave row-major FP16 data into column-major tile format. @@ -227,4 +360,69 @@ static inline void hmx_interleave_cols_to_tiles(__fp16 * restrict tiles_out, #define HMX_CLRACC_F16() \ "mxclracc.hf\n" +// --- Fixed-point INT HMX inline asm macros and helpers (v73+) --- + +#define HMX_CLRACC_INT() \ + "mxclracc\n" + +#define HMX_SWAPACC() \ + "mxswapacc\n" + +#define HMX_LOAD_MPY_DEEP_U8_S8_SM(act, act_rt, wt, wt_rt) \ + "{\n" \ + " activation.ub = mxmem(" act ", " act_rt "):deep\n" \ + " weight.b = mxmem(" wt ", " wt_rt ")\n" \ + "}\n" + +#define HMX_LOAD_MPY_DEEP_U8_S8_SM_64C(act, act_rt, wt, wt_rt) \ + "{\n" \ + " activation.ub = mxmem(" act ", " act_rt "):deep\n" \ + " weight.b = mxmem(" wt ", " wt_rt "):deep\n" \ + "}\n" + +#define HMX_LOAD_MPY_DEEP_U8_S8_CM(act, act_rt, wt, wt_rt) \ + "{\n" \ + " activation.ub = mxmem(" act ", " act_rt "):deep:cm\n" \ + " weight.b = mxmem(" wt ", " wt_rt ")\n" \ + "}\n" + +#define HMX_LOAD_MPY_DEEP_U8_S8_CM_64C(act, act_rt, wt, wt_rt) \ + "{\n" \ + " activation.ub = mxmem(" act ", " act_rt "):deep:cm\n" \ + " weight.b = mxmem(" wt ", " wt_rt "):deep\n" \ + "}\n" + +#define HMX_CVT_UB_ACC(ctrl) \ + "cvt.ub = acc(" ctrl ")\n" + +#define HMX_CVT_UH_ACC_2X1(ctrl) \ + "cvt.uh = acc(" ctrl "):2x1\n" + +#define HMX_STORE_CVT_SM(out, range) \ + "mxmem(" out ", " range ") = cvt\n" + +#define HMX_STORE_CVT_CM(out, range) \ + "mxmem(" out ", " range "):cm = cvt\n" + +static inline uint32_t hmx_act_sm_range(uint32_t n_tiles) { + return 2048u * n_tiles - 1u; +} + +static inline uint32_t hmx_out_cm_range(void) { + return 0x3Fu << 5; +} + +static inline uint32_t hmx_wt_b_range(uint32_t n_bytes) { + return ((n_bytes - 128u) & ~127u) | 0x7Fu; +} + +static inline uint32_t hmx_cvt_ctrl(uint32_t bank, uint32_t frac_only, uint32_t sat_mode, uint32_t retain_acc) { + return (1u << 15) | ((frac_only & 1u) << 14) | ((bank & 3u) << 12) | ((sat_mode & 1u) << 1) | (retain_acc & 1u); +} + +static inline void hmx_load_bias_bank(const void * addr, uint32_t bank) { + uint32_t rs = ((uint32_t) (uintptr_t) addr & ~255u) | (bank & 3u); + asm volatile("bias = mxmem2(%0)\n" :: "r"(rs) : "memory"); +} + #endif // HMX_UTILS_H diff --git a/ggml/src/ggml-hexagon/htp/htp-ctx.h b/ggml/src/ggml-hexagon/htp/htp-ctx.h index 27b56ff0be10..b514f633e59a 100644 --- a/ggml/src/ggml-hexagon/htp/htp-ctx.h +++ b/ggml/src/ggml-hexagon/htp/htp-ctx.h @@ -1,10 +1,11 @@ #ifndef HTP_CTX_H #define HTP_CTX_H +#include "dma-proxy.h" #include "dma-queue.h" #include "hmx-queue.h" -#include "htp-dcache.h" #include "htp-ops.h" +#include "htp-thread.h" #include "htp-trace.h" #include "work-queue.h" #include "hex-fastdiv.h" @@ -27,15 +28,6 @@ struct htp_mmap { uint32_t flags; }; -// Scratchpad state -struct htp_spad { - const struct htp_tensor * src; // original src of the data (for reuse) - uint8_t * data; // pointer to an area in vtcm - uint32_t stride; // stride used inside this spad - uint32_t size; // total size - uint32_t size_per_hvx; // size per hvx -}; - struct htp_mdev_group { uint16_t idx; uint16_t count; @@ -61,11 +53,6 @@ struct htp_ops_context { const struct htp_tensor * dsts[HTP_OP_MAX_OUTPUTS]; }; - // TODO convert these to an array - struct htp_spad src0_spad; - struct htp_spad src1_spad; - struct htp_spad dst_spad; - uint32_t flags; uint32_t n_hvx; struct fastdiv_values n_hvx_div; @@ -86,8 +73,10 @@ struct htp_context { struct htp_mmap mmap[HTP_MAX_MMAPS]; dma_queue_t dma[HTP_MAX_NTHREADS]; struct htp_thread_trace trace[HTP_MAX_NTHREADS]; + htp_thread_t main_th; work_queue_t hvx_queue; hmx_queue_t hmx_queue; + dma_proxy_t dma_proxy; uint32_t n_threads; uint32_t n_hvx; @@ -107,7 +96,6 @@ struct htp_context { atomic_bool vtcm_needs_release; uint64_t max_vmem; - struct htp_dirty_range dirty_ranges[HTP_MAX_DIRTY_RANGES]; // Persistent DDR scratchpad for MUL_MAT_ID mappings void * ddr_spad_base; diff --git a/ggml/src/ggml-hexagon/htp/htp-dcache.c b/ggml/src/ggml-hexagon/htp/htp-dcache.c deleted file mode 100644 index 52fc8e403864..000000000000 --- a/ggml/src/ggml-hexagon/htp/htp-dcache.c +++ /dev/null @@ -1,357 +0,0 @@ -#include "htp-dcache.h" - -#include -#include -#include - -#include "hex-common.h" -#include "hex-utils.h" -#include "hex-fastdiv.h" -#include "htp-trace.h" -#include "htp-ctx.h" -#include "work-queue.h" - -struct l2flush_range { - uint32_t start; // line-aligned start address - uint32_t end; // line-aligned end address - uint32_t block_first; // global block index of this range's first block - uint32_t n_blocks; // number of HTP_DCACHE_BLOCK_SIZE chunks (last may be partial) -}; - -struct l2flush_multi_task { - struct l2flush_range ranges[HTP_MAX_DIRTY_RANGES]; - uint32_t n_ranges; - uint32_t total_blocks; - uint32_t blocks_per_hvx; -}; - -static void flush_all_dcache(struct htp_context * ctx) { - struct htp_thread_trace * tr = &ctx->trace[0]; - htp_trace_event_start(tr, HTP_TRACE_EVT_L2FLUSH, 0); - qurt_mem_cache_clean((qurt_addr_t) 0, 0, QURT_MEM_CACHE_FLUSH_INVALIDATE_ALL, QURT_MEM_DCACHE); - hex_l2fetch_block(ctx, ctx->footprint); - htp_trace_event_stop(tr, HTP_TRACE_EVT_L2FLUSH, 0); - memset(ctx->dirty_ranges, 0, sizeof(ctx->dirty_ranges)); -} - -static void l2flush_multi_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { - struct l2flush_multi_task * task = (struct l2flush_multi_task *) data; - (void) n; - - const uint32_t gb_first = i * task->blocks_per_hvx; - uint32_t gb_last = gb_first + task->blocks_per_hvx; - if (gb_last > task->total_blocks) { - gb_last = task->total_blocks; - } - if (gb_first >= gb_last) { - return; - } - - struct htp_thread_trace * tr = th->trace; - htp_trace_event_start(tr, HTP_TRACE_EVT_L2FLUSH, gb_first); - - for (uint32_t r = 0; r < task->n_ranges; r++) { - const struct l2flush_range * rg = &task->ranges[r]; - const uint32_t rb_first = rg->block_first; - const uint32_t rb_last = rg->block_first + rg->n_blocks; - - const uint32_t lo = gb_first > rb_first ? gb_first : rb_first; - const uint32_t hi = gb_last < rb_last ? gb_last : rb_last; - if (lo >= hi) { - continue; - } - - const uint32_t s = rg->start + (lo - rb_first) * HTP_DCACHE_BLOCK_SIZE; - uint32_t e = rg->start + (hi - rb_first) * HTP_DCACHE_BLOCK_SIZE; - if (e > rg->end) { - e = rg->end; - } - hex_l2flush((void *) (uintptr_t) s, e - s); - } - - htp_trace_event_stop(tr, HTP_TRACE_EVT_L2FLUSH, gb_first); -} - -static void merge_dirty_ranges(struct htp_context * ctx) { - for (uint32_t i = 0; i < HTP_MAX_DIRTY_RANGES; i++) { - struct htp_dirty_range * r = &ctx->dirty_ranges[i]; - if (!r->start) continue; - - for (uint32_t j = 0; j < HTP_MAX_DIRTY_RANGES;) { - struct htp_dirty_range * s = &ctx->dirty_ranges[j]; - if (i == j || !s->start || r->end < s->start || s->end < r->start) { - j++; - continue; - } - - r->start = MIN(r->start, s->start); - r->end = MAX(r->end, s->end); - s->start = 0; - s->end = 0; - j = 0; - } - } -} - -void htp_dcache_mark_dirty_tensors(struct htp_context * ctx, const struct htp_tensor * const * tensors, uint32_t n) { - const struct htp_tensor * pending[HTP_OP_MAX_OUTPUTS]; - uint32_t n_pending = 0; - - for (uint32_t i = 0; i < n; i++) { - const struct htp_tensor * t = tensors[i]; - if (!t || (t->flags & (HTP_TENSOR_WEIGHT | HTP_TENSOR_FENCE))) { - continue; - } - - uint32_t t_start = t->data; - uint32_t t_end = t_start + t->size; - - bool merged = false; - for (uint32_t j = 0; j < HTP_MAX_DIRTY_RANGES; j++) { - struct htp_dirty_range * r = &ctx->dirty_ranges[j]; - if (!r->start) continue; - - if (r->start <= t_end && t_start <= r->end) { - uint32_t new_start = (t_start < r->start) ? t_start : r->start; - uint32_t new_end = (t_end > r->end) ? t_end : r->end; - r->start = new_start; - r->end = new_end; - merged = true; - } - } - - if (!merged) { - pending[n_pending++] = t; - } - } - - merge_dirty_ranges(ctx); - - if (n_pending == 0) { - return; - } - - uint32_t empty_indices[HTP_MAX_DIRTY_RANGES]; - uint32_t active_indices[HTP_MAX_DIRTY_RANGES]; - uint32_t n_active = 0; - uint32_t n_empty = 0; - for (uint32_t j = 0; j < HTP_MAX_DIRTY_RANGES; j++) { - if (ctx->dirty_ranges[j].start) { - active_indices[n_active++] = j; - } else { - empty_indices[n_empty++] = j; - } - } - - if (n_pending <= n_empty) { - for (uint32_t i = 0; i < n_pending; i++) { - uint32_t idx = empty_indices[i]; - struct htp_dirty_range * r = &ctx->dirty_ranges[idx]; - r->start = pending[i]->data; - r->end = pending[i]->data + pending[i]->size; - } - merge_dirty_ranges(ctx); - return; - } - - uint32_t n_evict = n_pending - n_empty; - uint32_t total_evict_size = 0; - for (uint32_t i = 0; i < n_evict; i++) { - uint32_t idx = active_indices[i]; - struct htp_dirty_range * r = &ctx->dirty_ranges[idx]; - total_evict_size += r->end - r->start; - } - - if (total_evict_size > HTP_DCACHE_FLUSH_ALL_THRESHOLD) { - flush_all_dcache(ctx); - for (uint32_t i = 0; i < n_pending; i++) { - struct htp_dirty_range * r = &ctx->dirty_ranges[i]; - r->start = pending[i]->data; - r->end = pending[i]->data + pending[i]->size; - } - merge_dirty_ranges(ctx); - return; - } - - if (total_evict_size > HTP_DCACHE_FLUSH_WQ_THRESHOLD && ctx->n_hvx > 1 && n_evict <= HTP_MAX_DIRTY_RANGES) { - struct l2flush_multi_task task; - task.n_ranges = n_evict; - - uint32_t block_acc = 0; - for (uint32_t i = 0; i < n_evict; i++) { - uint32_t idx = active_indices[i]; - struct htp_dirty_range * r = &ctx->dirty_ranges[idx]; - - struct l2flush_range * rg = &task.ranges[i]; - rg->start = hex_align_down((size_t) r->start, HEX_L2_LINE_SIZE); - rg->end = hex_align_up((size_t) r->end, HEX_L2_LINE_SIZE); - rg->block_first = block_acc; - rg->n_blocks = (rg->end - rg->start + HTP_DCACHE_BLOCK_SIZE - 1) / HTP_DCACHE_BLOCK_SIZE; - block_acc += rg->n_blocks; - } - - task.total_blocks = block_acc; - task.blocks_per_hvx = fastdiv(block_acc + ctx->n_hvx - 1, &ctx->n_hvx_div); - - work_queue_run(ctx->hvx_queue, l2flush_multi_worker, &task, ctx->n_hvx); - } else { - struct htp_thread_trace * tr = &ctx->trace[0]; - htp_trace_event_start(tr, HTP_TRACE_EVT_L2FLUSH, 0); - for (uint32_t i = 0; i < n_evict; i++) { - uint32_t idx = active_indices[i]; - struct htp_dirty_range * r = &ctx->dirty_ranges[idx]; - uint32_t size = r->end - r->start; - hex_l2flush((void *) (uintptr_t) r->start, size); - } - htp_trace_event_stop(tr, HTP_TRACE_EVT_L2FLUSH, 0); - } - - for (uint32_t i = 0; i < n_evict; i++) { - uint32_t idx = active_indices[i]; - struct htp_dirty_range * r = &ctx->dirty_ranges[idx]; - r->start = pending[i]->data; - r->end = pending[i]->data + pending[i]->size; - } - - for (uint32_t i = 0; i < n_empty; i++) { - uint32_t idx = empty_indices[i]; - struct htp_dirty_range * r = &ctx->dirty_ranges[idx]; - r->start = pending[n_evict + i]->data; - r->end = pending[n_evict + i]->data + pending[n_evict + i]->size; - } - - merge_dirty_ranges(ctx); -} - -static void make_tensor_clean(struct htp_context * ctx, const struct htp_tensor * t) { - if (!t || (t->flags & (HTP_TENSOR_WEIGHT | HTP_TENSOR_FENCE))) { - return; - } - - uint32_t t_start = t->data; - uint32_t t_end = t_start + t->size; - - for (uint32_t i = 0; i < HTP_MAX_DIRTY_RANGES; i++) { - struct htp_dirty_range * r = &ctx->dirty_ranges[i]; - if (!r->start) continue; - - if (r->start < t_end && t_start < r->end) { - if (t_start <= r->start && r->end <= t_end) { - r->start = 0; - r->end = 0; - } else if (t_start <= r->start) { - r->start = t_end; - } else if (r->end <= t_end) { - r->end = t_start; - } - } - } -} - -static inline bool is_tensor_dirty(struct htp_context * ctx, const struct htp_tensor * t) { - if (!t || (t->flags & (HTP_TENSOR_WEIGHT | HTP_TENSOR_FENCE))) { - return false; - } - - uint32_t t_start = t->data; - uint32_t t_end = t_start + t->size; - - for (uint32_t i = 0; i < HTP_MAX_DIRTY_RANGES; i++) { - struct htp_dirty_range * r = &ctx->dirty_ranges[i]; - if (!r->start) continue; - - if (r->start < t_end && t_start < r->end) { - return true; - } - } - return false; -} - -static void flush_dirty_ranges(struct htp_context * ctx, const struct htp_dirty_range * ranges, uint32_t n_ranges, uint64_t total_dirty) { - if (total_dirty >= HTP_DCACHE_FLUSH_WQ_THRESHOLD && ctx->n_hvx > 1) { - struct l2flush_multi_task task; - task.n_ranges = n_ranges; - - uint32_t block_acc = 0; - for (uint32_t i = 0; i < n_ranges; i++) { - const struct htp_dirty_range * r = &ranges[i]; - struct l2flush_range * rg = &task.ranges[i]; - rg->start = hex_align_down((size_t) r->start, HEX_L2_LINE_SIZE); - rg->end = hex_align_up((size_t) r->end, HEX_L2_LINE_SIZE); - rg->block_first = block_acc; - rg->n_blocks = (rg->end - rg->start + HTP_DCACHE_BLOCK_SIZE - 1) / HTP_DCACHE_BLOCK_SIZE; - block_acc += rg->n_blocks; - } - - task.total_blocks = block_acc; - task.blocks_per_hvx = fastdiv(block_acc + ctx->n_hvx - 1, &ctx->n_hvx_div); - - work_queue_run(ctx->hvx_queue, l2flush_multi_worker, &task, ctx->n_hvx); - } else { - struct htp_thread_trace * tr = &ctx->trace[0]; - htp_trace_event_start(tr, HTP_TRACE_EVT_L2FLUSH, 0); - for (uint32_t i = 0; i < n_ranges; i++) { - const struct htp_dirty_range * r = &ranges[i]; - hex_l2flush((void *) (uintptr_t) r->start, r->end - r->start); - } - htp_trace_event_stop(tr, HTP_TRACE_EVT_L2FLUSH, 0); - } -} - -void htp_dcache_flush_dirty_ranges(struct htp_context * ctx) { - struct htp_dirty_range ranges[HTP_MAX_DIRTY_RANGES]; - uint32_t n_ranges = 0; - uint64_t total_dirty = 0; - - for (uint32_t i = 0; i < HTP_MAX_DIRTY_RANGES; i++) { - const struct htp_dirty_range * r = &ctx->dirty_ranges[i]; - if (!r->start) { - continue; - } - ranges[n_ranges++] = *r; - total_dirty += r->end - r->start; - } - - if (total_dirty == 0) { - return; - } - - if (total_dirty > HTP_DCACHE_FLUSH_ALL_THRESHOLD) { - flush_all_dcache(ctx); - return; - } - - flush_dirty_ranges(ctx, ranges, n_ranges, total_dirty); - memset(ctx->dirty_ranges, 0, sizeof(ctx->dirty_ranges)); -} - -void htp_dcache_flush_dirty_tensors(struct htp_context * ctx, const struct htp_tensor * const * tensors, uint32_t n) { - const struct htp_tensor * dirty_tensors[HTP_OP_MAX_INPUTS]; - struct htp_dirty_range ranges[HTP_OP_MAX_INPUTS]; - uint32_t n_dirty = 0; - uint64_t total_dirty = 0; - - for (uint32_t i = 0; i < n; i++) { - const struct htp_tensor * t = tensors[i]; - if (is_tensor_dirty(ctx, t)) { - dirty_tensors[n_dirty++] = t; - ranges[n_dirty - 1].start = t->data; - ranges[n_dirty - 1].end = t->data + t->size; - total_dirty += t->size; - } - } - - if (total_dirty == 0) { - return; - } - - if (total_dirty > HTP_DCACHE_FLUSH_ALL_THRESHOLD) { - flush_all_dcache(ctx); - return; - } - - flush_dirty_ranges(ctx, ranges, n_dirty, total_dirty); - for (uint32_t i = 0; i < n_dirty; i++) { - make_tensor_clean(ctx, dirty_tensors[i]); - } -} diff --git a/ggml/src/ggml-hexagon/htp/htp-dcache.h b/ggml/src/ggml-hexagon/htp/htp-dcache.h deleted file mode 100644 index c1c37573ceb0..000000000000 --- a/ggml/src/ggml-hexagon/htp/htp-dcache.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef HTP_DCACHE_H -#define HTP_DCACHE_H - -#include -#include "hex-common.h" -#include "htp-ops.h" - -#define HTP_MAX_DIRTY_RANGES 64 -#define HTP_DCACHE_BLOCK_SIZE (HEX_L2_LINE_SIZE * 4) // flush granularity (chunks per thread) -#define HTP_DCACHE_FLUSH_WQ_THRESHOLD (4 * 1024) -#define HTP_DCACHE_FLUSH_ALL_THRESHOLD (4 * 1024 * 1024) - -struct htp_dirty_range { - uint32_t start; - uint32_t end; -}; - -struct htp_context; - -void htp_dcache_flush_dirty_ranges(struct htp_context * ctx); -void htp_dcache_flush_dirty_tensors(struct htp_context * ctx, const struct htp_tensor * const * tensors, uint32_t n); -void htp_dcache_mark_dirty_tensors(struct htp_context * ctx, const struct htp_tensor * const * tensors, uint32_t n); - -#endif // HTP_DCACHE_H diff --git a/ggml/src/ggml-hexagon/htp/htp-ops.h b/ggml/src/ggml-hexagon/htp/htp-ops.h index 2cb49c0a8f46..25a2b64592c1 100644 --- a/ggml/src/ggml-hexagon/htp/htp-ops.h +++ b/ggml/src/ggml-hexagon/htp/htp-ops.h @@ -129,6 +129,7 @@ enum htp_op_code { HTP_OP_LIGHTNING_INDEXER, HTP_OP_SSM_SCAN, HTP_OP_TIMESTEP_EMBEDDING, + HTP_OP_MUL_MAT_NX_GLU, HTP_OP_INVALID }; @@ -154,10 +155,11 @@ enum htp_op_code { #define HTP_DDR_SPAD_SIZE (512 * 1024) enum htp_tensor_flags { - HTP_TENSOR_WEIGHT = (1U << 0), // Tensor buffer model weight data (not compute) - HTP_TENSOR_TILED = (1U << 1), // Tensor is in tiled format - HTP_TENSOR_FENCE = (1U << 2), // Tensor is synchronization fence (explicitly managed) - HTP_TENSOR_FUSEABLE = (1U << 3), // Tensor can be fused (host-only) + HTP_TENSOR_WEIGHT = (1U << 0), // Tensor buffer model weight data (not compute) + HTP_TENSOR_TILED = (1U << 1), // Tensor is in tiled format + HTP_TENSOR_FENCE = (1U << 2), // Tensor is synchronization fence (explicitly managed) + HTP_TENSOR_FUSEABLE = (1U << 3), // Tensor can be fused (host-only) + HTP_TENSOR_LOWERED_F16 = (1U << 4), // F32 tensor lowered in-place to F16 (host-only) }; enum htp_buf_flags { diff --git a/ggml/src/ggml-hexagon/htp/htp-tensor.c b/ggml/src/ggml-hexagon/htp/htp-tensor.c new file mode 100644 index 000000000000..eceaa270abd8 --- /dev/null +++ b/ggml/src/ggml-hexagon/htp/htp-tensor.c @@ -0,0 +1,86 @@ +#include "htp-tensor.h" + +#include + +#include "dma-copy.h" +#include "hex-utils.h" + +#define HTP_TENSOR_READ_SMALL_BYTES 256 + +static inline void htp_tensor_read_l2flush(const htp_thread_t * th, uintptr_t start, size_t len) { + const uintptr_t s = hex_align_down(start, HEX_L2_LINE_SIZE); + const uintptr_t e = hex_align_up(start + len, HEX_L2_LINE_SIZE); + if (e <= s) { + return; + } + htp_trace_event_start(th->trace, HTP_TRACE_EVT_L2FLUSH, 0); + hex_l2flush((void *) s, e - s); + htp_trace_event_stop(th->trace, HTP_TRACE_EVT_L2FLUSH, 0); +} + +size_t htp_tensor_read(const htp_thread_t * th, void * dst, size_t dst_size, const struct htp_tensor * src) { + if (!th || !dst || !src) { + return 0; + } + + const uint32_t ne0 = src->ne[0]; + const uint32_t ne1 = src->ne[1]; + const uint32_t ne2 = src->ne[2]; + const uint32_t ne3 = src->ne[3]; + if (ne0 == 0 || ne1 == 0 || ne2 == 0 || ne3 == 0) { + return 0; + } + + const uint32_t row_bytes = htp_tensor_get_row_size(src->type, ne0); + if (row_bytes == 0 || (row_bytes % ne0) != 0) { + return 0; + } + + const uint32_t elem_size = row_bytes / ne0; + const size_t nrows = (size_t) ne1 * ne2 * ne3; + const size_t total_bytes = (size_t) row_bytes * nrows; + if (total_bytes > dst_size) { + return 0; + } + + const uintptr_t dst_addr = (uintptr_t) dst; + const bool is_contig = htp_tensor_is_contiguous(src, elem_size); + + if (!htp_tensor_is_extended(src) && is_contig && total_bytes <= HTP_TENSOR_READ_SMALL_BYTES) { + if (!(src->flags & (HTP_TENSOR_WEIGHT | HTP_TENSOR_FENCE))) { + htp_tensor_read_l2flush(th, (uintptr_t) src->data, total_bytes); + } + memcpy(dst, (const void *) (uintptr_t) src->data, total_bytes); + return total_bytes; + } + + htp_tensor_read_l2flush(th, dst_addr, total_bytes); + + dma_queue * dma_q = th->dma_q; + if (ne0 > 1 && src->nb[0] != elem_size) { + dma_addr_t cur_dst = (dma_addr_t) dst_addr; + for (uint32_t i3 = 0; i3 < ne3; ++i3) { + for (uint32_t i2 = 0; i2 < ne2; ++i2) { + for (uint32_t i1 = 0; i1 < ne1; ++i1) { + const dma_addr_t cur_src = src->data + + (dma_addr_t) i1 * src->nb[1] + + (dma_addr_t) i2 * src->nb[2] + + (dma_addr_t) i3 * src->nb[3]; + dma_cpy_push_2d_chunked(dma_q, cur_dst, cur_src, elem_size, src->nb[0], elem_size, ne0); + cur_dst += row_bytes; + } + } + } + } else { + struct htp_tensor dst_t = *src; + dst_t.data = (dma_addr_t) dst_addr; + dst_t.nb[0] = elem_size; + dst_t.nb[1] = row_bytes; + dst_t.nb[2] = row_bytes * ne1; + dst_t.nb[3] = dst_t.nb[2] * ne2; + dma_cpy_sametype_sameshape(dma_q, &dst_t, src, elem_size); + } + dma_queue_flush(dma_q); + + return total_bytes; +} diff --git a/ggml/src/ggml-hexagon/htp/htp-tensor.h b/ggml/src/ggml-hexagon/htp/htp-tensor.h index 2f9a4b129125..23122959d12c 100644 --- a/ggml/src/ggml-hexagon/htp/htp-tensor.h +++ b/ggml/src/ggml-hexagon/htp/htp-tensor.h @@ -8,8 +8,6 @@ #include "hex-common.h" #include "hex-fastdiv.h" -#define HTP_TENSOR_MDEV_LINE_SIZE 128 - // Currently HMX requires 32x32 tile formats (do not change) #define HTP_TENSOR_TILE_N_COLS 32 #define HTP_TENSOR_TILE_N_ROWS 32 @@ -69,53 +67,6 @@ static inline bool htp_tensor_is_permuted(const struct htp_tensor * t) { return t->nb[0] > t->nb[1] || t->nb[1] > t->nb[2] || t->nb[2] > t->nb[3]; } -static inline bool htp_tensor_mdev_data_aligned(const struct htp_tensor * t) { - return ((uintptr_t) t->data & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0; -} - -static inline bool htp_tensor_can_row_partition(const struct htp_tensor * t, uint32_t elem_size) { - if (!htp_tensor_mdev_data_aligned(t)) { - return false; - } - if (t->ne[0] != 1 && t->nb[0] != elem_size) { - return false; - } - if (htp_tensor_is_permuted(t)) { - return false; - } - if (t->ne[1] > 1 && (t->nb[1] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) != 0) return false; - if (t->ne[2] > 1 && (t->nb[2] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) != 0) return false; - if (t->ne[3] > 1 && (t->nb[3] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) != 0) return false; - return true; -} - -static inline bool htp_tensor_mdev_rows_per_chunk(const struct htp_tensor * t, uint32_t elem_size, uint32_t row_size, uint32_t * rows_per_chunk) { - *rows_per_chunk = 0; - - if (!htp_tensor_mdev_data_aligned(t)) { - return false; - } - if (t->ne[0] != 1 && t->nb[0] != elem_size) { - return false; - } - if (htp_tensor_is_permuted(t)) { - return false; - } - if (t->ne[1] > 1 && (t->nb[1] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0 && - (t->ne[2] <= 1 || (t->nb[2] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0) && - (t->ne[3] <= 1 || (t->nb[3] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0)) { - *rows_per_chunk = 1; - return true; - } - if (t->nb[1] == row_size && - (t->ne[2] <= 1 || t->nb[2] == t->nb[1] * t->ne[1]) && - (t->ne[3] <= 1 || t->nb[3] == t->nb[2] * t->ne[2])) { - *rows_per_chunk = (row_size > 0) ? (HTP_TENSOR_MDEV_LINE_SIZE / hex_gcd_u32(row_size, HTP_TENSOR_MDEV_LINE_SIZE)) : 1; - return true; - } - return false; -} - static inline struct htp_tensor_mdev_range htp_tensor_mdev_partition(uint32_t total_units, uint32_t units_per_chunk, uint32_t mdev_idx, uint32_t mdev_count, const struct fastdiv_values * mdev_count_div) { struct htp_tensor_mdev_range range = { 0, total_units }; @@ -214,4 +165,16 @@ static inline uint32_t htp_tensor_get_row_size(int type, uint32_t ne00) { } } +static inline size_t htp_tensor_nbytes(const struct htp_tensor * t) { + return (size_t) htp_tensor_get_row_size(t->type, t->ne[0]) * t->ne[1] * t->ne[2] * t->ne[3]; +} + +#ifdef __HVX_ARCH__ +#include "htp-thread.h" + +// Read tensor data contiguously into a 128-byte aligned cached DDR buffer. +// [dst, hex_align_up(dst + bytes, 128)) must be exclusively owned by the caller. +size_t htp_tensor_read(const htp_thread_t * th, void * dst, size_t dst_size, const struct htp_tensor * src); +#endif + #endif // HTP_TENSOR_H diff --git a/ggml/src/ggml-hexagon/htp/htp-vtcm.h b/ggml/src/ggml-hexagon/htp/htp-vtcm.h index a1e90575fb1c..f17fde80d4e7 100644 --- a/ggml/src/ggml-hexagon/htp/htp-vtcm.h +++ b/ggml/src/ggml-hexagon/htp/htp-vtcm.h @@ -4,6 +4,13 @@ #include #include +// Reserve one HVX vector at the end of physical VTCM so tail hvx_vmemu loads cannot fault past the page end +#define HTP_VTCM_GUARD_SIZE 128 + +static inline size_t htp_vtcm_usable_size(size_t raw_size) { + return (raw_size - HTP_VTCM_GUARD_SIZE) & ~(size_t) 127; +} + static inline uint8_t *vtcm_seq_alloc(uint8_t **vtcm_ptr, size_t size) { uint8_t *p = *vtcm_ptr; *vtcm_ptr += size; diff --git a/ggml/src/ggml-hexagon/htp/hvx-base.h b/ggml/src/ggml-hexagon/htp/hvx-base.h index e87a30d14e7c..c80ce5bb6ea9 100644 --- a/ggml/src/ggml-hexagon/htp/hvx-base.h +++ b/ggml/src/ggml-hexagon/htp/hvx-base.h @@ -12,6 +12,10 @@ #define hvx_vmem(A) *((HVX_Vector *)(A)) #define hvx_vmemu(A) *((HVX_UVector *)(A)) +static inline void hvx_vmem_store_nt(void * restrict dst, HVX_Vector v) { + asm("vmem(%1+#0):nt = %2" : "=m"(*(HVX_Vector *) dst) : "r"(dst), "v"(v)); +} + static inline void hvx_vec_store_u(void * restrict dst, uint32_t n, HVX_Vector v) { // Rotate as needed. v = Q6_V_vlalign_VVR(v, v, (size_t) dst); @@ -187,6 +191,9 @@ static inline HVX_VectorPair hvx_vec_f16_to_f32(HVX_Vector v) { #endif static inline HVX_Vector hvx_vec_i16_from_hf_rnd_sat(HVX_Vector vin) { +#if __HVX_ARCH__ >= 81 + return Q6_Vh_equals_Vhf_rnd(vin); +#else // This looks complicated. // Ideally should just be Q6_Vh_equals_Vhf(vin) // but that instruction does not do proper rounding. @@ -208,10 +215,17 @@ static inline HVX_Vector hvx_vec_i16_from_hf_rnd_sat(HVX_Vector vin) { // now round down to 16 return Q6_Vh_vround_VwVw_sat(vsf_1, vsf_0); +#endif } #if __HVX_ARCH__ < 79 +static inline HVX_VectorPair hvx_vec_mpy_f32_f16(HVX_Vector x, HVX_Vector y) +{ + HVX_VectorPair m = Q6_Wqf32_vmpy_VhfVhf(x, y); + return Q6_W_vcombine_VV(Q6_Vsf_equals_Vqf32(Q6_V_hi_W(m)), Q6_Vsf_equals_Vqf32(Q6_V_lo_W(m))); +} + static inline HVX_VectorPair hvx_vec_mpyacc_f32_f16(HVX_VectorPair acc, HVX_Vector x, HVX_Vector y) { HVX_VectorPair m = Q6_Wqf32_vmpy_VhfVhf(x, y); @@ -222,6 +236,11 @@ static inline HVX_VectorPair hvx_vec_mpyacc_f32_f16(HVX_VectorPair acc, HVX_Vect #else +static inline HVX_VectorPair hvx_vec_mpy_f32_f16(HVX_Vector x, HVX_Vector y) +{ + return Q6_Wsf_vmpy_VhfVhf(x, y); +} + static inline HVX_VectorPair hvx_vec_mpyacc_f32_f16(HVX_VectorPair acc, HVX_Vector x, HVX_Vector y) { return Q6_Wsf_vmpyacc_WsfVhfVhf(acc, x, y); @@ -400,7 +419,7 @@ static inline void hvx_transpose_32x32_w_shuff(uint8_t * restrict dst, uint32_t } } -// Specialized store that will follow outstanding scatters or gathers to make sure they complete +// Drain outstanding vscatter/vgather before DMA, HMX, or scalar access to the VTCM region. static inline void hvx_gather_sync(void * vtcm_addr) { asm volatile("vmem(%0+#0):scatter_release\n" "v0 = vmem(%0+#0)\n" :: "r"(vtcm_addr) : "v0", "memory"); @@ -424,7 +443,7 @@ static inline HVX_Vector hvx_vec_gather_offsets_h(uint32_t stride) { } // Rows [0, nrows) of the transpose of ncols src vectors (src_stride apart) to dst. -// src, dst in VTCM. Async: hvx_gather_sync() before use. +// src, dst in VTCM. Async: call hvx_gather_sync() before DMA, HMX, or scalar access. // Use for partial tiles (small ncols). Fewest packets. static inline void hvx_transpose_32x32_w_gather(uint8_t * restrict dst, uint32_t dst_stride, const uint8_t * restrict src, uint32_t src_stride, HVX_Vector offsets, uint32_t nrows, uint32_t ncols) { diff --git a/ggml/src/ggml-hexagon/htp/hvx-dump.h b/ggml/src/ggml-hexagon/htp/hvx-dump.h index 85201fc34532..684387d98453 100644 --- a/ggml/src/ggml-hexagon/htp/hvx-dump.h +++ b/ggml/src/ggml-hexagon/htp/hvx-dump.h @@ -9,7 +9,7 @@ #include "hex-utils.h" #include "hvx-types.h" -static void hvx_vec_dump_f16_n(char * pref, HVX_Vector v, uint32_t n) { +static inline void hvx_vec_dump_f16_n(char * pref, HVX_Vector v, uint32_t n) { HVX_VectorAlias u = { .v = v }; const uint32_t n0 = n / 16; @@ -23,11 +23,11 @@ static void hvx_vec_dump_f16_n(char * pref, HVX_Vector v, uint32_t n) { } } -static void hvx_vec_dump_f16(char * pref, HVX_Vector v) { +static inline void hvx_vec_dump_f16(char * pref, HVX_Vector v) { hvx_vec_dump_f16_n(pref, v, 64); } -static void hvx_vec_dump_f32_n(char * pref, HVX_Vector v, uint32_t n) { +static inline void hvx_vec_dump_f32_n(char * pref, HVX_Vector v, uint32_t n) { HVX_VectorAlias u = { .v = v }; const uint32_t n0 = n / 16; @@ -41,21 +41,22 @@ static void hvx_vec_dump_f32_n(char * pref, HVX_Vector v, uint32_t n) { } } -static void hvx_vec_dump_f32_hmt(char * pref, HVX_Vector v) { +static inline void hvx_vec_dump_f32_hmt(char * pref, HVX_Vector v) { union { HVX_Vector v; float d[32]; } u = { .v = v }; + (void) u; FARF(HIGH, "%s: %.6f %.6f %.6f %.6f ... %.6f %.6f %.6f %.6f ... %.6f %.6f %.6f %.6f\n", pref, u.d[0], u.d[1], u.d[2], u.d[3], u.d[12], u.d[13], u.d[14], u.d[15], u.d[28], u.d[29], u.d[30], u.d[31]); } -static void hvx_vec_dump_f32(char * pref, HVX_Vector v) { +static inline void hvx_vec_dump_f32(char * pref, HVX_Vector v) { hvx_vec_dump_f32_n(pref, v, 32); } -static void hvx_vec_dump_int32(char * pref, HVX_Vector v) { +static inline void hvx_vec_dump_int32(char * pref, HVX_Vector v) { union { HVX_Vector v; int32_t d[32]; @@ -66,27 +67,29 @@ static void hvx_vec_dump_int32(char * pref, HVX_Vector v) { } } -static void hvx_vec_dump_int32_hmt(char * pref, HVX_Vector v) { +static inline void hvx_vec_dump_int32_hmt(char * pref, HVX_Vector v) { union { HVX_Vector v; int32_t d[32]; } u = { .v = v }; + (void) u; FARF(HIGH, "%s: %d %d %d %d ... %d %d %d %d ... %d %d %d %d\n", pref, u.d[0], u.d[1], u.d[2], u.d[3], u.d[12], u.d[13], u.d[14], u.d[15], u.d[28], u.d[29], u.d[30], u.d[31]); } -static void hvx_vec_dump_int8_hmt(char * pref, HVX_Vector v) { +static inline void hvx_vec_dump_int8_hmt(char * pref, HVX_Vector v) { union { HVX_Vector v; int8_t d[128]; } u = { .v = v }; + (void) u; FARF(HIGH, "%s: %d %d %d %d ... %d %d %d %d ... %d %d %d %d\n", pref, u.d[0], u.d[1], u.d[2], u.d[3], u.d[60], u.d[61], u.d[62], u.d[63], u.d[124], u.d[125], u.d[126], u.d[127]); } -static void hvx_vec_dump_int8(char * pref, HVX_Vector v) { +static inline void hvx_vec_dump_int8(char * pref, HVX_Vector v) { union { HVX_Vector v; int8_t d[128]; @@ -97,7 +100,7 @@ static void hvx_vec_dump_int8(char * pref, HVX_Vector v) { } } -static void hvx_vec_dump_uint8(char * pref, HVX_Vector v) { +static inline void hvx_vec_dump_uint8(char * pref, HVX_Vector v) { union { HVX_Vector v; uint8_t d[128]; @@ -108,7 +111,7 @@ static void hvx_vec_dump_uint8(char * pref, HVX_Vector v) { } } -static bool hvx_vec_eq(HVX_Vector v0, HVX_Vector v1, size_t n) { +static inline bool hvx_vec_eq(HVX_Vector v0, HVX_Vector v1, size_t n) { typedef union { HVX_Vector v; int8_t d[128]; diff --git a/ggml/src/ggml-hexagon/htp/hvx-exp.h b/ggml/src/ggml-hexagon/htp/hvx-exp.h index 93ca8cf5133a..b69534a744ea 100644 --- a/ggml/src/ggml-hexagon/htp/hvx-exp.h +++ b/ggml/src/ggml-hexagon/htp/hvx-exp.h @@ -214,7 +214,25 @@ static inline void hvx_exp_f32(uint8_t * restrict dst, const uint8_t * restrict } } -static inline HVX_Vector hvx_vec_exp2_f16(HVX_Vector x_v) { +// 2^x on 64 fp16 lanes, requires x <= 0 +#if __HVX_ARCH__ >= 81 +#define HVX_EXP2_FIXED_G0 (-12573) +#define HVX_EXP2_FIXED_G1 (15210) +#define HVX_EXP2_FIXED_G2 (-2645) +#define HVX_EXP2_FIXED_G2_PAIR ((int32_t) ((uint32_t) (uint16_t) HVX_EXP2_FIXED_G2 * 0x00010001u)) + +static inline HVX_Vector hvx_vec_exp2_neg_f16(HVX_Vector x_v) { + const HVX_Vector z = Q6_Vuh_vmin_VuhVuh(Q6_V_vand_VV(x_v, Q6_Vh_vsplat_R(0x7FFF)), Q6_Vh_vsplat_R(0x4E40)); + const HVX_Vector t = Q6_Vh_equals_Vhf_rnd(Q6_Vh_vadd_VhVh(z, Q6_Vh_vsplat_R(0x2800))); + const HVX_Vector rho = Q6_V_vand_VV(t, Q6_Vh_vsplat_R(0x03FF)); + const HVX_Vector r15 = Q6_Vh_vasl_VhR(rho, 5); + HVX_Vector r = Q6_Vh_vadd_VhVh(Q6_Vh_vmpy_VhRh_s1_rnd_sat(r15, HVX_EXP2_FIXED_G2_PAIR), Q6_Vh_vsplat_R(HVX_EXP2_FIXED_G1)); + r = Q6_Vh_vadd_VhVh(Q6_Vh_vmpy_VhVh_s1_rnd_sat(r, r15), Q6_Vh_vsplat_R(HVX_EXP2_FIXED_G0)); + const HVX_Vector b = Q6_Vh_vadd_VhVh(Q6_Vh_vsub_VhVh(Q6_Vh_vsplat_R(0x6400), t), Q6_Vh_vmpy_VhVh_s1_rnd_sat(r, rho)); + return Q6_Vhf_equals_Wqf32(Q6_Wqf32_vmpy_VhfVhf(b, Q6_Vh_vsplat_R(0x1400))); +} +#else +static inline HVX_Vector hvx_vec_exp2_neg_f16(HVX_Vector x_v) { const HVX_Vector zero_v = Q6_V_vzero(); const HVX_Vector half_hf_v = Q6_Vh_vsplat_R(0x3800); // fp16 0.5 @@ -230,7 +248,7 @@ static inline HVX_Vector hvx_vec_exp2_f16(HVX_Vector x_v) { HVX_Vector x_qf16 = Q6_Vqf16_vsub_VhfVhf(x_v, f_v); // fractional part in qf16 // Horner: y = ((((E5*x + E4)*x + E3)*x + E2)*x + E1)*x + E0 - HVX_Vector y = Q6_Vqf16_vmpy_Vqf16Vqf16(Q6_Vh_vsplat_R(0x5082), x_qf16); // E5*x + HVX_Vector y = Q6_Vqf16_vmpy_Vqf16Vqf16(Q6_Vqf16_vadd_VhfVhf(Q6_Vh_vsplat_R(0x090c), zero_v), x_qf16); // E5*x y = Q6_Vqf16_vadd_Vqf16Vhf(y, Q6_Vh_vsplat_R(0x157d)); // + E4 y = Q6_Vqf16_vmpy_Vqf16Vqf16(y, x_qf16); y = Q6_Vqf16_vadd_Vqf16Vhf(y, Q6_Vh_vsplat_R(0x20ed)); // + E3 @@ -251,5 +269,6 @@ static inline HVX_Vector hvx_vec_exp2_f16(HVX_Vector x_v) { y = Q6_Vh_vaslacc_VhVhR(y, k_v, 10); return Q6_V_vmux_QVV(q_underflow, zero_v, y); } +#endif #endif /* HVX_EXP_H */ diff --git a/ggml/src/ggml-hexagon/htp/hvx-inverse.h b/ggml/src/ggml-hexagon/htp/hvx-inverse.h index 256a8843ba1b..312881b3d2f0 100644 --- a/ggml/src/ggml-hexagon/htp/hvx-inverse.h +++ b/ggml/src/ggml-hexagon/htp/hvx-inverse.h @@ -70,12 +70,9 @@ static inline HVX_Vector hvx_vec_inverse_f16(HVX_Vector vals) { // Get mantissa for 16-bit representation HVX_Vector mant_recip = Q6_V_vand_VV(Q6_Vh_vasr_VhR(Q6_Vh_vasl_VhVh(rm, vcl0), 5), Q6_Vh_vsplat_R(0x03FF)); - //Compute Reciprocal Exponent - HVX_Vector exp_recip = - Q6_Vh_vsub_VhVh(Q6_Vh_vsub_VhVh(Q6_Vh_vsplat_R(254), exp_u16), Q6_Vh_vsub_VhVh(vcl0, Q6_Vh_vsplat_R(1))); - //Convert it for 16-bit representation - exp_recip = Q6_Vh_vadd_VhVh_sat(Q6_Vh_vsub_VhVh(exp_recip, Q6_Vh_vsplat_R(127)), Q6_Vh_vsplat_R(15)); - exp_recip = Q6_Vh_vasl_VhR(exp_recip, 10); + // Compute reciprocal exponent for 16-bit representation: (254 - exp_u16) - (vcl0 - 1) - 127 + 15 + HVX_Vector exp_recip = Q6_Vh_vsub_VhVh(Q6_Vh_vsub_VhVh(Q6_Vh_vsplat_R(143), exp_u16), vcl0); + exp_recip = Q6_Vh_vasl_VhR(exp_recip, 10); //Merge exponent and mantissa for reciprocal HVX_Vector recip = Q6_V_vor_VV(exp_recip, mant_recip); @@ -86,6 +83,21 @@ static inline HVX_Vector hvx_vec_inverse_f16(HVX_Vector vals) { return recip; } +// Reciprocal of positive normal fp16 in [1.0f, 16384.0f] (e.g. 1 + exp(-|x|) in sigmoid). +static inline HVX_Vector hvx_vec_inverse_pos_f16(HVX_Vector avals) { + HVX_Vector mant_u16 = Q6_Vh_vasl_VhR(avals, 6); + HVX_Vector exp_u16 = Q6_Vuh_vlsr_VuhR(avals, 10); + + HVX_Vector rm = hvx_vec_recip_xp1_O3_unsigned(mant_u16); + HVX_Vector vcl0 = Q6_Vuh_vcl0_Vuh(rm); + + HVX_Vector mant_recip = Q6_V_vand_VV(Q6_Vh_vasr_VhR(Q6_Vh_vasl_VhVh(rm, vcl0), 5), Q6_Vh_vsplat_R(0x03FF)); + HVX_Vector exp_recip = Q6_Vh_vsub_VhVh(Q6_Vh_vsub_VhVh(Q6_Vh_vsplat_R(31), exp_u16), vcl0); + exp_recip = Q6_Vh_vasl_VhR(exp_recip, 10); + + return Q6_V_vor_VV(exp_recip, mant_recip); +} + static inline HVX_Vector hvx_vec_inverse_f32(HVX_Vector v_sf) { HVX_Vector inv_aprox_sf = Q6_V_vsplat_R(0x7EEEEBB3); HVX_Vector two_sf = hvx_vec_splat_f32(2.0); diff --git a/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-float.h b/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-float.h index d7488976bb19..53799b30aa2f 100644 --- a/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-float.h +++ b/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-float.h @@ -4,7 +4,7 @@ #include "hvx-utils.h" #include "htp-tensor.h" -// Float activation copy/quantization kernels (DDR -> VTCM) +// Float activation copy/quantization kernels (VTCM -> VTCM) static inline void quantize_f32_f32_kernel( const uint8_t * restrict src_data, @@ -16,9 +16,7 @@ static inline void quantize_f32_f32_kernel( size_t dst_stride ) { (void) tmp_data; - const size_t src_row_size = ne0 * sizeof(float); for (uint32_t i = 0; i < nrows; ++i) { - hex_l2fetch(src_data, src_row_size, src_stride, 2); hvx_copy_f32_au(dst_data, src_data, ne0); dst_data += dst_stride; @@ -36,9 +34,7 @@ static inline void quantize_f32_f16_kernel( size_t dst_stride ) { (void) tmp_data; - const size_t src_row_size = ne0 * sizeof(float); for (uint32_t i = 0; i < nrows; ++i) { - hex_l2fetch(src_data, src_row_size, src_stride, 2); hvx_copy_f16_f32_au(dst_data, src_data, ne0); dst_data += dst_stride; @@ -56,9 +52,7 @@ static inline void quantize_f16_f16_kernel( size_t dst_stride ) { (void) tmp_data; - const size_t src_row_size = ne0 * sizeof(float); for (uint32_t i = 0; i < nrows; ++i) { - hex_l2fetch(src_data, src_row_size, src_stride, 2); hvx_copy_f16_au(dst_data, src_data, ne0); dst_data += dst_stride; @@ -66,8 +60,65 @@ static inline void quantize_f16_f16_kernel( } } +static inline void quantize_f16_f32_kernel( + const uint8_t * restrict src_data, + uint8_t * restrict dst_data, + uint8_t * restrict tmp_data, + uint32_t ne0, + uint32_t nrows, + size_t src_stride, + size_t dst_stride +) { + (void) tmp_data; + const size_t dst_valid_bytes = ne0 * sizeof(float); + for (uint32_t i = 0; i < nrows; ++i) { + hvx_copy_f32_f16_au(dst_data, src_data, ne0); + if (dst_stride > dst_valid_bytes) { + hvx_splat_f32_u(dst_data + dst_valid_bytes, 0.0f, (dst_stride - dst_valid_bytes) / sizeof(float)); + } + + dst_data += dst_stride; + src_data += src_stride; + } +} + // Float dot product kernels (HVX) +typedef void (*hvx_flat_store_1x1_fn_t)(void * restrict s, HVX_Vector rsum); +typedef void (*hvx_flat_store_2x1_fn_t)(void * restrict s, HVX_Vector rsum0, HVX_Vector rsum1); + +static __attribute__((noinline)) void hvx_flat_store_1x1_f32(void * restrict s, HVX_Vector rsum) { + hvx_vec_store_u(s, 4, hvx_vec_reduce_sum_f32(rsum)); +} + +static __attribute__((noinline)) void hvx_flat_store_1x1_f16(void * restrict s, HVX_Vector rsum) { + HVX_Vector v_sum = hvx_vec_reduce_sum_f32(rsum); + const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); + const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); + v_sum = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v_sum)); + hvx_vec_store_u(s, 2, hvx_vec_f32_to_f16(v_sum, Q6_V_vzero())); +} + +static __attribute__((noinline)) void hvx_flat_store_2x1_f32(void * restrict s, HVX_Vector rsum0, HVX_Vector rsum1) { + hvx_vec_store_u(s, 8, hvx_vec_reduce_sum_f32x2(rsum0, rsum1)); +} + +static __attribute__((noinline)) void hvx_flat_store_2x1_f16(void * restrict s, HVX_Vector rsum0, HVX_Vector rsum1) { + HVX_Vector v_sum = hvx_vec_reduce_sum_f32x2(rsum0, rsum1); + const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); + const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); + v_sum = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v_sum)); + hvx_vec_store_u(s, 4, hvx_vec_f32_to_f16(v_sum, Q6_V_vzero())); +} + +static inline hvx_flat_store_1x1_fn_t resolve_hvx_flat_store_1x1_fn(uint32_t dst_elem_size) { + return (dst_elem_size == sizeof(__fp16)) ? hvx_flat_store_1x1_f16 : hvx_flat_store_1x1_f32; +} + +static inline hvx_flat_store_2x1_fn_t resolve_hvx_flat_store_2x1_fn(uint32_t dst_elem_size) { + return (dst_elem_size == sizeof(__fp16)) ? hvx_flat_store_2x1_f16 : hvx_flat_store_2x1_f32; +} + #if __HVX_ARCH__ < 79 #define HVX_OP_ADD_F32(a, b) Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_VsfVsf(a, b)) #define HVX_OP_MUL_F32(a, b) Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(a, b)) @@ -76,7 +127,7 @@ static inline void quantize_f16_f16_kernel( #define HVX_OP_MUL_F32(a, b) Q6_Vsf_vmpy_VsfVsf(a, b) #endif -static inline void flat_vec_dot_f32_f32_aa_1x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy) { +static inline void flat_vec_dot_f32_f32_aa_1x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, hvx_flat_store_1x1_fn_t store_1x1) { const HVX_Vector * restrict x = (const HVX_Vector *) vx; const HVX_Vector * restrict y = (const HVX_Vector *) vy; @@ -101,12 +152,12 @@ static inline void flat_vec_dot_f32_f32_aa_1x1(const uint32_t n, float * restric rsum = HVX_OP_ADD_F32(rsum, prod); } - *s = hvx_vec_get_f32(hvx_vec_reduce_sum_f32(rsum)); + store_1x1(s, rsum); } -static inline void flat_vec_dot_f32_f32_aa_2x1(const uint32_t n, float * restrict s0, +static inline void flat_vec_dot_f32_f32_aa_2x1(const uint32_t n, void * restrict s0, const void * restrict vx0, const void * restrict vx1, - const void * restrict vy0) { + const void * restrict vy0, hvx_flat_store_2x1_fn_t store_2x1) { const HVX_Vector * restrict x0 = (const HVX_Vector *) vx0; const HVX_Vector * restrict x1 = (const HVX_Vector *) vx1; const HVX_Vector * restrict y = (const HVX_Vector *) vy0; @@ -139,13 +190,12 @@ static inline void flat_vec_dot_f32_f32_aa_2x1(const uint32_t n, float * restric rsum1 = HVX_OP_ADD_F32(rsum1, prod1); } - HVX_Vector rsum = hvx_vec_reduce_sum_f32x2(rsum0, rsum1); - hvx_vec_store_u(s0, 8, rsum); + store_2x1(s0, rsum0, rsum1); } -static inline void flat_vec_dot_f32_f32_aa_2x2(const uint32_t n, float * restrict s0, float * restrict s1, +static inline void flat_vec_dot_f32_f32_aa_2x2(const uint32_t n, void * restrict s0, void * restrict s1, const void * restrict vx0, const void * restrict vx1, - const void * restrict vy0, const void * restrict vy1) { + const void * restrict vy0, const void * restrict vy1, hvx_flat_store_2x1_fn_t store_2x1) { const HVX_Vector * restrict x0 = (const HVX_Vector *) vx0; const HVX_Vector * restrict x1 = (const HVX_Vector *) vx1; const HVX_Vector * restrict y0 = (const HVX_Vector *) vy0; @@ -188,15 +238,11 @@ static inline void flat_vec_dot_f32_f32_aa_2x2(const uint32_t n, float * restric r1_c1_sum = HVX_OP_ADD_F32(r1_c1_sum, HVX_OP_MUL_F32(r1_sf, c1_sf)); } - // Reduce and store results - HVX_Vector r0_r1_c0_sum = hvx_vec_reduce_sum_f32x2(r0_c0_sum, r1_c0_sum); - HVX_Vector r0_r1_c1_sum = hvx_vec_reduce_sum_f32x2(r0_c1_sum, r1_c1_sum); - - hvx_vec_store_u(s0, 8, r0_r1_c0_sum); - hvx_vec_store_u(s1, 8, r0_r1_c1_sum); + store_2x1(s0, r0_c0_sum, r1_c0_sum); + store_2x1(s1, r0_c1_sum, r1_c1_sum); } -static inline void flat_vec_dot_bf16_f32_aa_1x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy) { +static inline void flat_vec_dot_bf16_f32_aa_1x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, hvx_flat_store_1x1_fn_t store_1x1) { const HVX_Vector * restrict x = (const HVX_Vector *) vx; const HVX_Vector * restrict y = (const HVX_Vector *) vy; @@ -240,12 +286,12 @@ static inline void flat_vec_dot_bf16_f32_aa_1x1(const uint32_t n, float * restri } HVX_Vector rsum = HVX_OP_ADD_F32(rsum0, rsum1); - *s = hvx_vec_get_f32(hvx_vec_reduce_sum_f32(rsum)); + store_1x1(s, rsum); } -static inline void flat_vec_dot_bf16_f32_aa_2x1(const uint32_t n, float * restrict s0, +static inline void flat_vec_dot_bf16_f32_aa_2x1(const uint32_t n, void * restrict s0, const void * restrict vx0, const void * restrict vx1, - const void * restrict vy0) { + const void * restrict vy0, hvx_flat_store_2x1_fn_t store_2x1) { const HVX_Vector * restrict x0 = (const HVX_Vector *) vx0; const HVX_Vector * restrict x1 = (const HVX_Vector *) vx1; const HVX_Vector * restrict y = (const HVX_Vector *) vy0; @@ -301,13 +347,12 @@ static inline void flat_vec_dot_bf16_f32_aa_2x1(const uint32_t n, float * restri } } - HVX_Vector rsum = hvx_vec_reduce_sum_f32x2(rsum0, rsum1); - hvx_vec_store_u(s0, 8, rsum); + store_2x1(s0, rsum0, rsum1); } -static inline void flat_vec_dot_bf16_f32_aa_2x2(const uint32_t n, float * restrict s0, float * restrict s1, +static inline void flat_vec_dot_bf16_f32_aa_2x2(const uint32_t n, void * restrict s0, void * restrict s1, const void * restrict vx0, const void * restrict vx1, - const void * restrict vy0, const void * restrict vy1) { + const void * restrict vy0, const void * restrict vy1, hvx_flat_store_2x1_fn_t store_2x1) { const HVX_Vector * restrict x0 = (const HVX_Vector *) vx0; const HVX_Vector * restrict x1 = (const HVX_Vector *) vx1; const HVX_Vector * restrict y0 = (const HVX_Vector *) vy0; @@ -382,17 +427,14 @@ static inline void flat_vec_dot_bf16_f32_aa_2x2(const uint32_t n, float * restri } } - HVX_Vector r0_r1_c0_sum = hvx_vec_reduce_sum_f32x2(r0_c0_sum, r1_c0_sum); - HVX_Vector r0_r1_c1_sum = hvx_vec_reduce_sum_f32x2(r0_c1_sum, r1_c1_sum); - - hvx_vec_store_u(s0, 8, r0_r1_c0_sum); - hvx_vec_store_u(s1, 8, r0_r1_c1_sum); + store_2x1(s0, r0_c0_sum, r1_c0_sum); + store_2x1(s1, r0_c1_sum, r1_c1_sum); } #undef HVX_OP_ADD_F32 #undef HVX_OP_MUL_F32 -static inline void flat_vec_dot_f16_f16_aa_1x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy) { +static inline void flat_vec_dot_f16_f16_aa_1x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, hvx_flat_store_1x1_fn_t store_1x1) { const HVX_Vector * restrict x = (const HVX_Vector *) vx; const HVX_Vector * restrict y = (const HVX_Vector *) vy; @@ -416,12 +458,12 @@ static inline void flat_vec_dot_f16_f16_aa_1x1(const uint32_t n, float * restric } HVX_Vector rsum = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_VsfVsf(Q6_V_lo_W(rsum_p), Q6_V_hi_W(rsum_p))); - hvx_vec_store_u(s, 4, hvx_vec_reduce_sum_f32(rsum)); + store_1x1(s, rsum); } -static inline void flat_vec_dot_f16_f16_aa_2x1(const uint32_t n, float * restrict s0, +static inline void flat_vec_dot_f16_f16_aa_2x1(const uint32_t n, void * restrict s0, const void * restrict vx0, const void * restrict vx1, - const void * restrict vy0) { + const void * restrict vy0, hvx_flat_store_2x1_fn_t store_2x1) { const HVX_Vector * restrict x0 = (const HVX_Vector *) vx0; const HVX_Vector * restrict x1 = (const HVX_Vector *) vx1; const HVX_Vector * restrict y = (const HVX_Vector *) vy0; @@ -452,13 +494,12 @@ static inline void flat_vec_dot_f16_f16_aa_2x1(const uint32_t n, float * restric HVX_Vector rsum0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_VsfVsf(Q6_V_lo_W(rsum0_p), Q6_V_hi_W(rsum0_p))); HVX_Vector rsum1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_VsfVsf(Q6_V_lo_W(rsum1_p), Q6_V_hi_W(rsum1_p))); - HVX_Vector rsum = hvx_vec_reduce_sum_f32x2(rsum0, rsum1); - hvx_vec_store_u(s0, 8, rsum); + store_2x1(s0, rsum0, rsum1); } -static inline void flat_vec_dot_f16_f16_aa_2x2(const uint32_t n, float * restrict s0, float * restrict s1, +static inline void flat_vec_dot_f16_f16_aa_2x2(const uint32_t n, void * restrict s0, void * restrict s1, const void * restrict vx0, const void * restrict vx1, - const void * restrict vy0, const void * restrict vy1) { + const void * restrict vy0, const void * restrict vy1, hvx_flat_store_2x1_fn_t store_2x1) { const HVX_Vector * restrict x0 = (const HVX_Vector *) vx0; const HVX_Vector * restrict x1 = (const HVX_Vector *) vx1; const HVX_Vector * restrict y0 = (const HVX_Vector *) vy0; @@ -508,19 +549,110 @@ static inline void flat_vec_dot_f16_f16_aa_2x2(const uint32_t n, float * restric HVX_Vector r1_c0_sum = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_VsfVsf(Q6_V_lo_W(r1_c0_sum_p), Q6_V_hi_W(r1_c0_sum_p))); HVX_Vector r1_c1_sum = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_VsfVsf(Q6_V_lo_W(r1_c1_sum_p), Q6_V_hi_W(r1_c1_sum_p))); - // Reduce and store results - HVX_Vector r0_r1_c0_sum = hvx_vec_reduce_sum_f32x2(r0_c0_sum, r1_c0_sum); - HVX_Vector r0_r1_c1_sum = hvx_vec_reduce_sum_f32x2(r0_c1_sum, r1_c1_sum); + store_2x1(s0, r0_c0_sum, r1_c0_sum); + store_2x1(s1, r0_c1_sum, r1_c1_sum); +} + +typedef void (*hvx_tensor_add_row_fn_t)(void * restrict dst_ptr, const void * restrict bias_ptr, uint32_t n); + +static __attribute__((noinline)) void hvx_tensor_add_row_f32_f32(void * restrict dst_ptr, const void * restrict bias_ptr, uint32_t n) { + float * restrict d = (float *) dst_ptr; + const float * restrict b = (const float *) bias_ptr; + uint32_t c = 0; + for (; c + 32 <= n; c += 32) { + hvx_vmemu(d + c) = hvx_vec_add_f32_f32(hvx_vmemu(d + c), hvx_vmemu(b + c)); + } + if (c < n) { + const uint32_t rem = n - c; + HVX_Vector v_sum = hvx_vec_add_f32_f32(hvx_vmemu(d + c), hvx_vmemu(b + c)); + hvx_vec_store_u(d + c, rem * sizeof(float), v_sum); + } +} + +static __attribute__((noinline)) void hvx_tensor_add_row_f32_f16(void * restrict dst_ptr, const void * restrict bias_ptr, uint32_t n) { + float * restrict d = (float *) dst_ptr; + const __fp16 * restrict b = (const __fp16 *) bias_ptr; + uint32_t c = 0; + for (; c + 64 <= n; c += 64) { + HVX_VectorPair vp_b = hvx_vec_f16_to_f32(hvx_vmemu(b + c)); + hvx_vmemu(d + c + 0) = hvx_vec_add_f32_f32(hvx_vmemu(d + c + 0), Q6_V_lo_W(vp_b)); + hvx_vmemu(d + c + 32) = hvx_vec_add_f32_f32(hvx_vmemu(d + c + 32), Q6_V_hi_W(vp_b)); + } + if (c + 32 <= n) { + HVX_Vector v_b = Q6_V_lo_W(hvx_vec_f16_to_f32(hvx_vmemu(b + c))); + hvx_vmemu(d + c) = hvx_vec_add_f32_f32(hvx_vmemu(d + c), v_b); + c += 32; + } + if (c < n) { + const uint32_t rem = n - c; + HVX_Vector v_b = Q6_V_lo_W(hvx_vec_f16_to_f32(hvx_vmemu(b + c))); + HVX_Vector v_sum = hvx_vec_add_f32_f32(hvx_vmemu(d + c), v_b); + hvx_vec_store_u(d + c, rem * sizeof(float), v_sum); + } +} - hvx_vec_store_u(&s0[0], 8, r0_r1_c0_sum); // row0,col0 row1,col0 - hvx_vec_store_u(&s1[0], 8, r0_r1_c1_sum); // row0,col1 row1,col1 +static __attribute__((noinline)) void hvx_tensor_add_row_f16_f32(void * restrict dst_ptr, const void * restrict bias_ptr, uint32_t n) { + __fp16 * restrict d = (__fp16 *) dst_ptr; + const float * restrict b = (const float *) bias_ptr; + const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); + const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); + uint32_t c = 0; + for (; c + 64 <= n; c += 64) { + HVX_VectorPair vp_d = hvx_vec_f16_to_f32(hvx_vmemu(d + c)); + HVX_Vector v0 = hvx_vec_add_f32_f32(Q6_V_lo_W(vp_d), hvx_vmemu(b + c + 0)); + HVX_Vector v1 = hvx_vec_add_f32_f32(Q6_V_hi_W(vp_d), hvx_vmemu(b + c + 32)); + v0 = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v0)); + v1 = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v1)); + hvx_vmemu(d + c) = hvx_vec_f32_to_f16(v0, v1); + } + if (c < n) { + const uint32_t rem = n - c; + HVX_VectorPair vp_d = hvx_vec_f16_to_f32(hvx_vmemu(d + c)); + HVX_Vector v0 = hvx_vec_add_f32_f32(Q6_V_lo_W(vp_d), hvx_vmemu(b + c)); + HVX_Vector v1 = (rem > 32) ? hvx_vec_add_f32_f32(Q6_V_hi_W(vp_d), hvx_vmemu(b + c + 32)) : Q6_V_vzero(); + v0 = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v0)); + v1 = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v1)); + hvx_vec_store_u(d + c, rem * sizeof(__fp16), hvx_vec_f32_to_f16(v0, v1)); + } } +static __attribute__((noinline)) void hvx_tensor_add_row_f16_f16(void * restrict dst_ptr, const void * restrict bias_ptr, uint32_t n) { + __fp16 * restrict d = (__fp16 *) dst_ptr; + const __fp16 * restrict b = (const __fp16 *) bias_ptr; + const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); + const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); + uint32_t c = 0; + for (; c + 64 <= n; c += 64) { + HVX_VectorPair vp_d = hvx_vec_f16_to_f32(hvx_vmemu(d + c)); + HVX_VectorPair vp_b = hvx_vec_f16_to_f32(hvx_vmemu(b + c)); + HVX_Vector v0 = hvx_vec_add_f32_f32(Q6_V_lo_W(vp_d), Q6_V_lo_W(vp_b)); + HVX_Vector v1 = hvx_vec_add_f32_f32(Q6_V_hi_W(vp_d), Q6_V_hi_W(vp_b)); + v0 = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v0)); + v1 = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v1)); + hvx_vmemu(d + c) = hvx_vec_f32_to_f16(v0, v1); + } + if (c < n) { + const uint32_t rem = n - c; + HVX_VectorPair vp_d = hvx_vec_f16_to_f32(hvx_vmemu(d + c)); + HVX_VectorPair vp_b = hvx_vec_f16_to_f32(hvx_vmemu(b + c)); + HVX_Vector v0 = hvx_vec_add_f32_f32(Q6_V_lo_W(vp_d), Q6_V_lo_W(vp_b)); + HVX_Vector v1 = (rem > 32) ? hvx_vec_add_f32_f32(Q6_V_hi_W(vp_d), Q6_V_hi_W(vp_b)) : Q6_V_vzero(); + v0 = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v0)); + v1 = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v1)); + hvx_vec_store_u(d + c, rem * sizeof(__fp16), hvx_vec_f32_to_f16(v0, v1)); + } +} +static inline hvx_tensor_add_row_fn_t resolve_hvx_tensor_add_row_fn(uint32_t dst_elem_size, uint32_t bias_elem_size) { + if (dst_elem_size == sizeof(__fp16)) { + return (bias_elem_size == sizeof(__fp16)) ? hvx_tensor_add_row_f16_f16 : hvx_tensor_add_row_f16_f32; + } + return (bias_elem_size == sizeof(__fp16)) ? hvx_tensor_add_row_f32_f16 : hvx_tensor_add_row_f32_f32; +} static inline void hvx_tensor_add_f32_grid( const struct htp_tensor * restrict dst, - const struct htp_tensor * restrict src2, + const struct htp_tensor * restrict bias, uint32_t start_row, uint32_t end_row, uint32_t start_col, @@ -529,46 +661,33 @@ static inline void hvx_tensor_add_f32_grid( const struct fastdiv_values * div_ne11 ) { if (start_row >= end_row || start_col >= end_col) return; - const uint32_t nb1 = dst->nb[1]; // row stride in bytes + const uint32_t nb1 = dst->nb[1]; + const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const uint32_t bias_elem_size = (bias->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const hvx_tensor_add_row_fn_t add_row_fn = resolve_hvx_tensor_add_row_fn(dst_elem_size, bias_elem_size); + const uint32_t n_cols = end_col - start_col; + const size_t dst_col_off = (size_t) start_col * dst_elem_size; + const size_t bias_col_off = (size_t) start_col * bias_elem_size; const uint32_t ne11 = dst->ne[1]; const uint32_t ne12 = dst->ne[2]; const uint32_t ne11_12 = ne11 * ne12; - const bool is_broadcast1 = (src2->ne[1] == 1); - const bool is_broadcast2 = (src2->ne[2] == 1); - const bool is_broadcast3 = (src2->ne[3] == 1); + const size_t bias_nb1 = (bias->ne[1] == 1) ? 0 : bias->nb[1]; + const size_t bias_nb2 = (bias->ne[2] == 1) ? 0 : bias->nb[2]; + const size_t bias_nb3 = (bias->ne[3] == 1) ? 0 : bias->nb[3]; for (uint32_t r = start_row; r < end_row; r++) { - float * dst_row = (float *) ((uint8_t *) dst->data + (size_t) r * nb1); - uint32_t i13 = fastdiv(r, div_ne11_12); uint32_t i12 = fastdiv(r - i13 * ne11_12, div_ne11); uint32_t i11 = r - i13 * ne11_12 - i12 * ne11; - uint32_t i23 = is_broadcast3 ? 0 : i13; - uint32_t i22 = is_broadcast2 ? 0 : i12; - uint32_t i21 = is_broadcast1 ? 0 : i11; - - const float * src2_row = (const float *) ((const uint8_t *) src2->data + - (size_t) i21 * src2->nb[1] + (size_t) i22 * src2->nb[2] + (size_t) i23 * src2->nb[3]); - - float * dst_ptr = &dst_row[start_col]; - const float * src2_ptr = &src2_row[start_col]; - int remaining = end_col - start_col; - while (remaining >= 32) { - HVX_Vector v_out = hvx_vmemu(dst_ptr); - HVX_Vector v_z = hvx_vmemu(src2_ptr); - hvx_vmemu(dst_ptr) = hvx_vec_add_f32_f32(v_out, v_z); - dst_ptr += 32; - src2_ptr += 32; - remaining -= 32; - } - if (remaining > 0) { - HVX_Vector v_out = hvx_vmemu(dst_ptr); - HVX_Vector v_z = hvx_vmemu(src2_ptr); - hvx_vec_store_u(dst_ptr, remaining * sizeof(float), hvx_vec_add_f32_f32(v_out, v_z)); - } + uint8_t * dst_ptr = (uint8_t *) dst->data + + (size_t) i11 * nb1 + (size_t) i12 * dst->nb[2] + (size_t) i13 * dst->nb[3] + dst_col_off; + const uint8_t * bias_ptr = (const uint8_t *) bias->data + + (size_t) i11 * bias_nb1 + (size_t) i12 * bias_nb2 + (size_t) i13 * bias_nb3 + bias_col_off; + + add_row_fn(dst_ptr, bias_ptr, n_cols); } } diff --git a/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-tiled.h b/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-tiled.h index e39ca336b417..1b4784665293 100644 --- a/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-tiled.h +++ b/ggml/src/ggml-hexagon/htp/hvx-mm-kernels-tiled.h @@ -64,25 +64,26 @@ static inline void quantize_block_f32_q8_1_tiled_impl(float * restrict x, uint8_ } // word 8b: sum of block b (sums16: k 0..15, and word 8b + 4: k 16..31) - const HVX_Vector v_inv127 = hvx_vec_splat_f32(1.0f / 127.0f); - HVX_Vector vd0_sf = hvx_vec_mul_f32_f32(vmax0_sf, v_inv127); - HVX_Vector vd1_sf = hvx_vec_mul_f32_f32(vmax1_sf, v_inv127); - HVX_Vector vd2_sf = hvx_vec_mul_f32_f32(vmax2_sf, v_inv127); - HVX_Vector vd3_sf = hvx_vec_mul_f32_f32(vmax3_sf, v_inv127); - - HVX_Vector v_sums_sf = Q6_Vsf_equals_Vw(v_sums); - HVX_Vector voff0_sf = hvx_vec_mul_f32_f32(vd0_sf, v_sums_sf); - HVX_Vector voff1_sf = hvx_vec_mul_f32_f32(vd1_sf, Q6_V_vror_VR(v_sums_sf, 32)); - HVX_Vector voff2_sf = hvx_vec_mul_f32_f32(vd2_sf, Q6_V_vror_VR(v_sums_sf, 64)); - HVX_Vector voff3_sf = hvx_vec_mul_f32_f32(vd3_sf, Q6_V_vror_VR(v_sums_sf, 96)); - - HVX_Vector voff01_hf = hvx_vec_f32_to_f16(voff0_sf, voff1_sf); - HVX_Vector voff23_hf = hvx_vec_f32_to_f16(voff2_sf, voff3_sf); - - int32_t __attribute__((aligned(128))) ws[32]; + HVX_Vector voff01_hf = Q6_V_vzero(); + HVX_Vector voff23_hf = Q6_V_vzero(); + HVX_Vector v_s16 = Q6_V_vzero(); if (sums16) { - // |sum of 16 int8| <= 2032 fits a halfword - *(HVX_Vector *) ws = v_sums; + v_s16 = Q6_Vh_vshuffe_VhVh(Q6_V_vror_VR(v_sums, 16), v_sums); + } else { + const HVX_Vector v_inv127 = hvx_vec_splat_f32(1.0f / 127.0f); + HVX_Vector vd0_sf = hvx_vec_mul_f32_f32(vmax0_sf, v_inv127); + HVX_Vector vd1_sf = hvx_vec_mul_f32_f32(vmax1_sf, v_inv127); + HVX_Vector vd2_sf = hvx_vec_mul_f32_f32(vmax2_sf, v_inv127); + HVX_Vector vd3_sf = hvx_vec_mul_f32_f32(vmax3_sf, v_inv127); + + HVX_Vector v_sums_sf = Q6_Vsf_equals_Vw(v_sums); + HVX_Vector voff0_sf = hvx_vec_mul_f32_f32(vd0_sf, v_sums_sf); + HVX_Vector voff1_sf = hvx_vec_mul_f32_f32(vd1_sf, Q6_V_vror_VR(v_sums_sf, 32)); + HVX_Vector voff2_sf = hvx_vec_mul_f32_f32(vd2_sf, Q6_V_vror_VR(v_sums_sf, 64)); + HVX_Vector voff3_sf = hvx_vec_mul_f32_f32(vd3_sf, Q6_V_vror_VR(v_sums_sf, 96)); + + voff01_hf = hvx_vec_f32_to_f16(voff0_sf, voff1_sf); + voff23_hf = hvx_vec_f32_to_f16(voff2_sf, voff3_sf); } static const uint8_t __attribute__((aligned(128))) repl[128] = { @@ -104,7 +105,7 @@ static inline void quantize_block_f32_q8_1_tiled_impl(float * restrict x, uint8_ HVX_Vector voff_b = (b < 2) ? voff01_hf : voff23_hf; HVX_Vector r_scale = hvx_vec_repl_f16((b & 1) ? Q6_V_vror_VR(vd_b, 64) : vd_b); HVX_Vector r_offset = sums16 - ? Q6_V_vsplat_R(((uint32_t) ws[8 * b + 4] << 16) | ((uint32_t) ws[8 * b] & 0xFFFF)) + ? Q6_V_vdelta_VV(Q6_V_vror_VR(v_s16, b * 32), v_repl_ctrl) : hvx_vec_repl_f16((b & 1) ? Q6_V_vror_VR(voff_b, 64) : voff_b); HVX_Vector r0 = Q6_V_vdelta_VV(v_act, v_repl_ctrl); @@ -264,6 +265,254 @@ static void quantize_row_f32_q8_1_s16_tiled(float * restrict x, uint8_t * restri } } +static inline HVX_Vector hvx_vec_reduce_abs_max_half_f16(HVX_Vector v) { + HVX_Vector m = hvx_vec_abs_f16(v); + m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 2)); + m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 4)); + m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 8)); + m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 16)); + m = Q6_Vhf_vmax_VhfVhf(m, Q6_V_vror_VR(m, 32)); + HVX_Vector m_lo = hvx_vec_repl_f16(m); + HVX_Vector m_hi = hvx_vec_repl_f16(Q6_V_vror_VR(m, 64)); + return Q6_V_vmux_QVV(Q6_Q_vsetq_R(64), m_lo, m_hi); +} + +__attribute__((always_inline)) +static inline void quantize_block_f16_q8_1_tiled_impl(const __fp16 * restrict x, uint8_t * restrict y_block, const bool sums16, + const __fp16 * restrict x_sb) { + assert((unsigned long) x % 128 == 0); + assert((unsigned long) y_block % 128 == 0); + + const HVX_Vector * vx = (const HVX_Vector *) x; + + HVX_Vector vx01_hf = vx[0]; + HVX_Vector vx23_hf = vx[1]; + HVX_Vector vmax01_hf, vmax23_hf; + HVX_Vector vmax0_sf = Q6_V_vzero(), vmax1_sf = Q6_V_vzero(), vmax2_sf = Q6_V_vzero(), vmax3_sf = Q6_V_vzero(); + if (sums16) { + const HVX_Vector * vsb = (const HVX_Vector *) x_sb; + HVX_Vector vm = hvx_vec_abs_f16(vsb[0]); + for (int i = 1; i < 4; i++) { + vm = Q6_Vhf_vmax_VhfVhf(vm, hvx_vec_abs_f16(vsb[i])); + } + vmax01_hf = vmax23_hf = hvx_vec_reduce_max_f16(vm); + } else { + vmax01_hf = hvx_vec_reduce_abs_max_half_f16(vx01_hf); + vmax23_hf = hvx_vec_reduce_abs_max_half_f16(vx23_hf); + HVX_VectorPair p01 = hvx_vec_f16_to_f32(vmax01_hf); + HVX_VectorPair p23 = hvx_vec_f16_to_f32(vmax23_hf); + vmax0_sf = Q6_V_lo_W(p01); + vmax1_sf = Q6_V_hi_W(p01); + vmax2_sf = Q6_V_lo_W(p23); + vmax3_sf = Q6_V_hi_W(p23); + } + + HVX_Vector vd01_qf16 = Q6_Vqf16_vmpy_VhfVhf(vmax01_hf, Q6_Vh_vsplat_R(0x2008)); // 1.0 / 127.0 + HVX_Vector vd01_hf = Q6_Vhf_equals_Vqf16(vd01_qf16); + HVX_Vector vd01_inv_hf = hvx_vec_inverse_f16(vd01_hf); + vx01_hf = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(vx01_hf, vd01_inv_hf)); + + HVX_Vector vd23_qf16 = Q6_Vqf16_vmpy_VhfVhf(vmax23_hf, Q6_Vh_vsplat_R(0x2008)); // 1.0 / 127.0 + HVX_Vector vd23_hf = Q6_Vhf_equals_Vqf16(vd23_qf16); + HVX_Vector vd23_inv_hf = hvx_vec_inverse_f16(vd23_hf); + vx23_hf = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(vx23_hf, vd23_inv_hf)); + + HVX_Vector vx01_i16 = hvx_vec_i16_from_hf_rnd_sat(vx01_hf); + HVX_Vector vx23_i16 = hvx_vec_i16_from_hf_rnd_sat(vx23_hf); + HVX_Vector vx_i8 = Q6_Vb_vpack_VhVh_sat(vx23_i16, vx01_i16); + + const HVX_Vector ones = Q6_Vb_vsplat_R(1); + HVX_Vector v_sums = Q6_Vw_vrmpy_VbVb(vx_i8, ones); + v_sums = Q6_Vw_vadd_VwVw(v_sums, Q6_V_vror_VR(v_sums, 4)); + v_sums = Q6_Vw_vadd_VwVw(v_sums, Q6_V_vror_VR(v_sums, 8)); + if (!sums16) { + v_sums = Q6_Vw_vadd_VwVw(v_sums, Q6_V_vror_VR(v_sums, 16)); + } + + HVX_Vector voff01_hf = Q6_V_vzero(); + HVX_Vector voff23_hf = Q6_V_vzero(); + HVX_Vector v_s16 = Q6_V_vzero(); + if (sums16) { + v_s16 = Q6_Vh_vshuffe_VhVh(Q6_V_vror_VR(v_sums, 16), v_sums); + } else { + const HVX_Vector v_inv127 = hvx_vec_splat_f32(1.0f / 127.0f); + HVX_Vector vd0_sf = hvx_vec_mul_f32_f32(vmax0_sf, v_inv127); + HVX_Vector vd1_sf = hvx_vec_mul_f32_f32(vmax1_sf, v_inv127); + HVX_Vector vd2_sf = hvx_vec_mul_f32_f32(vmax2_sf, v_inv127); + HVX_Vector vd3_sf = hvx_vec_mul_f32_f32(vmax3_sf, v_inv127); + + HVX_Vector v_sums_sf = Q6_Vsf_equals_Vw(v_sums); + HVX_Vector voff0_sf = hvx_vec_mul_f32_f32(vd0_sf, v_sums_sf); + HVX_Vector voff1_sf = hvx_vec_mul_f32_f32(vd1_sf, Q6_V_vror_VR(v_sums_sf, 32)); + HVX_Vector voff2_sf = hvx_vec_mul_f32_f32(vd2_sf, Q6_V_vror_VR(v_sums_sf, 64)); + HVX_Vector voff3_sf = hvx_vec_mul_f32_f32(vd3_sf, Q6_V_vror_VR(v_sums_sf, 96)); + + voff01_hf = hvx_vec_f32_to_f16(voff0_sf, voff1_sf); + voff23_hf = hvx_vec_f32_to_f16(voff2_sf, voff3_sf); + } + + static const uint8_t __attribute__((aligned(128))) repl[128] = { + 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04, + 0x10, 0x10, 0x10, 0x10, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04, + 0x20, 0x20, 0x20, 0x20, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04, + 0x10, 0x10, 0x10, 0x10, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04, + 0x40, 0x40, 0x40, 0x40, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04, + 0x10, 0x10, 0x10, 0x10, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04, + 0x20, 0x20, 0x20, 0x20, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04, + 0x10, 0x10, 0x10, 0x10, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04, + }; + HVX_Vector v_repl_ctrl = * (const HVX_Vector *) repl; + + #pragma unroll + for (int b = 0; b < 4; b++) { + HVX_Vector v_act = Q6_V_vror_VR(vx_i8, b * 32); + HVX_Vector vd_b = (b < 2) ? vd01_hf : vd23_hf; + HVX_Vector voff_b = (b < 2) ? voff01_hf : voff23_hf; + HVX_Vector r_scale = hvx_vec_repl_f16((b & 1) ? Q6_V_vror_VR(vd_b, 64) : vd_b); + HVX_Vector r_offset = sums16 + ? Q6_V_vdelta_VV(Q6_V_vror_VR(v_s16, b * 32), v_repl_ctrl) + : hvx_vec_repl_f16((b & 1) ? Q6_V_vror_VR(voff_b, 64) : voff_b); + + HVX_Vector r0 = Q6_V_vdelta_VV(v_act, v_repl_ctrl); + HVX_Vector r1 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 4), v_repl_ctrl); + HVX_Vector r2 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 8), v_repl_ctrl); + HVX_Vector r3 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 12), v_repl_ctrl); + HVX_Vector r4 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 16), v_repl_ctrl); + HVX_Vector r5 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 20), v_repl_ctrl); + HVX_Vector r6 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 24), v_repl_ctrl); + HVX_Vector r7 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 28), v_repl_ctrl); + + HVX_Vector * restrict dst = (HVX_Vector *) (y_block + b * 1280); + dst[0] = r0; + dst[1] = r1; + dst[2] = r2; + dst[3] = r3; + dst[4] = r4; + dst[5] = r5; + dst[6] = r6; + dst[7] = r7; + dst[8] = r_scale; + dst[9] = r_offset; + } +} + +static inline void quantize_block_f16_q8_1_tiled(const __fp16 * restrict x, uint8_t * restrict y_block) { + quantize_block_f16_q8_1_tiled_impl(x, y_block, false, NULL); +} + +static inline void quantize_block_f16_q8_1_s16_tiled(const __fp16 * restrict x, uint8_t * restrict y_block, const __fp16 * restrict x_sb) { + quantize_block_f16_q8_1_tiled_impl(x, y_block, true, x_sb); +} + +static inline void quantize_block_f16_q8_0_tiled(const __fp16 * restrict x, uint8_t * restrict y_block) { + assert((unsigned long) x % 128 == 0); + assert((unsigned long) y_block % 128 == 0); + + const HVX_Vector * vx = (const HVX_Vector *) x; + + HVX_Vector vx01_hf = vx[0]; + HVX_Vector vx23_hf = vx[1]; + HVX_Vector vmax01_hf = hvx_vec_reduce_abs_max_half_f16(vx01_hf); + HVX_Vector vmax23_hf = hvx_vec_reduce_abs_max_half_f16(vx23_hf); + + HVX_Vector vd01_qf16 = Q6_Vqf16_vmpy_VhfVhf(vmax01_hf, Q6_Vh_vsplat_R(0x2008)); + HVX_Vector vd23_qf16 = Q6_Vqf16_vmpy_VhfVhf(vmax23_hf, Q6_Vh_vsplat_R(0x2008)); + HVX_Vector vd01_hf = Q6_Vhf_equals_Vqf16(vd01_qf16); + HVX_Vector vd23_hf = Q6_Vhf_equals_Vqf16(vd23_qf16); + + HVX_Vector vd01_inv_hf = hvx_vec_inverse_f16(vd01_hf); + HVX_Vector vd23_inv_hf = hvx_vec_inverse_f16(vd23_hf); + vx01_hf = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(vx01_hf, vd01_inv_hf)); + vx23_hf = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(vx23_hf, vd23_inv_hf)); + + HVX_Vector vx01_i16 = hvx_vec_i16_from_hf_rnd_sat(vx01_hf); + HVX_Vector vx23_i16 = hvx_vec_i16_from_hf_rnd_sat(vx23_hf); + HVX_Vector vx_i8 = Q6_Vb_vpack_VhVh_sat(vx23_i16, vx01_i16); + + HVX_VectorPair vp01 = Q6_W_vshuff_VVR(vd01_hf, vd01_hf, -64); + HVX_VectorPair vp23 = Q6_W_vshuff_VVR(vd23_hf, vd23_hf, -64); + + static const uint8_t __attribute__((aligned(128))) repl[128] = { + 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04, + 0x10, 0x10, 0x10, 0x10, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04, + 0x20, 0x20, 0x20, 0x20, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04, + 0x10, 0x10, 0x10, 0x10, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04, + 0x40, 0x40, 0x40, 0x40, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04, + 0x10, 0x10, 0x10, 0x10, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04, + 0x20, 0x20, 0x20, 0x20, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04, + 0x10, 0x10, 0x10, 0x10, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04, + }; + HVX_Vector v_repl_ctrl = * (const HVX_Vector *) repl; + + #pragma unroll + for (int b = 0; b < 4; b++) { + HVX_Vector v_act = Q6_V_vror_VR(vx_i8, b * 32); + HVX_Vector r_scale; + if (b == 0) { + r_scale = Q6_V_lo_W(vp01); + } else if (b == 1) { + r_scale = Q6_V_hi_W(vp01); + } else if (b == 2) { + r_scale = Q6_V_lo_W(vp23); + } else { + r_scale = Q6_V_hi_W(vp23); + } + + HVX_Vector r0 = Q6_V_vdelta_VV(v_act, v_repl_ctrl); + HVX_Vector r1 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 4), v_repl_ctrl); + HVX_Vector r2 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 8), v_repl_ctrl); + HVX_Vector r3 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 12), v_repl_ctrl); + HVX_Vector r4 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 16), v_repl_ctrl); + HVX_Vector r5 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 20), v_repl_ctrl); + HVX_Vector r6 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 24), v_repl_ctrl); + HVX_Vector r7 = Q6_V_vdelta_VV(Q6_V_vror_VR(v_act, 28), v_repl_ctrl); + + HVX_Vector * restrict dst = (HVX_Vector *) (y_block + b * 1152); + dst[0] = r0; + dst[1] = r1; + dst[2] = r2; + dst[3] = r3; + dst[4] = r4; + dst[5] = r5; + dst[6] = r6; + dst[7] = r7; + dst[8] = r_scale; + } +} + +static void quantize_row_f16_q8_0_tiled(const __fp16 * restrict x, uint8_t * restrict y, uint32_t k) { + assert(k % 32 == 0); + const uint32_t qk = HTP_MM_ACT_BLOCK_K; + const uint32_t nb = (k + qk - 1) / qk; + + for (uint32_t i = 0; i < nb; i++) { + uint8_t * restrict y_block = y + i * 4 * 1152; + quantize_block_f16_q8_0_tiled(x + i * qk, y_block); + } +} + +static void quantize_row_f16_q8_1_tiled(const __fp16 * restrict x, uint8_t * restrict y, uint32_t k) { + assert(k % 32 == 0); + const uint32_t qk = HTP_MM_ACT_BLOCK_K; + const uint32_t nb = (k + qk - 1) / qk; + + for (uint32_t i = 0; i < nb; i++) { + uint8_t * restrict y_block = y + i * 4 * 1280; + quantize_block_f16_q8_1_tiled(x + i * qk, y_block); + } +} + +static void quantize_row_f16_q8_1_s16_tiled(const __fp16 * restrict x, uint8_t * restrict y, uint32_t k) { + assert(k % 32 == 0); + const uint32_t qk = HTP_MM_ACT_BLOCK_K; + const uint32_t nb = (k + qk - 1) / qk; + + for (uint32_t i = 0; i < nb; i++) { + uint8_t * restrict y_block = y + i * 4 * 1280; + quantize_block_f16_q8_1_s16_tiled(x + i * qk, y_block, x + (i & ~1u) * qk); // k % 256 == 0 for Q2_K + } +} + static inline void quantize_half_f16_tiled_splat(HVX_Vector v_src, HVX_Vector * restrict dst) { static const uint8_t __attribute__((aligned(128))) repl[128] = { 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x04, 0x04, 0x04, 0x04, @@ -357,34 +606,6 @@ static inline HVX_VectorPair hvx_vec_mul_f16_f16_to_f32_pair(HVX_Vector v1, HVX_ #endif } -static inline HVX_Vector unpack_and_interleave_4bit(HVX_Vector v_a, HVX_Vector v_b, HVX_Vector mask_h4) { - HVX_Vector v_W0 = Q6_V_vand_VV(v_a, mask_h4); - HVX_Vector v_W1 = Q6_Vub_vlsr_VubR(v_a, 4); - HVX_Vector v_W2 = Q6_V_vand_VV(v_b, mask_h4); - HVX_Vector v_W3 = Q6_Vub_vlsr_VubR(v_b, 4); - - HVX_VectorPair v01_pair = Q6_W_vshuff_VVR(v_W1, v_W0, -1); - HVX_VectorPair v23_pair = Q6_W_vshuff_VVR(v_W3, v_W2, -1); - HVX_VectorPair v0123_pair = Q6_W_vshuff_VVR(Q6_V_lo_W(v23_pair), Q6_V_lo_W(v01_pair), -2); - return Q6_V_lo_W(v0123_pair); -} - -static inline HVX_VectorPair unpack_and_interleave_4bit_x2(HVX_Vector v_src, HVX_Vector mask_h4) { - HVX_Vector v_lo = Q6_V_vand_VV(v_src, mask_h4); - HVX_Vector v_hi = Q6_Vub_vlsr_VubR(v_src, 4); - HVX_VectorPair v01_pair = Q6_W_vshuff_VVR(v_hi, v_lo, -1); - HVX_Vector v01_lo = Q6_V_lo_W(v01_pair); - HVX_Vector v01_hi = Q6_V_hi_W(v01_pair); - - HVX_Vector v23_lo = Q6_V_valign_VVR(v01_hi, v01_lo, 64); - HVX_Vector v_W0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v23_lo, v01_lo, -2)); - - HVX_Vector v67_lo = Q6_V_valign_VVR(v01_lo, v01_hi, 64); - HVX_Vector v_W1 = Q6_V_lo_W(Q6_W_vshuff_VVR(v67_lo, v01_hi, -2)); - - return Q6_W_vcombine_VV(v_W1, v_W0); -} - static inline HVX_Vector unpack_q1_0_group( HVX_Vector v_plane, int g, @@ -426,9 +647,9 @@ static inline HVX_Vector accum_4bit_32x1( #pragma unroll for (int i = 0; i < 4; i++) { - HVX_VectorPair v_W_pair = unpack_and_interleave_4bit_x2(vptr[i], mask_h4); - HVX_Vector v_W0 = Q6_Vb_vsub_VbVb(Q6_V_lo_W(v_W_pair), i8); - HVX_Vector v_W1 = Q6_Vb_vsub_VbVb(Q6_V_hi_W(v_W_pair), i8); + HVX_Vector v_src = vptr[i]; + HVX_Vector v_W0 = Q6_Vb_vsub_VbVb(Q6_V_vand_VV(v_src, mask_h4), i8); + HVX_Vector v_W1 = Q6_Vb_vsub_VbVb(Q6_Vub_vlsr_VubR(v_src, 4), i8); v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act[i * 2 + 0]); v_sum1 = Q6_Vw_vrmpyacc_VwVbVb(v_sum1, v_W1, v_act[i * 2 + 1]); } @@ -447,9 +668,9 @@ static inline HVX_Vector accum_4bit_32x1_lut( #pragma unroll for (int i = 0; i < 4; i++) { - HVX_VectorPair v_W_pair = unpack_and_interleave_4bit_x2(vptr[i], mask_h4); - HVX_Vector v_W0 = Q6_Vb_vlut32_VbVbI(Q6_V_lo_W(v_W_pair), lut, 0); - HVX_Vector v_W1 = Q6_Vb_vlut32_VbVbI(Q6_V_hi_W(v_W_pair), lut, 0); + HVX_Vector v_src = vptr[i]; + HVX_Vector v_W0 = Q6_Vb_vlut32_VbVbI(Q6_V_vand_VV(v_src, mask_h4), lut, 0); + HVX_Vector v_W1 = Q6_Vb_vlut32_VbVbI(Q6_Vub_vlsr_VubR(v_src, 4), lut, 0); v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act[i * 2 + 0]); v_sum1 = Q6_Vw_vrmpyacc_VwVbVb(v_sum1, v_W1, v_act[i * 2 + 1]); } @@ -496,9 +717,9 @@ static inline HVX_VectorPair accum_4bit_32x2( #pragma unroll for (int i = 0; i < 4; i++) { - HVX_VectorPair v_W_pair = unpack_and_interleave_4bit_x2(vptr[i], mask_h4); - HVX_Vector v_W0 = Q6_Vb_vsub_VbVb(Q6_V_lo_W(v_W_pair), i8); - HVX_Vector v_W1 = Q6_Vb_vsub_VbVb(Q6_V_hi_W(v_W_pair), i8); + HVX_Vector v_src = vptr[i]; + HVX_Vector v_W0 = Q6_Vb_vsub_VbVb(Q6_V_vand_VV(v_src, mask_h4), i8); + HVX_Vector v_W1 = Q6_Vb_vsub_VbVb(Q6_Vub_vlsr_VubR(v_src, 4), i8); v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act0[i * 2 + 0]); v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W1, v_act0[i * 2 + 1]); @@ -522,9 +743,9 @@ static inline HVX_VectorPair accum_4bit_32x2_lut( #pragma unroll for (int i = 0; i < 4; i++) { - HVX_VectorPair v_W_pair = unpack_and_interleave_4bit_x2(vptr[i], mask_h4); - HVX_Vector v_W0 = Q6_Vb_vlut32_VbVbI(Q6_V_lo_W(v_W_pair), lut, 0); - HVX_Vector v_W1 = Q6_Vb_vlut32_VbVbI(Q6_V_hi_W(v_W_pair), lut, 0); + HVX_Vector v_src = vptr[i]; + HVX_Vector v_W0 = Q6_Vb_vlut32_VbVbI(Q6_V_vand_VV(v_src, mask_h4), lut, 0); + HVX_Vector v_W1 = Q6_Vb_vlut32_VbVbI(Q6_Vub_vlsr_VubR(v_src, 4), lut, 0); v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act0[i * 2 + 0]); v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W1, v_act0[i * 2 + 1]); @@ -543,9 +764,7 @@ static inline HVX_Vector accum_q8_0_32x1( HVX_Vector v_sum = Q6_V_vzero(); #pragma unroll for (int g = 0; g < 8; g++) { - HVX_Vector v_rot = Q6_V_vror_VR(vptr[g], 64); - HVX_Vector v_W = Q6_V_lo_W(Q6_W_vshuff_VVR(v_rot, vptr[g], -2)); - v_sum = Q6_Vw_vrmpyacc_VwVbVb(v_sum, v_W, v_act[g]); + v_sum = Q6_Vw_vrmpyacc_VwVbVb(v_sum, vptr[g], v_act[g]); } return v_sum; } @@ -559,8 +778,7 @@ static inline HVX_VectorPair accum_q8_0_32x2( HVX_Vector v_sum1 = Q6_V_vzero(); #pragma unroll for (int g = 0; g < 8; g++) { - HVX_Vector v_rot = Q6_V_vror_VR(vptr[g], 64); - HVX_Vector v_W = Q6_V_lo_W(Q6_W_vshuff_VVR(v_rot, vptr[g], -2)); + HVX_Vector v_W = vptr[g]; v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W, v_act0[g]); v_sum1 = Q6_Vw_vrmpyacc_VwVbVb(v_sum1, v_W, v_act1[g]); } @@ -573,27 +791,9 @@ static inline HVX_Vector hvx_q5k_or_hibit(HVX_Vector v, HVX_Vector v_plane, int return Q6_V_vandor_VQR(v, q, 0x10101010); } -// 5-bit variant: the high bit comes from the plane, see hvx_q5k_or_hibit -static inline HVX_VectorPair unpack_and_interleave_5bit_x2(HVX_Vector v_src, HVX_Vector v_plane, int i, HVX_Vector mask_h4) { - HVX_Vector v_lo = hvx_q5k_or_hibit(Q6_V_vand_VV(v_src, mask_h4), v_plane, 2 * i); - HVX_Vector v_hi = hvx_q5k_or_hibit(Q6_Vub_vlsr_VubR(v_src, 4), v_plane, 2 * i + 1); - HVX_VectorPair v01_pair = Q6_W_vshuff_VVR(v_hi, v_lo, -1); - HVX_Vector v01_lo = Q6_V_lo_W(v01_pair); - HVX_Vector v01_hi = Q6_V_hi_W(v01_pair); - - HVX_Vector v23_lo = Q6_V_valign_VVR(v01_hi, v01_lo, 64); - HVX_Vector v_W0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v23_lo, v01_lo, -2)); - - HVX_Vector v67_lo = Q6_V_valign_VVR(v01_lo, v01_hi, 64); - HVX_Vector v_W1 = Q6_V_lo_W(Q6_W_vshuff_VVR(v67_lo, v01_hi, -2)); - - return Q6_W_vcombine_VV(v_W1, v_W0); -} - static inline HVX_Vector accum_5bit_32x1( const HVX_Vector * restrict vptr, - const HVX_Vector * restrict v_act, - HVX_Vector i8 + const HVX_Vector * restrict v_act ) { HVX_Vector v_sum0 = Q6_V_vzero(); HVX_Vector v_sum1 = Q6_V_vzero(); @@ -602,9 +802,9 @@ static inline HVX_Vector accum_5bit_32x1( #pragma unroll for (int i = 0; i < 4; i++) { - HVX_VectorPair v_W_pair = unpack_and_interleave_5bit_x2(vptr[i], v_plane, i, mask_h4); - HVX_Vector v_W0 = Q6_Vb_vsub_VbVb(Q6_V_lo_W(v_W_pair), i8); - HVX_Vector v_W1 = Q6_Vb_vsub_VbVb(Q6_V_hi_W(v_W_pair), i8); + HVX_Vector v_src = vptr[i]; + HVX_Vector v_W0 = hvx_q5k_or_hibit(Q6_V_vand_VV(v_src, mask_h4), v_plane, 2 * i + 0); + HVX_Vector v_W1 = hvx_q5k_or_hibit(Q6_Vub_vlsr_VubR(v_src, 4), v_plane, 2 * i + 1); v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act[i * 2 + 0]); v_sum1 = Q6_Vw_vrmpyacc_VwVbVb(v_sum1, v_W1, v_act[i * 2 + 1]); } @@ -615,8 +815,7 @@ static inline HVX_Vector accum_5bit_32x1( static inline HVX_VectorPair accum_5bit_32x2( const HVX_Vector * restrict vptr, const HVX_Vector * restrict v_act0, - const HVX_Vector * restrict v_act1, - HVX_Vector i8 + const HVX_Vector * restrict v_act1 ) { HVX_Vector v_sum0 = Q6_V_vzero(); HVX_Vector v_sum1 = Q6_V_vzero(); @@ -625,9 +824,9 @@ static inline HVX_VectorPair accum_5bit_32x2( #pragma unroll for (int i = 0; i < 4; i++) { - HVX_VectorPair v_W_pair = unpack_and_interleave_5bit_x2(vptr[i], v_plane, i, mask_h4); - HVX_Vector v_W0 = Q6_Vb_vsub_VbVb(Q6_V_lo_W(v_W_pair), i8); - HVX_Vector v_W1 = Q6_Vb_vsub_VbVb(Q6_V_hi_W(v_W_pair), i8); + HVX_Vector v_src = vptr[i]; + HVX_Vector v_W0 = hvx_q5k_or_hibit(Q6_V_vand_VV(v_src, mask_h4), v_plane, 2 * i + 0); + HVX_Vector v_W1 = hvx_q5k_or_hibit(Q6_Vub_vlsr_VubR(v_src, 4), v_plane, 2 * i + 1); v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act0[i * 2 + 0]); v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W1, v_act0[i * 2 + 1]); @@ -645,23 +844,6 @@ static inline HVX_Vector hvx_q5_0_or_neg(HVX_Vector v, HVX_Vector v_plane, int j return Q6_V_vandor_VQR(v, q, 0xF0F0F0F0); } -// Q5_0: signed bytes (q - 16) straight from the nibbles and the plane -static inline HVX_VectorPair unpack_and_interleave_q5_0_x2(HVX_Vector v_src, HVX_Vector v_plane, int i, HVX_Vector mask_h4) { - HVX_Vector v_lo = hvx_q5_0_or_neg(Q6_V_vand_VV(v_src, mask_h4), v_plane, 2 * i); - HVX_Vector v_hi = hvx_q5_0_or_neg(Q6_Vub_vlsr_VubR(v_src, 4), v_plane, 2 * i + 1); - HVX_VectorPair v01_pair = Q6_W_vshuff_VVR(v_hi, v_lo, -1); - HVX_Vector v01_lo = Q6_V_lo_W(v01_pair); - HVX_Vector v01_hi = Q6_V_hi_W(v01_pair); - - HVX_Vector v23_lo = Q6_V_valign_VVR(v01_hi, v01_lo, 64); - HVX_Vector v_W0 = Q6_V_lo_W(Q6_W_vshuff_VVR(v23_lo, v01_lo, -2)); - - HVX_Vector v67_lo = Q6_V_valign_VVR(v01_lo, v01_hi, 64); - HVX_Vector v_W1 = Q6_V_lo_W(Q6_W_vshuff_VVR(v67_lo, v01_hi, -2)); - - return Q6_W_vcombine_VV(v_W1, v_W0); -} - static inline HVX_Vector accum_q5_0_32x1( const HVX_Vector * restrict vptr, const HVX_Vector * restrict v_act @@ -673,9 +855,11 @@ static inline HVX_Vector accum_q5_0_32x1( #pragma unroll for (int i = 0; i < 4; i++) { - HVX_VectorPair v_W_pair = unpack_and_interleave_q5_0_x2(vptr[i], v_plane, i, mask_h4); - v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, Q6_V_lo_W(v_W_pair), v_act[i * 2 + 0]); - v_sum1 = Q6_Vw_vrmpyacc_VwVbVb(v_sum1, Q6_V_hi_W(v_W_pair), v_act[i * 2 + 1]); + HVX_Vector v_src = vptr[i]; + HVX_Vector v_W0 = hvx_q5_0_or_neg(Q6_V_vand_VV(v_src, mask_h4), v_plane, 2 * i + 0); + HVX_Vector v_W1 = hvx_q5_0_or_neg(Q6_Vub_vlsr_VubR(v_src, 4), v_plane, 2 * i + 1); + v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act[i * 2 + 0]); + v_sum1 = Q6_Vw_vrmpyacc_VwVbVb(v_sum1, v_W1, v_act[i * 2 + 1]); } return Q6_Vw_vadd_VwVw(v_sum0, v_sum1); @@ -693,9 +877,9 @@ static inline HVX_VectorPair accum_q5_0_32x2( #pragma unroll for (int i = 0; i < 4; i++) { - HVX_VectorPair v_W_pair = unpack_and_interleave_q5_0_x2(vptr[i], v_plane, i, mask_h4); - HVX_Vector v_W0 = Q6_V_lo_W(v_W_pair); - HVX_Vector v_W1 = Q6_V_hi_W(v_W_pair); + HVX_Vector v_src = vptr[i]; + HVX_Vector v_W0 = hvx_q5_0_or_neg(Q6_V_vand_VV(v_src, mask_h4), v_plane, 2 * i + 0); + HVX_Vector v_W1 = hvx_q5_0_or_neg(Q6_Vub_vlsr_VubR(v_src, 4), v_plane, 2 * i + 1); v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act0[i * 2 + 0]); v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W1, v_act0[i * 2 + 1]); @@ -986,7 +1170,63 @@ static inline HVX_Vector q2_k_int_scale(HVX_Vector v_isum, HVX_Vector v_msum, HV return hvx_vec_mul_f32_f32(v_t, v_da32); } -static void tiled_vec_dot_q1_0_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) { +typedef void (*hvx_tiled_store_row_fn_t)(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz); + +static __attribute__((noinline)) void hvx_tiled_store_row_f32_none(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz) { + (void) sz; + hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum); +} + +static __attribute__((noinline)) void hvx_tiled_store_row_f32_f32(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz) { + v_sum = hvx_vec_add_f32_f32(v_sum, hvx_vmemu(sz)); + hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum); +} + +static __attribute__((noinline)) void hvx_tiled_store_row_f32_f16(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz) { + HVX_Vector v_sz = Q6_V_lo_W(hvx_vec_f16_to_f32(hvx_vmemu(sz))); + v_sum = hvx_vec_add_f32_f32(v_sum, v_sz); + hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum); +} + +static __attribute__((noinline)) void hvx_tiled_store_row_f16_none(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz) { + (void) sz; + const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); + const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); + v_sum = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v_sum)); + hvx_vec_store_u(s, valid_rows * sizeof(__fp16), hvx_vec_f32_to_f16(v_sum, Q6_V_vzero())); +} + +static __attribute__((noinline)) void hvx_tiled_store_row_f16_f32(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz) { + v_sum = hvx_vec_add_f32_f32(v_sum, hvx_vmemu(sz)); + const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); + const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); + v_sum = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v_sum)); + hvx_vec_store_u(s, valid_rows * sizeof(__fp16), hvx_vec_f32_to_f16(v_sum, Q6_V_vzero())); +} + +static __attribute__((noinline)) void hvx_tiled_store_row_f16_f16(void * restrict s, uint32_t valid_rows, HVX_Vector v_sum, const void * restrict sz) { + HVX_Vector v_sz = Q6_V_lo_W(hvx_vec_f16_to_f32(hvx_vmemu(sz))); + v_sum = hvx_vec_add_f32_f32(v_sum, v_sz); + const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); + const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); + v_sum = Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v_sum)); + hvx_vec_store_u(s, valid_rows * sizeof(__fp16), hvx_vec_f32_to_f16(v_sum, Q6_V_vzero())); +} + +static inline hvx_tiled_store_row_fn_t resolve_hvx_tiled_store_row_fn(uint32_t dst_elem_size, bool has_bias, uint32_t bias_elem_size) { + const bool dst_f16 = (dst_elem_size == sizeof(__fp16)); + const bool bias_f16 = (bias_elem_size == sizeof(__fp16)); + if (dst_f16) { + return !has_bias ? hvx_tiled_store_row_f16_none + : (bias_f16 ? hvx_tiled_store_row_f16_f16 + : hvx_tiled_store_row_f16_f32); + } + return !has_bias ? hvx_tiled_store_row_f32_none + : (bias_f16 ? hvx_tiled_store_row_f32_f16 + : hvx_tiled_store_row_f32_f32); +} + +static void tiled_vec_dot_q1_0_32x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const void * restrict sz, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y_q = vy; @@ -1013,14 +1253,10 @@ static void tiled_vec_dot_q1_0_32x1(const uint32_t n, float * restrict s, const } HVX_Vector v_sum_float = Q6_Vsf_equals_Vqf32(v_sum_qf); - if (sz) { - hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz))); - } else { - hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float); - } + store_row(s, valid_rows, v_sum_float, sz); } -static void tiled_vec_dot_q1_0_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) { +static void tiled_vec_dot_q1_0_32x2(const uint32_t n, void * restrict s0, void * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const void * restrict sz0, const void * restrict sz1, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y0_q = vy0; const uint8_t * restrict y1_q = vy1; @@ -1057,19 +1293,11 @@ static void tiled_vec_dot_q1_0_32x2(const uint32_t n, float * restrict s0, float HVX_Vector v_sum_float_c0 = Q6_Vsf_equals_Vqf32(v_sum_qf_c0); HVX_Vector v_sum_float_c1 = Q6_Vsf_equals_Vqf32(v_sum_qf_c1); - if (sz0) { - hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0))); - } else { - hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0); - } - if (sz1) { - hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1))); - } else { - hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1); - } + store_row(s0, valid_rows, v_sum_float_c0, sz0); + store_row(s1, valid_rows, v_sum_float_c1, sz1); } -static void tiled_vec_dot_q4_0_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) { +static void tiled_vec_dot_q4_0_32x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const void * restrict sz, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y_q = vy; @@ -1092,14 +1320,10 @@ static void tiled_vec_dot_q4_0_32x1(const uint32_t n, float * restrict s, const v_sum_float = hvx_vec_add_f32_f32(v_sum_float, v_sum_scaled); } - if (sz) { - hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz))); - } else { - hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float); - } + store_row(s, valid_rows, v_sum_float, sz); } -static void tiled_vec_dot_q4_0_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) { +static void tiled_vec_dot_q4_0_32x2(const uint32_t n, void * restrict s0, void * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const void * restrict sz0, const void * restrict sz1, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y0_q = vy0; const uint8_t * restrict y1_q = vy1; @@ -1135,19 +1359,11 @@ static void tiled_vec_dot_q4_0_32x2(const uint32_t n, float * restrict s0, float v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, v_sum_scaled_c1); } - if (sz0) { - hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0))); - } else { - hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0); - } - if (sz1) { - hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1))); - } else { - hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1); - } + store_row(s0, valid_rows, v_sum_float_c0, sz0); + store_row(s1, valid_rows, v_sum_float_c1, sz1); } -static void tiled_vec_dot_q4_1_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) { +static void tiled_vec_dot_q4_1_32x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const void * restrict sz, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y_q = vy; @@ -1178,14 +1394,10 @@ static void tiled_vec_dot_q4_1_32x1(const uint32_t n, float * restrict s, const v_sum_float = hvx_vec_add_f32_f32(v_sum_float, v_sum_scaled); } - if (sz) { - hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz))); - } else { - hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float); - } + store_row(s, valid_rows, v_sum_float, sz); } -static void tiled_vec_dot_q4_1_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) { +static void tiled_vec_dot_q4_1_32x2(const uint32_t n, void * restrict s0, void * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const void * restrict sz0, const void * restrict sz1, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y0_q = vy0; const uint8_t * restrict y1_q = vy1; @@ -1231,19 +1443,11 @@ static void tiled_vec_dot_q4_1_32x2(const uint32_t n, float * restrict s0, float v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, v_sum_scaled_c1); } - if (sz0) { - hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0))); - } else { - hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0); - } - if (sz1) { - hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1))); - } else { - hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1); - } + store_row(s0, valid_rows, v_sum_float_c0, sz0); + store_row(s1, valid_rows, v_sum_float_c1, sz1); } -static void tiled_vec_dot_q8_0_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) { +static void tiled_vec_dot_q8_0_32x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const void * restrict sz, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y_q = vy; @@ -1265,14 +1469,10 @@ static void tiled_vec_dot_q8_0_32x1(const uint32_t n, float * restrict s, const v_sum_float = hvx_vec_add_f32_f32(v_sum_float, v_sum_scaled); } - if (sz) { - hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz))); - } else { - hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float); - } + store_row(s, valid_rows, v_sum_float, sz); } -static void tiled_vec_dot_q8_0_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) { +static void tiled_vec_dot_q8_0_32x2(const uint32_t n, void * restrict s0, void * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const void * restrict sz0, const void * restrict sz1, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y0_q = vy0; const uint8_t * restrict y1_q = vy1; @@ -1307,19 +1507,11 @@ static void tiled_vec_dot_q8_0_32x2(const uint32_t n, float * restrict s0, float v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, v_sum_scaled_c1); } - if (sz0) { - hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0))); - } else { - hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0); - } - if (sz1) { - hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1))); - } else { - hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1); - } + store_row(s0, valid_rows, v_sum_float_c0, sz0); + store_row(s1, valid_rows, v_sum_float_c1, sz1); } -static void tiled_vec_dot_q5_0_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) { +static void tiled_vec_dot_q5_0_32x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const void * restrict sz, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y_q = vy; @@ -1341,14 +1533,10 @@ static void tiled_vec_dot_q5_0_32x1(const uint32_t n, float * restrict s, const v_sum_float = hvx_vec_add_f32_f32(v_sum_float, v_sum_scaled); } - if (sz) { - hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz))); - } else { - hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float); - } + store_row(s, valid_rows, v_sum_float, sz); } -static void tiled_vec_dot_q5_0_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) { +static void tiled_vec_dot_q5_0_32x2(const uint32_t n, void * restrict s0, void * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const void * restrict sz0, const void * restrict sz1, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y0_q = vy0; const uint8_t * restrict y1_q = vy1; @@ -1383,19 +1571,11 @@ static void tiled_vec_dot_q5_0_32x2(const uint32_t n, float * restrict s0, float v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, v_sum_scaled_c1); } - if (sz0) { - hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0))); - } else { - hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0); - } - if (sz1) { - hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1))); - } else { - hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1); - } + store_row(s0, valid_rows, v_sum_float_c0, sz0); + store_row(s1, valid_rows, v_sum_float_c1, sz1); } -static void tiled_vec_dot_q5_k_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) { +static void tiled_vec_dot_q5_k_32x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const void * restrict sz, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y_q = vy; @@ -1406,7 +1586,7 @@ static void tiled_vec_dot_q5_k_32x1(const uint32_t n, float * restrict s, const const HVX_Vector * restrict vptr = (const HVX_Vector *) (tile_ptr + kt * 768); const HVX_Vector * restrict v_act = (const HVX_Vector *) (y_q + kt * 1280); - HVX_Vector v_sum = accum_5bit_32x1(vptr, v_act, Q6_V_vzero()); + HVX_Vector v_sum = accum_5bit_32x1(vptr, v_act); HVX_Vector v_sum_sf = Q6_Vsf_equals_Vw(v_sum); HVX_Vector v_scale_offset = vptr[4]; @@ -1426,14 +1606,10 @@ static void tiled_vec_dot_q5_k_32x1(const uint32_t n, float * restrict s, const v_sum_float = hvx_vec_add_f32_f32(v_sum_float, v_sum_scaled); } - if (sz) { - hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz))); - } else { - hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float); - } + store_row(s, valid_rows, v_sum_float, sz); } -static void tiled_vec_dot_q5_k_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) { +static void tiled_vec_dot_q5_k_32x2(const uint32_t n, void * restrict s0, void * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const void * restrict sz0, const void * restrict sz1, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y0_q = vy0; const uint8_t * restrict y1_q = vy1; @@ -1447,7 +1623,7 @@ static void tiled_vec_dot_q5_k_32x2(const uint32_t n, float * restrict s0, float const HVX_Vector * restrict v_act0 = (const HVX_Vector *) (y0_q + kt * 1280); const HVX_Vector * restrict v_act1 = (const HVX_Vector *) (y1_q + kt * 1280); - HVX_VectorPair v_sums = accum_5bit_32x2(vptr, v_act0, v_act1, Q6_V_vzero()); + HVX_VectorPair v_sums = accum_5bit_32x2(vptr, v_act0, v_act1); HVX_Vector v_sum_c0 = Q6_V_lo_W(v_sums); HVX_Vector v_sum_c1 = Q6_V_hi_W(v_sums); @@ -1479,19 +1655,11 @@ static void tiled_vec_dot_q5_k_32x2(const uint32_t n, float * restrict s0, float v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, v_sum_scaled_c1); } - if (sz0) { - hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0))); - } else { - hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0); - } - if (sz1) { - hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1))); - } else { - hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1); - } + store_row(s0, valid_rows, v_sum_float_c0, sz0); + store_row(s1, valid_rows, v_sum_float_c1, sz1); } -static void tiled_vec_dot_q6_k_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) { +static void tiled_vec_dot_q6_k_32x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const void * restrict sz, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y_q = vy; @@ -1507,14 +1675,10 @@ static void tiled_vec_dot_q6_k_32x1(const uint32_t n, float * restrict s, const v_sum_float = hvx_vec_add_f32_f32(v_sum_float, scale_q6_k_32x1(v_sums, vptr[6], v_act[8])); } - if (sz) { - hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz))); - } else { - hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float); - } + store_row(s, valid_rows, v_sum_float, sz); } -static void tiled_vec_dot_q6_k_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) { +static void tiled_vec_dot_q6_k_32x2(const uint32_t n, void * restrict s0, void * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const void * restrict sz0, const void * restrict sz1, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y0_q = vy0; const uint8_t * restrict y1_q = vy1; @@ -1536,19 +1700,11 @@ static void tiled_vec_dot_q6_k_32x2(const uint32_t n, float * restrict s0, float v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, scale_q6_k_32x1(v_sums1, vptr[6], v_act1[8])); } - if (sz0) { - hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0))); - } else { - hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0); - } - if (sz1) { - hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1))); - } else { - hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1); - } + store_row(s0, valid_rows, v_sum_float_c0, sz0); + store_row(s1, valid_rows, v_sum_float_c1, sz1); } -static void tiled_vec_dot_q3_k_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) { +static void tiled_vec_dot_q3_k_32x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const void * restrict sz, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y_q = vy; @@ -1563,14 +1719,10 @@ static void tiled_vec_dot_q3_k_32x1(const uint32_t n, float * restrict s, const v_sum_float = hvx_vec_add_f32_f32(v_sum_float, scale_q6_k_32x1(v_sums, vptr[3], v_act[8])); } - if (sz) { - hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz))); - } else { - hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float); - } + store_row(s, valid_rows, v_sum_float, sz); } -static void tiled_vec_dot_q3_k_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) { +static void tiled_vec_dot_q3_k_32x2(const uint32_t n, void * restrict s0, void * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const void * restrict sz0, const void * restrict sz1, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y0_q = vy0; const uint8_t * restrict y1_q = vy1; @@ -1591,19 +1743,11 @@ static void tiled_vec_dot_q3_k_32x2(const uint32_t n, float * restrict s0, float v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, scale_q6_k_32x1(v_sums1, vptr[3], v_act1[8])); } - if (sz0) { - hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0))); - } else { - hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0); - } - if (sz1) { - hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1))); - } else { - hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1); - } + store_row(s0, valid_rows, v_sum_float_c0, sz0); + store_row(s1, valid_rows, v_sum_float_c1, sz1); } -static void tiled_vec_dot_q2_k_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) { +static void tiled_vec_dot_q2_k_32x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const void * restrict sz, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y_q = vy; @@ -1628,14 +1772,10 @@ static void tiled_vec_dot_q2_k_32x1(const uint32_t n, float * restrict s, const v_sum_float = hvx_vec_add_f32_f32(v_sum_float, q2_k_int_scale(v_isum, v_msum, v_d, v_m, v_act_sb[8])); } - if (sz) { - hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz))); - } else { - hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float); - } + store_row(s, valid_rows, v_sum_float, sz); } -static void tiled_vec_dot_q2_k_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) { +static void tiled_vec_dot_q2_k_32x2(const uint32_t n, void * restrict s0, void * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const void * restrict sz0, const void * restrict sz1, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y0_q = vy0; const uint8_t * restrict y1_q = vy1; @@ -1671,20 +1811,12 @@ static void tiled_vec_dot_q2_k_32x2(const uint32_t n, float * restrict s0, float v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, q2_k_int_scale(v_isum1, v_msum1, v_d, v_m, v_act1_sb[8])); } - if (sz0) { - hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0))); - } else { - hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0); - } - if (sz1) { - hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1))); - } else { - hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1); - } + store_row(s0, valid_rows, v_sum_float_c0, sz0); + store_row(s1, valid_rows, v_sum_float_c1, sz1); } // One Q2_0 weight tile covers 64 k: act tiles 2 * kt and 2 * kt + 1, each 32 k wide (Q8_1) -static void tiled_vec_dot_q2_0_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) { +static void tiled_vec_dot_q2_0_32x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const void * restrict sz, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y_q = vy; @@ -1711,14 +1843,10 @@ static void tiled_vec_dot_q2_0_32x1(const uint32_t n, float * restrict s, const v_sum_float = hvx_vec_add_f32_f32(v_sum_float, hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vqf32(v_tile_qf), v_dw_sf)); } - if (sz) { - hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz))); - } else { - hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float); - } + store_row(s, valid_rows, v_sum_float, sz); } -static void tiled_vec_dot_q2_0_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) { +static void tiled_vec_dot_q2_0_32x2(const uint32_t n, void * restrict s0, void * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const void * restrict sz0, const void * restrict sz1, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y0_q = vy0; const uint8_t * restrict y1_q = vy1; @@ -1758,19 +1886,11 @@ static void tiled_vec_dot_q2_0_32x2(const uint32_t n, float * restrict s0, float v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vec_mul_f32_f32(Q6_Vsf_equals_Vqf32(v_tile_qf_c1), v_dw_sf)); } - if (sz0) { - hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0))); - } else { - hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0); - } - if (sz1) { - hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1))); - } else { - hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1); - } + store_row(s0, valid_rows, v_sum_float_c0, sz0); + store_row(s1, valid_rows, v_sum_float_c1, sz1); } -static void tiled_vec_dot_iq4nl_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) { +static void tiled_vec_dot_iq4nl_32x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const void * restrict sz, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y_q = vy; @@ -1794,14 +1914,10 @@ static void tiled_vec_dot_iq4nl_32x1(const uint32_t n, float * restrict s, const v_sum_float = hvx_vec_add_f32_f32(v_sum_float, v_sum_scaled); } - if (sz) { - hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz))); - } else { - hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float); - } + store_row(s, valid_rows, v_sum_float, sz); } -static void tiled_vec_dot_iq4nl_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) { +static void tiled_vec_dot_iq4nl_32x2(const uint32_t n, void * restrict s0, void * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const void * restrict sz0, const void * restrict sz1, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y0_q = vy0; const uint8_t * restrict y1_q = vy1; @@ -1838,16 +1954,8 @@ static void tiled_vec_dot_iq4nl_32x2(const uint32_t n, float * restrict s0, floa v_sum_float_c1 = hvx_vec_add_f32_f32(v_sum_float_c1, v_sum_scaled_c1); } - if (sz0) { - hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0))); - } else { - hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0); - } - if (sz1) { - hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1))); - } else { - hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1); - } + store_row(s0, valid_rows, v_sum_float_c0, sz0); + store_row(s1, valid_rows, v_sum_float_c1, sz1); } #define IQ2XXS_GROUPS 4 // 8-element grid entries per tile row @@ -1958,7 +2066,7 @@ static inline HVX_Vector iq2xxs_load_d(const uint8_t * restrict sb) { return hvx_vec_mul_f32_f32(Q6_V_lo_W(hvx_vec_f16_to_f32(iq2xxs_gather_d(sb))), hvx_vec_splat_f32(IQ2XXS_D_SCALE)); } -static void tiled_vec_dot_iq2xxs_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) { +static void tiled_vec_dot_iq2xxs_32x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const void * restrict sz, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y_q = vy; const uint32_t padded = htp_tensor_get_tile_padded_size(HTP_TYPE_IQ2_XXS); @@ -1993,14 +2101,10 @@ static void tiled_vec_dot_iq2xxs_32x1(const uint32_t n, float * restrict s, cons } } - if (sz) { - hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz))); - } else { - hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float); - } + store_row(s, valid_rows, v_sum_float, sz); } -static void tiled_vec_dot_iq2xxs_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) { +static void tiled_vec_dot_iq2xxs_32x2(const uint32_t n, void * restrict s0, void * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const void * restrict sz0, const void * restrict sz1, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y0_q = vy0; const uint8_t * restrict y1_q = vy1; @@ -2044,19 +2148,11 @@ static void tiled_vec_dot_iq2xxs_32x2(const uint32_t n, float * restrict s0, flo } } - if (sz0) { - hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0))); - } else { - hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0); - } - if (sz1) { - hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1))); - } else { - hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1); - } + store_row(s0, valid_rows, v_sum_float_c0, sz0); + store_row(s1, valid_rows, v_sum_float_c1, sz1); } -static void tiled_vec_dot_mxfp4_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) { +static void tiled_vec_dot_mxfp4_32x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const void * restrict sz, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y_q = vy; @@ -2091,14 +2187,10 @@ static void tiled_vec_dot_mxfp4_32x1(const uint32_t n, float * restrict s, const v_sum_float = hvx_vec_mul_f32_f32(v_sum_float, hvx_vec_splat_f32(0.5f)); - if (sz) { - hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz))); - } else { - hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float); - } + store_row(s, valid_rows, v_sum_float, sz); } -static void tiled_vec_dot_mxfp4_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) { +static void tiled_vec_dot_mxfp4_32x2(const uint32_t n, void * restrict s0, void * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const void * restrict sz0, const void * restrict sz1, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y0_q = vy0; const uint8_t * restrict y1_q = vy1; @@ -2150,16 +2242,8 @@ static void tiled_vec_dot_mxfp4_32x2(const uint32_t n, float * restrict s0, floa v_sum_float_c0 = hvx_vec_mul_f32_f32(v_sum_float_c0, hvx_vec_splat_f32(0.5f)); v_sum_float_c1 = hvx_vec_mul_f32_f32(v_sum_float_c1, hvx_vec_splat_f32(0.5f)); - if (sz0) { - hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0))); - } else { - hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0); - } - if (sz1) { - hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1))); - } else { - hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1); - } + store_row(s0, valid_rows, v_sum_float_c0, sz0); + store_row(s1, valid_rows, v_sum_float_c1, sz1); } #define NVFP4_SCALE_OFF 512 // UE4M3 scales after the 32 rows x 16 B of quants @@ -2200,9 +2284,9 @@ static inline HVX_Vector accum_nvfp4_group_32x1(const HVX_Vector * restrict vptr #pragma unroll for (int i = 0; i < NVFP4_VECS_PER_GROUP; i++) { - HVX_VectorPair v_W_pair = unpack_and_interleave_4bit_x2(vptr[i], mask_h4); - HVX_Vector v_W0 = Q6_Vb_vlut32_VbVbI(Q6_V_lo_W(v_W_pair), lut, 0); - HVX_Vector v_W1 = Q6_Vb_vlut32_VbVbI(Q6_V_hi_W(v_W_pair), lut, 0); + HVX_Vector v_src = vptr[i]; + HVX_Vector v_W0 = Q6_Vb_vlut32_VbVbI(Q6_V_vand_VV(v_src, mask_h4), lut, 0); + HVX_Vector v_W1 = Q6_Vb_vlut32_VbVbI(Q6_Vub_vlsr_VubR(v_src, 4), lut, 0); v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act[i * 2 + 0]); v_sum1 = Q6_Vw_vrmpyacc_VwVbVb(v_sum1, v_W1, v_act[i * 2 + 1]); } @@ -2216,9 +2300,9 @@ static inline HVX_VectorPair accum_nvfp4_group_32x2(const HVX_Vector * restrict #pragma unroll for (int i = 0; i < NVFP4_VECS_PER_GROUP; i++) { - HVX_VectorPair v_W_pair = unpack_and_interleave_4bit_x2(vptr[i], mask_h4); - HVX_Vector v_W0 = Q6_Vb_vlut32_VbVbI(Q6_V_lo_W(v_W_pair), lut, 0); - HVX_Vector v_W1 = Q6_Vb_vlut32_VbVbI(Q6_V_hi_W(v_W_pair), lut, 0); + HVX_Vector v_src = vptr[i]; + HVX_Vector v_W0 = Q6_Vb_vlut32_VbVbI(Q6_V_vand_VV(v_src, mask_h4), lut, 0); + HVX_Vector v_W1 = Q6_Vb_vlut32_VbVbI(Q6_Vub_vlsr_VubR(v_src, 4), lut, 0); v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W0, v_act0[i * 2 + 0]); v_sum0 = Q6_Vw_vrmpyacc_VwVbVb(v_sum0, v_W1, v_act0[i * 2 + 1]); @@ -2230,7 +2314,7 @@ static inline HVX_VectorPair accum_nvfp4_group_32x2(const HVX_Vector * restrict return Q6_W_vcombine_VV(v_sum1, v_sum0); } -static void tiled_vec_dot_nvfp4_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) { +static void tiled_vec_dot_nvfp4_32x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const void * restrict sz, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y_q = vy; const uint32_t padded = htp_tensor_get_tile_padded_size(HTP_TYPE_NVFP4); @@ -2261,14 +2345,10 @@ static void tiled_vec_dot_nvfp4_32x1(const uint32_t n, float * restrict s, const v_sum_float = hvx_vec_mul_f32_f32(v_sum_float, hvx_vec_splat_f32(0.5f)); - if (sz) { - hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float, hvx_vmemu(sz))); - } else { - hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum_float); - } + store_row(s, valid_rows, v_sum_float, sz); } -static void tiled_vec_dot_nvfp4_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) { +static void tiled_vec_dot_nvfp4_32x2(const uint32_t n, void * restrict s0, void * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const void * restrict sz0, const void * restrict sz1, hvx_tiled_store_row_fn_t store_row) { const uint8_t * restrict tile_ptr = vx; const uint8_t * restrict y0_q = vy0; const uint8_t * restrict y1_q = vy1; @@ -2307,19 +2387,11 @@ static void tiled_vec_dot_nvfp4_32x2(const uint32_t n, float * restrict s0, floa v_sum_float_c0 = hvx_vec_mul_f32_f32(v_sum_float_c0, hvx_vec_splat_f32(0.5f)); v_sum_float_c1 = hvx_vec_mul_f32_f32(v_sum_float_c1, hvx_vec_splat_f32(0.5f)); - if (sz0) { - hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c0, hvx_vmemu(sz0))); - } else { - hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum_float_c0); - } - if (sz1) { - hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum_float_c1, hvx_vmemu(sz1))); - } else { - hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum_float_c1); - } + store_row(s0, valid_rows, v_sum_float_c0, sz0); + store_row(s1, valid_rows, v_sum_float_c1, sz1); } -static void tiled_vec_dot_f16_32x1(const uint32_t n, float * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const float * restrict sz) { +static void tiled_vec_dot_f16_32x1(const uint32_t n, void * restrict s, const void * restrict vx, const void * restrict vy, uint32_t valid_rows, const void * restrict sz, hvx_tiled_store_row_fn_t store_row) { const HVX_Vector * restrict vptr = (const HVX_Vector *) vx; const HVX_Vector * restrict v_act = (const HVX_Vector *) vy; const uint32_t n_vecs = ((n + 31) / 32) * 16; @@ -2333,14 +2405,10 @@ static void tiled_vec_dot_f16_32x1(const uint32_t n, float * restrict s, const v HVX_Vector v_sum = hvx_vec_add_f32_f32(Q6_V_lo_W(acc), Q6_V_hi_W(acc)); - if (sz) { - hvx_vec_store_u(s, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum, hvx_vmemu(sz))); - } else { - hvx_vec_store_u(s, valid_rows * sizeof(float), v_sum); - } + store_row(s, valid_rows, v_sum, sz); } -static void tiled_vec_dot_f16_32x2(const uint32_t n, float * restrict s0, float * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const float * restrict sz0, const float * restrict sz1) { +static void tiled_vec_dot_f16_32x2(const uint32_t n, void * restrict s0, void * restrict s1, const void * restrict vx, const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, const void * restrict sz0, const void * restrict sz1, hvx_tiled_store_row_fn_t store_row) { const HVX_Vector * restrict vptr = (const HVX_Vector *) vx; const HVX_Vector * restrict v_act0 = (const HVX_Vector *) vy0; const HVX_Vector * restrict v_act1 = (const HVX_Vector *) vy1; @@ -2359,16 +2427,8 @@ static void tiled_vec_dot_f16_32x2(const uint32_t n, float * restrict s0, float HVX_Vector v_sum0 = hvx_vec_add_f32_f32(Q6_V_lo_W(acc0), Q6_V_hi_W(acc0)); HVX_Vector v_sum1 = hvx_vec_add_f32_f32(Q6_V_lo_W(acc1), Q6_V_hi_W(acc1)); - if (sz0) { - hvx_vec_store_u(s0, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum0, hvx_vmemu(sz0))); - } else { - hvx_vec_store_u(s0, valid_rows * sizeof(float), v_sum0); - } - if (sz1) { - hvx_vec_store_u(s1, valid_rows * sizeof(float), hvx_vec_add_f32_f32(v_sum1, hvx_vmemu(sz1))); - } else { - hvx_vec_store_u(s1, valid_rows * sizeof(float), v_sum1); - } + store_row(s0, valid_rows, v_sum0, sz0); + store_row(s1, valid_rows, v_sum1, sz1); } @@ -2389,6 +2449,23 @@ static inline void quantize_f32_q8_0_tiled_kernel( } } +static inline void quantize_f16_q8_0_tiled_kernel( + const uint8_t * restrict src_data, + uint8_t * restrict dst_data, + uint8_t * restrict tmp_data, + uint32_t ne0, + uint32_t nrows, + size_t src_row_size, + size_t dst_row_size +) { + (void) tmp_data; + for (uint32_t i = 0; i < nrows; ++i) { + quantize_row_f16_q8_0_tiled((const __fp16 *) src_data, dst_data, ne0); + dst_data += dst_row_size; + src_data += src_row_size; + } +} + static inline void quantize_f32_q8_1_tiled_kernel( const uint8_t * restrict src_data, uint8_t * restrict dst_data, @@ -2406,6 +2483,23 @@ static inline void quantize_f32_q8_1_tiled_kernel( } } +static inline void quantize_f16_q8_1_tiled_kernel( + const uint8_t * restrict src_data, + uint8_t * restrict dst_data, + uint8_t * restrict tmp_data, + uint32_t ne0, + uint32_t nrows, + size_t src_row_size, + size_t dst_row_size +) { + (void) tmp_data; + for (uint32_t i = 0; i < nrows; ++i) { + quantize_row_f16_q8_1_tiled((const __fp16 *) src_data, dst_data, ne0); + dst_data += dst_row_size; + src_data += src_row_size; + } +} + static inline void quantize_f32_q8_1_s16_tiled_kernel( const uint8_t * restrict src_data, uint8_t * restrict dst_data, @@ -2423,6 +2517,23 @@ static inline void quantize_f32_q8_1_s16_tiled_kernel( } } +static inline void quantize_f16_q8_1_s16_tiled_kernel( + const uint8_t * restrict src_data, + uint8_t * restrict dst_data, + uint8_t * restrict tmp_data, + uint32_t ne0, + uint32_t nrows, + size_t src_row_size, + size_t dst_row_size +) { + (void) tmp_data; + for (uint32_t i = 0; i < nrows; ++i) { + quantize_row_f16_q8_1_s16_tiled((const __fp16 *) src_data, dst_data, ne0); + dst_data += dst_row_size; + src_data += src_row_size; + } +} + static inline void quantize_f32_f16_tiled_kernel( const uint8_t * restrict src_data, uint8_t * restrict dst_data, @@ -2487,6 +2598,36 @@ static inline void quantize_f32_q8_0_tiled_block_kernel( } } +static inline void quantize_f16_q8_0_tiled_block_kernel( + const __fp16 * restrict src, + uint8_t * restrict dst, + uint8_t * restrict tmp_data, + uint32_t ne0, + uint32_t ib_first, + uint32_t ib_last, + size_t src_row_size, + size_t dst_row_size, + uint32_t r, + uint32_t c +) { + (void) tmp_data; + const uint32_t qk = HTP_MM_ACT_BLOCK_K; + const uint32_t nb = (ne0 + qk - 1) / qk; + + for (uint32_t ib = ib_first; ib < ib_last; ++ib) { + const __fp16 * restrict src_ptr = (const __fp16 *) ((const uint8_t *) src + r * src_row_size + c * qk * sizeof(__fp16)); + uint8_t * restrict dst_ptr = dst + r * dst_row_size + c * 4 * 1152; + + quantize_block_f16_q8_0_tiled(src_ptr, dst_ptr); + + c++; + if (c == nb) { + c = 0; + r++; + } + } +} + static inline void quantize_f32_q8_1_tiled_block_kernel( const float * restrict src, uint8_t * restrict dst, @@ -2517,6 +2658,36 @@ static inline void quantize_f32_q8_1_tiled_block_kernel( } } +static inline void quantize_f16_q8_1_tiled_block_kernel( + const __fp16 * restrict src, + uint8_t * restrict dst, + uint8_t * restrict tmp_data, + uint32_t ne0, + uint32_t ib_first, + uint32_t ib_last, + size_t src_row_size, + size_t dst_row_size, + uint32_t r, + uint32_t c +) { + (void) tmp_data; + const uint32_t qk = HTP_MM_ACT_BLOCK_K; + const uint32_t nb = (ne0 + qk - 1) / qk; + + for (uint32_t ib = ib_first; ib < ib_last; ++ib) { + const __fp16 * restrict src_ptr = (const __fp16 *) ((const uint8_t *) src + r * src_row_size + c * qk * sizeof(__fp16)); + uint8_t * restrict dst_ptr = dst + r * dst_row_size + c * 4 * 1280; + + quantize_block_f16_q8_1_tiled(src_ptr, dst_ptr); + + c++; + if (c == nb) { + c = 0; + r++; + } + } +} + static inline void quantize_f32_q8_1_s16_tiled_block_kernel( const float * restrict src, uint8_t * restrict dst, @@ -2547,6 +2718,36 @@ static inline void quantize_f32_q8_1_s16_tiled_block_kernel( } } +static inline void quantize_f16_q8_1_s16_tiled_block_kernel( + const __fp16 * restrict src, + uint8_t * restrict dst, + uint8_t * restrict tmp_data, + uint32_t ne0, + uint32_t ib_first, + uint32_t ib_last, + size_t src_row_size, + size_t dst_row_size, + uint32_t r, + uint32_t c +) { + (void) tmp_data; + const uint32_t qk = HTP_MM_ACT_BLOCK_K; + const uint32_t nb = (ne0 + qk - 1) / qk; + + for (uint32_t ib = ib_first; ib < ib_last; ++ib) { + const __fp16 * restrict src_ptr = (const __fp16 *) ((const uint8_t *) src + r * src_row_size + c * qk * sizeof(__fp16)); + uint8_t * restrict dst_ptr = dst + r * dst_row_size + c * 4 * 1280; + + quantize_block_f16_q8_1_s16_tiled(src_ptr, dst_ptr, src_ptr - (c & 1) * qk); // super-block of 256 k + + c++; + if (c == nb) { + c = 0; + r++; + } + } +} + static inline void quantize_f32_f16_tiled_block_kernel( const float * restrict src, uint8_t * restrict dst, diff --git a/ggml/src/ggml-hexagon/htp/hvx-norm.h b/ggml/src/ggml-hexagon/htp/hvx-norm.h index 5d13acc872e5..4f6011cc1ea5 100644 --- a/ggml/src/ggml-hexagon/htp/hvx-norm.h +++ b/ggml/src/ggml-hexagon/htp/hvx-norm.h @@ -341,29 +341,48 @@ static inline void hvx_fast_rms_norm_f16(const uint8_t * restrict src, const int nvec = num_elems / VLEN_FP16; // number of full f16 vectors const int nloe = num_elems % VLEN_FP16; // leftover elements - HVX_Vector sum_v = Q6_V_vsplat_R(0x00000000); HVX_Vector epsilon_v = hvx_vec_splat_f32(epsilon); +#if __HVX_ARCH__ >= 79 + HVX_VectorPair sum_p = Q6_W_vzero(); + #pragma unroll(4) for (int i = 0; i < nvec; i++) { - HVX_VectorPair p = hvx_vec_f16_to_f32(v_src[i]); - HVX_Vector p0 = Q6_V_lo_W(p); - HVX_Vector p1 = Q6_V_hi_W(p); - sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(p0, p0)); - sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(p1, p1)); + HVX_Vector v = v_src[i]; + sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, v, v); } if (nloe > 0) { HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * SIZEOF_FP16); - HVX_Vector v1 = Q6_V_vand_QV(bmask, v_src[nvec]); - HVX_VectorPair p = hvx_vec_f16_to_f32(v1); - HVX_Vector p0 = Q6_V_lo_W(p); - HVX_Vector p1 = Q6_V_hi_W(p); - sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(p0, p0)); - sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(p1, p1)); + HVX_Vector v = Q6_V_vand_QV(bmask, v_src[nvec]); + sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, v, v); } - sum_v = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_v)); + HVX_Vector sum_v = Q6_Vsf_vadd_VsfVsf(Q6_V_lo_W(sum_p), Q6_V_hi_W(sum_p)); +#else + HVX_Vector sum0 = Q6_V_vzero(); + HVX_Vector sum1 = Q6_V_vzero(); + + #pragma unroll(4) + for (int i = 0; i < nvec; i++) { + HVX_Vector v = v_src[i]; + HVX_VectorPair sq = Q6_Wqf32_vmpy_VhfVhf(v, v); + sum0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum0, Q6_V_lo_W(sq)); + sum1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum1, Q6_V_hi_W(sq)); + } + + if (nloe > 0) { + HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * SIZEOF_FP16); + HVX_Vector v = Q6_V_vand_QV(bmask, v_src[nvec]); + HVX_VectorPair sq = Q6_Wqf32_vmpy_VhfVhf(v, v); + sum0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum0, Q6_V_lo_W(sq)); + sum1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum1, Q6_V_hi_W(sq)); + } + + HVX_Vector sum_v = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(sum0, sum1)); +#endif + + sum_v = hvx_vec_reduce_sum_f32(sum_v); HVX_Vector t_v = hvx_vec_splat_f32((float) num_elems); HVX_Vector denom_v = hvx_vec_inverse_f32(t_v); @@ -374,19 +393,19 @@ static inline void hvx_fast_rms_norm_f16(const uint8_t * restrict src, #pragma unroll(4) for (int i = 0; i < nvec; i++) { - HVX_VectorPair p = hvx_vec_f16_to_f32(v_src[i]); + HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(v_src[i]); HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(p), scale_v)); HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(p), scale_v)); - v_dst[i] = hvx_vec_f32_to_f16(r0, r1); + v_dst[i] = hvx_vec_f32_to_f16_shuff(r0, r1); } if (nloe > 0) { HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * SIZEOF_FP16); HVX_Vector v1 = Q6_V_vand_QV(bmask, v_src[nvec]); - HVX_VectorPair p = hvx_vec_f16_to_f32(v1); + HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(v1); HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(p), scale_v)); HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(p), scale_v)); - HVX_Vector result = hvx_vec_f32_to_f16(r0, r1); + HVX_Vector result = hvx_vec_f32_to_f16_shuff(r0, r1); hvx_vec_store_a(&v_dst[nvec], nloe * SIZEOF_FP16, result); } } @@ -402,35 +421,63 @@ static inline void hvx_fast_norm_f16(const uint8_t * restrict src, const int nvec = num_elems / VLEN_FP16; const int nloe = num_elems % VLEN_FP16; - HVX_Vector sum_sq_v = Q6_V_vsplat_R(0x00000000); - HVX_Vector sum_x_v = Q6_V_vsplat_R(0x00000000); + const HVX_Vector one_hf = hvx_vec_splat_f16(1.0); HVX_Vector epsilon_v = hvx_vec_splat_f32(epsilon); +#if __HVX_ARCH__ >= 79 + HVX_VectorPair sum_sq_p = Q6_W_vzero(); + HVX_VectorPair sum_x_p = Q6_W_vzero(); + #pragma unroll(4) for (int i = 0; i < nvec; i++) { - HVX_VectorPair p = hvx_vec_f16_to_f32(v_src[i]); - HVX_Vector p0 = Q6_V_lo_W(p); - HVX_Vector p1 = Q6_V_hi_W(p); - sum_sq_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_sq_v, Q6_Vqf32_vmpy_VsfVsf(p0, p0)); - sum_sq_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_sq_v, Q6_Vqf32_vmpy_VsfVsf(p1, p1)); - sum_x_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_x_v, Q6_Vqf32_vadd_VsfVsf(p0, Q6_V_vzero())); - sum_x_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_x_v, Q6_Vqf32_vadd_VsfVsf(p1, Q6_V_vzero())); + HVX_Vector v = v_src[i]; + sum_sq_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_sq_p, v, v); + sum_x_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_x_p, v, one_hf); } if (nloe > 0) { HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * SIZEOF_FP16); - HVX_Vector v1 = Q6_V_vand_QV(bmask, v_src[nvec]); - HVX_VectorPair p = hvx_vec_f16_to_f32(v1); - HVX_Vector p0 = Q6_V_lo_W(p); - HVX_Vector p1 = Q6_V_hi_W(p); - sum_sq_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_sq_v, Q6_Vqf32_vmpy_VsfVsf(p0, p0)); - sum_sq_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_sq_v, Q6_Vqf32_vmpy_VsfVsf(p1, p1)); - sum_x_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_x_v, Q6_Vqf32_vadd_VsfVsf(p0, Q6_V_vzero())); - sum_x_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_x_v, Q6_Vqf32_vadd_VsfVsf(p1, Q6_V_vzero())); + HVX_Vector v = Q6_V_vand_QV(bmask, v_src[nvec]); + sum_sq_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_sq_p, v, v); + sum_x_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_x_p, v, one_hf); } - sum_sq_v = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_sq_v)); - sum_x_v = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_x_v)); + HVX_Vector sum_sq_v = Q6_Vsf_vadd_VsfVsf(Q6_V_lo_W(sum_sq_p), Q6_V_hi_W(sum_sq_p)); + HVX_Vector sum_x_v = Q6_Vsf_vadd_VsfVsf(Q6_V_lo_W(sum_x_p), Q6_V_hi_W(sum_x_p)); +#else + HVX_Vector sum_sq0 = Q6_V_vzero(); + HVX_Vector sum_sq1 = Q6_V_vzero(); + HVX_Vector sum_x0 = Q6_V_vzero(); + HVX_Vector sum_x1 = Q6_V_vzero(); + + #pragma unroll(4) + for (int i = 0; i < nvec; i++) { + HVX_Vector v = v_src[i]; + HVX_VectorPair sq = Q6_Wqf32_vmpy_VhfVhf(v, v); + HVX_VectorPair xp = Q6_Wqf32_vmpy_VhfVhf(v, one_hf); + sum_sq0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum_sq0, Q6_V_lo_W(sq)); + sum_sq1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum_sq1, Q6_V_hi_W(sq)); + sum_x0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum_x0, Q6_V_lo_W(xp)); + sum_x1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum_x1, Q6_V_hi_W(xp)); + } + + if (nloe > 0) { + HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * SIZEOF_FP16); + HVX_Vector v = Q6_V_vand_QV(bmask, v_src[nvec]); + HVX_VectorPair sq = Q6_Wqf32_vmpy_VhfVhf(v, v); + HVX_VectorPair xp = Q6_Wqf32_vmpy_VhfVhf(v, one_hf); + sum_sq0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum_sq0, Q6_V_lo_W(sq)); + sum_sq1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum_sq1, Q6_V_hi_W(sq)); + sum_x0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum_x0, Q6_V_lo_W(xp)); + sum_x1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum_x1, Q6_V_hi_W(xp)); + } + + HVX_Vector sum_sq_v = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(sum_sq0, sum_sq1)); + HVX_Vector sum_x_v = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(sum_x0, sum_x1)); +#endif + + sum_sq_v = hvx_vec_reduce_sum_f32(sum_sq_v); + sum_x_v = hvx_vec_reduce_sum_f32(sum_x_v); HVX_Vector t_v = hvx_vec_splat_f32((float) num_elems); HVX_Vector denom_v = hvx_vec_inverse_f32(t_v); @@ -445,23 +492,23 @@ static inline void hvx_fast_norm_f16(const uint8_t * restrict src, #pragma unroll(4) for (int i = 0; i < nvec; i++) { - HVX_VectorPair p = hvx_vec_f16_to_f32(v_src[i]); + HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(v_src[i]); HVX_Vector d0 = Q6_Vqf32_vsub_VsfVsf(Q6_V_lo_W(p), mean_x_b); HVX_Vector d1 = Q6_Vqf32_vsub_VsfVsf(Q6_V_hi_W(p), mean_x_b); HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(d0), scale_v)); HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(d1), scale_v)); - v_dst[i] = hvx_vec_f32_to_f16(r0, r1); + v_dst[i] = hvx_vec_f32_to_f16_shuff(r0, r1); } if (nloe > 0) { HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * SIZEOF_FP16); HVX_Vector v1 = Q6_V_vand_QV(bmask, v_src[nvec]); - HVX_VectorPair p = hvx_vec_f16_to_f32(v1); + HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(v1); HVX_Vector d0 = Q6_Vqf32_vsub_VsfVsf(Q6_V_lo_W(p), mean_x_b); HVX_Vector d1 = Q6_Vqf32_vsub_VsfVsf(Q6_V_hi_W(p), mean_x_b); HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(d0), scale_v)); HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(d1), scale_v)); - HVX_Vector result = hvx_vec_f32_to_f16(r0, r1); + HVX_Vector result = hvx_vec_f32_to_f16_shuff(r0, r1); hvx_vec_store_a(&v_dst[nvec], nloe * SIZEOF_FP16, result); } } @@ -477,51 +524,224 @@ static inline void hvx_fast_l2_norm_f16(const uint8_t * restrict src, const int nvec = num_elems / VLEN_FP16; const int nloe = num_elems % VLEN_FP16; - HVX_Vector sum_v = hvx_vec_splat_f32(0.0f); +#if __HVX_ARCH__ >= 79 + HVX_VectorPair sum_p = Q6_W_vzero(); #pragma unroll(4) for (int i = 0; i < nvec; i++) { - HVX_VectorPair p = hvx_vec_f16_to_f32(v_src[i]); - HVX_Vector p0 = Q6_V_lo_W(p); - HVX_Vector p1 = Q6_V_hi_W(p); - sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(p0, p0)); - sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(p1, p1)); + HVX_Vector v = v_src[i]; + sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, v, v); } if (nloe > 0) { HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * SIZEOF_FP16); - HVX_Vector v1 = Q6_V_vand_QV(bmask, v_src[nvec]); - HVX_VectorPair p = hvx_vec_f16_to_f32(v1); - HVX_Vector p0 = Q6_V_lo_W(p); - HVX_Vector p1 = Q6_V_hi_W(p); - sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(p0, p0)); - sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(p1, p1)); + HVX_Vector v = Q6_V_vand_QV(bmask, v_src[nvec]); + sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, v, v); } - HVX_Vector sum_sf = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_v)); - HVX_Vector rsqrt_v = hvx_vec_rsqrt_f32(sum_sf); - HVX_Vector sqrt_v = hvx_vec_inverse_f32(rsqrt_v); - HVX_Vector epsilon_v = hvx_vec_splat_f32(epsilon); - HVX_Vector denom_v = Q6_Vsf_vmax_VsfVsf(sqrt_v, epsilon_v); - HVX_Vector scale_v = hvx_vec_inverse_f32(denom_v); + HVX_Vector sum_sf = Q6_Vsf_vadd_VsfVsf(Q6_V_lo_W(sum_p), Q6_V_hi_W(sum_p)); +#else + HVX_Vector sum0 = Q6_V_vzero(); + HVX_Vector sum1 = Q6_V_vzero(); #pragma unroll(4) for (int i = 0; i < nvec; i++) { - HVX_VectorPair p = hvx_vec_f16_to_f32(v_src[i]); + HVX_Vector v = v_src[i]; + HVX_VectorPair sq = Q6_Wqf32_vmpy_VhfVhf(v, v); + sum0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum0, Q6_V_lo_W(sq)); + sum1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum1, Q6_V_hi_W(sq)); + } + + if (nloe > 0) { + HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * SIZEOF_FP16); + HVX_Vector v = Q6_V_vand_QV(bmask, v_src[nvec]); + HVX_VectorPair sq = Q6_Wqf32_vmpy_VhfVhf(v, v); + sum0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum0, Q6_V_lo_W(sq)); + sum1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum1, Q6_V_hi_W(sq)); + } + + HVX_Vector sum_sf = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(sum0, sum1)); +#endif + + sum_sf = hvx_vec_reduce_sum_f32(sum_sf); + HVX_Vector eps2_v = hvx_vec_splat_f32(epsilon * epsilon); + HVX_Vector scale_v = hvx_vec_rsqrt_f32(Q6_Vsf_vmax_VsfVsf(sum_sf, eps2_v)); + + #pragma unroll(4) + for (int i = 0; i < nvec; i++) { + HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(v_src[i]); HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(p), scale_v)); HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(p), scale_v)); - v_dst[i] = hvx_vec_f32_to_f16(r0, r1); + v_dst[i] = hvx_vec_f32_to_f16_shuff(r0, r1); } if (nloe > 0) { HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * SIZEOF_FP16); HVX_Vector v1 = Q6_V_vand_QV(bmask, v_src[nvec]); - HVX_VectorPair p = hvx_vec_f16_to_f32(v1); + HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(v1); HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(p), scale_v)); HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(p), scale_v)); - HVX_Vector result = hvx_vec_f32_to_f16(r0, r1); + HVX_Vector result = hvx_vec_f32_to_f16_shuff(r0, r1); hvx_vec_store_a(&v_dst[nvec], nloe * SIZEOF_FP16, result); } } +static __attribute__((noinline, unused)) void hvx_rms_norm_mul_f16_w32_ne128_bcast_rows( + const uint8_t * restrict src, + const uint8_t * restrict weight, + uint8_t * restrict dst, + uint32_t num_rows, + size_t src_stride, + size_t dst_stride, + float epsilon, + float scale) { + const HVX_Vector * restrict v_w = (const HVX_Vector *) weight; + const HVX_VectorPair wp0 = Q6_W_vdeal_VVR(v_w[1], v_w[0], -4); + const HVX_VectorPair wp1 = Q6_W_vdeal_VVR(v_w[3], v_w[2], -4); + const HVX_Vector w0 = Q6_V_lo_W(wp0); + const HVX_Vector w1 = Q6_V_hi_W(wp0); + const HVX_Vector w2 = Q6_V_lo_W(wp1); + const HVX_Vector w3 = Q6_V_hi_W(wp1); + + const HVX_Vector v_one_f16 = Q6_Vh_vsplat_R(0x3c00); + const HVX_Vector denom_v = hvx_vec_splat_f32(1.0f / 128.0f); + const HVX_Vector epsilon_v = hvx_vec_splat_f32(epsilon); + const HVX_Vector scale_opt = hvx_vec_splat_f32(scale); + const bool has_scale = (scale != 0.0f); + + #pragma nounroll + for (uint32_t ir = 0; ir < num_rows; ++ir) { + const HVX_Vector * restrict v_src = (const HVX_Vector *) (src + ir * src_stride); + HVX_Vector * restrict v_dst = (HVX_Vector *) (dst + ir * dst_stride); + + const HVX_Vector s0_hf = v_src[0]; + const HVX_Vector s1_hf = v_src[1]; + const HVX_VectorPair p0 = hvx_vec_mpy_f32_f16(s0_hf, v_one_f16); + const HVX_VectorPair p1 = hvx_vec_mpy_f32_f16(s1_hf, v_one_f16); + const HVX_Vector x0 = Q6_V_lo_W(p0); + const HVX_Vector x1 = Q6_V_hi_W(p0); + const HVX_Vector x2 = Q6_V_lo_W(p1); + const HVX_Vector x3 = Q6_V_hi_W(p1); + +#if __HVX_ARCH__ >= 79 + HVX_VectorPair sum_p = Q6_Wsf_vmpy_VhfVhf(s0_hf, s0_hf); + sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, s1_hf, s1_hf); + HVX_Vector sum_v = hvx_vec_reduce_sum_f32(Q6_Vsf_vadd_VsfVsf(Q6_V_lo_W(sum_p), Q6_V_hi_W(sum_p))); +#else + HVX_Vector sum01 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x0, x0), Q6_Vqf32_vmpy_VsfVsf(x1, x1)); + HVX_Vector sum23 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x2, x2), Q6_Vqf32_vmpy_VsfVsf(x3, x3)); + HVX_Vector sum_v = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(sum01, sum23))); +#endif + + HVX_Vector mean_eps = Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(sum_v, denom_v), epsilon_v); + HVX_Vector scale_v = hvx_vec_rsqrt_f32(Q6_Vsf_equals_Vqf32(mean_eps)); + if (has_scale) { + scale_v = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(scale_v, scale_opt)); + } + + HVX_Vector s0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x0, scale_v)); + HVX_Vector s1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x1, scale_v)); + HVX_Vector s2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x2, scale_v)); + HVX_Vector s3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x3, scale_v)); + + HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s0, w0)); + HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s1, w1)); + HVX_Vector r2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s2, w2)); + HVX_Vector r3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s3, w3)); + + v_dst[0] = hvx_vec_f32_to_f16_shuff(r0, r1); + v_dst[1] = hvx_vec_f32_to_f16_shuff(r2, r3); + } +} + +static __attribute__((noinline, unused)) void hvx_rms_norm_mul_f16_w32_ne256_bcast_rows( + const uint8_t * restrict src, + const uint8_t * restrict weight, + uint8_t * restrict dst, + uint32_t num_rows, + size_t src_stride, + size_t dst_stride, + float epsilon, + float scale) { + const HVX_Vector * restrict v_w = (const HVX_Vector *) weight; + const HVX_VectorPair wp0 = Q6_W_vdeal_VVR(v_w[1], v_w[0], -4); + const HVX_VectorPair wp1 = Q6_W_vdeal_VVR(v_w[3], v_w[2], -4); + const HVX_VectorPair wp2 = Q6_W_vdeal_VVR(v_w[5], v_w[4], -4); + const HVX_VectorPair wp3 = Q6_W_vdeal_VVR(v_w[7], v_w[6], -4); + const HVX_Vector w0 = Q6_V_lo_W(wp0); + const HVX_Vector w1 = Q6_V_hi_W(wp0); + const HVX_Vector w2 = Q6_V_lo_W(wp1); + const HVX_Vector w3 = Q6_V_hi_W(wp1); + const HVX_Vector w4 = Q6_V_lo_W(wp2); + const HVX_Vector w5 = Q6_V_hi_W(wp2); + const HVX_Vector w6 = Q6_V_lo_W(wp3); + const HVX_Vector w7 = Q6_V_hi_W(wp3); + + const HVX_Vector v_one_f16 = Q6_Vh_vsplat_R(0x3c00); + const HVX_Vector denom_v = hvx_vec_splat_f32(1.0f / 256.0f); + const HVX_Vector epsilon_v = hvx_vec_splat_f32(epsilon); + const HVX_Vector scale_opt = hvx_vec_splat_f32(scale); + const bool has_scale = (scale != 0.0f); + + #pragma nounroll + for (uint32_t ir = 0; ir < num_rows; ++ir) { + const HVX_Vector * restrict v_src = (const HVX_Vector *) (src + ir * src_stride); + HVX_Vector * restrict v_dst = (HVX_Vector *) (dst + ir * dst_stride); + + const HVX_Vector s0_hf = v_src[0]; + const HVX_Vector s1_hf = v_src[1]; + const HVX_Vector s2_hf = v_src[2]; + const HVX_Vector s3_hf = v_src[3]; + const HVX_VectorPair p0 = hvx_vec_mpy_f32_f16(s0_hf, v_one_f16); + const HVX_VectorPair p1 = hvx_vec_mpy_f32_f16(s1_hf, v_one_f16); + const HVX_VectorPair p2 = hvx_vec_mpy_f32_f16(s2_hf, v_one_f16); + const HVX_VectorPair p3 = hvx_vec_mpy_f32_f16(s3_hf, v_one_f16); + + const HVX_Vector x0 = Q6_V_lo_W(p0); + const HVX_Vector x1 = Q6_V_hi_W(p0); + const HVX_Vector x2 = Q6_V_lo_W(p1); + const HVX_Vector x3 = Q6_V_hi_W(p1); + const HVX_Vector x4 = Q6_V_lo_W(p2); + const HVX_Vector x5 = Q6_V_hi_W(p2); + const HVX_Vector x6 = Q6_V_lo_W(p3); + const HVX_Vector x7 = Q6_V_hi_W(p3); + +#if __HVX_ARCH__ >= 79 + HVX_VectorPair sum_p = Q6_Wsf_vmpy_VhfVhf(s0_hf, s0_hf); + sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, s1_hf, s1_hf); + sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, s2_hf, s2_hf); + sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, s3_hf, s3_hf); + HVX_Vector sum_v = hvx_vec_reduce_sum_f32(Q6_Vsf_vadd_VsfVsf(Q6_V_lo_W(sum_p), Q6_V_hi_W(sum_p))); +#else + HVX_Vector s01 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x0, x0), Q6_Vqf32_vmpy_VsfVsf(x1, x1)); + HVX_Vector s23 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x2, x2), Q6_Vqf32_vmpy_VsfVsf(x3, x3)); + HVX_Vector s45 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x4, x4), Q6_Vqf32_vmpy_VsfVsf(x5, x5)); + HVX_Vector s67 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x6, x6), Q6_Vqf32_vmpy_VsfVsf(x7, x7)); + HVX_Vector sum_qf = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(s01, s23), + Q6_Vqf32_vadd_Vqf32Vqf32(s45, s67)); + HVX_Vector sum_v = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_qf)); +#endif + + HVX_Vector mean_eps = Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(sum_v, denom_v), epsilon_v); + HVX_Vector scale_v = hvx_vec_rsqrt_f32(Q6_Vsf_equals_Vqf32(mean_eps)); + if (has_scale) { + scale_v = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(scale_v, scale_opt)); + } + + HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x0, scale_v)), w0)); + HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x1, scale_v)), w1)); + HVX_Vector r2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x2, scale_v)), w2)); + HVX_Vector r3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x3, scale_v)), w3)); + HVX_Vector r4 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x4, scale_v)), w4)); + HVX_Vector r5 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x5, scale_v)), w5)); + HVX_Vector r6 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x6, scale_v)), w6)); + HVX_Vector r7 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x7, scale_v)), w7)); + + v_dst[0] = hvx_vec_f32_to_f16_shuff(r0, r1); + v_dst[1] = hvx_vec_f32_to_f16_shuff(r2, r3); + v_dst[2] = hvx_vec_f32_to_f16_shuff(r4, r5); + v_dst[3] = hvx_vec_f32_to_f16_shuff(r6, r7); + } +} + #endif // HVX_NORM_H diff --git a/ggml/src/ggml-hexagon/htp/hvx-quant.h b/ggml/src/ggml-hexagon/htp/hvx-quant.h index b0ca6ecf6ac8..358ece4e86a0 100644 --- a/ggml/src/ggml-hexagon/htp/hvx-quant.h +++ b/ggml/src/ggml-hexagon/htp/hvx-quant.h @@ -16,12 +16,28 @@ #define GGML_COMMON_DECL_C #endif #include "ggml-common.h" -#include "ggml-impl.h" + +static inline float hvx_fp16_to_fp32(uint16_t h) { + __fp16 f; + memcpy(&f, &h, sizeof(f)); + return (float) f; +} + +static inline HVX_Vector hvx_vec_reduce_max_32_f16(HVX_Vector v) { + v = Q6_Vhf_vmax_VhfVhf(v, Q6_V_vror_VR(v, 32)); + v = Q6_Vhf_vmax_VhfVhf(v, Q6_V_vror_VR(v, 16)); + v = Q6_Vhf_vmax_VhfVhf(v, Q6_V_vror_VR(v, 8)); + v = Q6_Vhf_vmax_VhfVhf(v, Q6_V_vror_VR(v, 4)); + v = Q6_Vhf_vmax_VhfVhf(v, Q6_V_vror_VR(v, 2)); + HVX_Vector pair = Q6_V_vmux_QVV(Q6_Q_vsetq_R(2), v, Q6_V_vror_VR(v, 62)); + return hvx_vec_repl_2x_f16(pair); +} static inline void hvx_quantize_row_q8_0_f32(void * restrict dst_ptr, const float * restrict src_ptr, int n) { const int nb = n / QK8_0; block_q8_0 * dst = (block_q8_0 *) dst_ptr; - HVX_Vector zero = Q6_V_vzero(); + const HVX_Vector inv127_hf = Q6_Vh_vsplat_R(0x2008); // 1.0 / 127.0 + const HVX_Vector zero = Q6_V_vzero(); int i = 0; for (; i + 3 < nb; i += 4) { @@ -32,31 +48,78 @@ static inline void hvx_quantize_row_q8_0_f32(void * restrict dst_ptr, const floa HVX_Vector vmax2_sf = hvx_vec_reduce_max_f32(hvx_vec_abs_f32(vx[2])); HVX_Vector vmax3_sf = hvx_vec_reduce_max_f32(hvx_vec_abs_f32(vx[3])); - HVX_Vector vx0_qf = Q6_Vqf32_vsub_VsfVsf(vx[0], zero); - HVX_Vector vx1_qf = Q6_Vqf32_vsub_VsfVsf(vx[1], zero); - HVX_Vector vx2_qf = Q6_Vqf32_vsub_VsfVsf(vx[2], zero); - HVX_Vector vx3_qf = Q6_Vqf32_vsub_VsfVsf(vx[3], zero); + HVX_Vector vmax01_hf = hvx_vec_f32_to_f16(vmax0_sf, vmax1_sf); + HVX_Vector vmax23_hf = hvx_vec_f32_to_f16(vmax2_sf, vmax3_sf); + + HVX_Vector vx01_hf = hvx_vec_f32_to_f16(vx[0], vx[1]); + HVX_Vector vx23_hf = hvx_vec_f32_to_f16(vx[2], vx[3]); + + HVX_Vector vd01_hf = hvx_vec_mul_f16_f16(vmax01_hf, inv127_hf); + HVX_Vector vd23_hf = hvx_vec_mul_f16_f16(vmax23_hf, inv127_hf); + + HVX_Vector vd01_inv_hf = hvx_vec_inverse_f16(vd01_hf); + HVX_Vector vd23_inv_hf = hvx_vec_inverse_f16(vd23_hf); + vx01_hf = hvx_vec_mul_f16_f16(vx01_hf, vd01_inv_hf); + vx23_hf = hvx_vec_mul_f16_f16(vx23_hf, vd23_inv_hf); + + HVX_Vector vx01_i16 = hvx_vec_i16_from_hf_rnd_sat(vx01_hf); + HVX_Vector vx23_i16 = hvx_vec_i16_from_hf_rnd_sat(vx23_hf); + HVX_Vector vx_i8 = Q6_Vb_vpack_VhVh_sat(vx23_i16, vx01_i16); + + hvx_vec_store_u(&dst[i + 0].d, 2, vd01_hf); + hvx_vec_store_u(dst[i + 0].qs, 32, vx_i8); + + hvx_vec_store_u(&dst[i + 1].d, 2, Q6_V_vror_VR(vd01_hf, 64)); + hvx_vec_store_u(dst[i + 1].qs, 32, Q6_V_vror_VR(vx_i8, 32)); + + hvx_vec_store_u(&dst[i + 2].d, 2, vd23_hf); + hvx_vec_store_u(dst[i + 2].qs, 32, Q6_V_vror_VR(vx_i8, 64)); + + hvx_vec_store_u(&dst[i + 3].d, 2, Q6_V_vror_VR(vd23_hf, 64)); + hvx_vec_store_u(dst[i + 3].qs, 32, Q6_V_vror_VR(vx_i8, 96)); + } + + for (; i < nb; i++) { + const float * block_src = src_ptr + i * QK8_0; + HVX_Vector vx = *(const HVX_UVector *) block_src; + HVX_Vector vmax_sf = hvx_vec_reduce_max_f32(hvx_vec_abs_f32(vx)); + + HVX_Vector vmax_hf = hvx_vec_f32_to_f16(vmax_sf, zero); + HVX_Vector vx_hf = hvx_vec_f32_to_f16(vx, zero); + + HVX_Vector vd_hf = hvx_vec_mul_f16_f16(vmax_hf, inv127_hf); + HVX_Vector vd_inv_hf = hvx_vec_inverse_f16(vd_hf); + vx_hf = hvx_vec_mul_f16_f16(vx_hf, vd_inv_hf); + + HVX_Vector v_i16 = hvx_vec_i16_from_hf_rnd_sat(vx_hf); + HVX_Vector v_i8 = Q6_Vb_vpack_VhVh_sat(zero, v_i16); + + hvx_vec_store_u(&dst[i].d, 2, vd_hf); + hvx_vec_store_u(dst[i].qs, 32, v_i8); + } +} - HVX_Vector vmax0_qf = Q6_Vqf32_vsub_VsfVsf(vmax0_sf, zero); - HVX_Vector vmax1_qf = Q6_Vqf32_vsub_VsfVsf(vmax1_sf, zero); - HVX_Vector vmax2_qf = Q6_Vqf32_vsub_VsfVsf(vmax2_sf, zero); - HVX_Vector vmax3_qf = Q6_Vqf32_vsub_VsfVsf(vmax3_sf, zero); +static inline void hvx_quantize_row_q8_0_f16(void * restrict dst_ptr, const __fp16 * restrict src_ptr, int n) { + const int nb = n / QK8_0; + block_q8_0 * dst = (block_q8_0 *) dst_ptr; + const HVX_Vector inv127_hf = Q6_Vh_vsplat_R(0x2008); // 1.0 / 127.0 - HVX_Vector vmax01_hf = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(vmax1_qf, vmax0_qf))); - HVX_Vector vmax23_hf = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(vmax3_qf, vmax2_qf))); + int i = 0; + for (; i + 3 < nb; i += 4) { + const HVX_UVector * vsrc = (const HVX_UVector *) (src_ptr + i * QK8_0); + HVX_Vector vx01_hf = vsrc[0]; + HVX_Vector vx23_hf = vsrc[1]; - HVX_Vector vx01_hf = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(vx1_qf, vx0_qf))); - HVX_Vector vx23_hf = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(vx3_qf, vx2_qf))); + HVX_Vector vmax01_hf = hvx_vec_reduce_max_32_f16(hvx_vec_abs_f16(vx01_hf)); + HVX_Vector vmax23_hf = hvx_vec_reduce_max_32_f16(hvx_vec_abs_f16(vx23_hf)); - HVX_Vector vd01_qf16 = Q6_Vqf16_vmpy_VhfVhf(vmax01_hf, Q6_Vh_vsplat_R(0x2008)); // 1.0 / 127.0 - HVX_Vector vd23_qf16 = Q6_Vqf16_vmpy_VhfVhf(vmax23_hf, Q6_Vh_vsplat_R(0x2008)); // 1.0 / 127.0 - HVX_Vector vd01_hf = Q6_Vhf_equals_Vqf16(vd01_qf16); - HVX_Vector vd23_hf = Q6_Vhf_equals_Vqf16(vd23_qf16); + HVX_Vector vd01_hf = hvx_vec_mul_f16_f16(vmax01_hf, inv127_hf); + HVX_Vector vd23_hf = hvx_vec_mul_f16_f16(vmax23_hf, inv127_hf); HVX_Vector vd01_inv_hf = hvx_vec_inverse_f16(vd01_hf); HVX_Vector vd23_inv_hf = hvx_vec_inverse_f16(vd23_hf); - vx01_hf = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(vx01_hf, vd01_inv_hf)); - vx23_hf = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(vx23_hf, vd23_inv_hf)); + vx01_hf = hvx_vec_mul_f16_f16(vx01_hf, vd01_inv_hf); + vx23_hf = hvx_vec_mul_f16_f16(vx23_hf, vd23_inv_hf); HVX_Vector vx01_i16 = hvx_vec_i16_from_hf_rnd_sat(vx01_hf); HVX_Vector vx23_i16 = hvx_vec_i16_from_hf_rnd_sat(vx23_hf); @@ -75,24 +138,20 @@ static inline void hvx_quantize_row_q8_0_f32(void * restrict dst_ptr, const floa hvx_vec_store_u(dst[i + 3].qs, 32, Q6_V_vror_VR(vx_i8, 96)); } + const HVX_Vector zero = Q6_V_vzero(); for (; i < nb; i++) { - const float * block_src = src_ptr + i * QK8_0; - HVX_Vector vx = *(const HVX_UVector *) block_src; - HVX_Vector v_abs = hvx_vec_abs_f32(vx); - HVX_Vector v_max = hvx_vec_reduce_max_f32(v_abs); - float amax = hvx_vec_get_f32(v_max); - - const float d = amax / 127.0f; - const float id = d ? (1.0f / d) : 0.0f; - dst[i].d = GGML_FP32_TO_FP16(d); - - HVX_Vector vid = hvx_vec_splat_f32(id); - HVX_Vector v_scaled = hvx_vec_mul_f32_f32(vx, vid); - HVX_Vector v_scaled_qf = Q6_Vqf32_vsub_VsfVsf(v_scaled, zero); - HVX_Vector v_scaled_hf = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(zero, v_scaled_qf))); - HVX_Vector v_i16 = hvx_vec_i16_from_hf_rnd_sat(v_scaled_hf); + const __fp16 * block_src = src_ptr + i * QK8_0; + HVX_Vector vx_hf = *(const HVX_UVector *) block_src; + HVX_Vector vmax_hf = hvx_vec_reduce_max_32_f16(hvx_vec_abs_f16(vx_hf)); + + HVX_Vector vd_hf = hvx_vec_mul_f16_f16(vmax_hf, inv127_hf); + HVX_Vector vd_inv_hf = hvx_vec_inverse_f16(vd_hf); + vx_hf = hvx_vec_mul_f16_f16(vx_hf, vd_inv_hf); + + HVX_Vector v_i16 = hvx_vec_i16_from_hf_rnd_sat(vx_hf); HVX_Vector v_i8 = Q6_Vb_vpack_VhVh_sat(zero, v_i16); + hvx_vec_store_u(&dst[i].d, 2, vd_hf); hvx_vec_store_u(dst[i].qs, 32, v_i8); } } @@ -121,29 +180,99 @@ static inline void hvx_dequantize_row_flat_q8_0_f32(float * restrict dst_ptr, co } } -static inline void hvx_dequantize_row_flat_q8_0_f16(__fp16 * restrict dst_ptr, const void * restrict src_ptr, uint32_t n) { - const int nb = n / QK8_0; - const block_q8_0 * src = (const block_q8_0 *) src_ptr; +static inline HVX_VectorPair hvx_dequant_q8_0_x4_f16(HVX_Vector v0, HVX_Vector v1, + HVX_VectorPred q32, HVX_VectorPred q64, HVX_VectorPred q96) { + HVX_Vector qs = Q6_V_vmux_QVV(q96, Q6_V_valign_VVR(v1, v0, 6), Q6_V_valign_VVR(v1, v0, 8)); + qs = Q6_V_vmux_QVV(q64, Q6_V_valign_VVR(v1, v0, 4), qs); + qs = Q6_V_vmux_QVV(q32, Q6_V_valign_VVR(v1, v0, 2), qs); - for (int i = nb - 1; i >= 0; i--) { - HVX_Vector vd_f16 = Q6_Vh_vsplat_R(*(const int16_t *) &src[i].d); - HVX_VectorPair vp_f32 = hvx_vec_f16_to_f32(vd_f16); - HVX_Vector vd = Q6_V_lo_W(vp_f32); + const HVX_Vector s01 = Q6_V_vmux_QVV(q64, hvx_vec_repl_f16(v0), hvx_vec_repl_f16(Q6_V_valign_VVR(v1, v0, 34))); + const HVX_Vector s23 = Q6_V_vmux_QVV(q64, hvx_vec_repl_f16(Q6_V_valign_VVR(v1, v0, 68)), hvx_vec_repl_f16(Q6_V_valign_VVR(v1, v0, 102))); - HVX_Vector vq_i8 = *(const HVX_UVector *) src[i].qs; + const HVX_VectorPair qh = Q6_Wh_vunpack_Vb(qs); + const HVX_Vector res01 = hvx_vec_mul_f16_f16(Q6_Vhf_equals_Vh(Q6_V_lo_W(qh)), s01); + const HVX_Vector res23 = hvx_vec_mul_f16_f16(Q6_Vhf_equals_Vh(Q6_V_hi_W(qh)), s23); + return Q6_W_vcombine_VV(res23, res01); +} - HVX_VectorPair p16 = Q6_Wh_vunpack_Vb(vq_i8); - HVX_Vector v_i16 = Q6_V_lo_W(p16); - HVX_VectorPair p32 = Q6_Ww_vunpack_Vh(v_i16); - HVX_Vector v_i32 = Q6_V_lo_W(p32); +static __attribute__((noinline)) void hvx_dequantize_row_flat_q8_0_f16_u(__fp16 * dst_ptr, const void * src_ptr, int32_t nb) { + const uint8_t * src_base = (const uint8_t *) src_ptr; + const HVX_VectorPred q32 = Q6_Q_vsetq_R(32); + const HVX_VectorPred q64 = Q6_Q_vsetq_R(64); + const HVX_VectorPred q96 = Q6_Q_vsetq_R(96); + + const int32_t n_full = nb / 4; + const int32_t rem = nb & 3; + + if (rem > 0) { + const uint8_t * s = src_base + n_full * 4 * sizeof(block_q8_0); + __fp16 * d = dst_ptr + n_full * 4 * QK8_0; + const HVX_Vector v0 = *(const HVX_UVector *) s; + const HVX_VectorPair res = hvx_dequant_q8_0_x4_f16(v0, Q6_V_vzero(), q32, q64, q96); + if (rem == 3) { + hvx_vec_store_u(d + 64, 64, Q6_V_hi_W(res)); + hvx_vmemu(d + 0) = Q6_V_lo_W(res); + } else if (rem == 2) { + hvx_vmemu(d + 0) = Q6_V_lo_W(res); + } else { + hvx_vec_store_u(d + 0, 64, Q6_V_lo_W(res)); + } + } - HVX_Vector v_f32 = Q6_Vsf_equals_Vw(v_i32); - HVX_Vector res_f32 = hvx_vec_mul_f32_f32(v_f32, vd); + for (int32_t g = n_full - 1; g >= 0; --g) { + const uint8_t * s = src_base + g * 4 * sizeof(block_q8_0); + __fp16 * d = dst_ptr + g * 4 * QK8_0; + const HVX_Vector v0 = *(const HVX_UVector *) s; + const HVX_Vector v1 = *(const HVX_UVector *) (s + VLEN); + const HVX_VectorPair res = hvx_dequant_q8_0_x4_f16(v0, v1, q32, q64, q96); + hvx_vmemu(d + 64) = Q6_V_hi_W(res); + hvx_vmemu(d + 0) = Q6_V_lo_W(res); + } +} - HVX_Vector res_f16 = hvx_vec_f32_to_f16(res_f32, Q6_V_vzero()); +// Q8_0 row to f16 (supports in-place dst_ptr == src_ptr), 4 blocks (128 values) per step backwards. +static inline void hvx_dequantize_row_flat_q8_0_f16(__fp16 * dst_ptr, const void * src_ptr, uint32_t n) { + const int32_t nb = (int32_t) (n / QK8_0); + if (nb <= 0) { + return; + } + + if (!hex_is_aligned(dst_ptr, 128)) { + hvx_dequantize_row_flat_q8_0_f16_u(dst_ptr, src_ptr, nb); + return; + } - __fp16 * block_dst = dst_ptr + i * QK8_0; - hvx_vec_store_u(block_dst, QK8_0 * sizeof(__fp16), res_f16); + const uint8_t * src_base = (const uint8_t *) src_ptr; + const HVX_VectorPred q32 = Q6_Q_vsetq_R(32); + const HVX_VectorPred q64 = Q6_Q_vsetq_R(64); + const HVX_VectorPred q96 = Q6_Q_vsetq_R(96); + + const int32_t n_full = nb / 4; + const int32_t rem = nb & 3; + + if (rem > 0) { + const uint8_t * s = src_base + n_full * 4 * sizeof(block_q8_0); + __fp16 * d = dst_ptr + n_full * 4 * QK8_0; + const HVX_Vector v0 = *(const HVX_UVector *) s; + const HVX_VectorPair res = hvx_dequant_q8_0_x4_f16(v0, Q6_V_vzero(), q32, q64, q96); + if (rem == 3) { + Q6_vmem_QRIV(q64, (HVX_Vector *) (d + 64), Q6_V_hi_W(res)); + hvx_vmem(d + 0) = Q6_V_lo_W(res); + } else if (rem == 2) { + hvx_vmem(d + 0) = Q6_V_lo_W(res); + } else { + Q6_vmem_QRIV(q64, (HVX_Vector *) (d + 0), Q6_V_lo_W(res)); + } + } + + for (int32_t g = n_full - 1; g >= 0; --g) { + const uint8_t * s = src_base + g * 4 * sizeof(block_q8_0); + __fp16 * d = dst_ptr + g * 4 * QK8_0; + const HVX_Vector v0 = *(const HVX_UVector *) s; + const HVX_Vector v1 = *(const HVX_UVector *) (s + VLEN); + const HVX_VectorPair res = hvx_dequant_q8_0_x4_f16(v0, v1, q32, q64, q96); + hvx_vmem(d + 64) = Q6_V_hi_W(res); + hvx_vmem(d + 0) = Q6_V_lo_W(res); } } @@ -288,8 +417,8 @@ static inline void hvx_dequantize_row_flat_q4_k_f32(float * restrict dst_ptr, co const block_q4_K * src = (const block_q4_K *) src_ptr; for (int i = 0; i < nb; i++) { - const float d = GGML_FP16_TO_FP32(src[i].d); - const float min = GGML_FP16_TO_FP32(src[i].dmin); + const float d = hvx_fp16_to_fp32(src[i].d); + const float min = hvx_fp16_to_fp32(src[i].dmin); const uint8_t * sc = src[i].scales; float * y = dst_ptr + i * QK_K; @@ -343,8 +472,8 @@ static inline void hvx_dequantize_row_flat_q5_k_f32(float * restrict dst_ptr, co const block_q5_K * src = (const block_q5_K *) src_ptr; for (int i = 0; i < nb; i++) { - const float d = GGML_FP16_TO_FP32(src[i].d); - const float min = GGML_FP16_TO_FP32(src[i].dmin); + const float d = hvx_fp16_to_fp32(src[i].d); + const float min = hvx_fp16_to_fp32(src[i].dmin); const uint8_t * sc = src[i].scales; HVX_Vector v_qh = *(const HVX_UVector *) src[i].qh; @@ -410,7 +539,7 @@ static inline void hvx_dequantize_row_flat_q6_k_f32(float * restrict dst_ptr, co const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03); for (int i = 0; i < nb; i++) { - const float d = GGML_FP16_TO_FP32(src[i].d); + const float d = hvx_fp16_to_fp32(src[i].d); const uint8_t * restrict ql = src[i].ql; const uint8_t * restrict qh = src[i].qh; @@ -478,26 +607,17 @@ static inline void hvx_dequantize_row_flat_q6_k_f32(float * restrict dst_ptr, co } // bytes row, row + 32, row + 64 and row + 96 of v, to bytes 0..3 -static inline HVX_Vector hvx_dequantize_gather4(HVX_Vector v, uint32_t row) { - v = Q6_V_vror_VR(v, row); - HVX_Vector packed = Q6_V_vmux_QVV(Q6_Q_vsetq_R(1), v, Q6_V_vror_VR(v, 31)); - packed = Q6_V_vmux_QVV(Q6_Q_vsetq_R(2), packed, Q6_V_vror_VR(v, 62)); - return Q6_V_vmux_QVV(Q6_Q_vsetq_R(3), packed, Q6_V_vror_VR(v, 93)); -} - -static inline void hvx_dequantize_row_tiled_q8_0_f32(float * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) { - const HVX_VectorPred first2 = Q6_Q_vsetq_R(2); +static inline void hvx_dequantize_row_tiled_q8_0_f32(void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) { const HVX_VectorPred first4 = Q6_Q_vsetq_R(4); for (uint32_t k_tile = 0; k_tile < n_k_tiles; ++k_tile) { const uint8_t * tile = src_spad + k_tile * tile_stride; - float * dst = dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS; + float * dst = (float *) dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS; HVX_Vector vq = Q6_V_vzero(); for (int group = 7; group >= 0; --group) { - const HVX_Vector v = Q6_V_vror_VR(hvx_vmem(tile + group * VLEN), 2 * row); - const HVX_Vector packed = Q6_V_vmux_QVV(first2, v, Q6_V_vror_VR(v, 62)); - vq = Q6_V_vmux_QVV(first4, packed, Q6_V_vror_VR(vq, VLEN - 4)); + const HVX_Vector v = Q6_V_vror_VR(hvx_vmem(tile + group * VLEN), 4 * row); + vq = Q6_V_vmux_QVV(first4, v, Q6_V_vror_VR(vq, VLEN - 4)); } const HVX_Vector scales = hvx_vmem(tile + 1024); @@ -510,22 +630,24 @@ static inline void hvx_dequantize_row_tiled_q8_0_f32(float * dst_spad, const uin } } -static inline void hvx_dequantize_row_tiled_q4_0_f32(float * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) { - const HVX_VectorPred first4 = Q6_Q_vsetq_R(4); +static inline void hvx_dequantize_row_tiled_q4_0_f32(void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) { + const HVX_VectorPred first4 = Q6_Q_vsetq_R(4); + const HVX_Vector mask_0f = Q6_Vb_vsplat_R(0x0F); + const HVX_Vector i8 = Q6_Vb_vsplat_R(8); for (uint32_t k_tile = 0; k_tile < n_k_tiles; ++k_tile) { const uint8_t * tile = src_spad + k_tile * tile_stride; - float * dst = dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS; + float * dst = (float *) dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS; HVX_Vector vq = Q6_V_vzero(); - for (int group = 3; group >= 0; --group) { - vq = Q6_V_vmux_QVV(first4, hvx_dequantize_gather4(hvx_vmem(tile + group * VLEN), row), Q6_V_vror_VR(vq, VLEN - 4)); + for (int i = 3; i >= 0; --i) { + const HVX_Vector plane = Q6_V_vror_VR(hvx_vmem(tile + i * VLEN), 4 * row); + const HVX_Vector hi = Q6_Vub_vlsr_VubR(plane, 4); + const HVX_Vector lo = Q6_V_vand_VV(plane, mask_0f); + vq = Q6_V_vmux_QVV(first4, hi, Q6_V_vror_VR(vq, VLEN - 4)); + vq = Q6_V_vmux_QVV(first4, lo, Q6_V_vror_VR(vq, VLEN - 4)); } - - const HVX_Vector lo = Q6_V_vand_VV(vq, Q6_Vb_vsplat_R(0x0F)); - const HVX_Vector hi = Q6_Vub_vlsr_VubR(vq, 4); - vq = Q6_V_lo_W(Q6_W_vshuff_VVR(hi, lo, -1)); - vq = Q6_Vb_vsub_VbVb(vq, Q6_Vb_vsplat_R(8)); + vq = Q6_Vb_vsub_VbVb(vq, i8); const HVX_Vector scales = hvx_vmem(tile + 512); const HVX_Vector scale_hf = hvx_vec_repl_f16(Q6_V_vror_VR(scales, 2 * row)); @@ -537,22 +659,23 @@ static inline void hvx_dequantize_row_tiled_q4_0_f32(float * dst_spad, const uin } } -static inline void hvx_dequantize_row_tiled_q4_k_f32(float * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) { - const HVX_VectorPred first4 = Q6_Q_vsetq_R(4); +static inline void hvx_dequantize_row_tiled_q4_k_f32(void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) { + const HVX_VectorPred first4 = Q6_Q_vsetq_R(4); + const HVX_Vector mask_0f = Q6_Vb_vsplat_R(0x0F); for (uint32_t k_tile = 0; k_tile < n_k_tiles; ++k_tile) { const uint8_t * tile = src_spad + k_tile * tile_stride; - float * dst = dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS; + float * dst = (float *) dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS; HVX_Vector vq = Q6_V_vzero(); - for (int group = 3; group >= 0; --group) { - vq = Q6_V_vmux_QVV(first4, hvx_dequantize_gather4(hvx_vmem(tile + group * VLEN), row), Q6_V_vror_VR(vq, VLEN - 4)); + for (int i = 3; i >= 0; --i) { + const HVX_Vector plane = Q6_V_vror_VR(hvx_vmem(tile + i * VLEN), 4 * row); + const HVX_Vector hi = Q6_Vub_vlsr_VubR(plane, 4); + const HVX_Vector lo = Q6_V_vand_VV(plane, mask_0f); + vq = Q6_V_vmux_QVV(first4, hi, Q6_V_vror_VR(vq, VLEN - 4)); + vq = Q6_V_vmux_QVV(first4, lo, Q6_V_vror_VR(vq, VLEN - 4)); } - const HVX_Vector lo = Q6_V_vand_VV(vq, Q6_Vb_vsplat_R(0x0F)); - const HVX_Vector hi = Q6_Vub_vlsr_VubR(vq, 4); - vq = Q6_V_lo_W(Q6_W_vshuff_VVR(hi, lo, -1)); - const HVX_Vector scales = hvx_vmem(tile + 512); const HVX_Vector scale_hf = hvx_vec_repl_f16(Q6_V_vror_VR(scales, 4 * row)); const HVX_Vector scale = Q6_V_lo_W(hvx_vec_f16_to_f32(scale_hf)); @@ -566,26 +689,24 @@ static inline void hvx_dequantize_row_tiled_q4_k_f32(float * dst_spad, const uin } } -static inline void hvx_dequantize_row_tiled_q5_k_f32(float * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) { - const HVX_VectorPred first4 = Q6_Q_vsetq_R(4); - const HVX_Vector one = Q6_Vb_vsplat_R(1); +static inline void hvx_dequantize_row_tiled_q5_k_f32(void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) { + const HVX_VectorPred first4 = Q6_Q_vsetq_R(4); + const HVX_Vector mask_0f = Q6_Vb_vsplat_R(0x0F); for (uint32_t k_tile = 0; k_tile < n_k_tiles; ++k_tile) { const uint8_t * tile = src_spad + k_tile * tile_stride; - float * dst = dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS; + float * dst = (float *) dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS; - const HVX_Vector p5 = hvx_dequantize_gather4(hvx_vmem(tile + 640), row); + const HVX_Vector p5 = Q6_V_vror_VR(hvx_vmem(tile + 640), 4 * row); HVX_Vector vq = Q6_V_vzero(); - HVX_Vector vh = Q6_V_vzero(); - for (int group = 3; group >= 0; --group) { - vq = Q6_V_vmux_QVV(first4, hvx_dequantize_gather4(hvx_vmem(tile + group * VLEN), row), Q6_V_vror_VR(vq, VLEN - 4)); - vh = Q6_V_vmux_QVV(first4, Q6_Vub_vlsr_VubR(p5, 2 * group), Q6_V_vror_VR(vh, VLEN - 4)); + for (int i = 3; i >= 0; --i) { + const HVX_Vector plane = Q6_V_vror_VR(hvx_vmem(tile + i * VLEN), 4 * row); + const HVX_Vector hi = Q6_V_vandor_VQR(Q6_Vub_vlsr_VubR(plane, 4), Q6_Q_vand_VR(p5, 0x01010101u << (2 * i + 1)), 0x10101010); + const HVX_Vector lo = Q6_V_vandor_VQR(Q6_V_vand_VV(plane, mask_0f), Q6_Q_vand_VR(p5, 0x01010101u << (2 * i + 0)), 0x10101010); + vq = Q6_V_vmux_QVV(first4, hi, Q6_V_vror_VR(vq, VLEN - 4)); + vq = Q6_V_vmux_QVV(first4, lo, Q6_V_vror_VR(vq, VLEN - 4)); } - const HVX_Vector lo = Q6_V_vor_VV(Q6_V_vand_VV(vq, Q6_Vb_vsplat_R(0x0F)), Q6_Vw_vasl_VwR(Q6_V_vand_VV(vh, one), 4)); - const HVX_Vector hi = Q6_V_vor_VV(Q6_Vub_vlsr_VubR(vq, 4), Q6_Vw_vasl_VwR(Q6_V_vand_VV(Q6_Vub_vlsr_VubR(vh, 1), one), 4)); - vq = Q6_V_lo_W(Q6_W_vshuff_VVR(hi, lo, -1)); - const HVX_Vector scales = hvx_vmem(tile + 512); const HVX_Vector scale_hf = hvx_vec_repl_f16(Q6_V_vror_VR(scales, 4 * row)); const HVX_Vector scale = Q6_V_lo_W(hvx_vec_f16_to_f32(scale_hf)); @@ -599,7 +720,7 @@ static inline void hvx_dequantize_row_tiled_q5_k_f32(float * dst_spad, const uin } } -static inline void hvx_dequantize_row_tiled_q6_k_f32(float * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) { +static inline void hvx_dequantize_row_tiled_q6_k_f32(void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) { const HVX_VectorPred first4 = Q6_Q_vsetq_R(4); const HVX_VectorPred first16 = Q6_Q_vsetq_R(16 * sizeof(float)); const HVX_Vector mask_0f = Q6_Vb_vsplat_R(0x0F); @@ -607,7 +728,7 @@ static inline void hvx_dequantize_row_tiled_q6_k_f32(float * dst_spad, const uin for (uint32_t k_tile = 0; k_tile < n_k_tiles; ++k_tile) { const uint8_t * tile = src_spad + k_tile * tile_stride; - float * dst = dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS; + float * dst = (float *) dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS; HVX_Vector vq = Q6_V_vzero(); for (int group = 7; group >= 0; --group) { @@ -641,27 +762,53 @@ static inline HVX_Vector hvx_dequantize_tiled_f16_gather4(const uint8_t * p, uin return Q6_V_lo_W(Q6_W_vshuff_VVR(w23, w01, 8)); } -static inline void hvx_dequantize_row_tiled_f16_f32(float * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) { +static inline HVX_Vector hvx_gather_tiled_f16_row_k(const uint8_t * tile, uint32_t r_byte) { + HVX_Vector g0 = hvx_dequantize_tiled_f16_gather4(tile + 0 * VLEN, r_byte); + HVX_Vector g1 = hvx_dequantize_tiled_f16_gather4(tile + 4 * VLEN, r_byte); + HVX_Vector g01 = Q6_V_lo_W(Q6_W_vshuff_VVR(g1, g0, 16)); + asm volatile("" : "+v"(g01)); + + HVX_Vector g2 = hvx_dequantize_tiled_f16_gather4(tile + 8 * VLEN, r_byte); + HVX_Vector g3 = hvx_dequantize_tiled_f16_gather4(tile + 12 * VLEN, r_byte); + HVX_Vector g23 = Q6_V_lo_W(Q6_W_vshuff_VVR(g3, g2, 16)); + + return Q6_V_lo_W(Q6_W_vshuff_VVR(g23, g01, 32)); +} + +static inline void hvx_dequantize_row_tiled_f16_f32(void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) { const uint32_t r_byte = 4 * row; for (uint32_t k_tile = 0; k_tile < n_k_tiles; ++k_tile) { const uint8_t * tile = src_spad + k_tile * tile_stride; - float * dst = dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS; + float * dst = (float *) dst_spad + k_tile * HTP_TENSOR_TILE_N_COLS; - HVX_Vector g0 = hvx_dequantize_tiled_f16_gather4(tile + 0 * VLEN, r_byte); - HVX_Vector g1 = hvx_dequantize_tiled_f16_gather4(tile + 4 * VLEN, r_byte); - HVX_Vector g01 = Q6_V_lo_W(Q6_W_vshuff_VVR(g1, g0, 16)); + HVX_Vector g = hvx_gather_tiled_f16_row_k(tile, r_byte); + *(HVX_Vector *) dst = Q6_V_lo_W(hvx_vec_f16_to_f32(g)); + } +} - HVX_Vector g2 = hvx_dequantize_tiled_f16_gather4(tile + 8 * VLEN, r_byte); - HVX_Vector g3 = hvx_dequantize_tiled_f16_gather4(tile + 12 * VLEN, r_byte); - HVX_Vector g23 = Q6_V_lo_W(Q6_W_vshuff_VVR(g3, g2, 16)); +static inline void hvx_dequantize_row_tiled_f16_f16(void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) { + HVX_Vector * vdst = (HVX_Vector *) dst_spad; + const uint32_t r_byte = 4 * row; + const uint32_t n_pairs = n_k_tiles / 2; + + for (uint32_t pair = 0; pair < n_pairs; ++pair) { + const uint8_t * tile0 = src_spad + (2 * pair + 0) * tile_stride; + const uint8_t * tile1 = src_spad + (2 * pair + 1) * tile_stride; + HVX_Vector g0 = hvx_gather_tiled_f16_row_k(tile0, r_byte); + asm volatile("" : "+v"(g0)); + HVX_Vector g1 = hvx_gather_tiled_f16_row_k(tile1, r_byte); + vdst[pair] = Q6_V_lo_W(Q6_W_vshuff_VVR(g1, g0, 64)); + } - HVX_Vector g = Q6_V_lo_W(Q6_W_vshuff_VVR(g23, g01, 32)); - *(HVX_Vector *) dst = Q6_V_lo_W(hvx_vec_f16_to_f32(g)); + if (n_k_tiles & 1) { + const uint8_t * tile = src_spad + (2 * n_pairs) * tile_stride; + HVX_Vector g = hvx_gather_tiled_f16_row_k(tile, r_byte); + hvx_vec_store_a(&vdst[n_pairs], HTP_TENSOR_TILE_N_COLS * sizeof(__fp16), g); } } -static inline void hvx_dequantize_row_tiled_q1_0_f32(float * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) { +static inline void hvx_dequantize_row_tiled_q1_0_f32(void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) { static const uint32_t __attribute__((aligned(128))) bit_mask[32] = { 1u << 0, 1u << 8, 1u << 16, 1u << 24, 1u << 1, 1u << 9, 1u << 17, 1u << 25, @@ -678,7 +825,7 @@ static inline void hvx_dequantize_row_tiled_q1_0_f32(float * dst_spad, const uin for (uint32_t k_tile = 0; k_tile < n_k_tiles; ++k_tile) { const uint8_t * tile = src_spad + k_tile * tile_stride; - float * dst = dst_spad + k_tile * HTP_TENSOR_TILE_K_Q1_0; + float * dst = (float *) dst_spad + k_tile * HTP_TENSOR_TILE_K_Q1_0; const HVX_Vector scales = hvx_vmem(tile + 512); const HVX_Vector scale_hf = hvx_vec_repl_f16(Q6_V_vror_VR(scales, 2 * row)); @@ -694,13 +841,13 @@ static inline void hvx_dequantize_row_tiled_q1_0_f32(float * dst_spad, const uin } } -static inline void hvx_dequantize_row_tiled_q2_0_f32(float * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) { +static inline void hvx_dequantize_row_tiled_q2_0_f32(void * dst_spad, const uint8_t * src_spad, uint32_t n_k_tiles, uint32_t tile_stride, uint32_t row) { const HVX_Vector mask_03 = Q6_Vb_vsplat_R(0x03); const HVX_Vector v_one = Q6_Vb_vsplat_R(1); for (uint32_t k_tile = 0; k_tile < n_k_tiles; ++k_tile) { const uint8_t * tile = src_spad + k_tile * tile_stride; - float * dst = dst_spad + k_tile * HTP_TENSOR_TILE_K_Q2_0; + float * dst = (float *) dst_spad + k_tile * HTP_TENSOR_TILE_K_Q2_0; const HVX_Vector v_packed = hvx_dequantize_tiled_f16_gather4(tile, 4 * row); const HVX_Vector p0 = Q6_V_vand_VV(v_packed, mask_03); diff --git a/ggml/src/ggml-hexagon/htp/hvx-sigmoid.h b/ggml/src/ggml-hexagon/htp/hvx-sigmoid.h index 3f253a0b0325..c34583d7c1c5 100644 --- a/ggml/src/ggml-hexagon/htp/hvx-sigmoid.h +++ b/ggml/src/ggml-hexagon/htp/hvx-sigmoid.h @@ -52,6 +52,85 @@ static inline HVX_Vector hvx_vec_fast_sigmoid_f32_guard(HVX_Vector v, return Q6_V_vmux_QVV(pred_min, out, Q6_V_vzero()); } +static inline HVX_VectorPair hvx_vec_fast_sigmoid_f32_guard_pair(HVX_Vector x0, + HVX_Vector x1, + HVX_Vector one, + HVX_Vector max_exp, + HVX_Vector min_exp) { + const HVX_Vector c_log2f = Q6_V_vsplat_R(FAST_SIGMOID_LOG2F); + const HVX_Vector c1 = Q6_V_vsplat_R(FAST_SIGMOID_C1); + const HVX_Vector c2 = Q6_V_vsplat_R(FAST_SIGMOID_C2); + const HVX_Vector c3 = Q6_V_vsplat_R(FAST_SIGMOID_C3); + const HVX_Vector inv_aprox = Q6_V_vsplat_R(0x7EEEEBB3); + const HVX_Vector two_sf = hvx_vec_splat_f32(2.0f); + const HVX_Vector zero = Q6_V_vzero(); + + HVX_Vector v0 = Q6_Vqf32_vmpy_VsfVsf(x0, c_log2f); + HVX_Vector v1 = Q6_Vqf32_vmpy_VsfVsf(x1, c_log2f); + v0 = Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(v0), c3); + v1 = Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(v1), c3); + + HVX_Vector in_int0 = hvx_vec_truncate_f32(Q6_Vsf_equals_Vqf32(v0)); + HVX_Vector in_int1 = hvx_vec_truncate_f32(Q6_Vsf_equals_Vqf32(v1)); + HVX_Vector f0 = Q6_Vqf32_vsub_Vqf32Vsf(v0, Q6_Vsf_equals_Vw(in_int0)); + HVX_Vector f1 = Q6_Vqf32_vsub_Vqf32Vsf(v1, Q6_Vsf_equals_Vw(in_int1)); + HVX_Vector ff0 = Q6_Vqf32_vmpy_Vqf32Vqf32(f0, f0); + HVX_Vector ff1 = Q6_Vqf32_vmpy_Vqf32Vqf32(f1, f1); + + HVX_Vector p1_0 = Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(ff0), c2); + HVX_Vector p1_1 = Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(ff1), c2); + p1_0 = Q6_Vqf32_vadd_Vqf32Vsf(p1_0, c_log2f); + p1_1 = Q6_Vqf32_vadd_Vqf32Vsf(p1_1, c_log2f); + + HVX_Vector p2_0 = Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(f0), c1); + HVX_Vector p2_1 = Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(f1), c1); + p2_0 = Q6_Vqf32_vmpy_Vqf32Vqf32(p2_0, ff0); + p2_1 = Q6_Vqf32_vmpy_Vqf32Vqf32(p2_1, ff1); + p2_0 = Q6_Vqf32_vadd_Vqf32Vqf32(p2_0, f0); + p2_1 = Q6_Vqf32_vadd_Vqf32Vqf32(p2_1, f1); + + HVX_Vector v3_0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(p2_0, p1_0)); + HVX_Vector v3_1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(p2_1, p1_1)); + v3_0 = Q6_Vw_vaslacc_VwVwR(v3_0, in_int0, 24); + v3_1 = Q6_Vw_vaslacc_VwVwR(v3_1, in_int1, 24); + + HVX_Vector v4_0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vsub_Vqf32Vqf32(p2_0, p1_0)); + HVX_Vector v4_1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vsub_Vqf32Vqf32(p2_1, p1_1)); + HVX_Vector v5_0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vsub_VsfVsf(v3_0, v4_0)); + HVX_Vector v5_1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vsub_VsfVsf(v3_1, v4_1)); + + HVX_Vector i0 = Q6_Vw_vsub_VwVw(inv_aprox, v5_0); + HVX_Vector i1 = Q6_Vw_vsub_VwVw(inv_aprox, v5_1); + + HVX_Vector r0 = Q6_Vqf32_vmpy_VsfVsf( + i0, Q6_Vsf_equals_Vqf32(Q6_Vqf32_vsub_VsfVsf(two_sf, Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(i0, v5_0))))); + HVX_Vector r1 = Q6_Vqf32_vmpy_VsfVsf( + i1, Q6_Vsf_equals_Vqf32(Q6_Vqf32_vsub_VsfVsf(two_sf, Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(i1, v5_1))))); + + r0 = Q6_Vqf32_vmpy_Vqf32Vqf32( + r0, Q6_Vqf32_vsub_VsfVsf(two_sf, Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(r0), v5_0)))); + r1 = Q6_Vqf32_vmpy_Vqf32Vqf32( + r1, Q6_Vqf32_vsub_VsfVsf(two_sf, Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(r1), v5_1)))); + + r0 = Q6_Vqf32_vmpy_Vqf32Vqf32( + r0, Q6_Vqf32_vsub_VsfVsf(two_sf, Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(r0), v5_0)))); + r1 = Q6_Vqf32_vmpy_Vqf32Vqf32( + r1, Q6_Vqf32_vsub_VsfVsf(two_sf, Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(r1), v5_1)))); + + HVX_Vector out0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(v3_0, Q6_Vsf_equals_Vqf32(r0))); + HVX_Vector out1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(v3_1, Q6_Vsf_equals_Vqf32(r1))); + + const HVX_VectorPred pmax0 = Q6_Q_vcmp_gt_VsfVsf(max_exp, x0); + const HVX_VectorPred pmin0 = Q6_Q_vcmp_gt_VsfVsf(x0, min_exp); + const HVX_VectorPred pmax1 = Q6_Q_vcmp_gt_VsfVsf(max_exp, x1); + const HVX_VectorPred pmin1 = Q6_Q_vcmp_gt_VsfVsf(x1, min_exp); + + out0 = Q6_V_vmux_QVV(pmin0, Q6_V_vmux_QVV(pmax0, out0, one), zero); + out1 = Q6_V_vmux_QVV(pmin1, Q6_V_vmux_QVV(pmax1, out1, one), zero); + + return Q6_W_vcombine_VV(out1, out0); +} + static inline HVX_Vector hvx_vec_fast_sigmoid_f32_2it(HVX_Vector v) { v = Q6_Vqf32_vmpy_VsfVsf(v, Q6_V_vsplat_R(FAST_SIGMOID_LOG2F)); v = Q6_Vqf32_vmpy_VsfVsf(Q6_Vsf_equals_Vqf32(v), Q6_V_vsplat_R(FAST_SIGMOID_C3)); @@ -115,11 +194,15 @@ static inline HVX_Vector hvx_vec_tanh_f32(HVX_Vector x) { return Q6_Vsf_equals_Vqf32(res); } -static inline HVX_Vector hvx_vec_silu_f32(HVX_Vector x) { +static inline HVX_Vector hvx_vec_sigmoid_f32(HVX_Vector x) { HVX_Vector one = hvx_vec_splat_f32(1.0f); HVX_Vector max_exp = hvx_vec_splat_f32(87.f); HVX_Vector min_exp = hvx_vec_splat_f32(-87.f); - HVX_Vector sig = hvx_vec_fast_sigmoid_f32_guard(x, one, max_exp, min_exp); + return hvx_vec_fast_sigmoid_f32_guard(x, one, max_exp, min_exp); +} + +static inline HVX_Vector hvx_vec_silu_f32(HVX_Vector x) { + HVX_Vector sig = hvx_vec_sigmoid_f32(x); return Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(x, sig)); } @@ -195,33 +278,185 @@ static inline void hvx_tanh_f32_aa(uint8_t * restrict dst, const uint8_t * restr hvx_tanh_loop_body(HVX_Vector, HVX_Vector, hvx_vec_store_a); } +#if __HVX_ARCH__ >= 81 +// Centered degree-4 minimax polynomial for 1 / (1 + e) in t = e - 0.5 on [-0.5, 0.5] +#define HVX_SIGMOID_RECIP_C0 (0x3956) +#define HVX_SIGMOID_RECIP_C1 (0xB711) +#define HVX_SIGMOID_RECIP_C2 (0x34AF) +#define HVX_SIGMOID_RECIP_C3 (0xB365) +#define HVX_SIGMOID_RECIP_C4 (0x3113) + +static inline HVX_Vector hvx_vec_fast_sigmoid_f16(HVX_Vector x_v) { + const HVX_Vector a = Q6_V_vand_VV(x_v, Q6_Vh_vsplat_R(0x7FFF)); + const HVX_Vector z = Q6_Vuh_vmin_VuhVuh(a, Q6_Vh_vsplat_R(0x4C50)); // min(|x|, 17.25) so e underflows to exact 0 in fp16 + const HVX_Vector y = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(z, Q6_Vh_vsplat_R(0x65C5))); + const HVX_Vector t = Q6_Vh_equals_Vhf_rnd(y); + const HVX_Vector rho = Q6_V_vand_VV(t, Q6_Vh_vsplat_R(0x03FF)); + const HVX_Vector r15 = Q6_Vh_vasl_VhR(rho, 5); + HVX_Vector rp = Q6_Vh_vadd_VhVh(Q6_Vh_vmpy_VhRh_s1_rnd_sat(r15, HVX_EXP2_FIXED_G2_PAIR), Q6_Vh_vsplat_R(HVX_EXP2_FIXED_G1)); + rp = Q6_Vh_vadd_VhVh(Q6_Vh_vmpy_VhVh_s1_rnd_sat(rp, r15), Q6_Vh_vsplat_R(HVX_EXP2_FIXED_G0)); + const HVX_Vector b = Q6_Vh_vadd_VhVh(Q6_Vh_vsub_VhVh(Q6_Vh_vsplat_R(0x6400), t), Q6_Vh_vmpy_VhVh_s1_rnd_sat(rp, rho)); + const HVX_Vector e = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(b, Q6_Vh_vsplat_R(0x1400))); + const HVX_Vector tc = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_VhfVhf(e, Q6_Vh_vsplat_R(0xB800))); + + HVX_Vector p = Q6_Vqf16_vmpy_VhfVhf(tc, Q6_Vh_vsplat_R(HVX_SIGMOID_RECIP_C4)); + p = Q6_Vqf16_vadd_Vqf16Vhf(p, Q6_Vh_vsplat_R(HVX_SIGMOID_RECIP_C3)); + p = Q6_Vqf16_vmpy_Vqf16Vhf(p, tc); + p = Q6_Vqf16_vadd_Vqf16Vhf(p, Q6_Vh_vsplat_R(HVX_SIGMOID_RECIP_C2)); + p = Q6_Vqf16_vmpy_Vqf16Vhf(p, tc); + p = Q6_Vqf16_vadd_Vqf16Vhf(p, Q6_Vh_vsplat_R(HVX_SIGMOID_RECIP_C1)); + p = Q6_Vqf16_vmpy_Vqf16Vhf(p, tc); + const HVX_Vector r_q = Q6_Vqf16_vadd_Vqf16Vhf(p, Q6_Vh_vsplat_R(HVX_SIGMOID_RECIP_C0)); + + const HVX_Vector r = Q6_Vhf_equals_Vqf16(r_q); + const HVX_Vector er = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_Vqf16Vhf(r_q, e)); + const HVX_VectorPred is_neg = Q6_Q_vcmp_gt_VhVh(Q6_V_vzero(), x_v); + return Q6_V_vmux_QVV(is_neg, er, r); +} + +static inline HVX_VectorPair hvx_vec_fast_sigmoid_f16_pair(HVX_Vector x0, HVX_Vector x1) { + const HVX_Vector em_mask = Q6_Vh_vsplat_R(0x7FFF); + const HVX_Vector v_clamp = Q6_Vh_vsplat_R(0x4C50); // min(|x|, 17.25) so e underflows to exact 0 in fp16 + const HVX_Vector v_scale = Q6_Vh_vsplat_R(0x65C5); + const HVX_Vector v_frac = Q6_Vh_vsplat_R(0x03FF); + const HVX_Vector v_g1 = Q6_Vh_vsplat_R(HVX_EXP2_FIXED_G1); + const HVX_Vector v_g0 = Q6_Vh_vsplat_R(HVX_EXP2_FIXED_G0); + const HVX_Vector v_base = Q6_Vh_vsplat_R(0x6400); + const HVX_Vector v_last = Q6_Vh_vsplat_R(0x1400); + const HVX_Vector v_nhalf = Q6_Vh_vsplat_R(0xB800); + + const HVX_Vector z0 = Q6_Vuh_vmin_VuhVuh(Q6_V_vand_VV(x0, em_mask), v_clamp); + const HVX_Vector z1 = Q6_Vuh_vmin_VuhVuh(Q6_V_vand_VV(x1, em_mask), v_clamp); + const HVX_Vector y0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(z0, v_scale)); + const HVX_Vector y1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(z1, v_scale)); + const HVX_Vector t0 = Q6_Vh_equals_Vhf_rnd(y0); + const HVX_Vector t1 = Q6_Vh_equals_Vhf_rnd(y1); + const HVX_Vector rho0 = Q6_V_vand_VV(t0, v_frac); + const HVX_Vector rho1 = Q6_V_vand_VV(t1, v_frac); + const HVX_Vector r15_0 = Q6_Vh_vasl_VhR(rho0, 5); + const HVX_Vector r15_1 = Q6_Vh_vasl_VhR(rho1, 5); + + HVX_Vector rp0 = Q6_Vh_vadd_VhVh(Q6_Vh_vmpy_VhRh_s1_rnd_sat(r15_0, HVX_EXP2_FIXED_G2_PAIR), v_g1); + HVX_Vector rp1 = Q6_Vh_vadd_VhVh(Q6_Vh_vmpy_VhRh_s1_rnd_sat(r15_1, HVX_EXP2_FIXED_G2_PAIR), v_g1); + rp0 = Q6_Vh_vadd_VhVh(Q6_Vh_vmpy_VhVh_s1_rnd_sat(rp0, r15_0), v_g0); + rp1 = Q6_Vh_vadd_VhVh(Q6_Vh_vmpy_VhVh_s1_rnd_sat(rp1, r15_1), v_g0); + + const HVX_Vector b0 = Q6_Vh_vadd_VhVh(Q6_Vh_vsub_VhVh(v_base, t0), Q6_Vh_vmpy_VhVh_s1_rnd_sat(rp0, rho0)); + const HVX_Vector b1 = Q6_Vh_vadd_VhVh(Q6_Vh_vsub_VhVh(v_base, t1), Q6_Vh_vmpy_VhVh_s1_rnd_sat(rp1, rho1)); + const HVX_Vector e0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(b0, v_last)); + const HVX_Vector e1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_VhfVhf(b1, v_last)); + const HVX_Vector tc0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_VhfVhf(e0, v_nhalf)); + const HVX_Vector tc1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vadd_VhfVhf(e1, v_nhalf)); + + const HVX_Vector c4 = Q6_Vh_vsplat_R(HVX_SIGMOID_RECIP_C4); + const HVX_Vector c3 = Q6_Vh_vsplat_R(HVX_SIGMOID_RECIP_C3); + const HVX_Vector c2 = Q6_Vh_vsplat_R(HVX_SIGMOID_RECIP_C2); + const HVX_Vector c1 = Q6_Vh_vsplat_R(HVX_SIGMOID_RECIP_C1); + const HVX_Vector c0 = Q6_Vh_vsplat_R(HVX_SIGMOID_RECIP_C0); + + HVX_Vector p0 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(tc0, c4), c3); + HVX_Vector p1 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_VhfVhf(tc1, c4), c3); + p0 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vhf(p0, tc0), c2); + p1 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vhf(p1, tc1), c2); + p0 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vhf(p0, tc0), c1); + p1 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vhf(p1, tc1), c1); + const HVX_Vector rq0 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vhf(p0, tc0), c0); + const HVX_Vector rq1 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vhf(p1, tc1), c0); + + const HVX_Vector zero = Q6_V_vzero(); + const HVX_Vector r0 = Q6_Vhf_equals_Vqf16(rq0); + const HVX_Vector r1 = Q6_Vhf_equals_Vqf16(rq1); + const HVX_Vector er0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_Vqf16Vhf(rq0, e0)); + const HVX_Vector er1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vmpy_Vqf16Vhf(rq1, e1)); + const HVX_Vector out0 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VhVh(zero, x0), er0, r0); + const HVX_Vector out1 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VhVh(zero, x1), er1, r1); + return Q6_W_vcombine_VV(out1, out0); +} +#else +// Clamping u >= -14.0f keeps 2^u in normal fp16 range while 1.0f + 2^-14 == 1.0f in fp16 static inline HVX_Vector hvx_vec_fast_sigmoid_f16(HVX_Vector x_v) { const HVX_Vector v_one = hvx_vec_splat_f16(1.0f); const HVX_Vector v_neg_log2e = hvx_vec_splat_f16(-EXP_LOG2E_F); const HVX_Vector em_mask = Q6_Vh_vsplat_R(0x7FFF); + const HVX_Vector half_hf_v = Q6_Vh_vsplat_R(0x3800); + const HVX_Vector v_clamp_min = hvx_vec_splat_f16(-14.0f); - // Compute absolute value of x_v - HVX_Vector abs_x = Q6_V_vand_VV(x_v, em_mask); - - // Compute u = -abs_x * log2(e) <= 0. - HVX_Vector u = hvx_vec_mul_f16_f16(abs_x, v_neg_log2e); - - // Clamp input to prevent underflow in exp2 - const HVX_Vector v_clamp_min = hvx_vec_splat_f16(-24.0f); - u = Q6_Vhf_vmax_VhfVhf(v_clamp_min, u); - - HVX_Vector exp_val = hvx_vec_exp2_f16(u); - HVX_Vector denom = hvx_vec_add_f16_f16(v_one, exp_val); - HVX_Vector sig_abs = hvx_vec_inverse_f16(denom); - - // check if x_v < 0 (using integer comparison on absolute value) + HVX_Vector abs_x = Q6_V_vand_VV(x_v, em_mask); HVX_VectorPred is_neg = Q6_Q_vcmp_gt_VhVh(abs_x, x_v); - - // If x_v < 0, return 1.0f - sig_abs + HVX_Vector u = hvx_vec_mul_f16_f16(abs_x, v_neg_log2e); + u = Q6_Vhf_vmax_VhfVhf(v_clamp_min, u); + + HVX_Vector x_minus_half = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(u, half_hf_v)); + HVX_Vector k_v = Q6_Vh_equals_Vhf(x_minus_half); + HVX_Vector f_v = Q6_Vhf_equals_Vh(k_v); + HVX_Vector x_qf16 = Q6_Vqf16_vsub_VhfVhf(u, f_v); + + // Degree-4 polynomial for 2^f on [-0.5, 0.5] (max error < 4.2e-5, well below fp16 0.5 ULP) + HVX_Vector y = Q6_Vqf16_vmpy_Vqf16Vqf16(Q6_Vqf16_vadd_VhfVhf(Q6_Vh_vsplat_R(0x20ed), Q6_V_vzero()), x_qf16); + y = Q6_Vqf16_vadd_Vqf16Vhf(y, Q6_Vh_vsplat_R(0x2b1b)); + y = Q6_Vqf16_vmpy_Vqf16Vqf16(y, x_qf16); + y = Q6_Vqf16_vadd_Vqf16Vhf(y, Q6_Vh_vsplat_R(0x33b0)); + y = Q6_Vqf16_vmpy_Vqf16Vqf16(y, x_qf16); + y = Q6_Vqf16_vadd_Vqf16Vhf(y, Q6_Vh_vsplat_R(0x398c)); + y = Q6_Vqf16_vmpy_Vqf16Vqf16(y, x_qf16); + y = Q6_Vqf16_vadd_Vqf16Vhf(y, v_one); + + HVX_Vector exp_val = Q6_Vh_vaslacc_VhVhR(Q6_Vhf_equals_Vqf16(y), k_v, 10); + HVX_Vector denom = hvx_vec_add_f16_f16(v_one, exp_val); + HVX_Vector sig_abs = hvx_vec_inverse_pos_f16(denom); HVX_Vector sig_neg = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(v_one, sig_abs)); return Q6_V_vmux_QVV(is_neg, sig_neg, sig_abs); } +static inline HVX_VectorPair hvx_vec_fast_sigmoid_f16_pair(HVX_Vector x0, HVX_Vector x1) { + const HVX_Vector v_one = hvx_vec_splat_f16(1.0f); + const HVX_Vector v_neg_log2e = hvx_vec_splat_f16(-EXP_LOG2E_F); + const HVX_Vector em_mask = Q6_Vh_vsplat_R(0x7FFF); + const HVX_Vector half_hf_v = Q6_Vh_vsplat_R(0x3800); + const HVX_Vector v_clamp_min = hvx_vec_splat_f16(-14.0f); + + const HVX_Vector abs0 = Q6_V_vand_VV(x0, em_mask); + const HVX_Vector abs1 = Q6_V_vand_VV(x1, em_mask); + const HVX_VectorPred is_neg0 = Q6_Q_vcmp_gt_VhVh(abs0, x0); + const HVX_VectorPred is_neg1 = Q6_Q_vcmp_gt_VhVh(abs1, x1); + + HVX_Vector u0 = Q6_Vhf_vmax_VhfVhf(v_clamp_min, hvx_vec_mul_f16_f16(abs0, v_neg_log2e)); + HVX_Vector u1 = Q6_Vhf_vmax_VhfVhf(v_clamp_min, hvx_vec_mul_f16_f16(abs1, v_neg_log2e)); + + HVX_Vector k0 = Q6_Vh_equals_Vhf(Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(u0, half_hf_v))); + HVX_Vector k1 = Q6_Vh_equals_Vhf(Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(u1, half_hf_v))); + HVX_Vector q0 = Q6_Vqf16_vsub_VhfVhf(u0, Q6_Vhf_equals_Vh(k0)); + HVX_Vector q1 = Q6_Vqf16_vsub_VhfVhf(u1, Q6_Vhf_equals_Vh(k1)); + + // Degree-4 polynomial for 2^f on [-0.5, 0.5] (max error < 4.2e-5, well below fp16 0.5 ULP) + const HVX_Vector c3 = Q6_Vqf16_vadd_VhfVhf(Q6_Vh_vsplat_R(0x20ed), Q6_V_vzero()); + const HVX_Vector c2 = Q6_Vh_vsplat_R(0x2b1b); + const HVX_Vector c1 = Q6_Vh_vsplat_R(0x33b0); + const HVX_Vector c0 = Q6_Vh_vsplat_R(0x398c); + + HVX_Vector y0 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vqf16(c3, q0), c2); + HVX_Vector y1 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vqf16(c3, q1), c2); + y0 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vqf16(y0, q0), c1); + y1 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vqf16(y1, q1), c1); + y0 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vqf16(y0, q0), c0); + y1 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vqf16(y1, q1), c0); + y0 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vqf16(y0, q0), v_one); + y1 = Q6_Vqf16_vadd_Vqf16Vhf(Q6_Vqf16_vmpy_Vqf16Vqf16(y1, q1), v_one); + + HVX_Vector e0 = Q6_Vh_vaslacc_VhVhR(Q6_Vhf_equals_Vqf16(y0), k0, 10); + HVX_Vector e1 = Q6_Vh_vaslacc_VhVhR(Q6_Vhf_equals_Vqf16(y1), k1, 10); + HVX_Vector d0 = hvx_vec_add_f16_f16(v_one, e0); + HVX_Vector d1 = hvx_vec_add_f16_f16(v_one, e1); + HVX_Vector sa0 = hvx_vec_inverse_pos_f16(d0); + HVX_Vector sa1 = hvx_vec_inverse_pos_f16(d1); + HVX_Vector sn0 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(v_one, sa0)); + HVX_Vector sn1 = Q6_Vhf_equals_Vqf16(Q6_Vqf16_vsub_VhfVhf(v_one, sa1)); + HVX_Vector out0 = Q6_V_vmux_QVV(is_neg0, sn0, sa0); + HVX_Vector out1 = Q6_V_vmux_QVV(is_neg1, sn1, sa1); + return Q6_W_vcombine_VV(out1, out0); +} +#endif + static inline HVX_Vector hvx_vec_tanh_f16(HVX_Vector x) { // tanh(x) = 2 * sigmoid(2x) - 1 const HVX_Vector v_two = hvx_vec_splat_f16(2.0f); diff --git a/ggml/src/ggml-hexagon/htp/im2col-ops.c b/ggml/src/ggml-hexagon/htp/im2col-ops.c index 602ee1598f87..8bba8dedea41 100644 --- a/ggml/src/ggml-hexagon/htp/im2col-ops.c +++ b/ggml/src/ggml-hexagon/htp/im2col-ops.c @@ -1,7 +1,3 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include #include @@ -935,7 +931,7 @@ int op_im2col(struct htp_ops_context * octx) { uint32_t nrows = kparams->total_rows; if (octx->ctx->mdev.count > 1) { const struct htp_tensor_mdev_range range = - htp_tensor_mdev_partition(kparams->total_rows, htp_tensor_mdev_data_aligned(dst) ? kparams->rows_per_chunk : 0, + htp_tensor_mdev_partition(kparams->total_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); row_base = range.start; nrows = range.count; @@ -1039,7 +1035,7 @@ int op_im2col_3d(struct htp_ops_context * octx) { uint32_t nrows = kparams->total_rows; if (octx->ctx->mdev.count > 1) { const struct htp_tensor_mdev_range range = - htp_tensor_mdev_partition(kparams->total_rows, htp_tensor_mdev_data_aligned(dst) ? kparams->rows_per_chunk : 0, + htp_tensor_mdev_partition(kparams->total_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); row_base = range.start; nrows = range.count; diff --git a/ggml/src/ggml-hexagon/htp/im2col-ops.h b/ggml/src/ggml-hexagon/htp/im2col-ops.h index 23497d01d28e..d845f6cf1a28 100644 --- a/ggml/src/ggml-hexagon/htp/im2col-ops.h +++ b/ggml/src/ggml-hexagon/htp/im2col-ops.h @@ -65,7 +65,6 @@ struct htp_im2col_kernel_params { uint32_t OD, OH, OW; uint32_t patch_stride; uint32_t total_rows; - uint32_t rows_per_chunk; struct fastdiv_values div_OH; struct fastdiv_values div_OD; diff --git a/ggml/src/ggml-hexagon/htp/lightning-indexer-ops.c b/ggml/src/ggml-hexagon/htp/lightning-indexer-ops.c index 5d60c506e5e0..1d3f85e6120e 100644 --- a/ggml/src/ggml-hexagon/htp/lightning-indexer-ops.c +++ b/ggml/src/ggml-hexagon/htp/lightning-indexer-ops.c @@ -1,7 +1,3 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include @@ -25,12 +21,26 @@ #include "lightning-indexer-ops.h" +struct htp_lid_context; + +typedef void (*lid_prep_q_fn_t)(HVX_Vector * restrict q_sp, const uint8_t * restrict qs, uint8_t * restrict qh, + size_t qs_row_size, uint32_t D, uint32_t n_rows); +typedef void (*lid_prep_w_fn_t)(HVX_Vector * restrict w_dst, const uint8_t * restrict ws, uint32_t ha, uint32_t hb); +typedef void (*lid_prep_k_fn_t)(const struct htp_lid_context * lctx, HVX_Vector * restrict kt, uint8_t * restrict k_buf, + HVX_Vector * restrict kt_t0, uint32_t nkv, uint32_t b, struct htp_thread_trace * tr); + struct htp_lid_context { const struct htp_ops_context * octx; const struct htp_lid_kernel_params * kp; uint32_t n_blocks; uint32_t blocks_per_hvx; + uint32_t q_row_bytes; + uint32_t w_row_bytes; + + lid_prep_q_fn_t prep_q; + lid_prep_w_fn_t prep_w; + lid_prep_k_fn_t prep_k; // current stream and token tile uint32_t is; @@ -62,12 +72,53 @@ static inline void lid_prep_step_info(uint32_t k, uint32_t K, uint32_t t_first, static inline void lid_prep_push_step(dma_queue * dma_q, const struct htp_lid_context * lctx, const struct htp_tensor * q, const struct htp_tensor * w, uint8_t * qs, uint8_t * ws, uint32_t qs_row_size, uint32_t w_row_size, - uint32_t D, uint32_t n_head, uint32_t t, uint32_t ha, uint32_t hb) { + uint32_t t, uint32_t ha, uint32_t hb) { const uint32_t it = lctx->t0 + t; dma_queue_push(dma_q, dma_make_data(qs, q->data + it * q->nb[2] + lctx->is * q->nb[3] + ha * q->nb[1]), - qs_row_size, q->nb[1], D * sizeof(float), hb - ha); + qs_row_size, q->nb[1], lctx->q_row_bytes, hb - ha); dma_queue_push(dma_q, dma_make_data(ws, w->data + it * w->nb[1] + lctx->is * w->nb[3]), - w_row_size, w_row_size, n_head * sizeof(float), 1); + w_row_size, w_row_size, lctx->w_row_bytes, 1); +} + +static inline void lid_splat_q_row(HVX_Vector * restrict q_sp, const HVX_Vector * restrict qv, uint32_t D) { + for (uint32_t d0 = 0; d0 < D; d0 += VLEN_FP16) { + const HVX_Vector v = qv[d0 / VLEN_FP16]; + const uint32_t nd = MIN(VLEN_FP16, D - d0); + for (uint32_t j = 0; j < nd; ++j) { + *q_sp++ = hvx_vec_repl_f16(Q6_V_vror_VR(v, j * SIZEOF_FP16)); + } + } +} + +static void lid_prep_q_f32(HVX_Vector * restrict q_sp, const uint8_t * restrict qs, uint8_t * restrict qh, + size_t qs_row_size, uint32_t D, uint32_t n_rows) { + for (uint32_t r = 0; r < n_rows; ++r, q_sp += D) { + hvx_copy_f16_f32_aa(qh, qs + r * qs_row_size, D); + lid_splat_q_row(q_sp, (const HVX_Vector *) qh, D); + } +} + +static void lid_prep_q_f16(HVX_Vector * restrict q_sp, const uint8_t * restrict qs, uint8_t * restrict qh, + size_t qs_row_size, uint32_t D, uint32_t n_rows) { + (void) qh; + for (uint32_t r = 0; r < n_rows; ++r, q_sp += D) { + lid_splat_q_row(q_sp, (const HVX_Vector *) (qs + r * qs_row_size), D); + } +} + +static void lid_prep_w_f32(HVX_Vector * restrict w_dst, const uint8_t * restrict ws, uint32_t ha, uint32_t hb) { + const HVX_Vector * restrict wv = (const HVX_Vector *) ws; + for (uint32_t h = ha; h < hb; ++h) { + w_dst[h] = hvx_vec_repl4(Q6_V_vror_VR(wv[h / VLEN_FP32], (h % VLEN_FP32) * SIZEOF_FP32)); + } +} + +static void lid_prep_w_f16(HVX_Vector * restrict w_dst, const uint8_t * restrict ws, uint32_t ha, uint32_t hb) { + const HVX_Vector * restrict wv = (const HVX_Vector *) ws; + for (uint32_t h = ha; h < hb; ++h) { + const HVX_Vector vh = hvx_vec_repl_f16(Q6_V_vror_VR(wv[h / VLEN_FP16], (h % VLEN_FP16) * SIZEOF_FP16)); + w_dst[h] = Q6_V_lo_W(hvx_vec_f16_to_f32_shuff(vh)); + } } // Splat every Q element (f16) and every head weight (f32) into a full vector. @@ -115,11 +166,11 @@ static void lid_prep_thread(const htp_thread_t * th, unsigned int nth, unsigned // Prologue: prime both slots uint32_t t, ha, hb; lid_prep_step_info(0, n_steps, t_first, i0, i1, n_head, &t, &ha, &hb); - lid_prep_push_step(dma_q, lctx, q, w, qs[0], ws[0], L->size_qs_row, w_row_size, D, n_head, t, ha, hb); + lid_prep_push_step(dma_q, lctx, q, w, qs[0], ws[0], L->size_qs_row, w_row_size, t, ha, hb); if (n_steps > 1) { lid_prep_step_info(1, n_steps, t_first, i0, i1, n_head, &t, &ha, &hb); - lid_prep_push_step(dma_q, lctx, q, w, qs[1], ws[1], L->size_qs_row, w_row_size, D, n_head, t, ha, hb); + lid_prep_push_step(dma_q, lctx, q, w, qs[1], ws[1], L->size_qs_row, w_row_size, t, ha, hb); } // Loop: pop(slot) -> compute(slot) -> push(slot, k + 2) @@ -134,32 +185,15 @@ static void lid_prep_thread(const htp_thread_t * th, unsigned int nth, unsigned htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) it); - HVX_Vector * restrict q_sp = (HVX_Vector *) lctx->spad_q + (t * n_head + ha) * D; - for (uint32_t h = ha; h < hb; ++h) { - hvx_copy_f16_f32_aa(qh, qs[slot] + (h - ha) * L->size_qs_row, D); - - const HVX_Vector * restrict qv = (const HVX_Vector *) qh; - for (uint32_t d0 = 0; d0 < D; d0 += VLEN_FP16) { - const HVX_Vector v = qv[d0 / VLEN_FP16]; - const uint32_t nd = MIN(VLEN_FP16, D - d0); - for (uint32_t j = 0; j < nd; ++j) { - *q_sp++ = hvx_vec_repl_f16(Q6_V_vror_VR(v, j * SIZEOF_FP16)); - } - } - } - - const HVX_Vector * restrict wv = (const HVX_Vector *) ws[slot]; - HVX_Vector * restrict w_dst = (HVX_Vector *) (lctx->spad_w + t * n_head * VLEN); - for (uint32_t h = ha; h < hb; ++h) { - w_dst[h] = hvx_vec_repl4(Q6_V_vror_VR(wv[h / VLEN_FP32], (h % VLEN_FP32) * SIZEOF_FP32)); - } + lctx->prep_q((HVX_Vector *) lctx->spad_q + (t * n_head + ha) * D, qs[slot], qh, L->size_qs_row, D, hb - ha); + lctx->prep_w((HVX_Vector *) (lctx->spad_w + t * n_head * VLEN), ws[slot], ha, hb); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) it); if (k + 2 < n_steps) { uint32_t next_t, next_ha, next_hb; lid_prep_step_info(k + 2, n_steps, t_first, i0, i1, n_head, &next_t, &next_ha, &next_hb); - lid_prep_push_step(dma_q, lctx, q, w, qs[slot], ws[slot], L->size_qs_row, w_row_size, D, n_head, next_t, next_ha, next_hb); + lid_prep_push_step(dma_q, lctx, q, w, qs[slot], ws[slot], L->size_qs_row, w_row_size, next_t, next_ha, next_hb); } } } @@ -170,37 +204,6 @@ static void lid_prep_thread(const htp_thread_t * th, unsigned int nth, unsigned #define LID_MUL_F16(a, b) Q6_Vhf_vmpy_VhfVhf(a, b) #endif -// Q8_0 row to f16 in place, 4 blocks (128 values) per step. -// Go backwards: the f16 output of a group is wider than its input and covers the input of the next group. -static inline void lid_dequant_row_q8_0(uint8_t * restrict row, uint32_t D) { - const int32_t nb = D / QK8_0; - - const HVX_VectorPred q32 = Q6_Q_vsetq_R(32); - const HVX_VectorPred q64 = Q6_Q_vsetq_R(64); - const HVX_VectorPred q96 = Q6_Q_vsetq_R(96); - - for (int32_t g = (nb - 1) / 4; g >= 0; --g) { - const uint8_t * src = row + g * 4 * sizeof(block_q8_0); - const HVX_Vector v0 = *(const HVX_UVector *) src; - const HVX_Vector v1 = *(const HVX_UVector *) (src + VLEN); - - HVX_Vector qs = Q6_V_vmux_QVV(q96, Q6_V_valign_VVR(v1, v0, 6), Q6_V_valign_VVR(v1, v0, 8)); - qs = Q6_V_vmux_QVV(q64, Q6_V_valign_VVR(v1, v0, 4), qs); - qs = Q6_V_vmux_QVV(q32, Q6_V_valign_VVR(v1, v0, 2), qs); - - const HVX_Vector s01 = Q6_V_vmux_QVV(q64, hvx_vec_repl_f16(v0), hvx_vec_repl_f16(Q6_V_valign_VVR(v1, v0, 34))); - const HVX_Vector s23 = Q6_V_vmux_QVV(q64, hvx_vec_repl_f16(Q6_V_valign_VVR(v1, v0, 68)), hvx_vec_repl_f16(Q6_V_valign_VVR(v1, v0, 102))); - - const HVX_VectorPair qh = Q6_Wh_vunpack_Vb(qs); - - HVX_Vector * dst = (HVX_Vector *) (row + g * 2 * VLEN); - dst[0] = Q6_Vhf_equals_Wqf32(Q6_Wqf32_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_lo_W(qh)), s01)); - if (g * 4 + 2 < nb) { - dst[1] = Q6_Vhf_equals_Wqf32(Q6_Wqf32_vmpy_VhfVhf(Q6_Vhf_equals_Vh(Q6_V_hi_W(qh)), s23)); - } - } -} - // Q4_0 blocks i, i + 1 (v loaded at block i) to signed quants: block i in bytes 0..31, block i + 1 in bytes 32..63. // qs[j] holds value j (low nibble) and j + 16 (high nibble). lo16 selects bytes 0..15 and 32..47. static inline HVX_Vector lid_q4_0_pair_quants(HVX_Vector v, HVX_VectorPred q32, HVX_VectorPred lo16) { @@ -237,7 +240,8 @@ static __attribute__((noinline)) void lid_dequant_block(uint8_t * restrict k_buf } } else { for (uint32_t r = 0; r < nkv; ++r) { - lid_dequant_row_q8_0(k_buf + r * row_stride, D); + __fp16 * row = (__fp16 *) (k_buf + r * row_stride); + hvx_dequantize_row_flat_q8_0_f16(row, row, D); } } } @@ -446,46 +450,30 @@ static inline void lid_compute_row2(float * restrict o0, HVX_VectorPair out1 = Q6_W_vzero(); uint32_t h = 0; - for (; h + 4 <= n_head; h += 4) { + for (; h + 2 <= n_head; h += 2) { const HVX_Vector * restrict q0 = q_t + h * D; const HVX_Vector * restrict q1 = q0 + D; - const HVX_Vector * restrict q2 = q1 + D; - const HVX_Vector * restrict q3 = q2 + D; HVX_VectorPair a0 = Q6_W_vzero(); HVX_VectorPair a1 = Q6_W_vzero(); - HVX_VectorPair a2 = Q6_W_vzero(); - HVX_VectorPair a3 = Q6_W_vzero(); HVX_VectorPair b0 = Q6_W_vzero(); HVX_VectorPair b1 = Q6_W_vzero(); - HVX_VectorPair b2 = Q6_W_vzero(); - HVX_VectorPair b3 = Q6_W_vzero(); for (uint32_t d = 0; d < D; ++d) { const HVX_Vector k0 = kt0[d]; const HVX_Vector k1 = kt1[d]; const HVX_Vector v0 = q0[d]; const HVX_Vector v1 = q1[d]; - const HVX_Vector v2 = q2[d]; - const HVX_Vector v3 = q3[d]; a0 = lid_mpyacc(a0, k0, v0); b0 = lid_mpyacc(b0, k1, v0); a1 = lid_mpyacc(a1, k0, v1); b1 = lid_mpyacc(b1, k1, v1); - a2 = lid_mpyacc(a2, k0, v2); - b2 = lid_mpyacc(b2, k1, v2); - a3 = lid_mpyacc(a3, k0, v3); - b3 = lid_mpyacc(b3, k1, v3); } out0 = lid_head_acc(out0, a0, w_t[h + 0]); out0 = lid_head_acc(out0, a1, w_t[h + 1]); - out0 = lid_head_acc(out0, a2, w_t[h + 2]); - out0 = lid_head_acc(out0, a3, w_t[h + 3]); out1 = lid_head_acc(out1, b0, w_t[h + 0]); out1 = lid_head_acc(out1, b1, w_t[h + 1]); - out1 = lid_head_acc(out1, b2, w_t[h + 2]); - out1 = lid_head_acc(out1, b3, w_t[h + 3]); } for (; h < n_head; ++h) { const HVX_Vector * restrict q0 = q_t + h * D; @@ -505,6 +493,105 @@ static inline void lid_compute_row2(float * restrict o0, lid_store_row(o1, out1, m1); } +static __attribute__((noinline)) void lid_prep_k_block_f16(const struct htp_lid_context * lctx, HVX_Vector * restrict kt, uint8_t * restrict k_buf, + HVX_Vector * restrict kt_t0, uint32_t nkv, uint32_t b, struct htp_thread_trace * tr) { + const uint32_t D = lctx->octx->src[0]->ne[0]; + const size_t stride = lctx->L.size_k_raw_row; + HVX_Vector * const kt_t1 = kt_t0 + HTP_LID_KV_BLOCK; + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) b); + for (uint32_t d0 = 0; d0 < D; d0 += HTP_LID_KV_BLOCK) { + lid_transpose_64x64_f16(kt + d0, k_buf + d0 * sizeof(__fp16), stride, nkv, kt_t0, kt_t1); + } + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) b); +} + +static __attribute__((noinline)) void lid_prep_k_block_f32(const struct htp_lid_context * lctx, HVX_Vector * restrict kt, uint8_t * restrict k_buf, + HVX_Vector * restrict kt_t0, uint32_t nkv, uint32_t b, struct htp_thread_trace * tr) { + const uint32_t D = lctx->octx->src[0]->ne[0]; + const size_t stride = lctx->L.size_k_raw_row; + HVX_Vector * const kt_t1 = kt_t0 + HTP_LID_KV_BLOCK; + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) b); + for (uint32_t r = 0; r < nkv; ++r) { + lid_convert_row_f32_to_f16(k_buf + r * stride, D); + } + for (uint32_t d0 = 0; d0 < D; d0 += HTP_LID_KV_BLOCK) { + lid_transpose_64x64_f16(kt + d0, k_buf + d0 * sizeof(__fp16), stride, nkv, kt_t0, kt_t1); + } + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) b); +} + +static __attribute__((noinline)) void lid_prep_k_block_q8_0_gather(const struct htp_lid_context * lctx, HVX_Vector * restrict kt, uint8_t * restrict k_buf, + HVX_Vector * restrict kt_t0, uint32_t nkv, uint32_t b, struct htp_thread_trace * tr) { + (void) nkv; + const uint32_t D = lctx->octx->src[0]->ne[0]; + const size_t stride = lctx->L.size_k_raw_row; + HVX_Vector * const sc = kt_t0 + 2 * HTP_LID_KV_BLOCK; + const HVX_Vector g_offs = hvx_vec_gather_offsets_h(stride); + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) b); + lid_transpose_q8_0_gather(kt, kt_t0, sc, k_buf, stride, g_offs, D); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) b); +} + +static __attribute__((noinline)) void lid_prep_k_block_q8_0(const struct htp_lid_context * lctx, HVX_Vector * restrict kt, uint8_t * restrict k_buf, + HVX_Vector * restrict kt_t0, uint32_t nkv, uint32_t b, struct htp_thread_trace * tr) { + const uint32_t D = lctx->octx->src[0]->ne[0]; + const size_t stride = lctx->L.size_k_raw_row; + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, (uint16_t) b); + lid_dequant_block(k_buf, stride, nkv, D, false); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, (uint16_t) b); + + lid_prep_k_block_f16(lctx, kt, k_buf, kt_t0, nkv, b, tr); +} + +static __attribute__((noinline)) void lid_prep_k_block_q4_0(const struct htp_lid_context * lctx, HVX_Vector * restrict kt, uint8_t * restrict k_buf, + HVX_Vector * restrict kt_t0, uint32_t nkv, uint32_t b, struct htp_thread_trace * tr) { + const uint32_t D = lctx->octx->src[0]->ne[0]; + const size_t stride = lctx->L.size_k_raw_row; + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, (uint16_t) b); + lid_dequant_block(k_buf, stride, nkv, D, true); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, (uint16_t) b); + + lid_prep_k_block_f16(lctx, kt, k_buf, kt_t0, nkv, b, tr); +} + +static __attribute__((noinline)) void lid_compute_rows1(const struct htp_lid_context * lctx, uint8_t * restrict o0, + const HVX_Vector * restrict kt0, const uint8_t * restrict m0) { + const struct htp_lid_vtcm_layout * L = &lctx->L; + const uint32_t D = lctx->octx->src[0]->ne[0]; + const uint32_t n_head = lctx->octx->src[0]->ne[1]; + const uint32_t nt = lctx->nt; + + for (uint32_t t = 0; t < nt; ++t) { + const HVX_Vector * q_t = (const HVX_Vector *) lctx->spad_q + t * n_head * D; + const HVX_Vector * w_t = (const HVX_Vector *) (lctx->spad_w + t * n_head * VLEN); + lid_compute_row((float *) (o0 + t * L->size_o_row), q_t, w_t, kt0, + (const __fp16 *) (m0 + t * L->size_m_row), D, n_head); + } +} + +static __attribute__((noinline)) void lid_compute_rows2(const struct htp_lid_context * lctx, uint8_t * restrict o0, uint8_t * restrict o1, + const HVX_Vector * restrict kt0, const HVX_Vector * restrict kt1, + const uint8_t * restrict m0, const uint8_t * restrict m1) { + const struct htp_lid_vtcm_layout * L = &lctx->L; + const uint32_t D = lctx->octx->src[0]->ne[0]; + const uint32_t n_head = lctx->octx->src[0]->ne[1]; + const uint32_t nt = lctx->nt; + + for (uint32_t t = 0; t < nt; ++t) { + const HVX_Vector * q_t = (const HVX_Vector *) lctx->spad_q + t * n_head * D; + const HVX_Vector * w_t = (const HVX_Vector *) (lctx->spad_w + t * n_head * VLEN); + lid_compute_row2((float *) (o0 + t * L->size_o_row), (float *) (o1 + t * L->size_o_row), + q_t, w_t, kt0, kt1, + (const __fp16 *) (m0 + t * L->size_m_row), (const __fp16 *) (m1 + t * L->size_m_row), + D, n_head); + } +} + // Each thread owns a range of kv blocks and streams K / mask in, output out (HTP_LID_N_BUF buffers) static void lid_compute_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { struct htp_lid_context * lctx = (struct htp_lid_context *) data; @@ -523,14 +610,9 @@ static void lid_compute_thread(const htp_thread_t * th, unsigned int nth, unsign const struct htp_lid_vtcm_layout * L = &lctx->L; - const uint32_t D = q->ne[0]; - const uint32_t n_head = q->ne[1]; - const uint32_t n_kv = k->ne[2]; - const uint32_t nt = lctx->nt; - - const bool is_f32 = (k->type == HTP_TYPE_F32); - const bool is_q8_0 = (k->type == HTP_TYPE_Q8_0); - const bool is_q4_0 = (k->type == HTP_TYPE_Q4_0); + const uint32_t D = q->ne[0]; + const uint32_t n_kv = k->ne[2]; + const uint32_t nt = lctx->nt; const uint32_t k_row_size = lctx->kp->k_row_size; const uint32_t nbk2 = k->nb[2]; @@ -549,12 +631,6 @@ static void lid_compute_thread(const htp_thread_t * th, unsigned int nth, unsign kt[0] = (HVX_Vector *) (lctx->spad_kt + ith * L->size_kt); kt[1] = kt[0] + hex_round_up(D, HTP_LID_KV_BLOCK); HVX_Vector * kt_t0 = kt[1] + hex_round_up(D, HTP_LID_KV_BLOCK); - HVX_Vector * kt_t1 = kt_t0 + HTP_LID_KV_BLOCK; - - // Q8_0: transpose by gather from the raw rows (sc: one vector of block scales per 32 d) - const bool q8_g = is_q8_0 && lid_q8_0_gather_ok(L->size_k_raw_row, D); - HVX_Vector * sc = kt_t1 + HTP_LID_KV_BLOCK; - const HVX_Vector g_offs = hvx_vec_gather_offsets_h(L->size_k_raw_row); struct htp_thread_trace * tr = th->trace; dma_queue * dma_q = th->dma_q; @@ -586,41 +662,14 @@ static void lid_compute_thread(const htp_thread_t * th, unsigned int nth, unsign k_buf[j] = (uint8_t *) (uintptr_t) dma_queue_pop(dma_q).dst; m_buf[j] = (uint8_t *) (uintptr_t) dma_queue_pop(dma_q).dst; - if ((is_q8_0 && !q8_g) || is_q4_0) { - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, (uint16_t) (b + j)); - lid_dequant_block(k_buf[j], L->size_k_raw_row, nkv, D, is_q4_0); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, (uint16_t) (b + j)); - } - - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) (b + j)); - if (is_f32) { - for (uint32_t r = 0; r < nkv; ++r) { - lid_convert_row_f32_to_f16(k_buf[j] + r * L->size_k_raw_row, D); - } - } - if (q8_g) { - lid_transpose_q8_0_gather(kt[j], kt_t0, sc, k_buf[j], L->size_k_raw_row, g_offs, D); - } else { - for (uint32_t d0 = 0; d0 < D; d0 += HTP_LID_KV_BLOCK) { - lid_transpose_64x64_f16(kt[j] + d0, k_buf[j] + d0 * sizeof(__fp16), L->size_k_raw_row, nkv, kt_t0, kt_t1); - } - } - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) (b + j)); + lctx->prep_k(lctx, kt[j], k_buf[j], kt_t0, nkv, b + j, tr); } htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) b); - for (uint32_t t = 0; t < nt; ++t) { - const HVX_Vector * q_t = (const HVX_Vector *) lctx->spad_q + t * n_head * D; - const HVX_Vector * w_t = (const HVX_Vector *) (lctx->spad_w + t * n_head * VLEN); - if (nb == 2) { - lid_compute_row2((float *) (o_buf[0] + t * L->size_o_row), (float *) (o_buf[1] + t * L->size_o_row), - q_t, w_t, kt[0], kt[1], - (const __fp16 *) (m_buf[0] + t * L->size_m_row), (const __fp16 *) (m_buf[1] + t * L->size_m_row), - D, n_head); - } else { - lid_compute_row((float *) (o_buf[0] + t * L->size_o_row), q_t, w_t, kt[0], - (const __fp16 *) (m_buf[0] + t * L->size_m_row), D, n_head); - } + if (nb == 2) { + lid_compute_rows2(lctx, o_buf[0], o_buf[1], kt[0], kt[1], m_buf[0], m_buf[1]); + } else { + lid_compute_rows1(lctx, o_buf[0], kt[0], m_buf[0]); } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) b); @@ -670,6 +719,20 @@ struct lid_hmx_set { uint32_t n_u; }; +struct lid_hmx_w_slice { + const uint8_t * ptr; + size_t base_off; +}; + +struct htp_lid_hmx_context; + +typedef void (*lid_hmx_q_scg_fn_t)(const struct htp_lid_hmx_context * hctx, uint32_t slot, const struct lid_hmx_set * S, uint32_t c, + struct lid_hmx_w_slice ws); +typedef void (*lid_hmx_q_tiles_fn_t)(const struct htp_lid_hmx_context * hctx, uint32_t slot, const struct lid_hmx_set * S, uint32_t c, + const uint8_t * qs, uint8_t * qh); +typedef void (*lid_hmx_prep_k_fn_t)(const struct htp_lid_hmx_context * hctx, __fp16 * restrict k_t, const uint8_t * restrict k_raw, + uint32_t r0, uint32_t r1, uint32_t nv); + struct htp_lid_hmx_context { const struct htp_ops_context * octx; const struct htp_lid_kernel_params * kp; @@ -680,6 +743,12 @@ struct htp_lid_hmx_context { uint32_t n_blocks; // per run uint32_t n_tile; // tokens per token tile uint32_t n_tt; // token tiles per stream + uint32_t q_row_bytes; + uint32_t w_row_bytes; + + lid_hmx_q_scg_fn_t q_scg; + lid_hmx_q_tiles_fn_t q_tiles; + lid_hmx_prep_k_fn_t prep_k; uint32_t n_qsets; // Q sets per buffer uint32_t qbuf; // Q buffer of the run (two buffers: the next run's Q is prepped during this run) @@ -687,6 +756,7 @@ struct htp_lid_hmx_context { uint32_t tile0; // first (stream, token tile) of the run uint32_t n_run; // sets in the run uint32_t n_qthr; // threads with Q work in the run + uint32_t per_k0; // K rows per non-Q thread for block 0 uint32_t nt_run; // tokens of each set in the run uint32_t n_u_run; // token tiles of 32 of each set in the run int32_t g; // current stage @@ -704,7 +774,7 @@ struct htp_lid_hmx_context { uint8_t * sc; uint8_t * sc_id; __fp16 * s; - float * w; + uint8_t * w; uint8_t * qs; uint8_t * k_raw[2]; __fp16 * k_t[2]; @@ -841,17 +911,16 @@ static void lid_hmx_worker(const htp_thread_t * th, void * data) { static inline void lid_hmx_rows(const struct htp_lid_hmx_context * hctx, uint32_t ith, uint32_t nth, uint32_t g, uint32_t n_rows, uint32_t * r0, uint32_t * r1) { uint32_t per; - if (g == 0 && hctx->n_qthr < nth) { + if (g == 0 && hctx->per_k0 > 0) { if (ith < hctx->n_qthr) { *r0 = *r1 = 0; return; } ith -= hctx->n_qthr; - per = (n_rows + nth - hctx->n_qthr - 1) / (nth - hctx->n_qthr); + per = hctx->per_k0; } else { - per = fastdiv(n_rows + hctx->octx->n_hvx - 1, &hctx->octx->n_hvx_div); + per = hex_round_up(fastdiv(n_rows + hctx->octx->n_hvx - 1, &hctx->octx->n_hvx_div), 2); } - per = hex_round_up(per, 2); *r0 = MIN(ith * per, n_rows); *r1 = MIN(*r0 + per, n_rows); } @@ -920,12 +989,48 @@ static inline void lid_q8_0_pair_store(HVX_Vector * restrict dst, HVX_Vector a, } } +// Raw Q8_0 rows [r0, r1) (D = 128, n_dot = 4) to activation tiles, dequant fused with the row pair interleave. +static void lid_hmx_prep_k_q8_0_d128(const struct htp_lid_hmx_context * hctx, __fp16 * restrict k_t, const uint8_t * restrict k_raw, + uint32_t r0, uint32_t r1, uint32_t nv) { + const size_t row_stride = hctx->L.size_k_raw_row; + const HVX_Vector zero = Q6_V_vzero(); + const HVX_VectorPred q32 = Q6_Q_vsetq_R(32); + + for (uint32_t r = r0; r < r1; r += 2) { + const uint8_t * p0 = k_raw + r * row_stride; + const uint8_t * p1 = p0 + row_stride; + const bool v0 = r < nv; + const bool v1 = r + 1 < nv; + + HVX_Vector * dst = (HVX_Vector *) (k_t + (r / 32) * 4 * HMX_FP16_TILE_N_ELMS) + (r % 32) / 2; + + // D = 128: the row is 136 bytes, two aligned loads; scales at halfwords 0, 17, 34, 51 + const HVX_Vector a0 = v0 ? ((const HVX_Vector *) p0)[0] : zero; + const HVX_Vector a1 = v0 ? ((const HVX_Vector *) p0)[1] : zero; + const HVX_Vector b0 = v1 ? ((const HVX_Vector *) p1)[0] : zero; + const HVX_Vector b1 = v1 ? ((const HVX_Vector *) p1)[1] : zero; + + const HVX_VectorPair ds = Q6_W_vshuff_VVR(b0, a0, -SIZEOF_FP16); + + lid_q8_0_pair_store(dst, + Q6_V_vmux_QVV(q32, Q6_V_valign_VVR(a0, a0, 2), Q6_V_valign_VVR(a0, a0, 4)), + Q6_V_vmux_QVV(q32, Q6_V_valign_VVR(b0, b0, 2), Q6_V_valign_VVR(b0, b0, 4)), + hvx_vec_repl4(Q6_V_lo_W(ds)), hvx_vec_repl4(Q6_V_vror_VR(Q6_V_lo_W(ds), 17 * 4)), true); + lid_q8_0_pair_store(dst + 32, + Q6_V_vmux_QVV(q32, Q6_V_valign_VVR(a1, a0, 70), Q6_V_valign_VVR(a1, a0, 72)), + Q6_V_vmux_QVV(q32, Q6_V_valign_VVR(b1, b0, 70), Q6_V_valign_VVR(b1, b0, 72)), + hvx_vec_repl4(Q6_V_vror_VR(Q6_V_hi_W(ds), 2 * 4)), hvx_vec_repl4(Q6_V_vror_VR(Q6_V_hi_W(ds), 19 * 4)), true); + } +} + // Raw Q8_0 rows [r0, r1) to activation tiles, dequant fused with the row pair interleave. Rows >= nv are zero. // Per row pair and two blocks: interleave the quants of both rows as bytes, widen, then scale by the (d_r, d_r+1) word. -static inline void lid_hmx_prep_k_q8_0(__fp16 * restrict k_t, const uint8_t * restrict k_raw, size_t row_stride, - uint32_t r0, uint32_t r1, uint32_t nv, uint32_t n_dot) { - const HVX_Vector zero = Q6_V_vzero(); - const HVX_VectorPred q32 = Q6_Q_vsetq_R(32); +static void lid_hmx_prep_k_q8_0(const struct htp_lid_hmx_context * hctx, __fp16 * restrict k_t, const uint8_t * restrict k_raw, + uint32_t r0, uint32_t r1, uint32_t nv) { + const size_t row_stride = hctx->L.size_k_raw_row; + const uint32_t n_dot = hctx->L.n_dot; + const HVX_Vector zero = Q6_V_vzero(); + const HVX_VectorPred q32 = Q6_Q_vsetq_R(32); for (uint32_t r = r0; r < r1; r += 2) { const uint8_t * p0 = k_raw + r * row_stride; @@ -935,26 +1040,6 @@ static inline void lid_hmx_prep_k_q8_0(__fp16 * restrict k_t, const uint8_t * re HVX_Vector * dst = (HVX_Vector *) (k_t + (r / 32) * n_dot * HMX_FP16_TILE_N_ELMS) + (r % 32) / 2; - if (n_dot == 4) { - // D = 128: the row is 136 bytes, two aligned loads; scales at halfwords 0, 17, 34, 51 - const HVX_Vector a0 = v0 ? ((const HVX_Vector *) p0)[0] : zero; - const HVX_Vector a1 = v0 ? ((const HVX_Vector *) p0)[1] : zero; - const HVX_Vector b0 = v1 ? ((const HVX_Vector *) p1)[0] : zero; - const HVX_Vector b1 = v1 ? ((const HVX_Vector *) p1)[1] : zero; - - const HVX_VectorPair ds = Q6_W_vshuff_VVR(b0, a0, -SIZEOF_FP16); - - lid_q8_0_pair_store(dst, - Q6_V_vmux_QVV(q32, Q6_V_valign_VVR(a0, a0, 2), Q6_V_valign_VVR(a0, a0, 4)), - Q6_V_vmux_QVV(q32, Q6_V_valign_VVR(b0, b0, 2), Q6_V_valign_VVR(b0, b0, 4)), - hvx_vec_repl4(Q6_V_lo_W(ds)), hvx_vec_repl4(Q6_V_vror_VR(Q6_V_lo_W(ds), 17 * 4)), true); - lid_q8_0_pair_store(dst + 32, - Q6_V_vmux_QVV(q32, Q6_V_valign_VVR(a1, a0, 70), Q6_V_valign_VVR(a1, a0, 72)), - Q6_V_vmux_QVV(q32, Q6_V_valign_VVR(b1, b0, 70), Q6_V_valign_VVR(b1, b0, 72)), - hvx_vec_repl4(Q6_V_vror_VR(Q6_V_hi_W(ds), 2 * 4)), hvx_vec_repl4(Q6_V_vror_VR(Q6_V_hi_W(ds), 19 * 4)), true); - continue; - } - for (uint32_t i = 0; i < n_dot; i += 2) { const uint8_t * pa = p0 + i * sizeof(block_q8_0); const uint8_t * pb = p1 + i * sizeof(block_q8_0); @@ -973,11 +1058,13 @@ static inline void lid_hmx_prep_k_q8_0(__fp16 * restrict k_t, const uint8_t * re // Raw Q4_0 rows [r0, r1) to activation tiles, same as Q8_0: per row pair and two blocks, one load per row. // Rows >= nv are zero. -static inline void lid_hmx_prep_k_q4_0(__fp16 * restrict k_t, const uint8_t * restrict k_raw, size_t row_stride, - uint32_t r0, uint32_t r1, uint32_t nv, uint32_t n_dot) { - const HVX_Vector zero = Q6_V_vzero(); - const HVX_VectorPred q32 = Q6_Q_vsetq_R(32); - const HVX_VectorPred lo16 = Q6_Q_or_QQ(Q6_Q_vsetq_R(16), Q6_Q_and_QQn(Q6_Q_vsetq_R(48), q32)); +static void lid_hmx_prep_k_q4_0(const struct htp_lid_hmx_context * hctx, __fp16 * restrict k_t, const uint8_t * restrict k_raw, + uint32_t r0, uint32_t r1, uint32_t nv) { + const size_t row_stride = hctx->L.size_k_raw_row; + const uint32_t n_dot = hctx->L.n_dot; + const HVX_Vector zero = Q6_V_vzero(); + const HVX_VectorPred q32 = Q6_Q_vsetq_R(32); + const HVX_VectorPred lo16 = Q6_Q_or_QQ(Q6_Q_vsetq_R(16), Q6_Q_and_QQn(Q6_Q_vsetq_R(48), q32)); for (uint32_t r = r0; r < r1; r += 2) { const uint8_t * p0 = k_raw + r * row_stride; @@ -1000,9 +1087,11 @@ static inline void lid_hmx_prep_k_q4_0(__fp16 * restrict k_t, const uint8_t * re } // F16 rows [r0, r1) to activation tiles: row pairs interleaved. Rows >= nv are zero. -static inline void lid_hmx_prep_k_f16(__fp16 * restrict k_t, const uint8_t * restrict k_raw, size_t row_stride, - uint32_t r0, uint32_t r1, uint32_t nv, uint32_t n_dot) { - const HVX_Vector zero = Q6_V_vzero(); +static void lid_hmx_prep_k_f16(const struct htp_lid_hmx_context * hctx, __fp16 * restrict k_t, const uint8_t * restrict k_raw, + uint32_t r0, uint32_t r1, uint32_t nv) { + const size_t row_stride = hctx->L.size_k_raw_row; + const uint32_t n_dot = hctx->L.n_dot; + const HVX_Vector zero = Q6_V_vzero(); for (uint32_t r = r0; r < r1; r += 2) { const HVX_Vector * p0 = (const HVX_Vector *) (k_raw + r * row_stride); @@ -1022,10 +1111,30 @@ static inline void lid_hmx_prep_k_f16(__fp16 * restrict k_t, const uint8_t * res } } +// F32 rows [r0, r1) to activation tiles: f32 -> f16 fused with row-pair interleave. Rows >= nv are zero. +static void lid_hmx_prep_k_f32(const struct htp_lid_hmx_context * hctx, __fp16 * restrict k_t, const uint8_t * restrict k_raw, + uint32_t r0, uint32_t r1, uint32_t nv) { + const size_t row_stride = hctx->L.size_k_raw_row; + const uint32_t n_dot = hctx->L.n_dot; + const HVX_Vector zero = Q6_V_vzero(); + + for (uint32_t r = r0; r < r1; r += 2) { + const HVX_Vector * p0 = (const HVX_Vector *) (k_raw + r * row_stride); + const HVX_Vector * p1 = (const HVX_Vector *) (k_raw + (r + 1) * row_stride); + const bool v0 = r < nv; + const bool v1 = r + 1 < nv; + + HVX_Vector * dst = (HVX_Vector *) (k_t + (r / 32) * n_dot * HMX_FP16_TILE_N_ELMS) + (r % 32) / 2; + + for (uint32_t i = 0; i < n_dot; ++i) { + dst[i * 16] = hvx_vec_f32_to_f16_shuff(v0 ? p0[i] : zero, v1 ? p1[i] : zero); + } + } +} + // K rows of block g (this thread's rows) to activation tiles, one piece per set; set padding rows are zero. // Not inlined: keeps the stage's registers out of the prep loops. static __attribute__((noinline)) void lid_hmx_prep_k(const struct htp_lid_hmx_context * hctx, uint32_t ith, uint32_t nth, uint32_t g) { - const struct htp_lid_hmx_vtcm_layout * L = &hctx->L; const struct htp_tensor * k = hctx->octx->src[1]; const uint32_t n_kv = k->ne[2]; @@ -1036,11 +1145,8 @@ static __attribute__((noinline)) void lid_hmx_prep_k(const struct htp_lid_hmx_co uint32_t r0, r1; lid_hmx_rows(hctx, ith, nth, g, n_rows, &r0, &r1); - uint8_t * k_raw = hctx->k_raw[g % 2]; + const uint8_t * k_raw = hctx->k_raw[g % 2]; __fp16 * k_t = hctx->k_t[g % 2]; - const bool f32 = k->type == HTP_TYPE_F32; - const bool q8 = k->type == HTP_TYPE_Q8_0; - const bool q4 = k->type == HTP_TYPE_Q4_0; for (uint32_t r = r0; r < r1;) { const uint32_t x = xa + r; @@ -1049,24 +1155,71 @@ static __attribute__((noinline)) void lid_hmx_prep_k(const struct htp_lid_hmx_co const uint32_t end = MIN(r1, (set + 1) * ks - xa); const uint32_t nv = r + (kv < n_kv ? n_kv - kv : 0); - if (q8) { - lid_hmx_prep_k_q8_0(k_t, k_raw, L->size_k_raw_row, r, end, nv, L->n_dot); - } else if (q4) { - lid_hmx_prep_k_q4_0(k_t, k_raw, L->size_k_raw_row, r, end, nv, L->n_dot); - } else { - if (f32) { - for (uint32_t i = r; i < end; ++i) { - lid_convert_row_f32_to_f16(k_raw + i * L->size_k_raw_row, k->ne[0]); - } - } - lid_hmx_prep_k_f16(k_t, k_raw, L->size_k_raw_row, r, end, nv, L->n_dot); - } + hctx->prep_k(hctx, k_t, k_raw, r, end, nv); r = end; } } +static __attribute__((noinline)) void lid_hmx_extract_seg(const struct htp_lid_hmx_context * hctx, uint32_t ith, uint32_t g, + uint32_t ta, uint32_t tb, uint32_t q0, uint32_t q1) { + const struct htp_lid_hmx_vtcm_layout * L = &hctx->L; + + const uint32_t n_u = hctx->n_u_run; + const uint32_t mu = (n_u + 1) * HMX_FP16_TILE_SIZE - 1; + + static const int32_t base_offs[32] __attribute__((aligned(128))) = { + 0 * 128, 1 * 128, 2 * 128, 3 * 128, 4 * 128, 5 * 128, 6 * 128, 7 * 128, + 8 * 128, 9 * 128, 10 * 128, 11 * 128, 12 * 128, 13 * 128, 14 * 128, 15 * 128, + 0 * 128, 1 * 128, 2 * 128, 3 * 128, 4 * 128, 5 * 128, 6 * 128, 7 * 128, + 8 * 128, 9 * 128, 10 * 128, 11 * 128, 12 * 128, 13 * 128, 14 * 128, 15 * 128, + }; + const HVX_Vector zero = Q6_V_vzero(); + const HVX_Vector hi_off = Q6_V_vmux_QVV(Q6_Q_vsetq_R(64), zero, Q6_V_vsplat_R(n_u * HMX_FP16_TILE_SIZE)); + const HVX_Vector v_offs = Q6_Vw_vadd_VwVw(*(const HVX_Vector *) base_offs, hi_off); + + HVX_Vector * gbuf = (HVX_Vector *) (hctx->qs + ith * L->size_qs + 2 * 32 * L->size_qs_row + 32 * L->size_qh_row); + + const HVX_Vector ninf = Q6_V_vsplat_R(0xFF800000); + const HVX_Vector one = Q6_Vh_vsplat_R(0x3C00); + const HVX_Vector hinf = Q6_Vh_vsplat_R(0xFC00); + + const __fp16 * o_base = hctx->o[g % 2]; + const uint8_t * m_buf = hctx->m[g % 4]; + uint8_t * o_buf = hctx->out[g % 2]; + + for (uint32_t t = ta; t < tb; ++t) { + const uint32_t u = t / 32; + const HVX_Vector off = Q6_Vw_vadd_VwVw(v_offs, Q6_V_vsplat_R((t % 32) * 4)); + + for (uint32_t q = q0; q < q1; ++q) { + const __fp16 * base = o_base + (2 * q * n_u + u) * HMX_FP16_TILE_N_ELMS; + Q6_vgather_ARMVw(gbuf + q - q0, (size_t) base, mu, off); + } + hvx_gather_sync(gbuf + q1 - q0 - 1); + + const HVX_Vector * mv = (const HVX_Vector *) (m_buf + t * L->size_m_row); + HVX_Vector * ov = (HVX_Vector *) (o_buf + t * L->size_o_row); + + for (uint32_t q = q0; q < q1; ++q) { + const HVX_VectorPair s = hvx_vec_f16_to_f32(gbuf[q - q0]); + + // qf32 math does not keep inf: add a finite mask, then put -inf back + const HVX_Vector m_f16 = mv[q]; + const HVX_VectorPred m_inf = Q6_Q_vcmp_eq_VhVh(m_f16, hinf); + const HVX_VectorPair m_f32 = hvx_vec_f16_to_f32(Q6_V_vmux_QVV(m_inf, zero, m_f16)); + const HVX_VectorPair f_f32 = hvx_vec_f16_to_f32(Q6_V_vmux_QVV(m_inf, one, zero)); + + const HVX_Vector acc0 = HVX_OP_ADD_F32(Q6_V_lo_W(s), Q6_V_lo_W(m_f32)); + const HVX_Vector acc1 = HVX_OP_ADD_F32(Q6_V_hi_W(s), Q6_V_hi_W(m_f32)); + ov[2 * q + 0] = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VwVw(Q6_V_lo_W(f_f32), zero), ninf, acc0); + ov[2 * q + 1] = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VwVw(Q6_V_hi_W(f_f32), zero), ninf, acc1); + } + } +} + // O column of each token (64 kv per gather) + mask -> f32 rows, then one DMA out per segment static __attribute__((noinline)) void lid_hmx_extract(const struct htp_lid_hmx_context * hctx, const htp_thread_t * th, uint32_t ith, uint32_t nth, uint32_t g) { + (void) nth; const struct htp_ops_context * octx = hctx->octx; const struct htp_tensor * dst = octx->dst; const struct htp_lid_hmx_vtcm_layout * L = &hctx->L; @@ -1084,58 +1237,13 @@ static __attribute__((noinline)) void lid_hmx_extract(const struct htp_lid_hmx_c struct htp_thread_trace * tr = th->trace; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) g); - const uint32_t n_u = hctx->n_u_run; - const uint32_t mu = (n_u + 1) * HMX_FP16_TILE_SIZE - 1; - - int32_t offs[32] __attribute__((aligned(128))); - for (int l = 0; l < 32; l++) { - offs[l] = (l / 16) * n_u * HMX_FP16_TILE_SIZE + (l % 16) * 128; - } - const HVX_Vector v_offs = *(const HVX_Vector *) offs; - - HVX_Vector * gbuf = (HVX_Vector *) (hctx->qs + ith * L->size_qs + 2 * 32 * L->size_qs_row + 32 * L->size_qh_row); - - const HVX_Vector zero = Q6_V_vzero(); - const HVX_Vector ninf = Q6_V_vsplat_R(0xFF800000); - const HVX_Vector one = Q6_Vh_vsplat_R(0x3C00); - const HVX_Vector hinf = Q6_Vh_vsplat_R(0xFC00); - - const __fp16 * o_base = hctx->o[g % 2]; - const uint8_t * m_buf = hctx->m[g % 4]; - uint8_t * o_buf = hctx->out[g % 2]; + uint8_t * o_buf = hctx->out[g % 2]; for (uint32_t i = 0; i < n_seg; ++i) { const uint32_t q0 = seg[i].x0 / 64; const uint32_t q1 = (seg[i].x0 + seg[i].nv + 63) / 64; - for (uint32_t t = ta; t < tb; ++t) { - const uint32_t u = t / 32; - const HVX_Vector off = Q6_Vw_vadd_VwVw(v_offs, Q6_V_vsplat_R((t % 32) * 4)); - - for (uint32_t q = q0; q < q1; ++q) { - const __fp16 * base = o_base + (2 * q * n_u + u) * HMX_FP16_TILE_N_ELMS; - Q6_vgather_ARMVw(gbuf + q - q0, (size_t) base, mu, off); - } - hvx_gather_sync(gbuf + q1 - q0 - 1); - - const HVX_Vector * mv = (const HVX_Vector *) (m_buf + t * L->size_m_row); - HVX_Vector * ov = (HVX_Vector *) (o_buf + t * L->size_o_row); - - for (uint32_t q = q0; q < q1; ++q) { - const HVX_VectorPair s = hvx_vec_f16_to_f32(gbuf[q - q0]); - - // qf32 math does not keep inf: add a finite mask, then put -inf back - const HVX_Vector m_f16 = mv[q]; - const HVX_VectorPred m_inf = Q6_Q_vcmp_eq_VhVh(m_f16, hinf); - const HVX_VectorPair m_f32 = hvx_vec_f16_to_f32(Q6_V_vmux_QVV(m_inf, zero, m_f16)); - const HVX_VectorPair f_f32 = hvx_vec_f16_to_f32(Q6_V_vmux_QVV(m_inf, one, zero)); - - const HVX_Vector acc0 = HVX_OP_ADD_F32(Q6_V_lo_W(s), Q6_V_lo_W(m_f32)); - const HVX_Vector acc1 = HVX_OP_ADD_F32(Q6_V_hi_W(s), Q6_V_hi_W(m_f32)); - ov[2 * q + 0] = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VwVw(Q6_V_lo_W(f_f32), zero), ninf, acc0); - ov[2 * q + 1] = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VwVw(Q6_V_hi_W(f_f32), zero), ninf, acc1); - } - } + lid_hmx_extract_seg(hctx, ith, g, ta, tb, q0, q1); const struct lid_hmx_set S = hctx->sets[seg[i].set]; dma_queue_push(th->dma_q, @@ -1234,39 +1342,16 @@ static uint32_t lid_hmx_push_q(const struct htp_lid_hmx_context * hctx, dma_queu const uint32_t cnt = MIN(nh - h, nr - r); dma_queue_push(dma_q, dma_make_data(qs + r * hctx->L.size_qs_row, q->data + S->is * q->nb[3] + (S->t0 + t) * q->nb[2] + h * q->nb[1]), - hctx->L.size_qs_row, q->nb[1], q->ne[0] * sizeof(float), cnt); + hctx->L.size_qs_row, q->nb[1], hctx->q_row_bytes, cnt); r += cnt; n++; } return n; } -// Scales (|w| per channel, f16 in the low half of each word) and G tile (sign(w) at row c, column token(c) % 32) -// of one channel tile. w points at the tile's 32 channels, the first one is (token t, head h). -static inline void lid_hmx_build_sc_g(uint8_t * restrict sc, __fp16 * restrict gt, const float * restrict w, - uint32_t t, uint32_t h, uint32_t nr, uint32_t nh) { +// G tile (sign(w) at row c, column token(c) % 32) of one channel tile. First channel is (token t, head h). +static inline void lid_hmx_build_g(__fp16 * restrict gt, HVX_Vector sv, uint32_t t, uint32_t h, uint32_t nr, uint32_t nh) { const HVX_Vector zero = Q6_V_vzero(); - const HVX_Vector wv = Q6_V_vmux_QVV(Q6_Q_vsetq2_R(nr * sizeof(float)), *(const HVX_Vector *) w, zero); - - HVX_Vector * scv = (HVX_Vector *) sc; - scv[0] = hvx_vec_f32_to_f16_shuff(Q6_V_vand_VV(wv, Q6_V_vsplat_R(0x7FFFFFFF)), zero); - scv[1] = zero; - - // sign(w) as f16 bits in the low half of each word, then packed: row r in halfword r - const HVX_VectorPred nz = Q6_Q_vcmp_gt_VuwVuw(Q6_V_vand_VV(wv, Q6_V_vsplat_R(0x7FFFFFFF)), zero); - const HVX_Vector sgn = Q6_V_vor_VV(Q6_V_vsplat_R(0x3C00), Q6_Vw_vasr_VwR(Q6_V_vand_VV(wv, Q6_V_vsplat_R(0x80000000)), 16)); - const HVX_Vector sv = Q6_Vh_vpacke_VwVw(zero, Q6_V_vmux_QVV(nz, sgn, zero)); - - // token column of each row; -1 for missing rows (only rows 0..31 are used) - int16_t tcol[64] __attribute__((aligned(128))) = { 0 }; - for (uint32_t r = 0; r < 32; ++r) { - tcol[r] = r < nr ? (int16_t) (t % 32) : -1; - if (++h == nh) { - h = 0; - t++; - } - } - const HVX_Vector tv = *(const HVX_Vector *) tcol; // halfword 2n and 2n + 1 of a G vector are column n static const int16_t col[64] __attribute__((aligned(128))) = { @@ -1276,11 +1361,23 @@ static inline void lid_hmx_build_sc_g(uint8_t * restrict sc, __fp16 * restrict g }; const HVX_Vector cv = *(const HVX_Vector *) col; - // vector p holds rows 2p, 2p + 1 + // vector p holds rows 2p, 2p + 1; token column is t % 32 (-1 for missing rows) HVX_Vector * gv = (HVX_Vector *) gt; for (uint32_t p = 0; p < 16; ++p) { - const HVX_Vector tp = hvx_vec_repl4(Q6_V_vror_VR(tv, p * 4)); - const HVX_Vector sp = hvx_vec_repl4(Q6_V_vror_VR(sv, p * 4)); + const uint32_t r0 = 2 * p; + const int32_t c0 = r0 < nr ? (int32_t) (t & 31) : -1; + if (++h == nh) { + h = 0; + t++; + } + const int32_t c1 = (r0 + 1) < nr ? (int32_t) (t & 31) : -1; + if (++h == nh) { + h = 0; + t++; + } + const uint32_t t_pair = ((uint32_t) c1 << 16) | ((uint32_t) c0 & 0xFFFFu); + const HVX_Vector tp = Q6_V_vsplat_R(t_pair); + const HVX_Vector sp = hvx_vec_repl4(Q6_V_vror_VR(sv, p * 4)); gv[p] = Q6_V_vmux_QVV(Q6_Q_vcmp_eq_VhVh(cv, tp), sp, zero); } } @@ -1290,28 +1387,61 @@ static inline uint32_t lid_hmx_slot(const struct htp_lid_hmx_context * hctx, uin return qbuf * hctx->n_qsets + set; } -// Scales and G of channel tile c of a Q slot (needs the slot's w) -static __attribute__((noinline)) void lid_hmx_q_scg(const struct htp_lid_hmx_context * hctx, uint32_t slot, const struct lid_hmx_set * S, uint32_t c) { +// Scales (|w| per channel, f16 in the low half of each word) and G of channel tile c of a Q slot (f32 w) +static __attribute__((noinline)) void lid_hmx_q_scg_f32(const struct htp_lid_hmx_context * hctx, uint32_t slot, const struct lid_hmx_set * S, uint32_t c, + struct lid_hmx_w_slice ws) { const struct htp_lid_hmx_vtcm_layout * L = &hctx->L; const uint32_t nh = hctx->octx->src[0]->ne[1]; const uint32_t ch = c * 32; + const uint32_t nr = MIN(32, S->nt * nh - ch); const uint32_t t = fastdiv(ch, &hctx->kp->div_n_head); - lid_hmx_build_sc_g(hctx->sc + (slot * L->n_ch + c) * 256, hctx->gw + (slot * L->n_ch + c) * HMX_FP16_TILE_N_ELMS, - hctx->w + slot * (L->size_w / sizeof(float)) + ch, t, ch - t * nh, MIN(32, S->nt * nh - ch), nh); + const HVX_Vector zero = Q6_V_vzero(); + const HVX_Vector raw = *(const HVX_Vector *) (ws.ptr + ((size_t) c * 128 - ws.base_off)); + const HVX_Vector wv = Q6_V_vmux_QVV(Q6_Q_vsetq2_R(nr * sizeof(float)), raw, zero); + const HVX_Vector abs_wv = Q6_V_vand_VV(wv, Q6_V_vsplat_R(0x7FFFFFFF)); + + HVX_Vector * scv = (HVX_Vector *) (hctx->sc + (slot * L->n_ch + c) * 256); + scv[0] = hvx_vec_f32_to_f16_shuff(abs_wv, zero); + scv[1] = zero; + + // sign(w) as f16 bits in the low half of each word, then packed: row r in halfword r + const HVX_VectorPred nz = Q6_Q_vcmp_gt_VuwVuw(abs_wv, zero); + const HVX_Vector sgn = Q6_V_vor_VV(Q6_V_vsplat_R(0x3C00), Q6_Vw_vasr_VwR(Q6_V_vand_VV(wv, Q6_V_vsplat_R(0x80000000)), 16)); + const HVX_Vector sv = Q6_Vh_vpacke_VwVw(zero, Q6_V_vmux_QVV(nz, sgn, zero)); + + lid_hmx_build_g(hctx->gw + (slot * L->n_ch + c) * HMX_FP16_TILE_N_ELMS, sv, t, ch - t * nh, nr, nh); } -// Staged f32 Q rows of channel tile c to f16, then to the weight tiles of a Q slot -static __attribute__((noinline)) void lid_hmx_q_tiles(const struct htp_lid_hmx_context * hctx, uint32_t slot, const struct lid_hmx_set * S, uint32_t c, - const uint8_t * qs, uint8_t * qh) { +// Scales and G of channel tile c of a Q slot (f16 w) +static __attribute__((noinline)) void lid_hmx_q_scg_f16(const struct htp_lid_hmx_context * hctx, uint32_t slot, const struct lid_hmx_set * S, uint32_t c, + struct lid_hmx_w_slice ws) { const struct htp_lid_hmx_vtcm_layout * L = &hctx->L; - const uint32_t D = hctx->octx->src[0]->ne[0]; const uint32_t nh = hctx->octx->src[0]->ne[1]; - const uint32_t nr = MIN(32, S->nt * nh - c * 32); + const uint32_t ch = c * 32; + const uint32_t nr = MIN(32, S->nt * nh - ch); + const uint32_t t = fastdiv(ch, &hctx->kp->div_n_head); - for (uint32_t r = 0; r < nr; ++r) { - hvx_copy_f16_f32_aa(qh + r * L->size_qh_row, qs + r * L->size_qs_row, D); - } + const HVX_Vector zero = Q6_V_vzero(); + const HVX_Vector raw = Q6_V_vror_VR(*(const HVX_Vector *) (ws.ptr + ((size_t) (c / 2) * 128 - ws.base_off)), (c & 1) * 64); + const HVX_Vector wh = Q6_V_vmux_QVV(Q6_Q_vsetq2_R(nr * sizeof(__fp16)), raw, zero); + const HVX_Vector abs_wh = Q6_V_vand_VV(wh, Q6_Vh_vsplat_R(0x7FFF)); + + HVX_Vector * scv = (HVX_Vector *) (hctx->sc + (slot * L->n_ch + c) * 256); + scv[0] = Q6_V_lo_W(Q6_W_vshuff_VVR(zero, abs_wh, -SIZEOF_FP16)); + scv[1] = zero; + + const HVX_VectorPred nz = Q6_Q_vcmp_gt_VuhVuh(abs_wh, zero); + const HVX_Vector sgn = Q6_V_vor_VV(Q6_Vh_vsplat_R(0x3C00), Q6_V_vand_VV(wh, Q6_Vh_vsplat_R(0x8000))); + const HVX_Vector sv = Q6_V_vmux_QVV(nz, sgn, zero); + + lid_hmx_build_g(hctx->gw + (slot * L->n_ch + c) * HMX_FP16_TILE_N_ELMS, sv, t, ch - t * nh, nr, nh); +} + +static inline void lid_hmx_scatter_q_tiles(const struct htp_lid_hmx_context * hctx, uint32_t slot, uint32_t c, uint32_t nr, + const __fp16 * src, size_t src_stride) { + const struct htp_lid_hmx_vtcm_layout * L = &hctx->L; + const uint32_t D = hctx->octx->src[0]->ne[0]; // missing channels must be zero (finite): zero the tiles, then scatter only the valid rows __fp16 * qw = hctx->qw + (slot * L->n_ch + c) * L->n_dot * HMX_FP16_TILE_N_ELMS; @@ -1320,17 +1450,40 @@ static __attribute__((noinline)) void lid_hmx_q_tiles(const struct htp_lid_hmx_c ((HVX_Vector *) qw)[i] = Q6_V_vzero(); } } - hmx_interleave_rows_to_tiles(qw, (const __fp16 *) qh, nr, D, L->size_qh_row / sizeof(__fp16), 0, hex_round_up(nr, 2)); - hvx_gather_sync(qw); + hmx_interleave_rows_to_tiles(qw, src, nr, D, src_stride, 0, hex_round_up(nr, 2)); } -static inline uint32_t lid_hmx_find_valid_gc(const struct htp_lid_hmx_context * hctx, uint32_t gc, uint32_t gc1) { +// Staged f32 Q rows of channel tile c to f16, then to the weight tiles of a Q slot +static __attribute__((noinline)) void lid_hmx_q_tiles_f32(const struct htp_lid_hmx_context * hctx, uint32_t slot, const struct lid_hmx_set * S, uint32_t c, + const uint8_t * qs, uint8_t * qh) { + const struct htp_lid_hmx_vtcm_layout * L = &hctx->L; + const uint32_t D = hctx->octx->src[0]->ne[0]; + const uint32_t nh = hctx->octx->src[0]->ne[1]; + const uint32_t nr = MIN(32, S->nt * nh - c * 32); + + for (uint32_t r = 0; r < nr; ++r) { + hvx_copy_f16_f32_aa(qh + r * L->size_qh_row, qs + r * L->size_qs_row, D); + } + lid_hmx_scatter_q_tiles(hctx, slot, c, nr, (const __fp16 *) qh, L->size_qh_row / sizeof(__fp16)); +} + +// Staged f16 Q rows of channel tile c directly to the weight tiles of a Q slot +static __attribute__((noinline)) void lid_hmx_q_tiles_f16(const struct htp_lid_hmx_context * hctx, uint32_t slot, const struct lid_hmx_set * S, uint32_t c, + const uint8_t * qs, uint8_t * qh) { + (void) qh; + const uint32_t nh = hctx->octx->src[0]->ne[1]; + const uint32_t nr = MIN(32, S->nt * nh - c * 32); + lid_hmx_scatter_q_tiles(hctx, slot, c, nr, (const __fp16 *) qs, hctx->L.size_qs_row / sizeof(__fp16)); +} + +static inline uint32_t lid_hmx_find_valid_gc(const struct htp_lid_hmx_context * hctx, const struct lid_hmx_set * sets, + uint32_t gc, uint32_t gc1) { const struct fastdiv_values * div_n_ch = &hctx->kp->div_n_ch; const uint32_t n_ch = hctx->L.n_ch; while (gc < gc1) { const uint32_t set = fastdiv(gc, div_n_ch); const uint32_t c = gc - set * n_ch; - if (c < hctx->nx_sets[set].n_ch) { + if (c < sets[set].n_ch) { return gc; } gc++; @@ -1338,30 +1491,54 @@ static inline uint32_t lid_hmx_find_valid_gc(const struct htp_lid_hmx_context * return gc1; } -static inline uint32_t lid_hmx_q_chunk_push(const struct htp_lid_hmx_context * hctx, dma_queue * dma_q, - uint8_t * qs, uint32_t qb, uint32_t gc) { - const struct htp_ops_context * octx = hctx->octx; - const struct htp_tensor * w = octx->src[2]; - const struct htp_lid_hmx_vtcm_layout * L = &hctx->L; - const uint32_t nh = octx->src[0]->ne[1]; +// Push w rows of [gc0, gc1) into per-HVX wd, one 2D DMA per overlapped set +static uint32_t lid_hmx_push_w(const struct htp_lid_hmx_context * hctx, dma_queue * dma_q, uint8_t * wd, + const struct lid_hmx_set * sets, uint32_t gc0, uint32_t gc1, + struct lid_hmx_w_slice w_set[HTP_LID_HMX_MAX_QSETS]) { + if (gc0 >= gc1) { + return 0; + } + const struct htp_tensor * w = hctx->octx->src[2]; + const struct fastdiv_values * div_n_ch = &hctx->kp->div_n_ch; + const uint32_t n_ch = hctx->L.n_ch; + const uint32_t nh = hctx->octx->src[0]->ne[1]; + const size_t row_b = hctx->w_row_bytes; - const uint32_t set = fastdiv(gc, &hctx->kp->div_n_ch); - const uint32_t c = gc - set * L->n_ch; - const struct lid_hmx_set * S = &hctx->nx_sets[set]; + uint32_t n_dma = 0; + size_t off = 0; + for (uint32_t set = fastdiv(gc0, div_n_ch), set_end = fastdiv(gc1 - 1, div_n_ch); set <= set_end; ++set) { + const struct lid_hmx_set S = sets[set]; + const uint32_t c0 = MAX(gc0, set * n_ch) - set * n_ch; + const uint32_t c1 = MIN(MIN(gc1, (set + 1) * n_ch) - set * n_ch, S.n_ch); + if (c0 >= c1) { + continue; + } - const uint32_t slot = lid_hmx_slot(hctx, qb, set); - const uint32_t ch = c * 32; - const uint32_t ta = fastdiv(ch, &hctx->kp->div_n_head); - const uint32_t tb = fastdiv(MIN(ch + 32, S->nt * nh) - 1, &hctx->kp->div_n_head) + 1; + const uint32_t ta = fastdiv(c0 * 32, &hctx->kp->div_n_head); + const uint32_t tb = fastdiv(MIN(c1 * 32, S.nt * nh) - 1, &hctx->kp->div_n_head) + 1; + const size_t ta_b = (size_t) ta * row_b; + const size_t base_off = ta_b & ~(size_t) 127; + uint8_t * dst = wd + off; + + w_set[set].ptr = dst; + w_set[set].base_off = base_off; + dma_queue_push(dma_q, dma_make_data(dst + (ta_b & 127), w->data + S.is * w->nb[3] + (S.t0 + ta) * w->nb[1]), + row_b, w->nb[1], row_b, tb - ta); + off += hex_round_up((size_t) tb * row_b - base_off, 128); + n_dma++; + } + return n_dma; +} - float * wd = hctx->w + slot * (L->size_w / sizeof(float)); - dma_queue_push(dma_q, dma_make_data(wd + ta * nh, w->data + S->is * w->nb[3] + (S->t0 + ta) * w->nb[1]), - nh * sizeof(float), w->nb[1], nh * sizeof(float), tb - ta); - return 1 + lid_hmx_push_q(hctx, dma_q, qs, S, c); +static inline uint32_t lid_hmx_q_chunk_push(const struct htp_lid_hmx_context * hctx, dma_queue * dma_q, + uint8_t * qs, uint32_t gc) { + const uint32_t set = fastdiv(gc, &hctx->kp->div_n_ch); + return lid_hmx_push_q(hctx, dma_q, qs, &hctx->nx_sets[set], gc - set * hctx->L.n_ch); } // Stage g share of the next run's Q prep (the DMA queue of the thread is empty here) static __attribute__((noinline)) void lid_hmx_q_chunk(const struct htp_lid_hmx_context * hctx, const htp_thread_t * th, uint32_t ith, uint32_t nth) { + (void) nth; const struct htp_ops_context * octx = hctx->octx; const struct htp_lid_hmx_vtcm_layout * L = &hctx->L; @@ -1373,25 +1550,28 @@ static __attribute__((noinline)) void lid_hmx_q_chunk(const struct htp_lid_hmx_c const uint32_t gc1 = MIN(gc0 + per, b); const uint32_t qb = hctx->qbuf ^ 1; + uint32_t gc_cur = lid_hmx_find_valid_gc(hctx, hctx->nx_sets, gc0, gc1); + if (gc_cur >= gc1) { + return; + } + dma_queue * dma_q = th->dma_q; + uint8_t * wd = hctx->w + ith * L->size_w; uint8_t * qs[2]; qs[0] = hctx->qs + ith * L->size_qs; qs[1] = qs[0] + 32 * L->size_qs_row; uint8_t * qh = qs[0] + 2 * 32 * L->size_qs_row; - uint32_t gc_cur = lid_hmx_find_valid_gc(hctx, gc0, gc1); - if (gc_cur >= gc1) { - return; - } + struct lid_hmx_w_slice w_set[HTP_LID_HMX_MAX_QSETS]; + uint32_t n_dma[2] = {0, 0}; + n_dma[0] = lid_hmx_push_w(hctx, dma_q, wd, hctx->nx_sets, gc_cur, gc1, w_set) + + lid_hmx_q_chunk_push(hctx, dma_q, qs[0], gc_cur); - const uint32_t gc_next = lid_hmx_find_valid_gc(hctx, gc_cur + 1, gc1); + const uint32_t gc_next = lid_hmx_find_valid_gc(hctx, hctx->nx_sets, gc_cur + 1, gc1); uint32_t gc_prefetch = gc1; - - uint32_t n_dma[2] = {0, 0}; - n_dma[0] = lid_hmx_q_chunk_push(hctx, dma_q, qs[0], qb, gc_cur); if (gc_next < gc1) { - n_dma[1] = lid_hmx_q_chunk_push(hctx, dma_q, qs[1], qb, gc_next); - gc_prefetch = lid_hmx_find_valid_gc(hctx, gc_next + 1, gc1); + n_dma[1] = lid_hmx_q_chunk_push(hctx, dma_q, qs[1], gc_next); + gc_prefetch = lid_hmx_find_valid_gc(hctx, hctx->nx_sets, gc_next + 1, gc1); } uint32_t slot = 0; @@ -1405,17 +1585,17 @@ static __attribute__((noinline)) void lid_hmx_q_chunk(const struct htp_lid_hmx_c const struct lid_hmx_set * S = &hctx->nx_sets[set]; const uint32_t qslot = lid_hmx_slot(hctx, qb, set); - lid_hmx_q_scg(hctx, qslot, S, c); - lid_hmx_q_tiles(hctx, qslot, S, c, qs[slot], qh); + hctx->q_scg(hctx, qslot, S, c, w_set[set]); + hctx->q_tiles(hctx, qslot, S, c, qs[slot], qh); if (gc_prefetch < gc1) { - n_dma[slot] = lid_hmx_q_chunk_push(hctx, dma_q, qs[slot], qb, gc_prefetch); - gc_prefetch = lid_hmx_find_valid_gc(hctx, gc_prefetch + 1, gc1); + n_dma[slot] = lid_hmx_q_chunk_push(hctx, dma_q, qs[slot], gc_prefetch); + gc_prefetch = lid_hmx_find_valid_gc(hctx, hctx->nx_sets, gc_prefetch + 1, gc1); } else { n_dma[slot] = 0; } - gc_cur = lid_hmx_find_valid_gc(hctx, gc_cur + 1, gc1); + gc_cur = lid_hmx_find_valid_gc(hctx, hctx->nx_sets, gc_cur + 1, gc1); slot ^= 1; } } @@ -1425,12 +1605,8 @@ static __attribute__((noinline)) void lid_hmx_q_chunk(const struct htp_lid_hmx_c static void lid_hmx_qprep_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { struct htp_lid_hmx_context * hctx = (struct htp_lid_hmx_context *) data; const struct htp_ops_context * octx = hctx->octx; - const struct htp_tensor * q = octx->src[0]; - const struct htp_tensor * w = octx->src[2]; const struct htp_lid_hmx_vtcm_layout * L = &hctx->L; - const uint32_t nh = q->ne[1]; - struct htp_thread_trace * tr = th->trace; dma_queue * dma_q = th->dma_q; @@ -1438,32 +1614,16 @@ static void lid_hmx_qprep_thread(const htp_thread_t * th, unsigned int nth, unsi const uint32_t per = fastdiv(n_tot + octx->n_hvx - 1, &octx->n_hvx_div); const uint32_t gc0 = MIN(ith * per, n_tot); const uint32_t gc1 = MIN(gc0 + per, n_tot); + const uint32_t first = lid_hmx_find_valid_gc(hctx, hctx->sets, gc0, gc1); + uint8_t * wd = hctx->w + ith * L->size_w; uint8_t * qs = hctx->qs + ith * L->size_qs; uint8_t * qh = qs + 2 * 32 * L->size_qs_row; // all input DMAs in flight at once: w of the sets, Q of the first channel tile, then K and mask of block 0 - uint32_t n_dma = 0; - uint32_t first = gc1; + struct lid_hmx_w_slice w_set[HTP_LID_HMX_MAX_QSETS]; const struct fastdiv_values * div_n_ch = &hctx->kp->div_n_ch; - for (uint32_t set = fastdiv(gc0, div_n_ch); gc0 < gc1 && set <= fastdiv(gc1 - 1, div_n_ch); ++set) { - const struct lid_hmx_set S = hctx->sets[set]; - - const uint32_t c0 = MAX(gc0, set * L->n_ch) - set * L->n_ch; - const uint32_t c1 = MIN(MIN(gc1, (set + 1) * L->n_ch) - set * L->n_ch, S.n_ch); - if (c0 >= c1) { - continue; - } - first = MIN(first, set * L->n_ch + c0); - - const uint32_t ta = fastdiv(c0 * 32, &hctx->kp->div_n_head); - const uint32_t tb = fastdiv(MIN(c1 * 32, S.nt * nh) - 1, &hctx->kp->div_n_head) + 1; - float * wd = hctx->w + lid_hmx_slot(hctx, hctx->qbuf, set) * (L->size_w / sizeof(float)); - dma_queue_push(dma_q, dma_make_data(wd + ta * nh, w->data + S.is * w->nb[3] + (S.t0 + ta) * w->nb[1]), - nh * sizeof(float), w->nb[1], nh * sizeof(float), tb - ta); - n_dma++; - } - + uint32_t n_dma = lid_hmx_push_w(hctx, dma_q, wd, hctx->sets, first, gc1, w_set); if (first < gc1) { const uint32_t set = fastdiv(first, div_n_ch); const struct lid_hmx_set S = hctx->sets[set]; @@ -1494,13 +1654,13 @@ static void lid_hmx_qprep_thread(const htp_thread_t * th, unsigned int nth, unsi // scales and G while the Q rows land const uint32_t slot = lid_hmx_slot(hctx, hctx->qbuf, set); - lid_hmx_q_scg(hctx, slot, &S, c); + hctx->q_scg(hctx, slot, &S, c, w_set[set]); for (uint32_t i = 0; i < n_q; ++i) { dma_queue_pop(dma_q); } - lid_hmx_q_tiles(hctx, slot, &S, c, qs, qh); + hctx->q_tiles(hctx, slot, &S, c, qs, qh); } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) gc0); @@ -1525,24 +1685,35 @@ static void lid_hmx_first_thread(const htp_thread_t * th, unsigned int nth, unsi static int lid_hmx_run(struct htp_ops_context * octx, const struct htp_lid_kernel_params * kparams) { const struct htp_tensor * q = octx->src[0]; + const struct htp_tensor * k = octx->src[1]; + const struct htp_tensor * w = octx->src[2]; const uint32_t D = q->ne[0]; const uint32_t n_head = q->ne[1]; const uint32_t n_stream = q->ne[3]; const uint32_t n_hvx = kparams->n_hvx; const uint32_t n_qsets = kparams->n_qsets; + const bool q_f16 = (q->type == HTP_TYPE_F16); + const bool w_f16 = (w->type == HTP_TYPE_F16); struct htp_lid_hmx_context hctx; memset(&hctx, 0, sizeof(hctx)); - hctx.octx = octx; - hctx.kp = kparams; - hctx.Bc = kparams->kv_block; - hctx.kv_seg = kparams->kv_seg; - hctx.n_tile = kparams->n_tokens_tile; - hctx.n_tt = kparams->n_tt; - hctx.n_qsets = n_qsets; + hctx.octx = octx; + hctx.kp = kparams; + hctx.Bc = kparams->kv_block; + hctx.kv_seg = kparams->kv_seg; + hctx.n_tile = kparams->n_tokens_tile; + hctx.n_tt = kparams->n_tt; + hctx.q_row_bytes = D * (q_f16 ? sizeof(__fp16) : sizeof(float)); + hctx.w_row_bytes = n_head * (w_f16 ? sizeof(__fp16) : sizeof(float)); + hctx.q_scg = w_f16 ? lid_hmx_q_scg_f16 : lid_hmx_q_scg_f32; + hctx.q_tiles = q_f16 ? lid_hmx_q_tiles_f16 : lid_hmx_q_tiles_f32; + hctx.n_qsets = n_qsets; htp_lid_hmx_vtcm_layout_build(&hctx.L, D, n_head, hctx.n_tile, hctx.Bc, n_qsets * kparams->n_qbuf, n_hvx, kparams->k_row_size); + hctx.prep_k = k->type == HTP_TYPE_Q8_0 ? (hctx.L.n_dot == 4 ? lid_hmx_prep_k_q8_0_d128 : lid_hmx_prep_k_q8_0) : + k->type == HTP_TYPE_Q4_0 ? lid_hmx_prep_k_q4_0 : + k->type == HTP_TYPE_F32 ? lid_hmx_prep_k_f32 : lid_hmx_prep_k_f16; uint8_t * const base = octx->ctx->vtcm_base; const struct htp_lid_hmx_vtcm_layout * L = &hctx.L; @@ -1552,7 +1723,7 @@ static int lid_hmx_run(struct htp_ops_context * octx, const struct htp_lid_kerne hctx.sc = VTCM_LAYOUT_PTR(uint8_t, base, L->off_sc); hctx.sc_id = VTCM_LAYOUT_PTR(uint8_t, base, L->off_sc_id); hctx.s = VTCM_LAYOUT_PTR(__fp16, base, L->off_s); - hctx.w = VTCM_LAYOUT_PTR(float, base, L->off_w); + hctx.w = VTCM_LAYOUT_PTR(uint8_t, base, L->off_w); hctx.qs = VTCM_LAYOUT_PTR(uint8_t, base, L->off_qs); for (int i = 0; i < 2; i++) { hctx.k_raw[i] = VTCM_LAYOUT_PTR(uint8_t, base, L->off_k_raw[i]); @@ -1591,6 +1762,7 @@ static int lid_hmx_run(struct htp_ops_context * octx, const struct htp_lid_kerne const uint32_t per = fastdiv(n_tot + n_hvx - 1, &octx->n_hvx_div); hctx.n_qthr = (n_tot + per - 1) / per; + hctx.per_k0 = 0; hctx.g = -1; const bool q_ready = hctx.nx_on; @@ -1599,6 +1771,10 @@ static int lid_hmx_run(struct htp_ops_context * octx, const struct htp_lid_kerne hctx.nx_on = false; work_queue_run(octx->ctx->hvx_queue, lid_hmx_first_thread, &hctx, n_hvx); } else { + if (hctx.n_qthr < n_hvx) { + const uint32_t n_rows0 = MIN(hctx.Bc, hctx.n_run * hctx.kv_seg); + hctx.per_k0 = hex_round_up((n_rows0 + n_hvx - hctx.n_qthr - 1) / (n_hvx - hctx.n_qthr), 2); + } work_queue_run(octx->ctx->hvx_queue, lid_hmx_qprep_thread, &hctx, n_hvx); } @@ -1661,6 +1837,8 @@ static int lid_hmx_run(struct htp_ops_context * octx, const struct htp_lid_kerne int op_lightning_indexer(struct htp_ops_context * octx) { const struct htp_tensor * q = octx->src[0]; + const struct htp_tensor * k = octx->src[1]; + const struct htp_tensor * w = octx->src[2]; const struct htp_tensor * m = octx->src[3]; // no multi-device split yet, device 0 does all the work @@ -1682,14 +1860,25 @@ int op_lightning_indexer(struct htp_ops_context * octx) { return lid_hmx_run(octx, kparams); } + const bool q_f16 = (q->type == HTP_TYPE_F16); + const bool w_f16 = (w->type == HTP_TYPE_F16); + struct htp_lid_context lctx; - lctx.octx = octx; - lctx.kp = kparams; - lctx.n_blocks = kparams->n_kv_blocks; - lctx.blocks_per_hvx = kparams->blocks_per_hvx; + lctx.octx = octx; + lctx.kp = kparams; + lctx.n_blocks = kparams->n_kv_blocks; + lctx.blocks_per_hvx = kparams->blocks_per_hvx; + lctx.q_row_bytes = q->ne[0] * (q_f16 ? sizeof(__fp16) : sizeof(float)); + lctx.w_row_bytes = q->ne[1] * (w_f16 ? sizeof(__fp16) : sizeof(float)); + lctx.prep_q = q_f16 ? lid_prep_q_f16 : lid_prep_q_f32; + lctx.prep_w = w_f16 ? lid_prep_w_f16 : lid_prep_w_f32; htp_lid_vtcm_layout_build(&lctx.L, q->ne[0], q->ne[1], kparams->n_tokens_tile, kparams->n_hvx, kparams->k_row_size); + lctx.prep_k = k->type == HTP_TYPE_Q8_0 ? (lid_q8_0_gather_ok(lctx.L.size_k_raw_row, q->ne[0]) ? lid_prep_k_block_q8_0_gather : lid_prep_k_block_q8_0) : + k->type == HTP_TYPE_Q4_0 ? lid_prep_k_block_q4_0 : + k->type == HTP_TYPE_F32 ? lid_prep_k_block_f32 : lid_prep_k_block_f16; + uint8_t * const base = octx->ctx->vtcm_base; lctx.spad_q = VTCM_LAYOUT_PTR(uint8_t, base, lctx.L.off_q); diff --git a/ggml/src/ggml-hexagon/htp/lightning-indexer-ops.h b/ggml/src/ggml-hexagon/htp/lightning-indexer-ops.h index 14b3503f6e6d..4ed5bb5c7b1d 100644 --- a/ggml/src/ggml-hexagon/htp/lightning-indexer-ops.h +++ b/ggml/src/ggml-hexagon/htp/lightning-indexer-ops.h @@ -18,7 +18,7 @@ extern "C" { #define HTP_LID_HMX_TOKENS_MAX 512 // HMX can keep more tokens; VTCM decides #define HTP_LID_HMX_KV_BLOCK_MAX 2048 #define HTP_LID_HMX_MAX_QSETS 8 // streams in one HMX pipeline run -#define HTP_LID_N_BUF 4 // K / mask / output buffers per thread (two blocks computed, two in flight) +#define HTP_LID_N_BUF 4 // K / mask / output buffers per HVX (two blocks computed, two in flight) #ifndef HMX_FP16_TILE_N_COLS #define HMX_FP16_TILE_N_COLS 32 @@ -72,15 +72,15 @@ struct htp_lid_vtcm_layout { size_t off_o; size_t size_q_row; // f16 Q row, padded - size_t size_qs_row; // f32 Q staging row, padded + size_t size_qs_row; // f32/f16 Q staging row, padded size_t size_k_row; // f16 K row, padded size_t size_k_raw_row; size_t size_m_row; // f16 mask row of one kv block, padded size_t size_o_row; // f32 output row of one kv block, padded - size_t size_qs; // per thread + size_t size_qs; // per HVX size_t size_k_buf; // one K buffer - size_t size_kt; // per thread: two transposed K blocks, two 64x64 scratch tiles, Q8_0 block scales + size_t size_kt; // per HVX: two transposed K blocks, two 64x64 scratch tiles, Q8_0 block scales size_t size_m_buf; // one mask buffer size_t size_o_buf; // one output buffer @@ -122,29 +122,29 @@ static inline size_t htp_lid_compute_vtcm_usage(size_t D, size_t n_head, size_t // HMX path. K is the activation (kv rows), Q the weights (one output channel per (token, head)). // mm1: S = relu(K Q^T) * |w| per channel (HMX convert scale + pos clamp) // mm2: O = S G, G[(t,h), t] = sign(w[t,h]). O is [kv, token], f16. -// Q weights, G, scales and w are per Q set (one per stream when all tokens fit one tile). +// Q weights, G and scales are per Q set (one per stream when all tokens fit one tile). struct htp_lid_hmx_vtcm_layout { size_t off_qw; // Q weight tiles [n_qsets][n_ch][n_dot] size_t off_g; // G weight tiles [n_qsets][n_ch] size_t off_sc; // per channel scales, 256 bytes per channel tile, [n_qsets][n_ch] size_t off_sc_id; // identity scales size_t off_s; // S tiles of one block and token tile, [n_rt][n_sg] - size_t off_w; // w of the token tile, [n_qsets][n_tok][n_head] f32 - size_t off_qs; // per thread: f32 and f16 staging for 32 Q rows, gather scratch + size_t off_w; // per HVX: w staging for its channel tiles + size_t off_qs; // per HVX: f32/f16 and f16 staging for 32 Q rows, gather scratch size_t off_k_raw[2]; // K rows, [Bc][size_k_row] size_t off_k_t[2]; // K tiles [n_rt][n_dot] size_t off_o[2]; // O tiles [n_rt][n_u] size_t off_m[4]; // mask rows [n_tok][size_m_row] size_t off_out[2]; // f32 output rows [n_tok][size_o_row] - size_t size_qs_row; // f32 Q row, padded + size_t size_qs_row; // f32/f16 Q row, padded size_t size_qh_row; // f16 Q row, padded size_t size_k_row; // f16 K row, padded size_t size_k_raw_row; size_t size_m_row; size_t size_o_row; - size_t size_qs; // per thread - size_t size_w; // per Q set + size_t size_qs; // per HVX + size_t size_w; // per HVX uint32_t n_ch; // channel tiles: ceil(n_tok * n_head / 32) uint32_t n_u; // token tiles: ceil(n_tok / 32) @@ -169,8 +169,9 @@ static inline void htp_lid_hmx_vtcm_layout_build(struct htp_lid_hmx_vtcm_layout L->size_k_raw_row = L->size_k_row > hex_round_up(k_row_size, 128) ? L->size_k_row : hex_round_up(k_row_size, 128); L->size_m_row = hex_round_up(Bc * sizeof(uint16_t), 128); L->size_o_row = hex_round_up(Bc * sizeof(float), 128); + const size_t w_tiles = (n_qsets * L->n_ch + n_hvx - 1) / n_hvx; L->size_qs = 2 * 32 * L->size_qs_row + 32 * L->size_qh_row + hex_round_up(Bc / 64 * 128, 128); - L->size_w = hex_round_up(n_tok * n_head * sizeof(float), 128); + L->size_w = w_tiles * 128 + 2 * hex_round_up(n_head * sizeof(float), 128) + 256; const size_t tile = HMX_FP16_TILE_SIZE; @@ -185,7 +186,7 @@ static inline void htp_lid_hmx_vtcm_layout_build(struct htp_lid_hmx_vtcm_layout VTCM_LAYOUT_ALLOC(off, off_o[1], (size_t) L->n_rt * L->n_u * tile); VTCM_LAYOUT_ALLOC(off, off_sc, n_qsets * L->n_ch * 256); VTCM_LAYOUT_ALLOC(off, off_sc_id, 256); - VTCM_LAYOUT_ALLOC(off, off_w, n_qsets * L->size_w); + VTCM_LAYOUT_ALLOC(off, off_w, n_hvx * L->size_w); VTCM_LAYOUT_ALLOC(off, off_qs, n_hvx * L->size_qs); for (int i = 0; i < 2; i++) { VTCM_LAYOUT_ALLOC(off, off_k_raw[i], Bc * L->size_k_raw_row); diff --git a/ggml/src/ggml-hexagon/htp/main.c b/ggml/src/ggml-hexagon/htp/main.c index 712e898d2d89..a944d7c517a2 100644 --- a/ggml/src/ggml-hexagon/htp/main.c +++ b/ggml/src/ggml-hexagon/htp/main.c @@ -1,8 +1,3 @@ -#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include #include @@ -22,6 +17,7 @@ #include "htp-thread.h" #include "hex-utils.h" +#include "dma-proxy.h" #include "dma-queue.h" #include "hmx-queue.h" @@ -29,8 +25,8 @@ #include "ggml-common.h" #include "hex-bitmap.h" #include "htp-ctx.h" -#include "htp-dcache.h" #include "htp-ops.h" +#include "htp-vtcm.h" #include "htp_iface.h" #include "work-queue.h" #include "htp-trace.h" @@ -38,9 +34,10 @@ #include "dsv4-hc-ops.h" #include "htp-fence.h" +#define DMA_PROXY_CAPACITY 64 +#define DMA_PROXY_STACK_SIZE 16384 #define HMX_QUEUE_CAPACITY 128 #define HMX_QUEUE_STACK_SIZE 16384 -#define WORK_QUEUE_CAPACITY 16 #define WORK_QUEUE_STACK_SIZE 16384 #define MAIN_THREAD_STACK_SIZE 32768 @@ -348,14 +345,14 @@ static int vtcm_alloc(struct htp_context * ctx, uint64_t size_override) { } void * vtcm_ptr; - if (HAP_compute_res_attr_get_vtcm_ptr_v2(&attr, &vtcm_ptr, &vtcm_size) != 0) { + if (HAP_compute_res_attr_get_vtcm_ptr_v2(&attr, &vtcm_ptr, &vtcm_size) != 0 || vtcm_size < 2 * HTP_VTCM_GUARD_SIZE) { HAP_compute_res_release(rctx); FARF(ERROR, "failed to allocate %zu bytes VTCM (new)\n", ctx->vtcm_size); return AEE_ENOMEMORY; } ctx->vtcm_base = (uint8_t *) vtcm_ptr; - ctx->vtcm_size = vtcm_size; + ctx->vtcm_size = htp_vtcm_usable_size(vtcm_size); ctx->vtcm_rctx = rctx; atomic_store(&ctx->vtcm_valid, false); atomic_store(&ctx->vtcm_needs_release, false); @@ -502,8 +499,8 @@ AEEResult htp_iface_start(remote_handle64 handle, uint32_t sess_id, uint64_t dsp if (n_hvx > HTP_MAX_NHVX) { n_hvx = HTP_MAX_NHVX; } - if (n_hvx > hw_nth - 1) { - n_hvx = hw_nth - 1; + if (n_hvx > hw_nth - 2) { + n_hvx = hw_nth - 2; } uint32_t n_threads = hw_nth; @@ -525,7 +522,7 @@ AEEResult htp_iface_start(remote_handle64 handle, uint32_t sess_id, uint64_t dsp // 3. work_queue size_t wq_align = work_queue_alignof(); size_t offset_wq = hex_align_up(offset, wq_align); - size_t size_wq = work_queue_sizeof(n_hvx, WORK_QUEUE_CAPACITY, WORK_QUEUE_STACK_SIZE); + size_t size_wq = work_queue_sizeof(n_hvx, WORK_QUEUE_STACK_SIZE); offset = offset_wq + size_wq; // 4. dma_queue @@ -548,6 +545,12 @@ AEEResult htp_iface_start(remote_handle64 handle, uint32_t sess_id, uint64_t dsp offset = offset_hmx + size_hmx; } + // 6. dma_proxy + size_t dp_align = dma_proxy_alignof(); + size_t offset_dma_proxy = hex_align_up(offset, dp_align); + size_t size_dma_proxy = dma_proxy_sizeof(DMA_PROXY_CAPACITY, DMA_PROXY_STACK_SIZE); + offset = offset_dma_proxy + size_dma_proxy; + size_t footprint = hex_align_up(offset, 128); void * block = memalign(4096, footprint); @@ -610,6 +613,9 @@ AEEResult htp_iface_start(remote_handle64 handle, uint32_t sess_id, uint64_t dsp #if (__HEXAGON_ARCH__ >= 79) HAP_set_dcvs_v3_protected_bus_corners(&request, 1); + if (power_mode >= HTP_POWER_MODE_HIGH_PERFORMANCE) { + HAP_set_ddr_perf_mode(&request, 1); + } #endif if ((err = HAP_power_set((void *) ctx, &request)) != 0) { htp_iface_stop(handle); @@ -677,13 +683,15 @@ AEEResult htp_iface_start(remote_handle64 handle, uint32_t sess_id, uint64_t dsp dma_ptr_curr += size_dma_q; } + ctx->main_th = (htp_thread_t) { 0, ctx->dma[0], &ctx->trace[0] }; + ctx->ddr_spad_size = HTP_DDR_SPAD_SIZE; ctx->ddr_spad_base = memalign(128, ctx->ddr_spad_size); htp_thread_reset(); void * wq_ptr = (void *) ((uintptr_t) block + offset_wq); - ctx->hvx_queue = work_queue_init(wq_ptr, n_hvx, WORK_QUEUE_CAPACITY, WORK_QUEUE_STACK_SIZE, ctx->dma, ctx->trace); + ctx->hvx_queue = work_queue_init(wq_ptr, n_hvx, WORK_QUEUE_STACK_SIZE, ctx->dma, ctx->trace); ctx->hmx_enabled = n_hmx; ctx->hmx_queue = NULL; @@ -693,6 +701,9 @@ AEEResult htp_iface_start(remote_handle64 handle, uint32_t sess_id, uint64_t dsp } FARF(HIGH, "HMX %s (n_hmx=%d)", ctx->hmx_enabled ? "enabled" : "disabled", n_hmx); + void * dp_ptr = (void *) ((uintptr_t) block + offset_dma_proxy); + ctx->dma_proxy = dma_proxy_init(dp_ptr, DMA_PROXY_CAPACITY, DMA_PROXY_STACK_SIZE, ctx->dma, ctx->trace); + ctx->main_stack = NULL; ctx->main_thread = 0; atomic_store(&ctx->killed, false); @@ -744,16 +755,21 @@ AEEResult htp_iface_stop(remote_handle64 handle) { work_queue_free(ctx->hvx_queue); - for (int i = 0; i < ctx->n_threads; i++) { - dma_queue_free(ctx->dma[i]); - } - if (ctx->hmx_queue) { hmx_queue_free(ctx->hmx_queue); ctx->hmx_queue = NULL; } ctx->hmx_enabled = false; + if (ctx->dma_proxy) { + dma_proxy_free(ctx->dma_proxy); + ctx->dma_proxy = NULL; + } + + for (int i = 0; i < ctx->n_threads; i++) { + dma_queue_free(ctx->dma[i]); + } + vtcm_free(ctx); if (ctx->ddr_spad_base) { @@ -762,6 +778,18 @@ AEEResult htp_iface_stop(remote_handle64 handle) { ctx->ddr_spad_size = 0; } +#if (__HEXAGON_ARCH__ >= 79) + { + HAP_power_request_t request; + memset(&request, 0, sizeof(request)); + request.type = HAP_power_set_DCVS_v3; + request.dcvs_v3.set_dcvs_enable = TRUE; + request.dcvs_v3.dcvs_enable = TRUE; + HAP_set_ddr_perf_mode(&request, 0); + HAP_power_set((void *) ctx, &request); + } +#endif + free(ctx); h->ctx = NULL; @@ -787,8 +815,8 @@ AEEResult htp_iface_hwinfo(remote_handle64 handle, uint32_t * n_threads, uint32_ if (n_hvx_val > HTP_MAX_NHVX) { n_hvx_val = HTP_MAX_NHVX; } - if (n_hvx_val > n_threads_val - 1) { - n_hvx_val = n_threads_val - 1; + if (n_hvx_val > n_threads_val - 2) { + n_hvx_val = n_threads_val - 2; } *n_threads = n_threads_val; @@ -858,8 +886,6 @@ static int op_fence(struct htp_ops_context * octx) { atomic_uint * sync_fence = (atomic_uint *) (uintptr_t) sync->data; if (mode == 1) { - htp_dcache_flush_dirty_ranges(ctx); - htp_mdev_group_barrier(octx); if (ctx->mdev.idx == 0) { @@ -932,6 +958,7 @@ static int execute_op(struct htp_ops_context * octx) { return op_matmul_id_nx(octx); case HTP_OP_MUL_MAT_NX: + case HTP_OP_MUL_MAT_NX_GLU: return op_matmul_nx(octx); case HTP_OP_MUL: @@ -1273,8 +1300,6 @@ static int proc_op_req(struct htp_ops_context * octx, struct htp_buf_desc * bufs src->ne[0], src->ne[1], src->ne[2], src->ne[3]); } - htp_dcache_flush_dirty_tensors(octx->ctx, octx->src, HTP_OP_MAX_INPUTS); - // Prep output tensors for (uint32_t i = 0; i < HTP_OP_MAX_OUTPUTS; i++) { uint16_t dst_idx = op->dst[i]; @@ -1289,17 +1314,12 @@ static int proc_op_req(struct htp_ops_context * octx, struct htp_buf_desc * bufs dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3]); } - htp_dcache_mark_dirty_tensors(octx->ctx, octx->dsts, HTP_OP_MAX_OUTPUTS); - htp_mdev_group_barrier(octx); int status = execute_op(octx); htp_ops_context_set_status(octx, status); - octx->src0_spad.src = NULL; - octx->src1_spad.src = NULL; - octx->dst_spad.src = NULL; return octx->status; } @@ -1352,7 +1372,6 @@ static void process_opbatch(struct htp_context * ctx, const struct htp_opbatch_r htp_trace_event_start(&ctx->trace[0], HTP_TRACE_EVT_L2FLUSH, 0); qurt_mem_cache_clean((qurt_addr_t) 0, 0, QURT_MEM_CACHE_FLUSH_INVALIDATE_ALL, QURT_MEM_DCACHE); hex_l2fetch_block(ctx, ctx->footprint); - memset(ctx->dirty_ranges, 0, sizeof(ctx->dirty_ranges)); htp_trace_event_stop(&ctx->trace[0], HTP_TRACE_EVT_L2FLUSH, 0); htp_trace_event_start(&ctx->trace[0], HTP_TRACE_EVT_BUFF, 0); @@ -1395,6 +1414,7 @@ static void process_opbatch(struct htp_context * ctx, const struct htp_opbatch_r } } + dma_proxy_flush(ctx->dma_proxy); if (ctx->hmx_queue) { hmx_queue_suspend(ctx->hmx_queue); hmx_queue_flush(ctx->hmx_queue); diff --git a/ggml/src/ggml-hexagon/htp/matmul-ops.c b/ggml/src/ggml-hexagon/htp/matmul-ops.c index ea05937a5ed9..1dc0a9332d6f 100644 --- a/ggml/src/ggml-hexagon/htp/matmul-ops.c +++ b/ggml/src/ggml-hexagon/htp/matmul-ops.c @@ -1,8 +1,3 @@ -#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include #include @@ -27,7 +22,7 @@ #include "htp-vtcm.h" typedef struct { - float *dst; + dma_addr_t dst_dma_addr; dma_addr_t bias_addr; size_t bias_bytes; dma_addr_t act_dma_addr; @@ -37,7 +32,9 @@ typedef struct { int k; int n; int act_stride; - uint32_t act_elem_size; // 4=F32 src1, 2=F16 src1 + uint32_t act_elem_size; // 4=F32 src1, 2=F16 src1 + uint32_t dst_elem_size; // 4=F32 dst, 2=F16 dst + uint32_t bias_elem_size; // 4=F32 bias, 2=F16 bias int weight_stride; int weight_type; int dst_stride; @@ -61,90 +58,12 @@ typedef struct { int r3; struct fastdiv_values div_r2; struct fastdiv_values div_r3; + int32_t kernel_type; + int hmx_n_groups; + struct fastdiv_values div_hmx_n_groups; + struct fastdiv_values div_n_k_tiles; } hmx_mm_batched_params_t; -static bool htp_matmul_has_extended_weight(const struct htp_ops_context * octx, uint32_t n_weights) { - for (uint32_t i = 0; i < n_weights; ++i) { - if (htp_tensor_is_extended(octx->src[i])) { - return true; - } - } - return false; -} - -struct htp_mm_context { - const char * type; - struct htp_ops_context * octx; - const struct htp_tensor * act; - - void (*vec_dot_1x1)(const uint32_t n, float * restrict s0, - const void * restrict vx0, - const void * restrict vy0); - - void (*vec_dot_2x1)(const uint32_t n, float * restrict s0, - const void * restrict vx0, const void * restrict vx1, - const void * restrict vy0); - - void (*vec_dot_2x2)(const uint32_t n, float * restrict s0, float * restrict s1, - const void * restrict vx0, const void * restrict vx1, - const void * restrict vy0, const void * restrict vy1); - - void (*vec_dot_32x1)(const uint32_t n, float * restrict s, - const void * restrict vx, - const void * restrict vy, uint32_t valid_rows, - const float * restrict sz); - - void (*vec_dot_32x2)(const uint32_t n, float * restrict s0, float * restrict s1, - const void * restrict vx, - const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, - const float * restrict sz0, const float * restrict sz1); - - // Precomputed values - uint32_t src0_nrows_per_hvx; - uint32_t src0_row_start; - uint32_t src0_row_end; - uint32_t src0_row_size_padded; - uint32_t act_nrows; - uint32_t cur_m_start; - uint32_t cur_m_rows; - - struct fastdiv_values mm_div_ne12_ne1; - struct fastdiv_values mm_div_ne1; - struct fastdiv_values mm_div_r2; - struct fastdiv_values mm_div_r3; - struct fastdiv_values mm_div_ne11; - - // Precomputed block-parallel quantization values - uint32_t quant_ib_first[HTP_MAX_NHVX]; - uint32_t quant_ib_last[HTP_MAX_NHVX]; - uint32_t quant_r[HTP_MAX_NHVX]; - uint32_t quant_c[HTP_MAX_NHVX]; - uint32_t n_quant_tasks; - uint32_t n_quant_rows_per_hvx; - - // Fields for scattered mapping & HMX support in MUL_MAT_ID - const uint32_t * matrix_row_counts; - const struct mmid_row_mapping * matrix_rows; - uint32_t mapping_stride; - - // Dynamic VTCM pointers allocated sequentially - uint8_t * vtcm_src0; - uint8_t * vtcm_act; - uint8_t * vtcm_bias; - uint8_t * vtcm_dst; - uint8_t * vtcm_act_raw; - - // Cached strides - uint32_t vtcm_src0_stride; - uint32_t vtcm_act_stride; - uint32_t vtcm_act_raw_stride; - - // Cached thread offsets/sizes - uint32_t vtcm_src0_size_per_hvx; - uint32_t vtcm_act_size_per_hvx; - uint32_t vtcm_dst_size_per_hvx; -}; - static int htp_mm_init_context( struct htp_ops_context * octx, const struct htp_mm_kernel_params * kparams @@ -210,53 +129,48 @@ static inline void hvx_mm_iq2xxs_lut_init(uint8_t * restrict base, const struct iq2xxs_lut_copy(base + L->off_lut); } -#define htp_matmul_tensors_preamble \ - const struct htp_tensor * restrict src0 = octx->src[0]; \ - const struct htp_tensor * restrict src1 = octx->src[1]; \ - const struct htp_tensor * restrict src2 = octx->src[2]; \ - const struct htp_tensor * restrict dst = octx->dst; \ - const struct htp_tensor * restrict act = src1; \ - \ - const uint32_t ne00 = src0->ne[0]; \ - const uint32_t ne01 = src0->ne[1]; \ - const uint32_t ne02 = src0->ne[2]; \ - const uint32_t ne03 = src0->ne[3]; \ - \ - const uint32_t ne10 = src1->ne[0]; \ - const uint32_t ne11 = src1->ne[1]; \ - const uint32_t ne12 = src1->ne[2]; \ - const uint32_t ne13 = src1->ne[3]; \ - \ - const uint32_t ne20 = src2 ? src2->ne[0] : 0; \ - const uint32_t ne21 = src2 ? src2->ne[1] : 0; \ - const uint32_t ne22 = src2 ? src2->ne[2] : 0; \ - const uint32_t ne23 = src2 ? src2->ne[3] : 0; \ - \ - const uint32_t ne0 = dst->ne[0]; \ - const uint32_t ne1 = dst->ne[1]; \ - const uint32_t ne2 = dst->ne[2]; \ - const uint32_t ne3 = dst->ne[3]; \ - \ - const uint32_t nb00 = src0->nb[0]; \ - const uint32_t nb01 = src0->nb[1]; \ - const uint32_t nb02 = src0->nb[2]; \ - const uint32_t nb03 = src0->nb[3]; \ - \ - const uint32_t nb10 = src1->nb[0]; \ - const uint32_t nb11 = src1->nb[1]; \ - const uint32_t nb12 = src1->nb[2]; \ - const uint32_t nb13 = src1->nb[3]; \ - \ - const uint32_t nb0 = dst->nb[0]; \ - const uint32_t nb1 = dst->nb[1]; \ - const uint32_t nb2 = dst->nb[2]; \ - const uint32_t nb3 = dst->nb[3]; - -#define htp_matmul_preamble \ - struct htp_mm_context * mmctx = data; \ - struct htp_ops_context * octx = mmctx->octx; \ - dma_queue * dma_q = th->dma_q; \ - uint32_t src0_nrows_per_hvx = mmctx->src0_nrows_per_hvx; \ +#define htp_matmul_tensors_preamble \ + const struct htp_tensor * restrict __attribute__((unused)) src0 = octx->src[0]; \ + const struct htp_tensor * restrict __attribute__((unused)) src1 = octx->src[1]; \ + const struct htp_tensor * restrict __attribute__((unused)) bias = octx->src[2]; \ + const struct htp_tensor * restrict __attribute__((unused)) dst = octx->dst; \ + const struct htp_tensor * restrict __attribute__((unused)) act = src1; \ + \ + const uint32_t __attribute__((unused)) ne00 = src0->ne[0]; \ + const uint32_t __attribute__((unused)) ne01 = src0->ne[1]; \ + const uint32_t __attribute__((unused)) ne02 = src0->ne[2]; \ + const uint32_t __attribute__((unused)) ne03 = src0->ne[3]; \ + \ + const uint32_t __attribute__((unused)) ne10 = src1->ne[0]; \ + const uint32_t __attribute__((unused)) ne11 = src1->ne[1]; \ + const uint32_t __attribute__((unused)) ne12 = src1->ne[2]; \ + const uint32_t __attribute__((unused)) ne13 = src1->ne[3]; \ + \ + const uint32_t __attribute__((unused)) ne0 = dst->ne[0]; \ + const uint32_t __attribute__((unused)) ne1 = dst->ne[1]; \ + const uint32_t __attribute__((unused)) ne2 = dst->ne[2]; \ + const uint32_t __attribute__((unused)) ne3 = dst->ne[3]; \ + \ + const uint32_t __attribute__((unused)) nb00 = src0->nb[0]; \ + const uint32_t __attribute__((unused)) nb01 = src0->nb[1]; \ + const uint32_t __attribute__((unused)) nb02 = src0->nb[2]; \ + const uint32_t __attribute__((unused)) nb03 = src0->nb[3]; \ + \ + const uint32_t __attribute__((unused)) nb10 = src1->nb[0]; \ + const uint32_t __attribute__((unused)) nb11 = src1->nb[1]; \ + const uint32_t __attribute__((unused)) nb12 = src1->nb[2]; \ + const uint32_t __attribute__((unused)) nb13 = src1->nb[3]; \ + \ + const uint32_t __attribute__((unused)) nb0 = dst->nb[0]; \ + const uint32_t __attribute__((unused)) nb1 = dst->nb[1]; \ + const uint32_t __attribute__((unused)) nb2 = dst->nb[2]; \ + const uint32_t __attribute__((unused)) nb3 = dst->nb[3]; + +#define htp_matmul_preamble \ + struct htp_mm_context * mmctx = data; \ + struct htp_ops_context * octx = mmctx->octx; \ + dma_queue * __attribute__((unused)) dma_q = th->dma_q; \ + uint32_t __attribute__((unused)) src0_nrows_per_hvx = mmctx->src0_nrows_per_hvx; \ htp_matmul_tensors_preamble; @@ -265,12 +179,90 @@ static inline void hvx_mm_iq2xxs_lut_init(uint8_t * restrict base, const struct // hvx kernels first: the HMX Q6_K dequantizer reuses unpack_q6_k_group from there #include "hvx-mm-kernels-tiled.h" #include "hvx-mm-kernels-float.h" -#include "hmx-mm-kernels-tiled.h" +#include "hmx-mm-kernels-tiled-fp.h" +#include "hmx-mm-kernels-tiled-int.h" + +struct htp_mm_context { + const char * type; + struct htp_ops_context * octx; + const struct htp_tensor * act; + const int32_t * ids_data; + + void (*vec_dot_1x1)(const uint32_t n, void * restrict s0, + const void * restrict vx0, + const void * restrict vy0, hvx_flat_store_1x1_fn_t store_1x1); + + void (*vec_dot_2x1)(const uint32_t n, void * restrict s0, + const void * restrict vx0, const void * restrict vx1, + const void * restrict vy0, hvx_flat_store_2x1_fn_t store_2x1); + + void (*vec_dot_2x2)(const uint32_t n, void * restrict s0, void * restrict s1, + const void * restrict vx0, const void * restrict vx1, + const void * restrict vy0, const void * restrict vy1, hvx_flat_store_2x1_fn_t store_2x1); + + void (*vec_dot_32x1)(const uint32_t n, void * restrict s, + const void * restrict vx, + const void * restrict vy, uint32_t valid_rows, + const void * restrict sz, hvx_tiled_store_row_fn_t store_row); + + void (*vec_dot_32x2)(const uint32_t n, void * restrict s0, void * restrict s1, + const void * restrict vx, + const void * restrict vy0, const void * restrict vy1, uint32_t valid_rows, + const void * restrict sz0, const void * restrict sz1, hvx_tiled_store_row_fn_t store_row); + + hvx_tiled_store_row_fn_t store_row; + hvx_flat_store_1x1_fn_t flat_store_1x1; + hvx_flat_store_2x1_fn_t flat_store_2x1; + + // Precomputed values + uint32_t src0_nrows_per_hvx; + uint32_t src0_row_start; + uint32_t src0_row_end; + uint32_t src0_row_size_padded; + uint32_t act_nrows; + uint32_t cur_m_start; + uint32_t cur_m_rows; + + struct fastdiv_values mm_div_ne12_ne1; + struct fastdiv_values mm_div_ne1; + struct fastdiv_values mm_div_r2; + struct fastdiv_values mm_div_r3; + struct fastdiv_values mm_div_ne11; + + // Precomputed block-parallel quantization values + uint32_t quant_ib_first[HTP_MAX_NHVX]; + uint32_t quant_ib_last[HTP_MAX_NHVX]; + uint32_t quant_r[HTP_MAX_NHVX]; + uint32_t quant_c[HTP_MAX_NHVX]; + uint32_t n_quant_tasks; + uint32_t n_quant_rows_per_hvx; + + // Fields for scattered mapping & HMX support in MUL_MAT_ID + const uint32_t * matrix_row_counts; + const struct mmid_row_mapping * matrix_rows; + uint32_t mapping_stride; + + // Dynamic VTCM pointers allocated sequentially + uint8_t * vtcm_src0; + uint8_t * vtcm_act; + uint8_t * vtcm_bias; + uint8_t * vtcm_dst; + uint8_t * vtcm_act_raw; + + // Cached strides + uint32_t vtcm_src0_stride; + uint32_t vtcm_act_stride; + uint32_t vtcm_act_raw_stride; + + // Cached per-HVX VTCM sizes + uint32_t vtcm_src0_size_per_hvx; + uint32_t vtcm_act_size_per_hvx; + uint32_t vtcm_dst_size_per_hvx; +}; static void hvx_mm_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { htp_matmul_preamble; - const uint32_t src0_nrows = mmctx->src0_row_end - mmctx->src0_row_start; const uint32_t act_nrows = mmctx->cur_m_rows ? mmctx->cur_m_rows : (ne11 * ne12 * ne13); const uint32_t cur_m_start = mmctx->cur_m_start; @@ -282,11 +274,11 @@ static void hvx_mm_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params; const uint32_t n_prefetch = kparams->n_prefetch; assert(n_prefetch >= 2 && n_prefetch <= HTP_MM_MAX_PREFETCH && (n_prefetch & (n_prefetch - 1)) == 0); + (void) n_prefetch; const size_t dst_row_size = nb1; - const size_t act_row_size = nb11; const size_t act_stride = mmctx->vtcm_act_stride; - const size_t src2_stride = src2 ? ((src2->ne[1] == 1) ? 0 : src2->nb[1]) : 0; + const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); uint8_t * restrict vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith; uint8_t * restrict vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith; @@ -294,74 +286,55 @@ static void hvx_mm_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned const dma_addr_t src0_row = src0->data; - const uint32_t tile_size = htp_tensor_get_tile_size(src0->type); - const uint32_t aligned_tile_size = htp_tensor_get_tile_padded_size(src0->type); + const uint32_t tile_size = kparams->tile_size; + const uint32_t aligned_tile_size = kparams->aligned_tile_size; uint32_t n_k_tiles_w = ne00 / htp_tensor_get_tile_k(src0->type); uint32_t tile_row_stride = n_k_tiles_w * tile_size; - uint32_t tile_row_transfer_size_aligned = n_k_tiles_w * aligned_tile_size; uint32_t ct_start = src0_start_row / 32; uint32_t ct_end = (src0_end_row + 31) / 32; - uint32_t push_ct = ct_start; - if (src0_start_row < src0_end_row) { - for (uint32_t d = 0; d < n_prefetch && push_ct < ct_end; d++, push_ct++) { - dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + d * tile_row_transfer_size_aligned, - src0_row + push_ct * tile_row_stride), aligned_tile_size, tile_size, tile_size, n_k_tiles_w); - } - } - if (src0_start_row >= src0_end_row) { return; } + dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) ct_start * tile_row_stride), + aligned_tile_size, tile_size, tile_size, n_k_tiles_w); + for (uint32_t ct = ct_start; ct < ct_end; ct++) { const uint8_t * w_tile = (void *) dma_queue_pop(dma_q).dst; int valid_rows = (int)ne0 - (int)(ct * 32); valid_rows = MIN(32, MAX(0, valid_rows)); + const size_t ct_dst_off = (size_t) ct * 32 * dst_elem_size; + const size_t row_bytes = (size_t) valid_rows * dst_elem_size; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct); - uint32_t ir1 = 0; - for (; ir1 + 1 < act_nrows; ir1 += 2) { - const uint8_t * restrict act_col0 = (const uint8_t *) (act_data + (ir1+0) * act_stride); - const uint8_t * restrict act_col1 = (const uint8_t *) (act_data + (ir1+1) * act_stride); - float * restrict dst_row0 = (float *) (dst->data + ((cur_m_start + ir1+0) * dst_row_size)); - float * restrict dst_row1 = (float *) (dst->data + ((cur_m_start + ir1+1) * dst_row_size)); - - float * dst_ptr0 = &dst_row0[ct * 32]; - float * dst_ptr1 = &dst_row1[ct * 32]; - - const float * src2_ptr0 = NULL; - const float * src2_ptr1 = NULL; - if (src2) { - const float * restrict src2_row0 = (const float *) ((const uint8_t *) src2->data + ((cur_m_start + ir1+0) * src2_stride)); - const float * restrict src2_row1 = (const float *) ((const uint8_t *) src2->data + ((cur_m_start + ir1+1) * src2_stride)); - src2_ptr0 = &src2_row0[ct * 32]; - src2_ptr1 = &src2_row1[ct * 32]; + for (uint32_t m0 = 0; m0 < act_nrows; m0 += 32) { + const uint32_t m_cnt = MIN(32u, act_nrows - m0); + uint32_t r = 0; + for (; r + 1 < m_cnt; r += 2) { + const uint8_t * restrict act_col0 = (const uint8_t *) (act_data + (m0 + r + 0) * act_stride); + const uint8_t * restrict act_col1 = (const uint8_t *) (act_data + (m0 + r + 1) * act_stride); + void * dst_ptr0 = vtcm_dst_ptr + (size_t) (r + 0) * 128; + void * dst_ptr1 = vtcm_dst_ptr + (size_t) (r + 1) * 128; + mmctx->vec_dot_32x2(ne10, dst_ptr0, dst_ptr1, w_tile, act_col0, act_col1, valid_rows, NULL, NULL, mmctx->store_row); } - mmctx->vec_dot_32x2(ne10, dst_ptr0, dst_ptr1, w_tile, act_col0, act_col1, valid_rows, src2_ptr0, src2_ptr1); - } - - for (; ir1 < act_nrows; ++ir1) { - const uint8_t * restrict act_col = (const uint8_t *) (act_data + ir1 * act_stride); - float * restrict dst_row = (float *) (dst->data + ((cur_m_start + ir1) * dst_row_size)); - float * dst_ptr = &dst_row[ct * 32]; - - const float * src2_ptr = NULL; - if (src2) { - const float * restrict src2_row = (const float *) ((const uint8_t *) src2->data + ((cur_m_start + ir1) * src2_stride)); - src2_ptr = &src2_row[ct * 32]; + for (; r < m_cnt; ++r) { + const uint8_t * restrict act_col = (const uint8_t *) (act_data + (m0 + r) * act_stride); + void * dst_ptr = vtcm_dst_ptr + (size_t) r * 128; + mmctx->vec_dot_32x1(ne10, dst_ptr, w_tile, act_col, valid_rows, NULL, mmctx->store_row); } - mmctx->vec_dot_32x1(ne10, dst_ptr, w_tile, act_col, valid_rows, src2_ptr); + const dma_addr_t dst_addr = dst->data + (dma_addr_t) (cur_m_start + m0) * dst_row_size + ct_dst_off; + dma_queue_push(dma_q, dma_make_data(dst_addr, vtcm_dst_ptr), dst_row_size, 128, row_bytes, m_cnt); + dma_queue_pop(dma_q); } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct); - if (push_ct < ct_end) { - dma_queue_push(dma_q, dma_make_data(w_tile, src0_row + push_ct * tile_row_stride), + if (ct + 1 < ct_end) { + dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) (ct + 1) * tile_row_stride), aligned_tile_size, tile_size, tile_size, n_k_tiles_w); - push_ct++; } } } @@ -369,8 +342,6 @@ static void hvx_mm_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned static void hvx_mv_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { htp_matmul_preamble; - const uint32_t src0_nrows = mmctx->src0_row_end - mmctx->src0_row_start; - const uint32_t src0_start_row = mmctx->src0_row_start + src0_nrows_per_hvx * ith; const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, mmctx->src0_row_end); @@ -380,9 +351,8 @@ static void hvx_mv_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned const uint32_t n_prefetch = kparams->n_prefetch; assert(n_prefetch >= 2 && n_prefetch <= HTP_MM_MAX_PREFETCH && (n_prefetch & (n_prefetch - 1)) == 0); - const size_t dst_row_size = nb1; - const size_t act_row_size = nb11; - const size_t act_stride = mmctx->vtcm_act_stride; + const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const uint32_t bias_elem_size = (bias && bias->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); uint8_t * vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith; uint8_t * vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith; @@ -393,10 +363,9 @@ static void hvx_mv_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned const dma_addr_t src0_row = src0->data; const uint8_t * restrict act_col = (const uint8_t *) act_data; - float * restrict dst_col = (float *) dst->data; - const uint32_t tile_size = htp_tensor_get_tile_size(src0->type); - const uint32_t aligned_tile_size = htp_tensor_get_tile_padded_size(src0->type); + const uint32_t tile_size = kparams->tile_size; + const uint32_t aligned_tile_size = kparams->aligned_tile_size; uint32_t n_k_tiles_w = ne00 / htp_tensor_get_tile_k(src0->type); uint32_t tile_row_stride = n_k_tiles_w * tile_size; @@ -407,14 +376,15 @@ static void hvx_mv_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned uint32_t push_ct = ct_start; if (src0_start_row < src0_end_row) { - if (src2) { - float * vtcm_bias_ptr = (float *) mmctx->vtcm_bias + src0_start_row; - const dma_addr_t src2_addr = src2->data + src0_start_row * sizeof(float); + if (bias) { + uint8_t * vtcm_bias_ptr = mmctx->vtcm_bias + (size_t) src0_start_row * bias_elem_size; + const dma_addr_t bias_addr = bias->data + (size_t) src0_start_row * bias_elem_size; int slice_size = (int)MIN(src0_end_row, ne0) - (int)src0_start_row; if (slice_size > 0) { - dma_queue_push(dma_q, dma_make_data(vtcm_bias_ptr, src2_addr), - slice_size * sizeof(float), slice_size * sizeof(float), slice_size * sizeof(float), 1); - dma_queue_pop_nowait(dma_q); + const size_t slice_bytes = (size_t) slice_size * bias_elem_size; + dma_queue_push(dma_q, dma_make_data(vtcm_bias_ptr, bias_addr), + slice_bytes, slice_bytes, slice_bytes, 1); + dma_queue_pop(dma_q); } } for (uint32_t d = 0; d < n_prefetch && push_ct < ct_end; d++, push_ct++) { @@ -435,7 +405,7 @@ static void hvx_mv_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned valid_rows = MIN(32, MAX(0, valid_rows)); htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct); - mmctx->vec_dot_32x1(ne10, dst_ptr, w_tile, act_col, valid_rows, NULL); + mmctx->vec_dot_32x1(ne10, dst_ptr, w_tile, act_col, valid_rows, NULL, hvx_tiled_store_row_f32_none); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct); if (push_ct < ct_end) { @@ -448,15 +418,24 @@ static void hvx_mv_2d_tiled(const htp_thread_t * th, unsigned int nth, unsigned int copy_cnt = (int)MIN(src0_end_row, ne0) - (int)src0_start_row; if (copy_cnt > 0) { htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct_end); - if (src2) { - hvx_add_f32_uuu((uint8_t *) &dst_col[src0_start_row], - (const uint8_t *) tmp, - (const uint8_t *) ((const float *) mmctx->vtcm_bias + src0_start_row), - copy_cnt); - } else { - hvx_copy_f32_ua((uint8_t *) &dst_col[src0_start_row], (uint8_t *) tmp, copy_cnt); + const hvx_tiled_store_row_fn_t store_row = mmctx->store_row; + const uint8_t * bias_in = bias ? (mmctx->vtcm_bias + (size_t) src0_start_row * bias_elem_size) : NULL; + if (bias_in) { + for (int c = 0; c < copy_cnt; c += 32) { + const uint32_t valid_c = (uint32_t) MIN(32, copy_cnt - c); + HVX_Vector v_sum = *(const HVX_UVector *) (tmp + c); + store_row(vtcm_dst_ptr + (size_t) c * dst_elem_size, valid_c, v_sum, bias_in + (size_t) c * bias_elem_size); + } + } else if (dst_elem_size != sizeof(float)) { + for (int c = 0; c < copy_cnt; c += 32) { + const uint32_t valid_c = (uint32_t) MIN(32, copy_cnt - c); + HVX_Vector v_sum = *(const HVX_UVector *) (tmp + c); + store_row(vtcm_dst_ptr + (size_t) c * dst_elem_size, valid_c, v_sum, NULL); + } } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct_end); + dma_sync_write(dma_q, dst->data + (size_t) src0_start_row * dst_elem_size, + vtcm_dst_ptr, (size_t) copy_cnt * dst_elem_size); } } @@ -472,6 +451,7 @@ static void hvx_mm_nx_2d_tiled(const htp_thread_t * th, unsigned int nth, unsign const size_t act_stride = mmctx->vtcm_act_stride; uint8_t * restrict vtcm_weight_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith; + uint8_t * restrict vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith; uint8_t * restrict act_data = mmctx->vtcm_act; struct htp_thread_trace * tr = th->trace; @@ -484,11 +464,13 @@ static void hvx_mm_nx_2d_tiled(const htp_thread_t * th, unsigned int nth, unsign if (!src_w || !dst) continue; dma_queue * dma_q = th->dma_q; - const uint32_t tile_size = htp_tensor_get_tile_size(src_w->type); - const uint32_t aligned_tile_size = htp_tensor_get_tile_padded_size(src_w->type); + const uint32_t tile_size = kparams->tile_size; + const uint32_t aligned_tile_size = kparams->aligned_tile_size; const uint32_t ne00 = src_w->ne[0]; const uint32_t ne01 = src_w->ne[1]; const size_t dst_row_size = dst->nb[1]; + const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const hvx_tiled_store_row_fn_t store_row = resolve_hvx_tiled_store_row_fn(dst_elem_size, false, sizeof(float)); const dma_addr_t src_w_row = src_w->data; const uint32_t n_k_tiles_w = ne00 / htp_tensor_get_tile_k(src_w->type); @@ -498,8 +480,7 @@ static void hvx_mm_nx_2d_tiled(const htp_thread_t * th, unsigned int nth, unsign uint32_t src0_start_row = 0; uint32_t src0_end_row = ne01; if (octx->ctx->mdev.count > 1) { - const bool can_split = htp_tensor_can_row_partition(dst, sizeof(float)); - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(ne01, can_split ? 32 : 0, + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(ne01, 32, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); src0_start_row = range.start; src0_end_row = range.start + range.count; @@ -516,43 +497,68 @@ static void hvx_mm_nx_2d_tiled(const htp_thread_t * th, unsigned int nth, unsign uint32_t ct_start = start_row / 32; uint32_t ct_end = (end_row + 31) / 32; - uint32_t push_ct = ct_start; - for (uint32_t d = 0; d < n_prefetch && push_ct < ct_end; d++, push_ct++) { - dma_queue_push(dma_q, dma_make_data(vtcm_weight_ptr + d * tile_row_transfer_size_aligned, - src_w_row + push_ct * tile_row_stride), aligned_tile_size, tile_size, tile_size, n_k_tiles_w); - } - - for (uint32_t ct = ct_start; ct < ct_end; ct++) { - const uint8_t * w_tile = (void *) dma_queue_pop(dma_q).dst; - int valid_rows = (int)dst->ne[0] - (int)(ct * 32); - valid_rows = MIN(32, MAX(0, valid_rows)); + if (act_nrows == 1) { + uint32_t push_ct = ct_start; + for (uint32_t d = 0; d < n_prefetch && push_ct < ct_end; d++, push_ct++) { + dma_queue_push(dma_q, dma_make_data(vtcm_weight_ptr + d * tile_row_transfer_size_aligned, + src_w_row + (dma_addr_t) push_ct * tile_row_stride), aligned_tile_size, tile_size, tile_size, n_k_tiles_w); + } - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct); - uint32_t ir1 = 0; - for (; ir1 + 1 < act_nrows; ir1 += 2) { - const uint8_t * restrict act_col0 = (const uint8_t *) (act_data + (ir1+0) * act_stride); - const uint8_t * restrict act_col1 = (const uint8_t *) (act_data + (ir1+1) * act_stride); + for (uint32_t ct = ct_start; ct < ct_end; ct++) { + const uint8_t * w_tile = (void *) dma_queue_pop(dma_q).dst; + int valid_rows = (int)dst->ne[0] - (int)(ct * 32); + valid_rows = MIN(32, MAX(0, valid_rows)); - float * restrict dst_row0 = (float *) (dst->data + ((ir1+0) * dst_row_size)); - float * restrict dst_row1 = (float *) (dst->data + ((ir1+1) * dst_row_size)); - float * dst_ptr0 = &dst_row0[ct * 32]; - float * dst_ptr1 = &dst_row1[ct * 32]; + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct); + void * dst_ptr = vtcm_dst_ptr + (size_t) (ct - ct_start) * 32 * dst_elem_size; + mmctx->vec_dot_32x1(ne10, dst_ptr, w_tile, act_data, valid_rows, NULL, store_row); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct); - mmctx->vec_dot_32x2(ne10, dst_ptr0, dst_ptr1, w_tile, act_col0, act_col1, valid_rows, NULL, NULL); + if (push_ct < ct_end) { + dma_queue_push(dma_q, dma_make_data(w_tile, src_w_row + (dma_addr_t) push_ct * tile_row_stride), + aligned_tile_size, tile_size, tile_size, n_k_tiles_w); + push_ct++; + } } + const size_t copy_bytes = (size_t) (MIN(end_row, dst->ne[0]) - start_row) * dst_elem_size; + dma_sync_write(dma_q, dst->data + (size_t) start_row * dst_elem_size, vtcm_dst_ptr, copy_bytes); + } else { + dma_queue_push(dma_q, dma_make_data(vtcm_weight_ptr, src_w_row + (dma_addr_t) ct_start * tile_row_stride), + aligned_tile_size, tile_size, tile_size, n_k_tiles_w); - for (; ir1 < act_nrows; ++ir1) { - const uint8_t * restrict act_col = (const uint8_t *) (act_data + ir1 * act_stride); - float * restrict dst_row = (float *) (dst->data + (ir1 * dst_row_size)); - float * dst_ptr = &dst_row[ct * 32]; - mmctx->vec_dot_32x1(ne10, dst_ptr, w_tile, act_col, valid_rows, NULL); - } - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct); + for (uint32_t ct = ct_start; ct < ct_end; ct++) { + const uint8_t * w_tile = (void *) dma_queue_pop(dma_q).dst; + int valid_rows = (int)dst->ne[0] - (int)(ct * 32); + valid_rows = MIN(32, MAX(0, valid_rows)); + const size_t ct_dst_off = (size_t) ct * 32 * dst_elem_size; + const size_t row_bytes = (size_t) valid_rows * dst_elem_size; - if (push_ct < ct_end) { - dma_queue_push(dma_q, dma_make_data(w_tile, src_w_row + push_ct * tile_row_stride), - aligned_tile_size, tile_size, tile_size, n_k_tiles_w); - push_ct++; + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct); + for (uint32_t m0 = 0; m0 < act_nrows; m0 += 32) { + const uint32_t m_cnt = MIN(32u, act_nrows - m0); + uint32_t r = 0; + for (; r + 1 < m_cnt; r += 2) { + const uint8_t * restrict act_col0 = (const uint8_t *) (act_data + (m0 + r + 0) * act_stride); + const uint8_t * restrict act_col1 = (const uint8_t *) (act_data + (m0 + r + 1) * act_stride); + void * dst_ptr0 = vtcm_dst_ptr + (size_t) (r + 0) * 128; + void * dst_ptr1 = vtcm_dst_ptr + (size_t) (r + 1) * 128; + mmctx->vec_dot_32x2(ne10, dst_ptr0, dst_ptr1, w_tile, act_col0, act_col1, valid_rows, NULL, NULL, store_row); + } + for (; r < m_cnt; ++r) { + const uint8_t * restrict act_col = (const uint8_t *) (act_data + (m0 + r) * act_stride); + void * dst_ptr = vtcm_dst_ptr + (size_t) r * 128; + mmctx->vec_dot_32x1(ne10, dst_ptr, w_tile, act_col, valid_rows, NULL, store_row); + } + const dma_addr_t dst_addr = dst->data + (dma_addr_t) m0 * dst_row_size + ct_dst_off; + dma_queue_push(dma_q, dma_make_data(dst_addr, vtcm_dst_ptr), dst_row_size, 128, row_bytes, m_cnt); + dma_queue_pop(dma_q); + } + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct); + + if (ct + 1 < ct_end) { + dma_queue_push(dma_q, dma_make_data(vtcm_weight_ptr, src_w_row + (dma_addr_t) (ct + 1) * tile_row_stride), + aligned_tile_size, tile_size, tile_size, n_k_tiles_w); + } } } } @@ -588,21 +594,12 @@ static void hvx_mm_transfer_act_dma( dma_queue_pop(dma_q); } else { const uint32_t ne12_ne1 = act->ne[2] * act->ne[1]; - const bool use_fastdiv = kparams->div_ne12_ne1.mp != 0; for (uint32_t ir = 0; ir < m_rows; ++ir) { const uint32_t ir1 = m_start + ir; - uint32_t i11, i12, i13; - if (use_fastdiv) { - i13 = fastdiv(ir1, &kparams->div_ne12_ne1); - const uint32_t rem = ir1 - i13 * ne12_ne1; - i12 = fastdiv(rem, &kparams->div_ne1); - i11 = rem - i12 * act->ne[1]; - } else { - i13 = ne12_ne1 ? ir1 / ne12_ne1 : 0; - const uint32_t rem = ir1 - i13 * ne12_ne1; - i12 = act->ne[1] ? rem / act->ne[1] : 0; - i11 = rem - i12 * act->ne[1]; - } + const uint32_t i13 = fastdiv(ir1, &kparams->div_ne12_ne1); + const uint32_t rem = ir1 - i13 * ne12_ne1; + const uint32_t i12 = fastdiv(rem, &kparams->div_ne1); + const uint32_t i11 = rem - i12 * act->ne[1]; const dma_addr_t row_src = act_base + (i11 * act->nb[1] + i12 * act->nb[2] + i13 * act->nb[3]); @@ -634,7 +631,6 @@ static void hvx_mm_transfer_act_dma( static void name(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { \ (void) nth; \ struct htp_mm_context * mmctx = data; \ - struct htp_ops_context * octx = mmctx->octx; \ const struct htp_tensor * src = mmctx->act; \ const uint32_t ne0 = src->ne[0]; \ const uint32_t nrows = mmctx->cur_m_rows ? mmctx->cur_m_rows : mmctx->act_nrows; \ @@ -663,9 +659,12 @@ static void name(const htp_thread_t * th, unsigned int nth, unsigned int ith, vo QUANTIZE_IMPL(quantize_f32_q8_0_tiled, "quantize-f32-q8_0_tiled", quantize_f32_q8_0_tiled_kernel, htp_mm_q8_0_tiled_row_size(ne0)) QUANTIZE_IMPL(quantize_f32_q8_1_tiled, "quantize-f32-q8_1_tiled", quantize_f32_q8_1_tiled_kernel, htp_mm_q8_1_tiled_row_size(ne0)) QUANTIZE_IMPL(quantize_f32_q8_1_s16_tiled, "quantize-f32-q8_1_s16_tiled", quantize_f32_q8_1_s16_tiled_kernel, htp_mm_q8_1_tiled_row_size(ne0)) +QUANTIZE_IMPL(quantize_f16_q8_0_tiled, "quantize-f16-q8_0_tiled", quantize_f16_q8_0_tiled_kernel, htp_mm_q8_0_tiled_row_size(ne0)) +QUANTIZE_IMPL(quantize_f16_q8_1_tiled, "quantize-f16-q8_1_tiled", quantize_f16_q8_1_tiled_kernel, htp_mm_q8_1_tiled_row_size(ne0)) +QUANTIZE_IMPL(quantize_f16_q8_1_s16_tiled, "quantize-f16-q8_1_s16_tiled", quantize_f16_q8_1_s16_tiled_kernel, htp_mm_q8_1_tiled_row_size(ne0)) QUANTIZE_IMPL(quantize_f32_f16_tiled, "quantize-f32-f16_tiled", quantize_f32_f16_tiled_kernel, htp_mm_f16_tiled_row_size(ne0)) QUANTIZE_IMPL(quantize_f16_f16_tiled, "quantize-f16-f16_tiled", quantize_f16_f16_tiled_kernel, htp_mm_f16_tiled_row_size(ne0)) -QUANTIZE_IMPL(quantize_f32_f32, "quantize-f32-f32", quantize_f32_f32_kernel, mmctx->vtcm_act_stride) +QUANTIZE_IMPL(quantize_f16_f32, "quantize-f16-f32", quantize_f16_f32_kernel, mmctx->vtcm_act_stride) QUANTIZE_IMPL(quantize_f32_f16, "quantize-f32-f16", quantize_f32_f16_kernel, mmctx->vtcm_act_stride) QUANTIZE_IMPL(quantize_f16_f16, "quantize-f16-f16", quantize_f16_f16_kernel, mmctx->vtcm_act_stride) @@ -675,7 +674,6 @@ static void quantize_f32_q8_0_tiled_block(const htp_thread_t * th, unsigned int if (mmctx->quant_ib_first[ith] >= mmctx->quant_ib_last[ith]) { return; } - struct htp_ops_context * octx = mmctx->octx; struct htp_thread_trace * tr = th->trace; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]); @@ -703,7 +701,6 @@ static void quantize_f32_q8_1_tiled_block(const htp_thread_t * th, unsigned int if (mmctx->quant_ib_first[ith] >= mmctx->quant_ib_last[ith]) { return; } - struct htp_ops_context * octx = mmctx->octx; struct htp_thread_trace * tr = th->trace; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]); @@ -731,7 +728,6 @@ static void quantize_f32_q8_1_s16_tiled_block(const htp_thread_t * th, unsigned if (mmctx->quant_ib_first[ith] >= mmctx->quant_ib_last[ith]) { return; } - struct htp_ops_context * octx = mmctx->octx; struct htp_thread_trace * tr = th->trace; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]); @@ -759,7 +755,6 @@ static void quantize_f32_f16_tiled_block(const htp_thread_t * th, unsigned int n if (mmctx->quant_ib_first[ith] >= mmctx->quant_ib_last[ith]) { return; } - struct htp_ops_context * octx = mmctx->octx; struct htp_thread_trace * tr = th->trace; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]); @@ -787,7 +782,6 @@ static void quantize_f16_f16_tiled_block(const htp_thread_t * th, unsigned int n if (mmctx->quant_ib_first[ith] >= mmctx->quant_ib_last[ith]) { return; } - struct htp_ops_context * octx = mmctx->octx; struct htp_thread_trace * tr = th->trace; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]); @@ -809,55 +803,144 @@ static void quantize_f16_f16_tiled_block(const htp_thread_t * th, unsigned int n htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]); } -// q8_1 for weight types with offsets (q8_1_s16 for Q2_K), f16_tiled for F16, otherwise q8_0 -static inline work_queue_func_t htp_mm_act_quant_row_func(int weight_type, int act_type) { - if (weight_type == HTP_TYPE_F16) { - return (act_type == HTP_TYPE_F16) ? quantize_f16_f16_tiled : quantize_f32_f16_tiled; - } - if (weight_type == HTP_TYPE_Q2_K) { - return quantize_f32_q8_1_s16_tiled; - } - return htp_mm_weight_has_offset(weight_type) ? quantize_f32_q8_1_tiled : quantize_f32_q8_0_tiled; -} - -static inline work_queue_func_t htp_mm_act_quant_block_func(int weight_type, int act_type) { - if (weight_type == HTP_TYPE_F16) { - return (act_type == HTP_TYPE_F16) ? quantize_f16_f16_tiled_block : quantize_f32_f16_tiled_block; - } - if (weight_type == HTP_TYPE_Q2_K) { - return quantize_f32_q8_1_s16_tiled_block; +static void quantize_f16_q8_0_tiled_block(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; + struct htp_mm_context * mmctx = data; + if (mmctx->quant_ib_first[ith] >= mmctx->quant_ib_last[ith]) { + return; } - return htp_mm_weight_has_offset(weight_type) ? quantize_f32_q8_1_tiled_block : quantize_f32_q8_0_tiled_block; -} + struct htp_thread_trace * tr = th->trace; + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]); -static void hvx_mm_4d_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { - htp_matmul_preamble; + const struct htp_tensor * src = mmctx->act; - const uint32_t src0_nrows = mmctx->src0_row_end - mmctx->src0_row_start; - const uint32_t cur_m_rows = mmctx->cur_m_rows ? mmctx->cur_m_rows : (ne11 * ne12 * ne13); - const uint32_t cur_m_start = mmctx->cur_m_start; + quantize_f16_q8_0_tiled_block_kernel( + (const __fp16 *) mmctx->vtcm_act_raw, + mmctx->vtcm_act, + NULL, + src->ne[0], + mmctx->quant_ib_first[ith], + mmctx->quant_ib_last[ith], + mmctx->vtcm_act_raw_stride, + htp_mm_q8_0_tiled_row_size(src->ne[0]), + mmctx->quant_r[ith], + mmctx->quant_c[ith] + ); - const uint32_t src0_start_row = mmctx->src0_row_start + src0_nrows_per_hvx * ith; - const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, mmctx->src0_row_end); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]); +} +static void quantize_f16_q8_1_tiled_block(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; + struct htp_mm_context * mmctx = data; + if (mmctx->quant_ib_first[ith] >= mmctx->quant_ib_last[ith]) { + return; + } struct htp_thread_trace * tr = th->trace; + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]); - const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params; - const uint32_t n_prefetch = kparams->n_prefetch; - assert(n_prefetch >= 2 && n_prefetch <= HTP_MM_MAX_PREFETCH && (n_prefetch & (n_prefetch - 1)) == 0); - - const size_t dst_row_size = nb1; - const size_t act_stride = mmctx->vtcm_act_stride; - - uint8_t * restrict vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith; - uint8_t * restrict act_data = mmctx->vtcm_act; - - const uint32_t tile_size = htp_tensor_get_tile_size(src0->type); - const uint32_t aligned_tile_size = htp_tensor_get_tile_padded_size(src0->type); + const struct htp_tensor * src = mmctx->act; - const uint32_t n_k_tiles_w = ne00 / htp_tensor_get_tile_k(src0->type); - const uint32_t tile_row_stride = n_k_tiles_w * tile_size; - const uint32_t tile_row_transfer_size_aligned = n_k_tiles_w * aligned_tile_size; + quantize_f16_q8_1_tiled_block_kernel( + (const __fp16 *) mmctx->vtcm_act_raw, + mmctx->vtcm_act, + NULL, + src->ne[0], + mmctx->quant_ib_first[ith], + mmctx->quant_ib_last[ith], + mmctx->vtcm_act_raw_stride, + htp_mm_q8_1_tiled_row_size(src->ne[0]), + mmctx->quant_r[ith], + mmctx->quant_c[ith] + ); + + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]); +} + +static void quantize_f16_q8_1_s16_tiled_block(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; + struct htp_mm_context * mmctx = data; + if (mmctx->quant_ib_first[ith] >= mmctx->quant_ib_last[ith]) { + return; + } + struct htp_thread_trace * tr = th->trace; + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]); + + const struct htp_tensor * src = mmctx->act; + + quantize_f16_q8_1_s16_tiled_block_kernel( + (const __fp16 *) mmctx->vtcm_act_raw, + mmctx->vtcm_act, + NULL, + src->ne[0], + mmctx->quant_ib_first[ith], + mmctx->quant_ib_last[ith], + mmctx->vtcm_act_raw_stride, + htp_mm_q8_1_tiled_row_size(src->ne[0]), + mmctx->quant_r[ith], + mmctx->quant_c[ith] + ); + + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_QUANT, mmctx->quant_ib_first[ith]); +} + +// q8_1 for weight types with offsets (q8_1_s16 for Q2_K), f16_tiled for F16, otherwise q8_0 +static inline work_queue_func_t htp_mm_act_quant_row_func(int weight_type, int act_type) { + const bool act_f16 = (act_type == HTP_TYPE_F16); + if (weight_type == HTP_TYPE_F16) { + return act_f16 ? quantize_f16_f16_tiled : quantize_f32_f16_tiled; + } + if (weight_type == HTP_TYPE_Q2_K) { + return act_f16 ? quantize_f16_q8_1_s16_tiled : quantize_f32_q8_1_s16_tiled; + } + if (htp_mm_weight_has_offset(weight_type)) { + return act_f16 ? quantize_f16_q8_1_tiled : quantize_f32_q8_1_tiled; + } + return act_f16 ? quantize_f16_q8_0_tiled : quantize_f32_q8_0_tiled; +} + +static inline work_queue_func_t htp_mm_act_quant_block_func(int weight_type, int act_type) { + const bool act_f16 = (act_type == HTP_TYPE_F16); + if (weight_type == HTP_TYPE_F16) { + return act_f16 ? quantize_f16_f16_tiled_block : quantize_f32_f16_tiled_block; + } + if (weight_type == HTP_TYPE_Q2_K) { + return act_f16 ? quantize_f16_q8_1_s16_tiled_block : quantize_f32_q8_1_s16_tiled_block; + } + if (htp_mm_weight_has_offset(weight_type)) { + return act_f16 ? quantize_f16_q8_1_tiled_block : quantize_f32_q8_1_tiled_block; + } + return act_f16 ? quantize_f16_q8_0_tiled_block : quantize_f32_q8_0_tiled_block; +} + +static void hvx_mm_4d_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + htp_matmul_preamble; + + const uint32_t cur_m_rows = mmctx->cur_m_rows ? mmctx->cur_m_rows : (ne11 * ne12 * ne13); + const uint32_t cur_m_start = mmctx->cur_m_start; + + const uint32_t src0_start_row = mmctx->src0_row_start + src0_nrows_per_hvx * ith; + const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, mmctx->src0_row_end); + + struct htp_thread_trace * tr = th->trace; + + const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params; + const uint32_t n_prefetch = kparams->n_prefetch; + assert(n_prefetch >= 2 && n_prefetch <= HTP_MM_MAX_PREFETCH && (n_prefetch & (n_prefetch - 1)) == 0); + (void) n_prefetch; + + const size_t dst_row_size = nb1; + const size_t act_stride = mmctx->vtcm_act_stride; + const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + + uint8_t * restrict vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith; + uint8_t * restrict act_data = mmctx->vtcm_act; + + const uint32_t tile_size = kparams->tile_size; + const uint32_t aligned_tile_size = kparams->aligned_tile_size; + + const uint32_t n_k_tiles_w = ne00 / htp_tensor_get_tile_k(src0->type); + const uint32_t tile_row_stride = n_k_tiles_w * tile_size; const uint32_t src0_slice_stride = ((ne01 + 31) / 32) * tile_row_stride; const uint32_t ct_start = src0_start_row / 32; @@ -892,20 +975,20 @@ static void hvx_mm_4d_tiled(const htp_thread_t * th, unsigned int nth, unsigned } const uint32_t slice_idx = i03 * ne02 + i02; - const dma_addr_t src0_slice = src0->data + (size_t) slice_idx * src0_slice_stride; + const dma_addr_t src0_slice = src0->data + (dma_addr_t) slice_idx * src0_slice_stride; - uint32_t push_ct = ct_start; - for (uint32_t d = 0; d < n_prefetch && push_ct < ct_end; d++, push_ct++) { - dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + d * tile_row_transfer_size_aligned, - src0_slice + (size_t) push_ct * tile_row_stride), - aligned_tile_size, tile_size, tile_size, n_k_tiles_w); - } + uint8_t * restrict vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith; + + dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_slice + (dma_addr_t) ct_start * tile_row_stride), + aligned_tile_size, tile_size, tile_size, n_k_tiles_w); for (uint32_t ct = ct_start; ct < ct_end; ct++) { const uint8_t * w_tile = (void *) dma_queue_pop(dma_q).dst; int valid_rows = (int)ne0 - (int)(ct * 32); valid_rows = MIN(32, MAX(0, valid_rows)); + const size_t ct_dst_off = (size_t) ct * 32 * dst_elem_size; + const size_t row_bytes = (size_t) valid_rows * dst_elem_size; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct); for (uint32_t b = b_grp_start; b < b_grp_end; b++) { @@ -916,42 +999,41 @@ static void hvx_mm_4d_tiled(const htp_thread_t * th, unsigned int nth, unsigned const uint32_t cur_b3 = fastdiv(b, &kparams->div_ne12); const uint32_t cur_b2 = b - cur_b3 * ne12; - uint8_t * dst_batch_base = (uint8_t *) dst->data + (size_t) cur_b2 * nb2 + (size_t) cur_b3 * nb3; + const dma_addr_t dst_batch_base = dst->data + (dma_addr_t) cur_b2 * nb2 + (dma_addr_t) cur_b3 * nb3; const uint32_t chunk_m_offset = m_first - cur_m_start; const uint32_t dst_m_offset = m_first - b_m_start; const uint32_t batch_nrows = m_last - m_first; - uint32_t ir1 = 0; - for (; ir1 + 1 < batch_nrows; ir1 += 2) { - const uint8_t * restrict act_col0 = (const uint8_t *) (act_data + (chunk_m_offset + ir1 + 0) * act_stride); - const uint8_t * restrict act_col1 = (const uint8_t *) (act_data + (chunk_m_offset + ir1 + 1) * act_stride); - float * restrict dst_row0 = (float *) (dst_batch_base + (dst_m_offset + ir1 + 0) * dst_row_size); - float * restrict dst_row1 = (float *) (dst_batch_base + (dst_m_offset + ir1 + 1) * dst_row_size); - float * dst_ptr0 = &dst_row0[ct * 32]; - float * dst_ptr1 = &dst_row1[ct * 32]; - mmctx->vec_dot_32x2(ne10, dst_ptr0, dst_ptr1, w_tile, act_col0, act_col1, valid_rows, NULL, NULL); - } - for (; ir1 < batch_nrows; ++ir1) { - const uint8_t * restrict act_col = (const uint8_t *) (act_data + (chunk_m_offset + ir1) * act_stride); - float * restrict dst_row = (float *) (dst_batch_base + (dst_m_offset + ir1) * dst_row_size); - float * dst_ptr = &dst_row[ct * 32]; - mmctx->vec_dot_32x1(ne10, dst_ptr, w_tile, act_col, valid_rows, NULL); + for (uint32_t m0 = 0; m0 < batch_nrows; m0 += 32) { + const uint32_t m_cnt = MIN(32u, batch_nrows - m0); + uint32_t r = 0; + for (; r + 1 < m_cnt; r += 2) { + const uint8_t * restrict act_col0 = (const uint8_t *) (act_data + (chunk_m_offset + m0 + r + 0) * act_stride); + const uint8_t * restrict act_col1 = (const uint8_t *) (act_data + (chunk_m_offset + m0 + r + 1) * act_stride); + void * dst_ptr0 = vtcm_dst_ptr + (size_t) (r + 0) * 128; + void * dst_ptr1 = vtcm_dst_ptr + (size_t) (r + 1) * 128; + mmctx->vec_dot_32x2(ne10, dst_ptr0, dst_ptr1, w_tile, act_col0, act_col1, valid_rows, NULL, NULL, mmctx->store_row); + } + for (; r < m_cnt; ++r) { + const uint8_t * restrict act_col = (const uint8_t *) (act_data + (chunk_m_offset + m0 + r) * act_stride); + void * dst_ptr = vtcm_dst_ptr + (size_t) r * 128; + mmctx->vec_dot_32x1(ne10, dst_ptr, w_tile, act_col, valid_rows, NULL, mmctx->store_row); + } + const dma_addr_t dst_addr = dst_batch_base + (dma_addr_t) (dst_m_offset + m0) * dst_row_size + ct_dst_off; + dma_queue_push(dma_q, dma_make_data(dst_addr, vtcm_dst_ptr), dst_row_size, 128, row_bytes, m_cnt); + dma_queue_pop(dma_q); } } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct); - if (push_ct < ct_end) { - dma_queue_push(dma_q, dma_make_data(w_tile, src0_slice + (size_t) push_ct * tile_row_stride), + if (ct + 1 < ct_end) { + dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_slice + (dma_addr_t) (ct + 1) * tile_row_stride), aligned_tile_size, tile_size, tile_size, n_k_tiles_w); - push_ct++; } } b_grp_start = b_grp_end; } - if (src2) { - hvx_tensor_add_f32_grid(dst, src2, cur_m_start, cur_m_start + cur_m_rows, src0_start_row, src0_end_row, &kparams->div_ne12_ne1, &kparams->div_ne1); - } } static void hvx_mm_2d_flat(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { @@ -960,9 +1042,8 @@ static void hvx_mm_2d_flat(const htp_thread_t * th, unsigned int nth, unsigned i const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params; const uint32_t n_prefetch = kparams->n_prefetch; assert(n_prefetch >= 2 && n_prefetch <= HTP_MM_MAX_PREFETCH && (n_prefetch & (n_prefetch - 1)) == 0); - const uint32_t prefetch_mask = n_prefetch - 1; + (void) n_prefetch; - const uint32_t src0_nrows = mmctx->src0_row_end - mmctx->src0_row_start; // src0 rows const uint32_t act_nrows = mmctx->cur_m_rows ? mmctx->cur_m_rows : mmctx->act_nrows; const uint32_t cur_m_start = mmctx->cur_m_start; @@ -974,12 +1055,12 @@ static void hvx_mm_2d_flat(const htp_thread_t * th, unsigned int nth, unsigned i const size_t dst_row_size = nb1; const size_t src0_row_size = nb01; - const size_t act_row_size = nb11; + const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); const size_t src0_stride = mmctx->vtcm_src0_stride; const size_t act_stride = mmctx->vtcm_act_stride; - // Per-thread VTCMs for all tensors + // Per-HVX VTCMs for all tensors uint8_t * restrict vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith; uint8_t * restrict vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith; uint8_t * restrict act_data = mmctx->vtcm_act; @@ -987,94 +1068,87 @@ static void hvx_mm_2d_flat(const htp_thread_t * th, unsigned int nth, unsigned i const dma_addr_t src0_row = src0->data; - // Prefill vtcm with src0 rows - if (src0_start_row < src0_end_row) { - for (uint32_t ir0 = src0_start_row; ir0 < src0_end_row_x2; ir0 += 2) { - const int is0 = (ir0 - src0_start_row); - if (is0 >= (int)n_prefetch) { - break; - } - dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + is0 * src0_stride, src0_row + ir0 * src0_row_size), - src0_stride, src0_row_size, src0_row_size, 2); - } - } - if (src0_start_row >= src0_end_row) { return; } + if (src0_start_row < src0_end_row_x2) { + dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) src0_start_row * src0_row_size), + src0_stride, src0_row_size, src0_row_size, 2); + } + // Process src0 rows for (uint32_t ir0 = src0_start_row; ir0 < src0_end_row_x2; ir0 += 2) { const uint8_t * ss0 = (void *) dma_queue_pop(dma_q).dst; + const size_t ir0_dst_off = (size_t) ir0 * dst_elem_size; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir0); - // Process act columns in pairs (2x2 tiling) - uint32_t ir1 = 0; - for (; ir1 + 1 < act_nrows; ir1 += 2) { - const uint8_t * restrict act_col0 = (const uint8_t *) (act_data + (ir1+0) * act_stride); - const uint8_t * restrict act_col1 = (const uint8_t *) (act_data + (ir1+1) * act_stride); - float * restrict dst_row0 = (float *) (dst->data + ((cur_m_start + ir1+0) * dst_row_size)); - float * restrict dst_row1 = (float *) (dst->data + ((cur_m_start + ir1+1) * dst_row_size)); - mmctx->vec_dot_2x2(ne00, &dst_row0[ir0], &dst_row1[ir0], ss0, ss0 + src0_stride, act_col0, act_col1); - } - - // Handle remaining act rows (fallback to 2x1) - for (; ir1 < act_nrows; ++ir1) { - const uint8_t * restrict act_col = (const uint8_t *) (act_data + ir1 * act_stride); - float * restrict dst_row = (float *) (dst->data + ((cur_m_start + ir1) * dst_row_size)); - mmctx->vec_dot_2x1(ne00, &dst_row[ir0], ss0, ss0 + src0_stride, act_col); + for (uint32_t m0 = 0; m0 < act_nrows; m0 += 32) { + const uint32_t m_cnt = MIN(32u, act_nrows - m0); + uint32_t r = 0; + for (; r + 1 < m_cnt; r += 2) { + const uint8_t * restrict act_col0 = (const uint8_t *) (act_data + (m0 + r + 0) * act_stride); + const uint8_t * restrict act_col1 = (const uint8_t *) (act_data + (m0 + r + 1) * act_stride); + void * dst_ptr0 = vtcm_dst_ptr + (size_t) (r + 0) * 16; + void * dst_ptr1 = vtcm_dst_ptr + (size_t) (r + 1) * 16; + mmctx->vec_dot_2x2(ne00, dst_ptr0, dst_ptr1, ss0, ss0 + src0_stride, act_col0, act_col1, mmctx->flat_store_2x1); + } + for (; r < m_cnt; ++r) { + const uint8_t * restrict act_col = (const uint8_t *) (act_data + (m0 + r) * act_stride); + void * dst_ptr = vtcm_dst_ptr + (size_t) r * 16; + mmctx->vec_dot_2x1(ne00, dst_ptr, ss0, ss0 + src0_stride, act_col, mmctx->flat_store_2x1); + } + const dma_addr_t dst_addr = dst->data + (dma_addr_t) (cur_m_start + m0) * dst_row_size + ir0_dst_off; + dma_queue_push(dma_q, dma_make_data(dst_addr, vtcm_dst_ptr), dst_row_size, 16, 2u * dst_elem_size, m_cnt); + dma_queue_pop(dma_q); } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir0); - // Prefetch next (n + vtcm_nrows) row - const int pr0 = (ir0 + n_prefetch); - const int is0 = (pr0 - src0_start_row) & prefetch_mask; - if (pr0 < src0_end_row_x2) { - dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + is0 * src0_stride, src0_row + pr0 * src0_row_size), + if (ir0 + 2 < src0_end_row_x2) { + dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) (ir0 + 2) * src0_row_size), src0_stride, src0_row_size, src0_row_size, 2); } } // Process the last row (if any) if (src0_end_row != src0_end_row_x2) { - uint32_t ir0 = src0_end_row_x2; - const int is0 = (ir0 - src0_start_row) & prefetch_mask; - dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + is0 * src0_stride, src0_row + ir0 * src0_row_size), + const uint32_t ir0 = src0_end_row_x2; + const size_t ir0_dst_off = (size_t) ir0 * dst_elem_size; + dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) ir0 * src0_row_size), src0_stride, src0_row_size, src0_row_size, 1); const uint8_t * ss0 = (void *) dma_queue_pop(dma_q).dst; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir0); - #pragma unroll(2) - for (uint32_t ir1 = 0; ir1 < act_nrows; ++ir1) { - const uint8_t * restrict act_col = (const uint8_t *) (act_data + ir1 * act_stride); - float * restrict dst_row = (float *) (dst->data + ((cur_m_start + ir1) * dst_row_size)); - mmctx->vec_dot_1x1(ne00, &dst_row[ir0], ss0, act_col); + for (uint32_t m0 = 0; m0 < act_nrows; m0 += 32) { + const uint32_t m_cnt = MIN(32u, act_nrows - m0); + for (uint32_t r = 0; r < m_cnt; ++r) { + const uint8_t * restrict act_col = (const uint8_t *) (act_data + (m0 + r) * act_stride); + void * dst_ptr = vtcm_dst_ptr + (size_t) r * 16; + mmctx->vec_dot_1x1(ne00, dst_ptr, ss0, act_col, mmctx->flat_store_1x1); + } + const dma_addr_t dst_addr = dst->data + (dma_addr_t) (cur_m_start + m0) * dst_row_size + ir0_dst_off; + dma_queue_push(dma_q, dma_make_data(dst_addr, vtcm_dst_ptr), dst_row_size, 16, dst_elem_size, m_cnt); + dma_queue_pop(dma_q); } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir0); } - if (src2) { - hvx_tensor_add_f32_grid(dst, src2, cur_m_start, cur_m_start + act_nrows, src0_start_row, src0_end_row, &kparams->div_ne12_ne1, &kparams->div_ne1); - } } static void hvx_mv_2d_flat(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { htp_matmul_preamble; - const uint32_t src0_nrows = mmctx->src0_row_end - mmctx->src0_row_start; - const uint32_t src0_start_row = mmctx->src0_row_start + src0_nrows_per_hvx * ith; const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, mmctx->src0_row_end); struct htp_thread_trace * tr = th->trace; - const size_t dst_row_size = nb1; const size_t src0_row_size = nb01; - const size_t act_row_size = nb11; + const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const uint32_t bias_elem_size = (bias && bias->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); const size_t src0_stride = mmctx->vtcm_src0_stride; - const size_t act_stride = mmctx->vtcm_act_stride; - // Per-thread VTCMs for all tensors + // Per-HVX VTCMs for all tensors uint8_t * vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith; uint8_t * vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith; uint8_t * act_data = mmctx->vtcm_act; @@ -1083,7 +1157,6 @@ static void hvx_mv_2d_flat(const htp_thread_t * th, unsigned int nth, unsigned i const dma_addr_t src0_row = src0->data; const uint8_t * restrict act_col = (const uint8_t *) act_data; - float * restrict dst_col = (float *) dst->data; const uint32_t src0_end_row_x2 = src0_start_row + ((src0_end_row - src0_start_row) & ~1U); @@ -1094,14 +1167,15 @@ static void hvx_mv_2d_flat(const htp_thread_t * th, unsigned int nth, unsigned i // Prefill vtcm with 2x src0 rows if (src0_start_row < src0_end_row) { - if (src2) { - float * vtcm_bias_ptr = (float *) mmctx->vtcm_bias + src0_start_row; - const dma_addr_t src2_addr = src2->data + src0_start_row * sizeof(float); + if (bias) { + uint8_t * vtcm_bias_ptr = mmctx->vtcm_bias + (size_t) src0_start_row * bias_elem_size; + const dma_addr_t bias_addr = bias->data + (size_t) src0_start_row * bias_elem_size; int slice_size = (int)src0_end_row - (int)src0_start_row; if (slice_size > 0) { - dma_queue_push(dma_q, dma_make_data(vtcm_bias_ptr, src2_addr), - slice_size * sizeof(float), slice_size * sizeof(float), slice_size * sizeof(float), 1); - dma_queue_pop_nowait(dma_q); + const size_t slice_bytes = (size_t) slice_size * bias_elem_size; + dma_queue_push(dma_q, dma_make_data(vtcm_bias_ptr, bias_addr), + slice_bytes, slice_bytes, slice_bytes, 1); + dma_queue_pop(dma_q); } } for (uint32_t ir0 = src0_start_row; ir0 < src0_end_row_x2; ir0 += 2) { @@ -1123,7 +1197,7 @@ static void hvx_mv_2d_flat(const htp_thread_t * th, unsigned int nth, unsigned i for (uint32_t ir0 = src0_start_row; ir0 < src0_end_row_x2; ir0 += 2) { const uint8_t * ss0 = (void *) dma_queue_pop(dma_q).dst; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir0); - mmctx->vec_dot_2x1(ne00, &tmp[ir0 - src0_start_row], ss0, ss0 + src0_stride, act_col); + mmctx->vec_dot_2x1(ne00, &tmp[ir0 - src0_start_row], ss0, ss0 + src0_stride, act_col, hvx_flat_store_2x1_f32); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir0); // Prefetch next (n + vtcm_nrows) row @@ -1143,22 +1217,31 @@ static void hvx_mv_2d_flat(const htp_thread_t * th, unsigned int nth, unsigned i src0_stride, src0_row_size, src0_row_size, 1); const uint8_t * ss0 = (void *) dma_queue_pop(dma_q).dst; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir0); - mmctx->vec_dot_1x1(ne00, &tmp[ir0 - src0_start_row], ss0, act_col); + mmctx->vec_dot_1x1(ne00, &tmp[ir0 - src0_start_row], ss0, act_col, hvx_flat_store_1x1_f32); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir0); } int copy_cnt = src0_end_row - src0_start_row; if (copy_cnt > 0) { htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, src0_end_row); - if (src2) { - hvx_add_f32_uuu((uint8_t *) &dst_col[src0_start_row], - (const uint8_t *) tmp, - (const uint8_t *) ((const float *) mmctx->vtcm_bias + src0_start_row), - copy_cnt); - } else { - hvx_copy_f32_ua((uint8_t *) &dst_col[src0_start_row], (uint8_t *) tmp, copy_cnt); + const hvx_tiled_store_row_fn_t store_row = mmctx->store_row; + const uint8_t * bias_in = bias ? (mmctx->vtcm_bias + (size_t) src0_start_row * bias_elem_size) : NULL; + if (bias_in) { + for (int c = 0; c < copy_cnt; c += 32) { + const uint32_t valid_c = (uint32_t) MIN(32, copy_cnt - c); + HVX_Vector v_sum = *(const HVX_UVector *) (tmp + c); + store_row(vtcm_dst_ptr + (size_t) c * dst_elem_size, valid_c, v_sum, bias_in + (size_t) c * bias_elem_size); + } + } else if (dst_elem_size != sizeof(float)) { + for (int c = 0; c < copy_cnt; c += 32) { + const uint32_t valid_c = (uint32_t) MIN(32, copy_cnt - c); + HVX_Vector v_sum = *(const HVX_UVector *) (tmp + c); + store_row(vtcm_dst_ptr + (size_t) c * dst_elem_size, valid_c, v_sum, NULL); + } } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, src0_end_row); + dma_sync_write(dma_q, dst->data + (size_t) src0_start_row * dst_elem_size, + vtcm_dst_ptr, (size_t) copy_cnt * dst_elem_size); } } @@ -1168,9 +1251,8 @@ static void hvx_mm_4d_flat(const htp_thread_t * th, unsigned int nth, unsigned i const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params; const uint32_t n_prefetch = kparams->n_prefetch; assert(n_prefetch >= 2 && n_prefetch <= HTP_MM_MAX_PREFETCH && (n_prefetch & (n_prefetch - 1)) == 0); - const uint32_t prefetch_mask = n_prefetch - 1; + (void) n_prefetch; - const uint32_t src0_nrows = mmctx->src0_row_end - mmctx->src0_row_start; const uint32_t cur_m_rows = mmctx->cur_m_rows ? mmctx->cur_m_rows : (ne11 * ne12 * ne13); const uint32_t cur_m_start = mmctx->cur_m_start; @@ -1184,6 +1266,7 @@ static void hvx_mm_4d_flat(const htp_thread_t * th, unsigned int nth, unsigned i const size_t src0_row_size = nb01; const size_t src0_stride = mmctx->vtcm_src0_stride; const size_t act_stride = mmctx->vtcm_act_stride; + const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); uint8_t * restrict vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith; uint8_t * restrict act_data = mmctx->vtcm_act; @@ -1217,19 +1300,17 @@ static void hvx_mm_4d_flat(const htp_thread_t * th, unsigned int nth, unsigned i b_grp_end++; } - const dma_addr_t src0_row = src0->data + ((size_t) i02 * nb02 + (size_t) i03 * nb03); + const dma_addr_t src0_row = src0->data + ((dma_addr_t) i02 * nb02 + (dma_addr_t) i03 * nb03); + uint8_t * restrict vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith; - for (uint32_t ir0 = src0_start_row; ir0 < src0_end_row_x2; ir0 += 2) { - const int is0 = (ir0 - src0_start_row); - if (is0 >= (int)n_prefetch) { - break; - } - dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + is0 * src0_stride, src0_row + (size_t) ir0 * src0_row_size), + if (src0_start_row < src0_end_row_x2) { + dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) src0_start_row * src0_row_size), src0_stride, src0_row_size, src0_row_size, 2); } for (uint32_t ir0 = src0_start_row; ir0 < src0_end_row_x2; ir0 += 2) { const uint8_t * ss0 = (void *) dma_queue_pop(dma_q).dst; + const size_t ir0_dst_off = (size_t) ir0 * dst_elem_size; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir0); for (uint32_t b = b_grp_start; b < b_grp_end; b++) { @@ -1240,40 +1321,44 @@ static void hvx_mm_4d_flat(const htp_thread_t * th, unsigned int nth, unsigned i const uint32_t cur_b3 = fastdiv(b, &kparams->div_ne12); const uint32_t cur_b2 = b - cur_b3 * ne12; - uint8_t * dst_batch_base = (uint8_t *) dst->data + (size_t) cur_b2 * nb2 + (size_t) cur_b3 * nb3; + const dma_addr_t dst_batch_base = dst->data + (dma_addr_t) cur_b2 * nb2 + (dma_addr_t) cur_b3 * nb3; const uint32_t chunk_m_offset = m_first - cur_m_start; const uint32_t dst_m_offset = m_first - b_m_start; const uint32_t batch_nrows = m_last - m_first; - uint32_t ir1 = 0; - for (; ir1 + 1 < batch_nrows; ir1 += 2) { - const uint8_t * restrict act_col0 = (const uint8_t *) (act_data + (chunk_m_offset + ir1 + 0) * act_stride); - const uint8_t * restrict act_col1 = (const uint8_t *) (act_data + (chunk_m_offset + ir1 + 1) * act_stride); - float * restrict dst_row0 = (float *) (dst_batch_base + (dst_m_offset + ir1 + 0) * dst_row_size); - float * restrict dst_row1 = (float *) (dst_batch_base + (dst_m_offset + ir1 + 1) * dst_row_size); - mmctx->vec_dot_2x2(ne00, &dst_row0[ir0], &dst_row1[ir0], ss0, ss0 + src0_stride, act_col0, act_col1); - } - for (; ir1 < batch_nrows; ++ir1) { - const uint8_t * restrict act_col = (const uint8_t *) (act_data + (chunk_m_offset + ir1) * act_stride); - float * restrict dst_row = (float *) (dst_batch_base + (dst_m_offset + ir1) * dst_row_size); - mmctx->vec_dot_2x1(ne00, &dst_row[ir0], ss0, ss0 + src0_stride, act_col); + for (uint32_t m0 = 0; m0 < batch_nrows; m0 += 32) { + const uint32_t m_cnt = MIN(32u, batch_nrows - m0); + uint32_t r = 0; + for (; r + 1 < m_cnt; r += 2) { + const uint8_t * restrict act_col0 = (const uint8_t *) (act_data + (chunk_m_offset + m0 + r + 0) * act_stride); + const uint8_t * restrict act_col1 = (const uint8_t *) (act_data + (chunk_m_offset + m0 + r + 1) * act_stride); + void * dst_ptr0 = vtcm_dst_ptr + (size_t) (r + 0) * 16; + void * dst_ptr1 = vtcm_dst_ptr + (size_t) (r + 1) * 16; + mmctx->vec_dot_2x2(ne00, dst_ptr0, dst_ptr1, ss0, ss0 + src0_stride, act_col0, act_col1, mmctx->flat_store_2x1); + } + for (; r < m_cnt; ++r) { + const uint8_t * restrict act_col = (const uint8_t *) (act_data + (chunk_m_offset + m0 + r) * act_stride); + void * dst_ptr = vtcm_dst_ptr + (size_t) r * 16; + mmctx->vec_dot_2x1(ne00, dst_ptr, ss0, ss0 + src0_stride, act_col, mmctx->flat_store_2x1); + } + const dma_addr_t dst_addr = dst_batch_base + (dma_addr_t) (dst_m_offset + m0) * dst_row_size + ir0_dst_off; + dma_queue_push(dma_q, dma_make_data(dst_addr, vtcm_dst_ptr), dst_row_size, 16, 2u * dst_elem_size, m_cnt); + dma_queue_pop(dma_q); } } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir0); - const int pr0 = (ir0 + n_prefetch); - const int is0 = (pr0 - src0_start_row) & prefetch_mask; - if (pr0 < src0_end_row_x2) { - dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + is0 * src0_stride, src0_row + (size_t) pr0 * src0_row_size), + if (ir0 + 2 < src0_end_row_x2) { + dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) (ir0 + 2) * src0_row_size), src0_stride, src0_row_size, src0_row_size, 2); } } if (src0_end_row != src0_end_row_x2) { - uint32_t ir0 = src0_end_row_x2; - const int is0 = (ir0 - src0_start_row) & prefetch_mask; - dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + is0 * src0_stride, src0_row + (size_t) ir0 * src0_row_size), + const uint32_t ir0 = src0_end_row_x2; + const size_t ir0_dst_off = (size_t) ir0 * dst_elem_size; + dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) ir0 * src0_row_size), src0_stride, src0_row_size, src0_row_size, 1); const uint8_t * ss0 = (void *) dma_queue_pop(dma_q).dst; @@ -1286,16 +1371,22 @@ static void hvx_mm_4d_flat(const htp_thread_t * th, unsigned int nth, unsigned i const uint32_t cur_b3 = fastdiv(b, &kparams->div_ne12); const uint32_t cur_b2 = b - cur_b3 * ne12; - uint8_t * dst_batch_base = (uint8_t *) dst->data + (size_t) cur_b2 * nb2 + (size_t) cur_b3 * nb3; + const dma_addr_t dst_batch_base = dst->data + (dma_addr_t) cur_b2 * nb2 + (dma_addr_t) cur_b3 * nb3; const uint32_t chunk_m_offset = m_first - cur_m_start; const uint32_t dst_m_offset = m_first - b_m_start; const uint32_t batch_nrows = m_last - m_first; - for (uint32_t ir1 = 0; ir1 < batch_nrows; ++ir1) { - const uint8_t * restrict act_col = (const uint8_t *) (act_data + (chunk_m_offset + ir1) * act_stride); - float * restrict dst_row = (float *) (dst_batch_base + (dst_m_offset + ir1) * dst_row_size); - mmctx->vec_dot_1x1(ne00, &dst_row[ir0], ss0, act_col); + for (uint32_t m0 = 0; m0 < batch_nrows; m0 += 32) { + const uint32_t m_cnt = MIN(32u, batch_nrows - m0); + for (uint32_t r = 0; r < m_cnt; ++r) { + const uint8_t * restrict act_col = (const uint8_t *) (act_data + (chunk_m_offset + m0 + r) * act_stride); + void * dst_ptr = vtcm_dst_ptr + (size_t) r * 16; + mmctx->vec_dot_1x1(ne00, dst_ptr, ss0, act_col, mmctx->flat_store_1x1); + } + const dma_addr_t dst_addr = dst_batch_base + (dma_addr_t) (dst_m_offset + m0) * dst_row_size + ir0_dst_off; + dma_queue_push(dma_q, dma_make_data(dst_addr, vtcm_dst_ptr), dst_row_size, 16, dst_elem_size, m_cnt); + dma_queue_pop(dma_q); } } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir0); @@ -1303,10 +1394,6 @@ static void hvx_mm_4d_flat(const htp_thread_t * th, unsigned int nth, unsigned i b_grp_start = b_grp_end; } - - if (src2) { - hvx_tensor_add_f32_grid(dst, src2, cur_m_start, cur_m_start + cur_m_rows, src0_start_row, src0_end_row, &kparams->div_ne12_ne1, &kparams->div_ne1); - } } #define MMID_MATRIX_ROW(row_id, i1) matrix_rows[(row_id) * mmctx->mapping_stride + (i1)] @@ -1314,10 +1401,6 @@ static void hvx_mm_4d_flat(const htp_thread_t * th, unsigned int nth, unsigned i static void hvx_mm_id_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { htp_matmul_preamble; - const struct htp_tensor * restrict ids = octx->src[2]; - - const uint32_t src0_nrows = mmctx->src0_row_end - mmctx->src0_row_start; // src0 rows per expert - const uint32_t act_nrows = ne11; const uint32_t src0_start_row = mmctx->src0_row_start + src0_nrows_per_hvx * ith; const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, mmctx->src0_row_end); @@ -1331,20 +1414,20 @@ static void hvx_mm_id_tiled(const htp_thread_t * th, unsigned int nth, unsigned const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params; const uint32_t n_prefetch = kparams->n_prefetch; assert(n_prefetch >= 2 && n_prefetch <= HTP_MM_MAX_PREFETCH && (n_prefetch & (n_prefetch - 1)) == 0); + (void) n_prefetch; - const uint32_t n_ids = ids->ne[0]; // n_expert_used const uint32_t n_as = ne02; // n_expert const uint32_t * matrix_row_counts = mmctx->matrix_row_counts; const struct mmid_row_mapping * matrix_rows = mmctx->matrix_rows; - const size_t dst_row_size = nb1; - const size_t act_row_size = htp_mm_q8_0_tiled_row_size(ne10); + const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); const size_t act_stride = mmctx->vtcm_act_stride; - // Per-thread VTCMs for all tensors + // Per-HVX VTCMs for all tensors uint8_t * restrict vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith; + uint8_t * restrict vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith; uint8_t * restrict act_data = mmctx->vtcm_act; for (uint32_t cur_a = 0; cur_a < n_as; ++cur_a) { @@ -1353,47 +1436,50 @@ static void hvx_mm_id_tiled(const htp_thread_t * th, unsigned int nth, unsigned continue; } - const dma_addr_t src0_row = src0->data + cur_a * nb02; + const dma_addr_t src0_row = src0->data + (dma_addr_t) cur_a * nb02; - const uint32_t tile_size = htp_tensor_get_tile_size(src0->type); - const uint32_t aligned_tile_size = htp_tensor_get_tile_padded_size(src0->type); + const uint32_t tile_size = kparams->tile_size; + const uint32_t aligned_tile_size = kparams->aligned_tile_size; const uint32_t n_k_tiles_w = ne00 / htp_tensor_get_tile_k(src0->type); const uint32_t tile_row_stride = n_k_tiles_w * tile_size; - const uint32_t tile_row_transfer_size_aligned = n_k_tiles_w * aligned_tile_size; const uint32_t ct_start = src0_start_row / 32; const uint32_t ct_end = (src0_end_row + 31) / 32; - uint32_t push_ct = ct_start; - for (uint32_t d = 0; d < n_prefetch && push_ct < ct_end; d++, push_ct++) { - dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + d * tile_row_transfer_size_aligned, src0_row + push_ct * tile_row_stride), - aligned_tile_size, tile_size, tile_size, n_k_tiles_w); - } + dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) ct_start * tile_row_stride), + aligned_tile_size, tile_size, tile_size, n_k_tiles_w); for (uint32_t ct = ct_start; ct < ct_end; ct++) { const uint8_t * w_tile = (void *) dma_queue_pop(dma_q).dst; int valid_rows = (int)ne0 - (int)(ct * 32); valid_rows = MIN(32, MAX(0, valid_rows)); + const size_t ct_dst_off = (size_t) ct * 32 * dst_elem_size; + const size_t row_bytes = (size_t) valid_rows * dst_elem_size; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct); - for (uint32_t cid = 0; cid < cne1; ++cid) { - struct mmid_row_mapping row_mapping = MMID_MATRIX_ROW(cur_a, cid); - const int rm1 = row_mapping.i1; // expert idx - const int rm2 = row_mapping.i2; // token idx - - const uint32_t ir1 = fastmodulo(rm1, ne11, &mmctx->mm_div_ne11); // act row idx - const uint8_t * restrict act_col = (const uint8_t *) (act_data + (ir1 + rm2 * ne11 + 0) * act_stride); - float * restrict dst_row = (float *) (dst->data + (rm1 * nb1 + rm2 * nb2 + 0)); - - mmctx->vec_dot_32x1(ne10, &dst_row[ct * 32], w_tile, act_col, valid_rows, NULL); + for (uint32_t cid0 = 0; cid0 < (uint32_t) cne1; cid0 += 32) { + const uint32_t cnt = MIN(32u, (uint32_t) cne1 - cid0); + for (uint32_t r = 0; r < cnt; ++r) { + struct mmid_row_mapping row_mapping = MMID_MATRIX_ROW(cur_a, cid0 + r); + const int rm1 = row_mapping.i1; + const int rm2 = row_mapping.i2; + const uint32_t ir1 = fastmodulo(rm1, ne11, &mmctx->mm_div_ne11); + const uint8_t * restrict act_col = (const uint8_t *) (act_data + (ir1 + rm2 * ne11) * act_stride); + mmctx->vec_dot_32x1(ne10, vtcm_dst_ptr + (size_t) r * 128, w_tile, act_col, valid_rows, NULL, mmctx->store_row); + } + for (uint32_t r = 0; r < cnt; ++r) { + struct mmid_row_mapping row_mapping = MMID_MATRIX_ROW(cur_a, cid0 + r); + const dma_addr_t dst_addr = dst->data + (dma_addr_t) row_mapping.i1 * nb1 + (dma_addr_t) row_mapping.i2 * nb2 + ct_dst_off; + dma_queue_push(dma_q, dma_make_data(dst_addr, vtcm_dst_ptr + (size_t) r * 128), row_bytes, row_bytes, row_bytes, 1); + } + dma_queue_flush(dma_q); } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct); - if (push_ct < ct_end) { - dma_queue_push(dma_q, dma_make_data(w_tile, src0_row + push_ct * tile_row_stride), + if (ct + 1 < ct_end) { + dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) (ct + 1) * tile_row_stride), aligned_tile_size, tile_size, tile_size, n_k_tiles_w); - push_ct++; } } } @@ -1404,7 +1490,6 @@ static void hvx_mv_id_tiled(const htp_thread_t * th, unsigned int nth, unsigned const struct htp_tensor * restrict ids = octx->src[2]; - const uint32_t src0_nrows = mmctx->src0_row_end - mmctx->src0_row_start; // src0 rows per expert const uint32_t src0_start_row = mmctx->src0_row_start + src0_nrows_per_hvx * ith; const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, mmctx->src0_row_end); @@ -1421,29 +1506,32 @@ static void hvx_mv_id_tiled(const htp_thread_t * th, unsigned int nth, unsigned assert(ne13 % ne03 == 0); - const size_t dst_row_size = nb1; - const size_t act_row_size = htp_mm_q8_0_tiled_row_size(ne10); + const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); - const uint32_t n_aids = src2->ne[0]; // num activated experts + const uint32_t n_aids = ids->ne[0]; // num activated experts const uint32_t n_ids = ne02; // num experts + (void) n_ids; - // Per-thread VTCMs for all tensors + // Per-HVX VTCMs for all tensors uint8_t * restrict vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith; + uint8_t * restrict vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith; uint8_t * restrict act_data = mmctx->vtcm_act; + const uint32_t copy_cnt = MIN(src0_end_row, ne0) - src0_start_row; + for (uint32_t ie1 = 0; ie1 < n_aids; ++ie1) { // for each expert - const int32_t eid = *(const int32_t *) ((const uint8_t *) src2->data + ie1 * src2->nb[0]); + const int32_t eid = mmctx->ids_data[ie1]; if (eid < 0) { continue; } assert(eid >= 0 && eid < (int32_t) n_ids); - const dma_addr_t src0_row = src0->data + eid * nb02; + const dma_addr_t src0_row = src0->data + (dma_addr_t) eid * nb02; const uint8_t * restrict act_col = (const uint8_t *) act_data; - float * restrict dst_row = (float *) (dst->data + ie1 * nb1); + const dma_addr_t dst_row = dst->data + (dma_addr_t) ie1 * nb1; - const uint32_t tile_size = htp_tensor_get_tile_size(src0->type); - const uint32_t aligned_tile_size = htp_tensor_get_tile_padded_size(src0->type); + const uint32_t tile_size = kparams->tile_size; + const uint32_t aligned_tile_size = kparams->aligned_tile_size; const uint32_t n_k_tiles_w = ne00 / htp_tensor_get_tile_k(src0->type); const uint32_t tile_row_stride = n_k_tiles_w * tile_size; const uint32_t tile_row_transfer_size_aligned = n_k_tiles_w * aligned_tile_size; @@ -1453,7 +1541,7 @@ static void hvx_mv_id_tiled(const htp_thread_t * th, unsigned int nth, unsigned uint32_t push_ct = ct_start; for (uint32_t d = 0; d < n_prefetch && push_ct < ct_end; d++, push_ct++) { - dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + d * tile_row_transfer_size_aligned, src0_row + push_ct * tile_row_stride), + dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + d * tile_row_transfer_size_aligned, src0_row + (dma_addr_t) push_ct * tile_row_stride), aligned_tile_size, tile_size, tile_size, n_k_tiles_w); } @@ -1464,15 +1552,17 @@ static void hvx_mv_id_tiled(const htp_thread_t * th, unsigned int nth, unsigned valid_rows = MIN(32, MAX(0, valid_rows)); htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct); - mmctx->vec_dot_32x1(ne10, &dst_row[ct * 32], w_tile, act_col, valid_rows, NULL); + mmctx->vec_dot_32x1(ne10, vtcm_dst_ptr + (size_t) (ct - ct_start) * 32 * dst_elem_size, w_tile, act_col, valid_rows, NULL, mmctx->store_row); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct); if (push_ct < ct_end) { - dma_queue_push(dma_q, dma_make_data(w_tile, src0_row + push_ct * tile_row_stride), + dma_queue_push(dma_q, dma_make_data(w_tile, src0_row + (dma_addr_t) push_ct * tile_row_stride), aligned_tile_size, tile_size, tile_size, n_k_tiles_w); push_ct++; } } + dma_sync_write(dma_q, dst_row + (size_t) src0_start_row * dst_elem_size, + vtcm_dst_ptr, (size_t) copy_cnt * dst_elem_size); } } @@ -1493,12 +1583,14 @@ static void hvx_mv_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsign const uint32_t n_aids = ids->ne[0]; const uint32_t n_ids = src0->ne[2]; + (void) n_ids; uint8_t * restrict vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith; + uint8_t * restrict vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith; uint8_t * restrict act_data = mmctx->vtcm_act; for (uint32_t ie1 = 0; ie1 < n_aids; ++ie1) { - const int32_t eid = *(const int32_t *) ((const uint8_t *) ids->data + ie1 * ids->nb[0]); + const int32_t eid = mmctx->ids_data[ie1]; if (eid < 0) continue; assert(eid < (int32_t) n_ids); @@ -1508,12 +1600,13 @@ static void hvx_mv_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsign if (!src_w || !dst) continue; dma_queue * dma_q = th->dma_q; + const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const hvx_tiled_store_row_fn_t store_row = resolve_hvx_tiled_store_row_fn(dst_elem_size, false, sizeof(float)); const uint32_t ne01 = src_w->ne[1]; uint32_t start_row = 0; uint32_t end_row = ne01; if (octx->ctx->mdev.count > 1) { - const bool can_split = htp_tensor_can_row_partition(dst, sizeof(float)); - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(ne01, can_split ? 32 : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(ne01, 32, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); start_row = range.start; end_row = range.start + range.count; } @@ -1526,12 +1619,12 @@ static void hvx_mv_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsign const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, end_row); if (src0_start_row >= src0_end_row) continue; - const dma_addr_t src0_row = src_w->data + eid * src_w->nb[2]; + const dma_addr_t src0_row = src_w->data + (dma_addr_t) eid * src_w->nb[2]; const uint8_t * restrict act_col = (const uint8_t *) act_data; - float * restrict dst_row = (float *) (dst->data + ie1 * dst->nb[1]); + const dma_addr_t dst_row = dst->data + (dma_addr_t) ie1 * dst->nb[1]; - const uint32_t tile_size = htp_tensor_get_tile_size(src_w->type); - const uint32_t aligned_tile_size = htp_tensor_get_tile_padded_size(src_w->type); + const uint32_t tile_size = kparams->tile_size; + const uint32_t aligned_tile_size = kparams->aligned_tile_size; const uint32_t n_k_tiles_w = src_w->ne[0] / htp_tensor_get_tile_k(src_w->type); const uint32_t tile_row_stride = n_k_tiles_w * tile_size; const uint32_t tile_row_transfer_size_aligned = n_k_tiles_w * aligned_tile_size; @@ -1541,7 +1634,7 @@ static void hvx_mv_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsign uint32_t push_ct = ct_start; for (uint32_t d = 0; d < n_prefetch && push_ct < ct_end; d++, push_ct++) { - dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + d * tile_row_transfer_size_aligned, src0_row + push_ct * tile_row_stride), + dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + d * tile_row_transfer_size_aligned, src0_row + (dma_addr_t) push_ct * tile_row_stride), aligned_tile_size, tile_size, tile_size, n_k_tiles_w); } @@ -1552,15 +1645,17 @@ static void hvx_mv_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsign valid_rows = MIN(32, MAX(0, valid_rows)); htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct); - mmctx->vec_dot_32x1(act->ne[0], &dst_row[ct * 32], w_tile, act_col, valid_rows, NULL); + mmctx->vec_dot_32x1(act->ne[0], vtcm_dst_ptr + (size_t) (ct - ct_start) * 32 * dst_elem_size, w_tile, act_col, valid_rows, NULL, store_row); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct); if (push_ct < ct_end) { - dma_queue_push(dma_q, dma_make_data(w_tile, src0_row + push_ct * tile_row_stride), + dma_queue_push(dma_q, dma_make_data(w_tile, src0_row + (dma_addr_t) push_ct * tile_row_stride), aligned_tile_size, tile_size, tile_size, n_k_tiles_w); push_ct++; } } + const size_t copy_bytes = (size_t) (MIN(src0_end_row, dst->ne[0]) - src0_start_row) * dst_elem_size; + dma_sync_write(dma_q, dst_row + (size_t) src0_start_row * dst_elem_size, vtcm_dst_ptr, copy_bytes); } } } @@ -1572,13 +1667,13 @@ static void hvx_mm_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsign const uint32_t n_weights = kparams->n_weights; const struct htp_tensor * restrict src0 = octx->src[0]; const struct htp_tensor * restrict act = octx->src[n_weights]; - const struct htp_tensor * restrict ids = octx->src[n_weights + 1]; struct htp_thread_trace * tr = th->trace; const uint32_t n_prefetch = kparams->n_prefetch; assert(n_prefetch >= 2 && n_prefetch <= HTP_MM_MAX_PREFETCH && (n_prefetch & (n_prefetch - 1)) == 0); + (void) n_prefetch; const uint32_t n_as = src0->ne[2]; @@ -1588,6 +1683,7 @@ static void hvx_mm_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsign const size_t act_stride = mmctx->vtcm_act_stride; uint8_t * restrict vtcm_src0_ptr = mmctx->vtcm_src0 + mmctx->vtcm_src0_size_per_hvx * ith; + uint8_t * restrict vtcm_dst_ptr = mmctx->vtcm_dst + mmctx->vtcm_dst_size_per_hvx * ith; uint8_t * restrict act_data = mmctx->vtcm_act; for (uint32_t cur_a = 0; cur_a < n_as; ++cur_a) { @@ -1600,12 +1696,13 @@ static void hvx_mm_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsign if (!src_w || !dst) continue; dma_queue * dma_q = th->dma_q; + const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const hvx_tiled_store_row_fn_t store_row = resolve_hvx_tiled_store_row_fn(dst_elem_size, false, sizeof(float)); const uint32_t ne01 = src_w->ne[1]; uint32_t start_row = 0; uint32_t end_row = ne01; if (octx->ctx->mdev.count > 1) { - const bool can_split = htp_tensor_can_row_partition(dst, sizeof(float)); - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(ne01, can_split ? 32 : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(ne01, 32, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); start_row = range.start; end_row = range.start + range.count; } @@ -1618,47 +1715,50 @@ static void hvx_mm_id_nx_tiled(const htp_thread_t * th, unsigned int nth, unsign const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, end_row); if (src0_start_row >= src0_end_row) continue; - const dma_addr_t src0_row = src_w->data + cur_a * src_w->nb[2]; + const dma_addr_t src0_row = src_w->data + (dma_addr_t) cur_a * src_w->nb[2]; - const uint32_t tile_size = htp_tensor_get_tile_size(src_w->type); - const uint32_t aligned_tile_size = htp_tensor_get_tile_padded_size(src_w->type); + const uint32_t tile_size = kparams->tile_size; + const uint32_t aligned_tile_size = kparams->aligned_tile_size; const uint32_t n_k_tiles_w = src_w->ne[0] / htp_tensor_get_tile_k(src_w->type); const uint32_t tile_row_stride = n_k_tiles_w * tile_size; - const uint32_t tile_row_transfer_size_aligned = n_k_tiles_w * aligned_tile_size; const uint32_t ct_start = src0_start_row / 32; const uint32_t ct_end = (src0_end_row + 31) / 32; - uint32_t push_ct = ct_start; - for (uint32_t d = 0; d < n_prefetch && push_ct < ct_end; d++, push_ct++) { - dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr + d * tile_row_transfer_size_aligned, src0_row + push_ct * tile_row_stride), - aligned_tile_size, tile_size, tile_size, n_k_tiles_w); - } + dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) ct_start * tile_row_stride), + aligned_tile_size, tile_size, tile_size, n_k_tiles_w); for (uint32_t ct = ct_start; ct < ct_end; ct++) { const uint8_t * w_tile = (void *) dma_queue_pop(dma_q).dst; int valid_rows = (int)dst->ne[0] - (int)(ct * 32); valid_rows = MIN(32, MAX(0, valid_rows)); + const size_t ct_dst_off = (size_t) ct * 32 * dst_elem_size; + const size_t row_bytes = (size_t) valid_rows * dst_elem_size; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ct); - for (uint32_t cid = 0; cid < (uint32_t) cne1; ++cid) { - struct mmid_row_mapping row_mapping = MMID_MATRIX_ROW(cur_a, cid); - const int rm1 = row_mapping.i1; - const int rm2 = row_mapping.i2; - - const uint32_t ir1 = fastmodulo(rm1, act->ne[1], &mmctx->mm_div_ne11); - const uint8_t * restrict act_col = (const uint8_t *) (act_data + (ir1 + rm2 * act->ne[1]) * act_stride); - float * restrict dst_row = (float *) (dst->data + (rm1 * dst->nb[1] + rm2 * dst->nb[2])); - - mmctx->vec_dot_32x1(act->ne[0], &dst_row[ct * 32], w_tile, act_col, valid_rows, NULL); + for (uint32_t cid0 = 0; cid0 < (uint32_t) cne1; cid0 += 32) { + const uint32_t cnt = MIN(32u, (uint32_t) cne1 - cid0); + for (uint32_t r = 0; r < cnt; ++r) { + struct mmid_row_mapping row_mapping = MMID_MATRIX_ROW(cur_a, cid0 + r); + const int rm1 = row_mapping.i1; + const int rm2 = row_mapping.i2; + const uint32_t ir1 = fastmodulo(rm1, act->ne[1], &mmctx->mm_div_ne11); + const uint8_t * restrict act_col = (const uint8_t *) (act_data + (ir1 + rm2 * act->ne[1]) * act_stride); + mmctx->vec_dot_32x1(act->ne[0], vtcm_dst_ptr + (size_t) r * 128, w_tile, act_col, valid_rows, NULL, store_row); + } + for (uint32_t r = 0; r < cnt; ++r) { + struct mmid_row_mapping row_mapping = MMID_MATRIX_ROW(cur_a, cid0 + r); + const dma_addr_t dst_addr = dst->data + (dma_addr_t) row_mapping.i1 * dst->nb[1] + (dma_addr_t) row_mapping.i2 * dst->nb[2] + ct_dst_off; + dma_queue_push(dma_q, dma_make_data(dst_addr, vtcm_dst_ptr + (size_t) r * 128), row_bytes, row_bytes, row_bytes, 1); + } + dma_queue_flush(dma_q); } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ct); - if (push_ct < ct_end) { - dma_queue_push(dma_q, dma_make_data(w_tile, src0_row + push_ct * tile_row_stride), - aligned_tile_size, tile_size, tile_size, n_k_tiles_w); - push_ct++; + if (ct + 1 < ct_end) { + dma_queue_push(dma_q, dma_make_data(vtcm_src0_ptr, src0_row + (dma_addr_t) (ct + 1) * tile_row_stride), + aligned_tile_size, tile_size, tile_size, n_k_tiles_w); } } } @@ -1769,9 +1869,12 @@ static int hvx_mm_matmul(struct htp_ops_context * octx) { uint32_t src0_row_start = 0; uint32_t src0_row_end = src0_nrows; + const size_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const size_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const size_t bias_elem_size = (bias && bias->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + if (octx->ctx->mdev.count > 1) { - const bool can_split = htp_tensor_can_row_partition(dst, sizeof(float)); - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, can_split ? 32 : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, 32, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); src0_row_start = range.start; src0_row_end = range.start + range.count; } @@ -1795,23 +1898,30 @@ static int hvx_mm_matmul(struct htp_ops_context * octx) { } const size_t src0_row_size = nb01; - const size_t dst_row_size = nb1; - size_t act_row_size = nb11; + const size_t dst_row_size = (size_t) ne0 * sizeof(float); + const size_t act_row_size = kparams->act_row_size; const size_t src0_row_size_padded = hex_round_up(src0_row_size, 128); work_queue_func_t quant_task_func; - work_queue_func_t matmul_job_func; + work_queue_func_t matmul_task_func; uint32_t n_quant_tasks = 1; const bool is_batched = (ne12 > 1 || ne13 > 1 || ne02 > 1 || ne03 > 1); + if (bias && (is_batched || act_nrows > 1)) { + return HTP_STATUS_NO_SUPPORT; + } if (is_batched) { - matmul_job_func = is_tiled ? hvx_mm_4d_tiled : hvx_mm_4d_flat; + matmul_task_func = is_tiled ? hvx_mm_4d_tiled : hvx_mm_4d_flat; } else if (act_nrows > 1) { - matmul_job_func = is_tiled ? hvx_mm_2d_tiled : hvx_mm_2d_flat; + matmul_task_func = is_tiled ? hvx_mm_2d_tiled : hvx_mm_2d_flat; } else { - matmul_job_func = is_tiled ? hvx_mv_2d_tiled : hvx_mv_2d_flat; + matmul_task_func = is_tiled ? hvx_mv_2d_tiled : hvx_mv_2d_flat; } + mmctx->store_row = resolve_hvx_tiled_store_row_fn(dst_elem_size, bias != NULL && !is_batched, bias_elem_size); + mmctx->flat_store_1x1 = resolve_hvx_flat_store_1x1_fn(dst_elem_size); + mmctx->flat_store_2x1 = resolve_hvx_flat_store_2x1_fn(dst_elem_size); + bool need_quant = true; switch (kparams->kernel_type) { @@ -1822,27 +1932,26 @@ static int hvx_mm_matmul(struct htp_ops_context * octx) { mmctx->vec_dot_1x1 = flat_vec_dot_f16_f16_aa_1x1; mmctx->vec_dot_2x1 = flat_vec_dot_f16_f16_aa_2x1; mmctx->vec_dot_2x2 = flat_vec_dot_f16_f16_aa_2x2; - act_row_size = kparams->act_row_size; break; case HTP_MM_KERNEL_HVX_F32_F32_VTCM: - quant_task_func = NULL; - need_quant = false; + quant_task_func = (act->type == HTP_TYPE_F16) ? quantize_f16_f32 : NULL; + need_quant = (act->type == HTP_TYPE_F16); + n_quant_tasks = need_quant ? MIN(act_nrows, octx->n_hvx) : 1; mmctx->type = "f32-f32"; mmctx->vec_dot_1x1 = flat_vec_dot_f32_f32_aa_1x1; mmctx->vec_dot_2x1 = flat_vec_dot_f32_f32_aa_2x1; mmctx->vec_dot_2x2 = flat_vec_dot_f32_f32_aa_2x2; - act_row_size = kparams->act_row_size; break; case HTP_MM_KERNEL_HVX_BF16_F32_VTCM: - quant_task_func = NULL; - need_quant = false; + quant_task_func = (act->type == HTP_TYPE_F16) ? quantize_f16_f32 : NULL; + need_quant = (act->type == HTP_TYPE_F16); + n_quant_tasks = need_quant ? MIN(act_nrows, octx->n_hvx) : 1; mmctx->type = "bf16-f32"; mmctx->vec_dot_1x1 = flat_vec_dot_bf16_f32_aa_1x1; mmctx->vec_dot_2x1 = flat_vec_dot_bf16_f32_aa_2x1; mmctx->vec_dot_2x2 = flat_vec_dot_bf16_f32_aa_2x2; - act_row_size = kparams->act_row_size; break; case HTP_MM_KERNEL_HVX_QUANT_BLOCK: @@ -1871,7 +1980,6 @@ static int hvx_mm_matmul(struct htp_ops_context * octx) { n_quant_tasks = MIN(act_nrows, octx->n_hvx); quant_task_func = htp_mm_act_quant_row_func(src0->type, act->type); } - act_row_size = kparams->act_row_size; break; } } @@ -1882,7 +1990,7 @@ static int hvx_mm_matmul(struct htp_ops_context * octx) { struct htp_mm_hvx_vtcm_layout L; htp_mm_hvx_vtcm_layout_build(&L, kparams->kernel_type, src0->type, ne10, m_layout_rows, octx->n_hvx, - dst_row_size, src0_row_size, act_row_size, src2 ? src2->nb[1] : 0, kparams->n_prefetch, false, false); + dst_row_size, src0_row_size, act_elem_size, bias ? bias->nb[1] : 0, kparams->n_prefetch, false, false); if (kparams->kernel_type == HTP_MM_KERNEL_HVX_F16_F16_VTCM || kparams->kernel_type == HTP_MM_KERNEL_HVX_F32_F32_VTCM || @@ -1923,9 +2031,12 @@ static int hvx_mm_matmul(struct htp_ops_context * octx) { mmctx->vtcm_src0_stride = src0_row_size_padded; mmctx->vtcm_act_stride = act_row_size; if (kparams->kernel_type == HTP_MM_KERNEL_HVX_QUANT_BLOCK || kparams->kernel_type == HTP_MM_KERNEL_HVX_QUANT_ROW) { - mmctx->vtcm_act_raw_stride = htp_mm_act_raw_row_size(ne10); - } else if (kparams->kernel_type == HTP_MM_KERNEL_HVX_F16_F16_VTCM) { - mmctx->vtcm_act_raw_stride = hex_round_up(ne10 * sizeof(float), 128); + mmctx->vtcm_act_raw_stride = htp_mm_act_raw_row_size(ne10, act_elem_size); + } else if (kparams->kernel_type == HTP_MM_KERNEL_HVX_F16_F16_VTCM || + ((kparams->kernel_type == HTP_MM_KERNEL_HVX_F32_F32_VTCM || + kparams->kernel_type == HTP_MM_KERNEL_HVX_BF16_F32_VTCM) && + act_elem_size == sizeof(__fp16))) { + mmctx->vtcm_act_raw_stride = hex_round_up(ne10 * act_elem_size, 128); } else { mmctx->vtcm_act_raw_stride = 0; } @@ -1968,7 +2079,7 @@ static int hvx_mm_matmul(struct htp_ops_context * octx) { hvx_mm_transfer_act_dma(octx, kparams, act, mmctx->vtcm_act, mmctx->vtcm_act_stride, m_start, cur_m_rows); } - work_queue_run(octx->ctx->hvx_queue, matmul_job_func, mmctx, octx->n_hvx); + work_queue_run(octx->ctx->hvx_queue, matmul_task_func, mmctx, octx->n_hvx); } } else { mmctx->cur_m_start = 0; @@ -1983,7 +2094,7 @@ static int hvx_mm_matmul(struct htp_ops_context * octx) { hvx_mm_transfer_act_dma(octx, kparams, act, mmctx->vtcm_act, mmctx->vtcm_act_stride, 0, act_nrows); } - work_queue_run(octx->ctx->hvx_queue, matmul_job_func, mmctx, octx->n_hvx); + work_queue_run(octx->ctx->hvx_queue, matmul_task_func, mmctx, octx->n_hvx); } return HTP_STATUS_OK; @@ -1994,8 +2105,11 @@ static void dequantize_tiled_worker_loop(const htp_thread_t * th, unsigned int n struct htp_thread_trace * tr = th->trace; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, i); for (unsigned int task_id = i; task_id < (unsigned int) state->n_tasks; task_id += n) { - int start = task_id * state->n_tiles_per_task; - int end = hex_smin(start + state->n_tiles_per_task, state->n_tot_tiles); + const uint32_t start = task_id * state->n_tiles_per_task; + if (start >= state->n_tot_tiles) { + break; + } + const uint32_t end = hex_smin(start + state->n_tiles_per_task, state->n_tot_tiles); state->task_fn(state, start, end); } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, i); @@ -2010,12 +2124,16 @@ static void transfer_output_chunk_worker_fn(const htp_thread_t * th, unsigned in htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, start_chunk_idx); for (unsigned int task_id = i; task_id < (unsigned int)st->n_tasks; task_id += n) { - int chunk_idx = task_id * st->n_chunks_per_task; - size_t chunk_size = hex_smin(st->n_tot_chunks - chunk_idx, st->n_chunks_per_task); + const uint32_t chunk_idx = task_id * st->n_chunks_per_task; + if (chunk_idx >= st->n_tot_chunks) { + continue; + } + const uint32_t chunk_size = hex_smin(st->n_tot_chunks - chunk_idx, st->n_chunks_per_task); - float *dst = st->dst + chunk_idx * st->dst_stride; - const float *src2 = st->src2 ? (st->src2 + chunk_idx * st->src2_stride) : NULL; - transfer_output_chunk_fp16_to_fp32(dst, src2, st->vtcm_src, chunk_idx, chunk_size, st->n_cols, st->dst_stride, st->src2_stride, st->dst_cols); + void * dst = (uint8_t *) st->dst + (size_t) chunk_idx * st->dst_stride * st->dst_elem_size; + const void * bias = st->bias ? ((const uint8_t *) st->bias + (size_t) chunk_idx * st->bias_stride * st->bias_elem_size) : NULL; + st->col_chunk_fn(dst, bias, st->vtcm_src, chunk_idx, chunk_size, + st->n_cols, st->n_cols, st->dst_stride, st->bias_stride, st->dst_cols, st->bias_elem_size); } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, start_chunk_idx); @@ -2050,9 +2168,10 @@ typedef struct { size_t vtcm_f32_act_bytes; uint32_t dma_step_rows; uint32_t dma_step_rows_shift; + uint32_t act_elem_size; } activation_transfer_col_chunk_state_t; -static void transfer_activation_chunk_fp32_to_fp16_dma_pipelined_col_chunk( +static void transfer_activation_chunk_to_fp16_dma_pipelined_col_chunk( dma_queue *dma_q, __fp16 *restrict vtcm_dst, dma_addr_t act_dma_addr, @@ -2062,7 +2181,8 @@ static void transfer_activation_chunk_fp32_to_fp16_dma_pipelined_col_chunk( uint32_t k_chunk_valid, uint32_t c_first, uint32_t c_len, - float *thread_f32_act, + uint8_t *act_spad, + uint32_t act_elem_size, struct htp_thread_trace *tr, uint32_t dma_step_rows, uint32_t dma_step_rows_shift) { @@ -2072,40 +2192,59 @@ static void transfer_activation_chunk_fp32_to_fp16_dma_pipelined_col_chunk( const uint32_t n_steps = n_rows_padded >> dma_step_rows_shift; + const bool act_is_f16 = (act_elem_size == sizeof(__fp16)); + const size_t row_bytes = (size_t) c_len * act_elem_size; + const size_t src_row_bytes = (size_t) k_stride * act_elem_size; + const size_t width_bytes = (size_t) k_chunk_valid * act_elem_size; + const size_t src_col_offset = (size_t) c_first * act_elem_size; + // Push step 0 if (n_steps > 0 && n_rows > 0) { uint32_t nrows_to_fetch = hex_smin(n_rows, R); - dma_queue_push(dma_q, dma_make_data(thread_f32_act, act_dma_addr + (size_t) c_first * sizeof(float)), - c_len * sizeof(float), k_stride * sizeof(float), k_chunk_valid * sizeof(float), nrows_to_fetch); + dma_queue_push(dma_q, dma_make_data(act_spad, act_dma_addr + src_col_offset), + row_bytes, src_row_bytes, width_bytes, nrows_to_fetch); } // Push step 1 if (n_steps > 1) { uint32_t next_r = R * 1; if (next_r < n_rows) { uint32_t nrows_to_fetch = hex_smin(n_rows - next_r, R); - float *next_buf = thread_f32_act + 1 * R * c_len; - dma_queue_push(dma_q, dma_make_data(next_buf, act_dma_addr + ((size_t) next_r * k_stride + c_first) * sizeof(float)), - c_len * sizeof(float), k_stride * sizeof(float), k_chunk_valid * sizeof(float), nrows_to_fetch); + uint8_t *next_buf = act_spad + 1 * R * row_bytes; + dma_queue_push(dma_q, dma_make_data(next_buf, act_dma_addr + (size_t) next_r * src_row_bytes + src_col_offset), + row_bytes, src_row_bytes, width_bytes, nrows_to_fetch); } } for (uint32_t s = 0; s < n_steps; ++s) { uint32_t r = s << dma_step_rows_shift; - float *curr_buf = thread_f32_act; + uint8_t *curr_buf = act_spad; if (r < n_rows) { - curr_buf = (float *) dma_queue_pop(dma_q).dst; + curr_buf = (uint8_t *) dma_queue_pop(dma_q).dst; } htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, r); - for (uint32_t p = 0; p < (R >> 1); ++p) { - uint32_t row_idx = r + (p << 1); - float *pair_buf = curr_buf + (p << 1) * c_len; - bool r0_valid = ((row_idx + 0) < n_rows); - bool r1_valid = ((row_idx + 1) < n_rows); - - transfer_activation_row_pair_fp32_to_fp16_col_chunk( - vtcm_dst, pair_buf, pair_buf + c_len, row_idx, k_block, c_first, c_len, k_chunk_valid, r0_valid, r1_valid - ); + if (act_is_f16) { + for (uint32_t p = 0; p < (R >> 1); ++p) { + uint32_t row_idx = r + (p << 1); + const __fp16 *pair_buf = (const __fp16 *) (curr_buf + (p << 1) * row_bytes); + bool r0_valid = ((row_idx + 0) < n_rows); + bool r1_valid = ((row_idx + 1) < n_rows); + + transfer_activation_row_pair_f16_to_f16_col_chunk( + vtcm_dst, pair_buf, pair_buf + c_len, row_idx, k_block, c_first, c_len, k_chunk_valid, r0_valid, r1_valid + ); + } + } else { + for (uint32_t p = 0; p < (R >> 1); ++p) { + uint32_t row_idx = r + (p << 1); + const float *pair_buf = (const float *) (curr_buf + (p << 1) * row_bytes); + bool r0_valid = ((row_idx + 0) < n_rows); + bool r1_valid = ((row_idx + 1) < n_rows); + + transfer_activation_row_pair_fp32_to_fp16_col_chunk( + vtcm_dst, pair_buf, pair_buf + c_len, row_idx, k_block, c_first, c_len, k_chunk_valid, r0_valid, r1_valid + ); + } } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, r); @@ -2114,8 +2253,8 @@ static void transfer_activation_chunk_fp32_to_fp16_dma_pipelined_col_chunk( uint32_t next_r = next_s << dma_step_rows_shift; if (next_r < n_rows) { uint32_t nrows_to_fetch = hex_smin(n_rows - next_r, R); - dma_queue_push(dma_q, dma_make_data(curr_buf, act_dma_addr + ((size_t) next_r * k_stride + c_first) * sizeof(float)), - c_len * sizeof(float), k_stride * sizeof(float), k_chunk_valid * sizeof(float), nrows_to_fetch); + dma_queue_push(dma_q, dma_make_data(curr_buf, act_dma_addr + (size_t) next_r * src_row_bytes + src_col_offset), + row_bytes, src_row_bytes, width_bytes, nrows_to_fetch); } } } @@ -2125,11 +2264,19 @@ static void transfer_activation_chunk_col_chunk_worker_fn(const htp_thread_t * t struct htp_thread_trace * tr = th->trace; uint32_t n_blocks = st->k_block / 32; - uint32_t b_first = fastdiv(n_blocks * i, &st->n_hvx_div); - uint32_t b_last = fastdiv(n_blocks * (i + 1), &st->n_hvx_div); + uint32_t b_first; + uint32_t b_last; + if (st->act_elem_size == sizeof(__fp16)) { + uint32_t n_pairs = n_blocks / 2; + b_first = fastdiv(n_pairs * i, &st->n_hvx_div) * 2; + b_last = fastdiv(n_pairs * (i + 1), &st->n_hvx_div) * 2; + } else { + b_first = fastdiv(n_blocks * i, &st->n_hvx_div); + b_last = fastdiv(n_blocks * (i + 1), &st->n_hvx_div); + } uint32_t c_first = b_first * 32; - uint32_t c_last = b_last * 32; - uint32_t c_len = c_last - c_first; + uint32_t c_last = b_last * 32; + uint32_t c_len = c_last - c_first; if (c_len == 0) { return; @@ -2142,12 +2289,12 @@ static void transfer_activation_chunk_col_chunk_worker_fn(const htp_thread_t * t __fp16 *dst = st->dst; - size_t thread_scratch_bytes = hex_align_down(fastdiv(st->vtcm_f32_act_bytes, &st->n_hvx_div), 128); - float *thread_f32_act = (float *)((char *)st->vtcm_f32_act + i * thread_scratch_bytes); + size_t scratch_bytes_per_hvx = hex_align_down(fastdiv(st->vtcm_f32_act_bytes, &st->n_hvx_div), 128); + uint8_t *act_spad = (uint8_t *)st->vtcm_f32_act + i * scratch_bytes_per_hvx; - transfer_activation_chunk_fp32_to_fp16_dma_pipelined_col_chunk( + transfer_activation_chunk_to_fp16_dma_pipelined_col_chunk( th->dma_q, dst, st->act_dma_addr, st->n_rows, st->k_block, st->k_stride, k_chunk_valid, - c_first, c_len, thread_f32_act, tr, st->dma_step_rows, st->dma_step_rows_shift + c_first, c_len, act_spad, st->act_elem_size, tr, st->dma_step_rows, st->dma_step_rows_shift ); } @@ -2159,7 +2306,7 @@ static void transfer_activation_chunk_to_fp16_dma_pipelined( uint32_t k_block, uint32_t k_stride, uint32_t k_valid, - uint8_t *thread_act, + uint8_t *act_spad, uint32_t act_elem_size, struct htp_thread_trace *tr, uint32_t dma_step_rows, @@ -2178,7 +2325,7 @@ static void transfer_activation_chunk_to_fp16_dma_pipelined( // Push step 0 if (n_steps > 0 && n_rows > 0) { uint32_t nrows_to_fetch = hex_smin(n_rows, R); - dma_queue_push(dma_q, dma_make_data(thread_act, act_dma_addr), + dma_queue_push(dma_q, dma_make_data(act_spad, act_dma_addr), row_bytes, src_row_bytes, width_bytes, nrows_to_fetch); } // Push step 1 (if valid) @@ -2186,14 +2333,14 @@ static void transfer_activation_chunk_to_fp16_dma_pipelined( uint32_t next_r = R * 1; if (next_r < n_rows) { uint32_t nrows_to_fetch = hex_smin(n_rows - next_r, R); - uint8_t *next_buf = thread_act + 1 * R * row_bytes; + uint8_t *next_buf = act_spad + 1 * R * row_bytes; dma_queue_push(dma_q, dma_make_data(next_buf, act_dma_addr + (size_t) next_r * src_row_bytes), row_bytes, src_row_bytes, width_bytes, nrows_to_fetch); } } for (uint32_t s = 0; s < n_steps; ++s) { uint32_t r = s << dma_step_rows_shift; - uint8_t *curr_buf = thread_act; + uint8_t *curr_buf = act_spad; if (r < n_rows) { curr_buf = (uint8_t *) dma_queue_pop(dma_q).dst; @@ -2246,19 +2393,103 @@ static void transfer_activation_chunk_worker_fn(const htp_thread_t * th, unsigne __fp16 *dst = st->dst + chunk_idx * st->k_block; const dma_addr_t act_dma_addr = st->act_dma_addr + (size_t) chunk_idx * st->k_stride * st->act_elem_size; - uint8_t *thread_act = (uint8_t *) st->vtcm_f32_act + i * st->vtcm_f32_act_bytes_per_hvx; + uint8_t *act_spad = (uint8_t *) st->vtcm_f32_act + i * st->vtcm_f32_act_bytes_per_hvx; transfer_activation_chunk_to_fp16_dma_pipelined( - th->dma_q, dst, act_dma_addr, chunk_size, st->k_block, st->k_stride, st->k_valid, thread_act, st->act_elem_size, tr, st->dma_step_rows, st->dma_step_rows_shift + th->dma_q, dst, act_dma_addr, chunk_size, st->k_block, st->k_stride, st->k_valid, act_spad, st->act_elem_size, tr, st->dma_step_rows, st->dma_step_rows_shift ); } } +static inline void push_gathered_act_rows_dma( + dma_queue * dma_q, + uint8_t * slot_buf, + dma_addr_t act_dma_addr, + uint32_t valid_rows, + uint32_t start_row, + uint32_t r, + size_t row_bytes, + size_t valid_bytes, + const struct mmid_row_mapping * matrix_rows, + uint32_t cur_a, + uint32_t mapping_stride, + uint32_t ne11, + const struct fastdiv_values * ne11_div, + size_t nb11, + size_t nb12) { + const size_t base_idx = (size_t) cur_a * mapping_stride + start_row + r; + if (ne11 == 1) { + for (uint32_t s = 0; s < valid_rows; ++s) { + const struct mmid_row_mapping mapping = matrix_rows[base_idx + s]; + const dma_addr_t src_row = act_dma_addr + (size_t) mapping.i2 * nb12; + dma_queue_push(dma_q, dma_make_data(slot_buf + (size_t) s * row_bytes, src_row), + valid_bytes, valid_bytes, valid_bytes, 1); + } + } else { + for (uint32_t s = 0; s < valid_rows; ++s) { + const struct mmid_row_mapping mapping = matrix_rows[base_idx + s]; + const uint32_t i11 = fastmodulo(mapping.i1, ne11, ne11_div); + const dma_addr_t src_row = act_dma_addr + (size_t) i11 * nb11 + (size_t) mapping.i2 * nb12; + dma_queue_push(dma_q, dma_make_data(slot_buf + (size_t) s * row_bytes, src_row), + valid_bytes, valid_bytes, valid_bytes, 1); + } + } +} + +static inline void push_scattered_dst_rows_dma( + dma_queue * dma_q, + dma_addr_t dst_dma_addr, + const uint8_t * vtcm_src, + uint32_t start_row, + uint32_t n_rows, + size_t vtcm_row_bytes, + size_t copy_bytes, + const struct mmid_row_mapping * matrix_rows, + uint32_t cur_a, + uint32_t mapping_stride, + size_t dst_nb1, + size_t dst_nb2) { + const size_t base_idx = (size_t) cur_a * mapping_stride + start_row; + for (uint32_t r = 0; r < n_rows; ++r) { + const struct mmid_row_mapping mapping = matrix_rows[base_idx + r]; + const dma_addr_t dst_row = dst_dma_addr + (size_t) mapping.i1 * dst_nb1 + (size_t) mapping.i2 * dst_nb2; + dma_queue_push(dma_q, dma_make_data(dst_row, vtcm_src + (size_t) r * vtcm_row_bytes), + copy_bytes, copy_bytes, copy_bytes, 1); + } +} + +static inline void sync_scattered_dst_rows_dma( + dma_queue * dma_q, + dma_addr_t dst_dma_addr, + const uint8_t * vtcm_src, + uint32_t start_row, + uint32_t n_rows, + size_t vtcm_row_bytes, + size_t copy_bytes, + const struct mmid_row_mapping * matrix_rows, + uint32_t cur_a, + uint32_t mapping_stride, + size_t dst_nb1, + size_t dst_nb2) { + for (uint32_t r = 0; r < n_rows; r += 128u) { + const uint32_t batch = hex_smin(n_rows - r, 128u); + push_scattered_dst_rows_dma(dma_q, dst_dma_addr, vtcm_src + (size_t) r * vtcm_row_bytes, + start_row + r, batch, vtcm_row_bytes, copy_bytes, + matrix_rows, cur_a, mapping_stride, dst_nb1, dst_nb2); + for (uint32_t s = 0; s < batch; ++s) { + dma_queue_pop(dma_q); + } + } +} + typedef struct { const struct mmid_row_mapping * matrix_rows; __fp16 * dst; - const float * src; - uint32_t n_tasks; - uint32_t n_tot_chunks; + dma_addr_t act_dma_addr; + float * vtcm_f32_act; + size_t vtcm_f32_act_bytes_per_hvx; + size_t act_elem_size; + uint32_t n_rows; + uint32_t mc_pad; uint32_t n_chunks_per_task; uint32_t k_block; uint32_t cur_a; @@ -2268,90 +2499,95 @@ typedef struct { size_t nb11; size_t nb12; uint32_t start_row; - uint32_t cne1; uint32_t k_valid; } activation_transfer_gathered_task_state_t; -typedef struct { - const struct mmid_row_mapping * matrix_rows; - const __fp16 * vtcm_src; - float * dst; - uint32_t n_tasks; - uint32_t n_tot_chunks; - uint32_t n_chunks_per_task; - uint32_t n_cols; - uint32_t cur_a; - uint32_t mapping_stride; - size_t dst_nb1; - size_t dst_nb2; - uint32_t start_row; - uint32_t cne1; -} output_transfer_scattered_task_state_t; - static void transfer_activation_chunk_gathered_worker_fn(const htp_thread_t * th, unsigned int n, unsigned int i, void *data) { - activation_transfer_gathered_task_state_t *st = data; + (void) n; + activation_transfer_gathered_task_state_t * st = (activation_transfer_gathered_task_state_t *) data; struct htp_thread_trace * tr = th->trace; - int chunk_idx = i; - int chunk_size = st->n_chunks_per_task; - int vtcm_start_row = chunk_idx * chunk_size; - int start_row = st->start_row + vtcm_start_row; - int n_rows = hex_smin(st->cne1 - start_row, chunk_size); - if (n_rows > 0) { - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, chunk_idx); - transfer_activation_chunk_fp32_to_fp16_gathered( - st->dst, st->src, start_row, vtcm_start_row, n_rows, st->k_block, - st->matrix_rows, st->cur_a, st->mapping_stride, - st->ne11, &st->ne11_div, st->nb11, st->nb12, st->cne1, st->k_valid); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, chunk_idx); - } -} + dma_queue * dma_q = th->dma_q; -static void transfer_activation_chunk_gathered_worker_flat_fn(const htp_thread_t * th, unsigned int n, unsigned int i, void *data) { - activation_transfer_gathered_task_state_t *st = data; - struct htp_thread_trace * tr = th->trace; - int chunk_idx = i; - int chunk_size = st->n_chunks_per_task; - int vtcm_start_row = chunk_idx * chunk_size; - int start_row = st->start_row + vtcm_start_row; - int n_rows = hex_smin(st->cne1 - start_row, chunk_size); - if (n_rows > 0) { - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, chunk_idx); - transfer_activation_chunk_fp32_to_fp16_gathered_flat( - st->dst, st->src, start_row, vtcm_start_row, n_rows, st->k_block, - st->matrix_rows, st->cur_a, st->mapping_stride, - st->nb12, st->cne1, st->k_valid); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, chunk_idx); + const uint32_t vtcm_start_row = i * st->n_chunks_per_task; + if (vtcm_start_row >= st->mc_pad) { + return; } -} - -static void transfer_output_chunk_scattered_worker_fn(const htp_thread_t * th, unsigned int n, unsigned int i, void *data) { - output_transfer_scattered_task_state_t *st = data; - struct htp_thread_trace * tr = th->trace; - int chunk_idx = i; - int chunk_size = st->n_chunks_per_task; - int vtcm_start_row = chunk_idx * chunk_size; - int start_row = st->start_row + vtcm_start_row; - int n_rows = hex_smin(st->cne1 - start_row, chunk_size); - if (n_rows > 0) { - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, chunk_idx); - transfer_output_chunk_fp16_to_fp32_scattered( - st->dst, st->vtcm_src, start_row, vtcm_start_row, n_rows, st->n_cols, - st->matrix_rows, st->cur_a, st->mapping_stride, - st->dst_nb1, st->dst_nb2, st->cne1); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, chunk_idx); + const uint32_t vtcm_end_row = hex_smin(vtcm_start_row + st->n_chunks_per_task, st->mc_pad); + const bool act_is_f16 = (st->act_elem_size == sizeof(__fp16)); + const size_t row_bytes = (size_t) st->k_block * st->act_elem_size; + const size_t valid_bytes = (size_t) st->k_valid * st->act_elem_size; + const size_t slot_bytes = 2u * row_bytes; + const bool double_buf = (st->vtcm_f32_act_bytes_per_hvx >= 2u * slot_bytes); + uint8_t * act_spad = (uint8_t *) st->vtcm_f32_act + i * st->vtcm_f32_act_bytes_per_hvx; + + if (double_buf) { + if (vtcm_start_row < st->n_rows) { + const uint32_t nrows = hex_smin(st->n_rows - vtcm_start_row, 2u); + push_gathered_act_rows_dma(dma_q, act_spad, st->act_dma_addr, nrows, st->start_row, vtcm_start_row, + row_bytes, valid_bytes, st->matrix_rows, st->cur_a, st->mapping_stride, + st->ne11, &st->ne11_div, st->nb11, st->nb12); + } + const uint32_t r1 = vtcm_start_row + 2u; + if (r1 < vtcm_end_row && r1 < st->n_rows) { + const uint32_t nrows = hex_smin(st->n_rows - r1, 2u); + push_gathered_act_rows_dma(dma_q, act_spad + slot_bytes, st->act_dma_addr, nrows, st->start_row, r1, + row_bytes, valid_bytes, st->matrix_rows, st->cur_a, st->mapping_stride, + st->ne11, &st->ne11_div, st->nb11, st->nb12); + } } -} -// --- HMX Dispatchers & Entry Points --- + uint32_t step = 0; + for (uint32_t r = vtcm_start_row; r < vtcm_end_row; r += 2u, ++step) { + uint8_t * curr_buf = act_spad + (double_buf ? (step & 1u) * slot_bytes : 0u); + const uint32_t valid_rows = (r < st->n_rows) ? hex_smin(st->n_rows - r, 2u) : 0u; -static inline tiled_dequant_task_fn_t hmx_get_dequant_worker_fn(int weight_type, bool is_tiled) { - switch (weight_type) { - case HTP_TYPE_Q4_0: return dequantize_tiled_weight_to_fp16_task_q4_0; - case HTP_TYPE_IQ4_NL: return dequantize_tiled_weight_to_fp16_task_iq4_nl; - case HTP_TYPE_Q4_1: - case HTP_TYPE_Q4_K: return dequantize_tiled_weight_to_fp16_task_q4_1; - case HTP_TYPE_MXFP4: return dequantize_tiled_weight_to_fp16_task_mxfp4; - case HTP_TYPE_NVFP4: return dequantize_tiled_weight_to_fp16_task_nvfp4; + if (valid_rows > 0) { + if (!double_buf) { + push_gathered_act_rows_dma(dma_q, curr_buf, st->act_dma_addr, valid_rows, st->start_row, r, + row_bytes, valid_bytes, st->matrix_rows, st->cur_a, st->mapping_stride, + st->ne11, &st->ne11_div, st->nb11, st->nb12); + } + for (uint32_t s = 0; s < valid_rows; ++s) { + dma_queue_pop(dma_q); + } + } + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, r); + if (act_is_f16) { + const __fp16 * pair_buf = (const __fp16 *) curr_buf; + transfer_activation_row_pair_f16_to_f16( + st->dst, pair_buf, pair_buf + st->k_block, r, st->k_block, st->k_valid, + valid_rows >= 1u, valid_rows >= 2u); + } else { + const float * pair_buf = (const float *) curr_buf; + transfer_activation_row_pair_fp32_to_fp16( + st->dst, pair_buf, pair_buf + st->k_block, r, st->k_block, st->k_valid, + valid_rows >= 1u, valid_rows >= 2u); + } + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, r); + + if (double_buf) { + const uint32_t next_r = r + 4u; + if (next_r < vtcm_end_row && next_r < st->n_rows) { + const uint32_t nrows = hex_smin(st->n_rows - next_r, 2u); + push_gathered_act_rows_dma(dma_q, curr_buf, st->act_dma_addr, nrows, st->start_row, next_r, + row_bytes, valid_bytes, st->matrix_rows, st->cur_a, st->mapping_stride, + st->ne11, &st->ne11_div, st->nb11, st->nb12); + } + } + } +} + +// --- HMX Dispatchers & Entry Points --- + +static inline tiled_dequant_task_fn_t hmx_get_dequant_worker_fn(int weight_type, bool is_tiled) { + switch (weight_type) { + case HTP_TYPE_Q4_0: return dequantize_tiled_weight_to_fp16_task_q4_0; + case HTP_TYPE_IQ4_NL: return dequantize_tiled_weight_to_fp16_task_iq4_nl; + case HTP_TYPE_Q4_1: + case HTP_TYPE_Q4_K: return dequantize_tiled_weight_to_fp16_task_q4_1; + case HTP_TYPE_MXFP4: return dequantize_tiled_weight_to_fp16_task_mxfp4; + case HTP_TYPE_NVFP4: return dequantize_tiled_weight_to_fp16_task_nvfp4; case HTP_TYPE_IQ2_XXS: return dequantize_tiled_weight_to_fp16_task_iq2_xxs; case HTP_TYPE_Q8_0: return dequantize_tiled_weight_to_fp16_task_q8_0; case HTP_TYPE_Q5_0: return dequantize_tiled_weight_to_fp16_task_q5_0; @@ -2370,12 +2606,12 @@ static inline tiled_dequant_task_fn_t hmx_get_dequant_worker_fn(int weight_type, } static void dequantize_tiled_weight_chunk_to_fp16_tiles( - struct htp_context *ctx, __fp16 *vtcm_dst, + struct htp_ops_context *octx, __fp16 *vtcm_dst, const void *weight_src_ddr, int n_cols, int k_block, size_t row_stride, int weight_type, int n_k_tiles, struct fastdiv_values n_k_tiles_div, - tiled_dequant_task_fn_t dequant_worker_fn, int n_hvx) { + tiled_dequant_task_fn_t dequant_worker_fn) { if (!dequant_worker_fn) { return; @@ -2383,14 +2619,19 @@ static void dequantize_tiled_weight_chunk_to_fp16_tiles( assert(k_block % HTP_MM_HMX_TILE_N_COLS == 0); - const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS); + const int n_hvx = (int) octx->n_hvx; + const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS); const uint32_t n_weight_tiles = k_block / htp_tensor_get_tile_k(weight_type); - const size_t n_tot_tiles = n_col_tiles * n_weight_tiles; + const size_t n_tot_tiles = n_col_tiles * n_weight_tiles; + if (n_tot_tiles == 0) { + return; + } - size_t n_tiles_per_task = (n_hvx == 1) ? n_tot_tiles : hmx_ceil_div(n_tot_tiles, n_hvx); + const size_t n_tiles_per_task = (n_hvx <= 1) ? n_tot_tiles + : fastdiv(n_tot_tiles + (uint32_t) n_hvx - 1, &octx->n_hvx_div); tiled_dequantize_state_t state; - state.n_tasks = (n_tot_tiles + n_tiles_per_task - 1) / n_tiles_per_task; + state.n_tasks = hex_smin((int) n_tot_tiles, n_hvx); state.n_tot_tiles = n_tot_tiles; state.n_tiles_per_task = n_tiles_per_task; state.dst = vtcm_dst; @@ -2404,23 +2645,26 @@ static void dequantize_tiled_weight_chunk_to_fp16_tiles( state.n_weight_tiles = n_weight_tiles; state.n_k_tiles_div = n_k_tiles_div; - state.tile_size = htp_tensor_get_tile_size(weight_type); - state.aligned_tile_size = htp_tensor_get_tile_padded_size(weight_type); + const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params; + state.tile_size = kparams->tile_size; + state.aligned_tile_size = kparams->aligned_tile_size; - int n_tasks = hex_smin((int) state.n_tasks, n_hvx); - work_queue_run(ctx->hvx_queue, dequantize_tiled_worker_loop, &state, n_tasks); + work_queue_run(octx->ctx->hvx_queue, dequantize_tiled_worker_loop, &state, (int) state.n_tasks); } typedef struct { - float * dst; - const __fp16 * vtcm_src; - const float * src2; - uint32_t n_rows; - uint32_t n_cols; - uint32_t dst_stride; - uint32_t src2_stride; - uint32_t dst_cols; - struct fastdiv_values n_hvx_div; + hmx_fp16_output_col_chunk_fn_t col_chunk_fn; + void * dst; + const __fp16 * vtcm_src; + const void * bias; + uint32_t n_rows; + uint32_t n_cols; + uint32_t dst_stride; + uint32_t bias_stride; + uint32_t dst_cols; + size_t dst_elem_size; + size_t bias_elem_size; + struct fastdiv_values n_hvx_div; } output_transfer_col_chunk_state_t; static void transfer_output_chunk_col_chunk_worker_fn(const htp_thread_t * th, unsigned int n, unsigned int i, void *data) { @@ -2431,72 +2675,97 @@ static void transfer_output_chunk_col_chunk_worker_fn(const htp_thread_t * th, u // Round up: the last block is partial when N is not 32-aligned. Its pad // columns are dropped by the dst_cols clamp inside the store. uint32_t n_blocks = hmx_ceil_div(st->n_cols, 32); - uint32_t b_first = fastdiv(n_blocks * i, &st->n_hvx_div); - uint32_t b_last = fastdiv(n_blocks * (i + 1), &st->n_hvx_div); - uint32_t c_first = b_first * 32; - uint32_t c_last = b_last * 32; - uint32_t c_len = c_last - c_first; - - if (c_len == 0) return; + uint32_t b_first; + uint32_t b_last; + if (st->dst_elem_size == sizeof(__fp16)) { + uint32_t n_pairs = hmx_ceil_div(n_blocks, 2); + b_first = fastdiv(n_pairs * i, &st->n_hvx_div) * 2; + b_last = MIN(n_blocks, fastdiv(n_pairs * (i + 1), &st->n_hvx_div) * 2); + } else { + b_first = fastdiv(n_blocks * i, &st->n_hvx_div); + b_last = fastdiv(n_blocks * (i + 1), &st->n_hvx_div); + } + if (b_first >= b_last) return; + uint32_t c_first = b_first * 32; + uint32_t c_last = b_last * 32; + uint32_t c_len = c_last - c_first; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, c_first); - const __fp16 *vtcm_src = st->vtcm_src + b_first * HTP_MM_HMX_TILE_N_ELMS; - const float *src2 = st->src2 ? (st->src2 + c_first) : NULL; - float *dst = st->dst + c_first; + const __fp16 * vtcm_src = st->vtcm_src + b_first * HTP_MM_HMX_TILE_N_ELMS; + const void * bias = st->bias ? ((const uint8_t *) st->bias + (size_t) c_first * st->bias_elem_size) : NULL; + void * dst = (uint8_t *) st->dst + (size_t) c_first * st->dst_elem_size; int chunk_dst_cols = (int)st->dst_cols - (int)c_first; if (chunk_dst_cols > 0) { - transfer_output_chunk_fp16_to_fp32_col_chunk( - dst, src2, vtcm_src, 0, st->n_rows, c_len, st->n_cols, - st->dst_stride, st->src2_stride, (uint32_t)chunk_dst_cols - ); + st->col_chunk_fn(dst, bias, vtcm_src, 0, st->n_rows, c_len, st->n_cols, + st->dst_stride, st->bias_stride, (uint32_t)chunk_dst_cols, st->bias_elem_size); } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, c_first); } -static void transfer_output_chunk_threaded(struct htp_context *ctx, float *dst, const float *src2, const __fp16 *vtcm_src, - int n_rows, int n_cols, int dst_stride, uint32_t src2_stride, int dst_cols, int n_hvx) { - if (n_rows <= 0) return; - - uint32_t n_blocks = hmx_ceil_div((uint32_t) n_cols, 32); - if (n_hvx > 1 && n_blocks >= (uint32_t)n_hvx) { - struct fastdiv_values n_hvx_div = (n_hvx == (int)ctx->n_hvx) ? ctx->n_hvx_div : init_fastdiv_values(n_hvx); - output_transfer_col_chunk_state_t col_state; - col_state.dst = dst; - col_state.src2 = src2; - col_state.vtcm_src = vtcm_src; - col_state.n_rows = (uint32_t)n_rows; - col_state.n_cols = (uint32_t)n_cols; - col_state.dst_stride = (uint32_t)dst_stride; - col_state.src2_stride = src2_stride; - col_state.dst_cols = (uint32_t)dst_cols; - col_state.n_hvx_div = n_hvx_div; - - work_queue_run(ctx->hvx_queue, transfer_output_chunk_col_chunk_worker_fn, &col_state, n_hvx); +static void transfer_output_chunk_threaded(struct htp_ops_context *octx, void *dst, const void *bias, const __fp16 *vtcm_src, + int n_rows, int n_cols, int dst_stride, uint32_t bias_stride, int dst_cols, + size_t dst_elem_size, size_t bias_elem_size) { + if (n_rows <= 0 || dst_cols <= 0) { return; } - size_t n_tot_chunks = n_rows; - size_t n_chunks_per_task = (n_hvx == 1) ? n_tot_chunks : hmx_ceil_div(n_rows, n_hvx); - n_chunks_per_task = hex_align_up(n_chunks_per_task, 2); + const bool dst_aligned_nt = ((((uintptr_t) dst | ((size_t) dst_stride * dst_elem_size)) & 127u) == 0); + const hmx_fp16_output_col_chunk_fn_t col_chunk_fn = + resolve_fp16_output_col_chunk_fn(dst_elem_size, bias, bias_elem_size, dst_aligned_nt); + + const int n_hvx = (int) octx->n_hvx; + const uint32_t n_blocks = hmx_ceil_div((uint32_t) n_cols, 32); + const uint32_t n_units = (dst_elem_size == sizeof(__fp16)) ? hmx_ceil_div(n_blocks, 2) : n_blocks; + const bool prefer_row_chunk = ((uint32_t) n_rows >= (uint32_t) n_hvx * 32u); + if (n_hvx > 1 && !prefer_row_chunk && n_units >= (uint32_t) n_hvx) { + const uint32_t n_row_pairs = ((uint32_t) n_rows + 1u) >> 1; + const uint32_t row_max = fastdiv(n_row_pairs + (uint32_t) n_hvx - 1u, &octx->n_hvx_div); + const uint32_t col_max = fastdiv(n_units + (uint32_t) n_hvx - 1u, &octx->n_hvx_div); + if ((uint64_t) n_units * row_max > (uint64_t) n_row_pairs * col_max) { + output_transfer_col_chunk_state_t col_state; + col_state.col_chunk_fn = col_chunk_fn; + col_state.dst = dst; + col_state.bias = bias; + col_state.vtcm_src = vtcm_src; + col_state.n_rows = (uint32_t) n_rows; + col_state.n_cols = (uint32_t) n_cols; + col_state.dst_stride = (uint32_t) dst_stride; + col_state.bias_stride = bias_stride; + col_state.dst_cols = (uint32_t) dst_cols; + col_state.dst_elem_size = dst_elem_size; + col_state.bias_elem_size = bias_elem_size; + col_state.n_hvx_div = octx->n_hvx_div; + + work_queue_run(octx->ctx->hvx_queue, transfer_output_chunk_col_chunk_worker_fn, &col_state, n_hvx); + return; + } + } - int actual_hvx = hmx_ceil_div(n_rows, n_chunks_per_task); + const uint32_t chunk_align = prefer_row_chunk ? 32u : 2u; + uint32_t n_chunks_per_task = (n_hvx <= 1) ? (uint32_t) n_rows + : fastdiv((uint32_t) n_rows + (uint32_t) n_hvx - 1u, &octx->n_hvx_div); + n_chunks_per_task = hex_align_up(n_chunks_per_task, chunk_align); + const int actual_hvx = hex_smin(n_hvx, ((int) n_rows + 1) >> 1); output_transfer_task_state_t state; - state.n_tasks = actual_hvx; - state.n_tot_chunks = n_tot_chunks; + state.col_chunk_fn = col_chunk_fn; + state.n_tasks = (uint32_t) actual_hvx; + state.n_tot_chunks = (uint32_t) n_rows; state.n_chunks_per_task = n_chunks_per_task; state.dst = dst; - state.src2 = src2; + state.bias = bias; state.vtcm_src = vtcm_src; - state.n_cols = n_cols; - state.dst_stride = dst_stride; - state.src2_stride = src2_stride; - state.dst_cols = dst_cols; - - work_queue_run(ctx->hvx_queue, transfer_output_chunk_worker_fn, &state, actual_hvx); + state.n_cols = (uint32_t) n_cols; + state.dst_stride = (uint32_t) dst_stride; + state.bias_stride = bias_stride; + state.dst_cols = (uint32_t) dst_cols; + state.dst_elem_size = dst_elem_size; + state.bias_elem_size = bias_elem_size; + + work_queue_run(octx->ctx->hvx_queue, transfer_output_chunk_worker_fn, &state, actual_hvx); } struct activation_transfer_params { @@ -2536,14 +2805,17 @@ static void transfer_activation_chunk_threaded(const struct activation_transfer_ } const size_t n_tasks = (n_rows + 31) >> 5; - if (act_elem_size == sizeof(float) && n_hvx > 1 && k_block > 32 && n_tasks < (size_t) n_hvx) { + const bool col_chunk_ok = (act_elem_size == sizeof(float)) + ? (k_block >= 32 * n_hvx) + : ((k_block & 63) == 0 && (k_block >> 6) >= n_hvx); + if (n_hvx > 1 && col_chunk_ok && n_tasks < (size_t) n_hvx) { // Calculate step rows parameters for column-chunked dma pipelining uint32_t dma_step_rows = 2; uint32_t dma_step_rows_shift = 1; if (vtcm_f32_act_bytes > 0) { - size_t thread_scratch_bytes = hex_align_down(fastdiv(vtcm_f32_act_bytes, act_hvx_div), 128); - size_t thread_scratch_elements = thread_scratch_bytes / sizeof(float); - size_t dma_step_rows_max = fastdiv(thread_scratch_elements / 2, k_div); + size_t scratch_bytes_per_hvx = hex_align_down(fastdiv(vtcm_f32_act_bytes, act_hvx_div), 128); + size_t scratch_elems_per_hvx = scratch_bytes_per_hvx / act_elem_size; + size_t dma_step_rows_max = fastdiv(scratch_elems_per_hvx / 2, k_div); if (dma_step_rows_max >= 4) { dma_step_rows = 4; dma_step_rows_shift = 2; @@ -2563,6 +2835,7 @@ static void transfer_activation_chunk_threaded(const struct activation_transfer_ col_state.vtcm_f32_act_bytes = vtcm_f32_act_bytes; col_state.dma_step_rows = dma_step_rows; col_state.dma_step_rows_shift = dma_step_rows_shift; + col_state.act_elem_size = act_elem_size; work_queue_run(ctx->hvx_queue, transfer_activation_chunk_col_chunk_worker_fn, &col_state, n_hvx); return; @@ -2590,8 +2863,8 @@ static void transfer_activation_chunk_threaded(const struct activation_transfer_ uint32_t dma_step_rows = 2; uint32_t dma_step_rows_shift = 1; if (state.vtcm_f32_act_bytes_per_hvx > 0) { - size_t thread_scratch_elements = state.vtcm_f32_act_bytes_per_hvx / sizeof(float); - size_t dma_step_rows_max = fastdiv(thread_scratch_elements / 2, k_div); + size_t scratch_elems_per_hvx = state.vtcm_f32_act_bytes_per_hvx / act_elem_size; + size_t dma_step_rows_max = fastdiv(scratch_elems_per_hvx / 2, k_div); if (dma_step_rows_max >= 4) { dma_step_rows = 4; dma_step_rows_shift = 2; @@ -2603,25 +2876,686 @@ static void transfer_activation_chunk_threaded(const struct activation_transfer_ int active_hvx = hex_smin(n_hvx, (int)state.n_tasks); work_queue_run(ctx->hvx_queue, transfer_activation_chunk_worker_fn, &state, active_hvx); } -// --- Async HMX matmul job (for pipeline overlap) --- + +// --- INT HMX W8A8 SM Threaded Helpers --- + +static void rescale_int_weight_worker_loop(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { + int_weight_rescale_state_t * state = (int_weight_rescale_state_t *) data; + struct htp_thread_trace * tr = th->trace; + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, i); + for (unsigned int task_id = i; task_id < state->n_tasks; task_id += n) { + uint32_t start = task_id * state->n_units_per_task; + if (start >= state->n_tot_units) { + break; + } + uint32_t end = hex_smin(start + state->n_units_per_task, state->n_tot_units); + rescale_int_weight_to_int8_task(state, start, end); + } + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_DEQUANT, i); +} + +static void rescale_int_weight_chunk_to_int8_tiles_scales( + struct htp_ops_context * octx, + void * vtcm_weight_buf, + size_t weight_bias_offset, + float * dst_scales, + const void * weight_src_raw, + int n_cols, + int k_block, + int n_groups, + const struct fastdiv_values * n_groups_div, + int aligned_tile_size, + int32_t weight_type) { + + const int n_hvx = (int) octx->n_hvx; + const uint32_t n_col_tiles = (uint32_t) hmx_ceil_div(n_cols, 32); + const uint32_t n_k_tiles = (uint32_t) (k_block >> 5); + const uint32_t tail_tiles = n_k_tiles - ((uint32_t) n_groups - 1u) * HTP_MM_HMX_W8A8_KGROUP_TILES; + const uint32_t n_tot_units = n_col_tiles * (uint32_t) n_groups; + if (n_tot_units == 0) { + return; + } + + const uint32_t n_units_per_task = (n_hvx <= 1) ? n_tot_units + : fastdiv(n_tot_units + (uint32_t) n_hvx - 1, &octx->n_hvx_div); + + int_weight_rescale_state_t state; + resolve_int_weight_rescale_fns(weight_type, &state.rescale_2k_fn, &state.rescale_tail_fn); + state.dst_wt_base = (uint8_t *) vtcm_weight_buf; + state.dst_bias_base = (uint8_t *) vtcm_weight_buf + weight_bias_offset; + state.dst_scales_base = dst_scales; + state.src_raw = (const uint8_t *) weight_src_raw; + state.n_col_tiles = n_col_tiles; + state.n_k_tiles = n_k_tiles; + state.n_groups = (uint32_t) n_groups; + state.tail_tiles = tail_tiles; + state.aligned_tile_size = (uint32_t) aligned_tile_size; + state.raw_shift = (weight_type == HTP_TYPE_Q1_0) ? 2u + : ((weight_type == HTP_TYPE_Q2_0) ? 1u : 0u); + state.n_tot_units = n_tot_units; + state.n_units_per_task = n_units_per_task; + state.n_tasks = hex_smin(n_tot_units, (uint32_t) n_hvx); + state.n_groups_div = *n_groups_div; + + work_queue_run(octx->ctx->hvx_queue, rescale_int_weight_worker_loop, &state, (int) state.n_tasks); +} + +static void rescale_int_weight_chunk_to_int8_tiles( + struct htp_ops_context * octx, + void * vtcm_weight_buf, + size_t weight_bias_offset, + size_t weight_scales_offset, + const void * weight_src_raw, + int n_cols, + int k_block, + int n_groups, + const struct fastdiv_values * n_groups_div, + int aligned_tile_size, + int32_t weight_type) { + float * dst_scales = (float *) ((uint8_t *) vtcm_weight_buf + weight_scales_offset); + rescale_int_weight_chunk_to_int8_tiles_scales( + octx, vtcm_weight_buf, weight_bias_offset, dst_scales, + weight_src_raw, n_cols, k_block, n_groups, n_groups_div, aligned_tile_size, weight_type); +} + +typedef void (*int_act_dma_pipelined_fn_t)( + dma_queue * dma_q, + uint8_t * restrict vtcm_act_dst, + float * restrict vtcm_act_scales, + dma_addr_t act_dma_addr, + uint32_t row_start, + uint32_t row_end, + uint32_t n_rows, + uint32_t mc_pad, + uint32_t k_block, + uint32_t k_stride, + uint32_t k_valid, + uint32_t n_groups, + uint8_t * act_spad, + size_t scratch_bytes_per_hvx, + struct htp_thread_trace * tr); + +typedef struct { + int_act_dma_pipelined_fn_t dma_pipelined_fn; + uint8_t * vtcm_act_dst; + float * vtcm_act_scales; + dma_addr_t act_dma_addr; + float * vtcm_f32_act; + uint32_t n_tasks; + uint32_t n_rows; + uint32_t mc_pad; + uint32_t n_rows_per_task; + uint32_t k_block; + uint32_t k_stride; + uint32_t k_valid; + uint32_t n_groups; + size_t vtcm_f32_act_bytes_per_hvx; +} int_activation_transfer_task_state_t; + +#define DEFINE_TRANSFER_ACT_CHUNK_DMA_PIPELINED(SFX, ACT_T) \ +static void transfer_activation_chunk_##SFX##_dma_pipelined( \ + dma_queue * dma_q, \ + uint8_t * restrict vtcm_act_dst, \ + float * restrict vtcm_act_scales, \ + dma_addr_t act_dma_addr, \ + uint32_t row_start, \ + uint32_t row_end, \ + uint32_t n_rows, \ + uint32_t mc_pad, \ + uint32_t k_block, \ + uint32_t k_stride, \ + uint32_t k_valid, \ + uint32_t n_groups, \ + uint8_t * act_spad, \ + size_t scratch_bytes_per_hvx, \ + struct htp_thread_trace * tr) { \ + const uint32_t step_rows = 4u; \ + const size_t row_bytes = (size_t) k_block * sizeof(ACT_T); \ + const size_t src_row_bytes = (size_t) k_stride * sizeof(ACT_T); \ + const size_t width_bytes = (size_t) k_valid * sizeof(ACT_T); \ + const bool double_buf = (scratch_bytes_per_hvx >= 2 * step_rows * row_bytes); \ + const uint32_t n_k_tiles = k_block >> 5; \ + if (double_buf) { \ + if (row_start < row_end && row_start < n_rows) { \ + uint32_t nrows_to_fetch = hex_smin(n_rows - row_start, step_rows); \ + dma_queue_push(dma_q, dma_make_data(act_spad, act_dma_addr + (size_t) row_start * src_row_bytes), \ + row_bytes, src_row_bytes, width_bytes, nrows_to_fetch); \ + } \ + if (row_start + step_rows < row_end && row_start + step_rows < n_rows) { \ + uint32_t next_r = row_start + step_rows; \ + uint32_t nrows_to_fetch = hex_smin(n_rows - next_r, step_rows); \ + uint8_t * next_buf = act_spad + step_rows * row_bytes; \ + dma_queue_push(dma_q, dma_make_data(next_buf, act_dma_addr + (size_t) next_r * src_row_bytes), \ + row_bytes, src_row_bytes, width_bytes, nrows_to_fetch); \ + } \ + } \ + for (uint32_t r = row_start; r < row_end; r += step_rows) { \ + uint8_t * curr_buf = act_spad; \ + if (r < n_rows) { \ + if (double_buf) { \ + curr_buf = (uint8_t *) dma_queue_pop(dma_q).dst; \ + } else { \ + uint32_t nrows_to_fetch = hex_smin(n_rows - r, step_rows); \ + dma_queue_push(dma_q, dma_make_data(act_spad, act_dma_addr + (size_t) r * src_row_bytes), \ + row_bytes, src_row_bytes, width_bytes, nrows_to_fetch); \ + curr_buf = (uint8_t *) dma_queue_pop(dma_q).dst; \ + } \ + } \ + const uint32_t valid_rows = (r < n_rows) ? hex_smin(n_rows - r, step_rows) : 0u; \ + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, r); \ + quantize_act_step_rows_##SFX( \ + vtcm_act_dst, vtcm_act_scales, curr_buf, row_bytes, \ + r, valid_rows, mc_pad, n_k_tiles, n_groups, k_valid); \ + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_QUANT, r); \ + if (double_buf) { \ + uint32_t next_r = r + 2 * step_rows; \ + if (next_r < row_end && next_r < n_rows) { \ + uint32_t nrows_to_fetch = hex_smin(n_rows - next_r, step_rows); \ + dma_queue_push(dma_q, dma_make_data(curr_buf, act_dma_addr + (size_t) next_r * src_row_bytes), \ + row_bytes, src_row_bytes, width_bytes, nrows_to_fetch); \ + } \ + } \ + } \ +} + +DEFINE_TRANSFER_ACT_CHUNK_DMA_PIPELINED(f16_w8a8, __fp16) +DEFINE_TRANSFER_ACT_CHUNK_DMA_PIPELINED(f32_w8a8, float) + +static inline int_act_dma_pipelined_fn_t resolve_int_act_dma_pipelined_fn(uint32_t act_elem_size) { + return (act_elem_size == sizeof(__fp16)) ? transfer_activation_chunk_f16_w8a8_dma_pipelined + : transfer_activation_chunk_f32_w8a8_dma_pipelined; +} + +static void transfer_activation_chunk_int_worker_fn(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { + int_activation_transfer_task_state_t * st = (int_activation_transfer_task_state_t *) data; + struct htp_thread_trace * tr = th->trace; + + for (unsigned int task_id = i; task_id < st->n_tasks; task_id += n) { + uint32_t row_start = task_id * st->n_rows_per_task; + if (row_start >= st->mc_pad) { + break; + } + uint32_t row_end = hex_smin(row_start + st->n_rows_per_task, st->mc_pad); + uint8_t * act_spad = (uint8_t *) st->vtcm_f32_act + i * st->vtcm_f32_act_bytes_per_hvx; + st->dma_pipelined_fn( + th->dma_q, st->vtcm_act_dst, st->vtcm_act_scales, st->act_dma_addr, + row_start, row_end, st->n_rows, st->mc_pad, + st->k_block, st->k_stride, st->k_valid, st->n_groups, + act_spad, st->vtcm_f32_act_bytes_per_hvx, tr); + } +} + +static void transfer_activation_chunk_int_threaded( + struct htp_context * ctx, + uint8_t * vtcm_act_dst, + float * vtcm_act_scales, + dma_addr_t act_dma_addr, + int n_rows, + int k_block, + int k_stride, + int k_valid, + int n_groups, + int n_hvx, + const struct fastdiv_values * act_hvx_div, + float * vtcm_f32_act, + size_t vtcm_f32_act_bytes, + uint32_t act_elem_size) { + + if (n_rows <= 0) { + return; + } + + const uint32_t mc_pad = hex_align_up((uint32_t) n_rows, 64u); + const uint32_t resolved_esize = act_elem_size ? act_elem_size : (uint32_t) sizeof(float); + uint32_t rows_per_task = (n_hvx <= 1) ? mc_pad : fastdiv(mc_pad + (uint32_t) n_hvx - 1, act_hvx_div); + rows_per_task = hex_align_up(rows_per_task, 4u); + + int_activation_transfer_task_state_t state; + state.dma_pipelined_fn = resolve_int_act_dma_pipelined_fn(resolved_esize); + state.vtcm_act_dst = vtcm_act_dst; + state.vtcm_act_scales = vtcm_act_scales; + state.act_dma_addr = act_dma_addr; + state.vtcm_f32_act = vtcm_f32_act; + state.n_rows = (uint32_t) n_rows; + state.mc_pad = mc_pad; + state.n_rows_per_task = rows_per_task; + state.n_tasks = (uint32_t) hex_smin(n_hvx, (int) (mc_pad >> 2)); + state.k_block = (uint32_t) k_block; + state.k_stride = (uint32_t) k_stride; + state.k_valid = (uint32_t) k_valid; + state.n_groups = (uint32_t) n_groups; + state.vtcm_f32_act_bytes_per_hvx = hex_align_down(fastdiv(vtcm_f32_act_bytes, act_hvx_div), 128); + + work_queue_run(ctx->hvx_queue, transfer_activation_chunk_int_worker_fn, &state, (int) state.n_tasks); +} + +typedef struct { + int_output_col_chunk_fn_t col_chunk_fn; + void * dst; + const void * bias; + const uint8_t * vtcm_src; + const float * vtcm_act_scales; + const float * vtcm_weight_scales; + uint32_t n_rows; + uint32_t mc_pad; + uint32_t n_cols; + uint32_t n_groups; + uint32_t dst_stride; + uint32_t bias_stride; + uint32_t dst_cols; + uint32_t n_tasks; + uint32_t n_chunks_per_task; + size_t dst_elem_size; + size_t bias_elem_size; + struct fastdiv_values n_hvx_div; +} int_output_transfer_state_t; + +static void transfer_output_chunk_int_col_chunk_worker_fn(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { + (void) n; + int_output_transfer_state_t * st = (int_output_transfer_state_t *) data; + struct htp_thread_trace * tr = th->trace; + + const uint32_t n_blocks = hmx_ceil_div(st->n_cols, 32); + uint32_t b_first; + uint32_t b_last; + if (st->dst_elem_size == sizeof(__fp16)) { + const uint32_t n_pairs = hmx_ceil_div(n_blocks, 2); + b_first = fastdiv(n_pairs * i, &st->n_hvx_div) * 2; + b_last = MIN(n_blocks, fastdiv(n_pairs * (i + 1), &st->n_hvx_div) * 2); + } else { + b_first = fastdiv(n_blocks * i, &st->n_hvx_div); + b_last = fastdiv(n_blocks * (i + 1), &st->n_hvx_div); + } + if (b_first >= b_last) { + return; + } + const uint32_t c_first = b_first * 32; + const uint32_t c_last = b_last * 32; + const uint32_t c_len = c_last - c_first; + + const int chunk_dst_cols = (int) st->dst_cols - (int) c_first; + if (chunk_dst_cols <= 0) { + return; + } + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, c_first); + const void * bias = st->bias ? ((const uint8_t *) st->bias + (size_t) c_first * st->bias_elem_size) : NULL; + void * dst = (uint8_t *) st->dst + (size_t) c_first * st->dst_elem_size; + + st->col_chunk_fn( + dst, bias, st->vtcm_src, st->vtcm_act_scales, st->vtcm_weight_scales, + 0, st->n_rows, st->mc_pad, c_first, c_len, st->n_cols, st->n_groups, + st->dst_stride, st->bias_stride, (uint32_t) chunk_dst_cols, st->bias_elem_size); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, c_first); +} + +static void transfer_output_chunk_int_worker_fn(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { + int_output_transfer_state_t * st = (int_output_transfer_state_t *) data; + struct htp_thread_trace * tr = th->trace; + + const uint32_t n_quads = (st->n_rows + 3u) >> 2; + const uint32_t q_first = (n_quads <= n) ? i : fastdiv(n_quads * i, &st->n_hvx_div); + const uint32_t q_last = (n_quads <= n) ? (i + 1u) : fastdiv(n_quads * (i + 1u), &st->n_hvx_div); + const uint32_t row_start = q_first << 2; + const uint32_t row_end = hex_smin(st->n_rows, q_last << 2); + if (row_start >= row_end) { + return; + } + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, row_start); + const uint32_t chunk_size = row_end - row_start; + void * dst = (uint8_t *) st->dst + (size_t) row_start * st->dst_stride * st->dst_elem_size; + const void * bias = st->bias ? ((const uint8_t *) st->bias + (size_t) row_start * st->bias_stride * st->bias_elem_size) : NULL; + + st->col_chunk_fn( + dst, bias, st->vtcm_src, st->vtcm_act_scales, st->vtcm_weight_scales, + row_start, chunk_size, st->mc_pad, 0, st->n_cols, st->n_cols, st->n_groups, + st->dst_stride, st->bias_stride, st->dst_cols, st->bias_elem_size); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, row_start); +} + +static void transfer_output_chunk_int_threaded( + struct htp_ops_context * octx, + void * dst, + const void * bias, + const void * vtcm_src, + const float * vtcm_act_scales, + const float * vtcm_weight_scales, + int n_rows, + int n_cols, + int n_groups, + int dst_stride, + uint32_t bias_stride, + int dst_cols, + size_t dst_elem_size, + size_t bias_elem_size) { + + if (n_rows <= 0 || dst_cols <= 0) { + return; + } + + const int n_hvx = (int) octx->n_hvx; + const uint32_t mc_pad = hex_align_up((uint32_t) n_rows, 64u); + const bool dst_aligned_nt = ((((uintptr_t) dst | ((size_t) dst_stride * dst_elem_size)) & 127u) == 0); + + int_output_transfer_state_t state; + state.col_chunk_fn = resolve_int_output_col_chunk_fn((uint32_t) n_groups, dst_elem_size, bias, bias_elem_size, dst_aligned_nt); + state.dst = dst; + state.bias = bias; + state.vtcm_src = (const uint8_t *) vtcm_src; + state.vtcm_act_scales = vtcm_act_scales; + state.vtcm_weight_scales = vtcm_weight_scales; + state.n_rows = (uint32_t) n_rows; + state.mc_pad = mc_pad; + state.n_cols = (uint32_t) n_cols; + state.n_groups = (uint32_t) n_groups; + state.dst_stride = (uint32_t) dst_stride; + state.bias_stride = bias_stride; + state.dst_cols = (uint32_t) dst_cols; + state.dst_elem_size = dst_elem_size; + state.bias_elem_size = bias_elem_size; + state.n_hvx_div = octx->n_hvx_div; + + const uint32_t n_blocks = hmx_ceil_div((uint32_t) n_cols, 32); + const uint32_t n_units = (dst_elem_size == sizeof(__fp16)) ? hmx_ceil_div(n_blocks, 2) : n_blocks; + const bool prefer_row_chunk = ((uint32_t) n_rows >= (uint32_t) n_hvx * 64u); + if (n_hvx > 1 && !prefer_row_chunk && n_units >= (uint32_t) n_hvx) { + work_queue_run(octx->ctx->hvx_queue, transfer_output_chunk_int_col_chunk_worker_fn, &state, n_hvx); + return; + } + + const int actual_hvx = hex_smin(n_hvx, (n_rows + 3) >> 2); + work_queue_run(octx->ctx->hvx_queue, transfer_output_chunk_int_worker_fn, &state, actual_hvx); +} + +static void transfer_output_chunk_int_glu_col_chunk_task(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { + (void) n; + hmx_output_glu_state_t * st = (hmx_output_glu_state_t *) data; + struct htp_thread_trace * tr = th->trace; + + const uint32_t n_blocks = hmx_ceil_div(st->n_cols, 32); + uint32_t b_first; + uint32_t b_last; + if (st->dst_elem_size == sizeof(__fp16)) { + const uint32_t n_pairs = hmx_ceil_div(n_blocks, 2); + b_first = fastdiv(n_pairs * i, &st->n_hvx_div) * 2; + b_last = MIN(n_blocks, fastdiv(n_pairs * (i + 1), &st->n_hvx_div) * 2); + } else { + b_first = fastdiv(n_blocks * i, &st->n_hvx_div); + b_last = fastdiv(n_blocks * (i + 1), &st->n_hvx_div); + } + if (b_first >= b_last) { + return; + } + const uint32_t c_first = b_first * 32; + const uint32_t c_len = (b_last - b_first) * 32; + const int chunk_dst_cols = (int) st->dst_cols - (int) c_first; + if (chunk_dst_cols <= 0) { + return; + } + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, c_first); + void * dst = (uint8_t *) st->dst + (size_t) c_first * st->dst_elem_size; + const uint32_t eff_dst_cols = (uint32_t) hex_smin((size_t) c_len, (size_t) chunk_dst_cols); + st->col_chunk_fn(st, dst, 0, st->n_rows, c_first, (c_len << 16) | eff_dst_cols); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, c_first); +} + +static void transfer_output_chunk_int_glu_row_task(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { + hmx_output_glu_state_t * st = (hmx_output_glu_state_t *) data; + struct htp_thread_trace * tr = th->trace; + + const uint32_t n_quads = (st->n_rows + 3u) >> 2; + const uint32_t q_first = (n_quads <= n) ? i : fastdiv(n_quads * i, &st->n_hvx_div); + const uint32_t q_last = (n_quads <= n) ? (i + 1u) : fastdiv(n_quads * (i + 1u), &st->n_hvx_div); + const uint32_t row_start = q_first << 2; + const uint32_t row_end = hex_smin(st->n_rows, q_last << 2); + if (row_start >= row_end) { + return; + } + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_O_PROC, row_start); + const uint32_t eff_dst_cols = (uint32_t) hex_smin((size_t) st->n_cols, (size_t) st->dst_cols); + const uint32_t c_packed = (st->n_cols << 16) | eff_dst_cols; + const uint32_t chunk_size = row_end - row_start; + void * dst = (uint8_t *) st->dst + (size_t) row_start * st->dst_stride * st->dst_elem_size; + st->col_chunk_fn(st, dst, row_start, chunk_size, 0, c_packed); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, row_start); +} + +static void transfer_output_chunk_int_glu_threaded( + struct htp_ops_context * octx, + hmx_output_glu_state_t * state, + void * dst, + const void * vtcm_gate, + const void * vtcm_up, + const float * vtcm_wt_scales_gate, + const float * vtcm_wt_scales_up, + int n_rows, + int n_cols, + int dst_cols) { + + if (n_rows <= 0 || dst_cols <= 0) { + return; + } + + const int n_hvx = (int) octx->n_hvx; + state->dst = dst; + state->vtcm_gate = (const uint8_t *) vtcm_gate; + state->vtcm_up = (const uint8_t *) vtcm_up; + state->vtcm_wt_scales_gate = vtcm_wt_scales_gate; + state->vtcm_wt_scales_up = vtcm_wt_scales_up; + state->n_rows = (uint32_t) n_rows; + state->mc_pad = hex_align_up((uint32_t) n_rows, 64u); + state->n_cols = (uint32_t) n_cols; + state->dst_cols = (uint32_t) dst_cols; + state->n_hvx_div = octx->n_hvx_div; + + const uint32_t n_blocks = hmx_ceil_div((uint32_t) n_cols, 32); + const uint32_t n_units = (state->dst_elem_size == sizeof(__fp16)) ? hmx_ceil_div(n_blocks, 2) : n_blocks; + const bool prefer_row_chunk = ((uint32_t) n_rows >= (uint32_t) n_hvx * 64u); + if (n_hvx > 1 && !prefer_row_chunk && n_units >= (uint32_t) n_hvx) { + work_queue_run(octx->ctx->hvx_queue, transfer_output_chunk_int_glu_col_chunk_task, state, n_hvx); + return; + } + + const int actual_hvx = hex_smin(n_hvx, (n_rows + 3) >> 2); + work_queue_run(octx->ctx->hvx_queue, transfer_output_chunk_int_glu_row_task, state, actual_hvx); +} + +typedef struct { + const struct mmid_row_mapping * matrix_rows; + uint8_t * vtcm_act_dst; + float * vtcm_act_scales; + dma_addr_t act_dma_addr; + float * vtcm_f32_act; + uint32_t act_elem_size; + uint32_t n_tasks; + uint32_t n_rows; + uint32_t mc_pad; + uint32_t k_block; + uint32_t k_valid; + uint32_t n_groups; + size_t vtcm_f32_act_bytes_per_hvx; + uint32_t start_row; + uint32_t cur_a; + uint32_t mapping_stride; + uint32_t ne11; + struct fastdiv_values ne11_div; + size_t nb11; + size_t nb12; +} int_activation_transfer_gathered_state_t; + +static void transfer_activation_chunk_int_gathered_worker_fn(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { + int_activation_transfer_gathered_state_t * st = (int_activation_transfer_gathered_state_t *) data; + struct htp_thread_trace * tr = th->trace; + dma_queue * dma_q = th->dma_q; + + const uint32_t row_start = i * 4u; + const uint32_t row_stride = n * 4u; + if (row_start >= st->mc_pad) { + return; + } + + const bool act_is_f16 = (st->act_elem_size == sizeof(__fp16)); + const size_t row_bytes = hex_align_up((size_t) st->k_block * st->act_elem_size, 128); + const size_t valid_bytes = (size_t) st->k_valid * st->act_elem_size; + const size_t slot_bytes = 4u * row_bytes; + const bool double_buf = (st->vtcm_f32_act_bytes_per_hvx >= 2u * slot_bytes); + const uint32_t n_k_tiles = st->k_block >> 5; + uint8_t * act_spad = (uint8_t *) st->vtcm_f32_act + i * st->vtcm_f32_act_bytes_per_hvx; + + if (double_buf) { + if (row_start < st->n_rows) { + const uint32_t nrows = hex_smin(st->n_rows - row_start, 4u); + push_gathered_act_rows_dma(dma_q, act_spad, st->act_dma_addr, nrows, st->start_row, row_start, + row_bytes, valid_bytes, st->matrix_rows, st->cur_a, st->mapping_stride, + st->ne11, &st->ne11_div, st->nb11, st->nb12); + } + const uint32_t r1 = row_start + row_stride; + if (r1 < st->mc_pad && r1 < st->n_rows) { + const uint32_t nrows = hex_smin(st->n_rows - r1, 4u); + push_gathered_act_rows_dma(dma_q, act_spad + slot_bytes, st->act_dma_addr, nrows, st->start_row, r1, + row_bytes, valid_bytes, st->matrix_rows, st->cur_a, st->mapping_stride, + st->ne11, &st->ne11_div, st->nb11, st->nb12); + } + } + + uint32_t step = 0; + for (uint32_t r = row_start; r < st->mc_pad; r += row_stride, ++step) { + uint8_t * curr_buf = act_spad + (double_buf ? (step & 1u) * slot_bytes : 0u); + const uint32_t valid_rows = (r < st->n_rows) ? hex_smin(st->n_rows - r, 4u) : 0u; + + if (valid_rows > 0) { + if (!double_buf) { + push_gathered_act_rows_dma(dma_q, curr_buf, st->act_dma_addr, valid_rows, st->start_row, r, + row_bytes, valid_bytes, st->matrix_rows, st->cur_a, st->mapping_stride, + st->ne11, &st->ne11_div, st->nb11, st->nb12); + } + for (uint32_t s = 0; s < valid_rows; ++s) { + dma_queue_pop(dma_q); + } + } + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_QUANT, r); + if (act_is_f16) { + quantize_act_step_rows_f16_w8a8( + st->vtcm_act_dst, st->vtcm_act_scales, curr_buf, row_bytes, + r, valid_rows, st->mc_pad, n_k_tiles, st->n_groups, st->k_valid); + } else { + quantize_act_step_rows_f32_w8a8( + st->vtcm_act_dst, st->vtcm_act_scales, curr_buf, row_bytes, + r, valid_rows, st->mc_pad, n_k_tiles, st->n_groups, st->k_valid); + } + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_QUANT, r); + + if (double_buf) { + const uint32_t next_r = r + 2u * row_stride; + if (next_r < st->mc_pad && next_r < st->n_rows) { + const uint32_t nrows = hex_smin(st->n_rows - next_r, 4u); + push_gathered_act_rows_dma(dma_q, curr_buf, st->act_dma_addr, nrows, st->start_row, next_r, + row_bytes, valid_bytes, st->matrix_rows, st->cur_a, st->mapping_stride, + st->ne11, &st->ne11_div, st->nb11, st->nb12); + } + } + } +} + +static void transfer_activation_chunk_int_gathered_threaded( + struct htp_context * ctx, + uint8_t * vtcm_act_dst, + float * vtcm_act_scales, + dma_addr_t act_dma_addr, + uint32_t act_elem_size, + int start_row, + int n_rows, + int k_block, + int k_valid, + int n_groups, + const struct mmid_row_mapping * matrix_rows, + int cur_a, + int mapping_stride, + int ne11, + size_t nb11, + size_t nb12, + int n_hvx, + const struct fastdiv_values * act_hvx_div, + float * vtcm_f32_act, + size_t vtcm_f32_act_bytes) { + if (n_rows <= 0) { + return; + } + + const uint32_t mc_pad = hex_align_up((uint32_t) n_rows, 64u); + const uint32_t resolved_esize = act_elem_size ? act_elem_size : (uint32_t) sizeof(float); + + int_activation_transfer_gathered_state_t state = { + .matrix_rows = matrix_rows, + .vtcm_act_dst = vtcm_act_dst, + .vtcm_act_scales = vtcm_act_scales, + .act_dma_addr = act_dma_addr, + .vtcm_f32_act = vtcm_f32_act, + .act_elem_size = resolved_esize, + .n_tasks = (uint32_t) hex_smin(n_hvx, (int) (mc_pad >> 2)), + .n_rows = (uint32_t) n_rows, + .mc_pad = mc_pad, + .k_block = (uint32_t) k_block, + .k_valid = (uint32_t) k_valid, + .n_groups = (uint32_t) n_groups, + .vtcm_f32_act_bytes_per_hvx = hex_align_down(fastdiv(vtcm_f32_act_bytes, act_hvx_div), 128), + .start_row = (uint32_t) start_row, + .cur_a = (uint32_t) cur_a, + .mapping_stride = (uint32_t) mapping_stride, + .ne11 = (uint32_t) ne11, + .ne11_div = ne11 > 1 ? init_fastdiv_values(ne11) : (struct fastdiv_values){0, 0}, + .nb11 = nb11, + .nb12 = nb12, + }; + + work_queue_run(ctx->hvx_queue, transfer_activation_chunk_int_gathered_worker_fn, &state, (int) state.n_tasks); +} + +// --- Async HMX matmul task (for pipeline overlap) --- typedef struct { - __fp16 * output; - const __fp16 * activation; - const __fp16 * weight; - const __fp16 * scales; - uint32_t n_row_tiles; - uint32_t n_col_tiles; - uint32_t n_dot_tiles; -} hmx_matmul_job_t; - -static void hmx_matmul_worker_fn(const htp_thread_t * th, void * data) { - hmx_matmul_job_t * job = (hmx_matmul_job_t *) data; - FARF(HIGH, "hmx-mm-job: n_row_tiles %u n_col_tiles %u n_dot_tiles %u", job->n_row_tiles, job->n_col_tiles, job->n_dot_tiles); - core_dot_chunk_fp16(job->output, job->activation, job->weight, job->scales, job->n_row_tiles, job->n_col_tiles, job->n_dot_tiles); + __fp16 * output; + const __fp16 * activation; + const __fp16 * weight; + const __fp16 * scales; + const uint8_t * weight_bias; + uint32_t n_row_tiles; + uint32_t n_col_tiles; + uint32_t n_dot_tiles; + uint32_t n_groups; +} hmx_matmul_task_t; + +static void hmx_matmul_fp16_worker_fn(const htp_thread_t * th, void * data) { + (void) th; + hmx_matmul_task_t * task = (hmx_matmul_task_t *) data; + FARF(HIGH, "hmx-mm-fp16-task: n_row_tiles %u n_col_tiles %u n_dot_tiles %u", + task->n_row_tiles, task->n_col_tiles, task->n_dot_tiles); + core_dot_chunk_fp16(task->output, task->activation, task->weight, task->scales, + task->n_row_tiles, task->n_col_tiles, task->n_dot_tiles); } -static inline void hmx_matmul_job_init(hmx_matmul_job_t * job, +static void hmx_matmul_w8a8_worker_fn(const htp_thread_t * th, void * data) { + (void) th; + hmx_matmul_task_t * task = (hmx_matmul_task_t *) data; + FARF(HIGH, "hmx-mm-w8a8-task: n_row_tiles %u n_col_tiles %u n_dot_tiles %u n_groups %u", + task->n_row_tiles, task->n_col_tiles, task->n_dot_tiles, task->n_groups); + core_dot_chunk_w8a8_sm((uint8_t *) task->output, (const uint8_t *) task->activation, + (const uint8_t *) task->weight, task->weight_bias, + task->n_row_tiles, task->n_col_tiles, task->n_dot_tiles, task->n_groups); +} + +static inline hmx_queue_func hmx_get_matmul_worker_fn(int32_t kernel_type) { + if (htp_mm_kernel_is_hmx_w8a8(kernel_type)) { + return hmx_matmul_w8a8_worker_fn; + } + return hmx_matmul_fp16_worker_fn; +} + +static inline void hmx_matmul_task_init(hmx_matmul_task_t * task, __fp16 * output, const __fp16 * activation, const __fp16 * weight, @@ -2629,20 +3563,42 @@ static inline void hmx_matmul_job_init(hmx_matmul_job_t * job, uint32_t n_row_tiles, uint32_t n_col_tiles, uint32_t n_dot_tiles) { - job->output = output; - job->activation = activation; - job->weight = weight; - job->scales = scales; - job->n_row_tiles = n_row_tiles; - job->n_col_tiles = n_col_tiles; - job->n_dot_tiles = n_dot_tiles; + task->output = output; + task->activation = activation; + task->weight = weight; + task->scales = scales; + task->weight_bias = NULL; + task->n_row_tiles = n_row_tiles; + task->n_col_tiles = n_col_tiles; + task->n_dot_tiles = n_dot_tiles; + task->n_groups = 1; +} + +static inline void hmx_matmul_task_init_int(hmx_matmul_task_t * task, + void * output, + const void * activation, + const void * weight_buf, + size_t weight_bias_offset, + uint32_t n_row_tiles, + uint32_t n_col_tiles, + uint32_t n_dot_tiles, + uint32_t n_groups) { + task->output = (__fp16 *) output; + task->activation = (const __fp16 *) activation; + task->weight = (const __fp16 *) weight_buf; + task->scales = NULL; + task->weight_bias = (const uint8_t *) weight_buf + weight_bias_offset; + task->n_row_tiles = n_row_tiles; + task->n_col_tiles = n_col_tiles; + task->n_dot_tiles = n_dot_tiles; + task->n_groups = n_groups; } -static int hmx_mm_2d_f32(struct htp_context *ctx, +static int hmx_mm_2d_f32(struct htp_ops_context *octx, dma_queue *weight_dma, - float *restrict dst, - dma_addr_t src2_addr, - size_t src2_bytes, + dma_addr_t dst_dma_addr, + dma_addr_t bias_addr, + size_t bias_bytes, dma_addr_t act_dma_addr, dma_addr_t weight, int m, int k, int n, @@ -2652,27 +3608,38 @@ static int hmx_mm_2d_f32(struct htp_context *ctx, int weight_type, int k_valid, int dst_stride, - uint32_t src2_stride, + uint32_t bias_stride, int dst_cols, + uint32_t dst_elem_size, + uint32_t bias_elem_size, int m_chunk, int n_chunk, int pipeline, - int n_hvx, int act_hvx, const struct fastdiv_values * act_hvx_div, const struct fastdiv_values * k_div, int tile_size, int aligned_tile_size, - int vtcm_size) { + int vtcm_size, + int32_t kernel_type, + int hmx_n_groups, + const struct fastdiv_values * div_hmx_n_groups, + const struct fastdiv_values * div_n_k_tiles) { + struct htp_context * ctx = octx->ctx; struct htp_thread_trace * tr = &ctx->trace[0]; htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0); - const bool is_tiled = (tile_size > 0); + const bool is_tiled = (tile_size > 0); + const bool is_int_hmx = htp_mm_kernel_is_hmx_int(kernel_type); + const int n_groups = is_int_hmx ? hmx_n_groups : 1; - if (k % 32 != 0) { + if ((k & 31) != 0) { return -1; } - if (!hex_is_aligned(dst, sizeof(float))) { return -1; } + if ((dst_dma_addr & (dst_elem_size - 1)) != 0) { return -1; } + + const struct fastdiv_values n_groups_div = *div_hmx_n_groups; + const hmx_queue_func hmx_worker_fn = hmx_get_matmul_worker_fn(kernel_type); size_t row_stride = htp_tensor_get_row_size(weight_type, k); if (row_stride == 0) { @@ -2681,11 +3648,10 @@ static int hmx_mm_2d_f32(struct htp_context *ctx, tiled_dequant_task_fn_t dequant_worker_fn = hmx_get_dequant_worker_fn(weight_type, is_tiled); - const int n_k_tiles = k / HTP_MM_HMX_TILE_N_COLS; - const int n_weight_tiles = k / htp_tensor_get_tile_k(weight_type); - const struct fastdiv_values n_k_tiles_div = init_fastdiv_values(n_k_tiles); + const int n_k_tiles = k >> 5; + const int n_weight_tiles = (weight_type == HTP_TYPE_Q4_0) ? n_k_tiles : (k / htp_tensor_get_tile_k(weight_type)); + const struct fastdiv_values n_k_tiles_div = *div_n_k_tiles; - const size_t vec_dot_size = k * sizeof(__fp16); const size_t vtcm_budget = ctx->vtcm_size; const uint32_t dma_dst_stride = is_tiled ? aligned_tile_size : row_stride; @@ -2696,8 +3662,15 @@ static int hmx_mm_2d_f32(struct htp_context *ctx, size_t n_chunk_n_cols = n_chunk; size_t vtcm_used = vtcm_size; + const bool has_bias = (bias_bytes > 0 && bias_addr != 0); + const bool has_2d_bias = (pipeline && !has_bias && bias_addr != 0); + const size_t res_in_elem_size = has_2d_bias ? bias_elem_size : 0; + const size_t res_out_elem_size = dst_elem_size; + struct htp_mm_hmx_vtcm_layout L; - htp_mm_hmx_vtcm_layout_build(&L, HTP_MM_KERNEL_HMX_2D, weight_type, k, m_chunk_n_rows, n_chunk_n_cols, 1, pipeline, act_hvx, aligned_tile_size, src2_bytes); + htp_mm_hmx_vtcm_layout_build_ex(&L, is_int_hmx ? kernel_type : HTP_MM_KERNEL_HMX_2D, weight_type, k, + m_chunk_n_rows, n_chunk_n_cols, 1, pipeline, act_hvx, aligned_tile_size, bias_bytes, + res_in_elem_size, res_out_elem_size); vtcm_used = L.total_bytes; if (vtcm_used > vtcm_budget) { @@ -2713,34 +3686,45 @@ static int hmx_mm_2d_f32(struct htp_context *ctx, }; __fp16 *vtcm_f16_act = VTCM_LAYOUT_PTR(__fp16, base, L.off_act); float *vtcm_f32_act = VTCM_LAYOUT_PTR(float, base, L.off_act_f32); + float *vtcm_act_scales = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_act_scales, is_int_hmx); __fp16 *vtcm_output = VTCM_LAYOUT_PTR(__fp16, base, L.off_dst[0]); void *vtcm_scratch0 = VTCM_LAYOUT_PTR(void, base, L.off_scratch[0]); void *vtcm_scratch1 = VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_scratch[1], pipeline); void *vtcm_scratch2 = VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_dst[1], pipeline); - __fp16 *vtcm_scales = VTCM_LAYOUT_PTR(__fp16, base, L.off_scales); + void *vtcm_res_in[2] = { + VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_res_in[0], has_2d_bias), + VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_res_in[1], has_2d_bias), + }; + void *vtcm_res_out[2] = { + VTCM_LAYOUT_PTR(void, base, L.off_res_out[0]), + VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_res_out[1], pipeline), + }; + __fp16 *vtcm_scales = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_scales, !is_int_hmx); - hmx_init_column_scales(vtcm_scales, Q6_V_vsplat_R(0x3c00)); // scale: 1.0, bias: 0.0 in FP16 + if (!is_int_hmx) { + hmx_init_column_scales(vtcm_scales, Q6_V_vsplat_R(0x3c00)); // scale: 1.0, bias: 0.0 in FP16 + } if (L.lut_bytes > 0) { iq2xxs_lut_copy(base + L.off_lut); } - const bool has_bias = (src2_bytes > 0 && src2_addr != 0); - float *vtcm_bias = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_bias, has_bias); + void *vtcm_bias = VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_bias, has_bias); if (has_bias) { - dma_queue_push(weight_dma, dma_make_data(vtcm_bias, src2_addr), hex_align_up(src2_bytes, 128), 0, src2_bytes, 1); + dma_queue_push(weight_dma, dma_make_data(vtcm_bias, bias_addr), hex_align_up(bias_bytes, 128), 0, bias_bytes, 1); dma_queue_pop(weight_dma); } - FARF(HIGH, "hmx-mm-2d: m %d k %d n %d wtype %d mc %zu nc %zu vtcm %zu/%zu", - m, k, n, weight_type, m_chunk_n_rows, n_chunk_n_cols, vtcm_used, vtcm_budget); + FARF(HIGH, "hmx-mm-2d: ktype %d m %d k %d n %d wtype %d mc %zu nc %zu vtcm %zu/%zu", + (int) kernel_type, m, k, n, weight_type, m_chunk_n_rows, n_chunk_n_cols, vtcm_used, vtcm_budget); int n_chunk_cnt = hmx_ceil_div(n, n_chunk_n_cols); + const uint32_t m_tile_rows = is_int_hmx ? 64u : HTP_MM_HMX_TILE_N_ROWS; htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0); if (pipeline) { - // --- Asynchronous Pipelined Loop --- - hmx_matmul_job_t job_slots[2]; // persistent double-buffered job descriptors + // --- Asynchronous Pipelined Loop (strict lockstep FIFO on weight_dma) --- + hmx_matmul_task_t task_slots[2]; void *vtcm_raw_bufs[4] = { vtcm_weight_raw[0], vtcm_weight_raw[1], @@ -2755,163 +3739,363 @@ static int hmx_mm_2d_f32(struct htp_context *ctx, }; void *vtcm_output_bufs[2] = { vtcm_output, vtcm_scratch2 }; - for (size_t mr = 0; mr < m; mr += m_chunk_n_rows) { - const size_t n_rows = hex_smin(m - mr, m_chunk_n_rows); + const size_t dst_row_bytes = (size_t) dst_stride * dst_elem_size; + const size_t bias_row_bytes = (size_t) bias_stride * bias_elem_size; + const size_t res_out_stride_bytes = hex_align_up(n_chunk_n_cols * dst_elem_size, 128); + const int res_out_stride_elems = (int) (res_out_stride_bytes / dst_elem_size); + const size_t res_in_stride_bytes = has_2d_bias ? hex_align_up(n_chunk_n_cols * bias_elem_size, 128) : 0; + const uint32_t res_in_stride_elems = has_2d_bias ? (uint32_t) (res_in_stride_bytes / bias_elem_size) : 0; - struct activation_transfer_params act_params = { - .ctx = ctx, - .dst = vtcm_f16_act, - .act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size, // byte offset (F16/F32) - .n_rows = (int) n_rows, - .k_block = k, - .k_stride = act_stride, - .n_hvx = act_hvx, - .act_hvx_div = act_hvx_div, - .k_div = k_div, - .k_valid = k_valid, - .vtcm_f32_act = vtcm_f32_act, - .vtcm_f32_act_bytes = L.act_f32_bytes, - .act_elem_size = act_elem_size, - }; - transfer_activation_chunk_threaded(&act_params); + const bool preissue_w0 = is_int_hmx && L.can_preissue_weight && n > 0; - // Prologue: push A0 and optionally A1 (if n_chunk_cnt > 1) - const size_t n_cols_A0 = hex_smin(n - 0 * n_chunk_n_cols, n_chunk_n_cols); - const uint32_t height_A0 = is_tiled ? hmx_ceil_div(n_cols_A0, 32) * n_weight_tiles : n_cols_A0; - dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[0], weight), - dma_dst_stride, dma_src_stride, dma_width_bytes, height_A0); + for (size_t mr = 0; mr < (size_t) m; mr += m_chunk_n_rows) { + const size_t n_rows = hex_smin((size_t) m - mr, m_chunk_n_rows); + + if (preissue_w0) { + const size_t n_cols_A0 = hex_smin((size_t) n, n_chunk_n_cols); + const uint32_t height_A0 = is_tiled ? hmx_ceil_div(n_cols_A0, 32) * n_weight_tiles : n_cols_A0; + dma_proxy_push(ctx->dma_proxy, dma_make_data(vtcm_raw_bufs[0], weight), + dma_dst_stride, dma_src_stride, dma_width_bytes, height_A0); + } + + if (is_int_hmx) { + transfer_activation_chunk_int_threaded( + ctx, (uint8_t *) vtcm_f16_act, vtcm_act_scales, + act_dma_addr + (size_t) mr * act_stride * act_elem_size, + (int) n_rows, k, act_stride, k_valid, n_groups, + act_hvx, act_hvx_div, vtcm_f32_act, L.act_f32_bytes, act_elem_size); + } else { + struct activation_transfer_params act_params = { + .ctx = ctx, + .dst = vtcm_f16_act, + .act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size, + .n_rows = (int) n_rows, + .k_block = k, + .k_stride = act_stride, + .n_hvx = act_hvx, + .act_hvx_div = act_hvx_div, + .k_div = k_div, + .k_valid = k_valid, + .vtcm_f32_act = vtcm_f32_act, + .vtcm_f32_act_bytes = L.act_f32_bytes, + .act_elem_size = act_elem_size, + }; + transfer_activation_chunk_threaded(&act_params); + } + if (!preissue_w0) { + const size_t n_cols_A0 = hex_smin((size_t) n, n_chunk_n_cols); + const uint32_t height_A0 = is_tiled ? hmx_ceil_div(n_cols_A0, 32) * n_weight_tiles : n_cols_A0; + dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[0], weight), + dma_dst_stride, dma_src_stride, dma_width_bytes, height_A0); + } if (1 < n_chunk_cnt) { - const size_t n_cols_A1 = hex_smin(n - 1 * n_chunk_n_cols, n_chunk_n_cols); + const size_t n_cols_A1 = hex_smin((size_t) n - n_chunk_n_cols, n_chunk_n_cols); const uint32_t height_A1 = is_tiled ? hmx_ceil_div(n_cols_A1, 32) * n_weight_tiles : n_cols_A1; dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[1], weight + n_chunk_n_cols * weight_stride), dma_dst_stride, dma_src_stride, dma_width_bytes, height_A1); } + if (has_2d_bias) { + const int vcols0 = hex_smin((int) hex_smin((size_t) n, n_chunk_n_cols), dst_cols); + const size_t cbytes = (vcols0 > 0) ? (size_t) vcols0 * bias_elem_size : 0; + dma_queue_push(weight_dma, + dma_make_data(vtcm_res_in[0], bias_addr + (mr * bias_stride) * bias_elem_size), + res_in_stride_bytes, bias_row_bytes, cbytes, cbytes ? n_rows : 0); + } - // Main loop: pop A_i -> dequantize A_i -> push A_{i+2} -> submit C_i -> wait C_{i-1} and store D_{i-1} for (int i = 0; i < n_chunk_cnt; ++i) { - const size_t nc = i * n_chunk_n_cols; - const size_t nc_p2 = nc + 2 * n_chunk_n_cols; - - const size_t n_cols = hex_smin(n - nc, n_chunk_n_cols); - const size_t n_cols_p2 = hex_smin(n - nc_p2, n_chunk_n_cols); - - // 1. pop A_i - void * curr_raw = (void *) dma_queue_pop(weight_dma).dst; - - // 2. dequantize A_i - dequantize_tiled_weight_chunk_to_fp16_tiles( - ctx, vtcm_weight_bufs[i % 4], curr_raw, - n_cols, k, row_stride, weight_type, - n_k_tiles, n_k_tiles_div, dequant_worker_fn, n_hvx); - - // 3. push A_{i+2} (if i+2 < n_chunk_cnt) - if (i + 2 < n_chunk_cnt) { - const uint32_t height_p2 = is_tiled ? hmx_ceil_div(n_cols_p2, 32) * n_weight_tiles : n_cols_p2; - dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[(i + 2) % 4], weight + nc_p2 * weight_stride), - dma_dst_stride, dma_src_stride, dma_width_bytes, height_p2); - } + const size_t nc = (size_t) i * n_chunk_n_cols; + const size_t n_cols = hex_smin((size_t) n - nc, n_chunk_n_cols); - // 4. submit C_i - hmx_matmul_job_init(&job_slots[i % 2], (__fp16 *) vtcm_output_bufs[i % 2], - (__fp16 *) vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 4], - vtcm_scales, hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS), - hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS), k / HTP_MM_HMX_TILE_N_ROWS); - hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_matmul_worker_fn, &job_slots[i % 2])); + // 1. Pop w_i and dequantize / rescale into vtcm_weight_bufs[i % 4] + void * curr_raw; + if (i == 0 && preissue_w0) { + curr_raw = (void *) dma_proxy_pop(ctx->dma_proxy).dst; + } else { + curr_raw = (void *) dma_queue_pop(weight_dma).dst; + } + if (is_int_hmx) { + rescale_int_weight_chunk_to_int8_tiles( + octx, vtcm_weight_bufs[i % 4], L.weight_bias_offset, L.weight_scales_offset, + curr_raw, (int) n_cols, k, n_groups, &n_groups_div, aligned_tile_size, weight_type); + } else { + dequantize_tiled_weight_chunk_to_fp16_tiles( + octx, vtcm_weight_bufs[i % 4], curr_raw, + n_cols, k, row_stride, weight_type, + n_k_tiles, n_k_tiles_div, dequant_worker_fn); + } - // 5. wait C_{i-1} and store D_{i-1} (multi-thread HVX, parallel with C_i) - if (i > 0) { - hmx_queue_pop(ctx->hmx_queue); - const size_t nc_prev = (i - 1) * n_chunk_n_cols; - const size_t n_cols_prev = hex_smin(n - nc_prev, n_chunk_n_cols); - float *output_chunk = dst + (mr * dst_stride + nc_prev); - const float *bias_chunk = has_bias ? (vtcm_bias + mr * src2_stride + nc_prev) : NULL; - int chunk_dst_cols = dst_cols - (int)nc_prev; - if (chunk_dst_cols > 0) { - transfer_output_chunk_threaded(ctx, output_chunk, bias_chunk, vtcm_output_bufs[(i - 1) % 2], n_rows, n_cols_prev, dst_stride, src2_stride, chunk_dst_cols, n_hvx); + if (i == 0) { + if (is_int_hmx) { + hmx_matmul_task_init_int(&task_slots[0], vtcm_output_bufs[0], + vtcm_f16_act, vtcm_weight_bufs[0], L.weight_bias_offset, + hmx_ceil_div(n_rows, m_tile_rows), + hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS), + (uint32_t) n_k_tiles, (uint32_t) n_groups); + } else { + hmx_matmul_task_init(&task_slots[0], (__fp16 *) vtcm_output_bufs[0], + (__fp16 *) vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[0], + vtcm_scales, hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS), + hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS), (uint32_t) n_k_tiles); } - } - } + hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task_slots[0])); - // Epilogue: wait C_{last} and store D_{last} - hmx_queue_pop(ctx->hmx_queue); - const size_t nc_last = (n_chunk_cnt - 1) * n_chunk_n_cols; - const size_t n_cols_last = hex_smin(n - nc_last, n_chunk_n_cols); - float *output_chunk = dst + (mr * dst_stride + nc_last); - const float *bias_chunk = has_bias ? (vtcm_bias + mr * src2_stride + nc_last) : NULL; - int chunk_dst_cols = dst_cols - (int)nc_last; - if (chunk_dst_cols > 0) { - transfer_output_chunk_threaded(ctx, output_chunk, bias_chunk, vtcm_output_bufs[(n_chunk_cnt - 1) % 2], n_rows, n_cols_last, dst_stride, src2_stride, chunk_dst_cols, n_hvx); + if (2 < n_chunk_cnt) { + const size_t nc2 = 2u * n_chunk_n_cols; + const size_t n_cols_p2 = hex_smin((size_t) n - nc2, n_chunk_n_cols); + const uint32_t height_p2 = is_tiled ? hmx_ceil_div(n_cols_p2, 32) * n_weight_tiles : n_cols_p2; + dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[2], weight + nc2 * weight_stride), + dma_dst_stride, dma_src_stride, dma_width_bytes, height_p2); + } + if (has_2d_bias && 1 < n_chunk_cnt) { + const size_t nc1 = n_chunk_n_cols; + const int vcols1 = hex_smin((int) hex_smin((size_t) n - nc1, n_chunk_n_cols), dst_cols - (int) nc1); + const size_t cbytes = (vcols1 > 0) ? (size_t) vcols1 * bias_elem_size : 0; + dma_queue_push(weight_dma, + dma_make_data(vtcm_res_in[1], bias_addr + (mr * bias_stride + nc1) * bias_elem_size), + res_in_stride_bytes, bias_row_bytes, cbytes, cbytes ? n_rows : 0); + } + } else { + const int prev = (i - 1) & 1; + const size_t nc_prev = (size_t) (i - 1) * n_chunk_n_cols; + const size_t n_cols_p = hex_smin((size_t) n - nc_prev, n_chunk_n_cols); + + // 2. Wait C_{i-1} and submit C_i + hmx_queue_pop(ctx->hmx_queue); + if (is_int_hmx) { + hmx_matmul_task_init_int(&task_slots[i & 1], vtcm_output_bufs[i & 1], + vtcm_f16_act, vtcm_weight_bufs[i % 4], L.weight_bias_offset, + hmx_ceil_div(n_rows, m_tile_rows), + hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS), + (uint32_t) n_k_tiles, (uint32_t) n_groups); + } else { + hmx_matmul_task_init(&task_slots[i & 1], (__fp16 *) vtcm_output_bufs[i & 1], + (__fp16 *) vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 4], + vtcm_scales, hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS), + hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS), (uint32_t) n_k_tiles); + } + hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task_slots[i & 1])); + + // 3. Pop r_{i-1} (if 2D residual); out_{i-2} uses vtcm_res_out[cur], popped after D_{i-1} + if (has_2d_bias) { + dma_queue_pop(weight_dma); + } + + // 4. HVX epilogue D_{i-1} (VTCM -> vtcm_res_out[prev], parallel with C_i and out_{i-2} DMA) + const int chunk_dst_cols = dst_cols - (int) nc_prev; + if (chunk_dst_cols > 0) { + const void * bias_chunk = has_2d_bias ? vtcm_res_in[prev] + : (has_bias ? ((const uint8_t *) vtcm_bias + (mr * bias_stride + nc_prev) * bias_elem_size) : NULL); + const uint32_t ep_bias_stride = has_2d_bias ? res_in_stride_elems : bias_stride; + if (is_int_hmx) { + const float * wt_scales_prev = (const float *) ((const uint8_t *) vtcm_weight_bufs[(i - 1) % 4] + L.weight_scales_offset); + transfer_output_chunk_int_threaded( + octx, vtcm_res_out[prev], bias_chunk, vtcm_output_bufs[prev], + vtcm_act_scales, wt_scales_prev, (int) n_rows, (int) n_cols_p, + n_groups, res_out_stride_elems, ep_bias_stride, chunk_dst_cols, + dst_elem_size, bias_elem_size); + } else { + transfer_output_chunk_threaded(octx, vtcm_res_out[prev], bias_chunk, vtcm_output_bufs[prev], + n_rows, n_cols_p, res_out_stride_elems, ep_bias_stride, chunk_dst_cols, + dst_elem_size, bias_elem_size); + } + } + + // 5. Drain out_{i-2}, then push out_{i-1}, w_{i+2}, and r_{i+1} + if (i >= 2) { + dma_queue_pop(weight_dma); + } + { + const int vcols_o = hex_smin((int) n_cols_p, chunk_dst_cols); + const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0; + dma_queue_push(weight_dma, + dma_make_data(dst_dma_addr + (mr * dst_stride + nc_prev) * dst_elem_size, vtcm_res_out[prev]), + dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0); + } + if (i + 2 < n_chunk_cnt) { + const size_t nc_p2 = (size_t) (i + 2) * n_chunk_n_cols; + const size_t n_cols_p2 = hex_smin((size_t) n - nc_p2, n_chunk_n_cols); + const uint32_t height_p2 = is_tiled ? hmx_ceil_div(n_cols_p2, 32) * n_weight_tiles : n_cols_p2; + dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[(i + 2) % 4], weight + nc_p2 * weight_stride), + dma_dst_stride, dma_src_stride, dma_width_bytes, height_p2); + } + if (has_2d_bias && i + 1 < n_chunk_cnt) { + const size_t nc_p1 = (size_t) (i + 1) * n_chunk_n_cols; + const int vcols_r = hex_smin((int) hex_smin((size_t) n - nc_p1, n_chunk_n_cols), dst_cols - (int) nc_p1); + const size_t cbytes = (vcols_r > 0) ? (size_t) vcols_r * bias_elem_size : 0; + dma_queue_push(weight_dma, + dma_make_data(vtcm_res_in[prev], bias_addr + (mr * bias_stride + nc_p1) * bias_elem_size), + res_in_stride_bytes, bias_row_bytes, cbytes, cbytes ? n_rows : 0); + } + } + } + + // Epilogue: wait C_{last}, pop r_{last} and out_{last-1}, run D_{last}, push+pop out_{last} + { + const int last = (n_chunk_cnt - 1) & 1; + const size_t nc_last = (size_t) (n_chunk_cnt - 1) * n_chunk_n_cols; + const size_t n_cols_last = hex_smin((size_t) n - nc_last, n_chunk_n_cols); + + hmx_queue_pop(ctx->hmx_queue); + if (has_2d_bias) { + dma_queue_pop(weight_dma); + } + if (n_chunk_cnt >= 2) { + dma_queue_pop(weight_dma); + } + + const int chunk_dst_cols = dst_cols - (int) nc_last; + if (chunk_dst_cols > 0) { + const void * bias_chunk = has_2d_bias ? vtcm_res_in[last] + : (has_bias ? ((const uint8_t *) vtcm_bias + (mr * bias_stride + nc_last) * bias_elem_size) : NULL); + const uint32_t ep_bias_stride = has_2d_bias ? res_in_stride_elems : bias_stride; + if (is_int_hmx) { + const float * wt_scales_last = (const float *) ((const uint8_t *) vtcm_weight_bufs[(n_chunk_cnt - 1) % 4] + L.weight_scales_offset); + transfer_output_chunk_int_threaded( + octx, vtcm_res_out[last], bias_chunk, vtcm_output_bufs[last], + vtcm_act_scales, wt_scales_last, (int) n_rows, (int) n_cols_last, + n_groups, res_out_stride_elems, ep_bias_stride, chunk_dst_cols, + dst_elem_size, bias_elem_size); + } else { + transfer_output_chunk_threaded(octx, vtcm_res_out[last], bias_chunk, vtcm_output_bufs[last], + n_rows, n_cols_last, res_out_stride_elems, ep_bias_stride, chunk_dst_cols, + dst_elem_size, bias_elem_size); + } + } + + const int vcols_o = hex_smin((int) n_cols_last, chunk_dst_cols); + const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0; + dma_queue_push(weight_dma, + dma_make_data(dst_dma_addr + (mr * dst_stride + nc_last) * dst_elem_size, vtcm_res_out[last]), + dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0); + dma_queue_pop(weight_dma); } } } else { - // --- Synchronous loop (m <= 32 or fallback) --- - hmx_matmul_job_t job; + // --- Synchronous loop (m <= 32 or fallback) with lockstep DMA writeback --- + hmx_matmul_task_t task; void *vtcm_raw_bufs[2] = { vtcm_weight_raw[0], dequant_worker_fn ? vtcm_weight_raw[0] : vtcm_scratch0 }; void *vtcm_weight_bufs[2] = { dequant_worker_fn ? vtcm_scratch0 : vtcm_weight_raw[0], vtcm_scratch0 }; - for (size_t mr = 0; mr < m; mr += m_chunk_n_rows) { - const size_t n_rows = hex_smin(m - mr, m_chunk_n_rows); + const size_t dst_row_bytes = (size_t) dst_stride * dst_elem_size; + const size_t res_out_stride_bytes = hex_align_up(n_chunk_n_cols * dst_elem_size, 128); + const int res_out_stride_elems = (int) (res_out_stride_bytes / dst_elem_size); - struct activation_transfer_params act_params = { - .ctx = ctx, - .dst = vtcm_f16_act, - .act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size, // byte offset (F16/F32) - .n_rows = (int) n_rows, - .k_block = k, - .k_stride = act_stride, - .n_hvx = act_hvx, - .act_hvx_div = act_hvx_div, - .k_div = k_div, - .k_valid = k_valid, - .vtcm_f32_act = vtcm_f32_act, - .vtcm_f32_act_bytes = L.act_f32_bytes, - .act_elem_size = act_elem_size, - }; - transfer_activation_chunk_threaded(&act_params); + const bool preissue_w0 = is_int_hmx && L.can_preissue_weight && n > 0; + + for (size_t mr = 0; mr < (size_t) m; mr += m_chunk_n_rows) { + const size_t n_rows = hex_smin((size_t) m - mr, m_chunk_n_rows); + + if (preissue_w0) { + const size_t n_cols = hex_smin((size_t) n, n_chunk_n_cols); + const uint32_t height = is_tiled ? hmx_ceil_div(n_cols, 32) * n_weight_tiles : n_cols; + dma_proxy_push(ctx->dma_proxy, dma_make_data(vtcm_raw_bufs[0], weight), + dma_dst_stride, dma_src_stride, dma_width_bytes, height); + } + + if (is_int_hmx) { + transfer_activation_chunk_int_threaded( + ctx, (uint8_t *) vtcm_f16_act, vtcm_act_scales, + act_dma_addr + (size_t) mr * act_stride * act_elem_size, + (int) n_rows, k, act_stride, k_valid, n_groups, + act_hvx, act_hvx_div, vtcm_f32_act, L.act_f32_bytes, act_elem_size); + } else { + struct activation_transfer_params act_params = { + .ctx = ctx, + .dst = vtcm_f16_act, + .act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size, + .n_rows = (int) n_rows, + .k_block = k, + .k_stride = act_stride, + .n_hvx = act_hvx, + .act_hvx_div = act_hvx_div, + .k_div = k_div, + .k_valid = k_valid, + .vtcm_f32_act = vtcm_f32_act, + .vtcm_f32_act_bytes = L.act_f32_bytes, + .act_elem_size = act_elem_size, + }; + transfer_activation_chunk_threaded(&act_params); + } - // A0: Pre-fetch the first weight chunk (nc = 0) - if (n > 0) { - const size_t n_cols = hex_smin(n, n_chunk_n_cols); + if (!preissue_w0 && n > 0) { + const size_t n_cols = hex_smin((size_t) n, n_chunk_n_cols); const uint32_t height = is_tiled ? hmx_ceil_div(n_cols, 32) * n_weight_tiles : n_cols; dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[0], weight), dma_dst_stride, dma_src_stride, dma_width_bytes, height); } for (int i = 0; i < n_chunk_cnt; ++i) { const size_t nc = (size_t) i * n_chunk_n_cols; - const size_t n_cols = hex_smin(n - nc, n_chunk_n_cols); - const size_t n_row_tiles = hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS); + const size_t n_cols = hex_smin((size_t) n - nc, n_chunk_n_cols); + const size_t n_row_tiles = hmx_ceil_div(n_rows, m_tile_rows); const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS); - // A: Wait for weight DMA - void * curr_raw = (void *) dma_queue_pop(weight_dma).dst; + // A: Wait for weight DMA (and previous output writeback) + void * curr_raw; + if (i == 0 && preissue_w0) { + curr_raw = (void *) dma_proxy_pop(ctx->dma_proxy).dst; + } else { + curr_raw = (void *) dma_queue_pop(weight_dma).dst; + } + if (i > 0) { + dma_queue_pop(weight_dma); + } - // B: Weight Dequantize (Threaded) - dequantize_tiled_weight_chunk_to_fp16_tiles( - ctx, vtcm_weight_bufs[i % 2], curr_raw, - n_cols, k, row_stride, weight_type, - n_k_tiles, n_k_tiles_div, dequant_worker_fn, n_hvx); + // B: Weight Dequantize / Rescale (Threaded) + if (is_int_hmx) { + rescale_int_weight_chunk_to_int8_tiles( + octx, vtcm_weight_bufs[i % 2], L.weight_bias_offset, L.weight_scales_offset, + curr_raw, (int) n_cols, k, n_groups, &n_groups_div, aligned_tile_size, weight_type); + } else { + dequantize_tiled_weight_chunk_to_fp16_tiles( + octx, vtcm_weight_bufs[i % 2], curr_raw, + n_cols, k, row_stride, weight_type, + n_k_tiles, n_k_tiles_div, dequant_worker_fn); + } // Start weight DMA for the next chunk early const size_t nc_next = nc + n_chunk_n_cols; - if (nc_next < n) { - const size_t n_cols_next = hex_smin(n - nc_next, n_chunk_n_cols); + if (nc_next < (size_t) n) { + const size_t n_cols_next = hex_smin((size_t) n - nc_next, n_chunk_n_cols); const uint32_t height_next = is_tiled ? hmx_ceil_div(n_cols_next, 32) * n_weight_tiles : n_cols_next; dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[(i + 1) % 2], weight + nc_next * weight_stride), dma_dst_stride, dma_src_stride, dma_width_bytes, height_next); } // C: HMX Compute (Queue-based) - hmx_matmul_job_init(&job, vtcm_output, vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 2], vtcm_scales, n_row_tiles, n_col_tiles, k / HTP_MM_HMX_TILE_N_ROWS); - hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_matmul_worker_fn, &job)); + if (is_int_hmx) { + hmx_matmul_task_init_int(&task, vtcm_output, vtcm_f16_act, vtcm_weight_bufs[i % 2], L.weight_bias_offset, + n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles, (uint32_t) n_groups); + } else { + hmx_matmul_task_init(&task, vtcm_output, vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 2], vtcm_scales, n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles); + } + hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task)); hmx_queue_pop(ctx->hmx_queue); - // D: Output Store - float *output_chunk = dst + (mr * dst_stride + nc); - const float *bias_chunk = has_bias ? (vtcm_bias + mr * src2_stride + nc) : NULL; - int chunk_dst_cols = dst_cols - (int)nc; + // D: Output Store into vtcm_res_out[0] + 2D bypass DMA + const void *bias_chunk = has_bias ? ((const uint8_t *) vtcm_bias + (mr * bias_stride + nc) * bias_elem_size) : NULL; + int chunk_dst_cols = dst_cols - (int) nc; if (chunk_dst_cols > 0) { - transfer_output_chunk_threaded(ctx, output_chunk, bias_chunk, vtcm_output, n_rows, n_cols, dst_stride, src2_stride, chunk_dst_cols, n_hvx); + if (is_int_hmx) { + const float * wt_scales = (const float *) ((const uint8_t *) vtcm_weight_bufs[i % 2] + L.weight_scales_offset); + transfer_output_chunk_int_threaded( + octx, vtcm_res_out[0], bias_chunk, vtcm_output, + vtcm_act_scales, wt_scales, (int) n_rows, (int) n_cols, + n_groups, res_out_stride_elems, bias_stride, chunk_dst_cols, + dst_elem_size, bias_elem_size); + } else { + transfer_output_chunk_threaded(octx, vtcm_res_out[0], bias_chunk, vtcm_output, + n_rows, n_cols, res_out_stride_elems, bias_stride, chunk_dst_cols, + dst_elem_size, bias_elem_size); + } } + const int vcols_o = hex_smin((int) n_cols, chunk_dst_cols); + const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0; + dma_queue_push(weight_dma, + dma_make_data(dst_dma_addr + (mr * dst_stride + nc) * dst_elem_size, vtcm_res_out[0]), + dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0); + } + if (n_chunk_cnt > 0) { + dma_queue_pop(weight_dma); } } } @@ -2919,6 +4103,711 @@ static int hmx_mm_2d_f32(struct htp_context *ctx, return 0; } +static int hmx_mm_nx_glu_int_2d(struct htp_ops_context * octx, const struct htp_mm_kernel_params * kparams) { + struct htp_context * ctx = octx->ctx; + struct htp_thread_trace * tr = &ctx->trace[0]; + htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0); + + const struct htp_tensor * restrict src_gate = octx->src[0]; + const struct htp_tensor * restrict src_up = octx->src[1]; + const struct htp_tensor * restrict act = octx->src[2]; + const struct htp_tensor * restrict dst = octx->dst; + + const int weight_type = (int) src_gate->type; + const int k = (int) act->ne[0]; + const int k_valid = (int) act->ne[0]; + const size_t n = (size_t) src_gate->ne[1]; + const int m = (int) (act->ne[1] * act->ne[2] * act->ne[3]); + const uint32_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const size_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const int act_stride = (int) (act->nb[1] / act_elem_size); + const dma_addr_t act_dma_addr = act->data; + + const int32_t kernel_type = kparams->kernel_type; + const int n_groups = kparams->hmx_n_groups; + const int tile_k = htp_tensor_get_tile_k(weight_type); + + if (tile_k <= 0 || (k % tile_k) != 0 || (k & 31) != 0 || !htp_mm_kernel_is_hmx_int(kernel_type)) { + return HTP_STATUS_NO_SUPPORT; + } + if (n == 0) { + return HTP_STATUS_OK; + } + + hmx_output_glu_state_t glu_state; + if (!resolve_int_output_glu_fns((uint32_t) n_groups, kparams->glu_op, dst_elem_size, + &glu_state.col_chunk_fn, &glu_state.store_quad_fn, + &glu_state.store_tail_fn, &glu_state.store_strip_fn)) { + return HTP_STATUS_NO_SUPPORT; + } + + const struct fastdiv_values n_groups_div = kparams->div_hmx_n_groups; + const hmx_queue_func hmx_worker_fn = hmx_get_matmul_worker_fn(kernel_type); + + const int n_k_tiles = k >> 5; + const int n_weight_tiles = (weight_type == HTP_TYPE_Q4_0) ? n_k_tiles : (k / tile_k); + const int tile_size = kparams->tile_size; + const int aligned_tile_size = kparams->aligned_tile_size; + if (tile_size <= 0) { + return HTP_STATUS_NO_SUPPORT; + } + + const size_t vtcm_budget = ctx->vtcm_size; + const int m_chunk_n_rows = kparams->m_chunk; + const int n_chunk_n_cols = kparams->n_chunk; + const int pipeline = kparams->pipeline; + const int act_hvx = kparams->n_act_hvx; + const struct fastdiv_values * act_hvx_div = &kparams->div_n_act_hvx; + + struct htp_mm_hmx_vtcm_layout L; + htp_mm_hmx_vtcm_layout_build_glu(&L, kernel_type, weight_type, k, + m_chunk_n_rows, n_chunk_n_cols, pipeline, act_hvx, aligned_tile_size, + dst_elem_size); + if (L.total_bytes > vtcm_budget) { + FARF(ERROR, "hmx-mm-nx-glu: VTCM overflow: used %zu budget %zu, m %d k %d n %zu mc %d nc %d", + L.total_bytes, vtcm_budget, m, k, n, m_chunk_n_rows, n_chunk_n_cols); + return HTP_STATUS_VTCM_TOO_SMALL; + } + + uint8_t * const base = (uint8_t *) ctx->vtcm_base; + void * vtcm_weight_raw[2] = { + VTCM_LAYOUT_PTR(void, base, L.off_weight[0]), + VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_weight[1], pipeline) + }; + uint8_t * vtcm_act = VTCM_LAYOUT_PTR(uint8_t, base, L.off_act); + float * vtcm_f32_act = VTCM_LAYOUT_PTR(float, base, L.off_act_f32); + float * vtcm_act_scales = VTCM_LAYOUT_PTR(float, base, L.off_act_scales); + void * vtcm_gate[2] = { + VTCM_LAYOUT_PTR(void, base, L.off_dst[0]), + VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_dst[1], pipeline) + }; + void * vtcm_up[2] = { + VTCM_LAYOUT_PTR(void, base, L.off_dst_up[0]), + VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_dst_up[1], pipeline) + }; + void * vtcm_scratch[2] = { + VTCM_LAYOUT_PTR(void, base, L.off_scratch[0]), + VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_scratch[1], pipeline) + }; + float * vtcm_wt_scales_gate[2] = { + VTCM_LAYOUT_PTR(float, base, L.off_wt_scales_gate[0]), + VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_wt_scales_gate[1], pipeline) + }; + float * vtcm_wt_scales_up[2] = { + VTCM_LAYOUT_PTR(float, base, L.off_wt_scales_up[0]), + VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_wt_scales_up[1], pipeline) + }; + void * vtcm_res_out[2] = { + VTCM_LAYOUT_PTR(void, base, L.off_res_out[0]), + VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_res_out[1], pipeline) + }; + + if (L.lut_bytes > 0) { + iq2xxs_lut_copy(base + L.off_lut); + } + + int m_start = 0; + int m_rows = m; + if (octx->ctx->mdev.count > 1) { + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition((uint32_t) m, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + m_start = (int) range.start; + m_rows = (int) range.count; + } + if (m_rows == 0) { + return HTP_STATUS_OK; + } + + FARF(HIGH, "hmx-mm-nx-glu: glu %u ktype %d m %d (%d..%d) k %d n %zu wtype %d mc %d nc %d vtcm %zu/%zu", + (unsigned) kparams->glu_op, (int) kernel_type, m, m_start, m_start + m_rows, k, n, weight_type, + m_chunk_n_rows, n_chunk_n_cols, L.total_bytes, vtcm_budget); + + htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0); + + const size_t mr_end = (size_t) (m_start + m_rows); + const dma_addr_t w_gate = src_gate->data; + const dma_addr_t w_up = src_up->data; + const size_t w_gate_stride = src_gate->nb[1]; + const size_t w_up_stride = src_up->nb[1]; + const dma_addr_t dst_dma_addr = dst->data; + const size_t dst_stride = dst->nb[1] / dst_elem_size; + const size_t dst_row_bytes = dst->nb[1]; + const int dst_cols = (int) dst->ne[0]; + const size_t res_out_stride_bytes = hex_align_up((size_t) n_chunk_n_cols * dst_elem_size, 128); + const int res_out_stride_elems = (int) (res_out_stride_bytes / dst_elem_size); + const int n_chunk_cnt = hmx_ceil_div(n, n_chunk_n_cols); + dma_queue * weight_dma = octx->ctx->dma[0]; + + glu_state.vtcm_act_scales = vtcm_act_scales; + glu_state.n_groups = (uint32_t) n_groups; + glu_state.dst_stride = (uint32_t) res_out_stride_elems; + glu_state.dst_elem_size = dst_elem_size; + + if (pipeline) { + // 4-buffer HMX output pipeline: vtcm_gate[2] + vtcm_up[2] (GLU(s-1) overlaps both HMX(gate_s) and HMX(up_s)) + hmx_matmul_task_t task_gate[2]; + hmx_matmul_task_t task_up[2]; + const bool preissue_gate0 = L.can_preissue_weight && n > 0; + + for (size_t mr = (size_t) m_start; mr < mr_end; mr += m_chunk_n_rows) { + const size_t n_rows = hex_smin(mr_end - mr, m_chunk_n_rows); + const size_t n_row_tiles = hmx_ceil_div(n_rows, 64u); + + if (preissue_gate0) { + const size_t n_cols0 = hex_smin(n, (size_t) n_chunk_n_cols); + const uint32_t height0 = hmx_ceil_div(n_cols0, 32) * n_weight_tiles; + dma_proxy_push(ctx->dma_proxy, dma_make_data(vtcm_weight_raw[0], w_gate), + aligned_tile_size, tile_size, tile_size, height0); + } + + transfer_activation_chunk_int_threaded( + ctx, vtcm_act, vtcm_act_scales, + act_dma_addr + (size_t) mr * act_stride * act_elem_size, + (int) n_rows, k, act_stride, k_valid, n_groups, + act_hvx, act_hvx_div, vtcm_f32_act, L.act_f32_bytes, act_elem_size); + + // Prologue: push gate_0 (if not preissued) and up_0 + { + const size_t n_cols0 = hex_smin(n, (size_t) n_chunk_n_cols); + const uint32_t height0 = hmx_ceil_div(n_cols0, 32) * n_weight_tiles; + if (!preissue_gate0) { + dma_queue_push(weight_dma, dma_make_data(vtcm_weight_raw[0], w_gate), + aligned_tile_size, tile_size, tile_size, height0); + } + dma_queue_push(weight_dma, dma_make_data(vtcm_weight_raw[1], w_up), + aligned_tile_size, tile_size, tile_size, height0); + } + + for (int s = 0; s < n_chunk_cnt; ++s) { + const int cur = s & 1; + const int prev = (s - 1) & 1; + const size_t nc = (size_t) s * n_chunk_n_cols; + const size_t n_cols = hex_smin(n - nc, (size_t) n_chunk_n_cols); + const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS); + + // 1. Pop gate_s, wait HMX(gate_{s-1}) so vtcm_scratch[0] is free, rescale and submit HMX(gate_s) + if (s == 0 && preissue_gate0) { + dma_proxy_pop(ctx->dma_proxy); + } else { + dma_queue_pop(weight_dma); + } + if (s > 0) { + hmx_queue_pop(ctx->hmx_queue); + } + rescale_int_weight_chunk_to_int8_tiles_scales( + octx, vtcm_scratch[0], L.weight_bias_offset, vtcm_wt_scales_gate[cur], + vtcm_weight_raw[0], (int) n_cols, k, n_groups, &n_groups_div, aligned_tile_size, weight_type); + + hmx_matmul_task_init_int(&task_gate[cur], vtcm_gate[cur], + vtcm_act, vtcm_scratch[0], L.weight_bias_offset, + n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles, (uint32_t) n_groups); + hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task_gate[cur])); + + if (s + 1 < n_chunk_cnt) { + const size_t nc_n = (size_t) (s + 1) * n_chunk_n_cols; + const size_t n_cols_n = hex_smin(n - nc_n, (size_t) n_chunk_n_cols); + const uint32_t height_n = hmx_ceil_div(n_cols_n, 32) * n_weight_tiles; + dma_queue_push(weight_dma, dma_make_data(vtcm_weight_raw[0], w_gate + nc_n * w_gate_stride), + aligned_tile_size, tile_size, tile_size, height_n); + } + + // 2. Pop up_s, wait HMX(up_{s-1}) so vtcm_scratch[1] and GLU(s-1) inputs are ready, rescale and submit HMX(up_s) + dma_queue_pop(weight_dma); + if (s > 0) { + hmx_queue_pop(ctx->hmx_queue); + } + rescale_int_weight_chunk_to_int8_tiles_scales( + octx, vtcm_scratch[1], L.weight_bias_offset, vtcm_wt_scales_up[cur], + vtcm_weight_raw[1], (int) n_cols, k, n_groups, &n_groups_div, aligned_tile_size, weight_type); + + hmx_matmul_task_init_int(&task_up[cur], vtcm_up[cur], + vtcm_act, vtcm_scratch[1], L.weight_bias_offset, + n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles, (uint32_t) n_groups); + hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task_up[cur])); + + if (s + 1 < n_chunk_cnt) { + const size_t nc_n = (size_t) (s + 1) * n_chunk_n_cols; + const size_t n_cols_n = hex_smin(n - nc_n, (size_t) n_chunk_n_cols); + const uint32_t height_n = hmx_ceil_div(n_cols_n, 32) * n_weight_tiles; + dma_queue_push(weight_dma, dma_make_data(vtcm_weight_raw[1], w_up + nc_n * w_up_stride), + aligned_tile_size, tile_size, tile_size, height_n); + } + + // 3. Run HVX GLU(s-1) in parallel with HMX(gate_s) + HMX(up_s) + out_{s-2} DMA, then drain out_{s-2} and push out_{s-1} + if (s > 0) { + const size_t nc_prev = (size_t) (s - 1) * n_chunk_n_cols; + const size_t n_cols_p = hex_smin(n - nc_prev, (size_t) n_chunk_n_cols); + const int chunk_dst_cols = dst_cols - (int) nc_prev; + if (chunk_dst_cols > 0) { + transfer_output_chunk_int_glu_threaded( + octx, &glu_state, vtcm_res_out[prev], vtcm_gate[prev], vtcm_up[prev], + vtcm_wt_scales_gate[prev], vtcm_wt_scales_up[prev], + (int) n_rows, (int) n_cols_p, chunk_dst_cols); + } + if (s >= 2) { + dma_queue_pop(weight_dma); + } + const int vcols_o = hex_smin((int) n_cols_p, chunk_dst_cols); + const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0; + dma_queue_push(weight_dma, + dma_make_data(dst_dma_addr + (mr * dst_stride + nc_prev) * dst_elem_size, vtcm_res_out[prev]), + dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0); + } + } + + // Epilogue: wait HMX(gate_{last}) + HMX(up_{last}), drain out_{last-1}, run GLU(last), push+pop out_{last} + { + const int last = (n_chunk_cnt - 1) & 1; + const size_t nc_last = (size_t) (n_chunk_cnt - 1) * n_chunk_n_cols; + const size_t n_cols_last = hex_smin(n - nc_last, (size_t) n_chunk_n_cols); + const int chunk_dst_cols = dst_cols - (int) nc_last; + + hmx_queue_pop(ctx->hmx_queue); + hmx_queue_pop(ctx->hmx_queue); + if (n_chunk_cnt >= 2) { + dma_queue_pop(weight_dma); + } + + if (chunk_dst_cols > 0) { + transfer_output_chunk_int_glu_threaded( + octx, &glu_state, vtcm_res_out[last], vtcm_gate[last], vtcm_up[last], + vtcm_wt_scales_gate[last], vtcm_wt_scales_up[last], + (int) n_rows, (int) n_cols_last, chunk_dst_cols); + } + + const int vcols_o = hex_smin((int) n_cols_last, chunk_dst_cols); + const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0; + dma_queue_push(weight_dma, + dma_make_data(dst_dma_addr + (mr * dst_stride + nc_last) * dst_elem_size, vtcm_res_out[last]), + dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0); + dma_queue_pop(weight_dma); + } + } + } else { + // Non-pipelined 2-buffer path (m <= 32) + hmx_matmul_task_t task; + + for (size_t mr = (size_t) m_start; mr < mr_end; mr += m_chunk_n_rows) { + const size_t n_rows = hex_smin(mr_end - mr, m_chunk_n_rows); + const size_t n_row_tiles = hmx_ceil_div(n_rows, 64u); + + transfer_activation_chunk_int_threaded( + ctx, vtcm_act, vtcm_act_scales, + act_dma_addr + (size_t) mr * act_stride * act_elem_size, + (int) n_rows, k, act_stride, k_valid, n_groups, + act_hvx, act_hvx_div, vtcm_f32_act, L.act_f32_bytes, act_elem_size); + + for (int s = 0; s < n_chunk_cnt; ++s) { + const size_t nc = (size_t) s * n_chunk_n_cols; + const size_t n_cols = hex_smin(n - nc, (size_t) n_chunk_n_cols); + const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS); + const uint32_t height = hmx_ceil_div(n_cols, 32) * n_weight_tiles; + + dma_queue_push(weight_dma, dma_make_data(vtcm_weight_raw[0], w_gate + nc * w_gate_stride), + aligned_tile_size, tile_size, tile_size, height); + dma_queue_pop(weight_dma); + rescale_int_weight_chunk_to_int8_tiles_scales( + octx, vtcm_scratch[0], L.weight_bias_offset, vtcm_wt_scales_gate[0], + vtcm_weight_raw[0], (int) n_cols, k, n_groups, &n_groups_div, aligned_tile_size, weight_type); + hmx_matmul_task_init_int(&task, vtcm_gate[0], vtcm_act, vtcm_scratch[0], L.weight_bias_offset, + n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles, (uint32_t) n_groups); + hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task)); + hmx_queue_pop(ctx->hmx_queue); + + dma_queue_push(weight_dma, dma_make_data(vtcm_weight_raw[0], w_up + nc * w_up_stride), + aligned_tile_size, tile_size, tile_size, height); + dma_queue_pop(weight_dma); + rescale_int_weight_chunk_to_int8_tiles_scales( + octx, vtcm_scratch[0], L.weight_bias_offset, vtcm_wt_scales_up[0], + vtcm_weight_raw[0], (int) n_cols, k, n_groups, &n_groups_div, aligned_tile_size, weight_type); + hmx_matmul_task_init_int(&task, vtcm_up[0], vtcm_act, vtcm_scratch[0], L.weight_bias_offset, + n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles, (uint32_t) n_groups); + hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task)); + hmx_queue_pop(ctx->hmx_queue); + + const int chunk_dst_cols = dst_cols - (int) nc; + if (chunk_dst_cols > 0) { + transfer_output_chunk_int_glu_threaded( + octx, &glu_state, vtcm_res_out[0], vtcm_gate[0], vtcm_up[0], + vtcm_wt_scales_gate[0], vtcm_wt_scales_up[0], + (int) n_rows, (int) n_cols, chunk_dst_cols); + } + const int vcols_o = hex_smin((int) n_cols, chunk_dst_cols); + const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0; + dma_queue_push(weight_dma, + dma_make_data(dst_dma_addr + (mr * dst_stride + nc) * dst_elem_size, vtcm_res_out[0]), + dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0); + dma_queue_pop(weight_dma); + } + } + } + + return HTP_STATUS_OK; +} + +static int hmx_mm_nx_glu_fp16_2d(struct htp_ops_context * octx, const struct htp_mm_kernel_params * kparams) { + struct htp_context * ctx = octx->ctx; + struct htp_thread_trace * tr = &ctx->trace[0]; + htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0); + + const struct htp_tensor * restrict src_gate = octx->src[0]; + const struct htp_tensor * restrict src_up = octx->src[1]; + const struct htp_tensor * restrict act = octx->src[2]; + const struct htp_tensor * restrict dst = octx->dst; + + const int weight_type = (int) src_gate->type; + const int k = (int) act->ne[0]; + const int k_valid = (int) act->ne[0]; + const size_t n = (size_t) src_gate->ne[1]; + const int m = (int) (act->ne[1] * act->ne[2] * act->ne[3]); + const uint32_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const size_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const int act_stride = (int) (act->nb[1] / act_elem_size); + const dma_addr_t act_dma_addr = act->data; + + const int32_t kernel_type = kparams->kernel_type; + const int tile_size = kparams->tile_size; + const int aligned_tile_size = kparams->aligned_tile_size; + const bool is_tiled = (tile_size > 0); + const int tile_k = htp_tensor_get_tile_k(weight_type); + + if ((k & 31) != 0 || (is_tiled && (tile_k <= 0 || (k % tile_k) != 0)) || kernel_type != HTP_MM_KERNEL_HMX_2D) { + return HTP_STATUS_NO_SUPPORT; + } + if (n == 0) { + return HTP_STATUS_OK; + } + + const size_t row_stride = htp_tensor_get_row_size(weight_type, k); + if (row_stride == 0) { + return HTP_STATUS_NO_SUPPORT; + } + + hmx_output_glu_state_t glu_state; + if (!resolve_fp16_output_glu_fns(kparams->glu_op, dst_elem_size, + &glu_state.col_chunk_fn, &glu_state.store_quad_fn, + &glu_state.store_tail_fn, &glu_state.store_strip_fn)) { + return HTP_STATUS_NO_SUPPORT; + } + + const hmx_queue_func hmx_worker_fn = hmx_get_matmul_worker_fn(kernel_type); + const int n_k_tiles = k >> 5; + const int n_weight_tiles = is_tiled ? ((weight_type == HTP_TYPE_Q4_0) ? n_k_tiles : (k / tile_k)) : 0; + const struct fastdiv_values n_k_tiles_div = kparams->div_n_k_tiles; + tiled_dequant_task_fn_t dequant_worker_fn = hmx_get_dequant_worker_fn(weight_type, is_tiled); + + const size_t vtcm_budget = ctx->vtcm_size; + const int m_chunk_n_rows = kparams->m_chunk; + const int n_chunk_n_cols = kparams->n_chunk; + const int pipeline = kparams->pipeline; + const int act_hvx = kparams->n_act_hvx; + const struct fastdiv_values * act_hvx_div = &kparams->div_n_act_hvx; + const struct fastdiv_values * k_div = &kparams->div_ne00_padded; + + struct htp_mm_hmx_vtcm_layout L; + htp_mm_hmx_vtcm_layout_build_glu(&L, kernel_type, weight_type, k, + m_chunk_n_rows, n_chunk_n_cols, pipeline, act_hvx, aligned_tile_size, + dst_elem_size); + if (L.total_bytes > vtcm_budget) { + FARF(ERROR, "hmx-mm-nx-glu-fp16: VTCM overflow: used %zu budget %zu, m %d k %d n %zu mc %d nc %d", + L.total_bytes, vtcm_budget, m, k, n, m_chunk_n_rows, n_chunk_n_cols); + return HTP_STATUS_VTCM_TOO_SMALL; + } + + uint8_t * const base = (uint8_t *) ctx->vtcm_base; + void * vtcm_weight_raw[2] = { + VTCM_LAYOUT_PTR(void, base, L.off_weight[0]), + VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_weight[1], pipeline) + }; + __fp16 * vtcm_f16_act = VTCM_LAYOUT_PTR(__fp16, base, L.off_act); + float * vtcm_f32_act = VTCM_LAYOUT_PTR(float, base, L.off_act_f32); + __fp16 * vtcm_scales = VTCM_LAYOUT_PTR(__fp16, base, L.off_scales); + __fp16 * vtcm_gate[2] = { + VTCM_LAYOUT_PTR(__fp16, base, L.off_dst[0]), + VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_dst[1], pipeline) + }; + __fp16 * vtcm_up[2] = { + VTCM_LAYOUT_PTR(__fp16, base, L.off_dst_up[0]), + VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_dst_up[1], pipeline) + }; + void * vtcm_scratch[2] = { + VTCM_LAYOUT_PTR(void, base, L.off_scratch[0]), + VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_scratch[1], pipeline) + }; + void * vtcm_res_out[2] = { + VTCM_LAYOUT_PTR(void, base, L.off_res_out[0]), + VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_res_out[1], pipeline) + }; + + hmx_init_column_scales(vtcm_scales, Q6_V_vsplat_R(0x3c00)); // scale: 1.0, bias: 0.0 in FP16 + if (L.lut_bytes > 0) { + iq2xxs_lut_copy(base + L.off_lut); + } + + int m_start = 0; + int m_rows = m; + if (octx->ctx->mdev.count > 1) { + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition((uint32_t) m, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + m_start = (int) range.start; + m_rows = (int) range.count; + } + if (m_rows == 0) { + return HTP_STATUS_OK; + } + + FARF(HIGH, "hmx-mm-nx-glu-fp16: glu %u m %d (%d..%d) k %d n %zu wtype %d mc %d nc %d vtcm %zu/%zu", + (unsigned) kparams->glu_op, m, m_start, m_start + m_rows, k, n, weight_type, + m_chunk_n_rows, n_chunk_n_cols, L.total_bytes, vtcm_budget); + + htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0); + + const size_t mr_end = (size_t) (m_start + m_rows); + const dma_addr_t w_gate = src_gate->data; + const dma_addr_t w_up = src_up->data; + const size_t w_gate_stride = src_gate->nb[1]; + const size_t w_up_stride = src_up->nb[1]; + const dma_addr_t dst_dma_addr = dst->data; + const size_t dst_stride = dst->nb[1] / dst_elem_size; + const size_t dst_row_bytes = dst->nb[1]; + const int dst_cols = (int) dst->ne[0]; + const size_t res_out_stride_bytes = hex_align_up((size_t) n_chunk_n_cols * dst_elem_size, 128); + const int res_out_stride_elems = (int) (res_out_stride_bytes / dst_elem_size); + const int n_chunk_cnt = hmx_ceil_div(n, n_chunk_n_cols); + const uint32_t dma_dst_stride = is_tiled ? (uint32_t) aligned_tile_size : (uint32_t) row_stride; + const uint32_t dma_width_bytes = is_tiled ? (uint32_t) tile_size : (uint32_t) row_stride; + const uint32_t dma_src_stride_g = is_tiled ? (uint32_t) tile_size : (uint32_t) w_gate_stride; + const uint32_t dma_src_stride_u = is_tiled ? (uint32_t) tile_size : (uint32_t) w_up_stride; + dma_queue * weight_dma = octx->ctx->dma[0]; + + glu_state.vtcm_act_scales = NULL; + glu_state.vtcm_wt_scales_up = NULL; + glu_state.n_groups = 1u; + glu_state.dst_stride = (uint32_t) res_out_stride_elems; + glu_state.dst_elem_size = dst_elem_size; + + if (pipeline) { + // When dequant_worker_fn is NULL (pre-tiled F16), ping-pong raw/HMX across {weight_raw, scratch}. + void * gate_raw_buf[2] = { vtcm_weight_raw[0], dequant_worker_fn ? vtcm_weight_raw[0] : vtcm_scratch[0] }; + void * up_raw_buf[2] = { vtcm_weight_raw[1], dequant_worker_fn ? vtcm_weight_raw[1] : vtcm_scratch[1] }; + void * gate_hmx_buf[2] = { dequant_worker_fn ? vtcm_scratch[0] : vtcm_weight_raw[0], vtcm_scratch[0] }; + void * up_hmx_buf[2] = { dequant_worker_fn ? vtcm_scratch[1] : vtcm_weight_raw[1], vtcm_scratch[1] }; + + hmx_matmul_task_t task_gate[2]; + hmx_matmul_task_t task_up[2]; + + for (size_t mr = (size_t) m_start; mr < mr_end; mr += m_chunk_n_rows) { + const size_t n_rows = hex_smin(mr_end - mr, m_chunk_n_rows); + const size_t n_row_tiles = hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS); + + struct activation_transfer_params act_params = { + .ctx = ctx, + .dst = vtcm_f16_act, + .act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size, + .n_rows = (int) n_rows, + .k_block = k, + .k_stride = act_stride, + .n_hvx = act_hvx, + .act_hvx_div = act_hvx_div, + .k_div = k_div, + .k_valid = k_valid, + .vtcm_f32_act = vtcm_f32_act, + .vtcm_f32_act_bytes = L.act_f32_bytes, + .act_elem_size = act_elem_size, + }; + transfer_activation_chunk_threaded(&act_params); + + // Prologue: push gate_0 and up_0 + { + const size_t n_cols0 = hex_smin(n, (size_t) n_chunk_n_cols); + const uint32_t height0 = is_tiled ? (hmx_ceil_div(n_cols0, 32) * n_weight_tiles) : (uint32_t) n_cols0; + dma_queue_push(weight_dma, dma_make_data(gate_raw_buf[0], w_gate), + dma_dst_stride, dma_src_stride_g, dma_width_bytes, height0); + dma_queue_push(weight_dma, dma_make_data(up_raw_buf[0], w_up), + dma_dst_stride, dma_src_stride_u, dma_width_bytes, height0); + } + + for (int s = 0; s < n_chunk_cnt; ++s) { + const int cur = s & 1; + const int next = (s + 1) & 1; + const int prev = (s - 1) & 1; + const size_t nc = (size_t) s * n_chunk_n_cols; + const size_t n_cols = hex_smin(n - nc, (size_t) n_chunk_n_cols); + const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS); + + // 1. Pop gate_s, wait HMX(gate_{s-1}) so gate_hmx_buf[cur] is free, dequant and submit HMX(gate_s) + dma_queue_pop(weight_dma); + if (s > 0) { + hmx_queue_pop(ctx->hmx_queue); + } + if (dequant_worker_fn) { + dequantize_tiled_weight_chunk_to_fp16_tiles( + octx, gate_hmx_buf[cur], gate_raw_buf[cur], + n_cols, k, row_stride, weight_type, + n_k_tiles, n_k_tiles_div, dequant_worker_fn); + } + + hmx_matmul_task_init(&task_gate[cur], vtcm_gate[cur], vtcm_f16_act, (__fp16 *) gate_hmx_buf[cur], + vtcm_scales, n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles); + hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task_gate[cur])); + + if (s + 1 < n_chunk_cnt) { + const size_t nc_n = (size_t) (s + 1) * n_chunk_n_cols; + const size_t n_cols_n = hex_smin(n - nc_n, (size_t) n_chunk_n_cols); + const uint32_t height_n = is_tiled ? (hmx_ceil_div(n_cols_n, 32) * n_weight_tiles) : (uint32_t) n_cols_n; + dma_queue_push(weight_dma, dma_make_data(gate_raw_buf[next], w_gate + nc_n * w_gate_stride), + dma_dst_stride, dma_src_stride_g, dma_width_bytes, height_n); + } + + // 2. Pop up_s, wait HMX(up_{s-1}) so up_hmx_buf[cur] and GLU(s-1) inputs are ready, dequant and submit HMX(up_s) + dma_queue_pop(weight_dma); + if (s > 0) { + hmx_queue_pop(ctx->hmx_queue); + } + if (dequant_worker_fn) { + dequantize_tiled_weight_chunk_to_fp16_tiles( + octx, up_hmx_buf[cur], up_raw_buf[cur], + n_cols, k, row_stride, weight_type, + n_k_tiles, n_k_tiles_div, dequant_worker_fn); + } + + hmx_matmul_task_init(&task_up[cur], vtcm_up[cur], vtcm_f16_act, (__fp16 *) up_hmx_buf[cur], + vtcm_scales, n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles); + hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task_up[cur])); + + if (s + 1 < n_chunk_cnt) { + const size_t nc_n = (size_t) (s + 1) * n_chunk_n_cols; + const size_t n_cols_n = hex_smin(n - nc_n, (size_t) n_chunk_n_cols); + const uint32_t height_n = is_tiled ? (hmx_ceil_div(n_cols_n, 32) * n_weight_tiles) : (uint32_t) n_cols_n; + dma_queue_push(weight_dma, dma_make_data(up_raw_buf[next], w_up + nc_n * w_up_stride), + dma_dst_stride, dma_src_stride_u, dma_width_bytes, height_n); + } + + // 3. Run HVX GLU(s-1) in parallel with HMX(gate_s) + HMX(up_s) + out_{s-2} DMA, then drain out_{s-2} and push out_{s-1} + if (s > 0) { + const size_t nc_prev = (size_t) (s - 1) * n_chunk_n_cols; + const size_t n_cols_p = hex_smin(n - nc_prev, (size_t) n_chunk_n_cols); + const int chunk_dst_cols = dst_cols - (int) nc_prev; + if (chunk_dst_cols > 0) { + transfer_output_chunk_int_glu_threaded( + octx, &glu_state, vtcm_res_out[prev], vtcm_gate[prev], vtcm_up[prev], + NULL, NULL, (int) n_rows, (int) n_cols_p, chunk_dst_cols); + } + if (s >= 2) { + dma_queue_pop(weight_dma); + } + const int vcols_o = hex_smin((int) n_cols_p, chunk_dst_cols); + const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0; + dma_queue_push(weight_dma, + dma_make_data(dst_dma_addr + (mr * dst_stride + nc_prev) * dst_elem_size, vtcm_res_out[prev]), + dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0); + } + } + + // Epilogue: wait HMX(gate_{last}) + HMX(up_{last}), drain out_{last-1}, run GLU(last), push+pop out_{last} + { + const int last = (n_chunk_cnt - 1) & 1; + const size_t nc_last = (size_t) (n_chunk_cnt - 1) * n_chunk_n_cols; + const size_t n_cols_last = hex_smin(n - nc_last, (size_t) n_chunk_n_cols); + const int chunk_dst_cols = dst_cols - (int) nc_last; + + hmx_queue_pop(ctx->hmx_queue); + hmx_queue_pop(ctx->hmx_queue); + if (n_chunk_cnt >= 2) { + dma_queue_pop(weight_dma); + } + + if (chunk_dst_cols > 0) { + transfer_output_chunk_int_glu_threaded( + octx, &glu_state, vtcm_res_out[last], vtcm_gate[last], vtcm_up[last], + NULL, NULL, (int) n_rows, (int) n_cols_last, chunk_dst_cols); + } + + const int vcols_o = hex_smin((int) n_cols_last, chunk_dst_cols); + const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0; + dma_queue_push(weight_dma, + dma_make_data(dst_dma_addr + (mr * dst_stride + nc_last) * dst_elem_size, vtcm_res_out[last]), + dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0); + dma_queue_pop(weight_dma); + } + } + } else { + // Non-pipelined 2-buffer path (m <= 32) + void * w_hmx = dequant_worker_fn ? vtcm_scratch[0] : vtcm_weight_raw[0]; + hmx_matmul_task_t task; + + for (size_t mr = (size_t) m_start; mr < mr_end; mr += m_chunk_n_rows) { + const size_t n_rows = hex_smin(mr_end - mr, m_chunk_n_rows); + const size_t n_row_tiles = hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS); + + struct activation_transfer_params act_params = { + .ctx = ctx, + .dst = vtcm_f16_act, + .act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size, + .n_rows = (int) n_rows, + .k_block = k, + .k_stride = act_stride, + .n_hvx = act_hvx, + .act_hvx_div = act_hvx_div, + .k_div = k_div, + .k_valid = k_valid, + .vtcm_f32_act = vtcm_f32_act, + .vtcm_f32_act_bytes = L.act_f32_bytes, + .act_elem_size = act_elem_size, + }; + transfer_activation_chunk_threaded(&act_params); + + for (int s = 0; s < n_chunk_cnt; ++s) { + const size_t nc = (size_t) s * n_chunk_n_cols; + const size_t n_cols = hex_smin(n - nc, (size_t) n_chunk_n_cols); + const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS); + const uint32_t height = is_tiled ? (hmx_ceil_div(n_cols, 32) * n_weight_tiles) : (uint32_t) n_cols; + + dma_queue_push(weight_dma, dma_make_data(vtcm_weight_raw[0], w_gate + nc * w_gate_stride), + dma_dst_stride, dma_src_stride_g, dma_width_bytes, height); + dma_queue_pop(weight_dma); + if (dequant_worker_fn) { + dequantize_tiled_weight_chunk_to_fp16_tiles( + octx, w_hmx, vtcm_weight_raw[0], + n_cols, k, row_stride, weight_type, + n_k_tiles, n_k_tiles_div, dequant_worker_fn); + } + hmx_matmul_task_init(&task, vtcm_gate[0], vtcm_f16_act, (__fp16 *) w_hmx, + vtcm_scales, n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles); + hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task)); + hmx_queue_pop(ctx->hmx_queue); + + dma_queue_push(weight_dma, dma_make_data(vtcm_weight_raw[0], w_up + nc * w_up_stride), + dma_dst_stride, dma_src_stride_u, dma_width_bytes, height); + dma_queue_pop(weight_dma); + if (dequant_worker_fn) { + dequantize_tiled_weight_chunk_to_fp16_tiles( + octx, w_hmx, vtcm_weight_raw[0], + n_cols, k, row_stride, weight_type, + n_k_tiles, n_k_tiles_div, dequant_worker_fn); + } + hmx_matmul_task_init(&task, vtcm_up[0], vtcm_f16_act, (__fp16 *) w_hmx, + vtcm_scales, n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles); + hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task)); + hmx_queue_pop(ctx->hmx_queue); + + const int chunk_dst_cols = dst_cols - (int) nc; + if (chunk_dst_cols > 0) { + transfer_output_chunk_int_glu_threaded( + octx, &glu_state, vtcm_res_out[0], vtcm_gate[0], vtcm_up[0], + NULL, NULL, (int) n_rows, (int) n_cols, chunk_dst_cols); + } + const int vcols_o = hex_smin((int) n_cols, chunk_dst_cols); + const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0; + dma_queue_push(weight_dma, + dma_make_data(dst_dma_addr + (mr * dst_stride + nc) * dst_elem_size, vtcm_res_out[0]), + dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0); + dma_queue_pop(weight_dma); + } + } + } + + return HTP_STATUS_OK; +} + static int hmx_mm_nx_2d_f32(struct htp_ops_context * octx, const struct htp_mm_kernel_params * kparams) { struct htp_context * ctx = octx->ctx; struct htp_thread_trace * tr = &ctx->trace[0]; @@ -2940,16 +4829,23 @@ static int hmx_mm_nx_2d_f32(struct htp_ops_context * octx, const struct htp_mm_k const int act_stride = (int) (act->nb[1] / act_elem_size); const dma_addr_t act_dma_addr = act->data; - if (k % 32 != 0) { return HTP_STATUS_NO_SUPPORT; } + const int32_t kernel_type = kparams->kernel_type; + const bool is_int_hmx = htp_mm_kernel_is_hmx_int(kernel_type); + const int n_groups = is_int_hmx ? kparams->hmx_n_groups : 1; + + if ((k & 31) != 0) { return HTP_STATUS_NO_SUPPORT; } + + const struct fastdiv_values n_groups_div = kparams->div_hmx_n_groups; + const hmx_queue_func hmx_worker_fn = hmx_get_matmul_worker_fn(kernel_type); size_t row_stride = htp_tensor_get_row_size(weight_type, k); if (row_stride == 0) { return HTP_STATUS_NO_SUPPORT; } - const int n_k_tiles = k / HTP_MM_HMX_TILE_N_COLS; - const int n_weight_tiles = k / htp_tensor_get_tile_k(weight_type); - const struct fastdiv_values n_k_tiles_div = init_fastdiv_values(n_k_tiles); + const int n_k_tiles = k >> 5; + const int n_weight_tiles = (weight_type == HTP_TYPE_Q4_0) ? n_k_tiles : (k / htp_tensor_get_tile_k(weight_type)); + const struct fastdiv_values n_k_tiles_div = kparams->div_n_k_tiles; const int tile_size = kparams->tile_size; const int aligned_tile_size = kparams->aligned_tile_size; @@ -2961,7 +4857,6 @@ static int hmx_mm_nx_2d_f32(struct htp_ops_context * octx, const struct htp_mm_k const int m_chunk_n_rows = kparams->m_chunk; const int n_chunk_n_cols = kparams->n_chunk; const int pipeline = kparams->pipeline; - const int n_hvx = octx->n_hvx; const int act_hvx = kparams->n_act_hvx; const struct fastdiv_values * act_hvx_div = &kparams->div_n_act_hvx; const struct fastdiv_values * k_div = &kparams->div_ne00_padded; @@ -2969,8 +4864,18 @@ static int hmx_mm_nx_2d_f32(struct htp_ops_context * octx, const struct htp_mm_k const uint32_t dma_dst_stride = is_tiled ? aligned_tile_size : row_stride; const uint32_t dma_width_bytes = is_tiled ? tile_size : row_stride; + size_t max_dst_elem_size = sizeof(__fp16); + for (uint32_t p = 0; p < n_weights; ++p) { + if (octx->dsts[p]) { + const size_t es = (octx->dsts[p]->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + if (es > max_dst_elem_size) max_dst_elem_size = es; + } + } + struct htp_mm_hmx_vtcm_layout L; - htp_mm_hmx_vtcm_layout_build(&L, HTP_MM_KERNEL_HMX_2D, weight_type, k, m_chunk_n_rows, n_chunk_n_cols, 1, pipeline, act_hvx, aligned_tile_size, 0); + htp_mm_hmx_vtcm_layout_build_ex(&L, kernel_type, weight_type, k, + m_chunk_n_rows, n_chunk_n_cols, 1, pipeline, act_hvx, aligned_tile_size, 0, + 0, max_dst_elem_size); if (L.total_bytes > vtcm_budget) { FARF(ERROR, "hmx-mm-nx-2d: VTCM overflow: used %zu budget %zu, m %d k %d mc %d nc %d", @@ -2985,13 +4890,20 @@ static int hmx_mm_nx_2d_f32(struct htp_ops_context * octx, const struct htp_mm_k }; __fp16 *vtcm_f16_act = VTCM_LAYOUT_PTR(__fp16, base, L.off_act); float *vtcm_f32_act = VTCM_LAYOUT_PTR(float, base, L.off_act_f32); + float *vtcm_act_scales = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_act_scales, is_int_hmx); __fp16 *vtcm_output = VTCM_LAYOUT_PTR(__fp16, base, L.off_dst[0]); void *vtcm_scratch0 = VTCM_LAYOUT_PTR(void, base, L.off_scratch[0]); void *vtcm_scratch1 = VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_scratch[1], pipeline); void *vtcm_scratch2 = VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_dst[1], pipeline); - __fp16 *vtcm_scales = VTCM_LAYOUT_PTR(__fp16, base, L.off_scales); + void *vtcm_res_out[2] = { + VTCM_LAYOUT_PTR(void, base, L.off_res_out[0]), + VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_res_out[1], pipeline), + }; + __fp16 *vtcm_scales = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, base, L.off_scales, !is_int_hmx); - hmx_init_column_scales(vtcm_scales, Q6_V_vsplat_R(0x3c00)); // scale: 1.0, bias: 0.0 in FP16 + if (!is_int_hmx) { + hmx_init_column_scales(vtcm_scales, Q6_V_vsplat_R(0x3c00)); // scale: 1.0, bias: 0.0 in FP16 + } if (L.lut_bytes > 0) { iq2xxs_lut_copy(base + L.off_lut); } @@ -2999,17 +4911,7 @@ static int hmx_mm_nx_2d_f32(struct htp_ops_context * octx, const struct htp_mm_k int m_start = 0; int m_rows = m; if (octx->ctx->mdev.count > 1) { - uint32_t rows_per_chunk = 1; - for (uint32_t p = 0; p < n_weights; ++p) { - const struct htp_tensor * restrict dst = octx->dsts[p]; - uint32_t dst_rpc = 0; - if (!htp_tensor_mdev_rows_per_chunk(dst, sizeof(float), dst->ne[0] * sizeof(float), &dst_rpc)) { - rows_per_chunk = 0; - break; - } - rows_per_chunk = MAX(rows_per_chunk, dst_rpc); - } - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition((uint32_t) m, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition((uint32_t) m, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); m_start = (int) range.start; m_rows = (int) range.count; } @@ -3018,15 +4920,16 @@ static int hmx_mm_nx_2d_f32(struct htp_ops_context * octx, const struct htp_mm_k return HTP_STATUS_OK; } - FARF(HIGH, "hmx-mm-nx-2d: n_weights %u m %d (%d..%d) k %d wtype %d mc %d nc %d vtcm %zu/%zu", - n_weights, m, m_start, m_start + m_rows, k, weight_type, m_chunk_n_rows, n_chunk_n_cols, L.total_bytes, vtcm_budget); + FARF(HIGH, "hmx-mm-nx-2d: ktype %d n_weights %u m %d (%d..%d) k %d wtype %d mc %d nc %d vtcm %zu/%zu", + (int) kernel_type, n_weights, m, m_start, m_start + m_rows, k, weight_type, m_chunk_n_rows, n_chunk_n_cols, L.total_bytes, vtcm_budget); htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0); const size_t mr_end = (size_t)(m_start + m_rows); + const uint32_t m_tile_rows = is_int_hmx ? 64u : HTP_MM_HMX_TILE_N_ROWS; if (pipeline) { - hmx_matmul_job_t job_slots[2]; + hmx_matmul_task_t task_slots[2]; void *vtcm_raw_bufs[4] = { vtcm_weight_raw[0], vtcm_weight_raw[1], @@ -3041,25 +4944,46 @@ static int hmx_mm_nx_2d_f32(struct htp_ops_context * octx, const struct htp_mm_k }; void *vtcm_output_bufs[2] = { vtcm_output, vtcm_scratch2 }; + const bool preissue_p0 = is_int_hmx && L.can_preissue_weight && n_weights > 0 + && octx->src[0] && octx->dsts[0] && octx->src[0]->ne[1] > 0; + for (size_t mr = (size_t) m_start; mr < mr_end; mr += m_chunk_n_rows) { const size_t n_rows = hex_smin(mr_end - mr, m_chunk_n_rows); - struct activation_transfer_params act_params = { - .ctx = ctx, - .dst = vtcm_f16_act, - .act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size, - .n_rows = (int) n_rows, - .k_block = k, - .k_stride = act_stride, - .n_hvx = act_hvx, - .act_hvx_div = act_hvx_div, - .k_div = k_div, - .k_valid = k_valid, - .vtcm_f32_act = vtcm_f32_act, - .vtcm_f32_act_bytes = L.act_f32_bytes, - .act_elem_size = act_elem_size, - }; - transfer_activation_chunk_threaded(&act_params); + if (preissue_p0) { + const struct htp_tensor * src_w0 = octx->src[0]; + const size_t n0 = src_w0->ne[1]; + const size_t n_cols_A0 = hex_smin(n0, (size_t) n_chunk_n_cols); + const uint32_t height_A0 = is_tiled ? hmx_ceil_div(n_cols_A0, 32) * n_weight_tiles : n_cols_A0; + const uint32_t src_str0 = is_tiled ? tile_size : src_w0->nb[1]; + dma_proxy_push(ctx->dma_proxy, dma_make_data(vtcm_raw_bufs[0], src_w0->data), + dma_dst_stride, src_str0, dma_width_bytes, height_A0); + } + + if (is_int_hmx) { + transfer_activation_chunk_int_threaded( + ctx, (uint8_t *) vtcm_f16_act, vtcm_act_scales, + act_dma_addr + (size_t) mr * act_stride * act_elem_size, + (int) n_rows, k, act_stride, k_valid, n_groups, + act_hvx, act_hvx_div, vtcm_f32_act, L.act_f32_bytes, act_elem_size); + } else { + struct activation_transfer_params act_params = { + .ctx = ctx, + .dst = vtcm_f16_act, + .act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size, + .n_rows = (int) n_rows, + .k_block = k, + .k_stride = act_stride, + .n_hvx = act_hvx, + .act_hvx_div = act_hvx_div, + .k_div = k_div, + .k_valid = k_valid, + .vtcm_f32_act = vtcm_f32_act, + .vtcm_f32_act_bytes = L.act_f32_bytes, + .act_elem_size = act_elem_size, + }; + transfer_activation_chunk_threaded(&act_params); + } for (uint32_t p = 0; p < n_weights; p++) { const struct htp_tensor * restrict src_w = octx->src[p]; @@ -3067,101 +4991,203 @@ static int hmx_mm_nx_2d_f32(struct htp_ops_context * octx, const struct htp_mm_k if (!src_w || !dst) continue; const dma_addr_t weight = src_w->data; - dma_queue * weight_dma = octx->ctx->dma[0]; - float * dst_ptr = (float *) dst->data; - const size_t n = src_w->ne[1]; + dma_queue * weight_dma = octx->ctx->dma[0]; + const dma_addr_t dst_dma_addr = dst->data; + const size_t n = src_w->ne[1]; if (n == 0) continue; - const size_t weight_stride = src_w->nb[1]; - const size_t dst_stride = dst->nb[1] / sizeof(float); - const int dst_cols = (int) dst->ne[0]; - const int n_chunk_cnt = hmx_ceil_div(n, n_chunk_n_cols); + const size_t weight_stride = src_w->nb[1]; + const size_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const size_t dst_stride = dst->nb[1] / dst_elem_size; + const size_t dst_row_bytes = dst->nb[1]; + const size_t res_out_stride_bytes = hex_align_up((size_t) n_chunk_n_cols * dst_elem_size, 128); + const int res_out_stride_elems = (int) (res_out_stride_bytes / dst_elem_size); + const int dst_cols = (int) dst->ne[0]; + const int n_chunk_cnt = hmx_ceil_div(n, n_chunk_n_cols); const uint32_t dma_src_stride = is_tiled ? tile_size : weight_stride; + const bool p_preissued = (p == 0 && preissue_p0); - const size_t n_cols_A0 = hex_smin(n - 0 * n_chunk_n_cols, n_chunk_n_cols); - const uint32_t height_A0 = is_tiled ? hmx_ceil_div(n_cols_A0, 32) * n_weight_tiles : n_cols_A0; - dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[0], weight), - dma_dst_stride, dma_src_stride, dma_width_bytes, height_A0); + if (!p_preissued) { + const size_t n_cols_A0 = hex_smin(n, (size_t) n_chunk_n_cols); + const uint32_t height_A0 = is_tiled ? hmx_ceil_div(n_cols_A0, 32) * n_weight_tiles : n_cols_A0; + dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[0], weight), + dma_dst_stride, dma_src_stride, dma_width_bytes, height_A0); + } if (1 < n_chunk_cnt) { - const size_t n_cols_A1 = hex_smin(n - 1 * n_chunk_n_cols, n_chunk_n_cols); + const size_t n_cols_A1 = hex_smin(n - (size_t) n_chunk_n_cols, (size_t) n_chunk_n_cols); const uint32_t height_A1 = is_tiled ? hmx_ceil_div(n_cols_A1, 32) * n_weight_tiles : n_cols_A1; - dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[1], weight + n_chunk_n_cols * weight_stride), + dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[1], weight + (size_t) n_chunk_n_cols * weight_stride), dma_dst_stride, dma_src_stride, dma_width_bytes, height_A1); } for (int i = 0; i < n_chunk_cnt; ++i) { - const size_t nc = i * n_chunk_n_cols; - const size_t nc_p2 = nc + 2 * n_chunk_n_cols; - - const size_t n_cols = hex_smin(n - nc, n_chunk_n_cols); - const size_t n_cols_p2 = hex_smin(n - nc_p2, n_chunk_n_cols); - - void * curr_raw = (void *) dma_queue_pop(weight_dma).dst; - - dequantize_tiled_weight_chunk_to_fp16_tiles( - ctx, vtcm_weight_bufs[i % 4], curr_raw, - n_cols, k, row_stride, weight_type, - n_k_tiles, n_k_tiles_div, dequant_worker_fn, n_hvx); + const size_t nc = (size_t) i * n_chunk_n_cols; + const size_t n_cols = hex_smin(n - nc, (size_t) n_chunk_n_cols); + + void * curr_raw; + if (i == 0 && p_preissued) { + curr_raw = (void *) dma_proxy_pop(ctx->dma_proxy).dst; + } else { + curr_raw = (void *) dma_queue_pop(weight_dma).dst; + } - if (i + 2 < n_chunk_cnt) { - const uint32_t height_p2 = is_tiled ? hmx_ceil_div(n_cols_p2, 32) * n_weight_tiles : n_cols_p2; - dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[(i + 2) % 4], weight + nc_p2 * weight_stride), - dma_dst_stride, dma_src_stride, dma_width_bytes, height_p2); + if (is_int_hmx) { + rescale_int_weight_chunk_to_int8_tiles( + octx, vtcm_weight_bufs[i % 4], L.weight_bias_offset, L.weight_scales_offset, + curr_raw, (int) n_cols, k, n_groups, &n_groups_div, aligned_tile_size, weight_type); + } else { + dequantize_tiled_weight_chunk_to_fp16_tiles( + octx, vtcm_weight_bufs[i % 4], curr_raw, + n_cols, k, row_stride, weight_type, + n_k_tiles, n_k_tiles_div, dequant_worker_fn); } - hmx_matmul_job_init(&job_slots[i % 2], (__fp16 *) vtcm_output_bufs[i % 2], - (__fp16 *) vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 4], - vtcm_scales, hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS), - hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS), k / HTP_MM_HMX_TILE_N_ROWS); - hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_matmul_worker_fn, &job_slots[i % 2])); + if (i == 0) { + if (is_int_hmx) { + hmx_matmul_task_init_int(&task_slots[0], vtcm_output_bufs[0], + vtcm_f16_act, vtcm_weight_bufs[0], L.weight_bias_offset, + hmx_ceil_div(n_rows, m_tile_rows), + hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS), + (uint32_t) n_k_tiles, (uint32_t) n_groups); + } else { + hmx_matmul_task_init(&task_slots[0], (__fp16 *) vtcm_output_bufs[0], + (__fp16 *) vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[0], + vtcm_scales, hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS), + hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS), (uint32_t) n_k_tiles); + } + hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task_slots[0])); + + if (2 < n_chunk_cnt) { + const size_t nc2 = 2u * (size_t) n_chunk_n_cols; + const size_t n_cols_p2 = hex_smin(n - nc2, (size_t) n_chunk_n_cols); + const uint32_t height_p2 = is_tiled ? hmx_ceil_div(n_cols_p2, 32) * n_weight_tiles : n_cols_p2; + dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[2], weight + nc2 * weight_stride), + dma_dst_stride, dma_src_stride, dma_width_bytes, height_p2); + } + } else { + const int prev = (i - 1) & 1; + const size_t nc_prev = (size_t) (i - 1) * n_chunk_n_cols; + const size_t n_cols_p = hex_smin(n - nc_prev, (size_t) n_chunk_n_cols); - if (i > 0) { hmx_queue_pop(ctx->hmx_queue); - const size_t nc_prev = (i - 1) * n_chunk_n_cols; - const size_t n_cols_prev = hex_smin(n - nc_prev, n_chunk_n_cols); - float *output_chunk = dst_ptr + (mr * dst_stride + nc_prev); - int chunk_dst_cols = dst_cols - (int)nc_prev; + if (is_int_hmx) { + hmx_matmul_task_init_int(&task_slots[i & 1], vtcm_output_bufs[i & 1], + vtcm_f16_act, vtcm_weight_bufs[i % 4], L.weight_bias_offset, + hmx_ceil_div(n_rows, m_tile_rows), + hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS), + (uint32_t) n_k_tiles, (uint32_t) n_groups); + } else { + hmx_matmul_task_init(&task_slots[i & 1], (__fp16 *) vtcm_output_bufs[i & 1], + (__fp16 *) vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 4], + vtcm_scales, hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS), + hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS), (uint32_t) n_k_tiles); + } + hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task_slots[i & 1])); + + const int chunk_dst_cols = dst_cols - (int) nc_prev; if (chunk_dst_cols > 0) { - transfer_output_chunk_threaded(ctx, output_chunk, NULL, vtcm_output_bufs[(i - 1) % 2], n_rows, n_cols_prev, dst_stride, 0, chunk_dst_cols, n_hvx); + if (is_int_hmx) { + const float * wt_scales_prev = (const float *) ((const uint8_t *) vtcm_weight_bufs[(i - 1) % 4] + L.weight_scales_offset); + transfer_output_chunk_int_threaded( + octx, vtcm_res_out[prev], NULL, vtcm_output_bufs[prev], + vtcm_act_scales, wt_scales_prev, (int) n_rows, (int) n_cols_p, + n_groups, res_out_stride_elems, 0, chunk_dst_cols, + dst_elem_size, sizeof(float)); + } else { + transfer_output_chunk_threaded(octx, vtcm_res_out[prev], NULL, vtcm_output_bufs[prev], + n_rows, n_cols_p, res_out_stride_elems, 0, chunk_dst_cols, + dst_elem_size, sizeof(float)); + } + } + + if (i >= 2) { + dma_queue_pop(weight_dma); + } + + const int vcols_o = hex_smin((int) n_cols_p, chunk_dst_cols); + const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0; + dma_queue_push(weight_dma, + dma_make_data(dst_dma_addr + (mr * dst_stride + nc_prev) * dst_elem_size, vtcm_res_out[prev]), + dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0); + + if (i + 2 < n_chunk_cnt) { + const size_t nc_p2 = (size_t) (i + 2) * n_chunk_n_cols; + const size_t n_cols_p2 = hex_smin(n - nc_p2, (size_t) n_chunk_n_cols); + const uint32_t height_p2 = is_tiled ? hmx_ceil_div(n_cols_p2, 32) * n_weight_tiles : n_cols_p2; + dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[(i + 2) % 4], weight + nc_p2 * weight_stride), + dma_dst_stride, dma_src_stride, dma_width_bytes, height_p2); } } } - hmx_queue_pop(ctx->hmx_queue); - const size_t nc_last = (n_chunk_cnt - 1) * n_chunk_n_cols; - const size_t n_cols_last = hex_smin(n - nc_last, n_chunk_n_cols); - float *output_chunk = dst_ptr + (mr * dst_stride + nc_last); - int chunk_dst_cols = dst_cols - (int)nc_last; - if (chunk_dst_cols > 0) { - transfer_output_chunk_threaded(ctx, output_chunk, NULL, vtcm_output_bufs[(n_chunk_cnt - 1) % 2], n_rows, n_cols_last, dst_stride, 0, chunk_dst_cols, n_hvx); + { + const int last = (n_chunk_cnt - 1) & 1; + const size_t nc_last = (size_t) (n_chunk_cnt - 1) * n_chunk_n_cols; + const size_t n_cols_last = hex_smin(n - nc_last, (size_t) n_chunk_n_cols); + + hmx_queue_pop(ctx->hmx_queue); + if (n_chunk_cnt >= 2) { + dma_queue_pop(weight_dma); + } + + const int chunk_dst_cols = dst_cols - (int) nc_last; + if (chunk_dst_cols > 0) { + if (is_int_hmx) { + const float * wt_scales_last = (const float *) ((const uint8_t *) vtcm_weight_bufs[(n_chunk_cnt - 1) % 4] + L.weight_scales_offset); + transfer_output_chunk_int_threaded( + octx, vtcm_res_out[last], NULL, vtcm_output_bufs[last], + vtcm_act_scales, wt_scales_last, (int) n_rows, (int) n_cols_last, + n_groups, res_out_stride_elems, 0, chunk_dst_cols, + dst_elem_size, sizeof(float)); + } else { + transfer_output_chunk_threaded(octx, vtcm_res_out[last], NULL, vtcm_output_bufs[last], + n_rows, n_cols_last, res_out_stride_elems, 0, chunk_dst_cols, + dst_elem_size, sizeof(float)); + } + } + + const int vcols_o = hex_smin((int) n_cols_last, chunk_dst_cols); + const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0; + dma_queue_push(weight_dma, + dma_make_data(dst_dma_addr + (mr * dst_stride + nc_last) * dst_elem_size, vtcm_res_out[last]), + dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0); + dma_queue_pop(weight_dma); } } } } else { - hmx_matmul_job_t job; + hmx_matmul_task_t task; void *vtcm_raw_bufs[2] = { vtcm_weight_raw[0], dequant_worker_fn ? vtcm_weight_raw[0] : vtcm_scratch0 }; void *vtcm_weight_bufs[2] = { dequant_worker_fn ? vtcm_scratch0 : vtcm_weight_raw[0], vtcm_scratch0 }; for (size_t mr = (size_t) m_start; mr < mr_end; mr += m_chunk_n_rows) { const size_t n_rows = hex_smin(mr_end - mr, m_chunk_n_rows); - struct activation_transfer_params act_params = { - .ctx = ctx, - .dst = vtcm_f16_act, - .act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size, - .n_rows = (int) n_rows, - .k_block = k, - .k_stride = act_stride, - .n_hvx = act_hvx, - .act_hvx_div = act_hvx_div, - .k_div = k_div, - .k_valid = k_valid, - .vtcm_f32_act = vtcm_f32_act, - .vtcm_f32_act_bytes = L.act_f32_bytes, - .act_elem_size = act_elem_size, - }; - transfer_activation_chunk_threaded(&act_params); + if (is_int_hmx) { + transfer_activation_chunk_int_threaded( + ctx, (uint8_t *) vtcm_f16_act, vtcm_act_scales, + act_dma_addr + (size_t) mr * act_stride * act_elem_size, + (int) n_rows, k, act_stride, k_valid, n_groups, + act_hvx, act_hvx_div, vtcm_f32_act, L.act_f32_bytes, act_elem_size); + } else { + struct activation_transfer_params act_params = { + .ctx = ctx, + .dst = vtcm_f16_act, + .act_dma_addr = act_dma_addr + (size_t) mr * act_stride * act_elem_size, + .n_rows = (int) n_rows, + .k_block = k, + .k_stride = act_stride, + .n_hvx = act_hvx, + .act_hvx_div = act_hvx_div, + .k_div = k_div, + .k_valid = k_valid, + .vtcm_f32_act = vtcm_f32_act, + .vtcm_f32_act_bytes = L.act_f32_bytes, + .act_elem_size = act_elem_size, + }; + transfer_activation_chunk_threaded(&act_params); + } for (uint32_t p = 0; p < n_weights; p++) { const struct htp_tensor * restrict src_w = octx->src[p]; @@ -3169,52 +5195,88 @@ static int hmx_mm_nx_2d_f32(struct htp_ops_context * octx, const struct htp_mm_k if (!src_w || !dst) continue; const dma_addr_t weight = src_w->data; - dma_queue * weight_dma = octx->ctx->dma[0]; - float * dst_ptr = (float *) dst->data; - const size_t n = src_w->ne[1]; + dma_queue * weight_dma = octx->ctx->dma[0]; + const dma_addr_t dst_dma_addr = dst->data; + const size_t n = src_w->ne[1]; if (n == 0) continue; - const size_t weight_stride = src_w->nb[1]; - const size_t dst_stride = dst->nb[1] / sizeof(float); - const int dst_cols = (int) dst->ne[0]; - const int n_chunk_cnt = hmx_ceil_div(n, n_chunk_n_cols); + const size_t weight_stride = src_w->nb[1]; + const size_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const size_t dst_stride = dst->nb[1] / dst_elem_size; + const size_t dst_row_bytes = dst->nb[1]; + const size_t res_out_stride_bytes = hex_align_up((size_t) n_chunk_n_cols * dst_elem_size, 128); + const int res_out_stride_elems = (int) (res_out_stride_bytes / dst_elem_size); + const int dst_cols = (int) dst->ne[0]; + const int n_chunk_cnt = hmx_ceil_div(n, n_chunk_n_cols); const uint32_t dma_src_stride = is_tiled ? tile_size : weight_stride; if (n > 0) { - const size_t n_cols = hex_smin(n, n_chunk_n_cols); + const size_t n_cols = hex_smin(n, (size_t) n_chunk_n_cols); const uint32_t height = is_tiled ? hmx_ceil_div(n_cols, 32) * n_weight_tiles : n_cols; dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[0], weight), dma_dst_stride, dma_src_stride, dma_width_bytes, height); } for (int i = 0; i < n_chunk_cnt; ++i) { const size_t nc = (size_t) i * n_chunk_n_cols; - const size_t n_cols = hex_smin(n - nc, n_chunk_n_cols); - const size_t n_row_tiles = hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS); + const size_t n_cols = hex_smin(n - nc, (size_t) n_chunk_n_cols); + const size_t n_row_tiles = hmx_ceil_div(n_rows, m_tile_rows); const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS); void * curr_raw = (void *) dma_queue_pop(weight_dma).dst; + if (i > 0) { + dma_queue_pop(weight_dma); + } - dequantize_tiled_weight_chunk_to_fp16_tiles( - ctx, vtcm_weight_bufs[i % 2], curr_raw, - n_cols, k, row_stride, weight_type, - n_k_tiles, n_k_tiles_div, dequant_worker_fn, n_hvx); + if (is_int_hmx) { + rescale_int_weight_chunk_to_int8_tiles( + octx, vtcm_weight_bufs[i % 2], L.weight_bias_offset, L.weight_scales_offset, + curr_raw, (int) n_cols, k, n_groups, &n_groups_div, aligned_tile_size, weight_type); + } else { + dequantize_tiled_weight_chunk_to_fp16_tiles( + octx, vtcm_weight_bufs[i % 2], curr_raw, + n_cols, k, row_stride, weight_type, + n_k_tiles, n_k_tiles_div, dequant_worker_fn); + } - const size_t nc_next = nc + n_chunk_n_cols; + const size_t nc_next = nc + (size_t) n_chunk_n_cols; if (nc_next < n) { - const size_t n_cols_next = hex_smin(n - nc_next, n_chunk_n_cols); + const size_t n_cols_next = hex_smin(n - nc_next, (size_t) n_chunk_n_cols); const uint32_t height_next = is_tiled ? hmx_ceil_div(n_cols_next, 32) * n_weight_tiles : n_cols_next; dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[(i + 1) % 2], weight + nc_next * weight_stride), dma_dst_stride, dma_src_stride, dma_width_bytes, height_next); } - hmx_matmul_job_init(&job, vtcm_output, vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 2], vtcm_scales, n_row_tiles, n_col_tiles, k / HTP_MM_HMX_TILE_N_ROWS); - hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_matmul_worker_fn, &job)); + if (is_int_hmx) { + hmx_matmul_task_init_int(&task, vtcm_output, vtcm_f16_act, vtcm_weight_bufs[i % 2], L.weight_bias_offset, + n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles, (uint32_t) n_groups); + } else { + hmx_matmul_task_init(&task, vtcm_output, vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 2], vtcm_scales, n_row_tiles, n_col_tiles, (uint32_t) n_k_tiles); + } + hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_worker_fn, &task)); hmx_queue_pop(ctx->hmx_queue); - float *output_chunk = dst_ptr + (mr * dst_stride + nc); - int chunk_dst_cols = dst_cols - (int)nc; + int chunk_dst_cols = dst_cols - (int) nc; if (chunk_dst_cols > 0) { - transfer_output_chunk_threaded(ctx, output_chunk, NULL, vtcm_output, n_rows, n_cols, dst_stride, 0, chunk_dst_cols, n_hvx); + if (is_int_hmx) { + const float * wt_scales = (const float *) ((const uint8_t *) vtcm_weight_bufs[i % 2] + L.weight_scales_offset); + transfer_output_chunk_int_threaded( + octx, vtcm_res_out[0], NULL, vtcm_output, + vtcm_act_scales, wt_scales, (int) n_rows, (int) n_cols, + n_groups, res_out_stride_elems, 0, chunk_dst_cols, + dst_elem_size, sizeof(float)); + } else { + transfer_output_chunk_threaded(octx, vtcm_res_out[0], NULL, vtcm_output, + n_rows, n_cols, res_out_stride_elems, 0, chunk_dst_cols, + dst_elem_size, sizeof(float)); + } } + const int vcols_o = hex_smin((int) n_cols, chunk_dst_cols); + const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * dst_elem_size : 0; + dma_queue_push(weight_dma, + dma_make_data(dst_dma_addr + (mr * dst_stride + nc) * dst_elem_size, vtcm_res_out[0]), + dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0); + } + if (n_chunk_cnt > 0) { + dma_queue_pop(weight_dma); } } } @@ -3236,16 +5298,16 @@ static inline dma_addr_t hmx_mm_act_batch_addr(const hmx_mm_batched_params_t *pa dst_b3 * params->act_nb3; } -static inline float *hmx_mm_dst_batch_ptr(const hmx_mm_batched_params_t *params, - int dst_b2, int dst_b3) { - return (float *) ((uint8_t *) params->dst + - (size_t) dst_b2 * params->dst_nb2 + - (size_t) dst_b3 * params->dst_nb3); +static inline dma_addr_t hmx_mm_dst_batch_addr(const hmx_mm_batched_params_t *params, + int dst_b2, int dst_b3) { + return params->dst_dma_addr + + (size_t) dst_b2 * params->dst_nb2 + + (size_t) dst_b3 * params->dst_nb3; } -static int hmx_mm_batched_simple(struct htp_context *ctx, +static int hmx_mm_batched_simple(struct htp_ops_context *octx, const hmx_mm_batched_params_t *params, - int m_chunk, int n_chunk, int pipeline, int n_hvx, int act_hvx, int vtcm_size, + int m_chunk, int n_chunk, int pipeline, int act_hvx, int vtcm_size, const struct fastdiv_values * act_hvx_div, const struct fastdiv_values * k_div) { int ret = 0; for (int b3 = 0; b3 < params->ne13 && ret == 0; ++b3) { @@ -3253,25 +5315,29 @@ static int hmx_mm_batched_simple(struct htp_context *ctx, dma_addr_t cur_bias_addr = params->bias_addr ? (params->bias_addr + b2 * params->bias_nb2 + b3 * params->bias_nb3) : 0; - ret = hmx_mm_2d_f32(ctx, params->weight_dma, hmx_mm_dst_batch_ptr(params, b2, b3), + ret = hmx_mm_2d_f32(octx, params->weight_dma, hmx_mm_dst_batch_addr(params, b2, b3), cur_bias_addr, params->bias_bytes, hmx_mm_act_batch_addr(params, b2, b3), hmx_mm_weight_batch_data(params, b2, b3), params->m, params->k, params->n, params->act_stride, params->act_elem_size, params->weight_stride, params->weight_type, params->k, params->dst_stride, params->bias_stride, params->dst_cols, - m_chunk, n_chunk, pipeline, n_hvx, act_hvx, - act_hvx_div, k_div, params->tile_size, params->aligned_tile_size, vtcm_size); + params->dst_elem_size, params->bias_elem_size, + m_chunk, n_chunk, pipeline, act_hvx, + act_hvx_div, k_div, params->tile_size, params->aligned_tile_size, vtcm_size, + params->kernel_type, params->hmx_n_groups, + ¶ms->div_hmx_n_groups, ¶ms->div_n_k_tiles); } } return ret; } -static int hmx_mm_batched(struct htp_context *ctx, const hmx_mm_batched_params_t *params, - int m_chunk, int n_chunk, int pipeline, int n_hvx, int act_hvx, +static int hmx_mm_batched(struct htp_ops_context *octx, const hmx_mm_batched_params_t *params, + int m_chunk, int n_chunk, int pipeline, int act_hvx, const struct fastdiv_values * act_hvx_div, const struct fastdiv_values * k_div, int vtcm_size) { + struct htp_context * ctx = octx->ctx; const size_t row_stride = htp_tensor_get_row_size(params->weight_type, params->k); if (row_stride == 0) { return -1; } if (params->act_stride < params->k || (params->tile_size == 0 && (size_t) params->weight_stride < row_stride) || params->dst_stride < params->dst_cols) { return -1; } @@ -3279,7 +5345,7 @@ static int hmx_mm_batched(struct htp_context *ctx, const hmx_mm_batched_params_t if (params->ne12 % params->ne02 != 0 || params->ne13 % params->ne03 != 0) { return -1; } // N (the weight row count) does not have to be 32-aligned: if (params->k % 32 != 0) { return -1; } - if (!hex_is_aligned(params->dst, sizeof(float))) { return -1; } + if ((params->dst_dma_addr & (params->dst_elem_size - 1)) != 0) { return -1; } const int group_size = params->r2; const size_t vtcm_budget = ctx->vtcm_size; @@ -3287,9 +5353,10 @@ static int hmx_mm_batched(struct htp_context *ctx, const hmx_mm_batched_params_t // Check if the precomputed parameters are grouped or simple. // If simple, or if group_size <= 1, we use simple fallback loop. // Grouped path is only valid for flat F16 if group_size > 1 and it fits within VTCM budget. - bool run_grouped = (params->weight_type == HTP_TYPE_F16 && params->tile_size == 0 && group_size > 1 && (size_t)vtcm_size <= vtcm_budget); + bool run_grouped = (params->weight_type == HTP_TYPE_F16 && params->tile_size == 0 && group_size > 1 && + params->bias_nb2 == 0 && params->bias_nb3 == 0 && (size_t)vtcm_size <= vtcm_budget); if (!run_grouped) { - return hmx_mm_batched_simple(ctx, params, m_chunk, n_chunk, pipeline, n_hvx, act_hvx, vtcm_size, act_hvx_div, k_div); + return hmx_mm_batched_simple(octx, params, m_chunk, n_chunk, pipeline, act_hvx, vtcm_size, act_hvx_div, k_div); } struct htp_thread_trace * tr = &ctx->trace[0]; @@ -3299,12 +5366,12 @@ static int hmx_mm_batched(struct htp_context *ctx, const hmx_mm_batched_params_t size_t n_chunk_n_cols = n_chunk; struct htp_mm_hmx_vtcm_layout L; - htp_mm_hmx_vtcm_layout_build(&L, HTP_MM_KERNEL_HMX_BATCHED, HTP_TYPE_F16, params->k, m_chunk_n_rows, n_chunk_n_cols, group_size, false, act_hvx, 0, params->bias_bytes); + htp_mm_hmx_vtcm_layout_build_ex(&L, HTP_MM_KERNEL_HMX_BATCHED, HTP_TYPE_F16, params->k, m_chunk_n_rows, n_chunk_n_cols, group_size, false, act_hvx, 0, params->bias_bytes, 0, params->dst_elem_size); if (L.total_bytes > vtcm_budget) { FARF(HIGH, "%s: grouped layout overflowed VTCM, falling back to simple batched loop", __func__); htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0); - return hmx_mm_batched_simple(ctx, params, m_chunk, n_chunk, pipeline, n_hvx, act_hvx, vtcm_size, act_hvx_div, k_div); + return hmx_mm_batched_simple(octx, params, m_chunk, n_chunk, pipeline, act_hvx, vtcm_size, act_hvx_div, k_div); } uint8_t * const base = (uint8_t *) ctx->vtcm_base; @@ -3313,11 +5380,12 @@ static int hmx_mm_batched(struct htp_context *ctx, const hmx_mm_batched_params_t __fp16 *vtcm_output = VTCM_LAYOUT_PTR(__fp16, base, L.off_dst[0]); void *vtcm_scratch0 = VTCM_LAYOUT_PTR(void, base, L.off_scratch[0]); void *vtcm_scratch1 = VTCM_LAYOUT_PTR(void, base, L.off_scratch[1]); + void *vtcm_res_out = VTCM_LAYOUT_PTR(void, base, L.off_res_out[0]); __fp16 *vtcm_scales = VTCM_LAYOUT_PTR(__fp16, base, L.off_scales); float *vtcm_f32_act = VTCM_LAYOUT_PTR(float, base, L.off_act_f32); const bool has_bias = (params->bias_bytes > 0 && params->bias_addr != 0); - float *vtcm_bias = VTCM_LAYOUT_PTR_OPTIONAL(float, base, L.off_bias, has_bias); + void *vtcm_bias = VTCM_LAYOUT_PTR_OPTIONAL(void, base, L.off_bias, has_bias); if (has_bias) { dma_queue_push(params->weight_dma, dma_make_data(vtcm_bias, params->bias_addr), hex_align_up(params->bias_bytes, 128), 0, params->bias_bytes, 1); dma_queue_pop(params->weight_dma); @@ -3335,7 +5403,7 @@ static int hmx_mm_batched(struct htp_context *ctx, const hmx_mm_batched_params_t htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0); - hmx_matmul_job_t job; + hmx_matmul_task_t task; for (int b3 = 0; b3 < params->ne13; ++b3) { for (int b2_base = 0; b2_base < params->ne12; b2_base += group_size) { @@ -3373,60 +5441,66 @@ static int hmx_mm_batched(struct htp_context *ctx, const hmx_mm_batched_params_t transfer_activation_chunk_threaded(&act_params); } - // Prologue: Push A0 and A1 (if exists) - { + const size_t dst_row_bytes = (size_t) params->dst_stride * params->dst_elem_size; + const size_t res_out_stride_bytes = hex_align_up(n_chunk_n_cols * params->dst_elem_size, 128); + const int res_out_stride_elems = (int) (res_out_stride_bytes / params->dst_elem_size); + + // Prologue: push first weight chunk + if (params->n > 0) { const size_t n_cols_first = hex_smin((size_t) params->n, n_chunk_n_cols); dma_queue_push(weight_dma, dma_make_data(vtcm_scratch0, weight_group), - fp16_row_bytes, weight_row_bytes, fp16_row_bytes, n_cols_first); - } - if (n_chunk_n_cols < (size_t) params->n) { - const size_t n_cols_second = hex_smin((size_t) params->n - n_chunk_n_cols, n_chunk_n_cols); - const dma_addr_t second_weight_chunk = weight_group + n_chunk_n_cols * weight_row_bytes; - dma_queue_push(weight_dma, dma_make_data(vtcm_scratch1, second_weight_chunk), - fp16_row_bytes, weight_row_bytes, fp16_row_bytes, n_cols_second); + fp16_row_bytes, weight_row_bytes, fp16_row_bytes, n_cols_first); } for (size_t nc = 0; nc < (size_t) params->n; nc += n_chunk_n_cols) { const size_t n_cols = hex_smin((size_t) params->n - nc, n_chunk_n_cols); const size_t n_col_tiles = hmx_ceil_div((int) n_cols, HTP_MM_HMX_TILE_N_COLS); - { - void * curr_raw = (void *) dma_queue_pop(weight_dma).dst; - - const size_t n_cols_tiled = hex_align_up(n_cols, HTP_MM_HMX_TILE_N_COLS); + void * curr_raw = (void *) dma_queue_pop(weight_dma).dst; + if (nc > 0) { + dma_queue_pop(weight_dma); + } - hmx_interleave_rows_to_tiles(vtcm_weight, (const __fp16 *) curr_raw, (uint32_t) n_cols, params->k, params->k, 0, (uint32_t) n_cols_tiled); + const size_t n_cols_tiled = hex_align_up(n_cols, HTP_MM_HMX_TILE_N_COLS); + hmx_interleave_rows_to_tiles(vtcm_weight, (const __fp16 *) curr_raw, (uint32_t) n_cols, params->k, params->k, 0, (uint32_t) n_cols_tiled); - const size_t nc_next = nc + n_chunk_n_cols * 2; - if (nc_next < (size_t) params->n) { + // Reuse the interleaved weight for every q_head in this GQA group. + // Push next weight chunk right before the last head so earlier heads can + // sync-DMA their outputs on an empty queue, and the last head overlaps with next weight. + const size_t nc_next = nc + n_chunk_n_cols; + for (int g = 0; g < group_size; ++g) { + if (g == group_size - 1 && nc_next < (size_t) params->n) { const size_t n_cols_next = hex_smin((size_t) params->n - nc_next, n_chunk_n_cols); - const dma_addr_t next_weight_chunk = weight_group + nc_next * weight_row_bytes; - - dma_queue_push(weight_dma, dma_make_data(curr_raw, next_weight_chunk), - fp16_row_bytes, weight_row_bytes, fp16_row_bytes, n_cols_next); + void * next_raw = (curr_raw == vtcm_scratch0) ? vtcm_scratch1 : vtcm_scratch0; + dma_queue_push(weight_dma, dma_make_data(next_raw, weight_group + nc_next * weight_row_bytes), + fp16_row_bytes, weight_row_bytes, fp16_row_bytes, n_cols_next); } - } - // Reuse the interleaved weight for every q_head in this GQA group - for (int g = 0; g < group_size; ++g) { - { - const __fp16 * vtcm_act_g = vtcm_f16_act + (size_t) g * L.act_head_stride; - hmx_matmul_job_init(&job, vtcm_output, vtcm_act_g, vtcm_weight, vtcm_scales, n_row_tiles, n_col_tiles, params->k / 32); - hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_matmul_worker_fn, &job)); - hmx_queue_pop(ctx->hmx_queue); - } + const __fp16 * vtcm_act_g = vtcm_f16_act + (size_t) g * L.act_head_stride; + hmx_matmul_task_init(&task, vtcm_output, vtcm_act_g, vtcm_weight, vtcm_scales, n_row_tiles, n_col_tiles, params->k / 32); + hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_matmul_fp16_worker_fn, &task)); + hmx_queue_pop(ctx->hmx_queue); - { - float *output = hmx_mm_dst_batch_ptr(params, b2_base + g, b3) + mr * params->dst_stride + nc; - const float *bias_chunk = has_bias ? (vtcm_bias + mr * params->bias_stride + nc) : NULL; - int chunk_dst_cols = params->dst_cols - (int)nc; - if (chunk_dst_cols > 0) { - transfer_output_chunk_threaded(ctx, output, bias_chunk, vtcm_output, (int) n_rows, (int) n_cols, - params->dst_stride, params->bias_stride, chunk_dst_cols, n_hvx); - } + const void * bias_chunk = has_bias ? ((const uint8_t *) vtcm_bias + (mr * params->bias_stride + nc) * params->bias_elem_size) : NULL; + const int chunk_dst_cols = params->dst_cols - (int) nc; + if (chunk_dst_cols > 0) { + transfer_output_chunk_threaded(octx, vtcm_res_out, bias_chunk, vtcm_output, (int) n_rows, (int) n_cols, + res_out_stride_elems, params->bias_stride, chunk_dst_cols, + params->dst_elem_size, params->bias_elem_size); + } + const int vcols_o = hex_smin((int) n_cols, chunk_dst_cols); + const size_t cbytes = (vcols_o > 0) ? (size_t) vcols_o * params->dst_elem_size : 0; + const dma_addr_t out_addr = hmx_mm_dst_batch_addr(params, b2_base + g, b3) + (mr * params->dst_stride + nc) * params->dst_elem_size; + dma_queue_push(weight_dma, dma_make_data(out_addr, vtcm_res_out), + dst_row_bytes, res_out_stride_bytes, cbytes, cbytes ? n_rows : 0); + if (g < group_size - 1) { + dma_queue_pop(weight_dma); } } } + if (params->n > 0) { + dma_queue_pop(weight_dma); + } } } } @@ -3435,9 +5509,10 @@ static int hmx_mm_batched(struct htp_context *ctx, const hmx_mm_batched_params_t } static void transfer_activation_chunk_gathered_threaded( - struct htp_context *ctx, + struct htp_ops_context *octx, __fp16 *dst, - const float *src, + dma_addr_t act_dma_addr, + size_t act_elem_size, int start_row, int n_rows, int k_block, @@ -3447,83 +5522,250 @@ static void transfer_activation_chunk_gathered_threaded( int ne11, size_t nb11, size_t nb12, - int cne1, + int k_valid, int n_hvx, - int k_valid) { - if (n_rows <= 0) return; - int chunks_per_hvx = hmx_ceil_div(n_rows, n_hvx); - chunks_per_hvx = hex_align_up(chunks_per_hvx, 2); + const struct fastdiv_values * act_hvx_div, + float * vtcm_f32_act, + size_t vtcm_f32_act_bytes) { + if (n_rows <= 0) { + return; + } + const uint32_t mc_pad = hex_align_up((uint32_t) n_rows, HTP_MM_HMX_TILE_N_ROWS); + uint32_t chunks_per_hvx = (n_hvx <= 1) ? mc_pad + : fastdiv(mc_pad + (uint32_t) n_hvx - 1u, act_hvx_div); + chunks_per_hvx = hex_align_up(chunks_per_hvx, 2u); - int actual_hvx = hmx_ceil_div(n_rows, chunks_per_hvx); + const int actual_hvx = (int) hmx_ceil_div(mc_pad, chunks_per_hvx); activation_transfer_gathered_task_state_t state = { - .dst = dst, - .src = src, - .n_tasks = actual_hvx, - .n_tot_chunks = n_rows, - .n_chunks_per_task = chunks_per_hvx, - .k_block = k_block, - .matrix_rows = matrix_rows, - .cur_a = cur_a, - .mapping_stride = mapping_stride, - .ne11 = ne11, - .ne11_div = ne11 > 1 ? init_fastdiv_values(ne11) : (struct fastdiv_values){0, 0}, - .nb11 = nb11, - .nb12 = nb12, - .start_row = start_row, - .cne1 = cne1, - .k_valid = k_valid, + .dst = dst, + .act_dma_addr = act_dma_addr, + .vtcm_f32_act = vtcm_f32_act, + .vtcm_f32_act_bytes_per_hvx = hex_align_down(fastdiv(vtcm_f32_act_bytes, act_hvx_div), 128), + .act_elem_size = act_elem_size, + .n_rows = (uint32_t) n_rows, + .mc_pad = mc_pad, + .n_chunks_per_task = chunks_per_hvx, + .k_block = (uint32_t) k_block, + .matrix_rows = matrix_rows, + .cur_a = (uint32_t) cur_a, + .mapping_stride = (uint32_t) mapping_stride, + .ne11 = (uint32_t) ne11, + .ne11_div = ne11 > 1 ? init_fastdiv_values(ne11) : (struct fastdiv_values){0, 0}, + .nb11 = nb11, + .nb12 = nb12, + .start_row = (uint32_t) start_row, + .k_valid = (uint32_t) k_valid, }; - work_queue_func_t worker_fn = ne11 == 1 ? transfer_activation_chunk_gathered_worker_flat_fn : - transfer_activation_chunk_gathered_worker_fn; - - work_queue_run(ctx->hvx_queue, worker_fn, &state, actual_hvx); + work_queue_run(octx->ctx->hvx_queue, transfer_activation_chunk_gathered_worker_fn, &state, actual_hvx); } -static void transfer_output_chunk_scattered_threaded( - struct htp_context *ctx, - float *dst, - const __fp16 *vtcm_src, - int start_row, - int n_rows, - int n_cols, - const struct mmid_row_mapping *matrix_rows, - int cur_a, - int mapping_stride, - size_t dst_nb1, - size_t dst_nb2, - int cne1, - int n_hvx) { - if (n_rows <= 0) return; - int chunks_per_hvx = hmx_ceil_div(n_rows, n_hvx); - chunks_per_hvx = hex_align_up(chunks_per_hvx, 2); - - int actual_hvx = hmx_ceil_div(n_rows, chunks_per_hvx); - - output_transfer_scattered_task_state_t state = { - .vtcm_src = vtcm_src, - .dst = dst, - .n_tasks = actual_hvx, - .n_tot_chunks = n_rows, - .n_chunks_per_task = chunks_per_hvx, - .n_cols = n_cols, - .matrix_rows = matrix_rows, - .cur_a = cur_a, - .mapping_stride = mapping_stride, - .dst_nb1 = dst_nb1, - .dst_nb2 = dst_nb2, - .start_row = start_row, - .cne1 = cne1, - }; +static __attribute__((noinline)) int hmx_mm_id_2d_int( + struct htp_ops_context * octx, + dma_queue * weight_dma, + const dma_addr_t * dsts, + dma_addr_t activation, + size_t act_elem_size, + size_t dst_elem_size, + const dma_addr_t * weights, + uint32_t n_weights, + int m, int k, int n, + int k_valid, + int ne11, + size_t act_nb1, size_t act_nb2, + size_t dst_nb1, size_t dst_nb2, + int weight_stride, + int weight_type, + int tile_size, + int aligned_tile_size, + const struct mmid_row_mapping * matrix_rows, + int cur_a, + int mapping_stride, + int m_start, + int m_end, + int32_t kernel_type) { + struct htp_context * ctx = octx->ctx; + struct htp_thread_trace * tr = &ctx->trace[0]; + htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0); + + const int mr_limit = hex_smin(m, m_end); + const int m_valid_core = mr_limit - m_start; + if (m_valid_core <= 0 || n_weights == 0) { + htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0); + return 0; + } + + const int m_core_padded = hex_align_up(m_valid_core, 64); + + if (k % 32 != 0 || n % 32 != 0 || tile_size <= 0) { return -1; } + if ((activation & (act_elem_size - 1)) != 0) { return -1; } + for (uint32_t p = 0; p < n_weights; ++p) { + if ((dsts[p] & (dst_elem_size - 1)) != 0) { return -1; } + } + + size_t row_stride = htp_tensor_get_row_size(weight_type, k); + if (row_stride == 0) { + return -1; + } + + const uint32_t n_groups = ((uint32_t) k + HTP_MM_HMX_W8A8_KGROUP - 1u) / HTP_MM_HMX_W8A8_KGROUP; + const uint32_t n_k_tiles = (uint32_t) k / HTP_MM_HMX_TILE_N_COLS; + const uint32_t n_weight_tiles = (uint32_t) k / htp_tensor_get_tile_k(weight_type); + const struct fastdiv_values n_groups_div = init_fastdiv_values(n_groups); + + const size_t vtcm_budget = ctx->vtcm_size; + size_t m_chunk_n_rows = 0, n_chunk_n_cols = 0, vtcm_used = 0; + int act_hvx = 0; + if (!htp_mm_int_hmx_solve_2d_params( + kernel_type, weight_type, (uint32_t) k, (uint32_t) m_core_padded, + (uint32_t) n, (uint32_t) m_core_padded, (uint32_t) m_core_padded, + (int) octx->n_hvx, /*pipeline=*/false, /*is_matmul_id=*/true, + (uint32_t) aligned_tile_size, /*bias_size=*/0, dst_elem_size, vtcm_budget, + &m_chunk_n_rows, &n_chunk_n_cols, &act_hvx, &vtcm_used)) { + FARF(ERROR, "hmx-mm-id-2d-int: VTCM too small: m %d k %d n %d budget %zu", m_core_padded, k, n, vtcm_budget); + return -1; + } + + struct htp_mm_hmx_vtcm_layout L; + htp_mm_hmx_vtcm_layout_build_ex( + &L, kernel_type, weight_type, (uint32_t) k, + m_chunk_n_rows, n_chunk_n_cols, 1, /*pipeline=*/false, + (uint32_t) act_hvx, (uint32_t) aligned_tile_size, 0, 0, dst_elem_size); + if (L.total_bytes > vtcm_budget) { + FARF(ERROR, "hmx-mm-id-2d-int: VTCM overflow: used %zu budget %zu", L.total_bytes, vtcm_budget); + return -1; + } + + uint8_t * const base = (uint8_t *) ctx->vtcm_base; + void * vtcm_weight = VTCM_LAYOUT_PTR(void, base, L.off_weight[0]); + uint8_t * vtcm_act = VTCM_LAYOUT_PTR(uint8_t, base, L.off_act); + float * vtcm_act_scales = VTCM_LAYOUT_PTR(float, base, L.off_act_scales); + float * vtcm_f32_act = VTCM_LAYOUT_PTR(float, base, L.off_act_f32); + void * vtcm_output = VTCM_LAYOUT_PTR(void, base, L.off_dst[0]); + void * vtcm_scratch0 = VTCM_LAYOUT_PTR(void, base, L.off_scratch[0]); + uint8_t * vtcm_res_out = VTCM_LAYOUT_PTR(uint8_t, base, L.off_res_out[0]); + if (L.lut_bytes > 0) { + iq2xxs_lut_copy(base + L.off_lut); + } + + htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0); + + const struct fastdiv_values act_hvx_div = init_fastdiv_values((uint32_t) act_hvx); + const int n_chunk_cnt = hmx_ceil_div(n, n_chunk_n_cols); + const size_t res_out_stride_bytes = hex_align_up(n_chunk_n_cols * dst_elem_size, 128); + const int res_out_stride_elems = (int) (res_out_stride_bytes / dst_elem_size); + hmx_matmul_task_t task; + + const bool preissue_p0 = L.can_preissue_weight && n > 0 && n_weights > 0; + + for (size_t mr = (size_t) m_start; mr < (size_t) mr_limit; mr += m_chunk_n_rows) { + const size_t n_rows = hex_smin((size_t) mr_limit - mr, m_chunk_n_rows); + const size_t n_row_tiles = hmx_ceil_div(n_rows, 64u); + const bool overlap_w_next = (n_rows <= 200u); + + if (preissue_p0) { + const size_t n_cols0 = hex_smin((size_t) n, n_chunk_n_cols); + const uint32_t height0 = hmx_ceil_div(n_cols0, 32) * n_weight_tiles; + dma_proxy_push(ctx->dma_proxy, dma_make_data(vtcm_weight, weights[0]), + aligned_tile_size, tile_size, tile_size, height0); + } + + transfer_activation_chunk_int_gathered_threaded( + ctx, vtcm_act, vtcm_act_scales, activation, (uint32_t) act_elem_size, + (int) mr, (int) n_rows, k, k_valid, (int) n_groups, + matrix_rows, cur_a, mapping_stride, ne11, act_nb1, act_nb2, + act_hvx, &act_hvx_div, vtcm_f32_act, L.act_f32_bytes); - work_queue_run(ctx->hvx_queue, transfer_output_chunk_scattered_worker_fn, &state, actual_hvx); + for (uint32_t p = 0; p < n_weights; ++p) { + const dma_addr_t weight_p = weights[p]; + const dma_addr_t dst_p = dsts[p]; + const bool p_preissued = (p == 0 && preissue_p0); + + if (n > 0 && !p_preissued) { + const size_t n_cols = hex_smin((size_t) n, n_chunk_n_cols); + const uint32_t height = hmx_ceil_div(n_cols, 32) * n_weight_tiles; + dma_queue_push(weight_dma, dma_make_data(vtcm_weight, weight_p), + aligned_tile_size, tile_size, tile_size, height); + } + + for (int i = 0; i < n_chunk_cnt; ++i) { + const size_t nc = (size_t) i * n_chunk_n_cols; + const size_t n_cols = hex_smin((size_t) n - nc, n_chunk_n_cols); + const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS); + + void * curr_raw; + if (i == 0 && p_preissued) { + curr_raw = (void *) dma_proxy_pop(ctx->dma_proxy).dst; + } else { + curr_raw = (void *) dma_queue_pop(weight_dma).dst; + } + if (overlap_w_next && i > 0) { + for (size_t s = 0; s < n_rows; ++s) { + dma_queue_pop(weight_dma); + } + } + + rescale_int_weight_chunk_to_int8_tiles( + octx, vtcm_scratch0, L.weight_bias_offset, L.weight_scales_offset, + curr_raw, (int) n_cols, k, (int) n_groups, &n_groups_div, + aligned_tile_size, weight_type); + + const size_t nc_next = nc + n_chunk_n_cols; + if (overlap_w_next && nc_next < (size_t) n) { + const size_t n_cols_next = hex_smin((size_t) n - nc_next, n_chunk_n_cols); + const uint32_t height_next = hmx_ceil_div(n_cols_next, 32) * n_weight_tiles; + dma_queue_push(weight_dma, dma_make_data(vtcm_weight, weight_p + nc_next * weight_stride), + aligned_tile_size, tile_size, tile_size, height_next); + } + + hmx_matmul_task_init_int(&task, vtcm_output, vtcm_act, vtcm_scratch0, L.weight_bias_offset, + n_row_tiles, n_col_tiles, n_k_tiles, n_groups); + hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_matmul_w8a8_worker_fn, &task)); + hmx_queue_pop(ctx->hmx_queue); + + const float * wt_scales = (const float *) ((const uint8_t *) vtcm_scratch0 + L.weight_scales_offset); + transfer_output_chunk_int_threaded( + octx, vtcm_res_out, NULL, vtcm_output, + vtcm_act_scales, wt_scales, (int) n_rows, (int) n_cols, + (int) n_groups, res_out_stride_elems, 0, (int) n_cols, + dst_elem_size, sizeof(float)); + + if (overlap_w_next) { + push_scattered_dst_rows_dma( + weight_dma, dst_p + nc * dst_elem_size, vtcm_res_out, + (uint32_t) mr, (uint32_t) n_rows, res_out_stride_bytes, n_cols * dst_elem_size, + matrix_rows, (uint32_t) cur_a, (uint32_t) mapping_stride, dst_nb1, dst_nb2); + } else { + sync_scattered_dst_rows_dma( + weight_dma, dst_p + nc * dst_elem_size, vtcm_res_out, + (uint32_t) mr, (uint32_t) n_rows, res_out_stride_bytes, n_cols * dst_elem_size, + matrix_rows, (uint32_t) cur_a, (uint32_t) mapping_stride, dst_nb1, dst_nb2); + if (nc_next < (size_t) n) { + const size_t n_cols_next = hex_smin((size_t) n - nc_next, n_chunk_n_cols); + const uint32_t height_next = hmx_ceil_div(n_cols_next, 32) * n_weight_tiles; + dma_queue_push(weight_dma, dma_make_data(vtcm_weight, weight_p + nc_next * weight_stride), + aligned_tile_size, tile_size, tile_size, height_next); + } + } + } + if (overlap_w_next && n_chunk_cnt > 0) { + for (size_t s = 0; s < n_rows; ++s) { + dma_queue_pop(weight_dma); + } + } + } + } + + return 0; } -static int hmx_mm_id_2d_f32(struct htp_context *ctx, +static int hmx_mm_id_2d_f32(struct htp_ops_context *octx, dma_queue *weight_dma, - float *restrict dst, - const float *activation, + dma_addr_t dst, + dma_addr_t activation, + size_t act_elem_size, + size_t dst_elem_size, dma_addr_t weight, int m, int k, int n, int k_valid, @@ -3539,16 +5781,32 @@ static int hmx_mm_id_2d_f32(struct htp_context *ctx, int mapping_stride, int m_start, int m_end, - int n_hvx) { + int32_t kernel_type) { + if (htp_mm_kernel_is_hmx_int(kernel_type)) { + const dma_addr_t dsts[1] = { dst }; + const dma_addr_t weights[1] = { weight }; + return hmx_mm_id_2d_int( + octx, weight_dma, dsts, activation, act_elem_size, dst_elem_size, + weights, 1, m, k, n, k_valid, ne11, act_nb1, act_nb2, dst_nb1, dst_nb2, + weight_stride, weight_type, tile_size, aligned_tile_size, + matrix_rows, cur_a, mapping_stride, m_start, m_end, + kernel_type); + } + struct htp_context * ctx = octx->ctx; struct htp_thread_trace * tr = &ctx->trace[0]; htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0); - const int cne1 = m; - const int m_core = m_end - m_start; - const int m_core_padded = hex_align_up(m_core > 0 ? m_core : 1, 32); + const int mr_limit = hex_smin(m, m_end); + const int m_valid_core = mr_limit - m_start; + if (m_valid_core <= 0) { + htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0); + return 0; + } + + const int m_core_padded = hex_align_up(m_valid_core, HTP_MM_HMX_TILE_N_ROWS); if (k % 32 != 0 || n % 32 != 0) { return -1; } - if (!hex_is_aligned(dst, VLEN) || !hex_is_aligned(activation, VLEN)) { return -1; } + if ((dst & (dst_elem_size - 1)) != 0 || (activation & (act_elem_size - 1)) != 0) { return -1; } size_t row_stride = htp_tensor_get_row_size(weight_type, k); if (row_stride == 0) { @@ -3559,7 +5817,6 @@ static int hmx_mm_id_2d_f32(struct htp_context *ctx, const uint32_t n_weight_tiles = k / htp_tensor_get_tile_k(weight_type); const struct fastdiv_values n_k_tiles_div = init_fastdiv_values(n_k_tiles); - const size_t vec_dot_size = k * sizeof(__fp16); const size_t vtcm_budget = ctx->vtcm_size; size_t vtcm_used = 0; @@ -3570,65 +5827,63 @@ static int hmx_mm_id_2d_f32(struct htp_context *ctx, const uint32_t dma_src_stride = is_tiled ? tile_size : weight_stride; const uint32_t dma_width_bytes = is_tiled ? tile_size : row_stride; - const size_t qweight_row_stride = is_tiled ? (size_t)(n_weight_tiles * aligned_tile_size) / 32 : 0; - const size_t weight_row_stride = is_tiled ? qweight_row_stride : row_stride; - - size_t size_per_n = 0, size_per_m = 0, size_per_mn = 0; - htp_mm_hmx_get_2d_chunk_costs(weight_type, k, /*pipeline=*/false, aligned_tile_size, - &size_per_n, &size_per_m, &size_per_mn); - - const size_t overhead = htp_mm_hmx_get_2d_overhead(weight_type, /*pipeline=*/false, /*is_matmul_id=*/true); size_t m_chunk_n_rows = 0, n_chunk_n_cols = 0; - if (htp_mm_hmx_compute_chunks(vtcm_budget, overhead, size_per_n, size_per_m, size_per_mn, - m_core_padded, n, - /*m_block_cost=*/(size_t) n * HTP_MM_HMX_COST_W_DEQUANT, - /*n_block_cost=*/(size_t) m_core_padded * HTP_MM_HMX_COST_A_CONVERT, &m_chunk_n_rows, &n_chunk_n_cols, &vtcm_used)) { + int act_hvx = 0; + if (!htp_mm_hmx_solve_2d_params( + weight_type, (uint32_t) k, (uint32_t) m_core_padded, + (uint32_t) n, (uint32_t) m_core_padded, (uint32_t) m_core_padded, + (int) octx->n_hvx, /*pipeline=*/false, /*is_matmul_id=*/true, + (uint32_t) aligned_tile_size, /*bias_size=*/0, dst_elem_size, vtcm_budget, + &m_chunk_n_rows, &n_chunk_n_cols, &act_hvx, &vtcm_used)) { FARF(ERROR, "hmx-mm-id-2d: VTCM too small : m %d k %d n %d budget %zu", m_core_padded, k, n, vtcm_budget); return -1; } - const size_t weight_area_size = hex_align_up(n_chunk_n_cols * weight_row_stride, HTP_MM_HMX_TILE_SIZE); - const size_t act_area_size = hex_align_up(m_chunk_n_rows * vec_dot_size, HTP_MM_HMX_TILE_SIZE); - const size_t output_area_size = hex_align_up(m_chunk_n_rows * n_chunk_n_cols * sizeof(__fp16), HTP_MM_HMX_TILE_SIZE); - - size_t scratch0_size = hex_align_up(n_chunk_n_cols * vec_dot_size, HTP_MM_HMX_TILE_SIZE); - - uint8_t *vtcm_ptr = (uint8_t *) ctx->vtcm_base; - __fp16 *vtcm_weight = weight_area_size ? (__fp16 *) vtcm_seq_alloc(&vtcm_ptr, weight_area_size) : NULL; - __fp16 *vtcm_f16_act = (__fp16 *) vtcm_seq_alloc(&vtcm_ptr, act_area_size); - __fp16 *vtcm_output = (__fp16 *) vtcm_seq_alloc(&vtcm_ptr, output_area_size); - void *vtcm_scratch0 = vtcm_seq_alloc(&vtcm_ptr, scratch0_size); - __fp16 *vtcm_scales = (__fp16 *) vtcm_seq_alloc(&vtcm_ptr, 256); - const size_t lut_size = htp_mm_hmx_lut_bytes(weight_type); - uint8_t *vtcm_lut = lut_size ? (uint8_t *) vtcm_seq_alloc(&vtcm_ptr, lut_size) : NULL; - - vtcm_used = vtcm_ptr - (uint8_t *) ctx->vtcm_base; - if (vtcm_used > vtcm_budget) { - FARF(ERROR, "hmx-mm-id-2d: VTCM overflow: used %zu budget %zu", vtcm_used, vtcm_budget); + struct htp_mm_hmx_vtcm_layout L; + htp_mm_hmx_vtcm_layout_build_ex( + &L, HTP_MM_KERNEL_HMX_2D, weight_type, (uint32_t) k, + m_chunk_n_rows, n_chunk_n_cols, 1, /*pipeline=*/false, + (uint32_t) act_hvx, (uint32_t) aligned_tile_size, 0, 0, dst_elem_size); + if (L.total_bytes > vtcm_budget) { + FARF(ERROR, "hmx-mm-id-2d: VTCM overflow: used %zu budget %zu", L.total_bytes, vtcm_budget); return -1; } + uint8_t * const base = (uint8_t *) ctx->vtcm_base; + __fp16 *vtcm_weight = VTCM_LAYOUT_PTR(__fp16, base, L.off_weight[0]); + __fp16 *vtcm_f16_act = VTCM_LAYOUT_PTR(__fp16, base, L.off_act); + float *vtcm_f32_act = VTCM_LAYOUT_PTR(float, base, L.off_act_f32); + __fp16 *vtcm_output = VTCM_LAYOUT_PTR(__fp16, base, L.off_dst[0]); + void *vtcm_scratch0 = VTCM_LAYOUT_PTR(void, base, L.off_scratch[0]); + uint8_t *vtcm_res_out = VTCM_LAYOUT_PTR(uint8_t, base, L.off_res_out[0]); + __fp16 *vtcm_scales = VTCM_LAYOUT_PTR(__fp16, base, L.off_scales); + uint8_t *vtcm_lut = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, base, L.off_lut, L.lut_bytes > 0); + hmx_init_column_scales(vtcm_scales, Q6_V_vsplat_R(0x3c00)); - if (lut_size) { + if (L.lut_bytes > 0) { iq2xxs_lut_copy(vtcm_lut); } htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0); - hmx_matmul_job_t job; + const struct fastdiv_values act_hvx_div = init_fastdiv_values((uint32_t) act_hvx); + hmx_matmul_task_t task; void *vtcm_raw_bufs[2] = { vtcm_weight, dequant_worker_fn ? vtcm_weight : vtcm_scratch0 }; void *vtcm_weight_bufs[2] = { dequant_worker_fn ? vtcm_scratch0 : vtcm_weight, vtcm_scratch0 }; const int n_chunk_cnt = hmx_ceil_div(n, n_chunk_n_cols); + const size_t res_out_stride_bytes = hex_align_up(n_chunk_n_cols * dst_elem_size, 128); + const int res_out_stride_elems = (int) (res_out_stride_bytes / dst_elem_size); - for (size_t mr = (size_t) m_start; mr < (size_t) m_end; mr += m_chunk_n_rows) { - const size_t n_rows = hex_smin((size_t) m_end - mr, m_chunk_n_rows); - const size_t n_row_tiles = hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS); + for (size_t mr = (size_t) m_start; mr < (size_t) mr_limit; mr += m_chunk_n_rows) { + const size_t n_rows = hex_smin((size_t) mr_limit - mr, m_chunk_n_rows); + const size_t n_row_tiles = hmx_ceil_div(n_rows, HTP_MM_HMX_TILE_N_ROWS); + const bool overlap_w_next = (n_rows <= 200u); transfer_activation_chunk_gathered_threaded( - ctx, vtcm_f16_act, activation, (int) mr, (int) n_rows, k, - matrix_rows, cur_a, mapping_stride, ne11, act_nb1, act_nb2, cne1, n_hvx, k_valid); + octx, vtcm_f16_act, activation, act_elem_size, (int) mr, (int) n_rows, k, + matrix_rows, cur_a, mapping_stride, ne11, act_nb1, act_nb2, k_valid, + act_hvx, &act_hvx_div, vtcm_f32_act, L.act_f32_bytes); - // A0: Pre-fetch the first weight chunk (nc = 0) if (n > 0) { const size_t n_cols = hex_smin((size_t) n, n_chunk_n_cols); const uint32_t height = is_tiled ? hmx_ceil_div(n_cols, 32) * n_weight_tiles : n_cols; @@ -3641,34 +5896,58 @@ static int hmx_mm_id_2d_f32(struct htp_context *ctx, const size_t n_cols = hex_smin((size_t) n - nc, n_chunk_n_cols); const size_t n_col_tiles = hmx_ceil_div(n_cols, HTP_MM_HMX_TILE_N_COLS); - // A: Wait for weight DMA void * curr_raw = (void *) dma_queue_pop(weight_dma).dst; + if (overlap_w_next && i > 0) { + for (size_t s = 0; s < n_rows; ++s) { + dma_queue_pop(weight_dma); + } + } - // B: Weight Dequantize (Threaded) dequantize_tiled_weight_chunk_to_fp16_tiles( - ctx, vtcm_weight_bufs[i % 2], curr_raw, + octx, vtcm_weight_bufs[i % 2], curr_raw, n_cols, k, row_stride, weight_type, - n_k_tiles, n_k_tiles_div, dequant_worker_fn, n_hvx + n_k_tiles, n_k_tiles_div, dequant_worker_fn ); - // Start weight DMA for the next chunk early const size_t nc_next = nc + n_chunk_n_cols; - if (nc_next < (size_t) n) { + if (overlap_w_next && nc_next < (size_t) n) { const size_t n_cols_next = hex_smin((size_t) n - nc_next, n_chunk_n_cols); const uint32_t height_next = is_tiled ? hmx_ceil_div(n_cols_next, 32) * n_weight_tiles : n_cols_next; dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[(i + 1) % 2], weight + nc_next * weight_stride), dma_dst_stride, dma_src_stride, dma_width_bytes, height_next); } - // C: HMX Compute (Queue-based) - hmx_matmul_job_init(&job, vtcm_output, vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 2], vtcm_scales, n_row_tiles, n_col_tiles, k / HTP_MM_HMX_TILE_N_ROWS); - hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_matmul_worker_fn, &job)); + hmx_matmul_task_init(&task, vtcm_output, vtcm_f16_act, (__fp16 *) vtcm_weight_bufs[i % 2], vtcm_scales, n_row_tiles, n_col_tiles, k / HTP_MM_HMX_TILE_N_ROWS); + hmx_queue_push(ctx->hmx_queue, hmx_queue_make_desc(hmx_matmul_fp16_worker_fn, &task)); hmx_queue_pop(ctx->hmx_queue); - // D: Output Store - transfer_output_chunk_scattered_threaded( - ctx, dst + nc, vtcm_output, (int) mr, (int) n_rows, (int) n_cols, - matrix_rows, cur_a, mapping_stride, dst_nb1, dst_nb2, cne1, n_hvx); + transfer_output_chunk_threaded( + octx, vtcm_res_out, NULL, vtcm_output, + n_rows, n_cols, res_out_stride_elems, 0, (int) n_cols, + dst_elem_size, sizeof(float)); + + if (overlap_w_next) { + push_scattered_dst_rows_dma( + weight_dma, dst + nc * dst_elem_size, vtcm_res_out, + (uint32_t) mr, (uint32_t) n_rows, res_out_stride_bytes, n_cols * dst_elem_size, + matrix_rows, (uint32_t) cur_a, (uint32_t) mapping_stride, dst_nb1, dst_nb2); + } else { + sync_scattered_dst_rows_dma( + weight_dma, dst + nc * dst_elem_size, vtcm_res_out, + (uint32_t) mr, (uint32_t) n_rows, res_out_stride_bytes, n_cols * dst_elem_size, + matrix_rows, (uint32_t) cur_a, (uint32_t) mapping_stride, dst_nb1, dst_nb2); + if (nc_next < (size_t) n) { + const size_t n_cols_next = hex_smin((size_t) n - nc_next, n_chunk_n_cols); + const uint32_t height_next = is_tiled ? hmx_ceil_div(n_cols_next, 32) * n_weight_tiles : n_cols_next; + dma_queue_push(weight_dma, dma_make_data(vtcm_raw_bufs[(i + 1) % 2], weight + nc_next * weight_stride), + dma_dst_stride, dma_src_stride, dma_width_bytes, height_next); + } + } + } + if (overlap_w_next && n_chunk_cnt > 0) { + for (size_t s = 0; s < n_rows; ++s) { + dma_queue_pop(weight_dma); + } } } @@ -3683,18 +5962,15 @@ static int hmx_mm_op_matmul(struct htp_ops_context * octx, const struct htp_mm_k int k = (int) src0->ne[0]; int n = (int) src0->ne[1]; const int m_total = (int) act->ne[1]; - const uint32_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const uint32_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const uint32_t bias_elem_size = (bias && bias->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); const int act_stride = (int) (act->nb[1] / act_elem_size); int m_start = 0; int m_rows = m_total; if (octx->ctx->mdev.count > 1) { - uint32_t rows_per_chunk = 0; - if ((dst->ne[2] <= 1 || (dst->nb[2] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0) && - (dst->ne[3] <= 1 || (dst->nb[3] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0)) { - htp_tensor_mdev_rows_per_chunk(dst, sizeof(float), dst->ne[0] * sizeof(float), &rows_per_chunk); - } - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition((uint32_t) m_total, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition((uint32_t) m_total, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); m_start = (int) range.start; m_rows = (int) range.count; } @@ -3703,32 +5979,31 @@ static int hmx_mm_op_matmul(struct htp_ops_context * octx, const struct htp_mm_k return HTP_STATUS_OK; } - dma_addr_t src2_addr = 0; - size_t src2_bytes = 0; - uint32_t src2_stride = 0; - size_t src2_nb2 = 0; - size_t src2_nb3 = 0; - if (src2) { - src2_stride = (src2->ne[1] == 1) ? 0 : (uint32_t) (src2->nb[1] / sizeof(float)); - src2_addr = src2->data + (size_t) m_start * src2_stride * sizeof(float); - const size_t slice_bytes = (src2->ne[1] == 1) ? src2->nb[1] : (size_t) m_rows * src2->nb[1]; - src2_bytes = MIN((size_t) kparams->vtcm_bias_size, slice_bytes); - src2_nb2 = (src2->ne[2] == 1) ? 0 : src2->nb[2]; - src2_nb3 = (src2->ne[3] == 1) ? 0 : src2->nb[3]; + dma_addr_t bias_addr = 0; + size_t bias_bytes = 0; + uint32_t bias_stride = 0; + size_t bias_nb2 = 0; + size_t bias_nb3 = 0; + if (bias) { + bias_stride = (bias->ne[1] == 1) ? 0 : (uint32_t) (bias->nb[1] / bias_elem_size); + bias_addr = bias->data + (size_t) m_start * bias_stride * bias_elem_size; + const size_t slice_bytes = (bias->ne[1] == 1) ? bias->nb[1] : (size_t) m_rows * bias->nb[1]; + bias_bytes = MIN((size_t) kparams->vtcm_bias_size, slice_bytes); + bias_nb2 = (bias->ne[2] == 1) ? 0 : bias->nb[2]; + bias_nb3 = (bias->ne[3] == 1) ? 0 : bias->nb[3]; } - const int dst_stride = (int)(dst->nb[1] / sizeof(float)); - float * dst_ptr = (float *) dst->data + m_start * dst_stride; + const int dst_stride = (int) (dst->nb[1] / dst_elem_size); + const dma_addr_t dst_addr = dst->data + (size_t) m_start * dst_stride * dst_elem_size; // byte offset, act_stride is in activation elements (F16 or F32) const dma_addr_t act_addr = act->data + (size_t) m_start * act_stride * act_elem_size; int ret = -1; - const int n_hvx = kparams->n_hvx; - if (kparams->kernel_type == HTP_MM_KERNEL_HMX_BATCHED) { + if (htp_mm_kernel_is_hmx_batched(kparams->kernel_type)) { hmx_mm_batched_params_t batch_params = { - .dst = dst_ptr, - .bias_addr = src2_addr, - .bias_bytes = src2_bytes, + .dst_dma_addr = dst_addr, + .bias_addr = bias_addr, + .bias_bytes = bias_bytes, .act_dma_addr = act_addr, .weight = src0->data, .weight_dma = octx->ctx->dma[0], @@ -3737,11 +6012,13 @@ static int hmx_mm_op_matmul(struct htp_ops_context * octx, const struct htp_mm_k .n = n, .act_stride = act_stride, .act_elem_size = act_elem_size, + .dst_elem_size = dst_elem_size, + .bias_elem_size = bias_elem_size, .weight_stride = (int) src0->nb[1], .weight_type = (int) src0->type, .dst_stride = dst_stride, .dst_cols = (int) dst->ne[0], - .bias_stride = src2_stride, + .bias_stride = bias_stride, .tile_size = kparams->tile_size, .aligned_tile_size = kparams->aligned_tile_size, .ne02 = ne02, @@ -3754,31 +6031,37 @@ static int hmx_mm_op_matmul(struct htp_ops_context * octx, const struct htp_mm_k .act_nb3 = act->nb[3], .dst_nb2 = dst->nb[2], .dst_nb3 = dst->nb[3], - .bias_nb2 = src2_nb2, - .bias_nb3 = src2_nb3, + .bias_nb2 = bias_nb2, + .bias_nb3 = bias_nb3, .r2 = (ne02 > 0) ? (ne12 / ne02) : 1, .r3 = (ne03 > 0) ? (ne13 / ne03) : 1, .div_r2 = kparams->div_r2, .div_r3 = kparams->div_r3, + .kernel_type = kparams->kernel_type, + .hmx_n_groups = kparams->hmx_n_groups, + .div_hmx_n_groups = kparams->div_hmx_n_groups, + .div_n_k_tiles = kparams->div_n_k_tiles, }; - ret = hmx_mm_batched(octx->ctx, &batch_params, + ret = hmx_mm_batched(octx, &batch_params, kparams->m_chunk, kparams->n_chunk, - kparams->pipeline, n_hvx, + kparams->pipeline, kparams->n_act_hvx, &kparams->div_n_act_hvx, &kparams->div_ne00_padded, kparams->vtcm_size); } else { ret = hmx_mm_2d_f32( - octx->ctx, octx->ctx->dma[0], dst_ptr, src2_addr, src2_bytes, + octx, octx->ctx->dma[0], dst_addr, bias_addr, bias_bytes, act_addr, src0->data, m_rows, k, n, act_stride, act_elem_size, (int) src0->nb[1], (int) src0->type, (int) act->ne[0], - dst_stride, src2_stride, (int)dst->ne[0], - kparams->m_chunk, kparams->n_chunk, kparams->pipeline, n_hvx, + dst_stride, bias_stride, (int)dst->ne[0], dst_elem_size, bias_elem_size, + kparams->m_chunk, kparams->n_chunk, kparams->pipeline, kparams->n_act_hvx, &kparams->div_n_act_hvx, &kparams->div_ne00_padded, - kparams->tile_size, kparams->aligned_tile_size, kparams->vtcm_size + kparams->tile_size, kparams->aligned_tile_size, kparams->vtcm_size, + kparams->kernel_type, kparams->hmx_n_groups, + &kparams->div_hmx_n_groups, &kparams->div_n_k_tiles ); } @@ -3816,13 +6099,12 @@ static int hmx_mm_op_matmul_id( const struct mmid_row_mapping * matrix_rows = mmctx->matrix_rows; htp_matmul_tensors_preamble; const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params; - const int n_ids = octx->src[2]->ne[0]; const int n_as = ne02; - const bool mdev_split = (octx->ctx->mdev.count > 1) && htp_tensor_can_row_partition(dst, sizeof(float)); - if (octx->ctx->mdev.count > 1 && !mdev_split && octx->ctx->mdev.idx > 0) { - return HTP_STATUS_OK; - } + const size_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const size_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + + const bool mdev_split = (octx->ctx->mdev.count > 1); uint32_t n_active = 0; if (mdev_split) { for (uint32_t a = 0; a < (uint32_t) n_as; ++a) { @@ -3850,10 +6132,11 @@ static int hmx_mm_op_matmul_id( m_start = (int) range.start; m_end = (int) (range.start + range.count); } - if (m_start >= m_end) continue; + if (m_start >= m_end || m_start >= cne1) continue; - int ret = hmx_mm_id_2d_f32(octx->ctx, octx->ctx->dma[0], (float*) dst->data, (float*) act->data, - src0->data + cur_a * nb02, + int ret = hmx_mm_id_2d_f32(octx, octx->ctx->dma[0], dst->data, act->data, + act_elem_size, dst_elem_size, + src0->data + (dma_addr_t) cur_a * nb02, cne1, ne00, ne01, ne10, ne11, @@ -3862,7 +6145,8 @@ static int hmx_mm_op_matmul_id( (int) src0->nb[1], (int) src0->type, kparams->tile_size, kparams->aligned_tile_size, matrix_rows, cur_a, mmctx->mapping_stride, - m_start, m_end, (int) octx->n_hvx); + m_start, m_end, + kparams->kernel_type); if (ret != 0) { FARF(ERROR, "HMX matmul failed for expert %u, error %d\n", cur_a, ret); return HTP_STATUS_NO_SUPPORT; @@ -3885,7 +6169,6 @@ static int hvx_mm_matmul_id( htp_trace_event_start(tr, HTP_TRACE_EVT_INIT, 0); const struct htp_mm_kernel_params * kparams = (const struct htp_mm_kernel_params *) octx->kernel_params; - const struct htp_tensor * restrict ids = octx->src[2]; const size_t src0_row_size = nb01; const uint32_t qk = HTP_MM_ACT_BLOCK_K; @@ -3909,11 +6192,13 @@ static int hvx_mm_matmul_id( n_quant_tasks = MIN(act_nrows, octx->n_hvx); quant_task_func = htp_mm_act_quant_row_func(src0->type, act->type); } - size_t act_row_size = htp_mm_tiled_act_row_size(src0->type, ne10); + const size_t act_row_size = kparams->act_row_size; + size_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const size_t dst_row_size = (size_t) ne0 * sizeof(float); struct htp_mm_hvx_vtcm_layout L; htp_mm_hvx_vtcm_layout_build(&L, kparams->kernel_type, src0->type, ne10, act_nrows, octx->n_hvx, - 0, src0_row_size, act_row_size, 0, kparams->n_prefetch, true, false); + dst_row_size, src0_row_size, act_elem_size, 0, kparams->n_prefetch, true, false); const size_t vtcm_size = L.total_bytes; @@ -3941,7 +6226,7 @@ static int hvx_mm_matmul_id( mmctx->vtcm_src0_stride = src0_row_size_padded; mmctx->vtcm_act_stride = act_row_size; - mmctx->vtcm_act_raw_stride = htp_mm_act_raw_row_size(ne10); + mmctx->vtcm_act_raw_stride = htp_mm_act_raw_row_size(ne10, act_elem_size); mmctx->vtcm_src0_size_per_hvx = fastdiv(L.src0_bytes, &octx->n_hvx_div); mmctx->vtcm_act_size_per_hvx = L.act_bytes; @@ -3975,14 +6260,9 @@ static int hmx_mm_op_matmul_id_nx( const struct htp_tensor * restrict act = octx->src[n_weights]; const int n_as = src0->ne[2]; - bool mdev_split = (octx->ctx->mdev.count > 1); - for (uint32_t p = 0; p < n_weights && mdev_split; ++p) { - const struct htp_tensor * restrict dst = octx->dsts[p]; - mdev_split = htp_tensor_can_row_partition(dst, sizeof(float)); - } - if (octx->ctx->mdev.count > 1 && !mdev_split && octx->ctx->mdev.idx > 0) { - return HTP_STATUS_OK; - } + const size_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + + const bool mdev_split = (octx->ctx->mdev.count > 1); uint32_t n_active = 0; if (mdev_split) { for (uint32_t a = 0; a < (uint32_t) n_as; ++a) { @@ -4010,15 +6290,53 @@ static int hmx_mm_op_matmul_id_nx( m_start = (int) range.start; m_end = (int) (range.start + range.count); } - if (m_start >= m_end) continue; + if (m_start >= m_end || m_start >= cne1) continue; + + if (htp_mm_kernel_is_hmx_int(kparams->kernel_type)) { + const struct htp_tensor * restrict dst0 = octx->dsts[0]; + bool same_shape = true; + dma_addr_t dst_addrs[HTP_OP_MAX_OUTPUTS]; + dma_addr_t weight_addrs[HTP_OP_MAX_OUTPUTS]; + for (uint32_t p = 0; p < n_weights && same_shape; ++p) { + const struct htp_tensor * restrict sw = octx->src[p]; + const struct htp_tensor * restrict d = octx->dsts[p]; + if (sw->ne[0] != src0->ne[0] || sw->ne[1] != src0->ne[1] || + sw->nb[1] != src0->nb[1] || sw->type != src0->type || + d->type != dst0->type || d->nb[1] != dst0->nb[1] || d->nb[2] != dst0->nb[2]) { + same_shape = false; + break; + } + dst_addrs[p] = d->data; + weight_addrs[p] = sw->data + (dma_addr_t) cur_a * sw->nb[2]; + } + if (same_shape) { + const size_t dst0_elem_size = (dst0->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + int ret = hmx_mm_id_2d_int( + octx, octx->ctx->dma[0], dst_addrs, act->data, + act_elem_size, dst0_elem_size, weight_addrs, n_weights, + cne1, src0->ne[0], src0->ne[1], act->ne[0], act->ne[1], + act->nb[1], act->nb[2], dst0->nb[1], dst0->nb[2], + (int) src0->nb[1], (int) src0->type, + kparams->tile_size, kparams->aligned_tile_size, + matrix_rows, cur_a, mmctx->mapping_stride, + m_start, m_end, kparams->kernel_type); + if (ret != 0) { + FARF(ERROR, "HMX matmul ID NX failed for expert %u, error %d\n", cur_a, ret); + return HTP_STATUS_NO_SUPPORT; + } + continue; + } + } for (uint32_t p = 0; p < n_weights; ++p) { const struct htp_tensor * restrict src_w = octx->src[p]; const struct htp_tensor * restrict dst = octx->dsts[p]; if (!src_w || !dst) continue; + const size_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); - int ret = hmx_mm_id_2d_f32(octx->ctx, octx->ctx->dma[0], (float*) dst->data, (float*) act->data, - src_w->data + cur_a * src_w->nb[2], + int ret = hmx_mm_id_2d_f32(octx, octx->ctx->dma[0], dst->data, act->data, + act_elem_size, dst_elem_size, + src_w->data + (dma_addr_t) cur_a * src_w->nb[2], cne1, src_w->ne[0], src_w->ne[1], act->ne[0], act->ne[1], @@ -4027,7 +6345,8 @@ static int hmx_mm_op_matmul_id_nx( (int) src_w->nb[1], (int) src_w->type, kparams->tile_size, kparams->aligned_tile_size, matrix_rows, cur_a, mmctx->mapping_stride, - m_start, m_end, (int) octx->n_hvx); + m_start, m_end, + kparams->kernel_type); if (ret != 0) { FARF(ERROR, "HMX matmul ID NX failed for expert %u weight %u, error %d\n", cur_a, p, ret); return HTP_STATUS_NO_SUPPORT; @@ -4043,7 +6362,6 @@ static int hvx_mm_matmul_id_nx( struct htp_mm_context * mmctx, work_queue_func_t hvx_mmid_task_func ) { - const uint32_t src0_row_size_padded = mmctx->src0_row_size_padded; const uint32_t act_nrows = mmctx->act_nrows; struct htp_thread_trace * tr = &octx->ctx->trace[0]; @@ -4053,7 +6371,6 @@ static int hvx_mm_matmul_id_nx( const uint32_t n_weights = kparams->n_weights; const struct htp_tensor * restrict src0 = octx->src[0]; const struct htp_tensor * restrict act = octx->src[n_weights]; - const struct htp_tensor * restrict ids = octx->src[n_weights + 1]; const size_t src0_row_size = src0->nb[1]; const uint32_t qk = HTP_MM_ACT_BLOCK_K; @@ -4077,11 +6394,19 @@ static int hvx_mm_matmul_id_nx( n_quant_tasks = MIN(act_nrows, octx->n_hvx); quant_task_func = htp_mm_act_quant_row_func(src0->type, act->type); } - size_t act_row_size = htp_mm_tiled_act_row_size(src0->type, act->ne[0]); + const size_t act_row_size = kparams->act_row_size; + size_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + size_t max_dst_row_size = 0; + for (uint32_t p = 0; p < n_weights; ++p) { + if (octx->dsts[p]) { + const size_t sz = (size_t) octx->dsts[p]->ne[0] * sizeof(float); + if (sz > max_dst_row_size) max_dst_row_size = sz; + } + } struct htp_mm_hvx_vtcm_layout L; htp_mm_hvx_vtcm_layout_build(&L, kparams->kernel_type, src0->type, act->ne[0], act_nrows, octx->n_hvx, - 0, src0_row_size, act_row_size, 0, kparams->n_prefetch, true, false); + max_dst_row_size, src0_row_size, act_elem_size, 0, kparams->n_prefetch, true, false); const size_t vtcm_size = L.total_bytes; @@ -4100,7 +6425,7 @@ static int hvx_mm_matmul_id_nx( mmctx->vtcm_src0_stride = 0; mmctx->vtcm_act_stride = act_row_size; - mmctx->vtcm_act_raw_stride = htp_mm_act_raw_row_size(act->ne[0]); + mmctx->vtcm_act_raw_stride = htp_mm_act_raw_row_size(act->ne[0], act_elem_size); mmctx->vtcm_src0_size_per_hvx = fastdiv(L.src0_bytes, &octx->n_hvx_div); mmctx->vtcm_act_size_per_hvx = L.act_bytes; @@ -4128,19 +6453,18 @@ static int hvx_mm_matmul_id_nx( } static __attribute__((noinline)) uint32_t scan_expert_ids_n( - const struct htp_tensor * ids, + const int32_t * ids_data, + uint32_t ids_ne1, const uint32_t n_ids, uint32_t n_as, uint32_t * counts, struct mmid_row_mapping * matrix_rows, uint32_t mapping_stride ) { - const size_t ids_nb1 = ids->nb[1]; - const uint8_t * ids_data = (const uint8_t *) ids->data; uint32_t n_skipped = 0; - for (uint32_t iid1 = 0; iid1 < ids->ne[1]; ++iid1) { - const int32_t * row_ptr = (const int32_t *) (ids_data + iid1 * ids_nb1); + for (uint32_t iid1 = 0; iid1 < ids_ne1; ++iid1) { + const int32_t * row_ptr = ids_data + (size_t) iid1 * n_ids; for (uint32_t id = 0; id < n_ids; ++id) { const int32_t i02 = row_ptr[id]; if (i02 < 0) { @@ -4159,54 +6483,26 @@ static __attribute__((noinline)) uint32_t scan_expert_ids_n( } static __attribute__((noinline)) uint32_t scan_expert_ids( - const struct htp_tensor * ids, + const int32_t * ids_data, + uint32_t ids_ne1, uint32_t n_ids, uint32_t n_as, uint32_t * counts, struct mmid_row_mapping * matrix_rows, uint32_t mapping_stride ) { - const size_t ids_nb0 = ids->nb[0]; - - if (ids_nb0 == 4) { - switch (n_ids) { - case 8: return scan_expert_ids_n(ids, 8, n_as, counts, matrix_rows, mapping_stride); - case 4: return scan_expert_ids_n(ids, 4, n_as, counts, matrix_rows, mapping_stride); - case 2: return scan_expert_ids_n(ids, 2, n_as, counts, matrix_rows, mapping_stride); - default: return scan_expert_ids_n(ids, n_ids, n_as, counts, matrix_rows, mapping_stride); - } - } else { - // Strided fallback - const size_t ids_nb1 = ids->nb[1]; - const uint8_t * ids_data = (const uint8_t *) ids->data; - uint32_t n_skipped = 0; - for (uint32_t iid1 = 0; iid1 < ids->ne[1]; ++iid1) { - const int32_t * row_ptr = (const int32_t *) (ids_data + iid1 * ids_nb1); - for (uint32_t id = 0; id < n_ids; ++id) { - const int32_t i02 = *(const int32_t *) ((const uint8_t *) row_ptr + id * ids_nb0); - if (i02 < 0) { - n_skipped++; - continue; - } - assert(i02 >= 0 && i02 < (int32_t) n_as); - - if (matrix_rows) { - matrix_rows[i02 * mapping_stride + counts[i02]] = (struct mmid_row_mapping) { id, iid1 }; - } - counts[i02] += 1; - } - } - return n_skipped; + switch (n_ids) { + case 8: return scan_expert_ids_n(ids_data, ids_ne1, 8, n_as, counts, matrix_rows, mapping_stride); + case 4: return scan_expert_ids_n(ids_data, ids_ne1, 4, n_as, counts, matrix_rows, mapping_stride); + case 2: return scan_expert_ids_n(ids_data, ids_ne1, 2, n_as, counts, matrix_rows, mapping_stride); + default: return scan_expert_ids_n(ids_data, ids_ne1, n_ids, n_as, counts, matrix_rows, mapping_stride); } } -static __attribute__((noinline)) uint32_t count_skipped_ids_single(const struct htp_tensor * ids, uint32_t n_ids) { - const uint8_t * ids_data = (const uint8_t *) ids->data; - const size_t ids_nb0 = ids->nb[0]; +static __attribute__((noinline)) uint32_t count_skipped_ids_single(const int32_t * ids_data, uint32_t n_ids) { uint32_t n_skipped = 0; for (uint32_t id = 0; id < n_ids; ++id) { - const int32_t i02 = *(const int32_t *) (ids_data + id * ids_nb0); - if (i02 < 0) { + if (ids_data[id] < 0) { n_skipped++; } } @@ -4216,7 +6512,8 @@ static __attribute__((noinline)) uint32_t count_skipped_ids_single(const struct // Zero rows for skipped slots (ids < 0). Matmuls only write rows that an expert owns. static void zero_skipped_dst_rows( struct htp_ops_context * octx, - const struct htp_tensor * ids, + const int32_t * ids_data, + uint32_t ids_ne1, uint32_t n_ids, const struct htp_tensor * dst ) { @@ -4225,10 +6522,8 @@ static void zero_skipped_dst_rows( uint32_t col_count = dst->ne[0]; if (octx->ctx->mdev.count > 1) { - const bool can_split = htp_tensor_can_row_partition(dst, elem_size); - const uint32_t chunk_elems = (dst->type == HTP_TYPE_F16) ? 64 : 32; const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( - dst->ne[0], can_split ? chunk_elems : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + dst->ne[0], 32, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); col_start = range.start; col_count = range.count; } @@ -4237,51 +6532,104 @@ static void zero_skipped_dst_rows( return; } - const uint8_t * ids_data = (const uint8_t *) ids->data; - const size_t ids_nb0 = ids->nb[0]; - const size_t ids_nb1 = ids->nb[1]; const size_t dst_nb1 = dst->nb[1]; const size_t dst_nb2 = dst->nb[2]; - const uint32_t col_offset_bytes = col_start * elem_size; - - for (uint32_t iid1 = 0; iid1 < ids->ne[1]; ++iid1) { - const uint8_t * ids_row = ids_data + iid1 * ids_nb1; - uint8_t * dst_row_group = (uint8_t *) dst->data + iid1 * dst_nb2 + col_offset_bytes; + const size_t col_offset_bytes = (size_t) col_start * elem_size; + const size_t row_bytes = (size_t) col_count * elem_size; + + // Zero one row in VTCM and copy to skipped dst rows via bypass DMA. + dma_queue * const dma_q = octx->ctx->dma[0]; + uint8_t * const vtcm_zero = octx->ctx->vtcm_base; + const size_t chunk_bytes = MIN(row_bytes, octx->ctx->vtcm_size); + hvx_splat_u8_a(vtcm_zero, 0, (uint32_t) hex_round_up(chunk_bytes, 128)); + + uint32_t pending = 0; + for (uint32_t iid1 = 0; iid1 < ids_ne1; ++iid1) { + const int32_t * ids_row = ids_data + (size_t) iid1 * n_ids; + const dma_addr_t dst_row_group = dst->data + (dma_addr_t) iid1 * dst_nb2 + col_offset_bytes; for (uint32_t id = 0; id < n_ids; ++id) { - const int32_t i02 = *(const int32_t *) (ids_row + id * ids_nb0); - if (i02 < 0) { - hvx_splat_u(dst_row_group + id * dst_nb1, Q6_V_vzero(), col_count, elem_size); + if (ids_row[id] < 0) { + const dma_addr_t row_base = dst_row_group + (dma_addr_t) id * dst_nb1; + for (size_t off = 0; off < row_bytes; off += chunk_bytes) { + const size_t n = MIN(chunk_bytes, row_bytes - off); + dma_queue_push(dma_q, dma_make_data(row_base + off, vtcm_zero), n, n, n, 1); + if (++pending >= 128) { + dma_queue_flush(dma_q); + pending = 0; + } + } } } } + if (pending > 0) { + dma_queue_flush(dma_q); + } } static int htp_mmid_prepare_mapping( struct htp_ops_context * octx, const struct htp_tensor * ids, + uint8_t * ids_stack, + size_t ids_stack_size, uint32_t n_ids, uint32_t n_as, uint32_t act_nrows, - uint8_t ** out_mapping_buf, + const int32_t ** out_ids_data, + void ** out_ids_alloc, + void ** out_map_alloc, uint32_t ** out_matrix_row_counts, struct mmid_row_mapping ** out_matrix_rows, uint32_t * out_mapping_stride, uint32_t * out_n_skipped ) { - uint8_t * mapping_buf = octx->ctx->ddr_spad_base; + const size_t ids_bytes = hex_round_up(htp_tensor_nbytes(ids), 128); + uint8_t * ids_buf = NULL; + void * ids_alloc = NULL; + uint8_t * spad_base = (uint8_t *) octx->ctx->ddr_spad_base; + size_t spad_avail = octx->ctx->ddr_spad_size; + + if (ids_bytes <= ids_stack_size) { + ids_buf = ids_stack; + } else if (ids_bytes <= spad_avail) { + ids_buf = spad_base; + spad_base += ids_bytes; + spad_avail -= ids_bytes; + } else { + ids_alloc = memalign(128, ids_bytes); + if (!ids_alloc) { + return HTP_STATUS_INTERNAL_ERR; + } + ids_buf = (uint8_t *) ids_alloc; + } + + if (htp_tensor_read(&octx->ctx->main_th, ids_buf, ids_bytes, ids) == 0) { + free(ids_alloc); + return HTP_STATUS_INTERNAL_ERR; + } + + const int32_t * ids_data = (const int32_t *) ids_buf; + + void * map_alloc = NULL; + uint8_t * mapping_buf = spad_base; uint32_t mapping_stride = 1; - uint32_t * matrix_row_counts = (uint32_t *) mapping_buf; + uint32_t * matrix_row_counts = NULL; struct mmid_row_mapping * matrix_rows = NULL; uint32_t n_skipped = 0; if (act_nrows > 1) { const size_t matrix_row_counts_size = n_as * sizeof(uint32_t); - assert(octx->ctx->ddr_spad_size >= matrix_row_counts_size); - - hex_l2fetch_block((const void *) ids->data, ids->ne[1] * ids->nb[1]); + if (matrix_row_counts_size > spad_avail) { + map_alloc = memalign(128, matrix_row_counts_size); + if (!map_alloc) { + free(ids_alloc); + return HTP_STATUS_INTERNAL_ERR; + } + mapping_buf = (uint8_t *) map_alloc; + } + matrix_row_counts = (uint32_t *) mapping_buf; hvx_splat_u(matrix_row_counts, Q6_V_vzero(), n_as, sizeof(uint32_t)); - n_skipped = scan_expert_ids(ids, n_ids, n_as, matrix_row_counts, NULL, 0); + n_skipped = scan_expert_ids(ids_data, ids->ne[1], n_ids, n_as, matrix_row_counts, NULL, 0); uint32_t max_count = hvx_reduce_max_i32((const uint8_t *) matrix_row_counts, n_as); mapping_stride = max_count > 0 ? max_count : 1; @@ -4289,23 +6637,28 @@ static int htp_mmid_prepare_mapping( size_t matrix_row_map_size = n_as * mapping_stride * sizeof(struct mmid_row_mapping); const size_t total_map_size = matrix_row_counts_size + matrix_row_map_size; - if (total_map_size > octx->ctx->ddr_spad_size) { - mapping_buf = memalign(128, total_map_size); - if (!mapping_buf) { + if (total_map_size > spad_avail) { + free(map_alloc); + map_alloc = memalign(128, total_map_size); + if (!map_alloc) { + free(ids_alloc); return HTP_STATUS_INTERNAL_ERR; } + mapping_buf = (uint8_t *) map_alloc; } matrix_row_counts = (uint32_t *) mapping_buf; matrix_rows = (struct mmid_row_mapping *) (mapping_buf + matrix_row_counts_size); hvx_splat_u(matrix_row_counts, Q6_V_vzero(), n_as, sizeof(uint32_t)); - scan_expert_ids(ids, n_ids, n_as, matrix_row_counts, matrix_rows, mapping_stride); + scan_expert_ids(ids_data, ids->ne[1], n_ids, n_as, matrix_row_counts, matrix_rows, mapping_stride); } else { - n_skipped = count_skipped_ids_single(ids, n_ids); + n_skipped = count_skipped_ids_single(ids_data, n_ids); } - *out_mapping_buf = mapping_buf; + *out_ids_data = ids_data; + *out_ids_alloc = ids_alloc; + *out_map_alloc = map_alloc; *out_matrix_row_counts = matrix_row_counts; *out_matrix_rows = matrix_rows; *out_mapping_stride = mapping_stride; @@ -4333,12 +6686,8 @@ int op_matmul_id(struct htp_ops_context * octx) { mmctx->act = act; const struct htp_tensor * restrict ids = octx->src[2]; - if (htp_tensor_is_extended(ids) || htp_tensor_is_extended(act) || htp_tensor_is_extended(dst)) { - return HTP_STATUS_NO_SUPPORT; - } const size_t src0_row_size = nb01; - const size_t dst_row_size = nb1; const size_t src0_row_size_padded = hex_round_up(src0_row_size, 128); @@ -4349,23 +6698,28 @@ int op_matmul_id(struct htp_ops_context * octx) { const int n_ids = ids->ne[0]; // n_expert_used const int n_as = ne02; // n_expert - uint8_t * mapping_buf = NULL; - uint32_t * matrix_row_counts = NULL; + uint8_t __attribute__((aligned(128))) ids_stack[256]; + const int32_t * ids_data = NULL; + void * ids_alloc = NULL; + void * map_alloc = NULL; + uint32_t * matrix_row_counts = NULL; struct mmid_row_mapping * matrix_rows = NULL; - uint32_t mapping_stride = 1; - uint32_t n_skipped = 0; + uint32_t mapping_stride = 1; + uint32_t n_skipped = 0; - int map_status = htp_mmid_prepare_mapping(octx, ids, n_ids, n_as, act_nrows, - &mapping_buf, &matrix_row_counts, &matrix_rows, + int map_status = htp_mmid_prepare_mapping(octx, ids, ids_stack, sizeof(ids_stack), n_ids, n_as, act_nrows, + &ids_data, &ids_alloc, &map_alloc, + &matrix_row_counts, &matrix_rows, &mapping_stride, &n_skipped); if (map_status != HTP_STATUS_OK) { return map_status; } if (n_skipped > 0) { - zero_skipped_dst_rows(octx, ids, n_ids, dst); + zero_skipped_dst_rows(octx, ids_data, ids->ne[1], n_ids, dst); } + mmctx->ids_data = ids_data; mmctx->matrix_row_counts = matrix_row_counts; mmctx->matrix_rows = matrix_rows; mmctx->mapping_stride = mapping_stride; @@ -4383,17 +6737,16 @@ int op_matmul_id(struct htp_ops_context * octx) { } else { uint32_t src0_row_start = 0; uint32_t src0_row_end = src0_nrows; + const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); if (octx->ctx->mdev.count > 1) { - const bool can_split = htp_tensor_can_row_partition(dst, sizeof(float)); - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, can_split ? 32 : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, 32, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); src0_row_start = range.start; src0_row_end = range.start + range.count; } if (src0_row_start >= src0_row_end) { - if (mapping_buf != octx->ctx->ddr_spad_base) { - free(mapping_buf); - } + free(map_alloc); + free(ids_alloc); return HTP_STATUS_OK; } @@ -4404,6 +6757,8 @@ int op_matmul_id(struct htp_ops_context * octx) { mmctx->src0_nrows_per_hvx = fastdiv(nrows + octx->n_hvx - 1, &octx->n_hvx_div); mmctx->src0_nrows_per_hvx = hex_round_up(mmctx->src0_nrows_per_hvx, 32); + mmctx->store_row = resolve_hvx_tiled_store_row_fn(dst_elem_size, false, sizeof(float)); + if (hvx_mm_init_tiled_vec_dot(mmctx, src0->type) == 0) { s = hvx_mm_matmul_id(octx, mmctx, act_nrows > 1 ? hvx_mm_id_tiled : hvx_mv_id_tiled); } else { @@ -4411,9 +6766,8 @@ int op_matmul_id(struct htp_ops_context * octx) { } } - if (mapping_buf != octx->ctx->ddr_spad_base) { - free(mapping_buf); - } + free(map_alloc); + free(ids_alloc); return s; } @@ -4436,14 +6790,6 @@ int op_matmul_id_nx(struct htp_ops_context * octx) { const struct htp_tensor * restrict src0 = octx->src[0]; const struct htp_tensor * restrict act = octx->src[n_weights]; const struct htp_tensor * restrict ids = octx->src[n_weights + 1]; - if (htp_tensor_is_extended(ids) || htp_tensor_is_extended(act)) { - return HTP_STATUS_NO_SUPPORT; - } - for (uint32_t p = 0; p < n_weights; p++) { - if (htp_tensor_is_extended(octx->dsts[p])) { - return HTP_STATUS_NO_SUPPORT; - } - } mmctx->act = act; @@ -4455,14 +6801,18 @@ int op_matmul_id_nx(struct htp_ops_context * octx) { const int n_ids = ids->ne[0]; const int n_as = src0->ne[2]; - uint8_t * mapping_buf = NULL; - uint32_t * matrix_row_counts = NULL; + uint8_t __attribute__((aligned(128))) ids_stack[256]; + const int32_t * ids_data = NULL; + void * ids_alloc = NULL; + void * map_alloc = NULL; + uint32_t * matrix_row_counts = NULL; struct mmid_row_mapping * matrix_rows = NULL; - uint32_t mapping_stride = 1; - uint32_t n_skipped = 0; + uint32_t mapping_stride = 1; + uint32_t n_skipped = 0; - int map_status = htp_mmid_prepare_mapping(octx, ids, n_ids, n_as, act_nrows, - &mapping_buf, &matrix_row_counts, &matrix_rows, + int map_status = htp_mmid_prepare_mapping(octx, ids, ids_stack, sizeof(ids_stack), n_ids, n_as, act_nrows, + &ids_data, &ids_alloc, &map_alloc, + &matrix_row_counts, &matrix_rows, &mapping_stride, &n_skipped); if (map_status != HTP_STATUS_OK) { return map_status; @@ -4472,11 +6822,12 @@ int op_matmul_id_nx(struct htp_ops_context * octx) { for (uint32_t p = 0; p < n_weights; ++p) { const struct htp_tensor * restrict d = octx->dsts[p]; if (d) { - zero_skipped_dst_rows(octx, ids, n_ids, d); + zero_skipped_dst_rows(octx, ids_data, ids->ne[1], n_ids, d); } } } + mmctx->ids_data = ids_data; mmctx->matrix_row_counts = matrix_row_counts; mmctx->matrix_rows = matrix_rows; mmctx->mapping_stride = mapping_stride; @@ -4499,9 +6850,8 @@ int op_matmul_id_nx(struct htp_ops_context * octx) { } } - if (mapping_buf != octx->ctx->ddr_spad_base) { - free(mapping_buf); - } + free(map_alloc); + free(ids_alloc); return s; } @@ -4513,6 +6863,12 @@ static int op_matmul_nx_impl(struct htp_ops_context * octx) { return status; } + if (octx->op == HTP_OP_MUL_MAT_NX_GLU) { + return htp_mm_kernel_is_hmx_int(kparams->kernel_type) + ? hmx_mm_nx_glu_int_2d(octx, kparams) + : hmx_mm_nx_glu_fp16_2d(octx, kparams); + } + if (kparams->n_hmx) { return hmx_mm_nx_2d_f32(octx, kparams); } @@ -4563,11 +6919,19 @@ static int op_matmul_nx_impl(struct htp_ops_context * octx) { quant_task_func = htp_mm_act_quant_row_func(src0->type, act->type); } - const size_t act_row_size = htp_mm_tiled_act_row_size(src0->type, act->ne[0]); + const size_t act_row_size = kparams->act_row_size; + const size_t act_elem_size = (act->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + size_t max_dst_row_size = 0; + for (uint32_t p = 0; p < n_weights; ++p) { + if (octx->dsts[p]) { + const size_t sz = (size_t) octx->dsts[p]->ne[0] * sizeof(float); + if (sz > max_dst_row_size) max_dst_row_size = sz; + } + } struct htp_mm_hvx_vtcm_layout L; htp_mm_hvx_vtcm_layout_build(&L, kparams->kernel_type, src0->type, act->ne[0], act_nrows, octx->n_hvx, - 0, src0_row_size, act_row_size, 0, kparams->n_prefetch, false, true); + max_dst_row_size, src0_row_size, act_elem_size, 0, kparams->n_prefetch, false, true); const size_t vtcm_size = L.total_bytes; @@ -4581,12 +6945,12 @@ static int op_matmul_nx_impl(struct htp_ops_context * octx) { mmctx->vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, base, L.off_src0); mmctx->vtcm_act = VTCM_LAYOUT_PTR(uint8_t, base, L.off_act); mmctx->vtcm_dst = VTCM_LAYOUT_PTR(uint8_t, base, L.off_dst); - mmctx->vtcm_act_raw = VTCM_LAYOUT_PTR(uint8_t, base, L.off_act_raw); + mmctx->vtcm_act_raw = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, base, L.off_act_raw, quant_task_func != NULL); hvx_mm_iq2xxs_lut_init(base, &L); mmctx->vtcm_src0_stride = 0; mmctx->vtcm_act_stride = act_row_size; - mmctx->vtcm_act_raw_stride = htp_mm_act_raw_row_size(act->ne[0]); + mmctx->vtcm_act_raw_stride = htp_mm_act_raw_row_size(act->ne[0], act_elem_size); mmctx->vtcm_src0_size_per_hvx = fastdiv(L.src0_bytes, &octx->n_hvx_div); mmctx->vtcm_act_size_per_hvx = L.act_bytes; @@ -4594,11 +6958,14 @@ static int op_matmul_nx_impl(struct htp_ops_context * octx) { htp_trace_event_stop(tr, HTP_TRACE_EVT_INIT, 0); - hvx_mm_transfer_act_dma(octx, kparams, act, mmctx->vtcm_act_raw, mmctx->vtcm_act_raw_stride, 0, act_nrows); - - mmctx->n_quant_rows_per_hvx = (act_nrows + n_quant_tasks - 1) / n_quant_tasks; - mmctx->n_quant_tasks = n_quant_tasks; - work_queue_run(octx->ctx->hvx_queue, quant_task_func, mmctx, n_quant_tasks); + if (quant_task_func) { + hvx_mm_transfer_act_dma(octx, kparams, act, mmctx->vtcm_act_raw, mmctx->vtcm_act_raw_stride, 0, act_nrows); + mmctx->n_quant_rows_per_hvx = (act_nrows + n_quant_tasks - 1) / n_quant_tasks; + mmctx->n_quant_tasks = n_quant_tasks; + work_queue_run(octx->ctx->hvx_queue, quant_task_func, mmctx, n_quant_tasks); + } else { + hvx_mm_transfer_act_dma(octx, kparams, act, mmctx->vtcm_act, mmctx->vtcm_act_stride, 0, act_nrows); + } work_queue_run(octx->ctx->hvx_queue, hvx_mm_nx_2d_tiled, mmctx, octx->n_hvx); diff --git a/ggml/src/ggml-hexagon/htp/matmul-ops.h b/ggml/src/ggml-hexagon/htp/matmul-ops.h index 94441cf8cc17..e3c9569caf03 100644 --- a/ggml/src/ggml-hexagon/htp/matmul-ops.h +++ b/ggml/src/ggml-hexagon/htp/matmul-ops.h @@ -14,11 +14,15 @@ extern "C" { #endif // --- HMX Tile Constraints --- -#define HTP_MM_HMX_TILE_N_COLS 32 -#define HTP_MM_HMX_TILE_N_ROWS 32 -#define HTP_MM_HMX_TILE_SIZE (32 * 32 * sizeof(__fp16)) // 2048 bytes -#define HTP_MM_HMX_TILE_N_ELMS 1024 -#define HTP_MM_HMX_MIN_NROWS 4 +#define HTP_MM_HMX_TILE_N_COLS 32 +#define HTP_MM_HMX_TILE_N_ROWS 32 +#define HTP_MM_HMX_TILE_SIZE (32 * 32 * sizeof(__fp16)) // 2048 bytes +#define HTP_MM_HMX_TILE_N_ELMS 1024 +#define HTP_MM_HMX_MIN_NROWS 4 +#define HTP_MM_HMX_WEIGHT_B_TILE_SIZE 1024 +#define HTP_MM_HMX_BIAS_BANK_SIZE 256 +#define HTP_MM_HMX_W8A8_KGROUP 2048u +#define HTP_MM_HMX_W8A8_KGROUP_TILES 64u #define HTP_MM_WEIGHT_TILE_K_Q2_0 64 #define HTP_MM_WEIGHT_TILE_SIZE_Q2_0 HTP_TENSOR_TILE_SIZE_Q2_0 @@ -46,6 +50,8 @@ enum htp_mm_kernel_type { // HMX paths HTP_MM_KERNEL_HMX_2D, HTP_MM_KERNEL_HMX_BATCHED, + HTP_MM_KERNEL_HMX_W8A8_2D, + HTP_MM_KERNEL_HMX_W8A8_BATCHED, // HVX floating-point paths HTP_MM_KERNEL_HVX_F16_F16_VTCM, @@ -57,17 +63,60 @@ enum htp_mm_kernel_type { HTP_MM_KERNEL_HVX_QUANT_BLOCK, // parallel block-wise quantization }; +static inline bool htp_mm_kernel_is_hmx_w8a8(int32_t kt) { + return kt == HTP_MM_KERNEL_HMX_W8A8_2D || kt == HTP_MM_KERNEL_HMX_W8A8_BATCHED; +} + +static inline bool htp_mm_kernel_is_hmx_int(int32_t kt) { + return htp_mm_kernel_is_hmx_w8a8(kt); +} + +static inline bool htp_mm_kernel_is_hmx_2d(int32_t kt) { + return kt == HTP_MM_KERNEL_HMX_2D || kt == HTP_MM_KERNEL_HMX_W8A8_2D; +} + +static inline bool htp_mm_kernel_is_hmx_batched(int32_t kt) { + return kt == HTP_MM_KERNEL_HMX_BATCHED || kt == HTP_MM_KERNEL_HMX_W8A8_BATCHED; +} + +static inline bool htp_is_int_hmx_weight_type(int wtype) { + return wtype == HTP_TYPE_Q4_0 || wtype == HTP_TYPE_Q8_0 || + wtype == HTP_TYPE_IQ4_NL || wtype == HTP_TYPE_MXFP4 || + wtype == HTP_TYPE_Q5_0 || wtype == HTP_TYPE_Q1_0 || + wtype == HTP_TYPE_Q2_0 || wtype == HTP_TYPE_NVFP4 || + wtype == HTP_TYPE_Q3_K || wtype == HTP_TYPE_Q6_K || + wtype == HTP_TYPE_IQ2_XXS || wtype == HTP_TYPE_Q4_1 || + wtype == HTP_TYPE_Q4_K || wtype == HTP_TYPE_Q5_1 || + wtype == HTP_TYPE_Q5_K || wtype == HTP_TYPE_Q2_K; +} + +static inline uint32_t htp_int_hmx_min_k(int wtype) { + switch (wtype) { + case HTP_TYPE_IQ2_XXS: + case HTP_TYPE_Q2_K: + case HTP_TYPE_Q3_K: + case HTP_TYPE_Q4_K: + case HTP_TYPE_Q5_K: + case HTP_TYPE_Q6_K: + return 256u; + case HTP_TYPE_Q1_0: + return 128u; + default: + return 64u; + } +} + // Op-specific struct for precomputed matmul params struct htp_mm_kernel_params { uint8_t kernel_type; // enum htp_mm_kernel_type uint8_t pipeline; // 1 = pipelined execution, 0 = standard - uint8_t unused; // reserved uint8_t n_hmx; // 1 = use HMX, 0 = use HVX + uint8_t n_hvx; // Number of HVX threads - uint8_t n_hvx; // Number of threads to spawn - uint8_t n_act_hvx; // Number of threads for activation preparation + uint8_t n_act_hvx; // Number of HVX for activation preparation uint8_t n_prefetch; // Prefetch lookahead buffers/rows in VTCM uint8_t n_weights; // Number of weights for fused NX + uint8_t glu_op; // HTP_OP_GLU_* for fused MUL_MAT_NX_GLU (0 if none) int32_t m_chunk; // Row chunk size (M chunk) int32_t n_chunk; // Col chunk size (N chunk) @@ -76,6 +125,7 @@ struct htp_mm_kernel_params { int32_t act_row_size; // Row size for activation scratchpad int32_t vtcm_size; // Total required scratchpad size in VTCM int32_t vtcm_bias_size; // bias scratchpad size in VTCM (fused only) + int32_t hmx_n_groups; // Number of K superblocks for INT HMX kernels (1 for FP16) // Precomputed division values struct fastdiv_values div_ne12_ne1; @@ -85,6 +135,8 @@ struct htp_mm_kernel_params { struct fastdiv_values div_ne12; struct fastdiv_values div_n_act_hvx; struct fastdiv_values div_ne00_padded; + struct fastdiv_values div_hmx_n_groups; + struct fastdiv_values div_n_k_tiles; }; #if defined(__cplusplus) @@ -106,12 +158,13 @@ static inline int htp_mm_hmx_compute_chunks(size_t vtcm_total, size_t per_mn_cost, size_t m, size_t n, + size_t m_align, size_t m_block_cost, size_t n_block_cost, size_t * m_chunk_out, size_t * n_chunk_out, size_t * total_out) { - if (m == 0 || n == 0) return -1; + if (m == 0 || n == 0 || m_align == 0) return -1; if (vtcm_total <= overhead) return -1; if (per_n_cost == 0 || per_m_cost == 0 || per_mn_cost == 0) return -1; @@ -135,7 +188,7 @@ static inline int htp_mm_hmx_compute_chunks(size_t vtcm_total, { size_t remain = usable - n_fixed; size_t mc = remain / mc_denom; - mc = hex_align_down(mc, HTP_MM_HMX_TILE_N_ROWS); + mc = hex_align_down(mc, m_align); mc = hex_smin(mc, m); if (mc == 0) { @@ -214,8 +267,8 @@ static inline size_t htp_mm_tiled_act_row_size(int weight_type, uint32_t ne) { return htp_mm_weight_has_offset(weight_type) ? htp_mm_q8_1_tiled_row_size(ne) : htp_mm_q8_0_tiled_row_size(ne); } -static inline size_t htp_mm_act_raw_row_size(uint32_t ne) { - return hex_round_up(ne, HTP_MM_ACT_BLOCK_K) * sizeof(float); +static inline size_t htp_mm_act_raw_row_size(uint32_t ne, size_t act_elem_size) { + return hex_round_up(ne, HTP_MM_ACT_BLOCK_K) * act_elem_size; } static inline size_t htp_mm_round_up(size_t n, size_t m) { @@ -226,22 +279,40 @@ static inline bool htp_mm_hmx_pipeline(uint32_t m) { return m > 32; } -static inline void htp_mm_hmx_get_2d_chunk_costs( - int wtype, uint32_t k, bool pipeline, uint32_t aligned_tile_size, +static inline void htp_mm_hmx_get_2d_chunk_costs_ex( + int kernel_type, int wtype, uint32_t k, bool pipeline, uint32_t aligned_tile_size, size_t * size_per_n_out, size_t * size_per_m_out, size_t * size_per_mn_out ) { const bool is_quant = (wtype != HTP_TYPE_F16 && wtype != HTP_TYPE_F32 && wtype != HTP_TYPE_BF16); const size_t row_stride = htp_tensor_get_row_size(wtype, k); - const size_t vec_dot_size = k * sizeof(uint16_t); const uint32_t n_weight_tiles = k / htp_tensor_get_tile_k(wtype); const size_t qweight_row_stride = is_quant ? (size_t)(n_weight_tiles * aligned_tile_size) / 32 : 0; + if (htp_mm_kernel_is_hmx_int(kernel_type)) { + const size_t n_groups = (k + HTP_MM_HMX_W8A8_KGROUP - 1u) / HTP_MM_HMX_W8A8_KGROUP; + const size_t w_unpacked_per_n = (size_t) k * sizeof(uint8_t) + n_groups * 20; + + *size_per_n_out = (pipeline ? 2 : 1) * ((is_quant ? qweight_row_stride : row_stride) + w_unpacked_per_n); + *size_per_m_out = (size_t) k * sizeof(uint8_t) + n_groups * sizeof(float); + *size_per_mn_out = (pipeline ? 2 : 1) * n_groups * sizeof(uint16_t); + return; + } + + const size_t vec_dot_size = k * sizeof(uint16_t); *size_per_n_out = (pipeline ? 2 : 1) * (is_quant ? qweight_row_stride : row_stride) + (pipeline ? 2 * vec_dot_size : vec_dot_size); *size_per_m_out = vec_dot_size; *size_per_mn_out = (pipeline ? 2 : 1) * sizeof(uint16_t); } +static inline void htp_mm_hmx_get_2d_chunk_costs( + int wtype, uint32_t k, bool pipeline, uint32_t aligned_tile_size, + size_t * size_per_n_out, size_t * size_per_m_out, size_t * size_per_mn_out +) { + htp_mm_hmx_get_2d_chunk_costs_ex(HTP_MM_KERNEL_HMX_2D, wtype, k, pipeline, aligned_tile_size, + size_per_n_out, size_per_m_out, size_per_mn_out); +} + static inline void htp_mm_hmx_get_batched_chunk_costs( uint32_t k, uint32_t group_size, size_t * size_per_n_out, size_t * size_per_m_out, size_t * size_per_mn_out @@ -257,7 +328,7 @@ static inline size_t htp_mm_hmx_lut_bytes(int wtype) { } static inline size_t htp_mm_hmx_get_2d_overhead(int wtype, bool pipeline, bool is_matmul_id) { - size_t num_regions = pipeline ? 7 : (is_matmul_id ? 4 : 5); + size_t num_regions = pipeline ? 8 : (is_matmul_id ? 4 : 6); return num_regions * HTP_MM_HMX_TILE_SIZE + 256 + htp_mm_hmx_lut_bytes(wtype); } @@ -269,8 +340,14 @@ struct htp_mm_hmx_vtcm_layout { // Byte offsets from vtcm_base for each region size_t off_weight[2]; // [1] is only used when pipelined size_t off_act; + size_t off_act_scales; // INT HMX activation group scales d_a size_t off_act_f32; // fp32 activation conversion scratch size_t off_dst[2]; // [1] is only used when pipelined + size_t off_dst_up[2]; // double-buffered up HMX output for fused GLU ([1] when pipelined) + size_t off_wt_scales_gate[2]; // per-chunk gate weight scales for fused GLU + size_t off_wt_scales_up[2]; // per-chunk up weight scales for fused GLU ([1] when pipelined) + size_t off_res_in[2]; // double-buffered 2D residual/bias input slice (pipelined 2D MUL_MAT_ADD) + size_t off_res_out[2]; // double-buffered output DMA writeback slice (pipelined HMX 2D) size_t off_scratch[2]; // dequantization scratch pads size_t off_scales; // HMX scales (256 bytes) size_t off_bias; // bias in VTCM @@ -279,14 +356,22 @@ struct htp_mm_hmx_vtcm_layout { // Cached sizes of regions for HMX kernel use size_t weight_area_bytes; size_t act_area_bytes; + size_t act_scales_bytes; size_t act_f32_bytes; size_t output_area_bytes; + size_t wt_scales_bytes; + size_t res_in_bytes; + size_t res_out_bytes; size_t scratch_bytes[2]; + size_t weight_tiles_bytes; + size_t weight_bias_offset; + size_t weight_scales_offset; size_t act_head_stride; size_t bias_bytes; size_t lut_bytes; size_t total_bytes; + bool can_preissue_weight; }; struct htp_mm_hvx_vtcm_layout { @@ -309,7 +394,7 @@ struct htp_mm_hvx_vtcm_layout { size_t total_bytes; }; -static inline void htp_mm_hmx_vtcm_layout_build( +static inline void htp_mm_hmx_vtcm_layout_build_core( struct htp_mm_hmx_vtcm_layout * L, int kernel_type, int wtype, @@ -320,11 +405,33 @@ static inline void htp_mm_hmx_vtcm_layout_build( bool pipeline, uint32_t act_hvx, uint32_t aligned_tile_size, - size_t bias_size + size_t bias_size, + size_t res_in_elem_size, + size_t res_out_elem_size, + bool is_glu ) { size_t off = 0; - L->lut_bytes = 0; - L->off_lut = 0; + L->lut_bytes = 0; + L->off_lut = 0; + L->off_act_scales = 0; + L->can_preissue_weight = false; + L->act_scales_bytes = 0; + L->off_dst_up[0] = 0; + L->off_dst_up[1] = 0; + L->off_wt_scales_gate[0] = 0; + L->off_wt_scales_gate[1] = 0; + L->off_wt_scales_up[0] = 0; + L->off_wt_scales_up[1] = 0; + L->wt_scales_bytes = 0; + L->off_res_in[0] = 0; + L->off_res_in[1] = 0; + L->off_res_out[0] = 0; + L->off_res_out[1] = 0; + L->res_in_bytes = 0; + L->res_out_bytes = 0; + L->weight_tiles_bytes = 0; + L->weight_bias_offset = 0; + L->weight_scales_offset = 0; if (kernel_type == HTP_MM_KERNEL_HMX_BATCHED) { const size_t vec_dot_size = k * sizeof(uint16_t); @@ -333,6 +440,8 @@ static inline void htp_mm_hmx_vtcm_layout_build( const size_t activation_area_size = hex_align_up(group_size * act_head_stride * sizeof(uint16_t), HTP_MM_HMX_TILE_SIZE); const size_t output_area_size = hex_align_up(group_size * mc * nc * sizeof(uint16_t), HTP_MM_HMX_TILE_SIZE); const size_t scratch_area_size = hex_align_up(nc * vec_dot_size, HTP_MM_HMX_TILE_SIZE); + const size_t res_out_size = (res_out_elem_size > 0) + ? hex_align_up(mc * hex_align_up(nc * res_out_elem_size, 128), HTP_MM_HMX_TILE_SIZE) : 0; const size_t min_f32_size = hex_align_up(act_hvx * HTP_MM_DMA_ACT_MULTIPLIER * k * sizeof(float), 128); // Group A: Permanent activation tiles and scales @@ -349,6 +458,7 @@ static inline void htp_mm_hmx_vtcm_layout_build( VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_dst[1], output_area_size, false); VTCM_LAYOUT_ALLOC(off_group_b, off_scratch[0], scratch_area_size); VTCM_LAYOUT_ALLOC(off_group_b, off_scratch[1], scratch_area_size); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_res_out[0], res_out_size, res_out_size > 0); const size_t group_b_size = off_group_b - off_group_a; @@ -364,6 +474,7 @@ static inline void htp_mm_hmx_vtcm_layout_build( L->act_area_bytes = activation_area_size; L->act_f32_bytes = act_f32_size; L->output_area_bytes = output_area_size; + L->res_out_bytes = res_out_size; L->scratch_bytes[0] = scratch_area_size; L->scratch_bytes[1] = scratch_area_size; L->act_head_stride = act_head_stride; @@ -371,51 +482,108 @@ static inline void htp_mm_hmx_vtcm_layout_build( off = off_group_a + hex_smax(group_b_size, group_c_size); } else { - // HTP_MM_KERNEL_HMX_2D + // HTP_MM_KERNEL_HMX_2D / W8A8 + const bool is_int_hmx = htp_mm_kernel_is_hmx_int(kernel_type); const bool is_quant = (wtype != HTP_TYPE_F16 && wtype != HTP_TYPE_F32 && wtype != HTP_TYPE_BF16); const size_t row_stride = htp_tensor_get_row_size(wtype, k); - const size_t vec_dot_size = k * sizeof(uint16_t); const uint32_t n_weight_tiles = k / htp_tensor_get_tile_k(wtype); - const size_t min_f32_size = hex_align_up(act_hvx * HTP_MM_DMA_ACT_MULTIPLIER * k * sizeof(float), 128); + const uint32_t dma_act_mult = is_int_hmx ? 8u : HTP_MM_DMA_ACT_MULTIPLIER; + const size_t min_f32_size = hex_align_up((size_t) act_hvx * dma_act_mult * k * sizeof(float), 128); const size_t weight_area_size = is_quant ? hex_align_up((nc / 32) * n_weight_tiles * aligned_tile_size, HTP_MM_HMX_TILE_SIZE) : hex_align_up(nc * row_stride, HTP_MM_HMX_TILE_SIZE); - const size_t act_area_size = hex_align_up(mc * vec_dot_size, HTP_MM_HMX_TILE_SIZE); - const size_t output_area_size = hex_align_up(mc * nc * sizeof(__fp16), HTP_MM_HMX_TILE_SIZE); - const size_t scratch0_size = hex_align_up(nc * vec_dot_size, HTP_MM_HMX_TILE_SIZE); + size_t act_area_size = 0; + size_t act_scales_size = 0; + size_t output_area_size = 0; + size_t scratch0_size = 0; + + if (is_int_hmx) { + const size_t n_groups = (k + HTP_MM_HMX_W8A8_KGROUP - 1u) / HTP_MM_HMX_W8A8_KGROUP; + const size_t mc_pad = hex_align_up(mc, 64); + const size_t nc_pad = hex_align_up(nc, 32); + + act_area_size = hex_align_up(mc_pad * k * sizeof(uint8_t), HTP_MM_HMX_TILE_SIZE); + act_scales_size = hex_align_up(n_groups * mc_pad * sizeof(float), HTP_MM_HMX_TILE_SIZE); + output_area_size = hex_align_up(n_groups * mc_pad * nc_pad * sizeof(uint16_t), HTP_MM_HMX_TILE_SIZE); + + const size_t w_tiles_bytes = hex_align_up(nc_pad * k * sizeof(uint8_t), 256); + const size_t w_bias_bytes = hex_align_up((nc_pad / 32) * n_groups * 512, 256); + const size_t w_scales_bytes = hex_align_up(nc_pad * n_groups * sizeof(float), 256); + + L->weight_tiles_bytes = w_tiles_bytes; + L->weight_bias_offset = w_tiles_bytes; + L->weight_scales_offset = w_tiles_bytes + w_bias_bytes; + L->wt_scales_bytes = is_glu ? hex_align_up(w_scales_bytes, HTP_MM_HMX_TILE_SIZE) : 0; + scratch0_size = hex_align_up(w_tiles_bytes + w_bias_bytes + (is_glu ? 0 : w_scales_bytes), HTP_MM_HMX_TILE_SIZE); + } else { + const size_t vec_dot_size = k * sizeof(uint16_t); + act_area_size = hex_align_up(mc * vec_dot_size, HTP_MM_HMX_TILE_SIZE); + output_area_size = hex_align_up(mc * nc * sizeof(__fp16), HTP_MM_HMX_TILE_SIZE); + scratch0_size = hex_align_up(nc * vec_dot_size, HTP_MM_HMX_TILE_SIZE); + } + const size_t scratch1_size = pipeline ? scratch0_size : 0; + const size_t res_in_size = (pipeline && res_in_elem_size > 0) + ? hex_align_up(mc * hex_align_up(nc * res_in_elem_size, 128), HTP_MM_HMX_TILE_SIZE) : 0; + const size_t res_out_size = (res_out_elem_size > 0) + ? hex_align_up(mc * hex_align_up(nc * res_out_elem_size, 128), HTP_MM_HMX_TILE_SIZE) : 0; - // Group A: Scales and activation tiles (must not overlap with Group B or C) + // Group A: Scales and activation tiles (must not overlap with Group B or C) size_t off_group_a = 0; - VTCM_LAYOUT_ALLOC(off_group_a, off_scales, HTP_MM_HMX_TILE_SIZE); // Padded to 2K for alignment and future persistent data + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_a, off_scales, HTP_MM_HMX_TILE_SIZE, !is_int_hmx); VTCM_LAYOUT_ALLOC(off_group_a, off_act, act_area_size); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_a, off_act_scales, act_scales_size, act_scales_size > 0); VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_a, off_bias, hex_align_up(bias_size, HTP_MM_HMX_TILE_SIZE), bias_size > 0); // Group B: Compute-only buffers (starts at off_group_a) size_t off_group_b = off_group_a; VTCM_LAYOUT_ALLOC(off_group_b, off_weight[0], weight_area_size); VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_weight[1], weight_area_size, pipeline); + const size_t off_after_weights = off_group_b; VTCM_LAYOUT_ALLOC(off_group_b, off_dst[0], output_area_size); VTCM_LAYOUT_ALLOC(off_group_b, off_scratch[0], scratch0_size); VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_scratch[1], scratch0_size, pipeline); VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_dst[1], output_area_size, pipeline); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_dst_up[0], output_area_size, is_glu); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_dst_up[1], output_area_size, is_glu && pipeline); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_wt_scales_gate[0], L->wt_scales_bytes, is_glu); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_wt_scales_gate[1], L->wt_scales_bytes, is_glu && pipeline); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_wt_scales_up[0], L->wt_scales_bytes, is_glu); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_wt_scales_up[1], L->wt_scales_bytes, is_glu && pipeline); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_res_in[0], res_in_size, res_in_size > 0); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_res_in[1], res_in_size, res_in_size > 0); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_res_out[0], res_out_size, res_out_size > 0); + VTCM_LAYOUT_ALLOC_OPTIONAL(off_group_b, off_res_out[1], res_out_size, pipeline && res_out_size > 0); const size_t group_b_size = off_group_b - off_group_a; - // Group C: Activation prep temporary buffer (overlaps Group B, starting at off_group_a) - const size_t max_f32_size = act_hvx * 64 * k * sizeof(float); - const size_t act_f32_size = hex_align_up(hex_smin(max_f32_size, hex_smax(min_f32_size, group_b_size)), 128); - size_t off_group_c = off_group_a; - VTCM_LAYOUT_ALLOC(off_group_c, off_act_f32, act_f32_size); - - const size_t group_c_size = off_group_c - off_group_a; + // Group C: Activation prep temporary buffer (overlaps Group B). + // Place after weight staging when space permits so chunk-0 weight DMA overlaps activation quant. + const size_t max_f32_size = act_hvx * 64 * k * sizeof(float); + const size_t avail_after_w = off_group_b - off_after_weights; + size_t act_f32_size; + size_t group_c_size; + if (is_int_hmx && avail_after_w >= min_f32_size) { + act_f32_size = hex_align_down(hex_smin(max_f32_size, avail_after_w), 128); + L->off_act_f32 = off_after_weights; + group_c_size = group_b_size; + L->can_preissue_weight = true; + } else { + act_f32_size = hex_align_up(hex_smin(max_f32_size, hex_smax(min_f32_size, group_b_size)), 128); + size_t off_group_c = off_group_a; + VTCM_LAYOUT_ALLOC(off_group_c, off_act_f32, act_f32_size); + group_c_size = off_group_c - off_group_a; + } L->weight_area_bytes = weight_area_size; L->act_area_bytes = act_area_size; + L->act_scales_bytes = act_scales_size; L->act_f32_bytes = act_f32_size; L->output_area_bytes = output_area_size; + L->res_in_bytes = res_in_size; + L->res_out_bytes = res_out_size; L->scratch_bytes[0] = scratch0_size; L->scratch_bytes[1] = scratch1_size; L->act_head_stride = 0; @@ -430,6 +598,55 @@ static inline void htp_mm_hmx_vtcm_layout_build( L->total_bytes = off; } +static inline void htp_mm_hmx_vtcm_layout_build_ex( + struct htp_mm_hmx_vtcm_layout * L, + int kernel_type, + int wtype, + uint32_t k, + size_t mc, + size_t nc, + uint32_t group_size, + bool pipeline, + uint32_t act_hvx, + uint32_t aligned_tile_size, + size_t bias_size, + size_t res_in_elem_size, + size_t res_out_elem_size +) { + htp_mm_hmx_vtcm_layout_build_core(L, kernel_type, wtype, k, mc, nc, group_size, pipeline, act_hvx, aligned_tile_size, bias_size, res_in_elem_size, res_out_elem_size, false); +} + +static inline void htp_mm_hmx_vtcm_layout_build_glu( + struct htp_mm_hmx_vtcm_layout * L, + int kernel_type, + int wtype, + uint32_t k, + size_t mc, + size_t nc, + bool pipeline, + uint32_t act_hvx, + uint32_t aligned_tile_size, + size_t res_out_elem_size +) { + htp_mm_hmx_vtcm_layout_build_core(L, kernel_type, wtype, k, mc, nc, 1, pipeline, act_hvx, aligned_tile_size, 0, 0, res_out_elem_size, true); +} + +static inline void htp_mm_hmx_vtcm_layout_build( + struct htp_mm_hmx_vtcm_layout * L, + int kernel_type, + int wtype, + uint32_t k, + size_t mc, + size_t nc, + uint32_t group_size, + bool pipeline, + uint32_t act_hvx, + uint32_t aligned_tile_size, + size_t bias_size +) { + htp_mm_hmx_vtcm_layout_build_ex(L, kernel_type, wtype, k, mc, nc, group_size, pipeline, act_hvx, aligned_tile_size, bias_size, 0, 0); +} + static inline void htp_mm_hvx_vtcm_layout_build( struct htp_mm_hvx_vtcm_layout * L, int kernel_type, @@ -439,13 +656,14 @@ static inline void htp_mm_hvx_vtcm_layout_build( uint32_t n_hvx, size_t dst_row_size, size_t src0_row_size, - size_t act_row_size, + size_t act_elem_size, size_t bias_row_size, uint32_t n_prefetch, bool is_matmul_id, bool is_fused_nx ) { - (void)act_row_size; + const size_t raw_elem_size = (act_elem_size == sizeof(__fp16)) ? sizeof(__fp16) : sizeof(float); + const size_t hvx_dst_stage_bytes = 32u * 128u; // 4KB per HVX for DMA output staging size_t src0_sz = 0; size_t act_sz = 0; size_t bias_sz = bias_row_size > 0 ? htp_mm_round_up(bias_row_size, 128) : 0; @@ -461,12 +679,16 @@ static inline void htp_mm_hvx_vtcm_layout_build( size_t tiled_act_row_size = htp_mm_tiled_act_row_size(wtype, ne10); size_t q_act_sz = hex_round_up(tiled_act_row_size * act_nrows, 128); - size_t raw_row_size = htp_mm_act_raw_row_size(ne10); + size_t raw_row_size = htp_mm_act_raw_row_size(ne10, raw_elem_size); + + size_t dst_per_hvx = (act_nrows == 1) + ? hex_smax(htp_mm_round_up((dst_row_size + n_hvx - 1) / n_hvx, 128), hvx_dst_stage_bytes) + : hvx_dst_stage_bytes; src0_sz = weight_sz_per_hvx * n_hvx; // shared single-weight prefetch buffer act_sz = q_act_sz; // quantized activation buffer bias_sz = 0; - dst_sz = 0; + dst_sz = dst_per_hvx * n_hvx; act_raw_sz = hex_round_up(raw_row_size * act_nrows, 128); } else if (is_matmul_id) { const size_t act_row_size_tiled = htp_mm_tiled_act_row_size(wtype, ne10); @@ -477,23 +699,25 @@ static inline void htp_mm_hvx_vtcm_layout_build( act_sz = htp_mm_round_up(act_row_size_tiled * act_nrows, 256); - size_t raw_row_size = htp_mm_act_raw_row_size(ne10); + size_t raw_row_size = htp_mm_act_raw_row_size(ne10, raw_elem_size); + size_t dst_per_hvx = (act_nrows == 1) + ? hex_smax(htp_mm_round_up((dst_row_size + n_hvx - 1) / n_hvx, 128), hvx_dst_stage_bytes) + : hvx_dst_stage_bytes; src0_sz = src0_sz_per_hvx * n_hvx; - dst_sz = 0; + dst_sz = dst_per_hvx * n_hvx; bias_sz = 0; act_raw_sz = hex_round_up(raw_row_size * act_nrows, 128); } else { const size_t src0_row_size_padded = htp_mm_round_up(src0_row_size, 128); - const size_t dst_nrows = (act_nrows > 1) ? 0 : 1; switch (kernel_type) { case HTP_MM_KERNEL_HVX_F16_F16_VTCM: { size_t f16_act_row_size = htp_mm_round_up(ne10 * 2, 128); act_sz = htp_mm_round_up(f16_act_row_size * act_nrows, 256); src0_sz = htp_mm_round_up(n_prefetch * src0_row_size_padded, 256) * n_hvx; - dst_sz = dst_nrows > 0 ? htp_mm_round_up(dst_row_size, 128) * n_hvx : 0; - act_raw_sz = hex_round_up(hex_round_up(ne10 * sizeof(float), 128) * act_nrows, 128); + dst_sz = ((act_nrows == 1) ? hex_smax(htp_mm_round_up(dst_row_size, 128), hvx_dst_stage_bytes) : hvx_dst_stage_bytes) * n_hvx; + act_raw_sz = hex_round_up(hex_round_up(ne10 * raw_elem_size, 128) * act_nrows, 128); break; } case HTP_MM_KERNEL_HVX_F32_F32_VTCM: @@ -501,8 +725,10 @@ static inline void htp_mm_hvx_vtcm_layout_build( size_t f32_act_row_size = htp_mm_round_up(ne10 * 4, 128); act_sz = htp_mm_round_up(f32_act_row_size * act_nrows, 256); src0_sz = htp_mm_round_up(n_prefetch * src0_row_size_padded, 256) * n_hvx; - dst_sz = dst_nrows > 0 ? htp_mm_round_up(dst_row_size, 128) * n_hvx : 0; - act_raw_sz = 0; + dst_sz = ((act_nrows == 1) ? hex_smax(htp_mm_round_up(dst_row_size, 128), hvx_dst_stage_bytes) : hvx_dst_stage_bytes) * n_hvx; + act_raw_sz = (raw_elem_size == sizeof(__fp16)) + ? hex_round_up(hex_round_up(ne10 * sizeof(__fp16), 128) * act_nrows, 128) + : 0; break; } case HTP_MM_KERNEL_HVX_QUANT_BLOCK: @@ -516,9 +742,11 @@ static inline void htp_mm_hvx_vtcm_layout_build( src0_sz = tiled_vtcm_size * n_hvx; act_sz = htp_mm_round_up(q_act_row_size * act_nrows, 256); - size_t dst_slice_per_hvx = (dst_nrows > 0 && act_nrows == 1) ? htp_mm_round_up((dst_row_size + n_hvx - 1) / n_hvx, 128) : 0; - dst_sz = dst_slice_per_hvx * n_hvx; - size_t raw_row_size = htp_mm_act_raw_row_size(ne10); + size_t dst_per_hvx = (act_nrows == 1) + ? hex_smax(htp_mm_round_up((dst_row_size + n_hvx - 1) / n_hvx, 128), hvx_dst_stage_bytes) + : hvx_dst_stage_bytes; + dst_sz = dst_per_hvx * n_hvx; + size_t raw_row_size = htp_mm_act_raw_row_size(ne10, raw_elem_size); act_raw_sz = hex_round_up(raw_row_size * act_nrows, 128); break; } @@ -561,17 +789,18 @@ static inline bool htp_mm_hvx_solve_vtcm_params( uint32_t n_hvx, size_t dst_row_size, size_t src0_row_size, - size_t act_row_size, + size_t act_elem_size, size_t bias_row_size, uint32_t n_prefetch, size_t vtcm_budget, struct htp_mm_hvx_vtcm_layout * L_out, uint32_t * m_chunk_out ) { + const size_t raw_elem_size = (act_elem_size == sizeof(__fp16)) ? sizeof(__fp16) : sizeof(float); struct htp_mm_hvx_vtcm_layout L; htp_mm_hvx_vtcm_layout_build( &L, kernel_type, wtype, ne10, act_nrows, n_hvx, - dst_row_size, src0_row_size, act_row_size, bias_row_size, n_prefetch, false, false + dst_row_size, src0_row_size, raw_elem_size, bias_row_size, n_prefetch, false, false ); if (L.total_bytes <= vtcm_budget) { @@ -600,7 +829,7 @@ static inline bool htp_mm_hvx_solve_vtcm_params( size_t eff_row_size = row_size; if (kernel_type == HTP_MM_KERNEL_HVX_QUANT_ROW || kernel_type == HTP_MM_KERNEL_HVX_QUANT_BLOCK) { - eff_row_size += htp_mm_act_raw_row_size(ne10); + eff_row_size += htp_mm_act_raw_row_size(ne10, raw_elem_size); } uint32_t m_chunk = (uint32_t) (avail_act / eff_row_size); @@ -616,14 +845,22 @@ static inline bool htp_mm_hvx_solve_vtcm_params( htp_mm_hvx_vtcm_layout_build( &L, kernel_type, wtype, ne10, m_chunk, n_hvx, - dst_row_size, src0_row_size, act_row_size, bias_row_size, n_prefetch, false, false + dst_row_size, src0_row_size, raw_elem_size, bias_row_size, n_prefetch, false, false ); while (m_chunk > 2 && L.total_bytes > vtcm_budget) { m_chunk -= 2; htp_mm_hvx_vtcm_layout_build( &L, kernel_type, wtype, ne10, m_chunk, n_hvx, - dst_row_size, src0_row_size, act_row_size, bias_row_size, n_prefetch, false, false + dst_row_size, src0_row_size, raw_elem_size, bias_row_size, n_prefetch, false, false + ); + } + + if (m_chunk > 1 && L.total_bytes > vtcm_budget) { + m_chunk = 1; + htp_mm_hvx_vtcm_layout_build( + &L, kernel_type, wtype, ne10, m_chunk, n_hvx, + dst_row_size, src0_row_size, raw_elem_size, bias_row_size, n_prefetch, false, false ); } @@ -636,19 +873,33 @@ static inline bool htp_mm_hvx_solve_vtcm_params( return false; } -static inline size_t htp_mm_hmx_get_2d_vtcm_size( - int wtype, uint32_t k, size_t mc, size_t nc, bool pipeline, uint32_t act_hvx, uint32_t aligned_tile_size, size_t bias_size +static inline size_t htp_mm_hmx_get_2d_vtcm_size_core( + int kernel_type, int wtype, uint32_t k, size_t mc, size_t nc, bool pipeline, uint32_t act_hvx, uint32_t aligned_tile_size, size_t bias_size, + size_t res_in_elem_size, size_t res_out_elem_size, bool is_glu ) { struct htp_mm_hmx_vtcm_layout L; - htp_mm_hmx_vtcm_layout_build(&L, HTP_MM_KERNEL_HMX_2D, wtype, k, mc, nc, 1, pipeline, act_hvx, aligned_tile_size, bias_size); + htp_mm_hmx_vtcm_layout_build_core(&L, kernel_type, wtype, k, mc, nc, 1, pipeline, act_hvx, aligned_tile_size, bias_size, res_in_elem_size, res_out_elem_size, is_glu); return L.total_bytes; } +static inline size_t htp_mm_hmx_get_2d_vtcm_size_ex( + int kernel_type, int wtype, uint32_t k, size_t mc, size_t nc, bool pipeline, uint32_t act_hvx, uint32_t aligned_tile_size, size_t bias_size, + size_t res_in_elem_size, size_t res_out_elem_size +) { + return htp_mm_hmx_get_2d_vtcm_size_core(kernel_type, wtype, k, mc, nc, pipeline, act_hvx, aligned_tile_size, bias_size, res_in_elem_size, res_out_elem_size, false); +} + +static inline size_t htp_mm_hmx_get_2d_vtcm_size( + int wtype, uint32_t k, size_t mc, size_t nc, bool pipeline, uint32_t act_hvx, uint32_t aligned_tile_size, size_t bias_size +) { + return htp_mm_hmx_get_2d_vtcm_size_ex(HTP_MM_KERNEL_HMX_2D, wtype, k, mc, nc, pipeline, act_hvx, aligned_tile_size, bias_size, 0, 0); +} + static inline size_t htp_mm_hmx_get_batched_vtcm_size( - int wtype, uint32_t k, size_t mc, size_t nc, uint32_t group_size, bool pipeline, uint32_t act_hvx, size_t bias_size) { + int wtype, uint32_t k, size_t mc, size_t nc, uint32_t group_size, bool pipeline, uint32_t act_hvx, size_t bias_size, size_t res_out_elem_size) { (void)pipeline; struct htp_mm_hmx_vtcm_layout L; - htp_mm_hmx_vtcm_layout_build(&L, HTP_MM_KERNEL_HMX_BATCHED, wtype, k, mc, nc, group_size, false, act_hvx, 0, bias_size); + htp_mm_hmx_vtcm_layout_build_ex(&L, HTP_MM_KERNEL_HMX_BATCHED, wtype, k, mc, nc, group_size, false, act_hvx, 0, bias_size, 0, res_out_elem_size); return L.total_bytes; } @@ -661,6 +912,7 @@ static inline bool htp_mm_hmx_solve_batched_params( int n_hvx, bool pipeline, size_t bias_size, + size_t res_out_elem_size, size_t vtcm_budget, size_t * m_chunk_out, size_t * n_chunk_out, @@ -678,15 +930,16 @@ static inline bool htp_mm_hmx_solve_batched_params( size_t group_overhead = htp_mm_hmx_get_batched_overhead() + (bias_size > 0 ? hex_align_up(bias_size, HTP_MM_HMX_TILE_SIZE) : 0); size_t group_size_per_n, group_size_per_m, group_size_per_mn; htp_mm_hmx_get_batched_chunk_costs(k, group_size, &group_size_per_n, &group_size_per_m, &group_size_per_mn); + group_size_per_mn += res_out_elem_size; size_t m_chunk_candidate = 0; size_t n_chunk_candidate = 0; size_t vtcm_size_candidate = 0; - if (htp_mm_hmx_compute_chunks(vtcm_budget, group_overhead, group_size_per_n, group_size_per_m, group_size_per_mn, hex_align_up(ne11, 32), ne01_padded, + if (htp_mm_hmx_compute_chunks(vtcm_budget, group_overhead, group_size_per_n, group_size_per_m, group_size_per_mn, hex_align_up(ne11, 32), ne01_padded, HTP_MM_HMX_TILE_N_ROWS, (size_t) ne01_padded * HTP_MM_HMX_COST_W_DEQUANT, (size_t) ne11 * HTP_MM_HMX_COST_A_CONVERT, &m_chunk_candidate, &n_chunk_candidate, &vtcm_size_candidate) == 0) { - size_t exact_size = htp_mm_hmx_get_batched_vtcm_size(wtype, k, m_chunk_candidate, n_chunk_candidate, group_size, pipeline, act_hvx, bias_size); + size_t exact_size = htp_mm_hmx_get_batched_vtcm_size(wtype, k, m_chunk_candidate, n_chunk_candidate, group_size, pipeline, act_hvx, bias_size, res_out_elem_size); if (exact_size <= vtcm_budget) { size_t mblocks = ((size_t) ne11 + m_chunk_candidate - 1) / m_chunk_candidate; if (mblocks < best_mblocks || (mblocks == best_mblocks && act_hvx > best_act_hvx)) { @@ -715,7 +968,8 @@ static inline bool htp_mm_hmx_solve_batched_params( return false; } -static inline bool htp_mm_hmx_solve_2d_params( +static inline bool htp_mm_hmx_solve_2d_params_core( + int kernel_type, int wtype, uint32_t k, uint32_t m_id_rows, @@ -727,62 +981,247 @@ static inline bool htp_mm_hmx_solve_2d_params( bool is_matmul_id, uint32_t aligned_tile_size, size_t bias_size, + size_t res_in_elem_size, + size_t res_out_elem_size, + bool is_glu, size_t vtcm_budget, size_t * m_chunk_out, size_t * n_chunk_out, int * act_hvx_out, size_t * vtcm_size_out ) { - size_t best_mblocks = SIZE_MAX; - int best_act_hvx = 0; - size_t best_m_chunk = 0; - size_t best_n_chunk = 0; - size_t best_vtcm_size = 0; + const bool is_int_hmx = htp_mm_kernel_is_hmx_int(kernel_type); + const size_t m_align = is_int_hmx ? 64u : HTP_MM_HMX_TILE_N_ROWS; + const size_t n_total = hex_align_up((size_t) ne01_padded, HTP_MM_HMX_TILE_N_COLS); + const size_t m_target = is_matmul_id ? hex_align_up((size_t) m_id_rows, m_align) + : hex_align_up((size_t) ne11_padded, m_align); + const size_t m_rows = (m_for_cost > 0) ? (size_t) m_for_cost : m_target; + if (m_target == 0 || n_total == 0) { + return false; + } - const int m_for_chunks = is_matmul_id ? hex_align_up(m_id_rows, 32) : ne11_padded; + size_t per_n_approx = 0, per_m_approx = 0, per_mn_approx = 0; + htp_mm_hmx_get_2d_chunk_costs_ex(kernel_type, wtype, k, pipeline, aligned_tile_size, + &per_n_approx, &per_m_approx, &per_mn_approx); + if (is_glu) { + const size_t n_groups = (k + HTP_MM_HMX_W8A8_KGROUP - 1u) / HTP_MM_HMX_W8A8_KGROUP; + per_mn_approx += (pipeline ? 2u : 1u) * (is_int_hmx ? (n_groups * sizeof(uint16_t)) : sizeof(__fp16)); + } + per_mn_approx += (pipeline ? 2u : 1u) * res_out_elem_size + (pipeline ? 2u * res_in_elem_size : 0u); + const size_t base_overhead = htp_mm_hmx_get_2d_overhead(wtype, pipeline, is_matmul_id) + + (is_int_hmx ? (HTP_MM_HMX_TILE_SIZE + (pipeline ? 2u : 1u) * 768u) : 0u) + + ((is_glu && is_int_hmx) ? ((pipeline ? 4u : 2u) * HTP_MM_HMX_TILE_SIZE) : 0u) + + (bias_size > 0 ? hex_align_up(bias_size, HTP_MM_HMX_TILE_SIZE) : 0u); + if (vtcm_budget <= base_overhead || per_n_approx == 0 || per_m_approx == 0 || per_mn_approx == 0) { + return false; + } + const size_t usable = vtcm_budget - base_overhead; + + const size_t min_par_nc = (size_t) (n_hvx > 0 ? n_hvx : 1) * HTP_MM_HMX_TILE_N_COLS; + size_t nc_cap = n_total; + if (pipeline) { + if (n_total >= 4u * min_par_nc) { + nc_cap = hex_align_down(n_total / 4u, HTP_MM_HMX_TILE_N_COLS); + } else if (n_total >= 2u * min_par_nc) { + nc_cap = hex_align_down(n_total / 2u, HTP_MM_HMX_TILE_N_COLS); + } + if (nc_cap > 512u && min_par_nc <= 512u) { + nc_cap = 512u; + } + } + const size_t nc_hi = hex_align_down(hex_smin(nc_cap, usable / per_n_approx), HTP_MM_HMX_TILE_N_COLS); + if (nc_hi < HTP_MM_HMX_TILE_N_COLS) { + return false; + } + // Avoid 1-tile (64B fp16) column chunks when >=2 tiles fit, preventing partial-cacheline RFO stores in O-PROC + const size_t min_nc_pref = (n_total >= 2u * HTP_MM_HMX_TILE_N_COLS && nc_hi >= 2u * HTP_MM_HMX_TILE_N_COLS) + ? (2u * HTP_MM_HMX_TILE_N_COLS) + : HTP_MM_HMX_TILE_N_COLS; + + size_t best_mblocks = SIZE_MAX; + size_t best_ncost = SIZE_MAX; + int best_act_hvx = 0; + size_t best_mc = 0; + size_t best_nc = 0; + size_t best_vtcm_size = 0; - int act_hvx = n_hvx; - while (act_hvx >= 1) { - size_t simple_2d_overhead = htp_mm_hmx_get_2d_overhead(wtype, pipeline, is_matmul_id) + (bias_size > 0 ? hex_align_up(bias_size, HTP_MM_HMX_TILE_SIZE) : 0); - size_t simple_2d_size_per_n, simple_2d_size_per_m, simple_2d_size_per_mn; - htp_mm_hmx_get_2d_chunk_costs(wtype, k, pipeline, aligned_tile_size, &simple_2d_size_per_n, &simple_2d_size_per_m, &simple_2d_size_per_mn); + for (int act_hvx = n_hvx; act_hvx >= 1; act_hvx = (act_hvx == 1) ? 0 : (act_hvx / 2)) { + const uint32_t layout_act_hvx = (uint32_t) act_hvx; - size_t m_chunk_candidate = 0; - size_t n_chunk_candidate = 0; - size_t vtcm_size_candidate = 0; + for (size_t nc = nc_hi; nc >= HTP_MM_HMX_TILE_N_COLS; nc -= HTP_MM_HMX_TILE_N_COLS) { + if (nc < min_nc_pref && best_act_hvx > 0) { + break; + } + size_t n_fixed = 0, ncmn = 0, mc_denom = 0; + if (hex_mul_overflow(nc, per_n_approx, &n_fixed) || n_fixed >= usable) { + if (nc == HTP_MM_HMX_TILE_N_COLS) break; + continue; + } + if (hex_mul_overflow(nc, per_mn_approx, &ncmn) || + hex_add_overflow(per_m_approx, ncmn, &mc_denom) || mc_denom == 0) { + if (nc == HTP_MM_HMX_TILE_N_COLS) break; + continue; + } - if (htp_mm_hmx_compute_chunks(vtcm_budget, simple_2d_overhead, simple_2d_size_per_n, simple_2d_size_per_m, simple_2d_size_per_mn, m_for_chunks, ne01_padded, - (size_t) ne01_padded * HTP_MM_HMX_COST_W_DEQUANT, (size_t) m_for_cost * HTP_MM_HMX_COST_A_CONVERT, - &m_chunk_candidate, &n_chunk_candidate, &vtcm_size_candidate) == 0) { - size_t exact_size = htp_mm_hmx_get_2d_vtcm_size(wtype, k, m_chunk_candidate, n_chunk_candidate, pipeline, is_matmul_id ? 0 : act_hvx, aligned_tile_size, bias_size); - if (exact_size <= vtcm_budget) { - size_t mblocks = ((size_t) m_for_cost + m_chunk_candidate - 1) / m_chunk_candidate; - if (mblocks < best_mblocks || (mblocks == best_mblocks && act_hvx > best_act_hvx)) { - best_mblocks = mblocks; - best_act_hvx = act_hvx; - best_m_chunk = m_chunk_candidate; - best_n_chunk = n_chunk_candidate; - best_vtcm_size = exact_size; + size_t mc = hex_align_down((usable - n_fixed) / mc_denom, m_align); + mc = hex_smin(mc, m_target); + while (mc >= m_align) { + size_t exact = htp_mm_hmx_get_2d_vtcm_size_core( + kernel_type, wtype, k, mc, nc, pipeline, layout_act_hvx, aligned_tile_size, bias_size, res_in_elem_size, res_out_elem_size, is_glu); + if (exact <= vtcm_budget) { + const size_t mblocks = (m_rows + mc - 1u) / mc; + size_t mc_tight = (mblocks > 1u) + ? hex_smin(mc, hex_align_up((m_rows + mblocks - 1u) / mblocks, m_align)) + : mc; + if (mc_tight != mc) { + size_t exact_tight = htp_mm_hmx_get_2d_vtcm_size_core( + kernel_type, wtype, k, mc_tight, nc, pipeline, layout_act_hvx, aligned_tile_size, bias_size, res_in_elem_size, res_out_elem_size, is_glu); + if (exact_tight <= vtcm_budget) { + mc = mc_tight; + exact = exact_tight; + } + } + + const size_t nblocks = (n_total + nc - 1u) / nc; + const size_t col_tiles = nc / HTP_MM_HMX_TILE_N_COLS; + const size_t hvx_cnt = (n_hvx > 0) ? (size_t) n_hvx : 1u; + const size_t eff_nc = (col_tiles >= hvx_cnt) + ? (((col_tiles + hvx_cnt - 1u) / hvx_cnt) * hvx_cnt * HTP_MM_HMX_TILE_N_COLS) + : nc; + const size_t pipe_tail = pipeline ? ((nblocks == 1u) ? (2u * eff_nc) : eff_nc) : 0u; + const size_t ncost = nblocks * eff_nc + pipe_tail + nblocks * HTP_MM_HMX_TILE_N_COLS; + + const bool better = + (mblocks < best_mblocks) || + (mblocks == best_mblocks && ncost < best_ncost) || + (mblocks == best_mblocks && ncost == best_ncost && act_hvx > best_act_hvx) || + (mblocks == best_mblocks && ncost == best_ncost && act_hvx == best_act_hvx && nc < best_nc); + + if (better) { + best_mblocks = mblocks; + best_ncost = ncost; + best_act_hvx = act_hvx; + best_mc = mc; + best_nc = nc; + best_vtcm_size = exact; + } + break; } + mc -= m_align; } + + if ((best_mblocks == 1u && best_nc >= n_total) || nc == HTP_MM_HMX_TILE_N_COLS) break; } - if (act_hvx == 1) { - act_hvx = 0; - } else { - act_hvx /= 2; - } + if (best_mblocks == 1u && (best_nc >= n_total || best_nc >= 128u)) break; } if (best_act_hvx > 0) { - *m_chunk_out = best_m_chunk; - *n_chunk_out = best_n_chunk; + *m_chunk_out = best_mc; + *n_chunk_out = best_nc; + *act_hvx_out = best_act_hvx; *vtcm_size_out = best_vtcm_size; - *act_hvx_out = best_act_hvx; return true; } return false; } +static inline bool htp_mm_hmx_solve_2d_params_ex( + int kernel_type, + int wtype, + uint32_t k, + uint32_t m_id_rows, + uint32_t ne01_padded, + uint32_t ne11_padded, + uint32_t m_for_cost, + int n_hvx, + bool pipeline, + bool is_matmul_id, + uint32_t aligned_tile_size, + size_t bias_size, + size_t res_in_elem_size, + size_t res_out_elem_size, + size_t vtcm_budget, + size_t * m_chunk_out, + size_t * n_chunk_out, + int * act_hvx_out, + size_t * vtcm_size_out +) { + return htp_mm_hmx_solve_2d_params_core(kernel_type, wtype, k, m_id_rows, ne01_padded, ne11_padded, m_for_cost, + n_hvx, pipeline, is_matmul_id, aligned_tile_size, bias_size, res_in_elem_size, + res_out_elem_size, false, vtcm_budget, m_chunk_out, n_chunk_out, act_hvx_out, vtcm_size_out); +} + +static inline bool htp_mm_hmx_solve_2d_params_glu( + int kernel_type, + int wtype, + uint32_t k, + uint32_t ne01_padded, + uint32_t ne11_padded, + uint32_t m_for_cost, + int n_hvx, + bool pipeline, + uint32_t aligned_tile_size, + size_t res_out_elem_size, + size_t vtcm_budget, + size_t * m_chunk_out, + size_t * n_chunk_out, + int * act_hvx_out, + size_t * vtcm_size_out +) { + return htp_mm_hmx_solve_2d_params_core(kernel_type, wtype, k, 0, ne01_padded, ne11_padded, m_for_cost, + n_hvx, pipeline, false, aligned_tile_size, 0, 0, + res_out_elem_size, true, vtcm_budget, m_chunk_out, n_chunk_out, act_hvx_out, vtcm_size_out); +} + +static inline bool htp_mm_int_hmx_solve_2d_params( + int kernel_type, + int wtype, + uint32_t k, + uint32_t m_id_rows, + uint32_t ne01_padded, + uint32_t ne11_padded, + uint32_t m_for_cost, + int n_hvx, + bool pipeline, + bool is_matmul_id, + uint32_t aligned_tile_size, + size_t bias_size, + size_t res_out_elem_size, + size_t vtcm_budget, + size_t * m_chunk_out, + size_t * n_chunk_out, + int * act_hvx_out, + size_t * vtcm_size_out +) { + return htp_mm_hmx_solve_2d_params_ex(kernel_type, wtype, k, m_id_rows, ne01_padded, ne11_padded, m_for_cost, + n_hvx, pipeline, is_matmul_id, aligned_tile_size, bias_size, 0, res_out_elem_size, vtcm_budget, + m_chunk_out, n_chunk_out, act_hvx_out, vtcm_size_out); +} + +static inline bool htp_mm_hmx_solve_2d_params( + int wtype, + uint32_t k, + uint32_t m_id_rows, + uint32_t ne01_padded, + uint32_t ne11_padded, + uint32_t m_for_cost, + int n_hvx, + bool pipeline, + bool is_matmul_id, + uint32_t aligned_tile_size, + size_t bias_size, + size_t res_out_elem_size, + size_t vtcm_budget, + size_t * m_chunk_out, + size_t * n_chunk_out, + int * act_hvx_out, + size_t * vtcm_size_out +) { + return htp_mm_hmx_solve_2d_params_ex(HTP_MM_KERNEL_HMX_2D, wtype, k, m_id_rows, ne01_padded, ne11_padded, m_for_cost, + n_hvx, pipeline, is_matmul_id, aligned_tile_size, bias_size, 0, res_out_elem_size, vtcm_budget, + m_chunk_out, n_chunk_out, act_hvx_out, vtcm_size_out); +} + #ifdef __cplusplus } #endif diff --git a/ggml/src/ggml-hexagon/htp/pad-ops.c b/ggml/src/ggml-hexagon/htp/pad-ops.c index b77e95a902bb..61db555a9ff6 100644 --- a/ggml/src/ggml-hexagon/htp/pad-ops.c +++ b/ggml/src/ggml-hexagon/htp/pad-ops.c @@ -1,13 +1,8 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include -#include - #include "dma-queue.h" +#include "dma-pipeline.h" #include "hvx-utils.h" #define GGML_COMMON_DECL_C @@ -20,7 +15,7 @@ #include "htp-vtcm.h" #include "pad-ops.h" -/* Circular wrap: maps any integer x into [0, n) */ +// Circular wrap: maps any integer x into [0, n) static inline uint32_t wrap_around(int32_t x, uint32_t n, const struct fastdiv_values * div_n) { if (x >= 0) { const uint32_t ux = (uint32_t) x; @@ -31,54 +26,33 @@ static inline uint32_t wrap_around(int32_t x, uint32_t n, const struct fastdiv_v return rem ? (n - rem) : 0; } -/* Decompose a flat dst row index into (i1, i2, i3) */ +// Decompose a flat dst row index into (i1, i2, i3) static inline void pad_decompose_row(uint32_t ir, uint32_t ne1, uint32_t ne2, const struct htp_pad_kernel_params * kparams, - uint32_t *i1, uint32_t *i2, uint32_t *i3) { + uint32_t * i1, uint32_t * i2, uint32_t * i3) { *i3 = fastdiv(ir, &kparams->div_ne1_ne2); const uint32_t rem = ir - (*i3) * (ne1 * ne2); *i2 = fastdiv(rem, &kparams->div_ne1); *i1 = rem - (*i2) * ne1; } -/* Return non-zero if row (i1,i2,i3) falls in the non-padded interior */ +// Return non-zero if row (i1,i2,i3) falls in the non-padded interior static inline int pad_is_interior(uint32_t i1, uint32_t i2, uint32_t i3, - int32_t lp1, int32_t rp1, uint32_t ne1, - int32_t lp2, int32_t rp2, uint32_t ne2, - int32_t lp3, int32_t rp3, uint32_t ne3) { - return ((int32_t)i1 >= lp1 && (int32_t)i1 < (int32_t)ne1 - rp1) && - ((int32_t)i2 >= lp2 && (int32_t)i2 < (int32_t)ne2 - rp2) && - ((int32_t)i3 >= lp3 && (int32_t)i3 < (int32_t)ne3 - rp3); -} - -/* Compute the DDR src row pointer for a zero-pad interior row */ -static inline const uint8_t * pad_src_row_ptr(const struct htp_tensor * src, - uint32_t i1, uint32_t i2, uint32_t i3, - int32_t lp1, int32_t lp2, int32_t lp3) { - return (const uint8_t *) src->data - + (i1 - (uint32_t)lp1) * src->nb[1] - + (i2 - (uint32_t)lp2) * src->nb[2] - + (i3 - (uint32_t)lp3) * src->nb[3]; + int32_t lp1, int32_t rp1, uint32_t ne1, + int32_t lp2, int32_t rp2, uint32_t ne2, + int32_t lp3, int32_t rp3, uint32_t ne3) { + return ((int32_t) i1 >= lp1 && (int32_t) i1 < (int32_t) ne1 - rp1) && + ((int32_t) i2 >= lp2 && (int32_t) i2 < (int32_t) ne2 - rp2) && + ((int32_t) i3 >= lp3 && (int32_t) i3 < (int32_t) ne3 - rp3); } static inline dma_addr_t pad_src_row_data(const struct htp_tensor * src, uint32_t i1, uint32_t i2, uint32_t i3, int32_t lp1, int32_t lp2, int32_t lp3) { return src->data - + (i1 - (uint32_t)lp1) * src->nb[1] - + (i2 - (uint32_t)lp2) * src->nb[2] - + (i3 - (uint32_t)lp3) * src->nb[3]; -} - -/* Compute the DDR src row pointer for a circular row (wrap-around indexing) */ -static inline const uint8_t * pad_circ_src_row_ptr(const struct htp_tensor * src, - const struct htp_pad_kernel_params * kparams, - uint32_t i1, uint32_t i2, uint32_t i3, - int32_t lp1, int32_t lp2, int32_t lp3) { - return (const uint8_t *) src->data - + wrap_around((int32_t)i1 - lp1, src->ne[1], &kparams->div_ne01) * src->nb[1] - + wrap_around((int32_t)i2 - lp2, src->ne[2], &kparams->div_ne02) * src->nb[2] - + wrap_around((int32_t)i3 - lp3, src->ne[3], &kparams->div_ne03) * src->nb[3]; + + (size_t) (i1 - (uint32_t) lp1) * src->nb[1] + + (size_t) (i2 - (uint32_t) lp2) * src->nb[2] + + (size_t) (i3 - (uint32_t) lp3) * src->nb[3]; } static inline dma_addr_t pad_circ_src_row_data(const struct htp_tensor * src, @@ -86,14 +60,18 @@ static inline dma_addr_t pad_circ_src_row_data(const struct htp_tensor * src, uint32_t i1, uint32_t i2, uint32_t i3, int32_t lp1, int32_t lp2, int32_t lp3) { return src->data - + wrap_around((int32_t)i1 - lp1, src->ne[1], &kparams->div_ne01) * src->nb[1] - + wrap_around((int32_t)i2 - lp2, src->ne[2], &kparams->div_ne02) * src->nb[2] - + wrap_around((int32_t)i3 - lp3, src->ne[3], &kparams->div_ne03) * src->nb[3]; + + (size_t) wrap_around((int32_t) i1 - lp1, src->ne[1], &kparams->div_ne01) * src->nb[1] + + (size_t) wrap_around((int32_t) i2 - lp2, src->ne[2], &kparams->div_ne02) * src->nb[2] + + (size_t) wrap_around((int32_t) i3 - lp3, src->ne[3], &kparams->div_ne03) * src->nb[3]; } struct htp_pad_context { - struct htp_ops_context * octx; + struct htp_ops_context * octx; const struct htp_pad_kernel_params * kparams; + uint8_t * vtcm_src0; + uint8_t * vtcm_dst; + size_t src0_bytes_per_hvx; + size_t dst_bytes_per_hvx; int32_t lp0, rp0; int32_t lp1, rp1; @@ -103,385 +81,299 @@ struct htp_pad_context { uint32_t nrows_per_hvx; uint32_t total_dst_rows; uint32_t row_start; + uint32_t chunk_elems; size_t type_size; + size_t chunk_bytes_aligned; +}; - // Row sizes for DMA kernel (populated when VTCM is available) - size_t src_row_size; - size_t src_row_size_aligned; - size_t dst_row_size; - size_t dst_row_size_aligned; +struct pad_pipe_state { + const struct htp_tensor * src; + const struct htp_tensor * dst; + const struct htp_pad_kernel_params * kparams; + size_t type_size; + size_t chunk_bytes_aligned; + int32_t lp0, rp0; + int32_t lp1, rp1; + int32_t lp2, rp2; + int32_t lp3, rp3; + uint32_t ne00; + uint32_t ne0; + uint32_t ne1; + uint32_t ne2; + uint32_t ne3; + uint32_t nb1; + uint32_t nb2; + uint32_t nb3; + uint32_t chunk_elems; + uint32_t row; + uint32_t row_end; + uint32_t off; }; -#define htp_pad_preamble \ - const struct htp_tensor * src = octx->src[0]; \ - const struct htp_tensor * dst = octx->dst; \ - \ - const uint32_t ne00 = src->ne[0]; \ - const uint32_t nb00 = src->nb[0]; \ - \ - const uint32_t ne0 = dst->ne[0]; \ - const uint32_t ne1 = dst->ne[1]; \ - const uint32_t ne2 = dst->ne[2]; \ - const uint32_t ne3 = dst->ne[3]; \ - \ - const uint32_t nb1 = dst->nb[1]; \ - const uint32_t nb2 = dst->nb[2]; \ - const uint32_t nb3 = dst->nb[3]; \ - \ - const int32_t lp0 = pctx->lp0, rp0 = pctx->rp0; \ - const int32_t lp1 = pctx->lp1, rp1 = pctx->rp1; \ - const int32_t lp2 = pctx->lp2, rp2 = pctx->rp2; \ - const int32_t lp3 = pctx->lp3, rp3 = pctx->rp3; \ - \ - const size_t type_size = pctx->type_size; \ - \ - const uint32_t row_start = pctx->row_start + pctx->nrows_per_hvx * ith; \ - const uint32_t row_end = MIN(row_start + pctx->nrows_per_hvx, pctx->row_start + pctx->total_dst_rows); +// --------------------------------------------------------------------------- +// Shared task iteration and output writeback +// --------------------------------------------------------------------------- +static bool pad_next_task(void * ctx, struct dma_pipe_task * task) { + struct pad_pipe_state * s = (struct pad_pipe_state *) ctx; + if (s->row >= s->row_end) { + return false; + } -#define htp_pad_dma_preamble \ - const size_t src_row_size = pctx->src_row_size; \ - const size_t src_row_size_aligned = pctx->src_row_size_aligned; \ - const size_t dst_row_size = pctx->dst_row_size; \ - const size_t dst_row_size_aligned = pctx->dst_row_size_aligned; \ - \ - uint8_t * src_spad_base = octx->src0_spad.data + ith * octx->src0_spad.size_per_hvx; \ - uint8_t * dst_spad_base = octx->dst_spad.data + ith * octx->dst_spad.size_per_hvx; \ - \ - dma_queue * dma_q = th->dma_q; + const uint32_t rem = s->ne0 - s->off; + const uint32_t len = MIN(s->chunk_elems, rem); -// --------------------------------------------------------------------------- -// HVX vectorized PAD kernel -// --------------------------------------------------------------------------- + task->row = s->row; + task->off = s->off; + task->len = len; + task->aux = 0; -static void pad_job_per_hvx_hvx(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { - const struct htp_pad_context * pctx = (const struct htp_pad_context *) data; - struct htp_ops_context * octx = pctx->octx; - htp_pad_preamble; - - struct htp_thread_trace * tr = th->trace; - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, row_start); - - for (uint32_t dst_row = row_start; dst_row < row_end; dst_row++) { - uint32_t i1, i2, i3; - pad_decompose_row(dst_row, ne1, ne2, pctx->kparams, &i1, &i2, &i3); - - uint8_t * dst_ptr = (uint8_t *) dst->data + i1 * nb1 + i2 * nb2 + i3 * nb3; - - const int interior = pad_is_interior(i1, i2, i3, - lp1, rp1, ne1, - lp2, rp2, ne2, - lp3, rp3, ne3); - - if (!interior) { - hvx_splat_f32_u(dst_ptr, 0.0f, ne0); - } else { - const uint8_t * src_ptr = pad_src_row_ptr(src, i1, i2, i3, lp1, lp2, lp3); - - if (lp0 > 0) { - hvx_splat_f32_u(dst_ptr, 0.0f, (uint32_t)lp0); - } - - uint8_t * dst_row_start = dst_ptr + (size_t)lp0 * type_size; - if (nb00 == type_size) { - hvx_copy_f32_uu(dst_row_start, src_ptr, ne00); - } else { - for (uint32_t i = 0; i < ne00; i++) { - memcpy(dst_row_start + i * type_size, - src_ptr + (size_t)i * nb00, - type_size); - } - } - - if (rp0 > 0) { - hvx_splat_f32_u(dst_ptr + ((size_t)lp0 + ne00) * type_size, 0.0f, (uint32_t)rp0); - } - } + s->off += len; + if (s->off >= s->ne0) { + s->off = 0; + s->row++; } + return true; +} - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, row_start); +static bool pad_const_next_task(void * ctx, struct dma_pipe_task * task) { + struct pad_pipe_state * s = (struct pad_pipe_state *) ctx; + if (!pad_next_task(ctx, task)) { + return false; + } - FARF(HIGH, "pad-hvx %d/%d: (%ux%ux%ux%u) -> (%ux%ux%ux%u) rows %u:%u\n", - ith, nth, - src->ne[0], src->ne[1], src->ne[2], src->ne[3], - dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3], - row_start, row_end); + uint32_t i1, i2, i3; + pad_decompose_row(task->row, s->ne1, s->ne2, s->kparams, &i1, &i2, &i3); + task->aux = (uint32_t) pad_is_interior(i1, i2, i3, + s->lp1, s->rp1, s->ne1, + s->lp2, s->rp2, s->ne2, + s->lp3, s->rp3, s->ne3); + return true; +} + +static bool pad_circ_next_task(void * ctx, struct dma_pipe_task * task) { + struct pad_pipe_state * s = (struct pad_pipe_state *) ctx; + if (s->row >= s->row_end) { + return false; + } + + const uint32_t lp0 = (uint32_t) s->lp0; + const uint32_t ne00 = s->ne00; + uint32_t sx; + if (s->off < lp0) { + sx = ne00 - lp0 + s->off; + } else if (s->off < lp0 + ne00) { + sx = s->off - lp0; + } else { + sx = s->off - lp0 - ne00; + } + + // Split at ne00 wrap boundary so each task is one contiguous DMA read + const uint32_t rem = s->ne0 - s->off; + const uint32_t len = MIN(MIN(s->chunk_elems, rem), ne00 - sx); + + task->row = s->row; + task->off = s->off; + task->len = len; + task->aux = sx; + + s->off += len; + if (s->off >= s->ne0) { + s->off = 0; + s->row++; + } + return true; +} + +static void pad_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) { + struct pad_pipe_state * s = (struct pad_pipe_state *) ctx; + + uint32_t i1, i2, i3; + pad_decompose_row(task->row, s->ne1, s->ne2, s->kparams, &i1, &i2, &i3); + + const size_t bytes = (size_t) task->len * s->type_size; + const dma_addr_t dst = s->dst->data + + (size_t) i1 * s->nb1 + (size_t) i2 * s->nb2 + (size_t) i3 * s->nb3 + + (size_t) task->off * s->type_size; + + dma_queue_push(dma_q, dma_make_data(dst, out_spad), bytes, s->chunk_bytes_aligned, bytes, 1); } // --------------------------------------------------------------------------- -// HVX + DMA PAD kernel - aligned, double-buffered +// Constant (zero) PAD pipeline callbacks // --------------------------------------------------------------------------- -static void pad_job_per_hvx_hvx_dma(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { - const struct htp_pad_context * pctx = (const struct htp_pad_context *) data; - struct htp_ops_context * octx = pctx->octx; - htp_pad_preamble; - htp_pad_dma_preamble; - - // ----------------------------------------------------------------------- - // Priming phase: push 2 pairs of (dummy_dst_DMA, src_DMA) to seed the - // double-buffer pipeline before the main loop begins. - // ----------------------------------------------------------------------- - for (uint32_t ir = row_start, spad_idx = 0; ir < row_end && spad_idx < 2; ir++, spad_idx++) { - uint8_t * src_spad_cur = src_spad_base + spad_idx * src_row_size_aligned; - uint8_t * dst_spad_cur = dst_spad_base + spad_idx * dst_row_size_aligned; - - dma_queue_push(dma_q, - dma_make_data(dst->data, dst_spad_cur), - dst_row_size, dst_row_size_aligned, dst_row_size, 0); - - uint32_t i1, i2, i3; - pad_decompose_row(ir, ne1, ne2, pctx->kparams, &i1, &i2, &i3); - const int interior = pad_is_interior(i1, i2, i3, - lp1, rp1, ne1, - lp2, rp2, ne2, - lp3, rp3, ne3); - - const dma_addr_t src_data = interior - ? pad_src_row_data(src, i1, i2, i3, lp1, lp2, lp3) : src->data; - - // Interior row: real DMA (1 row) from DDR to VTCM. - // Border row: null DMA (nrows=0) - dma_queue_push(dma_q, - dma_make_data(src_spad_cur, src_data), - src_row_size_aligned, src_row_size, src_row_size, interior ? 1 : 0); +static void pad_const_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct pad_pipe_state * s = (struct pad_pipe_state *) ctx; + + if (!task->aux) { + dma_queue_push(dma_q, dma_make_data(in_spad, 0), 0, 0, 0, 0); + return; } - // ----------------------------------------------------------------------- - // Main loop: pop completed DMAs, compute in VTCM with aligned HVX ops, - // push dst DMA and prefetch src for the next+1 row. - // ----------------------------------------------------------------------- - struct htp_thread_trace * tr = th->trace; - - for (uint32_t ir = row_start; ir < row_end; ir++) { - uint8_t * dst_spad_cur = (uint8_t *) dma_queue_pop(dma_q).src; - uint8_t * src_spad_cur = (uint8_t *) dma_queue_pop(dma_q).dst; - - uint32_t i1, i2, i3; - pad_decompose_row(ir, ne1, ne2, pctx->kparams, &i1, &i2, &i3); - - const dma_addr_t dst_data = dst->data + i1 * nb1 + i2 * nb2 + i3 * nb3; - - const int interior = pad_is_interior(i1, i2, i3, - lp1, rp1, ne1, - lp2, rp2, ne2, - lp3, rp3, ne3); - - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); - if (!interior) { - hvx_splat_f32_a(dst_spad_cur, 0.0f, ne0); - } else { - hvx_splat_f32_a(dst_spad_cur, 0.0f, ne0); - - uint8_t * dst_interior = dst_spad_cur + (size_t)lp0 * type_size; - - if ((uintptr_t)dst_interior % VLEN == 0) { - hvx_copy_f32_aa(dst_interior, src_spad_cur, ne00); - } else { - hvx_copy_f32_ua(dst_interior, src_spad_cur, ne00); - } - } - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); - - dma_queue_push(dma_q, - dma_make_data(dst_data, dst_spad_cur), - dst_row_size, dst_row_size_aligned, dst_row_size, 1); - - const uint32_t next_row = ir + 2; - if (next_row < row_end) { - uint32_t ni1, ni2, ni3; - pad_decompose_row(next_row, ne1, ne2, pctx->kparams, &ni1, &ni2, &ni3); - const int next_interior = pad_is_interior(ni1, ni2, ni3, - lp1, rp1, ne1, - lp2, rp2, ne2, - lp3, rp3, ne3); - const dma_addr_t next_src_data = next_interior - ? pad_src_row_data(src, ni1, ni2, ni3, lp1, lp2, lp3) : src->data; - - dma_queue_push(dma_q, - dma_make_data(src_spad_cur, next_src_data), - src_row_size_aligned, src_row_size, src_row_size, next_interior ? 1 : 0); - } + const uint32_t ov_start = MAX(task->off, (uint32_t) s->lp0); + const uint32_t ov_end = MIN(task->off + task->len, (uint32_t) s->lp0 + s->ne00); + if (ov_start >= ov_end) { + dma_queue_push(dma_q, dma_make_data(in_spad, 0), 0, 0, 0, 0); + return; } - dma_queue_flush(dma_q); + uint32_t i1, i2, i3; + pad_decompose_row(task->row, s->ne1, s->ne2, s->kparams, &i1, &i2, &i3); - FARF(HIGH, "pad-hvx-dma %d/%d: (%ux%ux%ux%u) -> (%ux%ux%ux%u) rows %u:%u\n", - ith, nth, - src->ne[0], src->ne[1], src->ne[2], src->ne[3], - dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3], - row_start, row_end); + const uint32_t copy_len = ov_end - ov_start; + const uint32_t src_off = ov_start - (uint32_t) s->lp0; + const size_t bytes = (size_t) copy_len * s->type_size; + const dma_addr_t src_addr = pad_src_row_data(s->src, i1, i2, i3, s->lp1, s->lp2, s->lp3) + + (size_t) src_off * s->type_size; + + dma_queue_push(dma_q, dma_make_data(in_spad, src_addr), s->chunk_bytes_aligned, bytes, bytes, 1); +} + +static void __attribute__((noinline)) pad_const_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct pad_pipe_state * s = (struct pad_pipe_state *) ctx; + + const uint8_t * src_spad = (const uint8_t *) in_spad; + uint8_t * dst_spad = (uint8_t *) out_spad; + const uint32_t total_bytes = task->len * (uint32_t) s->type_size; + + if (!task->aux) { + hvx_splat_u8_a(dst_spad, 0, total_bytes); + return; + } + + const uint32_t ov_start = MAX(task->off, (uint32_t) s->lp0); + const uint32_t ov_end = MIN(task->off + task->len, (uint32_t) s->lp0 + s->ne00); + if (ov_start >= ov_end) { + hvx_splat_u8_a(dst_spad, 0, total_bytes); + return; + } + + const uint32_t copy_len = ov_end - ov_start; + const uint32_t copy_bytes = copy_len * (uint32_t) s->type_size; + const uint32_t dst_off = ov_start - task->off; + + if (copy_len < task->len) { + hvx_splat_u8_a(dst_spad, 0, total_bytes); + } + + uint8_t * dst_interior = dst_spad + (size_t) dst_off * s->type_size; + if (((uintptr_t) dst_interior & (VLEN - 1)) == 0) { + hvx_copy_aa(dst_interior, src_spad, copy_bytes, 1); + } else { + hvx_copy_ua(dst_interior, src_spad, copy_bytes, 1); + } } // --------------------------------------------------------------------------- -// HVX circular PAD kernel +// Circular PAD pipeline callbacks // --------------------------------------------------------------------------- -static void pad_job_per_hvx_hvx_circular(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { - const struct htp_pad_context * pctx = (const struct htp_pad_context *) data; - struct htp_ops_context * octx = pctx->octx; - htp_pad_preamble; - - struct htp_thread_trace * tr = th->trace; - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, row_start); - - for (uint32_t dst_row = row_start; dst_row < row_end; dst_row++) { - uint32_t i1, i2, i3; - pad_decompose_row(dst_row, ne1, ne2, pctx->kparams, &i1, &i2, &i3); - - uint8_t * dst_ptr = (uint8_t *) dst->data + i1 * nb1 + i2 * nb2 + i3 * nb3; - const uint8_t * src_row = pad_circ_src_row_ptr(src, pctx->kparams, i1, i2, i3, lp1, lp2, lp3); - - if (nb00 == type_size) { - - if (lp0 > 0) { - if ((uint32_t)lp0 < 32) { - memcpy(dst_ptr, - src_row + (size_t)(ne00 - (uint32_t)lp0) * type_size, - (size_t)lp0 * type_size); - } else { - hvx_copy_f32_uu(dst_ptr, - src_row + (size_t)(ne00 - (uint32_t)lp0) * type_size, - (uint32_t)lp0); - } - } - hvx_copy_f32_uu(dst_ptr + (size_t)lp0 * type_size, src_row, ne00); - if (rp0 > 0) { - if ((uint32_t)rp0 < 32) { - memcpy(dst_ptr + ((size_t)lp0 + ne00) * type_size, - src_row, - (size_t)rp0 * type_size); - } else { - hvx_copy_f32_uu(dst_ptr + ((size_t)lp0 + ne00) * type_size, - src_row, - (uint32_t)rp0); - } - } - } else { - for (uint32_t i = 0; i < (uint32_t)lp0; i++) { - *(float *)(dst_ptr + i * type_size) = - *(const float *)(src_row + (size_t)(ne00 - (uint32_t)lp0 + i) * nb00); - } - for (uint32_t i = 0; i < ne00; i++) { - *(float *)(dst_ptr + ((size_t)lp0 + i) * type_size) = - *(const float *)(src_row + (size_t)i * nb00); - } - for (uint32_t i = 0; i < (uint32_t)rp0; i++) { - *(float *)(dst_ptr + ((size_t)lp0 + ne00 + i) * type_size) = - *(const float *)(src_row + (size_t)i * nb00); - } - } - } +static void pad_circ_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct pad_pipe_state * s = (struct pad_pipe_state *) ctx; - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, row_start); + uint32_t i1, i2, i3; + pad_decompose_row(task->row, s->ne1, s->ne2, s->kparams, &i1, &i2, &i3); - FARF(HIGH, "pad-hvx-circ %d/%d: (%ux%ux%ux%u) -> (%ux%ux%ux%u) rows %u:%u\n", - ith, nth, - src->ne[0], src->ne[1], src->ne[2], src->ne[3], - dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3], - row_start, row_end); + const dma_addr_t src_row = pad_circ_src_row_data(s->src, s->kparams, i1, i2, i3, s->lp1, s->lp2, s->lp3); + const size_t bytes = (size_t) task->len * s->type_size; + + dma_queue_push(dma_q, + dma_make_data(in_spad, src_row + (size_t) task->aux * s->type_size), + s->chunk_bytes_aligned, bytes, bytes, 1); +} + +static void __attribute__((noinline)) pad_circ_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct pad_pipe_state * s = (struct pad_pipe_state *) ctx; + + hvx_copy_aa((uint8_t *) out_spad, (const uint8_t *) in_spad, task->len * (uint32_t) s->type_size, 1); } // --------------------------------------------------------------------------- -// HVX + DMA circular PAD kernel - aligned, double-buffered +// Per thread workers // --------------------------------------------------------------------------- -static void pad_job_per_hvx_hvx_circular_dma(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { +static void pad_state_init(struct pad_pipe_state * s, const struct htp_pad_context * pctx, + uint32_t row_start, uint32_t row_end) { + struct htp_ops_context * octx = pctx->octx; + const struct htp_tensor * src = octx->src[0]; + const struct htp_tensor * dst = octx->dst; + + s->src = src; + s->dst = dst; + s->kparams = pctx->kparams; + s->type_size = pctx->type_size; + s->chunk_bytes_aligned = pctx->chunk_bytes_aligned; + s->lp0 = pctx->lp0; s->rp0 = pctx->rp0; + s->lp1 = pctx->lp1; s->rp1 = pctx->rp1; + s->lp2 = pctx->lp2; s->rp2 = pctx->rp2; + s->lp3 = pctx->lp3; s->rp3 = pctx->rp3; + s->ne00 = src->ne[0]; + s->ne0 = dst->ne[0]; + s->ne1 = dst->ne[1]; + s->ne2 = dst->ne[2]; + s->ne3 = dst->ne[3]; + s->nb1 = dst->nb[1]; + s->nb2 = dst->nb[2]; + s->nb3 = dst->nb[3]; + s->chunk_elems = pctx->chunk_elems; + s->row = row_start; + s->row_end = row_end; + s->off = 0; +} + +static void pad_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { const struct htp_pad_context * pctx = (const struct htp_pad_context *) data; - struct htp_ops_context * octx = pctx->octx; - htp_pad_preamble; - htp_pad_dma_preamble; - - // ----------------------------------------------------------------------- - // Priming phase: push 2 pairs of (dummy_dst_DMA, src_DMA) to seed the - // double-buffer pipeline. Every row is a real src DMA (no null DMAs). - // ----------------------------------------------------------------------- - for (uint32_t ir = row_start, spad_idx = 0; ir < row_end && spad_idx < 2; ir++, spad_idx++) { - uint8_t * src_spad_cur = src_spad_base + spad_idx * src_row_size_aligned; - uint8_t * dst_spad_cur = dst_spad_base + spad_idx * dst_row_size_aligned; - - dma_queue_push(dma_q, - dma_make_data(dst->data, dst_spad_cur), - dst_row_size, dst_row_size_aligned, dst_row_size, 0); - - uint32_t pi1, pi2, pi3; - pad_decompose_row(ir, ne1, ne2, pctx->kparams, &pi1, &pi2, &pi3); - const dma_addr_t src_data = pad_circ_src_row_data(src, pctx->kparams, pi1, pi2, pi3, lp1, lp2, lp3); - dma_queue_push(dma_q, - dma_make_data(src_spad_cur, src_data), - src_row_size_aligned, src_row_size, src_row_size, 1); + + const uint32_t row_start = pctx->row_start + pctx->nrows_per_hvx * ith; + const uint32_t row_end = MIN(row_start + pctx->nrows_per_hvx, pctx->row_start + pctx->total_dst_rows); + + if (row_start >= row_end) { + return; } - // ----------------------------------------------------------------------- - // Main loop: pop completed DMAs, assemble circular row in VTCM with - // aligned HVX ops, push dst DMA and prefetch src for the next+1 row. - // ----------------------------------------------------------------------- - struct htp_thread_trace * tr = th->trace; - - for (uint32_t ir = row_start; ir < row_end; ir++) { - uint8_t * dst_spad_cur = (uint8_t *) dma_queue_pop(dma_q).src; - uint8_t * src_spad_cur = (uint8_t *) dma_queue_pop(dma_q).dst; - - uint32_t i1, i2, i3; - pad_decompose_row(ir, ne1, ne2, pctx->kparams, &i1, &i2, &i3); - const dma_addr_t dst_data = dst->data + i1 * nb1 + i2 * nb2 + i3 * nb3; - - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); - if (lp0 > 0) { - uint8_t * dst_left = dst_spad_cur; - const uint8_t * src_left = src_spad_cur + (size_t)(ne00 - (uint32_t)lp0) * type_size; - if ((uint32_t)lp0 < 32) { - memcpy(dst_left, src_left, (size_t)lp0 * type_size); - } else { - hvx_copy_f32_uu(dst_left, src_left, (uint32_t)lp0); - } - } - - { - uint8_t * dst_mid = dst_spad_cur + (size_t)lp0 * type_size; - if ((uintptr_t)dst_mid % VLEN == 0) { - hvx_copy_f32_aa(dst_mid, src_spad_cur, ne00); - } else { - hvx_copy_f32_ua(dst_mid, src_spad_cur, ne00); - } - } - - if (rp0 > 0) { - uint8_t * dst_right = dst_spad_cur + ((size_t)lp0 + ne00) * type_size; - if ((uint32_t)rp0 < 32) { - memcpy(dst_right, src_spad_cur, (size_t)rp0 * type_size); - } else { - if ((uintptr_t)dst_right % VLEN == 0) { - hvx_copy_f32_aa(dst_right, src_spad_cur, (uint32_t)rp0); - } else { - hvx_copy_f32_ua(dst_right, src_spad_cur, (uint32_t)rp0); - } - } - } - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); - - dma_queue_push(dma_q, - dma_make_data(dst_data, dst_spad_cur), - dst_row_size, dst_row_size_aligned, dst_row_size, 1); - - const uint32_t next_row = ir + 2; - if (next_row < row_end) { - uint32_t nri1, nri2, nri3; - pad_decompose_row(next_row, ne1, ne2, pctx->kparams, &nri1, &nri2, &nri3); - const dma_addr_t next_src_data = pad_circ_src_row_data(src, pctx->kparams, nri1, nri2, nri3, lp1, lp2, lp3); - dma_queue_push(dma_q, - dma_make_data(src_spad_cur, next_src_data), - src_row_size_aligned, src_row_size, src_row_size, 1); - } + uint8_t * src_spad = pctx->vtcm_src0 + ith * pctx->src0_bytes_per_hvx; + uint8_t * dst_spad = pctx->vtcm_dst + ith * pctx->dst_bytes_per_hvx; + void * in_buf[2] = { src_spad, src_spad + pctx->chunk_bytes_aligned }; + void * out_buf[2] = { dst_spad, dst_spad + pctx->chunk_bytes_aligned }; + + struct pad_pipe_state s; + pad_state_init(&s, pctx, row_start, row_end); + + dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, pad_const_next_task, pad_const_push_in, pad_const_compute, pad_push_out); + + FARF(HIGH, "pad-hvx %d/%d: (%ux%ux%ux%u) -> (%ux%ux%ux%u) rows %u:%u\n", + ith, nth, + s.src->ne[0], s.src->ne[1], s.src->ne[2], s.src->ne[3], + s.dst->ne[0], s.dst->ne[1], s.dst->ne[2], s.dst->ne[3], + row_start, row_end); +} + +static void pad_thread_circular(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + const struct htp_pad_context * pctx = (const struct htp_pad_context *) data; + + const uint32_t row_start = pctx->row_start + pctx->nrows_per_hvx * ith; + const uint32_t row_end = MIN(row_start + pctx->nrows_per_hvx, pctx->row_start + pctx->total_dst_rows); + + if (row_start >= row_end) { + return; } - dma_queue_flush(dma_q); + uint8_t * src_spad = pctx->vtcm_src0 + ith * pctx->src0_bytes_per_hvx; + uint8_t * dst_spad = pctx->vtcm_dst + ith * pctx->dst_bytes_per_hvx; + void * in_buf[2] = { src_spad, src_spad + pctx->chunk_bytes_aligned }; + void * out_buf[2] = { dst_spad, dst_spad + pctx->chunk_bytes_aligned }; + + struct pad_pipe_state s; + pad_state_init(&s, pctx, row_start, row_end); - FARF(HIGH, "pad-hvx-circ-dma %d/%d: (%ux%ux%ux%u) -> (%ux%ux%ux%u) rows %u:%u\n", + dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, pad_circ_next_task, pad_circ_push_in, pad_circ_compute, pad_push_out); + + FARF(HIGH, "pad-hvx-circ %d/%d: (%ux%ux%ux%u) -> (%ux%ux%ux%u) rows %u:%u\n", ith, nth, - src->ne[0], src->ne[1], src->ne[2], src->ne[3], - dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3], + s.src->ne[0], s.src->ne[1], s.src->ne[2], s.src->ne[3], + s.dst->ne[0], s.dst->ne[1], s.dst->ne[2], s.dst->ne[3], row_start, row_end); } @@ -491,6 +383,10 @@ int op_pad(struct htp_ops_context * octx) { const struct htp_pad_kernel_params * kparams = (const struct htp_pad_kernel_params *) octx->kernel_params; + if ((src0->type != HTP_TYPE_F32 && src0->type != HTP_TYPE_F16) || dst->type != src0->type) { + return HTP_STATUS_NO_SUPPORT; + } + const int32_t lp0 = octx->op_params[0]; const int32_t rp0 = octx->op_params[1]; const int32_t lp1 = octx->op_params[2]; @@ -499,20 +395,15 @@ int op_pad(struct htp_ops_context * octx) { const int32_t rp2 = octx->op_params[5]; const int32_t lp3 = octx->op_params[6]; const int32_t rp3 = octx->op_params[7]; - const int32_t circular = octx->op_params[8]; const uint32_t total_dst_rows = kparams->total_rows; const size_t type_size = kparams->elem_size; - const size_t src_row_size = src0->ne[0] * type_size; - const size_t dst_row_size = dst->ne[0] * type_size; uint32_t row_start = 0; uint32_t nrows = total_dst_rows; if (octx->ctx->mdev.count > 1) { - uint32_t rows_per_chunk = 0; - htp_tensor_mdev_rows_per_chunk(dst, type_size, (uint32_t) dst_row_size, &rows_per_chunk); - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_dst_rows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_dst_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); row_start = range.start; nrows = range.count; } @@ -527,60 +418,40 @@ int op_pad(struct htp_ops_context * octx) { const uint32_t n_hvx = octx->n_hvx; - if (!kparams->use_dma && (htp_tensor_is_extended(src0) || htp_tensor_is_extended(dst))) { - return HTP_STATUS_NO_SUPPORT; - } - struct htp_pad_vtcm_layout layout = { 0 }; - if (kparams->use_dma) { - htp_pad_vtcm_layout_build(&layout, src_row_size, dst_row_size, n_hvx); - - octx->src0_spad.size_per_hvx = layout.src0_bytes_per_hvx; - octx->dst_spad.size_per_hvx = layout.dst_bytes_per_hvx; - octx->src0_spad.size = n_hvx * layout.src0_bytes_per_hvx; - octx->dst_spad.size = n_hvx * layout.dst_bytes_per_hvx; - octx->src0_spad.data = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_src0); - octx->dst_spad.data = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_dst); - octx->src0_spad.src = NULL; - octx->dst_spad.src = NULL; - } + htp_pad_vtcm_layout_build(&layout, (size_t) kparams->chunk_elems * type_size, n_hvx); struct htp_pad_context pctx = { - .octx = octx, - .kparams = kparams, + .octx = octx, + .kparams = kparams, + .vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_src0), + .vtcm_dst = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_dst), + .src0_bytes_per_hvx = layout.src0_bytes_per_hvx, + .dst_bytes_per_hvx = layout.dst_bytes_per_hvx, .lp0 = lp0, .rp0 = rp0, .lp1 = lp1, .rp1 = rp1, .lp2 = lp2, .rp2 = rp2, .lp3 = lp3, .rp3 = rp3, - .nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div), - .total_dst_rows = nrows, - .row_start = row_start, - .type_size = type_size, - .src_row_size = src_row_size, - .src_row_size_aligned = layout.src_row_size_aligned, - .dst_row_size = dst_row_size, - .dst_row_size_aligned = layout.dst_row_size_aligned, + .nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div), + .total_dst_rows = nrows, + .row_start = row_start, + .chunk_elems = kparams->chunk_elems, + .type_size = type_size, + .chunk_bytes_aligned = layout.chunk_bytes_aligned, }; - FARF(HIGH, "pad-hvx%s%s: (%ux%ux%ux%u) -> (%ux%ux%ux%u) pads=(%d,%d,%d,%d,%d,%d,%d,%d)\n", - circular ? "-circ" : "", - kparams->use_dma ? "-dma" : "", + FARF(HIGH, "pad-hvx%s: (%ux%ux%ux%u) -> (%ux%ux%ux%u) pads=(%d,%d,%d,%d,%d,%d,%d,%d)\n", + circular ? "-circ" : "", src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3], dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3], lp0, rp0, lp1, rp1, lp2, rp2, lp3, rp3); switch (kparams->kernel_type) { - case HTP_PAD_KERNEL_HVX_CIRCULAR_DMA: - work_queue_run(octx->ctx->hvx_queue, pad_job_per_hvx_hvx_circular_dma, &pctx, n_hvx); - break; case HTP_PAD_KERNEL_HVX_CIRCULAR: - work_queue_run(octx->ctx->hvx_queue, pad_job_per_hvx_hvx_circular, &pctx, n_hvx); - break; - case HTP_PAD_KERNEL_HVX_DMA: - work_queue_run(octx->ctx->hvx_queue, pad_job_per_hvx_hvx_dma, &pctx, n_hvx); + work_queue_run(octx->ctx->hvx_queue, pad_thread_circular, &pctx, n_hvx); break; default: - work_queue_run(octx->ctx->hvx_queue, pad_job_per_hvx_hvx, &pctx, n_hvx); + work_queue_run(octx->ctx->hvx_queue, pad_thread, &pctx, n_hvx); break; } diff --git a/ggml/src/ggml-hexagon/htp/pad-ops.h b/ggml/src/ggml-hexagon/htp/pad-ops.h index 15357e5f67de..da0404f96cc7 100644 --- a/ggml/src/ggml-hexagon/htp/pad-ops.h +++ b/ggml/src/ggml-hexagon/htp/pad-ops.h @@ -7,32 +7,27 @@ #include enum htp_pad_kernel_type { - HTP_PAD_KERNEL_HVX = 0, - HTP_PAD_KERNEL_HVX_DMA = 1, - HTP_PAD_KERNEL_HVX_CIRCULAR = 2, - HTP_PAD_KERNEL_HVX_CIRCULAR_DMA = 3, + HTP_PAD_KERNEL_HVX = 0, + HTP_PAD_KERNEL_HVX_CIRCULAR = 1, }; struct htp_pad_vtcm_layout { size_t total_bytes; size_t off_src0; size_t off_dst; - size_t src_row_size_aligned; - size_t dst_row_size_aligned; + size_t chunk_bytes_aligned; size_t src0_bytes_per_hvx; size_t dst_bytes_per_hvx; }; static inline void htp_pad_vtcm_layout_build( struct htp_pad_vtcm_layout * L, - size_t src_row_size, - size_t dst_row_size, + size_t chunk_bytes, uint32_t n_hvx ) { - L->src_row_size_aligned = hex_round_up(src_row_size, 128); - L->dst_row_size_aligned = hex_round_up(dst_row_size, 128); - L->src0_bytes_per_hvx = 2 * L->src_row_size_aligned; - L->dst_bytes_per_hvx = 2 * L->dst_row_size_aligned; + L->chunk_bytes_aligned = hex_round_up(chunk_bytes, 128); + L->src0_bytes_per_hvx = 2 * L->chunk_bytes_aligned; + L->dst_bytes_per_hvx = 2 * L->chunk_bytes_aligned; size_t off = 0; VTCM_LAYOUT_ALLOC(off, off_src0, L->src0_bytes_per_hvx * n_hvx); @@ -45,7 +40,7 @@ struct htp_pad_kernel_params { uint8_t kernel_type; uint32_t n_hvx; uint32_t total_rows; - uint32_t use_dma; + uint32_t chunk_elems; uint32_t elem_size; uint32_t vtcm_size; diff --git a/ggml/src/ggml-hexagon/htp/pool-ops.c b/ggml/src/ggml-hexagon/htp/pool-ops.c index 12cd8ea90bf8..55bf27416f50 100644 --- a/ggml/src/ggml-hexagon/htp/pool-ops.c +++ b/ggml/src/ggml-hexagon/htp/pool-ops.c @@ -1,10 +1,9 @@ -#pragma clang diagnostic ignored "-Wunused-variable" - #include #include #include "hex-common.h" #include "dma-queue.h" +#include "dma-pipeline.h" #include "htp-trace.h" #include "htp-ctx.h" #include "htp-ops.h" @@ -147,9 +146,13 @@ static inline void pool_pixel_boundary_vec( HVX_Vector acc = mask_identity; for (uint32_t ky = ky_lo; ky < ky_hi; ++ky) { const float * row = src + (uint32_t) (iy0 + (int32_t) ky) * p->src_x; - for (uint32_t k = 0; k < valid_kx; k += VLEN_FP32) { - const uint32_t k_rem = valid_kx - k; - const uint32_t n = (k_rem < VLEN_FP32) ? k_rem : VLEN_FP32; + uint32_t k = 0; + for (; k + VLEN_FP32 <= valid_kx; k += VLEN_FP32) { + const HVX_Vector v = *(const HVX_UVector *) (row + ix0 + kx_lo + k); + acc = is_max ? Q6_Vsf_vmax_VsfVsf(acc, v) : hvx_vec_add_f32_f32(acc, v); + } + if (k < valid_kx) { + const uint32_t n = valid_kx - k; const HVX_VectorPred q = Q6_Q_vsetq_R(n * sizeof(float)); const HVX_Vector raw = *(const HVX_UVector *) (row + ix0 + kx_lo + k); const HVX_Vector v = Q6_V_vmux_QVV(q, raw, mask_identity); @@ -255,13 +258,57 @@ struct pool_2d_context { uint32_t planes_per_hvx; }; +struct pool_pipe_state { + dma_addr_t src_data; + dma_addr_t dst_data; + const struct htp_pool_2d_kernel_params * kparams; + pool_plane_fn_t pool_plane; + uint32_t src_plane_bytes; + uint32_t dst_plane_bytes; + uint32_t src_spad_half; + uint32_t dst_spad_half; + uint32_t plane; + uint32_t plane_end; +}; + +static bool pool_next_task(void * ctx, struct dma_pipe_task * task) { + struct pool_pipe_state * s = (struct pool_pipe_state *) ctx; + if (s->plane >= s->plane_end) { + return false; + } + task->row = s->plane++; + task->off = 0; + task->len = 0; + task->aux = 0; + return true; +} + +static void pool_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct pool_pipe_state * s = (struct pool_pipe_state *) ctx; + const dma_addr_t src_addr = s->src_data + (size_t) task->row * s->src_plane_bytes; + dma_queue_push(dma_q, dma_make_data(in_spad, src_addr), + s->src_spad_half, s->src_plane_bytes, s->src_plane_bytes, 1); +} + +static void pool_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + (void) task; + struct pool_pipe_state * s = (struct pool_pipe_state *) ctx; + s->pool_plane((const float *) in_spad, (float *) out_spad, s->kparams); +} + +static void pool_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) { + struct pool_pipe_state * s = (struct pool_pipe_state *) ctx; + const dma_addr_t dst_addr = s->dst_data + (size_t) task->row * s->dst_plane_bytes; + dma_queue_push(dma_q, dma_make_data(dst_addr, out_spad), + s->dst_plane_bytes, s->dst_spad_half, s->dst_plane_bytes, 1); +} + static void pool_2d_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { struct pool_2d_context * ctx = (struct pool_2d_context *) data; const struct htp_pool_2d_kernel_params * p = ctx->kparams; const struct htp_pool_vtcm_layout * L = &ctx->layout; const struct htp_tensor * src0 = ctx->octx->src[0]; const struct htp_tensor * dst = ctx->octx->dst; - pool_plane_fn_t pool_plane = ctx->pool_plane; const uint32_t planes_per_hvx = ctx->planes_per_hvx; const uint32_t first = ctx->plane_start + ith * planes_per_hvx; const uint32_t last = MIN(first + planes_per_hvx, ctx->plane_start + ctx->plane_count); @@ -270,75 +317,38 @@ static void pool_2d_thread(const htp_thread_t * th, unsigned int nth, unsigned i return; } - struct htp_thread_trace * tr = th->trace; - dma_queue * dma_queue = th->dma_q; - - const uint32_t src_plane_bytes = L->src_plane_bytes; - const uint32_t dst_plane_bytes = L->dst_plane_bytes; - 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 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 *) ctx->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) }; - - const uint32_t total = last - first; - - // Warm up the pipeline: push up to 2 initial (dummy dst, src) transfer pairs. - for (uint32_t i = 0; i < total && i < 2; ++i) { - dma_queue_push(dma_queue, - dma_make_data(dst->data, dstb2[i]), - dst_plane_bytes, dst_spad_half, - dst_plane_bytes, 0); - - const dma_addr_t src_addr = src0->data + (first + i) * src_plane_bytes; - dma_queue_push(dma_queue, - dma_make_data(srcb2[i], src_addr), - src_spad_half, src_plane_bytes, - src_plane_bytes, 1); - } - - for (uint32_t i = 0; i < total; ++i) { - const uint32_t plane = first + i; - const uint32_t buf = i & 1u; - float * srcb = srcb2[buf]; - float * dstb = dstb2[buf]; - - dma_queue_pop(dma_queue); // dst writeback from plane i - 2 (or dummy on iter 0, 1) - dma_queue_pop(dma_queue); // input for plane i - - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) plane); - pool_plane(srcb, dstb, p); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) plane); - - const dma_addr_t dst_addr = dst->data + plane * dst_plane_bytes; - dma_queue_push(dma_queue, - dma_make_data(dst_addr, dstb), - dst_plane_bytes, dst_spad_half, - dst_plane_bytes, 1); - - if (i + 2 < total) { - const dma_addr_t next_src_addr = src0->data + (plane + 2) * src_plane_bytes; - dma_queue_push(dma_queue, - dma_make_data(srcb, next_src_addr), - src_spad_half, src_plane_bytes, - src_plane_bytes, 1); - } - } + void * in_buf[2] = { src_spad, src_spad + src_spad_half }; + void * out_buf[2] = { dst_spad, dst_spad + dst_spad_half }; + + struct pool_pipe_state s = { + .src_data = src0->data, + .dst_data = dst->data, + .kparams = p, + .pool_plane = ctx->pool_plane, + .src_plane_bytes = L->src_plane_bytes, + .dst_plane_bytes = L->dst_plane_bytes, + .src_spad_half = src_spad_half, + .dst_spad_half = dst_spad_half, + .plane = first, + .plane_end = last, + }; - dma_queue_flush(dma_queue); + dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, pool_next_task, pool_push_in, pool_compute, pool_push_out); - FARF(HIGH, "pool2d-f32-dma %d/%d: %ux%ux%ux%u -> %ux%ux%ux%u (%u:%u)\n", + FARF(HIGH, "pool2d-f32 %d/%d: %ux%ux%ux%u -> %ux%ux%ux%u (%u:%u)\n", ith, nth, src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3], dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3], first, last); (void) nth; } int op_pool_2d(struct htp_ops_context * octx) { - const struct htp_tensor * dst = octx->dst; const struct htp_pool_2d_kernel_params * p = (const struct htp_pool_2d_kernel_params *) octx->kernel_params; @@ -346,7 +356,7 @@ int op_pool_2d(struct htp_ops_context * octx) { uint32_t plane_count = p->planes; if (octx->ctx->mdev.count > 1) { const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( - plane_count, htp_tensor_mdev_data_aligned(dst) ? p->planes_per_chunk : 0, + plane_count, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); plane_start = range.start; plane_count = range.count; diff --git a/ggml/src/ggml-hexagon/htp/pool-ops.h b/ggml/src/ggml-hexagon/htp/pool-ops.h index e113bb9dd30d..1e379bef50e0 100644 --- a/ggml/src/ggml-hexagon/htp/pool-ops.h +++ b/ggml/src/ggml-hexagon/htp/pool-ops.h @@ -31,7 +31,6 @@ struct htp_pool_2d_kernel_params { int32_t pad_y; uint32_t n_hvx; uint32_t planes; - uint32_t planes_per_chunk; uint32_t pool_op; uint32_t avg_divide_count; uint32_t ox_lo; diff --git a/ggml/src/ggml-hexagon/htp/repeat-ops.c b/ggml/src/ggml-hexagon/htp/repeat-ops.c index a9e4d5c8636f..43326232bf4b 100644 --- a/ggml/src/ggml-hexagon/htp/repeat-ops.c +++ b/ggml/src/ggml-hexagon/htp/repeat-ops.c @@ -1,12 +1,11 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include +#include #include +#include "dma-queue.h" +#include "dma-pipeline.h" #include "hvx-utils.h" #define GGML_COMMON_DECL_C @@ -16,49 +15,241 @@ #include "htp-trace.h" #include "htp-ops.h" #include "htp-tensor.h" +#include "htp-vtcm.h" #include "repeat-ops.h" +typedef void (*repeat_fill_vtcm_fn_t)( + uint8_t * restrict dst_vtcm, + const uint8_t * restrict src_vtcm, + uint32_t n_elems, + uint32_t reps, + uint32_t dst_elem_size +); + struct htp_repeat_context { - struct htp_ops_context * octx; + struct htp_ops_context * octx; const struct htp_repeat_kernel_params * kparams; + repeat_fill_vtcm_fn_t fill_vtcm; + + dma_addr_t data_src; + dma_addr_t data_dst; + uint8_t * vtcm_src; + uint8_t * vtcm_dst; + size_t src_buf_bytes; + size_t dst_buf_bytes; + size_t src_bytes_per_hvx; + size_t dst_bytes_per_hvx; uint32_t nrows_per_hvx; - uint32_t total_dst_rows; // ne1 * ne2 * ne3 + uint32_t total_dst_rows; uint32_t row_start; - - size_t type_size; + uint32_t src_elem_size; + uint32_t dst_elem_size; + uint32_t tile_elems; + uint32_t dst_reps; }; -static void repeat_job_per_hvx(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { - const struct htp_repeat_context * rctx = (const struct htp_repeat_context *) data; - struct htp_ops_context * octx = rctx->octx; +static inline void repeat_row_addrs( + const struct htp_repeat_context * rctx, + const struct htp_tensor * src, + const struct htp_tensor * dst, + uint32_t dst_row, + dma_addr_t * src_addr, + dma_addr_t * dst_addr +) { const struct htp_repeat_kernel_params * kparams = rctx->kparams; - const struct htp_tensor * src = octx->src[0]; - const struct htp_tensor * dst = octx->dst; + const uint32_t dst_row_div_ne1 = fastdiv(dst_row, &kparams->div_ne1); + const uint32_t i1 = dst_row - dst_row_div_ne1 * dst->ne[1]; + const uint32_t i3 = fastdiv(dst_row, &kparams->div_ne12); + const uint32_t i2 = dst_row_div_ne1 - i3 * dst->ne[2]; + + const uint32_t k1 = fastmodulo(i1, src->ne[1], &kparams->div_ne01); + const uint32_t k2 = fastmodulo(i2, src->ne[2], &kparams->div_ne02); + const uint32_t k3 = fastmodulo(i3, src->ne[3], &kparams->div_ne03); + + *src_addr = rctx->data_src + (size_t) k1 * src->nb[1] + (size_t) k2 * src->nb[2] + (size_t) k3 * src->nb[3]; + *dst_addr = rctx->data_dst + (size_t) i1 * dst->nb[1] + (size_t) i2 * dst->nb[2] + (size_t) i3 * dst->nb[3]; +} + +static inline HVX_Vector repeat_clamp_f16_finite(HVX_Vector v) { + const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); + const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); + const HVX_Vector inf = hvx_vec_splat_f32(INFINITY); + const HVX_VectorPred finite = Q6_Q_vcmp_gt_VsfVsf(inf, hvx_vec_abs_f32(v)); + const HVX_VectorPred high = Q6_Q_and_QQ(finite, Q6_Q_vcmp_gt_VsfVsf(v, max_f16)); + const HVX_VectorPred low = Q6_Q_and_QQ(finite, Q6_Q_vcmp_gt_VsfVsf(min_f16, v)); + v = Q6_V_vmux_QVV(high, max_f16, v); + return Q6_V_vmux_QVV(low, min_f16, v); +} + +static inline void repeat_row_f32_to_f16_a(uint8_t * restrict dst_ptr, const uint8_t * restrict src_ptr, uint32_t n) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src_ptr; + HVX_Vector * restrict vdst = (HVX_Vector *) dst_ptr; + + const uint32_t n_vec = n / 64; + const uint32_t n_rem = n % 64; + + for (uint32_t i = 0; i < n_vec; i++) { + const HVX_Vector v0 = repeat_clamp_f16_finite(vsrc[2 * i + 0]); + const HVX_Vector v1 = repeat_clamp_f16_finite(vsrc[2 * i + 1]); + vdst[i] = hvx_vec_f32_to_f16(v0, v1); + } + + if (n_rem > 0) { + const HVX_Vector v0 = repeat_clamp_f16_finite(vsrc[2 * n_vec + 0]); + const HVX_Vector v1 = (n_rem > 32) ? repeat_clamp_f16_finite(vsrc[2 * n_vec + 1]) : Q6_V_vzero(); + const HVX_Vector v = hvx_vec_f32_to_f16(v0, v1); + hvx_vec_store_a(&vdst[n_vec], n_rem * sizeof(__fp16), v); + } +} + +static void __attribute__((noinline)) repeat_fill_vtcm_same( + uint8_t * restrict dst_vtcm, + const uint8_t * restrict src_vtcm, + uint32_t n_elems, + uint32_t reps, + uint32_t dst_elem_size +) { + const uint32_t unit_bytes = n_elems * dst_elem_size; + if (reps == 1) { + hvx_copy_aa(dst_vtcm, src_vtcm, unit_bytes, 1); + return; + } + + if (n_elems == 1) { + const int32_t bits = Q6_R_vextract_VR(hvx_vmem(src_vtcm), 0); + const HVX_Vector sv = (dst_elem_size == 2) ? Q6_Vh_vsplat_R(bits) : Q6_V_vsplat_R(bits); + hvx_splat_a(dst_vtcm, sv, reps * dst_elem_size, 1); + return; + } + + hvx_copy_aa(dst_vtcm, src_vtcm, unit_bytes, 1); + for (uint32_t r = 1; r < reps; r++) { + hvx_copy_ua(dst_vtcm + (size_t) r * unit_bytes, src_vtcm, unit_bytes, 1); + } +} + +static void __attribute__((noinline)) repeat_fill_vtcm_f32_to_f16( + uint8_t * restrict dst_vtcm, + const uint8_t * restrict src_vtcm, + uint32_t n_elems, + uint32_t reps, + uint32_t dst_elem_size +) { + (void) dst_elem_size; + repeat_row_f32_to_f16_a(dst_vtcm, src_vtcm, n_elems); + if (reps == 1) { + return; + } + + if (n_elems == 1) { + const int32_t bits = Q6_R_vextract_VR(hvx_vmem(dst_vtcm), 0); + hvx_splat_a(dst_vtcm, Q6_Vh_vsplat_R(bits), reps, sizeof(__fp16)); + return; + } + + const size_t unit_bytes = (size_t) n_elems * sizeof(__fp16); + for (uint32_t r = 1; r < reps; r++) { + hvx_copy_f16_ua(dst_vtcm + (size_t) r * unit_bytes, dst_vtcm, n_elems); + } +} + +struct repeat_pipe_state { + const struct htp_repeat_context * rctx; + const struct htp_tensor * src; + const struct htp_tensor * dst; + repeat_fill_vtcm_fn_t fill_vtcm; + size_t src_row_bytes; + size_t dst_row_bytes; + size_t src_buf_bytes; + size_t dst_buf_bytes; + uint32_t ne00; + uint32_t nr0; + uint32_t dst_elem_size; + uint32_t row; + uint32_t row_end; +}; + +static bool repeat_next_task(void * ctx, struct dma_pipe_task * task) { + struct repeat_pipe_state * s = (struct repeat_pipe_state *) ctx; + if (s->row >= s->row_end) { + return false; + } + task->row = s->row++; + task->off = 0; + task->len = 0; + task->aux = 0; + return true; +} + +static void repeat_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct repeat_pipe_state * s = (struct repeat_pipe_state *) ctx; + dma_addr_t src_addr, dst_addr; + repeat_row_addrs(s->rctx, s->src, s->dst, task->row, &src_addr, &dst_addr); + dma_queue_push(dma_q, dma_make_data(in_spad, src_addr), + s->src_buf_bytes, s->src_row_bytes, s->src_row_bytes, 1); +} + +static void repeat_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + (void) task; + struct repeat_pipe_state * s = (struct repeat_pipe_state *) ctx; + s->fill_vtcm((uint8_t *) out_spad, (const uint8_t *) in_spad, s->ne00, s->nr0, s->dst_elem_size); +} - const uint32_t ne00 = src->ne[0]; - const uint32_t ne01 = src->ne[1]; - const uint32_t ne02 = src->ne[2]; - const uint32_t ne03 = src->ne[3]; +static void repeat_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) { + struct repeat_pipe_state * s = (struct repeat_pipe_state *) ctx; + dma_addr_t src_addr, dst_addr; + repeat_row_addrs(s->rctx, s->src, s->dst, task->row, &src_addr, &dst_addr); + dma_queue_push(dma_q, dma_make_data(dst_addr, out_spad), + s->dst_row_bytes, s->dst_buf_bytes, s->dst_row_bytes, 1); +} + +static void repeat_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + const struct htp_repeat_context * rctx = (const struct htp_repeat_context *) data; + struct htp_ops_context * octx = rctx->octx; + const struct htp_tensor * src = octx->src[0]; + const struct htp_tensor * dst = octx->dst; - const uint32_t nb00 = src->nb[0]; - const uint32_t nb01 = src->nb[1]; - const uint32_t nb02 = src->nb[2]; - const uint32_t nb03 = src->nb[3]; + const uint32_t row_start = rctx->row_start + rctx->nrows_per_hvx * ith; + const uint32_t row_end = MIN(row_start + rctx->nrows_per_hvx, rctx->row_start + rctx->total_dst_rows); + if (row_start >= row_end) { + return; + } - const uint32_t ne0 = dst->ne[0]; - const uint32_t ne1 = dst->ne[1]; - const uint32_t ne2 = dst->ne[2]; - const uint32_t ne3 = dst->ne[3]; + uint8_t * src_vtcm_base = rctx->vtcm_src + ith * rctx->src_bytes_per_hvx; + uint8_t * dst_vtcm_base = rctx->vtcm_dst + ith * rctx->dst_bytes_per_hvx; + void * in_buf[2] = { src_vtcm_base, src_vtcm_base + rctx->src_buf_bytes }; + void * out_buf[2] = { dst_vtcm_base, dst_vtcm_base + rctx->dst_buf_bytes }; + + struct repeat_pipe_state s = { + .rctx = rctx, + .src = src, + .dst = dst, + .fill_vtcm = rctx->fill_vtcm, + .src_row_bytes = (size_t) src->ne[0] * rctx->src_elem_size, + .dst_row_bytes = (size_t) dst->ne[0] * rctx->dst_elem_size, + .src_buf_bytes = rctx->src_buf_bytes, + .dst_buf_bytes = rctx->dst_buf_bytes, + .ne00 = src->ne[0], + .nr0 = rctx->kparams->nr0, + .dst_elem_size = rctx->dst_elem_size, + .row = row_start, + .row_end = row_end, + }; - const uint32_t nb0 = dst->nb[0]; - const uint32_t nb1 = dst->nb[1]; - const uint32_t nb2 = dst->nb[2]; - const uint32_t nb3 = dst->nb[3]; + dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, repeat_next_task, repeat_push_in, repeat_compute, repeat_push_out); - const uint32_t nr0 = kparams->nr0; + FARF(HIGH, "repeat %d/%d: (%ux%ux%ux%u) -> (%ux%ux%ux%u) rows %u:%u\n", + ith, nth, src->ne[0], src->ne[1], src->ne[2], src->ne[3], + dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3], + row_start, row_end); +} - const size_t row_bytes = ne00 * rctx->type_size; +static void repeat_thread_tiled(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + const struct htp_repeat_context * rctx = (const struct htp_repeat_context *) data; + struct htp_ops_context * octx = rctx->octx; + const struct htp_tensor * src = octx->src[0]; + const struct htp_tensor * dst = octx->dst; const uint32_t row_start = rctx->row_start + rctx->nrows_per_hvx * ith; const uint32_t row_end = MIN(row_start + rctx->nrows_per_hvx, rctx->row_start + rctx->total_dst_rows); @@ -66,34 +257,61 @@ static void repeat_job_per_hvx(const htp_thread_t * th, unsigned int nth, unsign return; } - struct htp_thread_trace * tr = th->trace; - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, row_start); + const uint32_t ne00 = src->ne[0]; + const uint32_t nr0 = rctx->kparams->nr0; + const uint32_t src_elem_size = rctx->src_elem_size; + const uint32_t dst_elem_size = rctx->dst_elem_size; + const uint32_t tile_elems = rctx->tile_elems; + const uint32_t dst_reps = rctx->dst_reps; - for (uint32_t dst_row = row_start; dst_row < row_end; dst_row++) { - // Decompose flat dst row index into (i1, i2, i3) - const uint32_t dst_row_div_ne1 = fastdiv(dst_row, &kparams->div_ne1); - const uint32_t i1 = dst_row - dst_row_div_ne1 * ne1; - const uint32_t i3 = fastdiv(dst_row, &kparams->div_ne12); - const uint32_t i2 = dst_row_div_ne1 - i3 * ne2; + uint8_t * src_vtcm = rctx->vtcm_src + ith * rctx->src_bytes_per_hvx; + uint8_t * dst_vtcm = rctx->vtcm_dst + ith * rctx->dst_bytes_per_hvx; - // Map to source indices (tiling) - const uint32_t k1 = fastmodulo(i1, ne01, &kparams->div_ne01); - const uint32_t k2 = fastmodulo(i2, ne02, &kparams->div_ne02); - const uint32_t k3 = fastmodulo(i3, ne03, &kparams->div_ne03); + dma_queue * dma_q = th->dma_q; + struct htp_thread_trace * tr = th->trace; + const repeat_fill_vtcm_fn_t fill_vtcm = rctx->fill_vtcm; - const uint8_t * src_row = (const uint8_t *) src->data + k1 * nb01 + k2 * nb02 + k3 * nb03; - uint8_t * dst_base = (uint8_t *) dst->data + i1 * nb1 + i2 * nb2 + i3 * nb3; + if (tile_elems == ne00) { + const size_t src_row_bytes = (size_t) ne00 * src_elem_size; + const size_t dst_unit_bytes = (size_t) ne00 * dst_elem_size; - // Tile along dimension 0 - for (uint32_t i0 = 0; i0 < nr0; i0++) { - uint8_t * dst_ptr = dst_base + i0 * ne00 * nb0; - memcpy(dst_ptr, src_row, row_bytes); + for (uint32_t ir = row_start; ir < row_end; ir++) { + dma_addr_t src_addr, dst_addr; + repeat_row_addrs(rctx, src, dst, ir, &src_addr, &dst_addr); + + dma_sync_read(dma_q, src_vtcm, src_addr, src_row_bytes); + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); + fill_vtcm(dst_vtcm, src_vtcm, ne00, dst_reps, dst_elem_size); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); + + for (uint32_t r = 0; r < nr0; r += dst_reps) { + const uint32_t cnt = MIN(dst_reps, nr0 - r); + dma_sync_write(dma_q, dst_addr + (size_t) r * dst_unit_bytes, dst_vtcm, (size_t) cnt * dst_unit_bytes); + } + } + } else { + for (uint32_t ir = row_start; ir < row_end; ir++) { + dma_addr_t src_addr, dst_addr; + repeat_row_addrs(rctx, src, dst, ir, &src_addr, &dst_addr); + + for (uint32_t col0 = 0; col0 < ne00; col0 += tile_elems) { + const uint32_t cnt = MIN(tile_elems, ne00 - col0); + dma_sync_read(dma_q, src_vtcm, src_addr + (size_t) col0 * src_elem_size, (size_t) cnt * src_elem_size); + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); + fill_vtcm(dst_vtcm, src_vtcm, cnt, 1, dst_elem_size); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); + + for (uint32_t i0 = 0; i0 < nr0; i0++) { + const dma_addr_t d = dst_addr + ((size_t) i0 * ne00 + col0) * dst_elem_size; + dma_sync_write(dma_q, d, dst_vtcm, (size_t) cnt * dst_elem_size); + } + } } } - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, row_start); - - FARF(HIGH, "repeat %d/%d: (%ux%ux%ux%u) -> (%ux%ux%ux%u) rows %u:%u\n", + FARF(HIGH, "repeat-tiled %d/%d: (%ux%ux%ux%u) -> (%ux%ux%ux%u) rows %u:%u\n", ith, nth, src->ne[0], src->ne[1], src->ne[2], src->ne[3], dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3], row_start, row_end); @@ -103,36 +321,26 @@ int op_repeat(struct htp_ops_context * octx) { const struct htp_tensor * src0 = octx->src[0]; const struct htp_tensor * dst = octx->dst; - size_t type_size; - switch (src0->type) { - case HTP_TYPE_F32: type_size = 4; break; - case HTP_TYPE_F16: type_size = 2; break; - default: - FARF(ERROR, "repeat: unsupported type %u\n", src0->type); - return HTP_STATUS_NO_SUPPORT; - } - - if (htp_tensor_is_extended(src0) || htp_tensor_is_extended(dst)) { + if ((src0->type != HTP_TYPE_F32 && src0->type != HTP_TYPE_F16) || + (dst->type != src0->type && !(src0->type == HTP_TYPE_F32 && dst->type == HTP_TYPE_F16))) { + FARF(ERROR, "repeat: unsupported types %u -> %u\n", src0->type, dst->type); return HTP_STATUS_NO_SUPPORT; } + const uint32_t src_elem_size = (src0->type == HTP_TYPE_F16) ? 2 : 4; + const uint32_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? 2 : 4; + const struct htp_repeat_kernel_params * kparams = (const struct htp_repeat_kernel_params *) octx->kernel_params; - if (!htp_ops_context_set_n_hvx(octx, kparams->n_hvx)) { - return HTP_STATUS_INVAL_PARAMS; - } - - const uint32_t total_dst_rows = dst->ne[1] * dst->ne[2] * dst->ne[3]; - const size_t dst_row_size = dst->ne[0] * type_size; + const uint32_t total_dst_rows = dst->ne[1] * dst->ne[2] * dst->ne[3]; uint32_t row_start = 0; uint32_t nrows = total_dst_rows; if (octx->ctx->mdev.count > 1) { - uint32_t rows_per_chunk = 0; - htp_tensor_mdev_rows_per_chunk(dst, type_size, (uint32_t) dst_row_size, &rows_per_chunk); - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_dst_rows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( + total_dst_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); row_start = range.start; nrows = range.count; } @@ -141,23 +349,54 @@ int op_repeat(struct htp_ops_context * octx) { return HTP_STATUS_OK; } - const uint32_t n_hvx = octx->n_hvx; + if (!htp_ops_context_set_n_hvx(octx, MIN(kparams->n_hvx, nrows))) { + return HTP_STATUS_INVAL_PARAMS; + } + + const uint32_t n_hvx = octx->n_hvx; + const uint32_t n_bufs = kparams->pipelined ? 2 : 1; + + struct htp_repeat_vtcm_layout layout; + htp_repeat_vtcm_layout_build(&layout, + (size_t) kparams->tile_elems * src_elem_size, + (size_t) kparams->tile_elems * kparams->dst_reps * dst_elem_size, + n_bufs, n_hvx); + + if (octx->ctx->vtcm_size < layout.total_bytes) { + FARF(ERROR, "repeat: VTCM size %zu is too small, needed %zu\n", octx->ctx->vtcm_size, layout.total_bytes); + return HTP_STATUS_VTCM_TOO_SMALL; + } + + uint8_t * vtcm_base = octx->ctx->vtcm_base; struct htp_repeat_context rctx = { - .octx = octx, - .kparams = kparams, - .nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div), - .total_dst_rows = nrows, - .row_start = row_start, - .type_size = type_size, + .octx = octx, + .kparams = kparams, + .fill_vtcm = (src0->type == dst->type) ? repeat_fill_vtcm_same : repeat_fill_vtcm_f32_to_f16, + .data_src = (dma_addr_t) src0->data, + .data_dst = (dma_addr_t) dst->data, + .vtcm_src = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_src), + .vtcm_dst = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_dst), + .src_buf_bytes = layout.src_buf_bytes, + .dst_buf_bytes = layout.dst_buf_bytes, + .src_bytes_per_hvx = layout.src_bytes_per_hvx, + .dst_bytes_per_hvx = layout.dst_bytes_per_hvx, + .nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div), + .total_dst_rows = nrows, + .row_start = row_start, + .src_elem_size = src_elem_size, + .dst_elem_size = dst_elem_size, + .tile_elems = kparams->tile_elems, + .dst_reps = kparams->dst_reps, }; - FARF(HIGH, "repeat: (%ux%ux%ux%u) -> (%ux%ux%ux%u) nr=(%u,%u,%u,%u)\n", + FARF(HIGH, "repeat: (%ux%ux%ux%u) -> (%ux%ux%ux%u) nr=(%u,%u,%u,%u) pipe=%u\n", src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3], dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3], - kparams->nr0, kparams->nr1, kparams->nr2, kparams->nr3); + kparams->nr0, kparams->nr1, kparams->nr2, kparams->nr3, kparams->pipelined); - work_queue_run(octx->ctx->hvx_queue, repeat_job_per_hvx, &rctx, n_hvx); + work_queue_func_t worker = kparams->pipelined ? repeat_thread : repeat_thread_tiled; + work_queue_run(octx->ctx->hvx_queue, worker, &rctx, n_hvx); return HTP_STATUS_OK; } diff --git a/ggml/src/ggml-hexagon/htp/repeat-ops.h b/ggml/src/ggml-hexagon/htp/repeat-ops.h index 1561994d49db..7fcb49470148 100644 --- a/ggml/src/ggml-hexagon/htp/repeat-ops.h +++ b/ggml/src/ggml-hexagon/htp/repeat-ops.h @@ -1,15 +1,51 @@ #ifndef HTP_REPEAT_OPS_H #define HTP_REPEAT_OPS_H +#include "hex-common.h" #include "hex-fastdiv.h" +#include "htp-vtcm.h" +#include #include +struct htp_repeat_vtcm_layout { + size_t src_buf_bytes; + size_t dst_buf_bytes; + size_t src_bytes_per_hvx; + size_t dst_bytes_per_hvx; + size_t off_src; + size_t off_dst; + size_t total_bytes; +}; + +static inline void htp_repeat_vtcm_layout_build( + struct htp_repeat_vtcm_layout * L, + size_t src_tile_bytes, + size_t dst_tile_bytes, + uint32_t n_bufs, + uint32_t n_hvx +) { + size_t off = 0; + + L->src_buf_bytes = hex_round_up(src_tile_bytes, 128); + L->dst_buf_bytes = hex_round_up(dst_tile_bytes, 128); + L->src_bytes_per_hvx = (size_t) n_bufs * L->src_buf_bytes; + L->dst_bytes_per_hvx = (size_t) n_bufs * L->dst_buf_bytes; + + VTCM_LAYOUT_ALLOC(off, off_src, (size_t) n_hvx * L->src_bytes_per_hvx); + VTCM_LAYOUT_ALLOC(off, off_dst, (size_t) n_hvx * L->dst_bytes_per_hvx); + L->total_bytes = off; +} + struct htp_repeat_kernel_params { uint32_t n_hvx; uint32_t nr0; uint32_t nr1; uint32_t nr2; uint32_t nr3; + uint32_t tile_elems; + uint32_t dst_reps; + uint32_t pipelined; + uint32_t vtcm_size; struct fastdiv_values div_ne1; struct fastdiv_values div_ne12; diff --git a/ggml/src/ggml-hexagon/htp/roll-ops.c b/ggml/src/ggml-hexagon/htp/roll-ops.c index aa7a0ad4b754..6279985baa0b 100644 --- a/ggml/src/ggml-hexagon/htp/roll-ops.c +++ b/ggml/src/ggml-hexagon/htp/roll-ops.c @@ -1,13 +1,10 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include #include #include "dma-queue.h" +#include "dma-pipeline.h" #include "hvx-utils.h" #define GGML_COMMON_DECL_C @@ -17,15 +14,22 @@ #include "htp-trace.h" #include "htp-ops.h" #include "htp-tensor.h" +#include "htp-vtcm.h" #include "roll-ops.h" struct htp_roll_context { - struct htp_ops_context * octx; + struct htp_ops_context * octx; const struct htp_roll_kernel_params * kparams; + uint8_t * vtcm_src; + uint8_t * vtcm_dst; + size_t row_size_aligned; + size_t src_bytes_per_hvx; + size_t dst_bytes_per_hvx; uint32_t row_start; uint32_t nrows; uint32_t nrows_per_hvx; + uint32_t use_vtcm; }; static inline uint32_t htp_roll_wrap(int32_t i, uint32_t ne) { @@ -38,32 +42,32 @@ static inline uint32_t htp_roll_wrap(int32_t i, uint32_t ne) { return (uint32_t) i; } -#define htp_roll_preamble \ - const struct htp_tensor * src0 = octx->src[0]; \ - const struct htp_tensor * dst = octx->dst; \ - const struct htp_roll_kernel_params * kparams = \ - (const struct htp_roll_kernel_params *) octx->kernel_params; \ - \ - const uint32_t ne0 = dst->ne[0]; \ - const uint32_t ne1 = dst->ne[1]; \ - const uint32_t ne2 = dst->ne[2]; \ - const uint32_t ne3 = dst->ne[3]; \ - \ - const uint32_t nb01 = src0->nb[1]; \ - const uint32_t nb02 = src0->nb[2]; \ - const uint32_t nb03 = src0->nb[3]; \ - \ - const uint32_t nb1 = dst->nb[1]; \ - const uint32_t nb2 = dst->nb[2]; \ - const uint32_t nb3 = dst->nb[3]; \ - \ - const int32_t s0 = octx->op_params[0]; \ - const int32_t s1 = octx->op_params[1]; \ - const int32_t s2 = octx->op_params[2]; \ - const int32_t s3 = octx->op_params[3]; \ - \ - const uint32_t i0_src0 = kparams->i0_src0; \ - const uint32_t n0 = kparams->n0; +#define htp_roll_preamble \ + const struct htp_tensor * src0 = octx->src[0]; \ + const struct htp_tensor * dst = octx->dst; \ + const struct htp_roll_kernel_params * kparams = \ + (const struct htp_roll_kernel_params *) octx->kernel_params; \ + \ + const uint32_t __attribute__((unused)) ne0 = dst->ne[0]; \ + const uint32_t __attribute__((unused)) ne1 = dst->ne[1]; \ + const uint32_t __attribute__((unused)) ne2 = dst->ne[2]; \ + const uint32_t __attribute__((unused)) ne3 = dst->ne[3]; \ + \ + const uint32_t __attribute__((unused)) nb01 = src0->nb[1]; \ + const uint32_t __attribute__((unused)) nb02 = src0->nb[2]; \ + const uint32_t __attribute__((unused)) nb03 = src0->nb[3]; \ + \ + const uint32_t __attribute__((unused)) nb1 = dst->nb[1]; \ + const uint32_t __attribute__((unused)) nb2 = dst->nb[2]; \ + const uint32_t __attribute__((unused)) nb3 = dst->nb[3]; \ + \ + const int32_t __attribute__((unused)) s0 = octx->op_params[0]; \ + const int32_t __attribute__((unused)) s1 = octx->op_params[1]; \ + const int32_t __attribute__((unused)) s2 = octx->op_params[2]; \ + const int32_t __attribute__((unused)) s3 = octx->op_params[3]; \ + \ + const uint32_t __attribute__((unused)) i0_src0 = kparams->i0_src0; \ + const uint32_t __attribute__((unused)) n0 = kparams->n0; #define htp_roll_dma_preamble dma_queue * q = octx->ctx->dma[0]; @@ -93,14 +97,15 @@ static inline void roll_dma_push_rows(dma_queue * q, uint32_t nrows, uint32_t row_size, uint32_t i0_src0, - uint32_t n0) { + uint32_t n0, + uint32_t elem_size) { const dma_addr_t dst_base = dst->data + (size_t) dst_row * row_size; const dma_addr_t src_base = src0->data + (size_t) src_row * row_size; - roll_dma_push(q, dst_base, src_base + (size_t) i0_src0 * sizeof(float), - row_size, row_size, n0 * sizeof(float), nrows); - roll_dma_push(q, dst_base + (size_t) n0 * sizeof(float), src_base, - row_size, row_size, i0_src0 * sizeof(float), nrows); + roll_dma_push(q, dst_base, src_base + (size_t) i0_src0 * elem_size, + row_size, row_size, n0 * elem_size, nrows); + roll_dma_push(q, dst_base + (size_t) n0 * elem_size, src_base, + row_size, row_size, i0_src0 * elem_size, nrows); } // Same row-wrap split as roll_dma_push_rows, but addressed with explicit byte strides so it @@ -112,21 +117,23 @@ static inline void roll_dma_push_range(dma_queue * q, uint32_t src_stride, uint32_t nrows, uint32_t i0_src0, - uint32_t n0) { - roll_dma_push(q, dst_row, src_row + (size_t) i0_src0 * sizeof(float), - dst_stride, src_stride, n0 * sizeof(float), nrows); - roll_dma_push(q, dst_row + (size_t) n0 * sizeof(float), src_row, - dst_stride, src_stride, i0_src0 * sizeof(float), nrows); + uint32_t n0, + uint32_t elem_size) { + roll_dma_push(q, dst_row, src_row + (size_t) i0_src0 * elem_size, + dst_stride, src_stride, n0 * elem_size, nrows); + roll_dma_push(q, dst_row + (size_t) n0 * elem_size, src_row, + dst_stride, src_stride, i0_src0 * elem_size, nrows); } -static int roll_dma_f32_contiguous(struct htp_ops_context * octx) { +static int roll_dma_contiguous(struct htp_ops_context * octx) { htp_roll_preamble; htp_roll_dma_preamble; - const uint32_t row_size = ne0 * sizeof(float); + const uint32_t elem_size = kparams->elem_size; + const uint32_t row_size = ne0 * elem_size; if (s1 == 0 && s2 == 0 && s3 == 0) { - roll_dma_push_rows(q, dst, src0, 0, 0, ne1 * ne2 * ne3, row_size, i0_src0, n0); + roll_dma_push_rows(q, dst, src0, 0, 0, ne1 * ne2 * ne3, row_size, i0_src0, n0, elem_size); dma_queue_flush(q); return HTP_STATUS_OK; } @@ -140,9 +147,9 @@ static int roll_dma_f32_contiguous(struct htp_ops_context * octx) { const uint32_t n2_first = ne2 - i2_src0; roll_dma_push_rows(q, dst, src0, dst_row0, src_row0, n2_first * ne1, - row_size, i0_src0, n0); + row_size, i0_src0, n0, elem_size); roll_dma_push_rows(q, dst, src0, dst_row0 + n2_first * ne1, i03 * ne2 * ne1, - i2_src0 * ne1, row_size, i0_src0, n0); + i2_src0 * ne1, row_size, i0_src0, n0, elem_size); } dma_queue_flush(q); @@ -160,9 +167,9 @@ static int roll_dma_f32_contiguous(struct htp_ops_context * octx) { const uint32_t src_row0 = (i03 * ne2 + i02) * ne1; roll_dma_push_rows(q, dst, src0, dst_row0, src_row0 + i1_src0, - n1_first, row_size, i0_src0, n0); + n1_first, row_size, i0_src0, n0, elem_size); roll_dma_push_rows(q, dst, src0, dst_row0 + n1_first, src_row0, - i1_src0, row_size, i0_src0, n0); + i1_src0, row_size, i0_src0, n0, elem_size); } } @@ -173,12 +180,13 @@ static int roll_dma_f32_contiguous(struct htp_ops_context * octx) { // DMA path for a row-contiguous but otherwise arbitrarily strided src0 (e.g. a permuted view). // Same row-wrap split as above, one DMA push per (i2,i3), addressed via the real nb01/nb02/nb03 // instead of assuming a packed layout. -static int roll_dma_f32_strided(struct htp_ops_context * octx) { +static int roll_dma_strided(struct htp_ops_context * octx) { htp_roll_preamble; htp_roll_dma_preamble; - const uint32_t i1_src0 = htp_roll_wrap(-s1, ne1); - const uint32_t n1_first = ne1 - i1_src0; + const uint32_t elem_size = kparams->elem_size; + const uint32_t i1_src0 = htp_roll_wrap(-s1, ne1); + const uint32_t n1_first = ne1 - i1_src0; for (uint32_t i3 = 0; i3 < ne3; i3++) { const uint32_t i03 = htp_roll_wrap((int32_t) i3 - s3, ne3); @@ -189,9 +197,9 @@ static int roll_dma_f32_strided(struct htp_ops_context * octx) { const dma_addr_t src_row0 = src0->data + (size_t) i02 * nb02 + (size_t) i03 * nb03; roll_dma_push_range(q, dst_row0, src_row0 + (size_t) i1_src0 * nb01, - nb1, nb01, n1_first, i0_src0, n0); + nb1, nb01, n1_first, i0_src0, n0, elem_size); roll_dma_push_range(q, dst_row0 + (size_t) n1_first * nb1, src_row0, - nb1, nb01, i1_src0, i0_src0, n0); + nb1, nb01, i1_src0, i0_src0, n0, elem_size); } } @@ -199,9 +207,104 @@ static int roll_dma_f32_strided(struct htp_ops_context * octx) { return HTP_STATUS_OK; } -static void roll_thread_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { +static inline void roll_row_addrs( + const struct htp_tensor * src0, + const struct htp_tensor * dst, + const struct htp_roll_kernel_params * kparams, + uint32_t row, + int32_t s1, + int32_t s2, + int32_t s3, + dma_addr_t * src_addr, + dma_addr_t * dst_addr +) { + const uint32_t ne1 = dst->ne[1]; + const uint32_t ne2 = dst->ne[2]; + const uint32_t ne3 = dst->ne[3]; + + const uint32_t i3 = fastdiv(row, &kparams->div_ne2_ne1); + const uint32_t rem = row - i3 * ne2 * ne1; + const uint32_t i2 = fastdiv(rem, &kparams->div_ne1); + const uint32_t i1 = rem - i2 * ne1; + + const uint32_t i01 = htp_roll_wrap((int32_t) i1 - s1, ne1); + const uint32_t i02 = htp_roll_wrap((int32_t) i2 - s2, ne2); + const uint32_t i03 = htp_roll_wrap((int32_t) i3 - s3, ne3); + + *src_addr = src0->data + (size_t) i01 * src0->nb[1] + (size_t) i02 * src0->nb[2] + (size_t) i03 * src0->nb[3]; + *dst_addr = dst->data + (size_t) i1 * dst->nb[1] + (size_t) i2 * dst->nb[2] + (size_t) i3 * dst->nb[3]; +} + +static void __attribute__((noinline)) roll_copy_row_vtcm( + uint8_t * restrict dst_vtcm, + const uint8_t * restrict src_vtcm, + uint32_t ne0, + uint32_t i0_src0, + uint32_t n0, + uint32_t elem_size +) { + if (i0_src0 == 0) { + hvx_copy_aa(dst_vtcm, src_vtcm, ne0 * elem_size, 1); + } else { + const uint32_t n0_bytes = n0 * elem_size; + const uint32_t i0_src0_bytes = i0_src0 * elem_size; + hvx_copy_au(dst_vtcm, src_vtcm + i0_src0_bytes, n0_bytes, 1); + hvx_copy_ua(dst_vtcm + n0_bytes, src_vtcm, i0_src0_bytes, 1); + } +} + +struct roll_pipe_state { + const struct htp_tensor * src0; + const struct htp_tensor * dst; + const struct htp_roll_kernel_params * kparams; + size_t row_size; + size_t row_size_aligned; + uint32_t ne0; + uint32_t i0_src0; + uint32_t n0; + uint32_t elem_size; + int32_t s1, s2, s3; + uint32_t row; + uint32_t row_end; +}; + +static bool roll_next_task(void * ctx, struct dma_pipe_task * task) { + struct roll_pipe_state * s = (struct roll_pipe_state *) ctx; + if (s->row >= s->row_end) { + return false; + } + task->row = s->row++; + task->off = 0; + task->len = 0; + task->aux = 0; + return true; +} + +static void roll_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct roll_pipe_state * s = (struct roll_pipe_state *) ctx; + dma_addr_t src_addr, dst_addr; + roll_row_addrs(s->src0, s->dst, s->kparams, task->row, s->s1, s->s2, s->s3, &src_addr, &dst_addr); + dma_queue_push(dma_q, dma_make_data(in_spad, src_addr), + s->row_size_aligned, s->row_size, s->row_size, 1); +} + +static void roll_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + (void) task; + struct roll_pipe_state * s = (struct roll_pipe_state *) ctx; + roll_copy_row_vtcm((uint8_t *) out_spad, (const uint8_t *) in_spad, s->ne0, s->i0_src0, s->n0, s->elem_size); +} + +static void roll_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) { + struct roll_pipe_state * s = (struct roll_pipe_state *) ctx; + dma_addr_t src_addr, dst_addr; + roll_row_addrs(s->src0, s->dst, s->kparams, task->row, s->s1, s->s2, s->s3, &src_addr, &dst_addr); + dma_queue_push(dma_q, dma_make_data(dst_addr, out_spad), + s->row_size, s->row_size_aligned, s->row_size, 1); +} + +static void roll_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { struct htp_roll_context * rctx = (struct htp_roll_context *) data; - struct htp_ops_context * octx = rctx->octx; + struct htp_ops_context * octx = rctx->octx; htp_roll_preamble; @@ -211,58 +314,68 @@ static void roll_thread_f32(const htp_thread_t * th, unsigned int nth, unsigned return; } - struct htp_thread_trace * tr = th->trace; - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, row_start); - - for (uint32_t row = row_start; row < row_end; row++) { - const uint32_t i3 = fastdiv(row, &kparams->div_ne2_ne1); - const uint32_t rem = row - i3 * ne2 * ne1; - const uint32_t i2 = fastdiv(rem, &kparams->div_ne1); - const uint32_t i1 = rem - i2 * ne1; + dma_queue * dma_q = th->dma_q; + const uint32_t elem_size = kparams->elem_size; + const size_t row_size = (size_t) ne0 * elem_size; - const uint32_t i01 = htp_roll_wrap((int32_t) i1 - s1, ne1); - const uint32_t i02 = htp_roll_wrap((int32_t) i2 - s2, ne2); - const uint32_t i03 = htp_roll_wrap((int32_t) i3 - s3, ne3); - - const uint8_t * src_row = (const uint8_t *) (uintptr_t) src0->data + i01*nb01 + i02*nb02 + i03*nb03; - uint8_t * dst_row = (uint8_t *) (uintptr_t) dst->data + i1*nb1 + i2*nb2 + i3*nb3; - - hex_l2fetch(src_row + i0_src0 * sizeof(float), n0 * sizeof(float), ne0 * sizeof(float), 1); - hvx_copy_uu(dst_row, src_row + i0_src0 * sizeof(float), n0, sizeof(float)); - - if (i0_src0 != 0) { - hex_l2fetch(src_row, i0_src0 * sizeof(float), ne0 * sizeof(float), 1); - hvx_copy_uu(dst_row + n0 * sizeof(float), src_row, i0_src0, sizeof(float)); + if (!rctx->use_vtcm) { + for (uint32_t row = row_start; row < row_end; row++) { + dma_addr_t src_addr, dst_addr; + roll_row_addrs(src0, dst, kparams, row, s1, s2, s3, &src_addr, &dst_addr); + roll_dma_push_range(dma_q, dst_addr, src_addr, nb1, nb01, 1, i0_src0, n0, elem_size); } + dma_queue_flush(dma_q); + return; } - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, row_start); + const size_t row_size_aligned = rctx->row_size_aligned; + uint8_t * src_vtcm_base = rctx->vtcm_src + ith * rctx->src_bytes_per_hvx; + uint8_t * dst_vtcm_base = rctx->vtcm_dst + ith * rctx->dst_bytes_per_hvx; + void * in_buf[2] = { src_vtcm_base, src_vtcm_base + row_size_aligned }; + void * out_buf[2] = { dst_vtcm_base, dst_vtcm_base + row_size_aligned }; + + struct roll_pipe_state s = { + .src0 = src0, + .dst = dst, + .kparams = kparams, + .row_size = row_size, + .row_size_aligned = row_size_aligned, + .ne0 = ne0, + .i0_src0 = i0_src0, + .n0 = n0, + .elem_size = elem_size, + .s1 = s1, .s2 = s2, .s3 = s3, + .row = row_start, + .row_end = row_end, + }; + + dma_pipe_io_run(dma_q, th->trace, &s, in_buf, out_buf, roll_next_task, roll_push_in, roll_compute, roll_push_out); FARF(HIGH, "roll %d/%d: (%ux%ux%ux%u) rows %u:%u shift=(%d,%d,%d,%d)\n", ith, nth, ne0, ne1, ne2, ne3, row_start, row_end, s0, s1, s2, s3); } -int execute_op_roll_f32(struct htp_ops_context * octx) { +static int execute_op_roll(struct htp_ops_context * octx) { htp_roll_preamble; if (kparams->kernel_type == HTP_ROLL_KERNEL_DMA_CONTIGUOUS) { - return roll_dma_f32_contiguous(octx); + return roll_dma_contiguous(octx); } if (kparams->kernel_type == HTP_ROLL_KERNEL_DMA_STRIDED) { - return roll_dma_f32_strided(octx); + return roll_dma_strided(octx); } - const uint32_t total_rows = kparams->total_rows; - const size_t dst_row_size = ne0 * sizeof(float); + const uint32_t total_rows = kparams->total_rows; + const uint32_t elem_size = kparams->elem_size; + const size_t dst_row_size = (size_t) ne0 * elem_size; uint32_t row_start = 0; uint32_t nrows = total_rows; if (octx->ctx->mdev.count > 1) { - uint32_t rows_per_chunk = 0; - htp_tensor_mdev_rows_per_chunk(dst, sizeof(float), (uint32_t) dst_row_size, &rows_per_chunk); - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_rows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( + total_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); row_start = range.start; nrows = range.count; } @@ -271,32 +384,51 @@ int execute_op_roll_f32(struct htp_ops_context * octx) { return HTP_STATUS_OK; } - if (htp_tensor_is_extended(src0) || htp_tensor_is_extended(dst)) { - return HTP_STATUS_NO_SUPPORT; - } - if (!htp_ops_context_set_n_hvx(octx, MIN(kparams->n_hvx, nrows))) { return HTP_STATUS_INVAL_PARAMS; } - const uint32_t n_hvx = octx->n_hvx; + const uint32_t n_hvx = octx->n_hvx; + const uint32_t use_vtcm = (kparams->vtcm_size > 0) ? 1 : 0; + + struct htp_roll_vtcm_layout layout = { 0 }; + if (use_vtcm) { + htp_roll_vtcm_layout_build(&layout, dst_row_size, n_hvx); + if (octx->ctx->vtcm_size < layout.total_bytes) { + FARF(ERROR, "roll: VTCM size %zu is too small, needed %zu\n", octx->ctx->vtcm_size, layout.total_bytes); + return HTP_STATUS_VTCM_TOO_SMALL; + } + } + + uint8_t * vtcm_base = octx->ctx->vtcm_base; + struct htp_roll_context rctx = { - .octx = octx, - .kparams = kparams, - .row_start = row_start, - .nrows = nrows, - .nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div), + .octx = octx, + .kparams = kparams, + .vtcm_src = use_vtcm ? VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_src) : NULL, + .vtcm_dst = use_vtcm ? VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_dst) : NULL, + .row_size_aligned = layout.row_size_aligned, + .src_bytes_per_hvx = layout.src_bytes_per_hvx, + .dst_bytes_per_hvx = layout.dst_bytes_per_hvx, + .row_start = row_start, + .nrows = nrows, + .nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div), + .use_vtcm = use_vtcm, }; - work_queue_run(octx->ctx->hvx_queue, roll_thread_f32, &rctx, n_hvx); + work_queue_run(octx->ctx->hvx_queue, roll_thread, &rctx, n_hvx); return HTP_STATUS_OK; } int op_roll(struct htp_ops_context * octx) { + if (octx->src[0]->type != octx->dst->type) { + return HTP_STATUS_NO_SUPPORT; + } switch (octx->src[0]->type) { case HTP_TYPE_F32: - return execute_op_roll_f32(octx); + case HTP_TYPE_F16: + return execute_op_roll(octx); default: return HTP_STATUS_NO_SUPPORT; diff --git a/ggml/src/ggml-hexagon/htp/roll-ops.h b/ggml/src/ggml-hexagon/htp/roll-ops.h index f98fb8ea9074..8774aee972fe 100644 --- a/ggml/src/ggml-hexagon/htp/roll-ops.h +++ b/ggml/src/ggml-hexagon/htp/roll-ops.h @@ -1,7 +1,10 @@ #ifndef HTP_ROLL_OPS_H #define HTP_ROLL_OPS_H +#include "hex-common.h" #include "hex-fastdiv.h" +#include "htp-vtcm.h" +#include #include enum htp_roll_kernel_type { @@ -10,12 +13,39 @@ enum htp_roll_kernel_type { HTP_ROLL_KERNEL_HVX = 3, }; +struct htp_roll_vtcm_layout { + size_t row_size_aligned; + size_t src_bytes_per_hvx; + size_t dst_bytes_per_hvx; + size_t off_src; + size_t off_dst; + size_t total_bytes; +}; + +static inline void htp_roll_vtcm_layout_build( + struct htp_roll_vtcm_layout * L, + size_t row_size, + uint32_t n_hvx +) { + size_t off = 0; + + L->row_size_aligned = hex_round_up(row_size, 128); + L->src_bytes_per_hvx = 2 * L->row_size_aligned; + L->dst_bytes_per_hvx = 2 * L->row_size_aligned; + + VTCM_LAYOUT_ALLOC(off, off_src, (size_t) n_hvx * L->src_bytes_per_hvx); + VTCM_LAYOUT_ALLOC(off, off_dst, (size_t) n_hvx * L->dst_bytes_per_hvx); + L->total_bytes = off; +} + struct htp_roll_kernel_params { uint8_t kernel_type; uint32_t n_hvx; uint32_t total_rows; uint32_t i0_src0; uint32_t n0; + uint32_t elem_size; + uint32_t vtcm_size; struct fastdiv_values div_ne1; struct fastdiv_values div_ne2_ne1; diff --git a/ggml/src/ggml-hexagon/htp/rope-ops.c b/ggml/src/ggml-hexagon/htp/rope-ops.c index 1c73de10b50f..b6924ee6eb35 100644 --- a/ggml/src/ggml-hexagon/htp/rope-ops.c +++ b/ggml/src/ggml-hexagon/htp/rope-ops.c @@ -1,7 +1,3 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include @@ -28,39 +24,34 @@ #define HTP_ROPE_TYPE_IMROPE 40 #define htp_rope_preamble \ - const uint32_t ne00 = src0->ne[0]; \ - const uint32_t ne01 = src0->ne[1]; \ - const uint32_t ne02 = src0->ne[2]; \ - const uint32_t ne03 = src0->ne[3]; \ - \ - const uint32_t ne0 = dst->ne[0]; \ const uint32_t ne1 = dst->ne[1]; \ const uint32_t ne2 = dst->ne[2]; \ const uint32_t ne3 = dst->ne[3]; \ \ - const uint32_t nb00 = src0->nb[0]; \ const uint32_t nb01 = src0->nb[1]; \ const uint32_t nb02 = src0->nb[2]; \ const uint32_t nb03 = src0->nb[3]; \ \ - const uint32_t nb0 = dst->nb[0]; \ const uint32_t nb1 = dst->nb[1]; \ const uint32_t nb2 = dst->nb[2]; \ const uint32_t nb3 = dst->nb[3]; +struct htp_rope_context; + +typedef void (*rope_compute_fn_t)(const struct htp_rope_context * rctx, uint8_t * src, uint32_t nr, const float * restrict theta_cache); + struct htp_rope_context { - int32_t n_dims; - int32_t n_offs; - int32_t mode; - int32_t n_ctx_orig; - int32_t sections[4]; + int32_t n_dims; + int32_t n_offs; + int32_t mode; + int32_t sections[4]; + uint32_t ne_rot; + + rope_compute_fn_t compute_block; - float freq_base; float freq_scale; float ext_factor; float attn_factor; - float beta_fast; - float beta_slow; float theta_scale; float theta_scale_32; float theta_powers[32]; @@ -74,19 +65,24 @@ struct htp_rope_context { size_t spad_per_hvx; size_t theta_cache_offset; - size_t src0_row_size; - size_t src0_row_stride; - size_t dst_row_size; - size_t dst_row_stride; - size_t src0_row_size_aligned; - uint32_t src0_nrows; + uint8_t * cs_table; + size_t cs_stride; + uint32_t cs_i2_base; + uint32_t cs_i2_count; + + size_t src0_row_size; + size_t src0_row_stride; + size_t dst_row_size; + size_t dst_row_stride; + size_t src0_row_size_aligned; uint32_t row_start; uint32_t nrows; struct fastdiv_values div_ne2_ne1; struct fastdiv_values div_ne1; - const float * freq_factors; + const float * freq_factors; + const int32_t * pos_data; }; static float rope_yarn_ramp(const float low, const float high, const int i0) { @@ -121,7 +117,7 @@ static inline void rope_yarn_one(float theta, float freq_scale, float * corr_dim } // 32 thetas -> 32 deinterleaved pairs [cos[32] | sin[32]] at cache[i0]. -static inline void rope_cache_hvx_32(float * cache, uint32_t i0, +static __attribute__((noinline)) void rope_cache_hvx_32(float * cache, uint32_t i0, HVX_Vector v_theta, const float * freq_factors, HVX_Vector v_freq_scale, @@ -138,13 +134,9 @@ static inline void rope_cache_hvx_32(float * cache, uint32_t i0, vcos = hvx_vec_mul_f32_f32(vcos, v_mscale); vsin = hvx_vec_mul_f32_f32(vsin, v_mscale); - if (((uintptr_t) (cache + i0)) % 128 == 0) { - hvx_vmem(cache + i0 + 0) = vcos; - hvx_vmem(cache + i0 + 32) = vsin; - } else { - hvx_vec_store_u(cache + i0 + 0, 32 * sizeof(float), vcos); - hvx_vec_store_u(cache + i0 + 32, 32 * sizeof(float), vsin); - } + assert(((uintptr_t) (cache + i0)) % 128 == 0); + hvx_vmem(cache + i0 + 0) = vcos; + hvx_vmem(cache + i0 + 32) = vsin; } static __attribute__((noinline)) void rope_cache_init(const float theta_base, @@ -280,6 +272,11 @@ static __attribute__((noinline)) void mrope_cache_init(const float pos_t, const float theta_scale, const float * theta_powers, const float theta_scale_32) { + if (!indep_sects && pos_t == pos_h && pos_t == pos_w && pos_t == pos_e) { + rope_cache_init(pos_t, freq_scale, freq_factors, corr_dims, n_cache, ext_factor, mscale, cache, theta_scale, theta_powers, theta_scale_32); + return; + } + const int sect_dims = sections[0] + sections[1] + sections[2] + sections[3]; const int sec_w = sections[0] + sections[1]; const int sec_e = sec_w + sections[2]; @@ -289,8 +286,8 @@ static __attribute__((noinline)) void mrope_cache_init(const float pos_t, const bool imrope_mod3 = is_imrope && !indep_sects && no_wrap && sections[0] > 0 && sections[1] > 0 && sections[2] > 0 && n_pairs <= (uint32_t) (3 * sections[0]) - && n_pairs <= (uint32_t) (3 * sections[1]) - && n_pairs <= (uint32_t) (3 * sections[2]); + && n_pairs <= (uint32_t) (3 * sections[1] + 1) + && n_pairs <= (uint32_t) (3 * sections[2] + 2); const bool contig = !is_imrope && !indep_sects && no_wrap; if (ext_factor == 0.0f && (imrope_mod3 || contig)) { @@ -379,18 +376,6 @@ static __attribute__((noinline)) void mrope_cache_init(const float pos_t, #define M_PI 3.1415926535897932384626433 -static void rope_corr_dims(int n_dims, - int n_ctx_orig, - float freq_base, - float beta_fast, - float beta_slow, - float * dims) { - float start = floorf(n_dims * logf(n_ctx_orig / (beta_fast * 2 * (float) M_PI)) / (2 * logf(freq_base))); - float end = ceilf(n_dims * logf(n_ctx_orig / (beta_slow * 2 * (float) M_PI)) / (2 * logf(freq_base))); - dims[0] = MAX(0, start); - dims[1] = MIN(n_dims - 1, end); -} - static inline void hvx_rope_neox_mul(HVX_Vector v0, HVX_Vector v1, HVX_Vector vcos, HVX_Vector vsin, HVX_Vector * o0, HVX_Vector * o1) { HVX_Vector vx0_c = Q6_Vqf32_vmpy_VsfVsf(v0, vcos); @@ -401,6 +386,18 @@ static inline void hvx_rope_neox_mul(HVX_Vector v0, HVX_Vector v1, HVX_Vector vc *o1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(vx0_s, vx1_c)); } +#if __HVX_ARCH__ < 79 +static inline void hvx_rope_neox_mul_qf32(HVX_Vector v0_qf, HVX_Vector v1_qf, HVX_Vector vcos_qf, HVX_Vector vsin_qf, + HVX_Vector * o0, HVX_Vector * o1) { + HVX_Vector vx0_c = Q6_Vqf32_vmpy_Vqf32Vqf32(v0_qf, vcos_qf); + HVX_Vector vx0_s = Q6_Vqf32_vmpy_Vqf32Vqf32(v0_qf, vsin_qf); + HVX_Vector vx1_c = Q6_Vqf32_vmpy_Vqf32Vqf32(v1_qf, vcos_qf); + HVX_Vector vx1_s = Q6_Vqf32_vmpy_Vqf32Vqf32(v1_qf, vsin_qf); + *o0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vsub_Vqf32Vqf32(vx0_c, vx1_s)); + *o1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(vx0_s, vx1_c)); +} +#endif + // theta_cache full 32-pair blocks are deinterleaved [cos | sin]. static inline void hvx_rope_neox_f32_aa(float * restrict dst, const float * restrict src0, uint32_t ne, const float * restrict theta_cache) { const uint32_t he = ne / 2; @@ -512,7 +509,7 @@ static inline void hvx_rope_f32_aa(float * restrict dst, const float * restrict } } -static void inline rope_basic_f32_inplace(struct htp_rope_context * rctx, uint8_t * src, +static __attribute__((noinline)) void rope_basic_f32_inplace(const struct htp_rope_context * rctx, uint8_t * src, uint32_t nr, const float * restrict theta_cache) { const uint32_t n_offs = rctx->n_offs; #pragma unroll(4) @@ -522,9 +519,10 @@ static void inline rope_basic_f32_inplace(struct htp_rope_context * rctx, uint8_ } } -static void inline rope_neox_f32_inplace(struct htp_rope_context * rctx, uint8_t * src, - uint32_t nr, uint32_t ne, const float * restrict theta_cache) { +static __attribute__((noinline)) void rope_neox_f32_inplace(const struct htp_rope_context * rctx, uint8_t * src, + uint32_t nr, const float * restrict theta_cache) { const uint32_t n_offs = rctx->n_offs; + const uint32_t ne = rctx->ne_rot; #pragma unroll(4) for (uint32_t i = 0; i < nr; i++) { float * s = (float *) (src + i * rctx->src0_row_size_aligned); @@ -532,13 +530,494 @@ static void inline rope_neox_f32_inplace(struct htp_rope_context * rctx, uint8_t } } -static void rope_job_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { +static inline HVX_Vector hvx_vec_clamp_f16_f32_vec(HVX_Vector x, HVX_Vector f16_min, HVX_Vector f16_max) { + return Q6_Vsf_vmin_VsfVsf(Q6_Vsf_vmax_VsfVsf(x, f16_min), f16_max); +} + +static __attribute__((noinline)) void hvx_rope_neox_f16_aa(_Float16 * restrict dst, const _Float16 * restrict src0, uint32_t ne, const float * restrict theta_cache) { + const uint32_t he = ne / 2; + const uint32_t nvec = he / 64; + const uint32_t nloe = he % 64; + + const HVX_Vector * vt = (const HVX_Vector *) theta_cache; + + const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f); + const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f); +#if __HVX_ARCH__ < 79 + const HVX_Vector one_hf = hvx_vec_splat_f16(1.0f); + const HVX_Vector zero = Q6_V_vzero(); +#endif + + if (nloe == 0) { + const HVX_Vector * vs = (const HVX_Vector *) src0; + HVX_Vector * vd = (HVX_Vector *) dst; + for (uint32_t i = 0; i < nvec; i++) { + HVX_Vector v0 = vs[i]; + HVX_Vector v1 = vs[nvec + i]; +#if __HVX_ARCH__ < 79 + HVX_VectorPair vp0 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v0), one_hf); + HVX_VectorPair vp1 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v1), one_hf); + + HVX_Vector vcos0_qf = Q6_Vqf32_vadd_VsfVsf(vt[i * 4 + 0], zero); + HVX_Vector vsin0_qf = Q6_Vqf32_vadd_VsfVsf(vt[i * 4 + 1], zero); + HVX_Vector vcos1_qf = Q6_Vqf32_vadd_VsfVsf(vt[i * 4 + 2], zero); + HVX_Vector vsin1_qf = Q6_Vqf32_vadd_VsfVsf(vt[i * 4 + 3], zero); + + HVX_Vector o0_lo, o1_lo, o0_hi, o1_hi; + hvx_rope_neox_mul_qf32(Q6_V_lo_W(vp0), Q6_V_lo_W(vp1), vcos0_qf, vsin0_qf, &o0_lo, &o1_lo); + hvx_rope_neox_mul_qf32(Q6_V_hi_W(vp0), Q6_V_hi_W(vp1), vcos1_qf, vsin1_qf, &o0_hi, &o1_hi); +#else + HVX_VectorPair vp0 = hvx_vec_f16_to_f32(v0); + HVX_VectorPair vp1 = hvx_vec_f16_to_f32(v1); + + HVX_Vector o0_lo, o1_lo, o0_hi, o1_hi; + hvx_rope_neox_mul(Q6_V_lo_W(vp0), Q6_V_lo_W(vp1), vt[i * 4 + 0], vt[i * 4 + 1], &o0_lo, &o1_lo); + hvx_rope_neox_mul(Q6_V_hi_W(vp0), Q6_V_hi_W(vp1), vt[i * 4 + 2], vt[i * 4 + 3], &o0_hi, &o1_hi); +#endif + HVX_Vector vout0 = hvx_vec_f32_to_f16(hvx_vec_clamp_f16_f32_vec(o0_lo, f16_min, f16_max), + hvx_vec_clamp_f16_f32_vec(o0_hi, f16_min, f16_max)); + HVX_Vector vout1 = hvx_vec_f32_to_f16(hvx_vec_clamp_f16_f32_vec(o1_lo, f16_min, f16_max), + hvx_vec_clamp_f16_f32_vec(o1_hi, f16_min, f16_max)); + + vd[i] = vout0; + vd[nvec + i] = vout1; + } + return; + } + + for (uint32_t i = 0; i < nvec; i++) { + HVX_Vector v0 = ((const HVX_Vector *) src0)[i]; + HVX_Vector v1 = hvx_vmemu(src0 + he + i * 64); +#if __HVX_ARCH__ < 79 + HVX_VectorPair vp0 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v0), one_hf); + HVX_VectorPair vp1 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v1), one_hf); + + HVX_Vector vcos0_qf = Q6_Vqf32_vadd_VsfVsf(vt[i * 4 + 0], zero); + HVX_Vector vsin0_qf = Q6_Vqf32_vadd_VsfVsf(vt[i * 4 + 1], zero); + HVX_Vector vcos1_qf = Q6_Vqf32_vadd_VsfVsf(vt[i * 4 + 2], zero); + HVX_Vector vsin1_qf = Q6_Vqf32_vadd_VsfVsf(vt[i * 4 + 3], zero); + + HVX_Vector o0_lo, o1_lo, o0_hi, o1_hi; + hvx_rope_neox_mul_qf32(Q6_V_lo_W(vp0), Q6_V_lo_W(vp1), vcos0_qf, vsin0_qf, &o0_lo, &o1_lo); + hvx_rope_neox_mul_qf32(Q6_V_hi_W(vp0), Q6_V_hi_W(vp1), vcos1_qf, vsin1_qf, &o0_hi, &o1_hi); +#else + HVX_VectorPair vp0 = hvx_vec_f16_to_f32(v0); + HVX_VectorPair vp1 = hvx_vec_f16_to_f32(v1); + + HVX_Vector o0_lo, o1_lo, o0_hi, o1_hi; + hvx_rope_neox_mul(Q6_V_lo_W(vp0), Q6_V_lo_W(vp1), vt[i * 4 + 0], vt[i * 4 + 1], &o0_lo, &o1_lo); + hvx_rope_neox_mul(Q6_V_hi_W(vp0), Q6_V_hi_W(vp1), vt[i * 4 + 2], vt[i * 4 + 3], &o0_hi, &o1_hi); +#endif + HVX_Vector vout0 = hvx_vec_f32_to_f16(hvx_vec_clamp_f16_f32_vec(o0_lo, f16_min, f16_max), + hvx_vec_clamp_f16_f32_vec(o0_hi, f16_min, f16_max)); + HVX_Vector vout1 = hvx_vec_f32_to_f16(hvx_vec_clamp_f16_f32_vec(o1_lo, f16_min, f16_max), + hvx_vec_clamp_f16_f32_vec(o1_hi, f16_min, f16_max)); + + ((HVX_Vector *) dst)[i] = vout0; + hvx_vmemu(dst + he + i * 64) = vout1; + } + + if (nloe > 0) { + HVX_Vector v0 = ((const HVX_Vector *) src0)[nvec]; + HVX_Vector v1 = hvx_vmemu(src0 + he + nvec * 64); +#if __HVX_ARCH__ < 79 + HVX_VectorPair vp0 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v0), one_hf); + HVX_VectorPair vp1 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v1), one_hf); + + HVX_Vector vcos0_qf = Q6_Vqf32_vadd_VsfVsf(vt[nvec * 4 + 0], zero); + HVX_Vector vsin0_qf = Q6_Vqf32_vadd_VsfVsf(vt[nvec * 4 + 1], zero); + + HVX_Vector o0_lo, o1_lo; + hvx_rope_neox_mul_qf32(Q6_V_lo_W(vp0), Q6_V_lo_W(vp1), vcos0_qf, vsin0_qf, &o0_lo, &o1_lo); + o0_lo = hvx_vec_clamp_f16_f32_vec(o0_lo, f16_min, f16_max); + o1_lo = hvx_vec_clamp_f16_f32_vec(o1_lo, f16_min, f16_max); + + HVX_Vector o0_hi = o0_lo; + HVX_Vector o1_hi = o1_lo; + if (nloe > 32) { + HVX_Vector vcos1_qf = Q6_Vqf32_vadd_VsfVsf(vt[nvec * 4 + 2], zero); + HVX_Vector vsin1_qf = Q6_Vqf32_vadd_VsfVsf(vt[nvec * 4 + 3], zero); + hvx_rope_neox_mul_qf32(Q6_V_hi_W(vp0), Q6_V_hi_W(vp1), vcos1_qf, vsin1_qf, &o0_hi, &o1_hi); + o0_hi = hvx_vec_clamp_f16_f32_vec(o0_hi, f16_min, f16_max); + o1_hi = hvx_vec_clamp_f16_f32_vec(o1_hi, f16_min, f16_max); + } +#else + HVX_VectorPair vp0 = hvx_vec_f16_to_f32(v0); + HVX_VectorPair vp1 = hvx_vec_f16_to_f32(v1); + + HVX_Vector o0_lo, o1_lo; + hvx_rope_neox_mul(Q6_V_lo_W(vp0), Q6_V_lo_W(vp1), vt[nvec * 4 + 0], vt[nvec * 4 + 1], &o0_lo, &o1_lo); + o0_lo = hvx_vec_clamp_f16_f32_vec(o0_lo, f16_min, f16_max); + o1_lo = hvx_vec_clamp_f16_f32_vec(o1_lo, f16_min, f16_max); + + HVX_Vector o0_hi = o0_lo; + HVX_Vector o1_hi = o1_lo; + if (nloe > 32) { + hvx_rope_neox_mul(Q6_V_hi_W(vp0), Q6_V_hi_W(vp1), vt[nvec * 4 + 2], vt[nvec * 4 + 3], &o0_hi, &o1_hi); + o0_hi = hvx_vec_clamp_f16_f32_vec(o0_hi, f16_min, f16_max); + o1_hi = hvx_vec_clamp_f16_f32_vec(o1_hi, f16_min, f16_max); + } +#endif + HVX_Vector vout0 = hvx_vec_f32_to_f16(o0_lo, o0_hi); + HVX_Vector vout1 = hvx_vec_f32_to_f16(o1_lo, o1_hi); + + hvx_vec_store_a(dst + nvec * 64, nloe * sizeof(_Float16), vout0); + hvx_vec_store_u(dst + he + nvec * 64, nloe * sizeof(_Float16), vout1); + } +} + +static __attribute__((noinline)) void hvx_rope_f16_aa(_Float16 * restrict dst, const _Float16 * restrict src0, uint32_t ne, const float * restrict theta_cache) { + const uint32_t nvec = ne / 64; + const uint32_t nloe = ne % 64; + + const HVX_Vector * vs = (const HVX_Vector *) src0; + HVX_Vector * vd = (HVX_Vector *) dst; + const HVX_Vector * vt = (const HVX_Vector *) theta_cache; + + const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f); + const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f); +#if __HVX_ARCH__ < 79 + const HVX_Vector one_hf = hvx_vec_splat_f16(1.0f); + const HVX_Vector zero = Q6_V_vzero(); +#endif + + for (uint32_t i = 0; i < nvec; i++) { +#if __HVX_ARCH__ < 79 + HVX_VectorPair vx0_x1 = Q6_Wqf32_vmpy_VhfVhf(vs[i], one_hf); + + HVX_Vector vcos_qf = Q6_Vqf32_vadd_VsfVsf(vt[i * 2 + 0], zero); + HVX_Vector vsin_qf = Q6_Vqf32_vadd_VsfVsf(vt[i * 2 + 1], zero); + + HVX_Vector o0, o1; + hvx_rope_neox_mul_qf32(Q6_V_lo_W(vx0_x1), Q6_V_hi_W(vx0_x1), vcos_qf, vsin_qf, &o0, &o1); +#else + HVX_VectorPair vx0_x1 = hvx_vec_f16_to_f32_shuff(vs[i]); + + HVX_Vector o0, o1; + hvx_rope_neox_mul(Q6_V_lo_W(vx0_x1), Q6_V_hi_W(vx0_x1), vt[i * 2 + 0], vt[i * 2 + 1], &o0, &o1); +#endif + HVX_Vector vout = hvx_vec_f32_to_f16_shuff(hvx_vec_clamp_f16_f32_vec(o0, f16_min, f16_max), + hvx_vec_clamp_f16_f32_vec(o1, f16_min, f16_max)); + + vd[i] = vout; + } + + if (nloe > 0) { +#if __HVX_ARCH__ < 79 + HVX_VectorPair vx0_x1 = Q6_Wqf32_vmpy_VhfVhf(vs[nvec], one_hf); + + HVX_Vector vcos_qf = Q6_Vqf32_vadd_VsfVsf(vt[nvec * 2 + 0], zero); + HVX_Vector vsin_qf = Q6_Vqf32_vadd_VsfVsf(vt[nvec * 2 + 1], zero); + + HVX_Vector o0, o1; + hvx_rope_neox_mul_qf32(Q6_V_lo_W(vx0_x1), Q6_V_hi_W(vx0_x1), vcos_qf, vsin_qf, &o0, &o1); +#else + HVX_VectorPair vx0_x1 = hvx_vec_f16_to_f32_shuff(vs[nvec]); + + HVX_Vector o0, o1; + hvx_rope_neox_mul(Q6_V_lo_W(vx0_x1), Q6_V_hi_W(vx0_x1), vt[nvec * 2 + 0], vt[nvec * 2 + 1], &o0, &o1); +#endif + HVX_Vector vout = hvx_vec_f32_to_f16_shuff(hvx_vec_clamp_f16_f32_vec(o0, f16_min, f16_max), + hvx_vec_clamp_f16_f32_vec(o1, f16_min, f16_max)); + + hvx_vec_store_a(dst + nvec * 64, nloe * sizeof(_Float16), vout); + } +} + +static __attribute__((noinline)) void hvx_rope_neox_f16(_Float16 * restrict dst, const _Float16 * restrict src0, uint32_t ne, const float * restrict theta_cache) { + const uint32_t he = ne / 2; + const uint32_t nvec = he / 64; + const uint32_t nloe = he % 64; + + const HVX_Vector * vt = (const HVX_Vector *) theta_cache; + + const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f); + const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f); + + for (uint32_t i = 0; i < nvec; i++) { + HVX_VectorPair vp0 = hvx_vec_f16_to_f32(hvx_vmemu(src0 + i * 64)); + HVX_VectorPair vp1 = hvx_vec_f16_to_f32(hvx_vmemu(src0 + he + i * 64)); + + HVX_Vector o0_lo, o1_lo, o0_hi, o1_hi; + hvx_rope_neox_mul(Q6_V_lo_W(vp0), Q6_V_lo_W(vp1), vt[i * 4 + 0], vt[i * 4 + 1], &o0_lo, &o1_lo); + hvx_rope_neox_mul(Q6_V_hi_W(vp0), Q6_V_hi_W(vp1), vt[i * 4 + 2], vt[i * 4 + 3], &o0_hi, &o1_hi); + + HVX_Vector vout0 = hvx_vec_f32_to_f16(hvx_vec_clamp_f16_f32_vec(o0_lo, f16_min, f16_max), + hvx_vec_clamp_f16_f32_vec(o0_hi, f16_min, f16_max)); + HVX_Vector vout1 = hvx_vec_f32_to_f16(hvx_vec_clamp_f16_f32_vec(o1_lo, f16_min, f16_max), + hvx_vec_clamp_f16_f32_vec(o1_hi, f16_min, f16_max)); + + hvx_vmemu(dst + i * 64) = vout0; + hvx_vmemu(dst + he + i * 64) = vout1; + } + + if (nloe > 0) { + HVX_VectorPair vp0 = hvx_vec_f16_to_f32(hvx_vmemu(src0 + nvec * 64)); + HVX_VectorPair vp1 = hvx_vec_f16_to_f32(hvx_vmemu(src0 + he + nvec * 64)); + + HVX_Vector o0_lo, o1_lo; + hvx_rope_neox_mul(Q6_V_lo_W(vp0), Q6_V_lo_W(vp1), vt[nvec * 4 + 0], vt[nvec * 4 + 1], &o0_lo, &o1_lo); + o0_lo = hvx_vec_clamp_f16_f32_vec(o0_lo, f16_min, f16_max); + o1_lo = hvx_vec_clamp_f16_f32_vec(o1_lo, f16_min, f16_max); + + HVX_Vector o0_hi = o0_lo; + HVX_Vector o1_hi = o1_lo; + if (nloe > 32) { + hvx_rope_neox_mul(Q6_V_hi_W(vp0), Q6_V_hi_W(vp1), vt[nvec * 4 + 2], vt[nvec * 4 + 3], &o0_hi, &o1_hi); + o0_hi = hvx_vec_clamp_f16_f32_vec(o0_hi, f16_min, f16_max); + o1_hi = hvx_vec_clamp_f16_f32_vec(o1_hi, f16_min, f16_max); + } + + HVX_Vector vout0 = hvx_vec_f32_to_f16(o0_lo, o0_hi); + HVX_Vector vout1 = hvx_vec_f32_to_f16(o1_lo, o1_hi); + + hvx_vec_store_u(dst + nvec * 64, nloe * sizeof(_Float16), vout0); + hvx_vec_store_u(dst + he + nvec * 64, nloe * sizeof(_Float16), vout1); + } +} + +static __attribute__((noinline)) void hvx_rope_f16(_Float16 * restrict dst, const _Float16 * restrict src0, uint32_t ne, const float * restrict theta_cache) { + const uint32_t nvec = ne / 64; + const uint32_t nloe = ne % 64; + + const HVX_Vector * vt = (const HVX_Vector *) theta_cache; + + const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f); + const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f); + + for (uint32_t i = 0; i < nvec; i++) { + HVX_VectorPair vx0_x1 = hvx_vec_f16_to_f32_shuff(hvx_vmemu(src0 + i * 64)); + + HVX_Vector o0, o1; + hvx_rope_neox_mul(Q6_V_lo_W(vx0_x1), Q6_V_hi_W(vx0_x1), vt[i * 2 + 0], vt[i * 2 + 1], &o0, &o1); + + HVX_Vector vout = hvx_vec_f32_to_f16_shuff(hvx_vec_clamp_f16_f32_vec(o0, f16_min, f16_max), + hvx_vec_clamp_f16_f32_vec(o1, f16_min, f16_max)); + + hvx_vmemu(dst + i * 64) = vout; + } + + if (nloe > 0) { + HVX_VectorPair vx0_x1 = hvx_vec_f16_to_f32_shuff(hvx_vmemu(src0 + nvec * 64)); + + HVX_Vector o0, o1; + hvx_rope_neox_mul(Q6_V_lo_W(vx0_x1), Q6_V_hi_W(vx0_x1), vt[nvec * 2 + 0], vt[nvec * 2 + 1], &o0, &o1); + + HVX_Vector vout = hvx_vec_f32_to_f16_shuff(hvx_vec_clamp_f16_f32_vec(o0, f16_min, f16_max), + hvx_vec_clamp_f16_f32_vec(o1, f16_min, f16_max)); + + hvx_vec_store_u(dst + nvec * 64, nloe * sizeof(_Float16), vout); + } +} + +static __attribute__((noinline)) void rope_basic_f16_aa_inplace(const struct htp_rope_context * rctx, uint8_t * src, + uint32_t nr, const float * restrict theta_cache) { + const uint32_t n_offs = rctx->n_offs; + #pragma unroll(4) + for (uint32_t i = 0; i < nr; i++) { + _Float16 * s = (_Float16 *) (src + i * rctx->src0_row_size_aligned); + hvx_rope_f16_aa(s + n_offs, s + n_offs, rctx->n_dims, theta_cache); + } +} + +static __attribute__((noinline)) void rope_basic_f16_ua_inplace(const struct htp_rope_context * rctx, uint8_t * src, + uint32_t nr, const float * restrict theta_cache) { + const uint32_t n_offs = rctx->n_offs; + for (uint32_t i = 0; i < nr; i++) { + _Float16 * s = (_Float16 *) (src + i * rctx->src0_row_size_aligned); + hvx_rope_f16(s + n_offs, s + n_offs, rctx->n_dims, theta_cache); + } +} + +static __attribute__((noinline)) void rope_neox_f16_aa_inplace(const struct htp_rope_context * rctx, uint8_t * src, + uint32_t nr, const float * restrict theta_cache) { + const uint32_t n_offs = rctx->n_offs; + const uint32_t ne = rctx->ne_rot; + #pragma unroll(4) + for (uint32_t i = 0; i < nr; i++) { + _Float16 * s = (_Float16 *) (src + i * rctx->src0_row_size_aligned); + hvx_rope_neox_f16_aa(s + n_offs, s + n_offs, ne, theta_cache); + } +} + +static __attribute__((noinline)) void rope_neox_f16_ua_inplace(const struct htp_rope_context * rctx, uint8_t * src, + uint32_t nr, const float * restrict theta_cache) { + const uint32_t n_offs = rctx->n_offs; + const uint32_t ne = rctx->ne_rot; + for (uint32_t i = 0; i < nr; i++) { + _Float16 * s = (_Float16 *) (src + i * rctx->src0_row_size_aligned); + hvx_rope_neox_f16(s + n_offs, s + n_offs, ne, theta_cache); + } +} + +static inline void rope_init_token_cache(const struct htp_rope_context * rctx, uint32_t i2, float * cache) { + const struct htp_tensor * dst = rctx->octx->dst; + const uint32_t ne2 = dst->ne[2]; + const int32_t * pos = rctx->pos_data; + const bool is_mrope = (rctx->mode & HTP_ROPE_TYPE_MROPE) != 0; + const bool is_vision = (rctx->mode == HTP_ROPE_TYPE_VISION); + + if (is_mrope) { + // src1 holds four position arrays stacked along ne0: pos[i2 + k*ne2] + const bool is_imrope = (rctx->mode == HTP_ROPE_TYPE_IMROPE); + mrope_cache_init( + (float) pos[i2], + (float) pos[i2 + ne2], + (float) pos[i2 + ne2 * 2], + (float) pos[i2 + ne2 * 3], + rctx->sections, is_imrope, is_vision, + rctx->freq_scale, rctx->freq_factors, (float *) rctx->corr_dims, + rctx->ne_rot, rctx->ext_factor, rctx->attn_factor, + cache, rctx->theta_scale, rctx->theta_powers, rctx->theta_scale_32); + } else { + rope_cache_init( + (float) pos[i2], rctx->freq_scale, rctx->freq_factors, (float *) rctx->corr_dims, + rctx->ne_rot, rctx->ext_factor, rctx->attn_factor, + cache, rctx->theta_scale, rctx->theta_powers, rctx->theta_scale_32); + } +} + +static void rope_cs_precomp_task(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + const struct htp_rope_context * rctx = (const struct htp_rope_context *) data; + struct htp_thread_trace * tr = th->trace; + + const uint32_t count = rctx->cs_i2_count; + const uint32_t per_hvx = (count + nth - 1) / nth; + const uint32_t t0 = per_hvx * ith; + const uint32_t t1 = MIN(t0 + per_hvx, count); + + if (t0 >= t1) { + return; + } + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, rctx->cs_i2_base + t0); + for (uint32_t t = t0; t < t1; t++) { + float * cache = (float *) (rctx->cs_table + (size_t) t * rctx->cs_stride); + rope_init_token_cache(rctx, rctx->cs_i2_base + t, cache); + } + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, rctx->cs_i2_base + t0); +} + +static void rope_task_precomp(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + const struct htp_rope_context * rctx = (const struct htp_rope_context *) data; + struct htp_ops_context * octx = rctx->octx; + + const struct htp_tensor * src0 = octx->src[0]; + const struct htp_tensor * dst = octx->dst; + + const uint32_t ne1 = dst->ne[1]; + const uint32_t ne2 = dst->ne[2]; + const uint32_t ne3 = dst->ne[3]; + const uint32_t nb01 = src0->nb[1]; + const uint32_t nb03 = src0->nb[3]; + const uint32_t nb1 = dst->nb[1]; + const uint32_t nb3 = dst->nb[3]; + + const uint32_t src0_nrows = rctx->nrows; + const uint32_t src0_nrows_per_hvx = rctx->src0_nrows_per_hvx; + + const uint32_t src0_start_row = rctx->row_start + src0_nrows_per_hvx * ith; + const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, rctx->row_start + src0_nrows); + + if (src0_start_row >= src0_end_row) { + return; + } + + uint8_t * src0_spad_base = rctx->vtcm_base + (ith * rctx->spad_per_hvx) + rctx->theta_cache_offset; + dma_queue * dma_q = th->dma_q; + struct htp_thread_trace * tr = th->trace; + + const uint8_t * cs_table = rctx->cs_table; + const size_t cs_stride = rctx->cs_stride; + const uint32_t cs_i2_base = rctx->cs_i2_base; + + const uint32_t ne2_ne1 = ne2 * ne1; + const uint32_t i3_start = fastdiv(src0_start_row, &rctx->div_ne2_ne1); + const uint32_t rem = fastmodulo(src0_start_row, ne2_ne1, &rctx->div_ne2_ne1); + const uint32_t i2_start = fastdiv(rem, &rctx->div_ne1); + const uint32_t i1_start = fastmodulo(rem, ne1, &rctx->div_ne1); + + uint32_t ir = src0_start_row; + uint32_t cur_slot = 0; + + for (uint32_t i3 = i3_start; i3 < ne3 && ir < src0_end_row; i3++) { + uint32_t cur_i2 = (i3 == i3_start) ? i2_start : 0; + uint32_t cur_i1 = (i3 == i3_start) ? i1_start : 0; + const uint32_t b_row0 = cur_i2 * ne1 + cur_i1; + const uint32_t nrows = MIN(src0_end_row - ir, ne2_ne1 - b_row0); + + const dma_addr_t src0_b_base = src0->data + (size_t) i3 * nb03; + const dma_addr_t dst_b_base = dst->data + (size_t) i3 * nb3; + const uint32_t dma_depth = dma_queue_depth(dma_q); + + const uint32_t p_nrows = MIN(nrows, 2 * HTP_ROPE_SPAD_BLOCK); + for (uint32_t pr = 0; pr < p_nrows; pr += HTP_ROPE_SPAD_BLOCK) { + const uint32_t pnr = MIN(nrows - pr, HTP_ROPE_SPAD_BLOCK); + const uint32_t slot = (cur_slot + pr / HTP_ROPE_SPAD_BLOCK) % HTP_ROPE_SPAD_NSLOTS; + uint8_t * spad_slot = rope_spad_slot(src0_spad_base, slot, rctx->src0_row_size_aligned); + const dma_addr_t src0_data = src0_b_base + (size_t) (b_row0 + pr) * nb01; + + dma_queue_push(dma_q, dma_make_data(dst->data, spad_slot), 0, 0, 0, 0); + dma_queue_push(dma_q, dma_make_data(spad_slot, src0_data), + rctx->src0_row_size_aligned, rctx->src0_row_stride, rctx->src0_row_size, pnr); + } + + for (uint32_t d = 0; d < dma_depth; d++) { dma_queue_pop_nowait(dma_q); } + + for (uint32_t cnr = 0, cr = 0; cr < nrows; cr += cnr) { + cnr = MIN(nrows - cr, HTP_ROPE_SPAD_BLOCK); + + dma_queue_pop(dma_q); + uint8_t * cur_spad = (uint8_t *) dma_queue_pop(dma_q).dst; + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir + cr); + uint32_t rem_c = cnr; + uint8_t * p = cur_spad; + while (rem_c > 0) { + const uint32_t run = MIN(rem_c, ne1 - cur_i1); + const float * cs = (const float *) (cs_table + (size_t) (cur_i2 - cs_i2_base) * cs_stride); + rctx->compute_block(rctx, p, run, cs); + p += run * rctx->src0_row_size_aligned; + rem_c -= run; + cur_i1 += run; + if (cur_i1 == ne1) { + cur_i1 = 0; + cur_i2++; + } + } + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir + cr); + + const dma_addr_t dst_data = dst_b_base + (size_t) (b_row0 + cr) * nb1; + dma_queue_push(dma_q, dma_make_data(dst_data, cur_spad), + rctx->dst_row_stride, rctx->src0_row_size_aligned, rctx->dst_row_size, cnr); + + if ((cr + 2 * HTP_ROPE_SPAD_BLOCK) < nrows) { + const uint32_t p_cr = cr + 2 * HTP_ROPE_SPAD_BLOCK; + const uint32_t pnr = MIN(nrows - p_cr, HTP_ROPE_SPAD_BLOCK); + const uint32_t p_slot = (cur_slot + p_cr / HTP_ROPE_SPAD_BLOCK) % HTP_ROPE_SPAD_NSLOTS; + uint8_t * p_spad = rope_spad_slot(src0_spad_base, p_slot, rctx->src0_row_size_aligned); + const dma_addr_t p_src0_data = src0_b_base + (size_t) (b_row0 + p_cr) * nb01; + + dma_queue_push(dma_q, dma_make_data(p_spad, p_src0_data), + rctx->src0_row_size_aligned, rctx->src0_row_stride, rctx->src0_row_size, pnr); + } + } + + const uint32_t n_chunks = (nrows + HTP_ROPE_SPAD_BLOCK - 1) / HTP_ROPE_SPAD_BLOCK; + cur_slot = (cur_slot + n_chunks) % HTP_ROPE_SPAD_NSLOTS; + ir += nrows; + } + + dma_queue_flush(dma_q); + + FARF(HIGH, "rope-precomp: %d/%d: (%u:%u)\n", ith, nth, src0_start_row, src0_end_row); +} + +static void rope_task(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { struct htp_rope_context * rctx = (struct htp_rope_context *) data; struct htp_ops_context * octx = rctx->octx; const struct htp_tensor * src0 = octx->src[0]; - const struct htp_tensor * src1 = octx->src[1]; - const struct htp_tensor * src2 = octx->src[2]; const struct htp_tensor * dst = octx->dst; htp_rope_preamble; @@ -554,11 +1033,6 @@ static void rope_job_f32(const htp_thread_t * th, unsigned int nth, unsigned int return; } - const int32_t mode = rctx->mode; - // MROPE, IMROPE and VISION use NEOX-style pairing for the rotation - const bool is_neox = (mode & HTP_ROPE_TYPE_NEOX) || (mode & HTP_ROPE_TYPE_MROPE); - const bool is_vision = (mode == HTP_ROPE_TYPE_VISION); - // VTCM setup uint8_t * src0_spad_base = rctx->vtcm_base + (ith * rctx->spad_per_hvx); float * theta_cache = (float *) (src0_spad_base); @@ -566,8 +1040,6 @@ static void rope_job_f32(const htp_thread_t * th, unsigned int nth, unsigned int dma_queue * dma_q = th->dma_q; struct htp_thread_trace * tr = th->trace; - const int32_t * pos = (const int32_t *) (uintptr_t) src1->data; - const float * freq_factors = rctx->freq_factors; const uint32_t i3_start = fastdiv(src0_start_row, &rctx->div_ne2_ne1); const uint32_t rem = fastmodulo(src0_start_row, ne2 * ne1, &rctx->div_ne2_ne1); @@ -606,32 +1078,10 @@ static void rope_job_f32(const htp_thread_t * th, unsigned int nth, unsigned int rctx->src0_row_size_aligned, rctx->src0_row_stride, rctx->src0_row_size, pnr); } - // Update theta cache if (i2 != prev_i2) { prev_i2 = i2; - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, i2); - // VISION rotates the full row; other modes only rotate n_dims. - const uint32_t n_cache = is_vision ? ne0 : (uint32_t) rctx->n_dims; - const bool is_mrope = (rctx->mode & HTP_ROPE_TYPE_MROPE) != 0; - if (is_mrope) { - // src1 holds four position arrays stacked along ne0: - // pos[i2], pos[i2+ne2], pos[i2+ne2*2], pos[i2+ne2*3] - const bool is_imrope = (rctx->mode == HTP_ROPE_TYPE_IMROPE); - mrope_cache_init( - (float) pos[i2], - (float) pos[i2 + ne2], - (float) pos[i2 + ne2 * 2], - (float) pos[i2 + ne2 * 3], - rctx->sections, is_imrope, is_vision, - rctx->freq_scale, freq_factors, rctx->corr_dims, - n_cache, rctx->ext_factor, rctx->attn_factor, - theta_cache, rctx->theta_scale, rctx->theta_powers, rctx->theta_scale_32); - } else { - rope_cache_init(pos[i2], rctx->freq_scale, freq_factors, rctx->corr_dims, - n_cache, rctx->ext_factor, rctx->attn_factor, - theta_cache, rctx->theta_scale, rctx->theta_powers, rctx->theta_scale_32); - } + rope_init_token_cache(rctx, i2, theta_cache); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, i2); } @@ -639,13 +1089,11 @@ static void rope_job_f32(const htp_thread_t * th, unsigned int nth, unsigned int for (uint32_t d = 0; d < dma_depth; d++) { dma_queue_pop_nowait(dma_q); } // Compute loop - const uint32_t ne = is_vision ? ne0 : rctx->n_dims; const uint32_t base_i1 = i1; const uint32_t base_ir = ir; for (uint32_t cnr = 0, cr = 0; cr < nrows; cr += cnr) { cnr = MIN(nrows - cr, HTP_ROPE_SPAD_BLOCK); - const uint32_t slot = (cur_slot + cr / HTP_ROPE_SPAD_BLOCK) % HTP_ROPE_SPAD_NSLOTS; const uint32_t cur_ir = base_ir + cr; const uint32_t cur_i1 = base_i1 + cr; @@ -653,11 +1101,7 @@ static void rope_job_f32(const htp_thread_t * th, unsigned int nth, unsigned int uint8_t * cur_spad = (uint8_t *) dma_queue_pop(dma_q).dst; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, cur_ir); - if (is_neox || is_vision) { - rope_neox_f32_inplace(rctx, cur_spad, cnr, ne, theta_cache); - } else { - rope_basic_f32_inplace(rctx, cur_spad, cnr, theta_cache); - } + rctx->compute_block(rctx, cur_spad, cnr, theta_cache); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, cur_ir); const dma_addr_t dst_data = dst->data + i3 * nb3 + i2 * nb2 + cur_i1 * nb1; @@ -689,10 +1133,32 @@ static void rope_job_f32(const htp_thread_t * th, unsigned int nth, unsigned int done: dma_queue_flush(dma_q); - FARF(HIGH, "rope-f32: %d/%d: (%u:%u)\n", ith, nth, src0_start_row, src0_end_row); + FARF(HIGH, "rope: %d/%d: (%u:%u)\n", ith, nth, src0_start_row, src0_end_row); } -static int execute_op_rope_f32(struct htp_ops_context * octx) { +static inline void hvx_rope_init_theta_powers(float * dst, float theta_scale) { + static const int32_t lane_idx[32] __attribute__((aligned(128))) = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, + }; + const HVX_Vector v_idx = *(const HVX_Vector *) lane_idx; + HVX_Vector v = Q6_Vqf32_vadd_VsfVsf(hvx_vec_splat_f32(1.0f), Q6_V_vzero()); + HVX_Vector p = Q6_Vqf32_vadd_VsfVsf(hvx_vec_splat_f32(theta_scale), Q6_V_vzero()); + + #pragma clang loop unroll(full) + for (int bit = 0; bit < 5; ++bit) { + const HVX_Vector mask = Q6_V_vsplat_R(1 << bit); + const HVX_VectorPred q = Q6_Q_vcmp_eq_VwVw(Q6_V_vand_VV(v_idx, mask), mask); + v = Q6_V_vmux_QVV(q, Q6_Vqf32_vmpy_Vqf32Vqf32(v, p), v); + if (bit < 4) { + p = Q6_Vqf32_vmpy_Vqf32Vqf32(p, p); + } + } + + hvx_vmemu(dst) = Q6_Vsf_equals_Vqf32(v); +} + +static int execute_op_rope(struct htp_ops_context * octx) { int err = HTP_STATUS_OK; const struct htp_tensor * src0 = octx->src[0]; @@ -706,21 +1172,17 @@ static int execute_op_rope_f32(struct htp_ops_context * octx) { } assert(octx->ctx->vtcm_size >= kparams->vtcm_size); - if (htp_tensor_is_extended(src1)) { - return HTP_STATUS_NO_SUPPORT; - } + const bool is_f16 = (src0->type == HTP_TYPE_F16); + const size_t elem_size = is_f16 ? sizeof(_Float16) : sizeof(float); const uint32_t total_rows = src0->ne[1] * src0->ne[2] * src0->ne[3]; - const size_t dst_data_row_size = dst->ne[0] * sizeof(float); uint32_t row_start = 0; uint32_t nrows = total_rows; if (octx->ctx->mdev.count > 1) { - uint32_t rows_per_chunk = 0; - htp_tensor_mdev_rows_per_chunk(dst, sizeof(float), (uint32_t) dst_data_row_size, &rows_per_chunk); const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( - total_rows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + total_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); row_start = range.start; nrows = range.count; } @@ -732,21 +1194,34 @@ static int execute_op_rope_f32(struct htp_ops_context * octx) { const uint32_t n_hvx = octx->n_hvx; const uint32_t ne0 = dst->ne[0]; - const size_t src0_row_size = src0->ne[0] * sizeof(float); + const size_t src0_row_size = src0->ne[0] * elem_size; const size_t src0_row_stride = src0->nb[1]; - const size_t dst_row_size = dst->ne[0] * sizeof(float); + const size_t dst_row_size = dst->ne[0] * elem_size; const size_t dst_row_stride = dst->nb[1]; struct htp_rope_vtcm_layout layout; - htp_rope_vtcm_layout_build(&layout, src0->ne[0], kparams->n_hvx, src2 ? src2->ne[0] : 0); + htp_rope_vtcm_layout_build(&layout, src0->ne[0], elem_size, kparams->n_hvx, src2 ? src2->ne[0] : 0); struct htp_rope_context rctx; memset(&rctx, 0, sizeof(struct htp_rope_context)); + const size_t pos_bytes = hex_round_up(htp_tensor_nbytes(src1), 128); + void * pos_buf = (pos_bytes <= octx->ctx->ddr_spad_size) ? octx->ctx->ddr_spad_base : memalign(128, pos_bytes); + if (!pos_buf) { + return HTP_STATUS_INTERNAL_ERR; + } + if (htp_tensor_read(&octx->ctx->main_th, pos_buf, pos_bytes, src1) == 0) { + if (pos_buf != octx->ctx->ddr_spad_base) { + free(pos_buf); + } + return HTP_STATUS_INTERNAL_ERR; + } + rctx.octx = octx; rctx.vtcm_base = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, layout.off_spad); rctx.spad_per_hvx = layout.bytes_per_hvx; rctx.theta_cache_offset = layout.theta_cache_size_aligned; + rctx.pos_data = (const int32_t *) pos_buf; if (src2) { dma_queue * dma_q = octx->ctx->dma[0]; @@ -759,27 +1234,20 @@ static int execute_op_rope_f32(struct htp_ops_context * octx) { } const int32_t * op_params = &octx->op_params[0]; - rctx.n_dims = ((const int32_t *) op_params)[1]; - rctx.mode = ((const int32_t *) op_params)[2]; - rctx.n_ctx_orig = ((const int32_t *) op_params)[4]; - rctx.n_offs = ((const int32_t *) op_params)[15]; + rctx.n_dims = ((const int32_t *) op_params)[1]; + rctx.mode = ((const int32_t *) op_params)[2]; + rctx.n_offs = ((const int32_t *) op_params)[15]; - memcpy(&rctx.freq_base, (int32_t *) op_params + 5, sizeof(float)); memcpy(&rctx.freq_scale, (int32_t *) op_params + 6, sizeof(float)); memcpy(&rctx.ext_factor, (int32_t *) op_params + 7, sizeof(float)); memcpy(&rctx.attn_factor, (int32_t *) op_params + 8, sizeof(float)); - memcpy(&rctx.beta_fast, (int32_t *) op_params + 9, sizeof(float)); - memcpy(&rctx.beta_slow, (int32_t *) op_params + 10, sizeof(float)); memcpy(&rctx.sections, (int32_t *) op_params + 11, sizeof(int) * 4); - rctx.theta_scale = powf(rctx.freq_base, -2.0f / rctx.n_dims); - rctx.theta_powers[0] = 1.0f; - for (int j = 1; j < 32; j++) { - rctx.theta_powers[j] = rctx.theta_powers[j - 1] * rctx.theta_scale; - } - rctx.theta_scale_32 = rctx.theta_powers[31] * rctx.theta_scale; - - rope_corr_dims(rctx.n_dims, rctx.n_ctx_orig, rctx.freq_base, rctx.beta_fast, rctx.beta_slow, rctx.corr_dims); + rctx.theta_scale = kparams->theta_scale; + rctx.theta_scale_32 = kparams->theta_scale_32; + hvx_rope_init_theta_powers(rctx.theta_powers, rctx.theta_scale); + rctx.corr_dims[0] = kparams->corr_dims[0]; + rctx.corr_dims[1] = kparams->corr_dims[1]; rctx.src0_row_size = src0_row_size; rctx.src0_row_stride = src0_row_stride; @@ -787,25 +1255,83 @@ static int execute_op_rope_f32(struct htp_ops_context * octx) { rctx.dst_row_stride = dst_row_stride; rctx.src0_row_size_aligned = layout.src0_row_size_aligned; - rctx.src0_nrows = nrows; rctx.nrows = nrows; rctx.row_start = row_start; rctx.src0_nrows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div); rctx.div_ne2_ne1 = kparams->div_ne2_ne1; rctx.div_ne1 = kparams->div_ne1; - FARF(HIGH, "rope-f32 n-rows %u n-dims %d ne0 %u ext-factor %.6f theta-scale %.6f attn-factor %.6f\n", rctx.src0_nrows, rctx.n_dims, ne0, + // MROPE, IMROPE and VISION use NEOX-style pairing for the rotation; VISION rotates full ne0 + const bool is_neox = (rctx.mode & HTP_ROPE_TYPE_NEOX) || (rctx.mode & HTP_ROPE_TYPE_MROPE); + const bool is_vision = (rctx.mode == HTP_ROPE_TYPE_VISION); + const bool f16_aa = (rctx.n_offs & 63) == 0; + + rctx.ne_rot = is_vision ? ne0 : (uint32_t) rctx.n_dims; + if (is_f16) { + if (is_neox || is_vision) { + rctx.compute_block = f16_aa ? rope_neox_f16_aa_inplace : rope_neox_f16_ua_inplace; + } else { + rctx.compute_block = f16_aa ? rope_basic_f16_aa_inplace : rope_basic_f16_ua_inplace; + } + } else { + rctx.compute_block = (is_neox || is_vision) ? rope_neox_f32_inplace : rope_basic_f32_inplace; + } + + const uint32_t ne1 = dst->ne[1]; + const uint32_t ne2 = dst->ne[2]; + const uint32_t ne3 = dst->ne[3]; + + uint32_t cs_i2_base = 0; + uint32_t cs_i2_count = ne2; + if (ne3 == 1) { + const uint32_t i2_first = fastdiv(row_start, &rctx.div_ne1); + const uint32_t i2_last = fastdiv(row_start + nrows - 1, &rctx.div_ne1); + cs_i2_base = i2_first; + cs_i2_count = i2_last - i2_first + 1; + } + + // Precompute cos/sin and batch DMAs across tokens only when ne1 < HTP_ROPE_SPAD_BLOCK; + // for larger ne1, rope_task already issues full DMA blocks and overlaps cos/sin with DMA. + const bool want_precomp = (ne1 < HTP_ROPE_SPAD_BLOCK) && (cs_i2_count > 1) && + (src0->nb[2] == ne1 * src0->nb[1]) && + (dst->nb[2] == ne1 * dst->nb[1]); + + if (want_precomp && rctx.ne_rot > 0) { + const size_t cs_stride = hex_round_up((uint32_t) (rctx.ne_rot * sizeof(float)), 256); + const size_t cs_off = hex_round_up(layout.total_bytes, 256); + const size_t cs_bytes = (size_t) cs_i2_count * cs_stride; + if (cs_off + cs_bytes <= octx->ctx->vtcm_size) { + rctx.cs_table = VTCM_LAYOUT_PTR(uint8_t, octx->ctx->vtcm_base, cs_off); + rctx.cs_stride = cs_stride; + rctx.cs_i2_base = cs_i2_base; + rctx.cs_i2_count = cs_i2_count; + + work_queue_run(octx->ctx->hvx_queue, rope_cs_precomp_task, &rctx, MIN(n_hvx, cs_i2_count)); + } + } + + FARF(HIGH, "rope-%s n-rows %u n-dims %d ne0 %u ext-factor %.6f theta-scale %.6f attn-factor %.6f\n", + is_f16 ? "f16" : "f32", rctx.nrows, rctx.n_dims, ne0, rctx.ext_factor, rctx.theta_scale, rctx.attn_factor); - work_queue_run(octx->ctx->hvx_queue, rope_job_f32, &rctx, n_hvx); + work_queue_run(octx->ctx->hvx_queue, rctx.cs_table ? rope_task_precomp : rope_task, &rctx, n_hvx); + + if (pos_buf != octx->ctx->ddr_spad_base) { + free(pos_buf); + } return err; } int op_rope(struct htp_ops_context * octx) { + if (octx->src[0]->type != octx->dst->type) { + return HTP_STATUS_NO_SUPPORT; + } + switch (octx->src[0]->type) { case HTP_TYPE_F32: - return execute_op_rope_f32(octx); + case HTP_TYPE_F16: + return execute_op_rope(octx); default: return HTP_STATUS_NO_SUPPORT; diff --git a/ggml/src/ggml-hexagon/htp/rope-ops.h b/ggml/src/ggml-hexagon/htp/rope-ops.h index a21b85c0600c..d5418d214b97 100644 --- a/ggml/src/ggml-hexagon/htp/rope-ops.h +++ b/ggml/src/ggml-hexagon/htp/rope-ops.h @@ -13,6 +13,10 @@ struct htp_rope_kernel_params { uint32_t n_hvx; uint32_t vtcm_size; + float theta_scale; + float theta_scale_32; + float corr_dims[2]; + struct fastdiv_values div_ne2_ne1; struct fastdiv_values div_ne1; }; @@ -36,12 +40,13 @@ struct htp_rope_vtcm_layout { static inline void htp_rope_vtcm_layout_build( struct htp_rope_vtcm_layout * L, uint32_t ne00, + size_t elem_size, uint32_t n_hvx, uint32_t n_freq_factors ) { - const size_t src0_row_size = ne00 * sizeof(float); + const size_t src0_row_size = ne00 * elem_size; const size_t src0_row_size_aligned = hex_round_up((uint32_t) src0_row_size, 128); - const size_t theta_cache_size_aligned = hex_round_up((uint32_t) src0_row_size, 256); + const size_t theta_cache_size_aligned = hex_round_up((uint32_t) (ne00 * sizeof(float)), 256); const size_t freq_factors_size_aligned = hex_round_up(n_freq_factors * sizeof(float), 256); L->src0_row_size_aligned = src0_row_size_aligned; diff --git a/ggml/src/ggml-hexagon/htp/set-rows-ops.c b/ggml/src/ggml-hexagon/htp/set-rows-ops.c index add91408fe5e..ec6db870b5fc 100644 --- a/ggml/src/ggml-hexagon/htp/set-rows-ops.c +++ b/ggml/src/ggml-hexagon/htp/set-rows-ops.c @@ -1,14 +1,12 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include #include +#include #include #include "dma-queue.h" +#include "dma-pipeline.h" #include "work-queue.h" #include "hvx-utils.h" #include "hex-utils.h" @@ -24,186 +22,235 @@ #include "htp-tensor.h" #include "htp/set-rows-ops.h" -#define set_rows_preamble \ - const uint32_t ne00 = octx->src[0]->ne[0]; \ - const uint32_t ne01 = octx->src[0]->ne[1]; \ - const uint32_t ne02 = octx->src[0]->ne[2]; \ - const uint32_t ne03 = octx->src[0]->ne[3]; \ - \ - const uint32_t ne10 = octx->src[1]->ne[0]; \ - const uint32_t ne11 = octx->src[1]->ne[1]; \ - const uint32_t ne12 = octx->src[1]->ne[2]; \ - const uint32_t ne13 = octx->src[1]->ne[3]; \ - \ - const uint32_t nb01 = octx->src[0]->nb[1]; \ - const uint32_t nb02 = octx->src[0]->nb[2]; \ - const uint32_t nb03 = octx->src[0]->nb[3]; \ - \ - const uint32_t nb10 = octx->src[1]->nb[0]; \ - const uint32_t nb11 = octx->src[1]->nb[1]; \ - const uint32_t nb12 = octx->src[1]->nb[2]; \ - \ - const uint32_t nb1 = octx->dst->nb[1]; \ - const uint32_t nb2 = octx->dst->nb[2]; \ - const uint32_t nb3 = octx->dst->nb[3]; \ - \ - const uint32_t ne0 = octx->dst->ne[0]; \ - const uint32_t ne1 = octx->dst->ne[1]; \ - const uint32_t ne2 = octx->dst->ne[2]; \ - const uint32_t ne3 = octx->dst->ne[3]; \ - \ - const uint32_t nr = ne01; +#define set_rows_preamble \ + const uint32_t __attribute__((unused)) ne00 = octx->src[0]->ne[0]; \ + const uint32_t __attribute__((unused)) ne01 = octx->src[0]->ne[1]; \ + const uint32_t __attribute__((unused)) ne02 = octx->src[0]->ne[2]; \ + const uint32_t __attribute__((unused)) ne03 = octx->src[0]->ne[3]; \ + \ + const uint32_t __attribute__((unused)) ne10 = octx->src[1]->ne[0]; \ + const uint32_t __attribute__((unused)) ne11 = octx->src[1]->ne[1]; \ + const uint32_t __attribute__((unused)) ne12 = octx->src[1]->ne[2]; \ + const uint32_t __attribute__((unused)) ne13 = octx->src[1]->ne[3]; \ + \ + const uint32_t __attribute__((unused)) nb01 = octx->src[0]->nb[1]; \ + const uint32_t __attribute__((unused)) nb02 = octx->src[0]->nb[2]; \ + const uint32_t __attribute__((unused)) nb03 = octx->src[0]->nb[3]; \ + \ + const uint32_t __attribute__((unused)) nb10 = octx->src[1]->nb[0]; \ + const uint32_t __attribute__((unused)) nb11 = octx->src[1]->nb[1]; \ + const uint32_t __attribute__((unused)) nb12 = octx->src[1]->nb[2]; \ + \ + const uint32_t __attribute__((unused)) nb1 = octx->dst->nb[1]; \ + const uint32_t __attribute__((unused)) nb2 = octx->dst->nb[2]; \ + const uint32_t __attribute__((unused)) nb3 = octx->dst->nb[3]; \ + \ + const uint32_t __attribute__((unused)) ne0 = octx->dst->ne[0]; \ + const uint32_t __attribute__((unused)) ne1 = octx->dst->ne[1]; \ + const uint32_t __attribute__((unused)) ne2 = octx->dst->ne[2]; \ + const uint32_t __attribute__((unused)) ne3 = octx->dst->ne[3]; \ + \ + const uint32_t __attribute__((unused)) nr = ne01; + +typedef void (*set_rows_compute_fn_t)(void * restrict dst, const void * restrict src, uint32_t n); struct set_rows_context { struct htp_ops_context * octx; const struct htp_set_rows_kernel_params * kparams; struct htp_set_rows_vtcm_layout vtcm_layout; + set_rows_compute_fn_t compute; uint8_t * vtcm_base; + const void * src1_data; uint32_t task_start; uint32_t tasks; uint32_t tasks_per_hvx; + bool is_i32; }; -#define SET_ROWS_THREAD_DMA_FN(TYPE_NAME, IDX_TYPE, COMPUTE_EXPR) \ -static void set_rows_thread_dma_##TYPE_NAME##_##IDX_TYPE(const htp_thread_t * th, unsigned int nth, \ - unsigned int ith, void *data) { \ - struct set_rows_context * srctx = (struct set_rows_context *)data; \ - struct htp_ops_context * octx = srctx->octx; \ - const struct htp_set_rows_kernel_params * kparams = srctx->kparams; \ - set_rows_preamble; \ - struct htp_thread_trace * tr = th->trace; \ - const uint32_t dr = srctx->tasks_per_hvx; \ - const uint32_t ir0 = srctx->task_start + dr * ith; \ - if (ir0 >= srctx->task_start + srctx->tasks) { \ - return; \ - } \ - const uint32_t ir1 = MIN(ir0 + dr, srctx->task_start + srctx->tasks); \ - dma_queue * dma_q = th->dma_q; \ - const struct htp_set_rows_vtcm_layout * vtcm_layout = &srctx->vtcm_layout; \ - uint8_t * vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, srctx->vtcm_base, vtcm_layout->off_src0) + \ - ith * vtcm_layout->src0_bytes_per_hvx; \ - uint8_t * vtcm_dst = VTCM_LAYOUT_PTR(uint8_t, srctx->vtcm_base, vtcm_layout->off_dst) + \ - ith * vtcm_layout->dst_bytes_per_hvx; \ - const uint32_t src0_row_size = ne00 * sizeof(float); \ - const uint32_t dst_row_size = htp_tensor_get_row_size(octx->dst->type, ne00); \ - const uint32_t nrows_per_hvx = ir1 - ir0; \ - const uint32_t total_steps = ne03 * ne02 * nrows_per_hvx; \ - uint32_t pi_step = 0; \ - uint32_t pi02 = 0; \ - uint32_t pi03 = 0; \ - for (uint32_t step = 0, spad_idx = 0; step < total_steps && spad_idx < 2; ++step, spad_idx++) { \ - uint32_t i = ir0 + pi_step; \ - const dma_addr_t src0_data = octx->src[0]->data + i*nb01 + pi02*nb02 + pi03*nb03; \ - dma_queue_push(dma_q, \ - dma_make_data(octx->dst->data, \ - vtcm_dst + spad_idx * vtcm_layout->dst_spad_half_size), \ - dst_row_size, vtcm_layout->dst_spad_half_size, dst_row_size, 0); \ - dma_queue_push(dma_q, \ - dma_make_data(vtcm_src0 + spad_idx * vtcm_layout->src0_spad_half_size, \ - src0_data), \ - vtcm_layout->src0_spad_half_size, src0_row_size, src0_row_size, 1); \ - pi_step++; \ - if (pi_step == nrows_per_hvx) { \ - pi_step = 0; \ - pi02++; \ - if (pi02 == ne02) { \ - pi02 = 0; \ - pi03++; \ - } \ - } \ - } \ - uint32_t ci_step = 0; \ - uint32_t ci02 = 0; \ - uint32_t ci03 = 0; \ - uint32_t ci11_base = 0; \ - uint32_t ci12_base = 0; \ - for (uint32_t step = 0; step < total_steps; ++step) { \ - void * dst_spad = (void *) dma_queue_pop(dma_q).src; \ - void * src_spad = (void *) dma_queue_pop(dma_q).dst; \ - uint32_t i = ir0 + ci_step; \ - const uintptr_t src1_addr = octx->src[1]->data + i*nb10 + ci11_base*nb11 + ci12_base*nb12; \ - const IDX_TYPE i1 = *(const IDX_TYPE *)src1_addr; \ - const bool valid_i1 = ((uint64_t)i1 < (uint64_t)ne1); \ - const uint32_t target_i1 = (uint32_t)i1; \ - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, step); \ - if (valid_i1) { \ - COMPUTE_EXPR; \ - } \ - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, step); \ - if (valid_i1) { \ - const dma_addr_t dst_data = octx->dst->data + target_i1*nb1 + ci02*nb2 + ci03*nb3; \ - dma_queue_push(dma_q, \ - dma_make_data(dst_data, dst_spad), \ - dst_row_size, vtcm_layout->dst_spad_half_size, dst_row_size, 1); \ - } else { \ - dma_queue_push(dma_q, \ - dma_make_data(octx->dst->data, dst_spad), \ - dst_row_size, vtcm_layout->dst_spad_half_size, dst_row_size, 0); \ - } \ - const uint32_t next_step = step + 2; \ - if (next_step < total_steps) { \ - uint32_t ni = ir0 + pi_step; \ - const dma_addr_t psrc0_data = octx->src[0]->data + ni*nb01 + pi02*nb02 + pi03*nb03; \ - dma_queue_push(dma_q, \ - dma_make_data(src_spad, psrc0_data), \ - vtcm_layout->src0_spad_half_size, src0_row_size, src0_row_size, 1); \ - pi_step++; \ - if (pi_step == nrows_per_hvx) { \ - pi_step = 0; \ - pi02++; \ - if (pi02 == ne02) { \ - pi02 = 0; \ - pi03++; \ - } \ - } \ - } \ - ci_step++; \ - if (ci_step == nrows_per_hvx) { \ - ci_step = 0; \ - ci02++; \ - ci11_base++; \ - if (ci11_base == ne11) { \ - ci11_base = 0; \ - } \ - if (ci02 == ne02) { \ - ci02 = 0; \ - ci03++; \ - ci12_base++; \ - if (ci12_base == ne12) { \ - ci12_base = 0; \ - } \ - } \ - } \ - } \ - dma_queue_flush(dma_q); \ +static __attribute__((noinline)) void set_rows_row_f32_f32(void * restrict dst, const void * restrict src, uint32_t n) { + hvx_copy_f32_uu((uint8_t *) dst, (const uint8_t *) src, n); } -SET_ROWS_THREAD_DMA_FN(f32, int32_t, { hvx_copy_f32_uu((uint8_t *)dst_spad, (const uint8_t *)src_spad, ne00); }) -SET_ROWS_THREAD_DMA_FN(f32, int64_t, { hvx_copy_f32_uu((uint8_t *)dst_spad, (const uint8_t *)src_spad, ne00); }) +static __attribute__((noinline)) void set_rows_row_f16_f32(void * restrict dst, const void * restrict src, uint32_t n) { + hvx_copy_f16_f32_uu((uint8_t *) dst, (const uint8_t *) src, n); +} -SET_ROWS_THREAD_DMA_FN(f16, int32_t, { hvx_copy_f16_f32_uu((uint8_t *)dst_spad, (const uint8_t *)src_spad, ne00); }) -SET_ROWS_THREAD_DMA_FN(f16, int64_t, { hvx_copy_f16_f32_uu((uint8_t *)dst_spad, (const uint8_t *)src_spad, ne00); }) +static __attribute__((noinline)) void set_rows_row_q8_0_f32(void * restrict dst, const void * restrict src, uint32_t n) { + hvx_quantize_row_q8_0_f32(dst, (const float *) src, n); +} -SET_ROWS_THREAD_DMA_FN(q8_0, int32_t, { hvx_quantize_row_q8_0_f32(dst_spad, (const float *)src_spad, ne00); }) -SET_ROWS_THREAD_DMA_FN(q8_0, int64_t, { hvx_quantize_row_q8_0_f32(dst_spad, (const float *)src_spad, ne00); }) +static __attribute__((noinline)) void set_rows_row_f32_f16(void * restrict dst, const void * restrict src, uint32_t n) { + hvx_copy_f32_f16_uu((uint8_t *) dst, (const uint8_t *) src, n); +} -int op_set_rows(struct htp_ops_context * octx) { - const struct htp_set_rows_kernel_params * kparams = (const struct htp_set_rows_kernel_params *)octx->kernel_params; +static __attribute__((noinline)) void set_rows_row_f16_f16(void * restrict dst, const void * restrict src, uint32_t n) { + hvx_copy_f16_uu((uint8_t *) dst, (const uint8_t *) src, n); +} + +static __attribute__((noinline)) void set_rows_row_q8_0_f16(void * restrict dst, const void * restrict src, uint32_t n) { + hvx_quantize_row_q8_0_f16(dst, (const __fp16 *) src, n); +} + +struct set_rows_pipe_state { + dma_addr_t src0_data; + uintptr_t src1_data; + dma_addr_t dst_data; + set_rows_compute_fn_t compute; + uint32_t ne00; + uint32_t ne02; + uint32_t ne1; + uint32_t ne11; + uint32_t ne12; + uint32_t nb01, nb02, nb03; + uint32_t nb10, nb11, nb12; + uint32_t nb1, nb2, nb3; + uint32_t src0_row_size; + uint32_t dst_row_size; + size_t src0_spad_half; + size_t dst_spad_half; + uint32_t ir0; + uint32_t nrows_per_hvx; + uint32_t step; + uint32_t total_steps; + uint32_t ci_step; + uint32_t ci02; + uint32_t ci03; + uint32_t ci11_base; + uint32_t ci12_base; + bool is_i32; +}; + +static bool set_rows_next_task(void * ctx, struct dma_pipe_task * task) { + struct set_rows_pipe_state * s = (struct set_rows_pipe_state *) ctx; + if (s->step >= s->total_steps) { + return false; + } + + const uint32_t i = s->ir0 + s->ci_step; + const uintptr_t src1_addr = s->src1_data + (size_t) i * s->nb10 + (size_t) s->ci11_base * s->nb11 + (size_t) s->ci12_base * s->nb12; + const uint64_t idx = s->is_i32 ? (uint64_t) *(const int32_t *) src1_addr : (uint64_t) *(const int64_t *) src1_addr; + + task->row = i; + task->off = s->ci02; + task->len = s->ci03; + task->aux = (idx < (uint64_t) s->ne1) ? (uint32_t) idx : UINT32_MAX; + + s->step++; + s->ci_step++; + if (s->ci_step == s->nrows_per_hvx) { + s->ci_step = 0; + s->ci02++; + s->ci11_base++; + if (s->ci11_base == s->ne11) { + s->ci11_base = 0; + } + if (s->ci02 == s->ne02) { + s->ci02 = 0; + s->ci03++; + s->ci12_base++; + if (s->ci12_base == s->ne12) { + s->ci12_base = 0; + } + } + } + return true; +} + +static void set_rows_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct set_rows_pipe_state * s = (struct set_rows_pipe_state *) ctx; + if (task->aux >= s->ne1) { + dma_queue_push(dma_q, dma_make_data(in_spad, 0), 0, 0, 0, 0); + return; + } + const dma_addr_t src0_addr = s->src0_data + (size_t) task->row * s->nb01 + (size_t) task->off * s->nb02 + (size_t) task->len * s->nb03; + dma_queue_push(dma_q, dma_make_data(in_spad, src0_addr), + s->src0_spad_half, s->src0_row_size, s->src0_row_size, 1); +} + +static void set_rows_pipe_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct set_rows_pipe_state * s = (struct set_rows_pipe_state *) ctx; + if (task->aux < s->ne1) { + s->compute(out_spad, in_spad, s->ne00); + } +} + +static void set_rows_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) { + struct set_rows_pipe_state * s = (struct set_rows_pipe_state *) ctx; + if (task->aux >= s->ne1) { + dma_queue_push(dma_q, dma_make_data(0, out_spad), 0, 0, 0, 0); + return; + } + const dma_addr_t dst_addr = s->dst_data + (size_t) task->aux * s->nb1 + (size_t) task->off * s->nb2 + (size_t) task->len * s->nb3; + dma_queue_push(dma_q, dma_make_data(dst_addr, out_spad), + s->dst_row_size, s->dst_spad_half, s->dst_row_size, 1); +} + +static void set_rows_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; + struct set_rows_context * srctx = (struct set_rows_context *) data; + struct htp_ops_context * octx = srctx->octx; set_rows_preamble; - if (htp_tensor_is_extended(octx->src[1])) { - return HTP_STATUS_NO_SUPPORT; + const uint32_t dr = srctx->tasks_per_hvx; + const uint32_t ir0 = srctx->task_start + dr * ith; + if (ir0 >= srctx->task_start + srctx->tasks) { + return; } + const uint32_t ir1 = MIN(ir0 + dr, srctx->task_start + srctx->tasks); + + const struct htp_set_rows_vtcm_layout * vtcm_layout = &srctx->vtcm_layout; + uint8_t * vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, srctx->vtcm_base, vtcm_layout->off_src0) + ith * vtcm_layout->src0_bytes_per_hvx; + uint8_t * vtcm_dst = VTCM_LAYOUT_PTR(uint8_t, srctx->vtcm_base, vtcm_layout->off_dst) + ith * vtcm_layout->dst_bytes_per_hvx; + void * in_buf[2] = { vtcm_src0, vtcm_src0 + vtcm_layout->src0_spad_half_size }; + void * out_buf[2] = { vtcm_dst, vtcm_dst + vtcm_layout->dst_spad_half_size }; + + const uint32_t nrows_per_hvx = ir1 - ir0; + const uint32_t idx_elem_size = srctx->is_i32 ? sizeof(int32_t) : sizeof(int64_t); + + struct set_rows_pipe_state s = { + .src0_data = octx->src[0]->data, + .src1_data = (uintptr_t) srctx->src1_data, + .dst_data = octx->dst->data, + .compute = srctx->compute, + .ne00 = ne00, + .ne02 = ne02, + .ne1 = ne1, + .ne11 = ne11, + .ne12 = ne12, + .nb01 = nb01, .nb02 = nb02, .nb03 = nb03, + .nb10 = idx_elem_size, .nb11 = ne10 * idx_elem_size, .nb12 = ne10 * ne11 * idx_elem_size, + .nb1 = nb1, .nb2 = nb2, .nb3 = nb3, + .src0_row_size = htp_tensor_get_row_size(octx->src[0]->type, ne00), + .dst_row_size = htp_tensor_get_row_size(octx->dst->type, ne00), + .src0_spad_half = vtcm_layout->src0_spad_half_size, + .dst_spad_half = vtcm_layout->dst_spad_half_size, + .ir0 = ir0, + .nrows_per_hvx = nrows_per_hvx, + .step = 0, + .total_steps = ne03 * ne02 * nrows_per_hvx, + .ci_step = 0, + .ci02 = 0, + .ci03 = 0, + .ci11_base = 0, + .ci12_base = 0, + .is_i32 = srctx->is_i32, + }; + + dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, + set_rows_next_task, set_rows_push_in, set_rows_pipe_compute, set_rows_push_out); +} + +int op_set_rows(struct htp_ops_context * octx) { + const struct htp_set_rows_kernel_params * kparams = (const struct htp_set_rows_kernel_params *)octx->kernel_params; + set_rows_preamble; - const struct htp_tensor * dst = octx->dst; const uint32_t total_tasks = kparams->total_tasks; uint32_t task_start = 0; uint32_t tasks = total_tasks; if (octx->ctx->mdev.count > 1) { - const bool can_split = htp_tensor_mdev_data_aligned(dst) && (dst->nb[1] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0 && !htp_tensor_is_permuted(dst); - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_tasks, can_split ? 1 : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_tasks, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); task_start = range.start; tasks = range.count; } @@ -218,9 +265,6 @@ int op_set_rows(struct htp_ops_context * octx) { const uint32_t n_hvx = octx->n_hvx; - // l2fetch the src1 (indices) tensor in the main thread - hex_l2fetch_block((const void *)octx->src[1]->data, octx->src[1]->ne[3] * octx->src[1]->nb[3]); - struct set_rows_context srctx; srctx.octx = octx; srctx.kparams = kparams; @@ -228,19 +272,43 @@ int op_set_rows(struct htp_ops_context * octx) { srctx.tasks = tasks; srctx.tasks_per_hvx = fastdiv(tasks + n_hvx - 1, &octx->n_hvx_div); - htp_set_rows_vtcm_layout_build(&srctx.vtcm_layout, octx->dst->type, ne00, n_hvx); + htp_set_rows_vtcm_layout_build(&srctx.vtcm_layout, octx->src[0]->type, octx->dst->type, ne00, n_hvx); srctx.vtcm_base = (uint8_t *)octx->ctx->vtcm_base; - work_queue_func_t q_func = NULL; - const bool is_i32 = (octx->src[1]->type == HTP_TYPE_I32); + srctx.is_i32 = (octx->src[1]->type == HTP_TYPE_I32); + srctx.compute = NULL; - switch (octx->dst->type) { - case HTP_TYPE_F32: q_func = is_i32 ? set_rows_thread_dma_f32_int32_t : set_rows_thread_dma_f32_int64_t; break; - case HTP_TYPE_F16: q_func = is_i32 ? set_rows_thread_dma_f16_int32_t : set_rows_thread_dma_f16_int64_t; break; - case HTP_TYPE_Q8_0: q_func = is_i32 ? set_rows_thread_dma_q8_0_int32_t : set_rows_thread_dma_q8_0_int64_t; break; - default: return HTP_STATUS_NO_SUPPORT; + if (octx->src[0]->type == HTP_TYPE_F32) { + switch (octx->dst->type) { + case HTP_TYPE_F32: srctx.compute = set_rows_row_f32_f32; break; + case HTP_TYPE_F16: srctx.compute = set_rows_row_f16_f32; break; + case HTP_TYPE_Q8_0: srctx.compute = set_rows_row_q8_0_f32; break; + default: return HTP_STATUS_NO_SUPPORT; + } + } else if (octx->src[0]->type == HTP_TYPE_F16) { + switch (octx->dst->type) { + case HTP_TYPE_F32: srctx.compute = set_rows_row_f32_f16; break; + case HTP_TYPE_F16: srctx.compute = set_rows_row_f16_f16; break; + case HTP_TYPE_Q8_0: srctx.compute = set_rows_row_q8_0_f16; break; + default: return HTP_STATUS_NO_SUPPORT; + } + } else { + return HTP_STATUS_NO_SUPPORT; } + const size_t src1_bytes = hex_round_up(htp_tensor_nbytes(octx->src[1]), 128); + void * src1_buf = (src1_bytes <= octx->ctx->ddr_spad_size) ? octx->ctx->ddr_spad_base : memalign(128, src1_bytes); + if (!src1_buf) { + return HTP_STATUS_INTERNAL_ERR; + } + if (htp_tensor_read(&octx->ctx->main_th, src1_buf, src1_bytes, octx->src[1]) == 0) { + if (src1_buf != octx->ctx->ddr_spad_base) { + free(src1_buf); + } + return HTP_STATUS_INTERNAL_ERR; + } + srctx.src1_data = src1_buf; + FARF(HIGH, "set-rows: (%ux%ux%ux%u) x (%ux%ux%ux%u) -> (%ux%ux%ux%u) : src0-vtcm-size %zu dst-vtcm-size %zu n-hvx %d\n", octx->src[0]->ne[0], octx->src[0]->ne[1], octx->src[0]->ne[2], octx->src[0]->ne[3], octx->src[1]->ne[0], octx->src[1]->ne[1], octx->src[1]->ne[2], octx->src[1]->ne[3], @@ -249,7 +317,11 @@ int op_set_rows(struct htp_ops_context * octx) { srctx.vtcm_layout.dst_bytes_per_hvx * n_hvx, n_hvx); - work_queue_run(octx->ctx->hvx_queue, q_func, &srctx, n_hvx); + work_queue_run(octx->ctx->hvx_queue, set_rows_thread, &srctx, n_hvx); + + if (src1_buf != octx->ctx->ddr_spad_base) { + free(src1_buf); + } return HTP_STATUS_OK; } diff --git a/ggml/src/ggml-hexagon/htp/set-rows-ops.h b/ggml/src/ggml-hexagon/htp/set-rows-ops.h index 85086b08ef6a..b693606d4253 100644 --- a/ggml/src/ggml-hexagon/htp/set-rows-ops.h +++ b/ggml/src/ggml-hexagon/htp/set-rows-ops.h @@ -25,11 +25,12 @@ struct htp_set_rows_vtcm_layout { static inline void htp_set_rows_vtcm_layout_build( struct htp_set_rows_vtcm_layout * L, + int src0_type, int dst_type, uint32_t ne00, uint32_t n_hvx) { - size_t src0_row_size = ne00 * sizeof(float); + size_t src0_row_size = htp_tensor_get_row_size(src0_type, ne00); size_t dst_row_size = htp_tensor_get_row_size(dst_type, ne00); size_t src0_row_size_aligned = (src0_row_size + 255) & ~255; diff --git a/ggml/src/ggml-hexagon/htp/softmax-ops.c b/ggml/src/ggml-hexagon/htp/softmax-ops.c index 22aebcd5e650..44293de0651a 100644 --- a/ggml/src/ggml-hexagon/htp/softmax-ops.c +++ b/ggml/src/ggml-hexagon/htp/softmax-ops.c @@ -1,7 +1,3 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include @@ -9,6 +5,7 @@ #include #include "dma-queue.h" +#include "dma-pipeline.h" #include "work-queue.h" #include "hvx-utils.h" #include "hex-fastdiv.h" @@ -28,7 +25,8 @@ struct htp_softmax_context { struct htp_ops_context * octx; const struct htp_softmax_kernel_params * kparams; - void * compute; + void * prep; + void * softmax; dma_addr_t data_src0; dma_addr_t data_src1; @@ -37,10 +35,13 @@ struct htp_softmax_context { uint8_t * vtcm_src0; uint8_t * vtcm_src1; uint8_t * vtcm_dst; + uint8_t * vtcm_work; + float * vtcm_src2; uint32_t vtcm_src0_size_per_hvx; uint32_t vtcm_src1_size_per_hvx; uint32_t vtcm_dst_size_per_hvx; + uint32_t vtcm_work_size_per_hvx; uint32_t src0_spad_half_size; uint32_t src1_spad_half_size; @@ -50,7 +51,10 @@ struct htp_softmax_context { uint32_t src1_row_size_aligned; uint32_t dst_row_size_aligned; + bool src0_f16; + bool dst_f16; bool use_f16; + bool use_src2; uint32_t n_head; uint32_t n_head_log2; @@ -72,7 +76,7 @@ struct htp_softmax_context { float slopes[512] __attribute__((aligned(128))); }; -typedef void (*softmax_compute_fn_t)( +typedef void (*softmax_prep_fn_t)( void * restrict dst, const void * restrict src0, const void * restrict mask, @@ -81,21 +85,82 @@ typedef void (*softmax_compute_fn_t)( float slope ); -static void hvx_fast_softmax_prep_f16(const uint8_t * restrict src, - uint8_t * restrict dst, - const int num_elems, - float scale, - const uint8_t * restrict mask, - float slope) { - const HVX_Vector * restrict v_src = (const HVX_Vector *) src; +static __attribute__((noinline)) void hvx_fast_softmax_prep_nomask( + void * restrict dst, + const void * restrict src0, + const void * restrict mask, + uint32_t ne00, + float scale, + float slope +) { + (void) mask; + (void) slope; + hvx_scale_f32((uint8_t *) dst, (const uint8_t *) src0, ne00, scale); +} + +static __attribute__((noinline)) void hvx_fast_softmax_prep_src16_nomask( + void * restrict dst, + const void * restrict src0, + const void * restrict mask, + uint32_t ne00, + float scale, + float slope +) { + (void) mask; + (void) slope; + const HVX_Vector * restrict v_src = (const HVX_Vector *) src0; + HVX_Vector * restrict v_dst = (HVX_Vector *) dst; + + HVX_Vector scale_vec = hvx_vec_splat_f32(scale); + + const int nvec_64 = (int) ne00 / VLEN_FP16; + const int nloe_64 = (int) ne00 % VLEN_FP16; + + #pragma unroll(2) + for (int i = 0; i < nvec_64; i++) { + HVX_VectorPair p = hvx_vec_f16_to_f32(v_src[i]); + HVX_Vector s0 = Q6_V_lo_W(p); + HVX_Vector s1 = Q6_V_hi_W(p); + + v_dst[2 * i] = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s0, scale_vec)); + v_dst[2 * i + 1] = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s1, scale_vec)); + } + + if (nloe_64 > 0) { + HVX_VectorPair p = hvx_vec_f16_to_f32(v_src[nvec_64]); + HVX_Vector s0 = Q6_V_lo_W(p); + HVX_Vector v0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s0, scale_vec)); + + if (nloe_64 <= VLEN_FP32) { + hvx_vec_store_a(&v_dst[2 * nvec_64], nloe_64 * sizeof(float), v0); + } else { + v_dst[2 * nvec_64] = v0; + + HVX_Vector s1 = Q6_V_hi_W(p); + HVX_Vector v1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(s1, scale_vec)); + + hvx_vec_store_a(&v_dst[2 * nvec_64 + 1], (nloe_64 - VLEN_FP32) * sizeof(float), v1); + } + } +} + +static __attribute__((noinline)) void hvx_fast_softmax_prep_f16( + void * restrict dst, + const void * restrict src0, + const void * restrict mask, + uint32_t ne00, + float scale, + float slope +) { + const HVX_Vector * restrict v_src = (const HVX_Vector *) src0; HVX_Vector * restrict v_dst = (HVX_Vector *) dst; const HVX_Vector * restrict v_mask = (const HVX_Vector *) mask; HVX_Vector scale_vec = hvx_vec_splat_f32(scale); HVX_Vector slope_vec = hvx_vec_splat_f32(slope); - const int nvec_64 = num_elems / VLEN_FP16; - const int nloe_64 = num_elems % VLEN_FP16; + const int nvec_64 = (int) ne00 / VLEN_FP16; + const int nloe_64 = (int) ne00 % VLEN_FP16; #pragma unroll(2) for (int i = 0; i < nvec_64; i++) { @@ -134,21 +199,23 @@ static void hvx_fast_softmax_prep_f16(const uint8_t * restrict src, } } -static void hvx_fast_softmax_prep_f32(const uint8_t * restrict src, - uint8_t * restrict dst, - const int num_elems, - float scale, - const uint8_t * restrict mask, - float slope) { - const HVX_Vector * restrict v_src = (const HVX_Vector *) src; +static __attribute__((noinline)) void hvx_fast_softmax_prep_f32( + void * restrict dst, + const void * restrict src0, + const void * restrict mask, + uint32_t ne00, + float scale, + float slope +) { + const HVX_Vector * restrict v_src = (const HVX_Vector *) src0; HVX_Vector * restrict v_dst = (HVX_Vector *) dst; const HVX_Vector * restrict v_mask = (const HVX_Vector *) mask; HVX_Vector scale_vec = hvx_vec_splat_f32(scale); HVX_Vector slope_vec = hvx_vec_splat_f32(slope); - const int nvec = num_elems / VLEN_FP32; - const int nloe = num_elems % VLEN_FP32; + const int nvec = (int) ne00 / VLEN_FP32; + const int nloe = (int) ne00 % VLEN_FP32; #pragma unroll(4) for (int i = 0; i < nvec; i++) { @@ -174,76 +241,65 @@ static void hvx_fast_softmax_prep_f32(const uint8_t * restrict src, } } -static void hvx_fast_softmax_f32(const uint8_t * restrict src, uint8_t * restrict dst, const int num_elems) { - const HVX_Vector * restrict v_src = (const HVX_Vector *) src; - HVX_Vector * restrict v_dst = (HVX_Vector *) dst; - - const int nvec = num_elems / VLEN_FP32; - const int nloe = num_elems % VLEN_FP32; - - HVX_Vector max_vec = hvx_vec_splat_f32(((const float *) src)[0]); - - #pragma unroll(2) - for (int i = 0; i < nvec; i++) { - HVX_Vector v1 = v_src[i]; - max_vec = Q6_Vsf_vmax_VsfVsf(max_vec, v1); - } - - if (nloe > 0) { - HVX_VectorPred q_mask = Q6_Q_vsetq_R(nloe * sizeof(float)); - HVX_Vector neg_inf = hvx_vec_splat_f32(-INFINITY); - HVX_Vector v_tail = Q6_V_vmux_QVV(q_mask, v_src[nvec], neg_inf); - max_vec = Q6_Vsf_vmax_VsfVsf(max_vec, v_tail); - } +static __attribute__((noinline)) void hvx_fast_softmax_prep_src16_mask_f16( + void * restrict dst, + const void * restrict src0, + const void * restrict mask, + uint32_t ne00, + float scale, + float slope +) { + const HVX_Vector * restrict v_src = (const HVX_Vector *) src0; + HVX_Vector * restrict v_dst = (HVX_Vector *) dst; + const HVX_Vector * restrict v_mask = (const HVX_Vector *) mask; - max_vec = hvx_vec_reduce_max_f32(max_vec); + HVX_Vector scale_vec = hvx_vec_splat_f32(scale); + HVX_Vector slope_vec = hvx_vec_splat_f32(slope); - HVX_Vector sum_vec = Q6_V_vsplat_R(0x00000000); + const int nvec_64 = (int) ne00 / VLEN_FP16; + const int nloe_64 = (int) ne00 % VLEN_FP16; #pragma unroll(2) - for (int i = 0; i < nvec; i++) { - HVX_Vector v1 = v_src[i]; - HVX_Vector v2 = Q6_Vqf32_vsub_VsfVsf(v1, max_vec); + for (int i = 0; i < nvec_64; i++) { + HVX_VectorPair ps = hvx_vec_f16_to_f32(v_src[i]); + HVX_Vector s0 = Q6_V_lo_W(ps); + HVX_Vector s1 = Q6_V_hi_W(ps); - HVX_Vector v3 = hvx_vec_exp_f32(Q6_Vsf_equals_Vqf32(v2)); + HVX_VectorPair pm = hvx_vec_f16_to_f32(v_mask[i]); + HVX_Vector m0 = Q6_V_lo_W(pm); + HVX_Vector m1 = Q6_V_hi_W(pm); - sum_vec = Q6_Vqf32_vadd_VsfVsf(Q6_Vsf_equals_Vqf32(sum_vec), v3); + HVX_Vector v0 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(s0, scale_vec), Q6_Vqf32_vmpy_VsfVsf(m0, slope_vec)); + HVX_Vector v1 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(s1, scale_vec), Q6_Vqf32_vmpy_VsfVsf(m1, slope_vec)); - v_dst[i] = v3; + v_dst[2 * i] = Q6_Vsf_equals_Vqf32(v0); + v_dst[2 * i + 1] = Q6_Vsf_equals_Vqf32(v1); } - if (nloe > 0) { - HVX_VectorPred q_mask = Q6_Q_vsetq_R(nloe * sizeof(float)); - HVX_Vector v1 = v_src[nvec]; - HVX_Vector v2 = Q6_Vqf32_vsub_VsfVsf(v1, max_vec); - HVX_Vector v3 = hvx_vec_exp_f32(Q6_Vsf_equals_Vqf32(v2)); - HVX_Vector v3_pad = Q6_V_vmux_QVV(q_mask, v3, Q6_V_vzero()); - - sum_vec = Q6_Vqf32_vadd_VsfVsf(Q6_Vsf_equals_Vqf32(sum_vec), v3_pad); - v_dst[nvec] = v3_pad; - } + if (nloe_64 > 0) { + HVX_VectorPair ps = hvx_vec_f16_to_f32(v_src[nvec_64]); + HVX_Vector s0 = Q6_V_lo_W(ps); - sum_vec = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_vec)); + HVX_VectorPair pm = hvx_vec_f16_to_f32(v_mask[nvec_64]); + HVX_Vector m0 = Q6_V_lo_W(pm); - HVX_VectorPred pos_sum = Q6_Q_vcmp_gt_VwVw(sum_vec, Q6_V_vzero()); - HVX_Vector v4 = hvx_vec_inverse_f32(sum_vec); - HVX_Vector scale_vec = Q6_V_vmux_QVV(pos_sum, v4, hvx_vec_splat_f32(1.0f)); + HVX_Vector v0 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(s0, scale_vec), Q6_Vqf32_vmpy_VsfVsf(m0, slope_vec)); - #pragma unroll(2) - for (int i = 0; i < nvec; i++) { - HVX_Vector v1 = v_dst[i]; - HVX_Vector v2 = Q6_Vqf32_vmpy_VsfVsf(v1, scale_vec); - v_dst[i] = Q6_Vsf_equals_Vqf32(v2); - } + if (nloe_64 <= VLEN_FP32) { + hvx_vec_store_a(&v_dst[2 * nvec_64], nloe_64 * sizeof(float), Q6_Vsf_equals_Vqf32(v0)); + } else { + v_dst[2 * nvec_64] = Q6_Vsf_equals_Vqf32(v0); - if (nloe > 0) { - HVX_Vector v1 = v_dst[nvec]; - HVX_Vector v2 = Q6_Vqf32_vmpy_VsfVsf(v1, scale_vec); - hvx_vec_store_a(&v_dst[nvec], nloe * sizeof(float), Q6_Vsf_equals_Vqf32(v2)); + HVX_Vector s1 = Q6_V_hi_W(ps); + HVX_Vector m1 = Q6_V_hi_W(pm); + HVX_Vector v1 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(s1, scale_vec), Q6_Vqf32_vmpy_VsfVsf(m1, slope_vec)); + + hvx_vec_store_a(&v_dst[2 * nvec_64 + 1], (nloe_64 - VLEN_FP32) * sizeof(float), Q6_Vsf_equals_Vqf32(v1)); + } } } -static void compute_fast_softmax_f32_nomask( +static __attribute__((noinline)) void hvx_fast_softmax_prep_src16_mask_f32( void * restrict dst, const void * restrict src0, const void * restrict mask, @@ -251,236 +307,413 @@ static void compute_fast_softmax_f32_nomask( float scale, float slope ) { - (void) mask; - (void) slope; - hvx_scale_f32((uint8_t *) dst, (const uint8_t *) src0, ne00, scale); - hvx_fast_softmax_f32((const uint8_t *) dst, (uint8_t *) dst, ne00); + const HVX_Vector * restrict v_src = (const HVX_Vector *) src0; + HVX_Vector * restrict v_dst = (HVX_Vector *) dst; + const HVX_Vector * restrict v_mask = (const HVX_Vector *) mask; + + HVX_Vector scale_vec = hvx_vec_splat_f32(scale); + HVX_Vector slope_vec = hvx_vec_splat_f32(slope); + + const int nvec_64 = (int) ne00 / VLEN_FP16; + const int nloe_64 = (int) ne00 % VLEN_FP16; + + #pragma unroll(2) + for (int i = 0; i < nvec_64; i++) { + HVX_VectorPair ps = hvx_vec_f16_to_f32(v_src[i]); + HVX_Vector s0 = Q6_V_lo_W(ps); + HVX_Vector s1 = Q6_V_hi_W(ps); + + HVX_Vector m0 = v_mask[2 * i]; + HVX_Vector m1 = v_mask[2 * i + 1]; + + HVX_Vector v0 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(s0, scale_vec), Q6_Vqf32_vmpy_VsfVsf(m0, slope_vec)); + HVX_Vector v1 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(s1, scale_vec), Q6_Vqf32_vmpy_VsfVsf(m1, slope_vec)); + + v_dst[2 * i] = Q6_Vsf_equals_Vqf32(v0); + v_dst[2 * i + 1] = Q6_Vsf_equals_Vqf32(v1); + } + + if (nloe_64 > 0) { + HVX_VectorPair ps = hvx_vec_f16_to_f32(v_src[nvec_64]); + HVX_Vector s0 = Q6_V_lo_W(ps); + HVX_Vector m0 = v_mask[2 * nvec_64]; + HVX_Vector v0 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(s0, scale_vec), Q6_Vqf32_vmpy_VsfVsf(m0, slope_vec)); + + if (nloe_64 <= VLEN_FP32) { + hvx_vec_store_a(&v_dst[2 * nvec_64], nloe_64 * sizeof(float), Q6_Vsf_equals_Vqf32(v0)); + } else { + v_dst[2 * nvec_64] = Q6_Vsf_equals_Vqf32(v0); + + HVX_Vector s1 = Q6_V_hi_W(ps); + HVX_Vector m1 = v_mask[2 * nvec_64 + 1]; + HVX_Vector v1 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(s1, scale_vec), Q6_Vqf32_vmpy_VsfVsf(m1, slope_vec)); + + hvx_vec_store_a(&v_dst[2 * nvec_64 + 1], (nloe_64 - VLEN_FP32) * sizeof(float), Q6_Vsf_equals_Vqf32(v1)); + } + } } -static void compute_fast_softmax_f32_mask_f32( - void * restrict dst, - const void * restrict src0, - const void * restrict mask, - uint32_t ne00, - float scale, - float slope -) { - hvx_fast_softmax_prep_f32((const uint8_t *) src0, (uint8_t *) dst, ne00, scale, (const uint8_t *) mask, slope); - hvx_fast_softmax_f32((const uint8_t *) dst, (uint8_t *) dst, ne00); +typedef void (*softmax_fn_t)( + uint8_t * restrict work, + uint8_t * restrict dst, + const int num_elems, + const float * restrict sink_ptr +); + +#define DEFINE_HVX_FAST_SOFTMAX(SFX, HAS_SINK, DST_F16) \ +static __attribute__((noinline)) void hvx_fast_softmax_##SFX( \ + uint8_t * restrict work, \ + uint8_t * restrict dst, \ + const int num_elems, \ + const float * restrict sink_ptr \ +) { \ + HVX_Vector * restrict v_work = (HVX_Vector *) work; \ + HVX_Vector * restrict v_dst = (HVX_Vector *) dst; \ + (void) sink_ptr; \ + (void) v_dst; \ + \ + const int nvec = num_elems / VLEN_FP32; \ + const int nloe = num_elems % VLEN_FP32; \ + \ + HVX_Vector max_vec = hvx_vec_repl4(v_work[0]); \ + \ + _Pragma("unroll(2)") \ + for (int i = 0; i < nvec; i++) { \ + HVX_Vector v1 = v_work[i]; \ + max_vec = Q6_Vsf_vmax_VsfVsf(max_vec, v1); \ + } \ + \ + if (nloe > 0) { \ + HVX_VectorPred q_mask = Q6_Q_vsetq_R(nloe * sizeof(float)); \ + HVX_Vector neg_inf = hvx_vec_splat_f32(-INFINITY); \ + HVX_Vector v_tail = Q6_V_vmux_QVV(q_mask, v_work[nvec], neg_inf); \ + max_vec = Q6_Vsf_vmax_VsfVsf(max_vec, v_tail); \ + } \ + \ + max_vec = hvx_vec_reduce_max_f32(max_vec); \ + HVX_Vector sink_vec; \ + if (HAS_SINK) { \ + sink_vec = hvx_vec_repl4(hvx_vmemu(sink_ptr)); \ + max_vec = Q6_Vsf_vmax_VsfVsf(max_vec, sink_vec); \ + } \ + \ + HVX_Vector sum_vec = Q6_V_vsplat_R(0x00000000); \ + \ + _Pragma("nounroll") \ + _Pragma("clang loop pipeline(disable)") \ + for (int i = 0; i < nvec; i++) { \ + HVX_Vector v1 = v_work[i]; \ + HVX_Vector v2 = Q6_Vqf32_vsub_VsfVsf(v1, max_vec); \ + HVX_Vector v3 = hvx_vec_exp_f32(Q6_Vsf_equals_Vqf32(v2)); \ + \ + sum_vec = Q6_Vqf32_vadd_VsfVsf(Q6_Vsf_equals_Vqf32(sum_vec), v3); \ + v_work[i] = v3; \ + } \ + \ + if (nloe > 0) { \ + HVX_VectorPred q_mask = Q6_Q_vsetq_R(nloe * sizeof(float)); \ + HVX_Vector v1 = v_work[nvec]; \ + HVX_Vector v2 = Q6_Vqf32_vsub_VsfVsf(v1, max_vec); \ + HVX_Vector v3 = hvx_vec_exp_f32(Q6_Vsf_equals_Vqf32(v2)); \ + HVX_Vector v3_pad = Q6_V_vmux_QVV(q_mask, v3, Q6_V_vzero()); \ + \ + sum_vec = Q6_Vqf32_vadd_VsfVsf(Q6_Vsf_equals_Vqf32(sum_vec), v3_pad); \ + v_work[nvec] = v3_pad; \ + } \ + \ + sum_vec = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_vec)); \ + if (HAS_SINK) { \ + HVX_Vector sink_sub = Q6_Vqf32_vsub_VsfVsf(sink_vec, max_vec); \ + HVX_Vector sink_exp = hvx_vec_exp_f32(Q6_Vsf_equals_Vqf32(sink_sub)); \ + sum_vec = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_VsfVsf(sum_vec, sink_exp)); \ + } \ + \ + HVX_VectorPred pos_sum = Q6_Q_vcmp_gt_VwVw(sum_vec, Q6_V_vzero()); \ + HVX_Vector v4 = hvx_vec_inverse_f32(sum_vec); \ + HVX_Vector scale_vec = Q6_V_vmux_QVV(pos_sum, v4, hvx_vec_splat_f32(1.0f)); \ + \ + if (DST_F16) { \ + const int nvec_64 = num_elems / VLEN_FP16; \ + const int nloe_64 = num_elems % VLEN_FP16; \ + \ + _Pragma("unroll(2)") \ + for (int i = 0; i < nvec_64; i++) { \ + HVX_Vector s0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(v_work[2 * i], scale_vec)); \ + HVX_Vector s1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(v_work[2 * i + 1], scale_vec)); \ + v_dst[i] = hvx_vec_f32_to_f16(s0, s1); \ + } \ + \ + if (nloe_64 > 0) { \ + HVX_Vector s0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(v_work[2 * nvec_64], scale_vec)); \ + HVX_Vector s1 = (nloe_64 > VLEN_FP32) \ + ? Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(v_work[2 * nvec_64 + 1], scale_vec)) \ + : Q6_V_vzero(); \ + HVX_Vector d = hvx_vec_f32_to_f16(s0, s1); \ + hvx_vec_store_a(&v_dst[nvec_64], nloe_64 * sizeof(__fp16), d); \ + } \ + } else { \ + _Pragma("unroll(2)") \ + for (int i = 0; i < nvec; i++) { \ + HVX_Vector v1 = v_work[i]; \ + HVX_Vector v2 = Q6_Vqf32_vmpy_VsfVsf(v1, scale_vec); \ + v_work[i] = Q6_Vsf_equals_Vqf32(v2); \ + } \ + \ + if (nloe > 0) { \ + HVX_Vector v1 = v_work[nvec]; \ + HVX_Vector v2 = Q6_Vqf32_vmpy_VsfVsf(v1, scale_vec); \ + hvx_vec_store_a(&v_work[nvec], nloe * sizeof(float), Q6_Vsf_equals_Vqf32(v2)); \ + } \ + } \ } -static void compute_fast_softmax_f32_mask_f16( - void * restrict dst, - const void * restrict src0, - const void * restrict mask, - uint32_t ne00, - float scale, - float slope +DEFINE_HVX_FAST_SOFTMAX(f32_nosink, 0, 0) +DEFINE_HVX_FAST_SOFTMAX(f32_sink, 1, 0) +DEFINE_HVX_FAST_SOFTMAX(f16_nosink, 0, 1) +DEFINE_HVX_FAST_SOFTMAX(f16_sink, 1, 1) + +#undef DEFINE_HVX_FAST_SOFTMAX + +static __attribute__((noinline)) void softmax_init_alibi_slopes( + float * restrict slopes, + uint32_t n_head, + uint32_t n_head_log2, + float m0, + float m1 ) { - hvx_fast_softmax_prep_f16((const uint8_t *) src0, (uint8_t *) dst, ne00, scale, (const uint8_t *) mask, slope); - hvx_fast_softmax_f32((const uint8_t *) dst, (uint8_t *) dst, ne00); + for (uint32_t h = 0; h < n_head; h += 32) { + HVX_Vector v_slopes = hvx_alibi_slopes(h, 1, n_head_log2, m0, m1); + hvx_vmem(&slopes[h]) = v_slopes; + } } -static const softmax_compute_fn_t softmax_kernels[HTP_SOFTMAX_KERNEL_COUNT] = { - [HTP_SOFTMAX_KERNEL_NOMASK] = compute_fast_softmax_f32_nomask, - [HTP_SOFTMAX_KERNEL_MASK_F32] = compute_fast_softmax_f32_mask_f32, - [HTP_SOFTMAX_KERNEL_MASK_F16] = compute_fast_softmax_f32_mask_f16, +static const softmax_prep_fn_t softmax_prep_kernels[HTP_SOFTMAX_KERNEL_COUNT] = { + [HTP_SOFTMAX_KERNEL_NOMASK] = hvx_fast_softmax_prep_nomask, + [HTP_SOFTMAX_KERNEL_MASK_F32] = hvx_fast_softmax_prep_f32, + [HTP_SOFTMAX_KERNEL_MASK_F16] = hvx_fast_softmax_prep_f16, + [HTP_SOFTMAX_KERNEL_SRC16_NOMASK] = hvx_fast_softmax_prep_src16_nomask, + [HTP_SOFTMAX_KERNEL_SRC16_MASK_F32] = hvx_fast_softmax_prep_src16_mask_f32, + [HTP_SOFTMAX_KERNEL_SRC16_MASK_F16] = hvx_fast_softmax_prep_src16_mask_f16, }; -static void softmax_thread_dma(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { - (void) nth; - const struct htp_softmax_context * smctx = (const struct htp_softmax_context *) data; - struct htp_ops_context * octx = smctx->octx; - const struct htp_tensor * src0 = octx->src[0]; - const struct htp_tensor * dst = octx->dst; - struct htp_thread_trace * tr = th->trace; - - const uint32_t src0_nrows = smctx->nrows; - const uint32_t src0_nrows_per_hvx = smctx->src0_nrows_per_hvx; +static const softmax_fn_t softmax_kernels[2][2] = { + { hvx_fast_softmax_f32_nosink, hvx_fast_softmax_f32_sink }, + { hvx_fast_softmax_f16_nosink, hvx_fast_softmax_f16_sink }, +}; - const uint32_t src0_start_row = smctx->row_start + src0_nrows_per_hvx * ith; - const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, smctx->row_start + src0_nrows); +struct softmax_pipe_state { + const struct htp_softmax_context * smctx; + dma_addr_t data_src0; + dma_addr_t data_src1; + dma_addr_t data_dst; + uint8_t * work_vtcm; + size_t src0_row_size; + size_t dst_row_size; + size_t mask_row_size; + size_t src0_row_size_aligned; + size_t src1_row_size_aligned; + size_t dst_row_size_aligned; + uint32_t ne00, ne01, ne02, ne03; + uint32_t ne12, ne13; + uint32_t nb11, nb12, nb13; + softmax_prep_fn_t prep; + softmax_fn_t softmax_fn; + float scale; + float slope; + const float * sink_ptr; + uint32_t prev_i2; + uint32_t r; + uint32_t r_end; + bool has_bias; + bool has_sinks; + bool dst_f16; +}; - if (src0_start_row >= src0_end_row) { - return; +static bool softmax_next_task(void * ctx, struct dma_pipe_task * task) { + struct softmax_pipe_state * s = (struct softmax_pipe_state *) ctx; + if (s->r >= s->r_end) { + return false; } + task->row = s->r++; + task->off = 0; + task->len = 0; + task->aux = 0; + return true; +} - const dma_addr_t data_src0 = smctx->data_src0; - const dma_addr_t data_dst = smctx->data_dst; +static void softmax_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct softmax_pipe_state * s = (struct softmax_pipe_state *) ctx; + const dma_addr_t src0_addr = s->data_src0 + (size_t) task->row * s->src0_row_size; + dma_queue_push(dma_q, dma_make_data(in_spad, src0_addr), + s->src0_row_size_aligned, s->src0_row_size, s->src0_row_size, 1); +} - const size_t src0_row_size = src0->ne[0] * sizeof(float); - const size_t dst_row_size = src0->ne[0] * sizeof(float); +static void softmax_push_in_mask(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in0_spad, void * in1_spad) { + struct softmax_pipe_state * s = (struct softmax_pipe_state *) ctx; + const struct htp_softmax_context * smctx = s->smctx; + const uint32_t r = task->row; + + const dma_addr_t src0_addr = s->data_src0 + (size_t) r * s->src0_row_size; + + const uint32_t i1 = fastmodulo(r, s->ne01, &smctx->div_ne01); + const uint32_t r_div_ne01 = fastdiv(r, &smctx->div_ne01); + const uint32_t i2 = fastmodulo(r_div_ne01, s->ne02, &smctx->div_ne02); + const uint32_t i3 = fastdiv(r_div_ne01, &smctx->div_ne02); + const uint32_t i12 = (s->ne12 == s->ne02) ? i2 : fastmodulo(i2, s->ne12, &smctx->div_ne12); + const uint32_t i13 = (s->ne13 == s->ne03) ? i3 : fastmodulo(i3, s->ne13, &smctx->div_ne13); + const dma_addr_t src1_addr = s->data_src1 + (size_t) i1 * s->nb11 + (size_t) i12 * s->nb12 + (size_t) i13 * s->nb13; + + dma_queue_push(dma_q, dma_make_data(in0_spad, src0_addr), + s->src0_row_size_aligned, s->src0_row_size, s->src0_row_size, 1); + dma_queue_push(dma_q, dma_make_data(in1_spad, src1_addr), + s->src1_row_size_aligned, s->mask_row_size, s->mask_row_size, 1); +} - uint8_t * src0_vtcm_base = smctx->vtcm_src0 + (ith * smctx->vtcm_src0_size_per_hvx); - uint8_t * dst_vtcm_base = smctx->vtcm_dst + (ith * smctx->vtcm_dst_size_per_hvx); +static void softmax_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct softmax_pipe_state * s = (struct softmax_pipe_state *) ctx; + void * w_spad = s->dst_f16 ? (void *) s->work_vtcm : out_spad; - const size_t src0_vtcm_half = smctx->src0_spad_half_size; - const size_t dst_vtcm_half = smctx->dst_spad_half_size; + if (s->has_sinks) { + const uint32_t r_div_ne01 = fastdiv(task->row, &s->smctx->div_ne01); + const uint32_t i2 = fastmodulo(r_div_ne01, s->ne02, &s->smctx->div_ne02); + if (i2 != s->prev_i2) { + s->sink_ptr = s->smctx->vtcm_src2 + i2; + s->prev_i2 = i2; + } + } - dma_queue * dma_q = th->dma_q; + s->prep(w_spad, in_spad, NULL, s->ne00, s->scale, 1.0f); + s->softmax_fn((uint8_t *) w_spad, (uint8_t *) out_spad, s->ne00, s->sink_ptr); +} - for (uint32_t r = src0_start_row, idx = 0; r < src0_end_row && idx < 2; r++, idx++) { - dma_addr_t cur_dst = data_dst + r * dst_row_size; - dma_addr_t cur_src0 = data_src0 + r * src0_row_size; - void * d_spad = dst_vtcm_base + idx * dst_vtcm_half; - void * s_spad = src0_vtcm_base + idx * src0_vtcm_half; +static void softmax_compute_mask(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in0_spad, void * in1_spad) { + struct softmax_pipe_state * s = (struct softmax_pipe_state *) ctx; + void * w_spad = s->dst_f16 ? (void *) s->work_vtcm : out_spad; - dma_queue_push(dma_q, dma_make_data(cur_dst, d_spad), - dst_row_size, smctx->dst_row_size_aligned, dst_row_size, 0); - dma_queue_push(dma_q, dma_make_data(s_spad, cur_src0), - smctx->src0_row_size_aligned, src0_row_size, src0_row_size, 1); + if (s->has_bias || s->has_sinks) { + const uint32_t r_div_ne01 = fastdiv(task->row, &s->smctx->div_ne01); + const uint32_t i2 = fastmodulo(r_div_ne01, s->ne02, &s->smctx->div_ne02); + if (i2 != s->prev_i2) { + if (s->has_bias) { + s->slope = s->smctx->slopes[i2]; + } + if (s->has_sinks) { + s->sink_ptr = s->smctx->vtcm_src2 + i2; + } + s->prev_i2 = i2; + } } - softmax_compute_fn_t compute = (softmax_compute_fn_t) smctx->compute; - const uint32_t ne00 = src0->ne[0]; + s->prep(w_spad, in0_spad, in1_spad, s->ne00, s->scale, s->slope); + s->softmax_fn((uint8_t *) w_spad, (uint8_t *) out_spad, s->ne00, s->sink_ptr); +} - for (uint32_t r = src0_start_row; r < src0_end_row; ++r) { - void * d_spad = (void *) dma_queue_pop(dma_q).src; - void * s_spad = (void *) dma_queue_pop(dma_q).dst; +static void softmax_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) { + struct softmax_pipe_state * s = (struct softmax_pipe_state *) ctx; + const dma_addr_t dst_addr = s->data_dst + (size_t) task->row * s->dst_row_size; + dma_queue_push(dma_q, dma_make_data(dst_addr, out_spad), + s->dst_row_size, s->dst_row_size_aligned, s->dst_row_size, 1); +} - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, r); - compute(d_spad, s_spad, NULL, ne00, smctx->scale, 1.0f); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, r); +static void softmax_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; + const struct htp_softmax_context * smctx = (const struct htp_softmax_context *) data; + struct htp_ops_context * octx = smctx->octx; + const struct htp_tensor * src0 = octx->src[0]; + const struct htp_tensor * dst = octx->dst; - dma_addr_t cur_dst = data_dst + r * dst_row_size; - dma_queue_push(dma_q, dma_make_data(cur_dst, d_spad), - dst_row_size, smctx->dst_row_size_aligned, dst_row_size, 1); + const uint32_t src0_start_row = smctx->row_start + smctx->src0_nrows_per_hvx * ith; + const uint32_t src0_end_row = MIN(src0_start_row + smctx->src0_nrows_per_hvx, smctx->row_start + smctx->nrows); - const uint32_t next_r = r + 2; - if (next_r < src0_end_row) { - dma_addr_t next_src0 = data_src0 + next_r * src0_row_size; - dma_queue_push(dma_q, dma_make_data(s_spad, next_src0), - smctx->src0_row_size_aligned, src0_row_size, src0_row_size, 1); - } + if (src0_start_row >= src0_end_row) { + return; } - dma_queue_flush(dma_q); + uint8_t * src0_vtcm_base = smctx->vtcm_src0 + (ith * smctx->vtcm_src0_size_per_hvx); + uint8_t * dst_vtcm_base = smctx->vtcm_dst + (ith * smctx->vtcm_dst_size_per_hvx); + void * in_buf[2] = { src0_vtcm_base, src0_vtcm_base + smctx->src0_spad_half_size }; + void * out_buf[2] = { dst_vtcm_base, dst_vtcm_base + smctx->dst_spad_half_size }; + + struct softmax_pipe_state s = { + .smctx = smctx, + .data_src0 = smctx->data_src0, + .data_dst = smctx->data_dst, + .work_vtcm = smctx->dst_f16 ? (smctx->vtcm_work + ith * smctx->vtcm_work_size_per_hvx) : NULL, + .src0_row_size = src0->ne[0] * (smctx->src0_f16 ? sizeof(__fp16) : sizeof(float)), + .dst_row_size = dst->ne[0] * (smctx->dst_f16 ? sizeof(__fp16) : sizeof(float)), + .src0_row_size_aligned = smctx->src0_row_size_aligned, + .dst_row_size_aligned = smctx->dst_row_size_aligned, + .ne00 = src0->ne[0], + .ne02 = src0->ne[2], + .prep = (softmax_prep_fn_t) smctx->prep, + .softmax_fn = (softmax_fn_t) smctx->softmax, + .scale = smctx->scale, + .slope = 1.0f, + .sink_ptr = NULL, + .prev_i2 = (uint32_t) -1, + .r = src0_start_row, + .r_end = src0_end_row, + .has_bias = false, + .has_sinks = smctx->use_src2, + .dst_f16 = smctx->dst_f16, + }; + + dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, + softmax_next_task, softmax_push_in, softmax_compute, softmax_push_out); } -static void softmax_thread_mask_dma(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { +static void softmax_thread_mask(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { (void) nth; const struct htp_softmax_context * smctx = (const struct htp_softmax_context *) data; struct htp_ops_context * octx = smctx->octx; const struct htp_tensor * src0 = octx->src[0]; const struct htp_tensor * src1 = octx->src[1]; const struct htp_tensor * dst = octx->dst; - struct htp_thread_trace * tr = th->trace; - - const uint32_t src0_nrows = smctx->nrows; - const uint32_t src0_nrows_per_hvx = smctx->src0_nrows_per_hvx; - const uint32_t src0_start_row = smctx->row_start + src0_nrows_per_hvx * ith; - const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, smctx->row_start + src0_nrows); + const uint32_t src0_start_row = smctx->row_start + smctx->src0_nrows_per_hvx * ith; + const uint32_t src0_end_row = MIN(src0_start_row + smctx->src0_nrows_per_hvx, smctx->row_start + smctx->nrows); if (src0_start_row >= src0_end_row) { return; } - const dma_addr_t data_src0 = smctx->data_src0; - const dma_addr_t data_src1 = smctx->data_src1; - const dma_addr_t data_dst = smctx->data_dst; - - const size_t src0_row_size = src0->ne[0] * sizeof(float); - const size_t dst_row_size = src0->ne[0] * sizeof(float); - const size_t mask_row_size = smctx->use_f16 ? (src1->ne[0] * sizeof(__fp16)) : (src1->ne[0] * sizeof(float)); - uint8_t * src0_vtcm_base = smctx->vtcm_src0 + (ith * smctx->vtcm_src0_size_per_hvx); uint8_t * src1_vtcm_base = smctx->vtcm_src1 + (ith * smctx->vtcm_src1_size_per_hvx); uint8_t * dst_vtcm_base = smctx->vtcm_dst + (ith * smctx->vtcm_dst_size_per_hvx); + void * in0_buf[2] = { src0_vtcm_base, src0_vtcm_base + smctx->src0_spad_half_size }; + void * in1_buf[2] = { src1_vtcm_base, src1_vtcm_base + smctx->src1_spad_half_size }; + void * out_buf[2] = { dst_vtcm_base, dst_vtcm_base + smctx->dst_spad_half_size }; + + struct softmax_pipe_state s = { + .smctx = smctx, + .data_src0 = smctx->data_src0, + .data_src1 = smctx->data_src1, + .data_dst = smctx->data_dst, + .work_vtcm = smctx->dst_f16 ? (smctx->vtcm_work + ith * smctx->vtcm_work_size_per_hvx) : NULL, + .src0_row_size = src0->ne[0] * (smctx->src0_f16 ? sizeof(__fp16) : sizeof(float)), + .dst_row_size = dst->ne[0] * (smctx->dst_f16 ? sizeof(__fp16) : sizeof(float)), + .mask_row_size = smctx->use_f16 ? (src1->ne[0] * sizeof(__fp16)) : (src1->ne[0] * sizeof(float)), + .src0_row_size_aligned = smctx->src0_row_size_aligned, + .src1_row_size_aligned = smctx->src1_row_size_aligned, + .dst_row_size_aligned = smctx->dst_row_size_aligned, + .ne00 = src0->ne[0], .ne01 = src0->ne[1], .ne02 = src0->ne[2], .ne03 = src0->ne[3], + .ne12 = src1->ne[2], .ne13 = src1->ne[3], + .nb11 = src1->nb[1], .nb12 = src1->nb[2], .nb13 = src1->nb[3], + .prep = (softmax_prep_fn_t) smctx->prep, + .softmax_fn = (softmax_fn_t) smctx->softmax, + .scale = smctx->scale, + .slope = 1.0f, + .sink_ptr = NULL, + .prev_i2 = (uint32_t) -1, + .r = src0_start_row, + .r_end = src0_end_row, + .has_bias = smctx->max_bias > 0.0f, + .has_sinks = smctx->use_src2, + .dst_f16 = smctx->dst_f16, + }; - const size_t src0_vtcm_half = smctx->src0_spad_half_size; - const size_t src1_vtcm_half = smctx->src1_spad_half_size; - const size_t dst_vtcm_half = smctx->dst_spad_half_size; - - const uint32_t nb11 = src1->nb[1]; - const uint32_t nb12 = src1->nb[2]; - const uint32_t nb13 = src1->nb[3]; - - const uint32_t ne00 = src0->ne[0]; - const uint32_t ne01 = src0->ne[1]; - const uint32_t ne02 = src0->ne[2]; - const uint32_t ne03 = src0->ne[3]; - const uint32_t ne12 = src1->ne[2]; - const uint32_t ne13 = src1->ne[3]; - - const struct fastdiv_values * div_ne01 = &smctx->div_ne01; - const struct fastdiv_values * div_ne02 = &smctx->div_ne02; - const struct fastdiv_values * div_ne12 = &smctx->div_ne12; - const struct fastdiv_values * div_ne13 = &smctx->div_ne13; - - dma_queue * dma_q = th->dma_q; - - for (uint32_t r = src0_start_row, idx = 0; r < src0_end_row && idx < 2; r++, idx++) { - dma_addr_t cur_dst = data_dst + r * dst_row_size; - dma_addr_t cur_src0 = data_src0 + r * src0_row_size; - - uint32_t i1 = fastmodulo(r, ne01, div_ne01); - uint32_t r_div_ne01 = fastdiv(r, div_ne01); - uint32_t i2 = fastmodulo(r_div_ne01, ne02, div_ne02); - uint32_t i3 = fastdiv(r_div_ne01, div_ne02); - uint32_t i12 = (ne12 == ne02) ? i2 : fastmodulo(i2, ne12, div_ne12); - uint32_t i13 = (ne13 == ne03) ? i3 : fastmodulo(i3, ne13, div_ne13); - dma_addr_t cur_src1 = data_src1 + i1 * nb11 + i12 * nb12 + i13 * nb13; - - void * d_spad = dst_vtcm_base + idx * dst_vtcm_half; - void * s_spad = src0_vtcm_base + idx * src0_vtcm_half; - void * m_spad = src1_vtcm_base + idx * src1_vtcm_half; - - dma_queue_push(dma_q, dma_make_data(cur_dst, d_spad), - dst_row_size, smctx->dst_row_size_aligned, dst_row_size, 0); - dma_queue_push(dma_q, dma_make_data(s_spad, cur_src0), - smctx->src0_row_size_aligned, src0_row_size, src0_row_size, 1); - dma_queue_push(dma_q, dma_make_data(m_spad, cur_src1), - smctx->src1_row_size_aligned, mask_row_size, mask_row_size, 1); - } - - softmax_compute_fn_t compute = (softmax_compute_fn_t) smctx->compute; - const bool has_bias = smctx->max_bias > 0.0f; - uint32_t prev_i2 = (uint32_t)-1; - float slope = 1.0f; - - for (uint32_t r = src0_start_row; r < src0_end_row; ++r) { - void * d_spad = (void *) (uintptr_t) dma_queue_pop(dma_q).src; - void * s_spad = (void *) (uintptr_t) dma_queue_pop(dma_q).dst; - void * m_spad = (void *) (uintptr_t) dma_queue_pop(dma_q).dst; - - if (has_bias) { - uint32_t r_div_ne01 = fastdiv(r, div_ne01); - uint32_t i2 = fastmodulo(r_div_ne01, ne02, div_ne02); - if (i2 != prev_i2) { - slope = smctx->slopes[i2]; - prev_i2 = i2; - } - } - - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, r); - compute(d_spad, s_spad, m_spad, ne00, smctx->scale, slope); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, r); - - dma_addr_t cur_dst = data_dst + r * dst_row_size; - dma_queue_push(dma_q, dma_make_data(cur_dst, d_spad), - dst_row_size, smctx->dst_row_size_aligned, dst_row_size, 1); - - const uint32_t next_r = r + 2; - if (next_r < src0_end_row) { - dma_addr_t next_src0 = data_src0 + next_r * src0_row_size; - - uint32_t ni1 = fastmodulo(next_r, ne01, div_ne01); - uint32_t nr_div_ne01 = fastdiv(next_r, div_ne01); - uint32_t ni2 = fastmodulo(nr_div_ne01, ne02, div_ne02); - uint32_t ni3 = fastdiv(nr_div_ne01, div_ne02); - uint32_t ni12 = (ne12 == ne02) ? ni2 : fastmodulo(ni2, ne12, div_ne12); - uint32_t ni13 = (ne13 == ne03) ? ni3 : fastmodulo(ni3, ne13, div_ne13); - dma_addr_t next_src1 = data_src1 + ni1 * nb11 + ni12 * nb12 + ni13 * nb13; - - dma_queue_push(dma_q, dma_make_data(s_spad, next_src0), - smctx->src0_row_size_aligned, src0_row_size, src0_row_size, 1); - dma_queue_push(dma_q, dma_make_data(m_spad, next_src1), - smctx->src1_row_size_aligned, mask_row_size, mask_row_size, 1); - } - } - - dma_queue_flush(dma_q); + dma_pipe_io2_run(th->dma_q, th->trace, &s, in0_buf, in1_buf, out_buf, + softmax_next_task, softmax_push_in_mask, softmax_compute_mask, softmax_push_out); } static int execute_op_softmax_f32(struct htp_ops_context * octx) { @@ -507,17 +740,13 @@ static int execute_op_softmax_f32(struct htp_ops_context * octx) { } const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3]; - const size_t elem_size = sizeof(float); - const size_t dst_row_size = dst->nb[1]; uint32_t row_start = 0; uint32_t nrows = src0_nrows; if (octx->ctx->mdev.count > 1) { - uint32_t rows_per_chunk = 0; - htp_tensor_mdev_rows_per_chunk(dst, (uint32_t) elem_size, (uint32_t) dst_row_size, &rows_per_chunk); const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( - src0_nrows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + src0_nrows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); row_start = range.start; nrows = range.count; if (nrows < octx->n_hvx) { @@ -536,14 +765,19 @@ static int execute_op_softmax_f32(struct htp_ops_context * octx) { htp_softmax_vtcm_layout_build(&layout, src0->ne[0], kparams->use_src1 ? octx->src[1]->ne[0] : 0, + kparams->n_head, + kparams->src0_f16 != 0, + kparams->dst_f16 != 0, kparams->use_src1 != 0, kparams->use_f16 != 0, + kparams->use_src2 != 0, kparams->n_hvx); struct htp_softmax_context smctx = { .octx = octx, .kparams = kparams, - .compute = (void *) softmax_kernels[kparams->kernel_type], + .prep = (void *) softmax_prep_kernels[kparams->kernel_type], + .softmax = (void *) softmax_kernels[kparams->dst_f16 != 0][kparams->use_src2 != 0], .data_src0 = src0->data, .data_src1 = kparams->use_src1 ? octx->src[1]->data : 0, @@ -552,10 +786,13 @@ static int execute_op_softmax_f32(struct htp_ops_context * octx) { .vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_src0), .vtcm_dst = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_dst), .vtcm_src1 = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, vtcm_base, layout.off_src1, kparams->use_src1), + .vtcm_work = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, vtcm_base, layout.off_work, kparams->dst_f16), + .vtcm_src2 = VTCM_LAYOUT_PTR_OPTIONAL(float, vtcm_base, layout.off_src2, kparams->use_src2), .vtcm_src0_size_per_hvx = (uint32_t) layout.src0_bytes_per_hvx, .vtcm_src1_size_per_hvx = (uint32_t) layout.src1_bytes_per_hvx, .vtcm_dst_size_per_hvx = (uint32_t) layout.dst_bytes_per_hvx, + .vtcm_work_size_per_hvx = (uint32_t) layout.work_bytes_per_hvx, .src0_spad_half_size = (uint32_t) layout.src0_spad_half_size, .src1_spad_half_size = (uint32_t) layout.src1_spad_half_size, @@ -565,7 +802,10 @@ static int execute_op_softmax_f32(struct htp_ops_context * octx) { .src1_row_size_aligned = (uint32_t) layout.src1_spad_half_size, .dst_row_size_aligned = (uint32_t) layout.dst_spad_half_size, + .src0_f16 = kparams->src0_f16 != 0, + .dst_f16 = kparams->dst_f16 != 0, .use_f16 = kparams->use_f16 != 0, + .use_src2 = kparams->use_src2 != 0, .n_head = kparams->n_head, .n_head_log2 = kparams->n_head_log2, @@ -589,30 +829,33 @@ static int execute_op_softmax_f32(struct htp_ops_context * octx) { if (kparams->n_head > 512) { return HTP_STATUS_INVAL_PARAMS; } - for (uint32_t h = 0; h < kparams->n_head; h += 32) { - HVX_Vector v_slopes = hvx_alibi_slopes(h, 1, kparams->n_head_log2, kparams->m0, kparams->m1); - hvx_vmem(&smctx.slopes[h]) = v_slopes; - } + softmax_init_alibi_slopes(smctx.slopes, kparams->n_head, kparams->n_head_log2, kparams->m0, kparams->m1); + } + + if (kparams->use_src2) { + const struct htp_tensor * src2 = octx->src[2]; + dma_queue * dma_q = octx->ctx->dma[0]; + dma_queue_push(dma_q, dma_make_data(smctx.vtcm_src2, src2->data), layout.src2_bytes, 0, src2->size, 1); + dma_queue_pop(dma_q); } - work_queue_func_t task_func = kparams->use_src1 ? softmax_thread_mask_dma : softmax_thread_dma; + work_queue_func_t task_func = kparams->use_src1 ? softmax_thread_mask : softmax_thread; work_queue_run(octx->ctx->hvx_queue, task_func, &smctx, n_hvx); return HTP_STATUS_OK; } int op_softmax(struct htp_ops_context * octx) { - int err = HTP_STATUS_OK; + if (octx->dst->type != HTP_TYPE_F32 && octx->dst->type != HTP_TYPE_F16) { + return HTP_STATUS_NO_SUPPORT; + } switch (octx->src[0]->type) { case HTP_TYPE_F32: - err = execute_op_softmax_f32(octx); - break; + case HTP_TYPE_F16: + return execute_op_softmax_f32(octx); default: - err = HTP_STATUS_NO_SUPPORT; - break; + return HTP_STATUS_NO_SUPPORT; } - - return err; } diff --git a/ggml/src/ggml-hexagon/htp/softmax-ops.h b/ggml/src/ggml-hexagon/htp/softmax-ops.h index 9e5f9c759f51..3ca9ff3152ed 100644 --- a/ggml/src/ggml-hexagon/htp/softmax-ops.h +++ b/ggml/src/ggml-hexagon/htp/softmax-ops.h @@ -13,11 +13,17 @@ enum htp_softmax_kernel_type { HTP_SOFTMAX_KERNEL_NOMASK = 0, HTP_SOFTMAX_KERNEL_MASK_F32, HTP_SOFTMAX_KERNEL_MASK_F16, + HTP_SOFTMAX_KERNEL_SRC16_NOMASK, + HTP_SOFTMAX_KERNEL_SRC16_MASK_F32, + HTP_SOFTMAX_KERNEL_SRC16_MASK_F16, HTP_SOFTMAX_KERNEL_COUNT, }; struct htp_softmax_kernel_params { uint8_t kernel_type; + uint8_t src0_f16; + uint8_t dst_f16; + uint8_t use_src2; uint32_t n_hvx; uint32_t vtcm_size; @@ -48,10 +54,14 @@ struct htp_softmax_vtcm_layout { size_t off_src0; size_t off_dst; size_t off_src1; + size_t off_work; + size_t off_src2; size_t src0_bytes_per_hvx; size_t dst_bytes_per_hvx; size_t src1_bytes_per_hvx; + size_t work_bytes_per_hvx; + size_t src2_bytes; size_t src0_spad_half_size; size_t dst_spad_half_size; @@ -62,17 +72,23 @@ static inline void htp_softmax_vtcm_layout_build( struct htp_softmax_vtcm_layout * L, uint32_t ne00, uint32_t ne10, + uint32_t n_head, + bool src0_f16, + bool dst_f16, bool use_src1, bool use_f16, + bool use_src2, uint32_t n_hvx ) { - size_t src0_row_size = ne00 * sizeof(float); - size_t dst_row_size = ne00 * sizeof(float); + size_t src0_row_size = ne00 * (src0_f16 ? 2 : 4); + size_t dst_row_size = ne00 * (dst_f16 ? 2 : 4); size_t src1_row_size = use_src1 ? (ne10 * (use_f16 ? 2 : 4)) : 0; + size_t work_row_size = dst_f16 ? (ne00 * sizeof(float)) : 0; size_t src0_row_size_aligned = hex_round_up(src0_row_size, 128); size_t dst_row_size_aligned = hex_round_up(dst_row_size, 128); size_t src1_row_size_aligned = use_src1 ? hex_round_up(src1_row_size, 128) : 0; + size_t work_row_size_aligned = dst_f16 ? hex_round_up(work_row_size, 128) : 0; L->src0_spad_half_size = src0_row_size_aligned; L->dst_spad_half_size = dst_row_size_aligned; @@ -82,11 +98,15 @@ static inline void htp_softmax_vtcm_layout_build( L->src0_bytes_per_hvx = src0_row_size_aligned * 2; L->dst_bytes_per_hvx = dst_row_size_aligned * 2; L->src1_bytes_per_hvx = src1_row_size_aligned * 2; + L->work_bytes_per_hvx = work_row_size_aligned; + L->src2_bytes = use_src2 ? hex_round_up(n_head * sizeof(float), 128) : 0; size_t off = 0; VTCM_LAYOUT_ALLOC(off, off_src0, L->src0_bytes_per_hvx * n_hvx); VTCM_LAYOUT_ALLOC(off, off_dst, L->dst_bytes_per_hvx * n_hvx); VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_src1, L->src1_bytes_per_hvx * n_hvx, use_src1); + VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_work, L->work_bytes_per_hvx * n_hvx, dst_f16); + VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_src2, L->src2_bytes, use_src2); L->total_bytes = off; } diff --git a/ggml/src/ggml-hexagon/htp/solve-tri-ops.c b/ggml/src/ggml-hexagon/htp/solve-tri-ops.c index 73eff927edff..082db4043c7b 100644 --- a/ggml/src/ggml-hexagon/htp/solve-tri-ops.c +++ b/ggml/src/ggml-hexagon/htp/solve-tri-ops.c @@ -1,8 +1,7 @@ -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include +#include "dma-queue.h" #include "hex-common.h" #include "htp-trace.h" @@ -11,155 +10,309 @@ #include "htp-ctx.h" #include "htp-ops.h" #include "htp-tensor.h" +#include "htp-vtcm.h" #include "hvx-types.h" #include "hvx-utils.h" #include "solve-tri-ops.h" struct htp_solve_tri_context { - struct htp_ops_context * octx; + struct htp_ops_context * octx; const struct htp_solve_tri_kernel_params * kparams; - uint32_t jobs_per_hvx; - uint32_t total_jobs; - uint32_t job_start; - uint32_t k_chunks; - uint32_t col_block; + uint8_t * vtcm_a; + uint8_t * vtcm_bx; + size_t a_row_aligned; + size_t a_bytes_per_hvx; + size_t bx_bytes_per_hvx; + uint32_t jobs_per_hvx; + uint32_t total_jobs; + uint32_t job_start; + uint32_t k_chunks; + uint32_t col_block; + uint32_t a_full; + uint8_t a_f16; + uint8_t b_f16; + uint8_t x_f16; }; -static inline void solve_tri_row_scalar(const float * A_row, - const float * B_row, - float * X, - uint32_t row, - uint32_t k, - uint32_t col0, - uint32_t coln, - float inv_diag) { - for (uint32_t col = col0; col < col0 + coln; ++col) { - float sum = 0.0f; - for (uint32_t t = 0; t < row; ++t) { - sum += A_row[t] * X[t * k + col]; - } - X[row * k + col] = (B_row[col] - sum) * inv_diag; +static inline HVX_Vector hvx_solve_tri_clamp_f16(HVX_Vector v) { + const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); + const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); + return Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v)); +} + +static void __attribute__((noinline)) solve_tri_widen_bx_f16(HVX_Vector * restrict bx, uint32_t n) { + for (uint32_t row = 0; row < n; ++row) { + bx[row] = Q6_V_lo_W(hvx_vec_f16_to_f32(bx[row])); } } -static inline HVX_Vector hvx_load_partial_f32(const float * src, uint32_t n) { - HVX_Vector v = *((const HVX_UVector *) src); - HVX_VectorPred mask = Q6_Q_vsetq2_R(n * sizeof(float)); - return Q6_V_vmux_QVV(mask, v, Q6_V_vzero()); +static void __attribute__((noinline)) solve_tri_pack_bx_f16(HVX_Vector * restrict bx, uint32_t n) { + const HVX_Vector zero = Q6_V_vzero(); + for (uint32_t row = 0; row < n; ++row) { + bx[row] = hvx_vec_f32_to_f16(hvx_solve_tri_clamp_f16(bx[row]), zero); + } } -static inline void solve_tri_row_hvx(const float * A_row, - const float * B_row, - float * X, - uint32_t row, - uint32_t k, - uint32_t col0, - uint32_t coln, - float inv_diag) { - const bool full = (coln == VLEN_FP32); +static void __attribute__((noinline)) solve_tri_widen_a_row_f16(uint8_t * restrict row_buf, uint32_t len) { + HVX_Vector * restrict vecs = (HVX_Vector *) row_buf; + const uint32_t nvec_f32 = (len + VLEN_FP32 - 1) >> 5; + const uint32_t nvec_f16 = (len + VLEN_FP16 - 1) >> 6; + for (int32_t vi = (int32_t) nvec_f16 - 1; vi >= 0; --vi) { + const HVX_VectorPair p = hvx_vec_f16_to_f32(vecs[vi]); + if ((uint32_t) (2 * vi + 1) < nvec_f32) { + vecs[2 * vi + 1] = Q6_V_hi_W(p); + } + vecs[2 * vi] = Q6_V_lo_W(p); + } +} +static void __attribute__((noinline)) solve_tri_widen_a_full_f16(uint8_t * restrict vtcm_a, size_t a_row_aligned, uint32_t n) { + for (uint32_t row = 0; row < n; ++row) { + solve_tri_widen_a_row_f16(vtcm_a + (size_t) row * a_row_aligned, row + 1); + } +} + +static inline void solve_tri_row_vtcm_hvx( + const HVX_Vector * restrict a_row_vecs, + HVX_Vector * restrict bx, + uint32_t row +) { HVX_Vector sum_v = Q6_V_vzero(); - for (uint32_t t = 0; t < row; ++t) { - const float a = A_row[t]; - const float * x_row_col = X + t * k + col0; + uint32_t t = 0; + + for (; t + VLEN_FP32 <= row; t += VLEN_FP32) { + const HVX_Vector a_vec = a_row_vecs[t >> 5]; + for (uint32_t j = 0; j < VLEN_FP32; ++j) { + const HVX_Vector a_v = Q6_V_vsplat_R(Q6_R_vextract_VR(a_vec, j * 4)); + sum_v = hvx_vec_add_f32_f32(sum_v, hvx_vec_mul_f32_f32(bx[t + j], a_v)); + } + } + + if (t < row) { + const HVX_Vector a_vec = a_row_vecs[t >> 5]; + const uint32_t rem = row - t; + for (uint32_t j = 0; j < rem; ++j) { + const HVX_Vector a_v = Q6_V_vsplat_R(Q6_R_vextract_VR(a_vec, j * 4)); + sum_v = hvx_vec_add_f32_f32(sum_v, hvx_vec_mul_f32_f32(bx[t + j], a_v)); + } + } - HVX_Vector x_v = full ? *((const HVX_UVector *) x_row_col) : hvx_load_partial_f32(x_row_col, coln); - HVX_Vector a_v = hvx_vec_splat_f32(a); - sum_v = hvx_vec_add_f32_f32(sum_v, hvx_vec_mul_f32_f32(x_v, a_v)); + const int32_t diag_bits = Q6_R_vextract_VR(a_row_vecs[row >> 5], (row & 31u) * 4); + float diag; + memcpy(&diag, &diag_bits, sizeof(float)); + + const HVX_Vector inv_diag_v = hvx_vec_splat_f32(1.0f / diag); + bx[row] = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(bx[row], sum_v), inv_diag_v); +} + +static void __attribute__((noinline)) solve_tri_solve_full_f32( + const uint8_t * restrict vtcm_a, + HVX_Vector * restrict vtcm_bx, + size_t a_row_aligned, + uint32_t n +) { + for (uint32_t row = 0; row < n; ++row) { + const HVX_Vector * a_row_vecs = (const HVX_Vector *) (vtcm_a + (size_t) row * a_row_aligned); + solve_tri_row_vtcm_hvx(a_row_vecs, vtcm_bx, row); } +} - const float * b_row_col = B_row + col0; - float * x_out_col = X + row * k + col0; +static void __attribute__((noinline)) solve_tri_solve_row_f32( + const HVX_Vector * restrict a_row_vecs, + HVX_Vector * restrict vtcm_bx, + uint32_t row +) { + solve_tri_row_vtcm_hvx(a_row_vecs, vtcm_bx, row); +} - HVX_Vector b_v = full ? *((const HVX_UVector *) b_row_col) : hvx_load_partial_f32(b_row_col, coln); - HVX_Vector inv_diag_v = hvx_vec_splat_f32(inv_diag); +static void solve_tri_col_chunk_a_full( + dma_queue * dma_q, + struct htp_thread_trace * tr, + const uint8_t * vtcm_a, + HVX_Vector * vtcm_bx, + dma_addr_t B_batch, + dma_addr_t X_batch, + uint32_t nb11, + uint32_t dst_nb1, + size_t a_row_aligned, + uint32_t n, + uint32_t col0, + uint32_t coln, + uint8_t b_f16, + uint8_t x_f16, + uint16_t trace_id +) { + const size_t b_elem_size = b_f16 ? sizeof(__fp16) : sizeof(float); + const size_t x_elem_size = x_f16 ? sizeof(__fp16) : sizeof(float); + + dma_queue_push(dma_q, dma_make_data(vtcm_bx, B_batch + (size_t) col0 * b_elem_size), VLEN, nb11, (size_t) coln * b_elem_size, n); + dma_queue_pop(dma_q); + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, trace_id); + if (b_f16) { + solve_tri_widen_bx_f16(vtcm_bx, n); + } + solve_tri_solve_full_f32(vtcm_a, vtcm_bx, a_row_aligned, n); + if (x_f16) { + solve_tri_pack_bx_f16(vtcm_bx, n); + } + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, trace_id); + + dma_queue_push(dma_q, dma_make_data(X_batch + (size_t) col0 * x_elem_size, vtcm_bx), dst_nb1, VLEN, (size_t) coln * x_elem_size, n); + dma_queue_pop(dma_q); +} + +static void solve_tri_col_chunk_a_stream( + dma_queue * dma_q, + struct htp_thread_trace * tr, + uint8_t * vtcm_a_row, + HVX_Vector * vtcm_bx, + dma_addr_t A_batch, + dma_addr_t B_batch, + dma_addr_t X_batch, + uint32_t nb01, + uint32_t nb11, + uint32_t dst_nb1, + uint32_t n, + uint32_t col0, + uint32_t coln, + uint8_t a_f16, + uint8_t b_f16, + uint8_t x_f16, + uint16_t trace_id +) { + const size_t a_elem_size = a_f16 ? sizeof(__fp16) : sizeof(float); + const size_t b_elem_size = b_f16 ? sizeof(__fp16) : sizeof(float); + const size_t x_elem_size = x_f16 ? sizeof(__fp16) : sizeof(float); + + dma_queue_push(dma_q, dma_make_data(vtcm_bx, B_batch + (size_t) col0 * b_elem_size), VLEN, nb11, (size_t) coln * b_elem_size, n); + dma_queue_pop(dma_q); + + if (b_f16) { + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, trace_id); + solve_tri_widen_bx_f16(vtcm_bx, n); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, trace_id); + } + + for (uint32_t row = 0; row < n; ++row) { + const size_t a_bytes = (size_t) (row + 1) * a_elem_size; + dma_sync_read(dma_q, vtcm_a_row, A_batch + (size_t) row * nb01, a_bytes); + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, trace_id); + if (a_f16) { + solve_tri_widen_a_row_f16(vtcm_a_row, row + 1); + } + solve_tri_solve_row_f32((const HVX_Vector *) vtcm_a_row, vtcm_bx, row); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, trace_id); + } + + if (x_f16) { + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, trace_id); + solve_tri_pack_bx_f16(vtcm_bx, n); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, trace_id); + } - HVX_Vector out_v = hvx_vec_mul_f32_f32(hvx_vec_sub_f32_f32(b_v, sum_v), inv_diag_v); - hvx_vec_store_u((void *) x_out_col, coln * sizeof(float), out_v); + dma_queue_push(dma_q, dma_make_data(X_batch + (size_t) col0 * x_elem_size, vtcm_bx), dst_nb1, VLEN, (size_t) coln * x_elem_size, n); + dma_queue_pop(dma_q); } // Batch-level thread: each job is one full batch. -static void solve_tri_batch_thread_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { - struct htp_solve_tri_context * sctx = (struct htp_solve_tri_context *) data; - struct htp_ops_context * octx = sctx->octx; +static void solve_tri_batch_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + struct htp_solve_tri_context * sctx = (struct htp_solve_tri_context *) data; + struct htp_ops_context * octx = sctx->octx; const struct htp_solve_tri_kernel_params * kparams = sctx->kparams; - const struct htp_tensor * src0 = octx->src[0]; // A - const struct htp_tensor * src1 = octx->src[1]; // B - const struct htp_tensor * dst = octx->dst; // X - - const uint32_t n = src0->ne[0]; - const uint32_t k = src1->ne[0]; + const struct htp_tensor * src0 = octx->src[0]; + const struct htp_tensor * src1 = octx->src[1]; + const struct htp_tensor * dst = octx->dst; + const uint32_t n = src0->ne[0]; + const uint32_t k = src1->ne[0]; const uint32_t ne02 = src0->ne[2]; - const uint32_t col_block = VLEN_FP32; - const uint32_t k_full = k & ~(col_block - 1); - const uint32_t start_batch = sctx->job_start + sctx->jobs_per_hvx * ith; const uint32_t end_batch = MIN(start_batch + sctx->jobs_per_hvx, sctx->job_start + sctx->total_jobs); + if (start_batch >= end_batch) { + return; + } - struct htp_thread_trace * tr = th->trace; - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) start_batch); + uint8_t * vtcm_a = sctx->vtcm_a + ith * sctx->a_bytes_per_hvx; + HVX_Vector * vtcm_bx = (HVX_Vector *) (sctx->vtcm_bx + ith * sctx->bx_bytes_per_hvx); + const size_t a_row_aligned = sctx->a_row_aligned; + const uint8_t a_f16 = sctx->a_f16; + const uint8_t b_f16 = sctx->b_f16; + const uint8_t x_f16 = sctx->x_f16; + const size_t a_row_bytes = (size_t) n * (a_f16 ? sizeof(__fp16) : sizeof(float)); + + dma_queue * dma_q = th->dma_q; + struct htp_thread_trace * tr = th->trace; for (uint32_t batch = start_batch; batch < end_batch; ++batch) { const uint32_t i03 = fastdiv(batch, &kparams->div_ne02); const uint32_t i02 = batch - i03 * ne02; - const float * A_batch = - (const float *) ((const uint8_t *) (uintptr_t) src0->data + i02 * src0->nb[2] + i03 * src0->nb[3]); - const float * B_batch = - (const float *) ((const uint8_t *) (uintptr_t) src1->data + i02 * src1->nb[2] + i03 * src1->nb[3]); - float * X_batch = (float *) ((uint8_t *) (uintptr_t) dst->data + i02 * dst->nb[2] + i03 * dst->nb[3]); - - for (uint32_t row = 0; row < n; ++row) { - const float diag = A_batch[row * n + row]; - const float inv_diag = 1.0f / diag; - const float * A_row = A_batch + row * n; - const float * B_row = B_batch + row * k; - - uint32_t col0 = 0; - for (; col0 < k_full; col0 += col_block) { - solve_tri_row_hvx(A_row, B_row, X_batch, row, k, col0, col_block, inv_diag); + const dma_addr_t A_batch = src0->data + (size_t) i02 * src0->nb[2] + (size_t) i03 * src0->nb[3]; + const dma_addr_t B_batch = src1->data + (size_t) i02 * src1->nb[2] + (size_t) i03 * src1->nb[3]; + const dma_addr_t X_batch = dst->data + (size_t) i02 * dst->nb[2] + (size_t) i03 * dst->nb[3]; + + if (sctx->a_full) { + dma_queue_push(dma_q, dma_make_data(vtcm_a, A_batch), a_row_aligned, src0->nb[1], a_row_bytes, n); + dma_queue_pop(dma_q); + if (a_f16) { + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) batch); + solve_tri_widen_a_full_f16(vtcm_a, a_row_aligned, n); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) batch); } - if (col0 < k) { - const uint32_t coln = k - col0; - if (coln >= 8) { - solve_tri_row_hvx(A_row, B_row, X_batch, row, k, col0, coln, inv_diag); - } else { - solve_tri_row_scalar(A_row, B_row, X_batch, row, k, col0, coln, inv_diag); - } + for (uint32_t col0 = 0; col0 < k; col0 += VLEN_FP32) { + const uint32_t coln = MIN(VLEN_FP32, k - col0); + solve_tri_col_chunk_a_full(dma_q, tr, vtcm_a, vtcm_bx, B_batch, X_batch, + src1->nb[1], dst->nb[1], a_row_aligned, n, col0, coln, b_f16, x_f16, (uint16_t) batch); + } + } else { + for (uint32_t col0 = 0; col0 < k; col0 += VLEN_FP32) { + const uint32_t coln = MIN(VLEN_FP32, k - col0); + solve_tri_col_chunk_a_stream(dma_q, tr, vtcm_a, vtcm_bx, A_batch, B_batch, X_batch, + src0->nb[1], src1->nb[1], dst->nb[1], n, col0, coln, a_f16, b_f16, x_f16, (uint16_t) batch); } } } - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) end_batch); - FARF(HIGH, "solve-tri-batch %d/%d: A=(%ux%u) B=(%ux%u) batch %u:%u\n", ith, nth, n, n, k, n, start_batch, end_batch); } // Chunk-level thread: each job is one (batch, col_chunk) pair. -static void solve_tri_chunk_thread_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { - struct htp_solve_tri_context * sctx = (struct htp_solve_tri_context *) data; - struct htp_ops_context * octx = sctx->octx; +static void solve_tri_chunk_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + struct htp_solve_tri_context * sctx = (struct htp_solve_tri_context *) data; + struct htp_ops_context * octx = sctx->octx; const struct htp_solve_tri_kernel_params * kparams = sctx->kparams; - const struct htp_tensor * src0 = octx->src[0]; // A - const struct htp_tensor * src1 = octx->src[1]; // B - const struct htp_tensor * dst = octx->dst; // X - - const uint32_t n = src0->ne[0]; - const uint32_t k = src1->ne[0]; + const struct htp_tensor * src0 = octx->src[0]; + const struct htp_tensor * src1 = octx->src[1]; + const struct htp_tensor * dst = octx->dst; + const uint32_t n = src0->ne[0]; + const uint32_t k = src1->ne[0]; const uint32_t ne02 = src0->ne[2]; const uint32_t start_job = sctx->job_start + sctx->jobs_per_hvx * ith; const uint32_t end_job = MIN(start_job + sctx->jobs_per_hvx, sctx->job_start + sctx->total_jobs); + if (start_job >= end_job) { + return; + } - struct htp_thread_trace * tr = th->trace; - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) start_job); + uint8_t * vtcm_a = sctx->vtcm_a + ith * sctx->a_bytes_per_hvx; + HVX_Vector * vtcm_bx = (HVX_Vector *) (sctx->vtcm_bx + ith * sctx->bx_bytes_per_hvx); + const size_t a_row_aligned = sctx->a_row_aligned; + const uint8_t a_f16 = sctx->a_f16; + const uint8_t b_f16 = sctx->b_f16; + const uint8_t x_f16 = sctx->x_f16; + const size_t a_row_bytes = (size_t) n * (a_f16 ? sizeof(__fp16) : sizeof(float)); + + dma_queue * dma_q = th->dma_q; + struct htp_thread_trace * tr = th->trace; + uint32_t last_batch = UINT32_MAX; for (uint32_t job = start_job; job < end_job; ++job) { const uint32_t batch = fastdiv(job, &kparams->div_k_chunks); @@ -168,123 +321,114 @@ static void solve_tri_chunk_thread_f32(const htp_thread_t * th, unsigned int nth const uint32_t i03 = fastdiv(batch, &kparams->div_ne02); const uint32_t i02 = batch - i03 * ne02; - const float * A_batch = - (const float *) ((const uint8_t *) (uintptr_t) src0->data + i02 * src0->nb[2] + i03 * src0->nb[3]); - const float * B_batch = - (const float *) ((const uint8_t *) (uintptr_t) src1->data + i02 * src1->nb[2] + i03 * src1->nb[3]); - float * X_batch = (float *) ((uint8_t *) (uintptr_t) dst->data + i02 * dst->nb[2] + i03 * dst->nb[3]); + const dma_addr_t A_batch = src0->data + (size_t) i02 * src0->nb[2] + (size_t) i03 * src0->nb[3]; + const dma_addr_t B_batch = src1->data + (size_t) i02 * src1->nb[2] + (size_t) i03 * src1->nb[3]; + const dma_addr_t X_batch = dst->data + (size_t) i02 * dst->nb[2] + (size_t) i03 * dst->nb[3]; const uint32_t col0 = chunk * sctx->col_block; const uint32_t coln = MIN(sctx->col_block, k - col0); - for (uint32_t row = 0; row < n; ++row) { - const float diag = A_batch[row * n + row]; - const float inv_diag = 1.0f / diag; - - const float * A_row = A_batch + row * n; - const float * B_row = B_batch + row * k; - - if (coln >= 8) { - solve_tri_row_hvx(A_row, B_row, X_batch, row, k, col0, coln, inv_diag); - } else { - solve_tri_row_scalar(A_row, B_row, X_batch, row, k, col0, coln, inv_diag); + if (sctx->a_full) { + if (batch != last_batch) { + dma_queue_push(dma_q, dma_make_data(vtcm_a, A_batch), a_row_aligned, src0->nb[1], a_row_bytes, n); + dma_queue_pop(dma_q); + if (a_f16) { + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) job); + solve_tri_widen_a_full_f16(vtcm_a, a_row_aligned, n); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) job); + } + last_batch = batch; } + solve_tri_col_chunk_a_full(dma_q, tr, vtcm_a, vtcm_bx, B_batch, X_batch, + src1->nb[1], dst->nb[1], a_row_aligned, n, col0, coln, b_f16, x_f16, (uint16_t) job); + } else { + solve_tri_col_chunk_a_stream(dma_q, tr, vtcm_a, vtcm_bx, A_batch, B_batch, X_batch, + src0->nb[1], src1->nb[1], dst->nb[1], n, col0, coln, a_f16, b_f16, x_f16, (uint16_t) job); } } - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) end_job); - FARF(HIGH, "solve-tri-chunk %d/%d: A=(%ux%u) B=(%ux%u) jobs %u:%u\n", ith, nth, n, n, k, n, start_job, end_job); } int op_solve_tri(struct htp_ops_context * octx) { - const struct htp_tensor * src0 = octx->src[0]; // A - const struct htp_tensor * src1 = octx->src[1]; // B - const struct htp_tensor * dst = octx->dst; // X - const struct htp_solve_tri_kernel_params * kparams = - (const struct htp_solve_tri_kernel_params *) octx->kernel_params; + const struct htp_tensor * src0 = octx->src[0]; + const struct htp_tensor * src1 = octx->src[1]; + const struct htp_tensor * dst = octx->dst; - if (htp_tensor_is_extended(src0) || htp_tensor_is_extended(src1) || htp_tensor_is_extended(dst)) { + if ((src0->type != HTP_TYPE_F32 && src0->type != HTP_TYPE_F16) || + (src1->type != HTP_TYPE_F32 && src1->type != HTP_TYPE_F16) || + (dst->type != HTP_TYPE_F32 && dst->type != HTP_TYPE_F16)) { return HTP_STATUS_NO_SUPPORT; } + const struct htp_solve_tri_kernel_params * kparams = + (const struct htp_solve_tri_kernel_params *) octx->kernel_params; + const uint32_t col_block = kparams->col_block; const uint32_t k_chunks = kparams->k_chunks; const uint32_t total_batches = kparams->total_batches; const bool batched = (kparams->batched != 0); + const uint8_t a_f16 = (src0->type == HTP_TYPE_F16) ? 1 : 0; + const uint8_t b_f16 = (src1->type == HTP_TYPE_F16) ? 1 : 0; + const uint8_t x_f16 = (dst->type == HTP_TYPE_F16) ? 1 : 0; FARF(HIGH, "solve-tri: (%ux%ux%ux%u) x (%ux%ux%ux%u) -> (%ux%ux%ux%u) : batched %d\n", src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3], src1->ne[0], src1->ne[1], src1->ne[2], src1->ne[3], dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3], batched); - if (batched) { - uint32_t job_start = 0; - uint32_t njobs = total_batches; - - if (octx->ctx->mdev.count > 1) { - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_batches, htp_tensor_mdev_data_aligned(dst) ? kparams->batches_per_chunk : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); - job_start = range.start; - njobs = range.count; - } - - if (njobs == 0) { - return HTP_STATUS_OK; - } - - if (!htp_ops_context_set_n_hvx(octx, MIN(kparams->n_hvx, njobs))) { - return HTP_STATUS_INVAL_PARAMS; - } - - const uint32_t n_hvx = octx->n_hvx; - - struct htp_solve_tri_context sctx = { - .octx = octx, - .kparams = kparams, - .jobs_per_hvx = fastdiv(njobs + n_hvx - 1, &octx->n_hvx_div), - .total_jobs = njobs, - .job_start = job_start, - .k_chunks = k_chunks, - .col_block = col_block, - }; - - work_queue_run(octx->ctx->hvx_queue, solve_tri_batch_thread_f32, &sctx, n_hvx); - } else { - const uint32_t total_jobs = kparams->total_jobs; - - uint32_t job_start = 0; - uint32_t njobs = total_jobs; - - if (octx->ctx->mdev.count > 1) { - const bool can_split = htp_tensor_mdev_data_aligned(dst) && ((dst->nb[1] & (HTP_TENSOR_MDEV_LINE_SIZE - 1)) == 0); - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(total_jobs, can_split ? 1 : 0, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); - job_start = range.start; - njobs = range.count; - } + uint32_t job_start = 0; + uint32_t njobs = batched ? total_batches : kparams->total_jobs; - if (njobs == 0) { - return HTP_STATUS_OK; - } + if (octx->ctx->mdev.count > 1) { + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( + njobs, 1, + octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + job_start = range.start; + njobs = range.count; + } - if (!htp_ops_context_set_n_hvx(octx, MIN(kparams->n_hvx, njobs))) { - return HTP_STATUS_INVAL_PARAMS; - } + if (njobs == 0) { + return HTP_STATUS_OK; + } - const uint32_t n_hvx = octx->n_hvx; + if (!htp_ops_context_set_n_hvx(octx, MIN(kparams->n_hvx, njobs))) { + return HTP_STATUS_INVAL_PARAMS; + } - struct htp_solve_tri_context sctx = { - .octx = octx, - .kparams = kparams, - .jobs_per_hvx = fastdiv(njobs + n_hvx - 1, &octx->n_hvx_div), - .total_jobs = njobs, - .job_start = job_start, - .k_chunks = k_chunks, - .col_block = col_block, - }; + const uint32_t n_hvx = octx->n_hvx; - work_queue_run(octx->ctx->hvx_queue, solve_tri_chunk_thread_f32, &sctx, n_hvx); + struct htp_solve_tri_vtcm_layout layout; + htp_solve_tri_vtcm_layout_build(&layout, src0->ne[0], kparams->a_full, n_hvx); + if (octx->ctx->vtcm_size < layout.total_bytes) { + FARF(ERROR, "solve-tri: VTCM size %zu is too small, needed %zu\n", octx->ctx->vtcm_size, layout.total_bytes); + return HTP_STATUS_VTCM_TOO_SMALL; } + uint8_t * vtcm_base = octx->ctx->vtcm_base; + + struct htp_solve_tri_context sctx = { + .octx = octx, + .kparams = kparams, + .vtcm_a = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_a), + .vtcm_bx = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, layout.off_bx), + .a_row_aligned = layout.a_row_aligned, + .a_bytes_per_hvx = layout.a_bytes_per_hvx, + .bx_bytes_per_hvx = layout.bx_bytes_per_hvx, + .jobs_per_hvx = fastdiv(njobs + n_hvx - 1, &octx->n_hvx_div), + .total_jobs = njobs, + .job_start = job_start, + .k_chunks = k_chunks, + .col_block = col_block, + .a_full = kparams->a_full, + .a_f16 = a_f16, + .b_f16 = b_f16, + .x_f16 = x_f16, + }; + + work_queue_func_t worker = batched ? solve_tri_batch_thread : solve_tri_chunk_thread; + work_queue_run(octx->ctx->hvx_queue, worker, &sctx, n_hvx); + return HTP_STATUS_OK; } diff --git a/ggml/src/ggml-hexagon/htp/solve-tri-ops.h b/ggml/src/ggml-hexagon/htp/solve-tri-ops.h index 6a46cfdc414d..965545ad6359 100644 --- a/ggml/src/ggml-hexagon/htp/solve-tri-ops.h +++ b/ggml/src/ggml-hexagon/htp/solve-tri-ops.h @@ -1,9 +1,38 @@ #ifndef HTP_SOLVE_TRI_OPS_H #define HTP_SOLVE_TRI_OPS_H +#include "hex-common.h" #include "hex-fastdiv.h" +#include "htp-vtcm.h" +#include #include +struct htp_solve_tri_vtcm_layout { + size_t a_row_aligned; + size_t a_bytes_per_hvx; + size_t bx_bytes_per_hvx; + size_t off_a; + size_t off_bx; + size_t total_bytes; +}; + +static inline void htp_solve_tri_vtcm_layout_build( + struct htp_solve_tri_vtcm_layout * L, + uint32_t n, + uint32_t a_full, + uint32_t n_hvx +) { + size_t off = 0; + + L->a_row_aligned = hex_round_up((size_t) n * sizeof(float), 128); + L->a_bytes_per_hvx = a_full ? ((size_t) n * L->a_row_aligned) : L->a_row_aligned; + L->bx_bytes_per_hvx = (size_t) n * 128; + + VTCM_LAYOUT_ALLOC(off, off_a, (size_t) n_hvx * L->a_bytes_per_hvx); + VTCM_LAYOUT_ALLOC(off, off_bx, (size_t) n_hvx * L->bx_bytes_per_hvx); + L->total_bytes = off; +} + struct htp_solve_tri_kernel_params { uint32_t n_hvx; uint32_t total_batches; @@ -11,7 +40,8 @@ struct htp_solve_tri_kernel_params { uint32_t k_chunks; uint32_t col_block; uint32_t batched; - uint32_t batches_per_chunk; + uint32_t a_full; + uint32_t vtcm_size; struct fastdiv_values div_ne02; struct fastdiv_values div_k_chunks; diff --git a/ggml/src/ggml-hexagon/htp/ssm-conv.c b/ggml/src/ggml-hexagon/htp/ssm-conv.c index d75304fef11d..a7a511ba7f0a 100644 --- a/ggml/src/ggml-hexagon/htp/ssm-conv.c +++ b/ggml/src/ggml-hexagon/htp/ssm-conv.c @@ -1,7 +1,3 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include #include @@ -21,66 +17,157 @@ #include "hvx-utils.h" #include "ssm-conv.h" +typedef void (*htp_ssm_conv_decode_dot_fn_t)( + const void * restrict raw_in, + float * restrict src0_T, + const float * restrict src1_raw, + const float * restrict src1_T, + float * restrict out, + uint32_t tile_n, + uint32_t d_inner_stride, + uint32_t tile_off, + uint32_t d_conv); + +typedef void (*htp_ssm_conv_transpose_block_fn_t)( + const void * restrict raw_block, + float * restrict T, + uint32_t raw_stride_bytes, + uint32_t ncs, + uint32_t cb_n); + +typedef void (*htp_ssm_conv_prefill_dot_fn_t)( + const float * restrict src0_T, + const float * restrict wp, + float * restrict op, + uint32_t n_t, + uint32_t d_conv, + uint32_t d_inner_stride, + uint32_t dst_tile_stride); + +typedef size_t (*htp_ssm_conv_epilogue_fn_t)( + float * restrict out, + uint32_t n_t, + uint32_t tile_n); + +typedef void (*htp_ssm_conv_token_step_fn_t)( + float * restrict hist, + const void * restrict x_tile, + const float * restrict wp, + void * restrict dst_tile, + float * restrict strip_f32, + uint32_t cur_c, + uint32_t cur_t, + uint32_t d_conv, + uint32_t c_stride, + uint32_t w_stride, + size_t x_row_stride, + size_t d_row_stride); + +typedef void (*htp_ssm_conv_state_unpack_fn_t)( + float * restrict state_raw, + float * restrict hist, + uint32_t cur_c, + uint32_t c_stride, + uint32_t s_taps); + +typedef void (*htp_ssm_conv_state_pack_fn_t)( + float * restrict hist, + float * restrict state_raw, + uint32_t cur_c, + uint32_t c_stride, + uint32_t s_taps); + struct htp_ssm_conv_context { struct htp_ops_context * octx; const struct htp_ssm_conv_kernel_params * kparams; + struct htp_ssm_conv_vtcm_layout layout; + uint8_t * vtcm_base; uint32_t nrows_per_hvx; uint32_t d_inner_tile; uint32_t row_start; uint32_t nrows; + bool raw_dot; + htp_ssm_conv_decode_dot_fn_t decode_dot_fn; + htp_ssm_conv_transpose_block_fn_t transpose_block_fn; + htp_ssm_conv_prefill_dot_fn_t prefill_dot_fn; + htp_ssm_conv_epilogue_fn_t epilogue_fn; + htp_ssm_conv_token_step_fn_t token_step_fn; + htp_ssm_conv_state_unpack_fn_t state_unpack_fn; + htp_ssm_conv_state_pack_fn_t state_pack_fn; }; -// In-register 32x32 fp32 transpose using std 5-stage HVX vshuff butterfly. -static inline void hvx_transpose_32x32_f32(HVX_Vector m[32]) { - HVX_Vector tmp[32]; - - // Stage 0 (R = -4): pair (2i, 2i+1) for i = 0..15. m -> tmp. - for (int i = 0; i < 16; ++i) { - HVX_VectorPair p = Q6_W_vshuff_VVR(m[2*i + 1], m[2*i], -4); - tmp[2*i + 0] = Q6_V_lo_W(p); - tmp[2*i + 1] = Q6_V_hi_W(p); +static __attribute__((noinline)) void hvx_ssm_conv_widen_f16_vtcm(const __fp16 * restrict src, + float * restrict dst, + uint32_t n_elems) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + HVX_Vector * restrict vdst = (HVX_Vector *) dst; + const uint32_t n_v = (n_elems + VLEN_FP16 - 1) / VLEN_FP16; + for (uint32_t i = 0; i < n_v; ++i) { + HVX_VectorPair p = hvx_vec_f16_to_f32(vsrc[i]); + vdst[2 * i + 0] = Q6_V_lo_W(p); + vdst[2 * i + 1] = Q6_V_hi_W(p); } +} - // Stage 1 (R = -8): per block of 4, pair (b+0, b+2) and (b+1, b+3). tmp -> m. - for (int b = 0; b < 32; b += 4) { - HVX_VectorPair p0 = Q6_W_vshuff_VVR(tmp[b + 2], tmp[b + 0], -8); - HVX_VectorPair p1 = Q6_W_vshuff_VVR(tmp[b + 3], tmp[b + 1], -8); - m[b + 0] = Q6_V_lo_W(p0); m[b + 1] = Q6_V_hi_W(p0); - m[b + 2] = Q6_V_lo_W(p1); m[b + 3] = Q6_V_hi_W(p1); - } +static inline HVX_Vector hvx_ssm_conv_clamp_f16_f32(HVX_Vector x) { + const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f); + const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f); + return Q6_Vsf_vmin_VsfVsf(Q6_Vsf_vmax_VsfVsf(x, f16_min), f16_max); +} - // Stage 2 (R = -16): per block of 8, pair (b+i, b+i+4) for i = 0..3. m -> tmp. - for (int b = 0; b < 32; b += 8) { - for (int i = 0; i < 4; ++i) { - HVX_VectorPair p = Q6_W_vshuff_VVR(m[b + i + 4], m[b + i], -16); - tmp[b + 2*i + 0] = Q6_V_lo_W(p); - tmp[b + 2*i + 1] = Q6_V_hi_W(p); - } - } +static inline HVX_Vector hvx_ssm_conv_silu_pack_f16(HVX_Vector u0, HVX_Vector u1) { + HVX_Vector x = hvx_vec_f32_to_f16(hvx_ssm_conv_clamp_f16_f32(u0), + hvx_ssm_conv_clamp_f16_f32(u1)); + return hvx_vec_mul_f16_f16(x, hvx_vec_fast_sigmoid_f16(x)); +} - // Stage 3 (R = -32): per block of 16, pair (b+i, b+i+8) for i = 0..7. tmp -> m. - for (int b = 0; b < 32; b += 16) { - for (int i = 0; i < 8; ++i) { - HVX_VectorPair p = Q6_W_vshuff_VVR(tmp[b + i + 8], tmp[b + i], -32); - m[b + 2*i + 0] = Q6_V_lo_W(p); - m[b + 2*i + 1] = Q6_V_hi_W(p); - } - } +static __attribute__((noinline)) void hvx_ssm_conv_pack_f16_rows_vtcm(float * restrict buf, + uint32_t n_rows, + uint32_t n_elems_per_row) { + const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f); + const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f); + const HVX_Vector zero = Q6_V_vzero(); + const uint32_t n_v32 = (n_elems_per_row + VLEN_FP32 - 1) / VLEN_FP32; + const uint32_t n_v16 = (n_v32 + 1) / 2; + HVX_Vector * restrict vbuf = (HVX_Vector *) buf; - // Stage 4 (R = -64): pair (i, i+16) for i = 0..15. m -> tmp -> m. - for (int i = 0; i < 16; ++i) { - HVX_VectorPair p = Q6_W_vshuff_VVR(m[i + 16], m[i], -64); - tmp[2 * i + 0] = Q6_V_lo_W(p); - tmp[2 * i + 1] = Q6_V_hi_W(p); + for (uint32_t r = 0; r < n_rows; ++r) { + HVX_Vector * sr = vbuf + (size_t) r * n_v32; + HVX_Vector * dr = vbuf + (size_t) r * n_v16; + for (uint32_t i = 0; i < n_v32; i += 2) { + HVX_Vector v0 = sr[i]; + HVX_Vector v1 = (i + 1 < n_v32) ? sr[i + 1] : zero; + v0 = Q6_Vsf_vmax_VsfVsf(Q6_Vsf_vmin_VsfVsf(v0, f16_max), f16_min); + v1 = Q6_Vsf_vmax_VsfVsf(Q6_Vsf_vmin_VsfVsf(v1, f16_max), f16_min); + dr[i / 2] = hvx_vec_f32_to_f16(v0, v1); + } } +} - for (int i = 0; i < 32; ++i) { - m[i] = tmp[i]; +static __attribute__((noinline)) void hvx_ssm_conv_silu_pack_f16_rows_vtcm(float * restrict buf, + uint32_t n_rows, + uint32_t n_elems_per_row) { + const HVX_Vector zero = Q6_V_vzero(); + const uint32_t n_v32 = (n_elems_per_row + VLEN_FP32 - 1) / VLEN_FP32; + const uint32_t n_v16 = (n_v32 + 1) / 2; + HVX_Vector * restrict vbuf = (HVX_Vector *) buf; + + for (uint32_t r = 0; r < n_rows; ++r) { + HVX_Vector * sr = vbuf + (size_t) r * n_v32; + HVX_Vector * dr = vbuf + (size_t) r * n_v16; + for (uint32_t i = 0; i < n_v32; i += 2) { + HVX_Vector v0 = sr[i]; + HVX_Vector v1 = (i + 1 < n_v32) ? sr[i + 1] : zero; + dr[i / 2] = hvx_ssm_conv_silu_pack_f16(v0, v1); + } } } // HVX deinterleave for d_conv == 4: channel-major raw VTCM -> tap-major T VTCM -static inline void hvx_ssm_conv_unpack_to_T_4(const float * raw, float * T, uint32_t d_inner_per_hvx, uint32_t d_inner_stride) { +static __attribute__((noinline)) void hvx_ssm_conv_unpack_to_T_4(const float * restrict raw, + float * restrict T, + uint32_t d_inner_per_hvx, + uint32_t d_inner_stride) { for (uint32_t cb = 0; cb < d_inner_per_hvx; cb += VLEN_FP32) { HVX_Vector v0 = *(const HVX_Vector *)(raw + (cb + 0) * 4); HVX_Vector v1 = *(const HVX_Vector *)(raw + (cb + 8) * 4); @@ -100,31 +187,27 @@ static inline void hvx_ssm_conv_unpack_to_T_4(const float * raw, float * T, uint } } -// HVX transpose for general d_conv <= 32: channel-major raw VTCM -> tap-major T VTCM -static inline void hvx_ssm_conv_unpack_to_T_gen(const float * raw, float * T, uint32_t d_inner_per_hvx, uint32_t d_inner_stride, uint32_t d_conv) { - uint32_t __attribute__((aligned(VLEN))) mask_buf[VLEN_FP32] = { 0 }; - for (uint32_t j = 0; j < d_conv; ++j) { - mask_buf[j] = 0xFFFFFFFF; - } - const HVX_Vector mask = *(const HVX_Vector *) mask_buf; +// HVX gather transpose for general d_conv <= 32: channel-major raw VTCM -> tap-major T VTCM +static __attribute__((noinline)) void hvx_ssm_conv_unpack_to_T_gen(const float * restrict raw, + float * restrict T, + uint32_t d_inner_per_hvx, + uint32_t d_inner_stride, + uint32_t d_conv) { + const uint32_t raw_stride_bytes = d_conv * sizeof(float); + const HVX_Vector vv = hvx_vec_gather_offsets_w(raw_stride_bytes); for (uint32_t cb = 0; cb < d_inner_per_hvx; cb += VLEN_FP32) { const uint32_t cb_n = MIN(VLEN_FP32, d_inner_per_hvx - cb); - HVX_Vector sub[32]; - for (uint32_t r = 0; r < cb_n; ++r) { - const float * ch_ptr = raw + (cb + r) * d_conv; - sub[r] = Q6_V_vand_VV(*(const HVX_UVector *) ch_ptr, mask); - } - for (uint32_t r = cb_n; r < 32; ++r) { - sub[r] = hvx_vec_splat_f32(0.0f); - } - - hvx_transpose_32x32_f32(sub); + const size_t base = (size_t) (raw + (size_t) cb * d_conv); + const uint32_t mu = cb_n * raw_stride_bytes - 1; for (uint32_t j = 0; j < d_conv; ++j) { - *(HVX_Vector *)(T + j * d_inner_stride + cb) = sub[j]; + Q6_vgather_ARMVw((HVX_Vector *) (T + (size_t) j * d_inner_stride + cb), + base + j * sizeof(float), mu, vv); } } + + hvx_gather_sync(T); } static inline void hvx_ssm_conv_unpack_to_T(const float * raw, float * T, uint32_t d_inner_per_hvx, uint32_t d_inner_stride, uint32_t d_conv) { @@ -135,6 +218,40 @@ static inline void hvx_ssm_conv_unpack_to_T(const float * raw, float * T, uint32 } } +// HVX gather transpose + F16->F32 widen for decode when d_conv != 4 +static __attribute__((noinline)) void hvx_ssm_conv_unpack_to_T_f16(const __fp16 * restrict raw, + float * restrict T, + uint32_t d_inner_per_hvx, + uint32_t d_inner_stride, + uint32_t d_conv) { + const uint32_t raw_stride_bytes = hex_round_up(d_conv, 2) * sizeof(__fp16); + const HVX_Vector vv = hvx_vec_gather_offsets_w(raw_stride_bytes); + + for (uint32_t cb = 0; cb < d_inner_per_hvx; cb += VLEN_FP32) { + const uint32_t cb_n = MIN(VLEN_FP32, d_inner_per_hvx - cb); + const size_t base = (size_t) ((const uint8_t *) raw + (size_t) cb * raw_stride_bytes); + const uint32_t mu = cb_n * raw_stride_bytes - 1; + + for (uint32_t j = 0; j < d_conv; j += 2) { + Q6_vgather_ARMVw((HVX_Vector *) (T + (size_t) j * d_inner_stride + cb), + base + j * sizeof(__fp16), mu, vv); + } + } + + hvx_gather_sync(T); + + for (uint32_t cb = 0; cb < d_inner_per_hvx; cb += VLEN_FP32) { + for (uint32_t j = 0; j < d_conv; j += 2) { + HVX_Vector v_pair = *(const HVX_Vector *) (T + (size_t) j * d_inner_stride + cb); + HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(v_pair); + *(HVX_Vector *) (T + (size_t) j * d_inner_stride + cb) = Q6_V_lo_W(p); + if (j + 1 < d_conv) { + *(HVX_Vector *) (T + (size_t) (j + 1) * d_inner_stride + cb) = Q6_V_hi_W(p); + } + } + } +} + static __attribute__((noinline)) void hvx_ssm_conv_silu_vtcm(float * restrict buf, uint32_t n_vecs) { HVX_Vector * restrict vbuf = (HVX_Vector *) buf; for (uint32_t i = 0; i < n_vecs; ++i) { @@ -145,7 +262,10 @@ static __attribute__((noinline)) void hvx_ssm_conv_silu_vtcm(float * restrict bu // Decode dot product specialization for d_conv == 4: multiply in the raw channel-major layout, // then deinterleave the products so each vector holds one tap of 32 channels, and sum. // Keeps both operands in DMA layout - no transpose, no scratch. -static inline void hvx_ssm_conv_decode_4(const float * x, const float * w, float * out, uint32_t n_ch) { +static __attribute__((noinline)) void hvx_ssm_conv_decode_4(const float * restrict x, + const float * restrict w, + float * restrict out, + uint32_t n_ch) { for (uint32_t cb = 0; cb < n_ch; cb += VLEN_FP32) { const float * xp = x + cb * 4; const float * wp = w + cb * 4; @@ -168,23 +288,730 @@ static inline void hvx_ssm_conv_decode_4(const float * x, const float * w, float } } +static __attribute__((noinline)) void hvx_ssm_conv_decode_4_f16(const __fp16 * restrict x, + const float * restrict w, + float * restrict out, + uint32_t n_ch) { + for (uint32_t cb = 0; cb < n_ch; cb += VLEN_FP32) { + const __fp16 * xp = x + cb * 4; + const float * wp = w + cb * 4; + + HVX_VectorPair x01 = hvx_vec_f16_to_f32(*(const HVX_Vector *)(xp + 0)); + HVX_VectorPair x23 = hvx_vec_f16_to_f32(*(const HVX_Vector *)(xp + 64)); + + HVX_Vector p0 = Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(x01), *(const HVX_Vector *)(wp + 0)); + HVX_Vector p1 = Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(x01), *(const HVX_Vector *)(wp + 32)); + HVX_Vector p2 = Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(x23), *(const HVX_Vector *)(wp + 64)); + HVX_Vector p3 = Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(x23), *(const HVX_Vector *)(wp + 96)); + + HVX_VectorPair p01 = Q6_W_vdeal_VVR(p1, p0, -4); + HVX_VectorPair p23 = Q6_W_vdeal_VVR(p3, p2, -4); + + HVX_VectorPair q02 = Q6_W_vdeal_VVR(Q6_V_lo_W(p23), Q6_V_lo_W(p01), -4); + HVX_VectorPair q13 = Q6_W_vdeal_VVR(Q6_V_hi_W(p23), Q6_V_hi_W(p01), -4); + + HVX_Vector a = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_V_lo_W(q02), Q6_V_lo_W(q13)); + HVX_Vector b = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_V_hi_W(q02), Q6_V_hi_W(q13)); + + *(HVX_Vector *)(out + cb) = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(a, b)); + } +} + +static __attribute__((noinline)) void hvx_ssm_conv_decode_dot_gen(const float * restrict src0_T, + const float * restrict src1_T, + float * restrict out, + uint32_t tile_n, + uint32_t tile_stride, + uint32_t d_inner_stride, + uint32_t tile_off, + uint32_t d_conv) { + for (uint32_t cb = 0; cb < tile_n; cb += VLEN_FP32) { + HVX_Vector acc = hvx_vec_splat_f32(0.0f); + for (uint32_t j = 0; j < d_conv; ++j) { + HVX_Vector x = *(const HVX_Vector *)(src0_T + j * tile_stride + cb); + HVX_Vector w = *(const HVX_Vector *)(src1_T + j * d_inner_stride + tile_off + cb); + acc = Q6_Vqf32_vadd_Vqf32Vqf32(acc, Q6_Vqf32_vmpy_VsfVsf(x, w)); + } + *(HVX_Vector *)(out + cb) = Q6_Vsf_equals_Vqf32(acc); + } +} + +static size_t ssm_conv_epilogue_f32(float * restrict out, uint32_t n_t, uint32_t tile_n) { + (void) out; + (void) n_t; + return (size_t) hex_round_up(tile_n, VLEN_FP32) * sizeof(float); +} + +static size_t ssm_conv_epilogue_silu_f32(float * restrict out, uint32_t n_t, uint32_t tile_n) { + const uint32_t dst_tile_stride = hex_round_up(tile_n, VLEN_FP32); + hvx_ssm_conv_silu_vtcm(out, n_t * (dst_tile_stride / VLEN_FP32)); + return (size_t) dst_tile_stride * sizeof(float); +} + +static size_t ssm_conv_epilogue_f16(float * restrict out, uint32_t n_t, uint32_t tile_n) { + hvx_ssm_conv_pack_f16_rows_vtcm(out, n_t, tile_n); + return (size_t) hex_round_up(tile_n, VLEN_FP16) * sizeof(__fp16); +} + +static size_t ssm_conv_epilogue_silu_f16(float * restrict out, uint32_t n_t, uint32_t tile_n) { + hvx_ssm_conv_silu_pack_f16_rows_vtcm(out, n_t, tile_n); + return (size_t) hex_round_up(tile_n, VLEN_FP16) * sizeof(__fp16); +} + +static void ssm_conv_decode_dot_4_f32(const void * restrict raw_in, + float * restrict src0_T, + const float * restrict src1_raw, + const float * restrict src1_T, + float * restrict out, + uint32_t tile_n, + uint32_t d_inner_stride, + uint32_t tile_off, + uint32_t d_conv) { + (void) src0_T; + (void) src1_T; + (void) d_inner_stride; + (void) d_conv; + hvx_ssm_conv_decode_4((const float *) raw_in, src1_raw + tile_off * 4, out, tile_n); +} + +static void ssm_conv_decode_dot_4_f16(const void * restrict raw_in, + float * restrict src0_T, + const float * restrict src1_raw, + const float * restrict src1_T, + float * restrict out, + uint32_t tile_n, + uint32_t d_inner_stride, + uint32_t tile_off, + uint32_t d_conv) { + (void) src0_T; + (void) src1_T; + (void) d_inner_stride; + (void) d_conv; + hvx_ssm_conv_decode_4_f16((const __fp16 *) raw_in, src1_raw + tile_off * 4, out, tile_n); +} + +static void ssm_conv_decode_dot_gen_f32(const void * restrict raw_in, + float * restrict src0_T, + const float * restrict src1_raw, + const float * restrict src1_T, + float * restrict out, + uint32_t tile_n, + uint32_t d_inner_stride, + uint32_t tile_off, + uint32_t d_conv) { + (void) src1_raw; + const uint32_t tile_stride = hex_round_up(tile_n, VLEN_FP32); + hvx_ssm_conv_unpack_to_T((const float *) raw_in, src0_T, tile_n, tile_stride, d_conv); + hvx_ssm_conv_decode_dot_gen(src0_T, src1_T, out, tile_n, tile_stride, d_inner_stride, tile_off, d_conv); +} + +static void ssm_conv_decode_dot_gen_f16(const void * restrict raw_in, + float * restrict src0_T, + const float * restrict src1_raw, + const float * restrict src1_T, + float * restrict out, + uint32_t tile_n, + uint32_t d_inner_stride, + uint32_t tile_off, + uint32_t d_conv) { + (void) src1_raw; + const uint32_t tile_stride = hex_round_up(tile_n, VLEN_FP32); + hvx_ssm_conv_unpack_to_T_f16((const __fp16 *) raw_in, src0_T, tile_n, tile_stride, d_conv); + hvx_ssm_conv_decode_dot_gen(src0_T, src1_T, out, tile_n, tile_stride, d_inner_stride, tile_off, d_conv); +} + // Transpose src0 for prefill: one 32-channel block {32, ncs} (VTCM) -> T {ncs, 32} (VTCM). // One VTCM gather per output row: lane r picks channel cb+r, the region bound drops // the lanes past the channel tail. -static inline void hvx_ssm_conv_transpose_block(const float * raw_block, - float * T, - uint32_t raw_stride_bytes, - uint32_t ncs, - uint32_t cb_n, - HVX_Vector vv) { - const size_t base = (size_t) raw_block; - const uint32_t mu = cb_n * raw_stride_bytes - 1; +static __attribute__((noinline)) void hvx_ssm_conv_transpose_block(const void * restrict raw_block, + float * restrict T, + uint32_t raw_stride_bytes, + uint32_t ncs, + uint32_t cb_n) { + const size_t base = (size_t) raw_block; + const uint32_t mu = cb_n * raw_stride_bytes - 1; + const HVX_Vector vv = hvx_vec_gather_offsets_w(raw_stride_bytes); for (uint32_t t = 0; t < ncs; ++t) { Q6_vgather_ARMVw((HVX_Vector *) (T + (size_t) t * VLEN_FP32), base + t * sizeof(float), mu, vv); } + + hvx_gather_sync(T); +} + +// Transpose + widen F16 src0 for prefill: each 32-bit word gather fetches 2 consecutive F16 time steps +// across 32 channels into even rows of T, then hvx_vec_f16_to_f32_shuff widens them into rows t and t+1. +static __attribute__((noinline)) void hvx_ssm_conv_transpose_block_f16(const void * restrict raw_block, + float * restrict T, + uint32_t raw_stride_bytes, + uint32_t ncs, + uint32_t cb_n) { + const size_t base = (size_t) raw_block; + const uint32_t mu = cb_n * raw_stride_bytes - 1; + const HVX_Vector vv = hvx_vec_gather_offsets_w(raw_stride_bytes); + HVX_Vector * T_vec = (HVX_Vector *) T; + + for (uint32_t t = 0; t < ncs; t += 2) { + Q6_vgather_ARMVw(&T_vec[t], base + t * sizeof(__fp16), mu, vv); + } + + hvx_gather_sync(T); + + for (uint32_t t = 0; t < ncs; t += 2) { + HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(T_vec[t]); + T_vec[t] = Q6_V_lo_W(p); + if (t + 1 < ncs) { + T_vec[t + 1] = Q6_V_hi_W(p); + } + } +} + +static __attribute__((noinline)) void hvx_ssm_conv_prefill_dot_block_4(const float * restrict src0_T, + const float * restrict wp, + float * restrict op, + uint32_t n_t, + uint32_t d_conv, + uint32_t d_inner_stride, + uint32_t dst_tile_stride) { + (void) d_conv; + const uint32_t C_TILE = VLEN_FP32; + const HVX_Vector w0 = *(const HVX_Vector *) (wp); + const HVX_Vector w1 = *(const HVX_Vector *) (wp + d_inner_stride); + const HVX_Vector w2 = *(const HVX_Vector *) (wp + 2 * d_inner_stride); + const HVX_Vector w3 = *(const HVX_Vector *) (wp + 3 * d_inner_stride); + + HVX_Vector x0 = *(const HVX_Vector *) (src0_T); + HVX_Vector x1 = *(const HVX_Vector *) (src0_T + C_TILE); + HVX_Vector x2 = *(const HVX_Vector *) (src0_T + 2 * C_TILE); + + for (uint32_t t = 0; t < n_t; ++t) { + const HVX_Vector x3 = *(const HVX_Vector *) (src0_T + (t + 3) * C_TILE); + + HVX_Vector a = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x0, w0), + Q6_Vqf32_vmpy_VsfVsf(x1, w1)); + HVX_Vector b = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x2, w2), + Q6_Vqf32_vmpy_VsfVsf(x3, w3)); + + *(HVX_Vector *) (op + t * dst_tile_stride) = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(a, b)); + + x0 = x1; + x1 = x2; + x2 = x3; + } +} + +static __attribute__((noinline)) void hvx_ssm_conv_prefill_dot_block_gen(const float * restrict src0_T, + const float * restrict wp, + float * restrict op, + uint32_t n_t, + uint32_t d_conv, + uint32_t d_inner_stride, + uint32_t dst_tile_stride) { + const uint32_t C_TILE = VLEN_FP32; + for (uint32_t t = 0; t < n_t; ++t) { + HVX_Vector acc = hvx_vec_splat_f32(0.0f); + for (uint32_t j = 0; j < d_conv; ++j) { + HVX_Vector x = *(const HVX_Vector *) (src0_T + (t + j) * C_TILE); + HVX_Vector w = *(const HVX_Vector *) (wp + j * d_inner_stride); + acc = Q6_Vqf32_vadd_Vqf32Vqf32(acc, Q6_Vqf32_vmpy_VsfVsf(x, w)); + } + *(HVX_Vector *) (op + t * dst_tile_stride) = Q6_Vsf_equals_Vqf32(acc); + } +} + +// HVX scatter transpose for tap-major hist [s_taps, c_stride] -> channel-major raw [cur_c, s_taps] +static __attribute__((noinline)) void hvx_ssm_conv_pack_from_T_gen(const float * restrict hist, + float * restrict raw, + uint32_t cur_c, + uint32_t c_stride, + uint32_t s_taps) { + const uint32_t raw_stride_bytes = s_taps * sizeof(float); + const HVX_Vector vv = hvx_vec_gather_offsets_w(raw_stride_bytes); + + for (uint32_t cb = 0; cb < cur_c; cb += VLEN_FP32) { + const uint32_t cb_n = MIN(VLEN_FP32, cur_c - cb); + const size_t base = (size_t) (raw + (size_t) cb * s_taps); + const uint32_t mu = cb_n * raw_stride_bytes - 1; + + for (uint32_t j = 0; j < s_taps; ++j) { + const HVX_Vector vj = *(const HVX_Vector *) (hist + (size_t) j * c_stride + cb); + Q6_vscatter_RMVwV(base + j * sizeof(float), mu, vv, vj); + } + } + + hvx_gather_sync(raw); +} + +static __attribute__((noinline)) void hvx_ssm_conv_pack_f16_flat_vtcm(const float * restrict src, + __fp16 * restrict dst, + uint32_t n_elems) { + const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f); + const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f); + const HVX_Vector zero = Q6_V_vzero(); + const uint32_t n_v32 = (n_elems + VLEN_FP32 - 1) / VLEN_FP32; + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + HVX_Vector * restrict vdst = (HVX_Vector *) dst; + + for (uint32_t i = 0; i < n_v32; i += 2) { + HVX_Vector v0 = vsrc[i]; + HVX_Vector v1 = (i + 1 < n_v32) ? vsrc[i + 1] : zero; + v0 = Q6_Vsf_vmax_VsfVsf(Q6_Vsf_vmin_VsfVsf(v0, f16_max), f16_min); + v1 = Q6_Vsf_vmax_VsfVsf(Q6_Vsf_vmin_VsfVsf(v1, f16_max), f16_min); + vdst[i / 2] = hvx_vec_f32_to_f16(v0, v1); + } +} + +static void ssm_conv_state_unpack_f32_nat(float * restrict state_raw, + float * restrict hist, + uint32_t cur_c, + uint32_t c_stride, + uint32_t s_taps) { + hvx_ssm_conv_unpack_to_T_gen(state_raw, hist, cur_c, c_stride, s_taps); +} + +static void ssm_conv_state_unpack_f16_nat(float * restrict state_raw, + float * restrict hist, + uint32_t cur_c, + uint32_t c_stride, + uint32_t s_taps) { + hvx_ssm_conv_widen_f16_vtcm((const __fp16 *) hist, state_raw, cur_c * s_taps); + hvx_ssm_conv_unpack_to_T_gen(state_raw, hist, cur_c, c_stride, s_taps); +} + +static void ssm_conv_state_pack_f32_nat(float * restrict hist, + float * restrict state_raw, + uint32_t cur_c, + uint32_t c_stride, + uint32_t s_taps) { + hvx_ssm_conv_pack_from_T_gen(hist, state_raw, cur_c, c_stride, s_taps); +} + +static void ssm_conv_state_pack_f16_nat(float * restrict hist, + float * restrict state_raw, + uint32_t cur_c, + uint32_t c_stride, + uint32_t s_taps) { + hvx_ssm_conv_pack_from_T_gen(hist, state_raw, cur_c, c_stride, s_taps); + hvx_ssm_conv_pack_f16_flat_vtcm(state_raw, (__fp16 *) hist, cur_c * s_taps); +} + +static __attribute__((noinline)) void hvx_ssm_conv_pack_f16_strip_1d(const float * restrict strip_f32, + uint8_t * restrict dp, + uint32_t cur_t, + size_t d_row_stride, + bool has_hi) { + const HVX_Vector * restrict sp = (const HVX_Vector *) strip_f32; + const uint32_t hi_off = has_hi ? 1 : 0; + _Pragma("clang loop unroll(disable)") + for (uint32_t t = 0; t < cur_t; ++t) { + HVX_Vector u0 = sp[0]; + HVX_Vector u1 = sp[hi_off]; + *(HVX_Vector *) dp = hvx_vec_f32_to_f16(hvx_ssm_conv_clamp_f16_f32(u0), + hvx_ssm_conv_clamp_f16_f32(u1)); + sp += 2; + dp += d_row_stride; + } } +static __attribute__((noinline)) void hvx_ssm_conv_silu_pack_f16_strip_1d(const float * restrict strip_f32, + uint8_t * restrict dp, + uint32_t cur_t, + size_t d_row_stride, + bool has_hi) { + const HVX_Vector * restrict sp = (const HVX_Vector *) strip_f32; + const uint32_t hi_off = has_hi ? 1 : 0; + +#if __HVX_ARCH__ >= 81 + _Pragma("clang loop unroll(disable)") +#else + _Pragma("clang loop unroll(disable) pipeline(disable)") +#endif + for (uint32_t t = 0; t < cur_t; ++t) { + *(HVX_Vector *) dp = hvx_ssm_conv_silu_pack_f16(sp[0], sp[hi_off]); + sp += 2; + dp += d_row_stride; + } +} + +#define DEFINE_SSM_CONV_TOKEN_4_DOT_STRIP(NAME, X_F16) \ + static __attribute__((noinline)) void NAME(float * restrict hist, \ + const void * restrict x_tile, \ + const float * restrict wp, \ + void * restrict out_ptr, \ + uint32_t cb, \ + uint32_t cur_t, \ + uint32_t c_stride, \ + uint32_t w_stride, \ + size_t x_row_stride, \ + size_t out_row_stride) { \ + const HVX_Vector w0_0 = *(const HVX_Vector *) (wp + 0 * w_stride + cb + 0); \ + const HVX_Vector w0_1 = *(const HVX_Vector *) (wp + 0 * w_stride + cb + 32); \ + const HVX_Vector w1_0 = *(const HVX_Vector *) (wp + 1 * w_stride + cb + 0); \ + const HVX_Vector w1_1 = *(const HVX_Vector *) (wp + 1 * w_stride + cb + 32); \ + const HVX_Vector w2_0 = *(const HVX_Vector *) (wp + 2 * w_stride + cb + 0); \ + const HVX_Vector w2_1 = *(const HVX_Vector *) (wp + 2 * w_stride + cb + 32); \ + const HVX_Vector w3_0 = *(const HVX_Vector *) (wp + 3 * w_stride + cb + 0); \ + const HVX_Vector w3_1 = *(const HVX_Vector *) (wp + 3 * w_stride + cb + 32); \ + \ + HVX_Vector xm3_0 = *(const HVX_Vector *) (hist + 0 * c_stride + cb + 0); \ + HVX_Vector xm3_1 = *(const HVX_Vector *) (hist + 0 * c_stride + cb + 32); \ + HVX_Vector xm2_0 = *(const HVX_Vector *) (hist + 1 * c_stride + cb + 0); \ + HVX_Vector xm2_1 = *(const HVX_Vector *) (hist + 1 * c_stride + cb + 32); \ + HVX_Vector xm1_0 = *(const HVX_Vector *) (hist + 2 * c_stride + cb + 0); \ + HVX_Vector xm1_1 = *(const HVX_Vector *) (hist + 2 * c_stride + cb + 32); \ + \ + const uint8_t * restrict xp = (const uint8_t *) x_tile + cb * (X_F16 ? 2 : 4); \ + uint8_t * restrict dp = (uint8_t *) out_ptr; \ + \ + _Pragma("clang loop unroll(disable)") \ + for (uint32_t t = 0; t < cur_t; ++t) { \ + HVX_Vector x0_0; \ + HVX_Vector x0_1; \ + if (X_F16) { \ + HVX_VectorPair x0_p = hvx_vec_f16_to_f32(*(const HVX_Vector *) xp); \ + x0_0 = Q6_V_lo_W(x0_p); \ + x0_1 = Q6_V_hi_W(x0_p); \ + } else { \ + x0_0 = *((const HVX_Vector *) xp + 0); \ + x0_1 = *((const HVX_Vector *) xp + 1); \ + } \ + \ + HVX_Vector a0 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(xm3_0, w0_0), \ + Q6_Vqf32_vmpy_VsfVsf(xm2_0, w1_0)); \ + HVX_Vector b0 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(xm1_0, w2_0), \ + Q6_Vqf32_vmpy_VsfVsf(x0_0, w3_0)); \ + HVX_Vector a1 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(xm3_1, w0_1), \ + Q6_Vqf32_vmpy_VsfVsf(xm2_1, w1_1)); \ + HVX_Vector b1 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(xm1_1, w2_1), \ + Q6_Vqf32_vmpy_VsfVsf(x0_1, w3_1)); \ + *((HVX_Vector *) dp + 0) = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(a0, b0)); \ + *((HVX_Vector *) dp + 1) = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(a1, b1)); \ + \ + xm3_0 = xm2_0; \ + xm3_1 = xm2_1; \ + xm2_0 = xm1_0; \ + xm2_1 = xm1_1; \ + xm1_0 = x0_0; \ + xm1_1 = x0_1; \ + \ + xp += x_row_stride; \ + dp += out_row_stride; \ + } \ + \ + *(HVX_Vector *) (hist + 0 * c_stride + cb + 0) = xm3_0; \ + *(HVX_Vector *) (hist + 0 * c_stride + cb + 32) = xm3_1; \ + *(HVX_Vector *) (hist + 1 * c_stride + cb + 0) = xm2_0; \ + *(HVX_Vector *) (hist + 1 * c_stride + cb + 32) = xm2_1; \ + *(HVX_Vector *) (hist + 2 * c_stride + cb + 0) = xm1_0; \ + *(HVX_Vector *) (hist + 2 * c_stride + cb + 32) = xm1_1; \ + } + +DEFINE_SSM_CONV_TOKEN_4_DOT_STRIP(hvx_ssm_conv_token_4_dot_f32_strip, false) +DEFINE_SSM_CONV_TOKEN_4_DOT_STRIP(hvx_ssm_conv_token_4_dot_f16_strip, true) + +#undef DEFINE_SSM_CONV_TOKEN_4_DOT_STRIP + +#define DEFINE_SSM_CONV_TOKEN_4_DOT_SILU_F32(NAME, X_F16) \ + static __attribute__((noinline)) void NAME(float * restrict hist, \ + const void * restrict x_tile, \ + const float * restrict wp, \ + void * restrict dst_tile, \ + uint32_t cur_c, \ + uint32_t cur_t, \ + uint32_t c_stride, \ + uint32_t w_stride, \ + size_t x_row_stride, \ + size_t f32_row_stride) { \ + for (uint32_t cb = 0; cb < cur_c; cb += 64) { \ + for (uint32_t sub = 0; sub < 64 && cb + sub < cur_c; sub += 32) { \ + const uint32_t ch = cb + sub; \ + const HVX_Vector w0 = *(const HVX_Vector *) (wp + 0 * w_stride + ch); \ + const HVX_Vector w1 = *(const HVX_Vector *) (wp + 1 * w_stride + ch); \ + const HVX_Vector w2 = *(const HVX_Vector *) (wp + 2 * w_stride + ch); \ + const HVX_Vector w3 = *(const HVX_Vector *) (wp + 3 * w_stride + ch); \ + \ + HVX_Vector xm3 = *(const HVX_Vector *) (hist + 0 * c_stride + ch); \ + HVX_Vector xm2 = *(const HVX_Vector *) (hist + 1 * c_stride + ch); \ + HVX_Vector xm1 = *(const HVX_Vector *) (hist + 2 * c_stride + ch); \ + \ + const uint8_t * restrict xp = (const uint8_t *) x_tile + \ + (X_F16 ? (cb * 2) : (ch * 4)); \ + uint8_t * restrict dp = (uint8_t *) dst_tile + ch * sizeof(float); \ + \ + _Pragma("clang loop unroll(disable) pipeline(disable)") \ + for (uint32_t t = 0; t < cur_t; ++t) { \ + HVX_Vector x0; \ + if (X_F16) { \ + HVX_VectorPair x0_p = hvx_vec_f16_to_f32(*(const HVX_Vector *) xp); \ + x0 = (sub == 0) ? Q6_V_lo_W(x0_p) : Q6_V_hi_W(x0_p); \ + } else { \ + x0 = *(const HVX_Vector *) xp; \ + } \ + \ + HVX_Vector a = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(xm3, w0), \ + Q6_Vqf32_vmpy_VsfVsf(xm2, w1)); \ + HVX_Vector b = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(xm1, w2), \ + Q6_Vqf32_vmpy_VsfVsf(x0, w3)); \ + HVX_Vector u = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(a, b)); \ + *(HVX_Vector *) dp = hvx_vec_silu_f32(u); \ + \ + xm3 = xm2; \ + xm2 = xm1; \ + xm1 = x0; \ + \ + xp += x_row_stride; \ + dp += f32_row_stride; \ + } \ + \ + *(HVX_Vector *) (hist + 0 * c_stride + ch) = xm3; \ + *(HVX_Vector *) (hist + 1 * c_stride + ch) = xm2; \ + *(HVX_Vector *) (hist + 2 * c_stride + ch) = xm1; \ + } \ + } \ + } + +DEFINE_SSM_CONV_TOKEN_4_DOT_SILU_F32(hvx_ssm_conv_token_4_dot_f32_silu, false) +DEFINE_SSM_CONV_TOKEN_4_DOT_SILU_F32(hvx_ssm_conv_token_4_dot_f16_silu, true) + +#undef DEFINE_SSM_CONV_TOKEN_4_DOT_SILU_F32 + +static __attribute__((noinline)) void hvx_ssm_conv_token_4_f16_f16(float * restrict hist, + const void * restrict x_tile, + const float * restrict wp, + void * restrict dst_tile, + float * restrict strip_f32, + uint32_t cur_c, + uint32_t cur_t, + uint32_t d_conv, + uint32_t c_stride, + uint32_t w_stride, + size_t x_row_stride, + size_t d_row_stride) { + (void) d_conv; + for (uint32_t cb = 0; cb < cur_c; cb += 64) { + hvx_ssm_conv_token_4_dot_f16_strip(hist, x_tile, wp, strip_f32, cb, cur_t, c_stride, w_stride, x_row_stride, 256); + hvx_ssm_conv_pack_f16_strip_1d(strip_f32, (uint8_t *) dst_tile + cb * sizeof(__fp16), cur_t, d_row_stride, cb + 32 < cur_c); + } +} + +static __attribute__((noinline)) void hvx_ssm_conv_token_4_f16_f16_silu(float * restrict hist, + const void * restrict x_tile, + const float * restrict wp, + void * restrict dst_tile, + float * restrict strip_f32, + uint32_t cur_c, + uint32_t cur_t, + uint32_t d_conv, + uint32_t c_stride, + uint32_t w_stride, + size_t x_row_stride, + size_t d_row_stride) { + (void) d_conv; + for (uint32_t cb = 0; cb < cur_c; cb += 64) { + hvx_ssm_conv_token_4_dot_f16_strip(hist, x_tile, wp, strip_f32, cb, cur_t, c_stride, w_stride, x_row_stride, 256); + hvx_ssm_conv_silu_pack_f16_strip_1d(strip_f32, (uint8_t *) dst_tile + cb * sizeof(__fp16), cur_t, d_row_stride, cb + 32 < cur_c); + } +} + +static __attribute__((noinline)) void hvx_ssm_conv_token_4_f32_f32(float * restrict hist, + const void * restrict x_tile, + const float * restrict wp, + void * restrict dst_tile, + float * restrict strip_f32, + uint32_t cur_c, + uint32_t cur_t, + uint32_t d_conv, + uint32_t c_stride, + uint32_t w_stride, + size_t x_row_stride, + size_t d_row_stride) { + (void) d_conv; + (void) strip_f32; + for (uint32_t cb = 0; cb < cur_c; cb += 64) { + hvx_ssm_conv_token_4_dot_f32_strip(hist, x_tile, wp, (uint8_t *) dst_tile + cb * sizeof(float), cb, cur_t, c_stride, w_stride, x_row_stride, d_row_stride); + } +} + +static __attribute__((noinline)) void hvx_ssm_conv_token_4_f32_f32_silu(float * restrict hist, + const void * restrict x_tile, + const float * restrict wp, + void * restrict dst_tile, + float * restrict strip_f32, + uint32_t cur_c, + uint32_t cur_t, + uint32_t d_conv, + uint32_t c_stride, + uint32_t w_stride, + size_t x_row_stride, + size_t d_row_stride) { + (void) d_conv; + (void) strip_f32; + hvx_ssm_conv_token_4_dot_f32_silu(hist, x_tile, wp, dst_tile, cur_c, cur_t, c_stride, w_stride, x_row_stride, d_row_stride); +} + +static __attribute__((noinline)) void hvx_ssm_conv_token_4_f32_f16(float * restrict hist, + const void * restrict x_tile, + const float * restrict wp, + void * restrict dst_tile, + float * restrict strip_f32, + uint32_t cur_c, + uint32_t cur_t, + uint32_t d_conv, + uint32_t c_stride, + uint32_t w_stride, + size_t x_row_stride, + size_t d_row_stride) { + (void) d_conv; + for (uint32_t cb = 0; cb < cur_c; cb += 64) { + hvx_ssm_conv_token_4_dot_f32_strip(hist, x_tile, wp, strip_f32, cb, cur_t, c_stride, w_stride, x_row_stride, 256); + hvx_ssm_conv_pack_f16_strip_1d(strip_f32, (uint8_t *) dst_tile + cb * sizeof(__fp16), cur_t, d_row_stride, cb + 32 < cur_c); + } +} + +static __attribute__((noinline)) void hvx_ssm_conv_token_4_f32_f16_silu(float * restrict hist, + const void * restrict x_tile, + const float * restrict wp, + void * restrict dst_tile, + float * restrict strip_f32, + uint32_t cur_c, + uint32_t cur_t, + uint32_t d_conv, + uint32_t c_stride, + uint32_t w_stride, + size_t x_row_stride, + size_t d_row_stride) { + (void) d_conv; + for (uint32_t cb = 0; cb < cur_c; cb += 64) { + hvx_ssm_conv_token_4_dot_f32_strip(hist, x_tile, wp, strip_f32, cb, cur_t, c_stride, w_stride, x_row_stride, 256); + hvx_ssm_conv_silu_pack_f16_strip_1d(strip_f32, (uint8_t *) dst_tile + cb * sizeof(__fp16), cur_t, d_row_stride, cb + 32 < cur_c); + } +} + +static __attribute__((noinline)) void hvx_ssm_conv_token_4_f16_f32(float * restrict hist, + const void * restrict x_tile, + const float * restrict wp, + void * restrict dst_tile, + float * restrict strip_f32, + uint32_t cur_c, + uint32_t cur_t, + uint32_t d_conv, + uint32_t c_stride, + uint32_t w_stride, + size_t x_row_stride, + size_t d_row_stride) { + (void) d_conv; + (void) strip_f32; + for (uint32_t cb = 0; cb < cur_c; cb += 64) { + hvx_ssm_conv_token_4_dot_f16_strip(hist, x_tile, wp, (uint8_t *) dst_tile + cb * sizeof(float), cb, cur_t, c_stride, w_stride, x_row_stride, d_row_stride); + } +} + +static __attribute__((noinline)) void hvx_ssm_conv_token_4_f16_f32_silu(float * restrict hist, + const void * restrict x_tile, + const float * restrict wp, + void * restrict dst_tile, + float * restrict strip_f32, + uint32_t cur_c, + uint32_t cur_t, + uint32_t d_conv, + uint32_t c_stride, + uint32_t w_stride, + size_t x_row_stride, + size_t d_row_stride) { + (void) d_conv; + (void) strip_f32; + hvx_ssm_conv_token_4_dot_f16_silu(hist, x_tile, wp, dst_tile, cur_c, cur_t, c_stride, w_stride, x_row_stride, d_row_stride); +} + +#define DEFINE_SSM_CONV_TOKEN_GEN(NAME, X_F16, DST_F16, APPLY_SILU) \ + static __attribute__((noinline)) void NAME(float * restrict hist, \ + const void * restrict x_tile, \ + const float * restrict wp, \ + void * restrict dst_tile, \ + float * restrict strip_f32, \ + uint32_t cur_c, \ + uint32_t cur_t, \ + uint32_t d_conv, \ + uint32_t c_stride, \ + uint32_t w_stride, \ + size_t x_row_stride, \ + size_t d_row_stride) { \ + (void) strip_f32; \ + const uint32_t s_taps = d_conv - 1; \ + for (uint32_t cb = 0; cb < cur_c; cb += 64) { \ + const uint8_t * restrict xp = (const uint8_t *) x_tile + cb * (X_F16 ? 2 : 4); \ + uint8_t * restrict dp = (uint8_t *) dst_tile + cb * (DST_F16 ? 2 : 4); \ + \ + _Pragma("clang loop unroll(disable) pipeline(disable)") \ + for (uint32_t t = 0; t < cur_t; ++t) { \ + HVX_Vector x0_0; \ + HVX_Vector x0_1; \ + if (X_F16) { \ + HVX_VectorPair x0_p = hvx_vec_f16_to_f32(*(const HVX_Vector *) xp); \ + x0_0 = Q6_V_lo_W(x0_p); \ + x0_1 = Q6_V_hi_W(x0_p); \ + } else { \ + x0_0 = *((const HVX_Vector *) xp + 0); \ + x0_1 = *((const HVX_Vector *) xp + 1); \ + } \ + \ + HVX_Vector acc0 = Q6_Vqf32_vmpy_VsfVsf( \ + x0_0, *(const HVX_Vector *) (wp + (size_t) s_taps * w_stride + cb + 0)); \ + HVX_Vector acc1 = Q6_Vqf32_vmpy_VsfVsf( \ + x0_1, *(const HVX_Vector *) (wp + (size_t) s_taps * w_stride + cb + 32)); \ + \ + _Pragma("clang loop unroll(disable)") \ + for (uint32_t j = 0; j < s_taps; ++j) { \ + HVX_Vector hj_0 = *(const HVX_Vector *) (hist + (size_t) j * c_stride + cb + 0); \ + HVX_Vector hj_1 = *(const HVX_Vector *) (hist + (size_t) j * c_stride + cb + 32); \ + HVX_Vector wj_0 = *(const HVX_Vector *) (wp + (size_t) j * w_stride + cb + 0); \ + HVX_Vector wj_1 = *(const HVX_Vector *) (wp + (size_t) j * w_stride + cb + 32); \ + acc0 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, Q6_Vqf32_vmpy_VsfVsf(hj_0, wj_0)); \ + acc1 = Q6_Vqf32_vadd_Vqf32Vqf32(acc1, Q6_Vqf32_vmpy_VsfVsf(hj_1, wj_1)); \ + if (j > 0) { \ + *(HVX_Vector *) (hist + (size_t) (j - 1) * c_stride + cb + 0) = hj_0; \ + *(HVX_Vector *) (hist + (size_t) (j - 1) * c_stride + cb + 32) = hj_1; \ + } \ + } \ + *(HVX_Vector *) (hist + (size_t) (s_taps - 1) * c_stride + cb + 0) = x0_0; \ + *(HVX_Vector *) (hist + (size_t) (s_taps - 1) * c_stride + cb + 32) = x0_1; \ + \ + HVX_Vector u0 = Q6_Vsf_equals_Vqf32(acc0); \ + HVX_Vector u1 = Q6_Vsf_equals_Vqf32(acc1); \ + \ + if (DST_F16) { \ + if (APPLY_SILU) { \ + *(HVX_Vector *) dp = hvx_ssm_conv_silu_pack_f16(u0, u1); \ + } else { \ + *(HVX_Vector *) dp = hvx_vec_f32_to_f16(hvx_ssm_conv_clamp_f16_f32(u0), \ + hvx_ssm_conv_clamp_f16_f32(u1)); \ + } \ + } else { \ + if (APPLY_SILU) { \ + u0 = hvx_vec_silu_f32(u0); \ + u1 = hvx_vec_silu_f32(u1); \ + } \ + *((HVX_Vector *) dp + 0) = u0; \ + *((HVX_Vector *) dp + 1) = u1; \ + } \ + \ + xp += x_row_stride; \ + dp += d_row_stride; \ + } \ + } \ + } + +DEFINE_SSM_CONV_TOKEN_GEN(hvx_ssm_conv_token_gen_f32_f32, false, false, false) +DEFINE_SSM_CONV_TOKEN_GEN(hvx_ssm_conv_token_gen_f32_f32_silu, false, false, true) +DEFINE_SSM_CONV_TOKEN_GEN(hvx_ssm_conv_token_gen_f32_f16, false, true, false) +DEFINE_SSM_CONV_TOKEN_GEN(hvx_ssm_conv_token_gen_f32_f16_silu, false, true, true) +DEFINE_SSM_CONV_TOKEN_GEN(hvx_ssm_conv_token_gen_f16_f32, true, false, false) +DEFINE_SSM_CONV_TOKEN_GEN(hvx_ssm_conv_token_gen_f16_f32_silu, true, false, true) +DEFINE_SSM_CONV_TOKEN_GEN(hvx_ssm_conv_token_gen_f16_f16, true, true, false) +DEFINE_SSM_CONV_TOKEN_GEN(hvx_ssm_conv_token_gen_f16_f16_silu, true, true, true) + +#undef DEFINE_SSM_CONV_TOKEN_GEN + // Single-token decode worker (n_t == 1) static void ssm_conv_thread_f32_decode(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { struct htp_ssm_conv_context * scctx = (struct htp_ssm_conv_context *) data; @@ -197,10 +1024,19 @@ static void ssm_conv_thread_f32_decode(const htp_thread_t * th, unsigned int nth dma_queue * dma_q = th->dma_q; - const uint32_t d_conv = kparams->d_conv; - const uint32_t d_inner = kparams->d_inner; - const uint32_t n_s = kparams->n_s; - const bool apply_silu = kparams->silu != 0; + const uint32_t d_conv = kparams->d_conv; + const uint32_t n_s = kparams->n_s; + const bool src0_f16 = (src0->type == HTP_TYPE_F16); + const bool src1_f16 = (src1->type == HTP_TYPE_F16); + const bool dst_f16 = (dst->type == HTP_TYPE_F16); + const bool raw_dot = scctx->raw_dot; + + const htp_ssm_conv_decode_dot_fn_t decode_dot_fn = scctx->decode_dot_fn; + const htp_ssm_conv_epilogue_fn_t epilogue_fn = scctx->epilogue_fn; + + const size_t src0_elem_size = src0_f16 ? sizeof(__fp16) : sizeof(float); + const size_t src1_elem_size = src1_f16 ? sizeof(__fp16) : sizeof(float); + const size_t dst_elem_size = dst_f16 ? sizeof(__fp16) : sizeof(float); const uint32_t dr = scctx->nrows_per_hvx; const uint32_t ir0 = scctx->row_start + dr * ith; @@ -210,26 +1046,28 @@ static void ssm_conv_thread_f32_decode(const htp_thread_t * th, unsigned int nth return; } - const uint32_t d_inner_per_hvx = ir1 - ir0; - const uint32_t d_inner_stride = hex_round_up(d_inner_per_hvx, VLEN_FP32); - const uint32_t d_inner_tile = scctx->d_inner_tile; + const uint32_t d_inner_per_hvx = ir1 - ir0; + const uint32_t d_inner_stride = hex_round_up(d_inner_per_hvx, VLEN_FP32); + const uint32_t d_inner_tile = scctx->d_inner_tile; const size_t src0_stride_inner_bytes = src0->nb[1]; const size_t src0_stride_seq_bytes = src0->nb[2]; const size_t dst_stride_seq_bytes = dst->nb[2]; - uint8_t * src1_spad_base = octx->src1_spad.data + ith * octx->src1_spad.size_per_hvx; - uint8_t * src0_spad_base = octx->src0_spad.data + ith * octx->src0_spad.size_per_hvx; - uint8_t * dst_spad_base = octx->dst_spad.data + ith * octx->dst_spad.size_per_hvx; + uint8_t * src1_spad_base = VTCM_LAYOUT_PTR(uint8_t, scctx->vtcm_base, scctx->layout.off_src1) + ith * scctx->layout.src1_bytes_per_hvx; + uint8_t * src0_spad_base = VTCM_LAYOUT_PTR(uint8_t, scctx->vtcm_base, scctx->layout.off_src0) + ith * scctx->layout.src0_bytes_per_hvx; + uint8_t * dst_spad_base = VTCM_LAYOUT_PTR(uint8_t, scctx->vtcm_base, scctx->layout.off_dst) + ith * scctx->layout.dst_bytes_per_hvx; - const size_t weight_bytes = (size_t) d_inner_per_hvx * d_conv * sizeof(float); - const size_t weight_raw_size = hex_round_up(weight_bytes, 128); + const size_t weight_f32_bytes = (size_t) d_inner_per_hvx * d_conv * sizeof(float); + const size_t weight_dma_bytes = (size_t) d_inner_per_hvx * d_conv * src1_elem_size; + const size_t weight_raw_size = hex_round_up(weight_f32_bytes, 128) + 128; float * src1_raw = (float *) src1_spad_base; float * src1_T = (float *) (src1_spad_base + weight_raw_size); - const size_t src0_tile_raw_bytes = hex_round_up(d_inner_tile * d_conv * sizeof(float), 128); - const size_t dst_tile_bytes = hex_round_up(d_inner_tile * sizeof(float), 128); + const size_t raw_stride_bytes = src0_f16 ? ((size_t) hex_round_up(d_conv, 2) * sizeof(__fp16)) : ((size_t) d_conv * sizeof(float)); + const size_t src0_tile_raw_bytes = hex_round_up((size_t) d_inner_tile * raw_stride_bytes, 128); + const size_t dst_tile_bytes = hex_round_up((size_t) d_inner_tile * sizeof(float), 128); float * src0_tile_raw[2] = { (float *) src0_spad_base, (float *) (src0_spad_base + src0_tile_raw_bytes) }; float * src0_T = (float *) (src0_spad_base + 2 * src0_tile_raw_bytes); @@ -238,12 +1076,9 @@ static void ssm_conv_thread_f32_decode(const htp_thread_t * th, unsigned int nth struct htp_thread_trace * tr = th->trace; - // raw_dot keeps both operands in the DMA layout, so src1 needs no prep pass - const bool raw_dot = (d_conv == 4) && (d_inner_per_hvx % VLEN_FP32 == 0); - const uint32_t n_tiles = fastdiv(d_inner_per_hvx + d_inner_tile - 1, &kparams->div_d_inner_tile); const uint32_t n_chunks = n_s * n_tiles; - const size_t row_bytes = d_conv * sizeof(float); + const size_t row_bytes = (size_t) d_conv * src0_elem_size; uint32_t s_fetch = 0; uint32_t tile_off_fetch = 0; @@ -251,11 +1086,11 @@ static void ssm_conv_thread_f32_decode(const htp_thread_t * th, unsigned int nth #define SSM_CONV_DECODE_PUSH_FETCH(c) \ do { \ const uint32_t cur_tile_n = MIN(d_inner_tile, d_inner_per_hvx - tile_off_fetch); \ - const dma_addr_t fetch_ddr = src0->data + s_fetch * src0_stride_seq_bytes + \ - (ir0 + tile_off_fetch) * src0_stride_inner_bytes; \ + const dma_addr_t fetch_ddr = src0->data + (s_fetch * src0_stride_seq_bytes + \ + (ir0 + tile_off_fetch) * src0_stride_inner_bytes); \ dma_queue_push(dma_q, \ dma_make_data((uint8_t *) src0_tile_raw[(c) & 1], fetch_ddr), \ - row_bytes, src0_stride_inner_bytes, row_bytes, cur_tile_n); \ + raw_stride_bytes, src0_stride_inner_bytes, row_bytes, cur_tile_n); \ tile_off_fetch += d_inner_tile; \ if (tile_off_fetch >= d_inner_per_hvx) { \ tile_off_fetch = 0; \ @@ -264,20 +1099,27 @@ static void ssm_conv_thread_f32_decode(const htp_thread_t * th, unsigned int nth } while (0) // Queue weights and initial input tiles together so DDR reads overlap - const dma_addr_t src1_ddr = src1->data + ir0 * d_conv * sizeof(float); - dma_queue_push(dma_q, dma_make_data((uint8_t *) src1_raw, src1_ddr), weight_bytes, weight_bytes, weight_bytes, 1); + const dma_addr_t src1_ddr = src1->data + (size_t) ir0 * d_conv * src1_elem_size; + uint8_t * src1_dma_dest = src1_f16 ? (uint8_t *) src1_T : (uint8_t *) src1_raw; + dma_queue_push(dma_q, dma_make_data(src1_dma_dest, src1_ddr), weight_dma_bytes, weight_dma_bytes, weight_dma_bytes, 1); + dma_queue_push(dma_q, dma_make_data(dst->data, (uint8_t *) dst_tile[0]), 0, 0, 0, 0); SSM_CONV_DECODE_PUSH_FETCH(0); if (n_chunks > 1) { + dma_queue_push(dma_q, dma_make_data(dst->data, (uint8_t *) dst_tile[1]), 0, 0, 0, 0); SSM_CONV_DECODE_PUSH_FETCH(1); } dma_queue_pop(dma_q); // weights - if (!raw_dot) { - // Unpack/transpose src1_raw into src1_T {d_conv, d_inner_stride} + if (src1_f16 || !raw_dot) { htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) ir0); - hvx_ssm_conv_unpack_to_T(src1_raw, src1_T, d_inner_per_hvx, d_inner_stride, d_conv); + if (src1_f16) { + hvx_ssm_conv_widen_f16_vtcm((const __fp16 *) src1_T, src1_raw, d_inner_per_hvx * d_conv); + } + if (!raw_dot) { + hvx_ssm_conv_unpack_to_T(src1_raw, src1_T, d_inner_per_hvx, d_inner_stride, d_conv); + } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) ir0); } @@ -287,39 +1129,18 @@ static void ssm_conv_thread_f32_decode(const htp_thread_t * th, unsigned int nth for (uint32_t c = 0; c < n_chunks; ++c) { const uint32_t tile_n = MIN(d_inner_tile, d_inner_per_hvx - tile_off); - if (c >= 2) { - dma_queue_pop(dma_q); // writeback of chunk c-2, frees dst_tile[c & 1] - } + dma_queue_pop(dma_q); // writeback of chunk c-2, frees dst_tile[c & 1] dma_queue_pop(dma_q); // fetch chunk c float * restrict out = dst_tile[c & 1]; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i3); - if (raw_dot) { - const float * xp = src0_tile_raw[c & 1]; - const float * wp = src1_raw + tile_off * 4; - hvx_ssm_conv_decode_4(xp, wp, out, tile_n); - } else { - const uint32_t tile_stride = hex_round_up(tile_n, VLEN_FP32); - hvx_ssm_conv_unpack_to_T(src0_tile_raw[c & 1], src0_T, tile_n, tile_stride, d_conv); - - for (uint32_t cb = 0; cb < tile_n; cb += VLEN_FP32) { - HVX_Vector acc = hvx_vec_splat_f32(0.0f); - for (uint32_t j = 0; j < d_conv; ++j) { - HVX_Vector x = *(const HVX_Vector *)(src0_T + j * tile_stride + cb); - HVX_Vector w = *(const HVX_Vector *)(src1_T + j * d_inner_stride + tile_off + cb); - acc = Q6_Vqf32_vadd_Vqf32Vqf32(acc, Q6_Vqf32_vmpy_VsfVsf(x, w)); - } - *(HVX_Vector *)(out + cb) = Q6_Vsf_equals_Vqf32(acc); - } - } - if (apply_silu) { - hvx_ssm_conv_silu_vtcm(out, hex_round_up(tile_n, VLEN_FP32) / VLEN_FP32); - } + decode_dot_fn(src0_tile_raw[c & 1], src0_T, src1_raw, src1_T, out, tile_n, d_inner_stride, tile_off, d_conv); + epilogue_fn(out, 1, tile_n); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) i3); - const dma_addr_t dst_ddr = dst->data + i3 * dst_stride_seq_bytes + (ir0 + tile_off) * sizeof(float); - const size_t tile_out_bytes = (size_t) tile_n * sizeof(float); + const dma_addr_t dst_ddr = dst->data + (i3 * dst_stride_seq_bytes + (size_t) (ir0 + tile_off) * dst_elem_size); + const size_t tile_out_bytes = (size_t) tile_n * dst_elem_size; dma_queue_push(dma_q, dma_make_data(dst_ddr, (uint8_t *) out), tile_out_bytes, tile_out_bytes, tile_out_bytes, 1); @@ -334,9 +1155,7 @@ static void ssm_conv_thread_f32_decode(const htp_thread_t * th, unsigned int nth } } - for (uint32_t k = MIN(n_chunks, 2); k > 0; --k) { - dma_queue_pop(dma_q); // drain the last writebacks - } + dma_queue_flush(dma_q); #undef SSM_CONV_DECODE_PUSH_FETCH @@ -358,12 +1177,21 @@ static void ssm_conv_thread_f32_prefill(const htp_thread_t * th, unsigned int nt dma_queue * dma_q = th->dma_q; - const uint32_t d_conv = kparams->d_conv; - const uint32_t d_inner = kparams->d_inner; - const uint32_t n_t = kparams->n_t; - const uint32_t n_s = kparams->n_s; - const uint32_t ncs = src0->ne[0]; - const bool apply_silu = kparams->silu != 0; + const uint32_t d_conv = kparams->d_conv; + const uint32_t n_t = kparams->n_t; + const uint32_t n_s = kparams->n_s; + const uint32_t ncs = src0->ne[0]; + const bool src0_f16 = (src0->type == HTP_TYPE_F16); + const bool src1_f16 = (src1->type == HTP_TYPE_F16); + const bool dst_f16 = (dst->type == HTP_TYPE_F16); + + const htp_ssm_conv_transpose_block_fn_t transpose_block_fn = scctx->transpose_block_fn; + const htp_ssm_conv_prefill_dot_fn_t prefill_dot_fn = scctx->prefill_dot_fn; + const htp_ssm_conv_epilogue_fn_t epilogue_fn = scctx->epilogue_fn; + + const size_t src0_elem_size = src0_f16 ? sizeof(__fp16) : sizeof(float); + const size_t src1_elem_size = src1_f16 ? sizeof(__fp16) : sizeof(float); + const size_t dst_elem_size = dst_f16 ? sizeof(__fp16) : sizeof(float); const uint32_t dr = scctx->nrows_per_hvx; const uint32_t ir0 = scctx->row_start + dr * ith; @@ -373,28 +1201,29 @@ static void ssm_conv_thread_f32_prefill(const htp_thread_t * th, unsigned int nt return; } - const uint32_t d_inner_per_hvx = ir1 - ir0; - const uint32_t d_inner_stride = hex_round_up(d_inner_per_hvx, VLEN_FP32); - const uint32_t d_inner_tile = scctx->d_inner_tile; + const uint32_t d_inner_per_hvx = ir1 - ir0; + const uint32_t d_inner_stride = hex_round_up(d_inner_per_hvx, VLEN_FP32); + const uint32_t d_inner_tile = scctx->d_inner_tile; const size_t src0_stride_inner_bytes = src0->nb[1]; const size_t src0_stride_seq_bytes = src0->nb[2]; const size_t dst_stride_token_bytes = dst->nb[1]; const size_t dst_stride_seq_bytes = dst->nb[2]; - uint8_t * src1_spad_base = octx->src1_spad.data + ith * octx->src1_spad.size_per_hvx; - uint8_t * src0_spad_base = octx->src0_spad.data + ith * octx->src0_spad.size_per_hvx; - uint8_t * dst_spad_base = octx->dst_spad.data + ith * octx->dst_spad.size_per_hvx; + uint8_t * src1_spad_base = VTCM_LAYOUT_PTR(uint8_t, scctx->vtcm_base, scctx->layout.off_src1) + ith * scctx->layout.src1_bytes_per_hvx; + uint8_t * src0_spad_base = VTCM_LAYOUT_PTR(uint8_t, scctx->vtcm_base, scctx->layout.off_src0) + ith * scctx->layout.src0_bytes_per_hvx; + uint8_t * dst_spad_base = VTCM_LAYOUT_PTR(uint8_t, scctx->vtcm_base, scctx->layout.off_dst) + ith * scctx->layout.dst_bytes_per_hvx; - const size_t weight_bytes = (size_t) d_inner_per_hvx * d_conv * sizeof(float); - const size_t weight_raw_size = hex_round_up(weight_bytes, 128); + const size_t weight_f32_bytes = (size_t) d_inner_per_hvx * d_conv * sizeof(float); + const size_t weight_dma_bytes = (size_t) d_inner_per_hvx * d_conv * src1_elem_size; + const size_t weight_raw_size = hex_round_up(weight_f32_bytes, 128) + 128; float * src1_raw = (float *) src1_spad_base; float * src1_T = (float *) (src1_spad_base + weight_raw_size); // src0 spad holds two raw tiles (fetch of tile n+1 overlaps compute of tile n) plus // the transposed block. dst spad holds two tiles so a writeback can stay in flight. - const size_t raw_stride_bytes = ncs * sizeof(float) + sizeof(float); + const size_t raw_stride_bytes = htp_ssm_conv_raw_stride_bytes(ncs, src0_elem_size); const size_t src0_tile_raw_bytes = hex_round_up(d_inner_tile * raw_stride_bytes, 128); const size_t dst_tile_bytes = hex_round_up(d_inner_tile * n_t * sizeof(float), 128); @@ -407,18 +1236,18 @@ static void ssm_conv_thread_f32_prefill(const htp_thread_t * th, unsigned int nt const uint32_t n_tiles = fastdiv(d_inner_per_hvx + d_inner_tile - 1, &kparams->div_d_inner_tile); const uint32_t n_chunks = n_s * n_tiles; - const size_t row_bytes = ncs * sizeof(float); + const size_t row_bytes = (size_t) ncs * src0_elem_size; uint32_t s_fetch = 0; uint32_t tile_off_fetch = 0; // Chunk c fetches into src0_tile_raw[c & 1] and writes back from dst_tile[c & 1]. - // Two fetches run ahead, so the queue order is F0 F1 W0 F2 W1 ... and pops follow it. + // Two fetches run ahead with dummy writeback pushes in prologue: W-2 F0 W-1 F1 W0 F2 ... #define SSM_CONV_PUSH_FETCH(c) \ do { \ const uint32_t cur_tile_n = MIN(d_inner_tile, d_inner_per_hvx - tile_off_fetch); \ - const dma_addr_t fetch_ddr = src0->data + s_fetch * src0_stride_seq_bytes + \ - (ir0 + tile_off_fetch) * src0_stride_inner_bytes; \ + const dma_addr_t fetch_ddr = src0->data + (s_fetch * src0_stride_seq_bytes + \ + (ir0 + tile_off_fetch) * src0_stride_inner_bytes); \ dma_queue_push(dma_q, \ dma_make_data((uint8_t *) src0_tile_raw[(c) & 1], fetch_ddr), \ raw_stride_bytes, src0_stride_inner_bytes, row_bytes, cur_tile_n); \ @@ -430,11 +1259,14 @@ static void ssm_conv_thread_f32_prefill(const htp_thread_t * th, unsigned int nt } while (0) // Queue weights and initial input tiles together so DDR reads overlap - const dma_addr_t src1_ddr = src1->data + ir0 * d_conv * sizeof(float); - dma_queue_push(dma_q, dma_make_data((uint8_t *) src1_raw, src1_ddr), weight_bytes, weight_bytes, weight_bytes, 1); + const dma_addr_t src1_ddr = src1->data + (size_t) ir0 * d_conv * src1_elem_size; + uint8_t * src1_dma_dest = src1_f16 ? (uint8_t *) src1_T : (uint8_t *) src1_raw; + dma_queue_push(dma_q, dma_make_data(src1_dma_dest, src1_ddr), weight_dma_bytes, weight_dma_bytes, weight_dma_bytes, 1); + dma_queue_push(dma_q, dma_make_data(dst->data, (uint8_t *) dst_tile[0]), 0, 0, 0, 0); SSM_CONV_PUSH_FETCH(0); if (n_chunks > 1) { + dma_queue_push(dma_q, dma_make_data(dst->data, (uint8_t *) dst_tile[1]), 0, 0, 0, 0); SSM_CONV_PUSH_FETCH(1); } @@ -442,14 +1274,14 @@ static void ssm_conv_thread_f32_prefill(const htp_thread_t * th, unsigned int nt // Unpack/transpose src1_raw into src1_T {d_conv, d_inner_stride} htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) ir0); + if (src1_f16) { + hvx_ssm_conv_widen_f16_vtcm((const __fp16 *) src1_T, src1_raw, d_inner_per_hvx * d_conv); + } hvx_ssm_conv_unpack_to_T(src1_raw, src1_T, d_inner_per_hvx, d_inner_stride, d_conv); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) ir0); const uint32_t C_TILE = VLEN_FP32; - // gather offsets: lane r reads channel r of the raw tile block - const HVX_Vector vv = hvx_vec_gather_offsets_w(raw_stride_bytes); - uint32_t i3 = 0; uint32_t tile_off = 0; @@ -459,9 +1291,7 @@ static void ssm_conv_thread_f32_prefill(const htp_thread_t * th, unsigned int nt const float * restrict raw = src0_tile_raw[c & 1]; float * restrict out = dst_tile[c & 1]; - if (c >= 2) { - dma_queue_pop(dma_q); // writeback of chunk c-2, frees dst_tile[c & 1] - } + dma_queue_pop(dma_q); // writeback of chunk c-2, frees dst_tile[c & 1] dma_queue_pop(dma_q); // fetch chunk c // Channel block outer, token inner: the taps and the sliding window stay in @@ -472,61 +1302,25 @@ static void ssm_conv_thread_f32_prefill(const htp_thread_t * th, unsigned int nt const uint32_t cb_n = MIN(C_TILE, tile_n - cb); htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) tile_off); - const float * raw_ch = (const float *) ((const uint8_t *) raw + (size_t) cb * raw_stride_bytes); - hvx_ssm_conv_transpose_block(raw_ch, src0_T, raw_stride_bytes, ncs, cb_n, vv); + const uint8_t * raw_ch = (const uint8_t *) raw + (size_t) cb * raw_stride_bytes; + transpose_block_fn(raw_ch, src0_T, raw_stride_bytes, ncs, cb_n); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) tile_off); const float * restrict wp = src1_T + tile_off + cb; float * restrict op = out + cb; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) tile_off); - if (d_conv == 4) { - const HVX_Vector w0 = *(const HVX_Vector *) (wp); - const HVX_Vector w1 = *(const HVX_Vector *) (wp + d_inner_stride); - const HVX_Vector w2 = *(const HVX_Vector *) (wp + 2 * d_inner_stride); - const HVX_Vector w3 = *(const HVX_Vector *) (wp + 3 * d_inner_stride); - - HVX_Vector x0 = *(const HVX_Vector *) (src0_T); - HVX_Vector x1 = *(const HVX_Vector *) (src0_T + C_TILE); - HVX_Vector x2 = *(const HVX_Vector *) (src0_T + 2 * C_TILE); - - for (uint32_t t = 0; t < n_t; ++t) { - const HVX_Vector x3 = *(const HVX_Vector *) (src0_T + (t + 3) * C_TILE); - - HVX_Vector a = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x0, w0), - Q6_Vqf32_vmpy_VsfVsf(x1, w1)); - HVX_Vector b = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x2, w2), - Q6_Vqf32_vmpy_VsfVsf(x3, w3)); - - *(HVX_Vector *) (op + t * dst_tile_stride) = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(a, b)); - - x0 = x1; - x1 = x2; - x2 = x3; - } - } else { - for (uint32_t t = 0; t < n_t; ++t) { - HVX_Vector acc = hvx_vec_splat_f32(0.0f); - for (uint32_t j = 0; j < d_conv; ++j) { - HVX_Vector x = *(const HVX_Vector *) (src0_T + (t + j) * C_TILE); - HVX_Vector w = *(const HVX_Vector *) (wp + j * d_inner_stride); - acc = Q6_Vqf32_vadd_Vqf32Vqf32(acc, Q6_Vqf32_vmpy_VsfVsf(x, w)); - } - *(HVX_Vector *) (op + t * dst_tile_stride) = Q6_Vsf_equals_Vqf32(acc); - } - } + prefill_dot_fn(src0_T, wp, op, n_t, d_conv, d_inner_stride, dst_tile_stride); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) tile_off); } - if (apply_silu) { - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) tile_off); - hvx_ssm_conv_silu_vtcm(out, n_t * (dst_tile_stride / C_TILE)); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) tile_off); - } + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) tile_off); + const size_t dst_vtcm_stride_bytes = epilogue_fn(out, n_t, tile_n); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) tile_off); // Writeback dst_tile VTCM -> DDR via 2D DMA - dma_queue_push(dma_q, dma_make_data(dst->data + i3 * dst_stride_seq_bytes + (ir0 + tile_off) * sizeof(float), (uint8_t *) out), - dst_stride_token_bytes, dst_tile_stride * sizeof(float), tile_n * sizeof(float), n_t); + dma_queue_push(dma_q, dma_make_data(dst->data + (i3 * dst_stride_seq_bytes + (size_t) (ir0 + tile_off) * dst_elem_size), (uint8_t *) out), + dst_stride_token_bytes, dst_vtcm_stride_bytes, (size_t) tile_n * dst_elem_size, n_t); if (c + 2 < n_chunks) { SSM_CONV_PUSH_FETCH(c + 2); @@ -539,9 +1333,7 @@ static void ssm_conv_thread_f32_prefill(const htp_thread_t * th, unsigned int nt } } - for (uint32_t k = MIN(n_chunks, 2); k > 0; --k) { - dma_queue_pop(dma_q); // drain the last writebacks - } + dma_queue_flush(dma_q); #undef SSM_CONV_PUSH_FETCH @@ -551,10 +1343,176 @@ static void ssm_conv_thread_f32_prefill(const htp_thread_t * th, unsigned int nt dst->ne[2], dst->ne[3]); } +// Fused token-major worker (n_t == 1 decode and n_t > 1 prefill) +static void ssm_conv_thread_token_major(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + struct htp_ssm_conv_context * scctx = (struct htp_ssm_conv_context *) data; + struct htp_ops_context * octx = scctx->octx; + const struct htp_ssm_conv_kernel_params * kparams = scctx->kparams; + + const struct htp_tensor * restrict state = octx->src[0]; + const struct htp_tensor * restrict weight = octx->src[1]; + const struct htp_tensor * restrict x = octx->src[2]; + const struct htp_tensor * restrict dst = octx->dsts[0]; + const struct htp_tensor * restrict dst_state = octx->dsts[1]; + + dma_queue * dma_q = th->dma_q; + + const uint32_t d_conv = kparams->d_conv; + const uint32_t s_taps = d_conv - 1; + const uint32_t n_t = kparams->n_t; + const uint32_t n_s = kparams->n_s; + const uint32_t n_t_tile = kparams->n_t_tile; + const bool state_f16 = (state->type == HTP_TYPE_F16); + const bool weight_f16 = (weight->type == HTP_TYPE_F16); + const bool x_f16 = (x->type == HTP_TYPE_F16); + const bool dst_f16 = (dst->type == HTP_TYPE_F16); + const bool dst_state_f16 = (dst_state && dst_state->type == HTP_TYPE_F16); + + const htp_ssm_conv_token_step_fn_t token_step_fn = scctx->token_step_fn; + const htp_ssm_conv_state_unpack_fn_t state_unpack_fn = scctx->state_unpack_fn; + const htp_ssm_conv_state_pack_fn_t state_pack_fn = scctx->state_pack_fn; + + const size_t state_elem_size = state_f16 ? sizeof(__fp16) : sizeof(float); + const size_t weight_elem_size = weight_f16 ? sizeof(__fp16) : sizeof(float); + const size_t x_elem_size = x_f16 ? sizeof(__fp16) : sizeof(float); + const size_t dst_elem_size = dst_f16 ? sizeof(__fp16) : sizeof(float); + const size_t dst_state_elem_size = dst_state_f16 ? sizeof(__fp16) : sizeof(float); + + const uint32_t dr = scctx->nrows_per_hvx; + const uint32_t ir0 = scctx->row_start + dr * ith; + const uint32_t ir1 = MIN(ir0 + dr, scctx->row_start + scctx->nrows); + + if (ir0 >= ir1) { + return; + } + + const uint32_t d_inner_per_hvx = ir1 - ir0; + const uint32_t w_stride = hex_round_up(d_inner_per_hvx, 64); + const uint32_t d_inner_tile = scctx->d_inner_tile; + const uint32_t c_stride = hex_round_up(d_inner_tile, 64); + + const size_t state_stride_seq_bytes = state->nb[2]; + const size_t x_stride_token_bytes = x->nb[1]; + const size_t x_stride_seq_bytes = x->nb[2]; + const size_t dst_stride_token_bytes = dst->nb[1]; + const size_t dst_stride_seq_bytes = dst->nb[2]; + const size_t dst_state_stride_seq_bytes = dst_state ? dst_state->nb[1] : 0; + + uint8_t * src1_spad_base = VTCM_LAYOUT_PTR(uint8_t, scctx->vtcm_base, scctx->layout.off_src1) + ith * scctx->layout.src1_bytes_per_hvx; + uint8_t * src0_spad_base = VTCM_LAYOUT_PTR(uint8_t, scctx->vtcm_base, scctx->layout.off_src0) + ith * scctx->layout.src0_bytes_per_hvx; + uint8_t * dst_spad_base = VTCM_LAYOUT_PTR(uint8_t, scctx->vtcm_base, scctx->layout.off_dst) + ith * scctx->layout.dst_bytes_per_hvx; + + const size_t weight_dma_bytes = (size_t) d_inner_per_hvx * d_conv * weight_elem_size; + const size_t weight_raw_size = hex_round_up((size_t) w_stride * d_conv * sizeof(float), 128) + 128; + + float * src1_raw = (float *) src1_spad_base; + float * src1_T = (float *) (src1_spad_base + weight_raw_size); + + const size_t x_row_stride = hex_round_up((size_t) c_stride * x_elem_size, 128); + const size_t x_tile_bytes = hex_round_up((size_t) n_t_tile * x_row_stride, 128); + const size_t state_raw_sz = hex_round_up((size_t) c_stride * s_taps * sizeof(float), 128) + 128; + const size_t d_row_stride = hex_round_up((size_t) c_stride * dst_elem_size, 128); + const size_t d_tile_bytes = hex_round_up((size_t) n_t_tile * d_row_stride, 128); + + uint8_t * x_tile[2] = { src0_spad_base, src0_spad_base + x_tile_bytes }; + float * state_raw = (float *) (src0_spad_base + 2 * x_tile_bytes); + float * hist = (float *) ((uint8_t *) state_raw + state_raw_sz); + uint8_t * d_tile[2] = { dst_spad_base, dst_spad_base + d_tile_bytes }; + float * strip_f32 = (float *) (dst_spad_base + 2 * d_tile_bytes); + + struct htp_thread_trace * tr = th->trace; + + const dma_addr_t src1_ddr = weight->data + (size_t) ir0 * d_conv * weight_elem_size; + uint8_t * src1_dma_dest = weight_f16 ? (uint8_t *) src1_T : (uint8_t *) src1_raw; + dma_queue_push(dma_q, dma_make_data(src1_dma_dest, src1_ddr), weight_dma_bytes, weight_dma_bytes, weight_dma_bytes, 1); + dma_queue_pop(dma_q); + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) ir0); + if (weight_f16) { + hvx_ssm_conv_widen_f16_vtcm((const __fp16 *) src1_T, src1_raw, d_inner_per_hvx * d_conv); + } + hvx_ssm_conv_unpack_to_T(src1_raw, src1_T, d_inner_per_hvx, w_stride, d_conv); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) ir0); + + const uint32_t n_t_blocks = kparams->n_t_blocks; + + for (uint32_t seq = 0; seq < n_s; ++seq) { + for (uint32_t tile_off = 0; tile_off < d_inner_per_hvx; tile_off += d_inner_tile) { + const uint32_t cur_c = MIN(d_inner_tile, d_inner_per_hvx - tile_off); + const size_t st_in_sz = (size_t) cur_c * s_taps * state_elem_size; + const dma_addr_t st_in_ddr = state->data + seq * state_stride_seq_bytes + (size_t) (ir0 + tile_off) * s_taps * state_elem_size; + const size_t x_width = (size_t) cur_c * x_elem_size; + const size_t d_width = (size_t) cur_c * dst_elem_size; + const dma_addr_t x_base = x->data + seq * x_stride_seq_bytes + (size_t) (ir0 + tile_off) * x_elem_size; + const dma_addr_t d_base = dst->data + seq * dst_stride_seq_bytes + (size_t) (ir0 + tile_off) * dst_elem_size; + + uint8_t * st_in_vtcm = state_f16 ? (uint8_t *) hist : (uint8_t *) state_raw; + dma_queue_push(dma_q, dma_make_data(st_in_vtcm, st_in_ddr), st_in_sz, st_in_sz, st_in_sz, 1); + + const uint32_t cur_t0 = MIN(n_t_tile, n_t); + dma_queue_push(dma_q, dma_make_data(dst->data, d_tile[0]), 0, 0, 0, 0); + dma_queue_push(dma_q, dma_make_data(x_tile[0], x_base), x_row_stride, x_stride_token_bytes, x_width, cur_t0); + if (n_t_blocks > 1) { + const uint32_t cur_t1 = MIN(n_t_tile, n_t - n_t_tile); + dma_queue_push(dma_q, dma_make_data(dst->data, d_tile[1]), 0, 0, 0, 0); + dma_queue_push(dma_q, dma_make_data(x_tile[1], x_base + (size_t) n_t_tile * x_stride_token_bytes), + x_row_stride, x_stride_token_bytes, x_width, cur_t1); + } + + dma_queue_pop(dma_q); // state + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) tile_off); + state_unpack_fn(state_raw, hist, cur_c, c_stride, s_taps); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) tile_off); + + const float * restrict wp = src1_T + tile_off; + + for (uint32_t tb = 0; tb < n_t_blocks; ++tb) { + const uint32_t t0 = tb * n_t_tile; + const uint32_t cur_t = MIN(n_t_tile, n_t - t0); + + dma_queue_pop(dma_q); // writeback of block tb-2 + dma_queue_pop(dma_q); // fetch of block tb + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) t0); + token_step_fn(hist, x_tile[tb & 1], wp, d_tile[tb & 1], strip_f32, + cur_c, cur_t, d_conv, c_stride, w_stride, x_row_stride, d_row_stride); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) t0); + + dma_queue_push(dma_q, dma_make_data(d_base + (size_t) t0 * dst_stride_token_bytes, d_tile[tb & 1]), + dst_stride_token_bytes, d_row_stride, d_width, cur_t); + + if (tb + 2 < n_t_blocks) { + const uint32_t next_t0 = (tb + 2) * n_t_tile; + const uint32_t next_t = MIN(n_t_tile, n_t - next_t0); + dma_queue_push(dma_q, dma_make_data(x_tile[tb & 1], x_base + (size_t) next_t0 * x_stride_token_bytes), + x_row_stride, x_stride_token_bytes, x_width, next_t); + } + } + + if (dst_state) { + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) tile_off); + state_pack_fn(hist, state_raw, cur_c, c_stride, s_taps); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) tile_off); + + const size_t st_out_sz = (size_t) cur_c * s_taps * dst_state_elem_size; + const dma_addr_t st_out_ddr = dst_state->data + seq * dst_state_stride_seq_bytes + (size_t) (ir0 + tile_off) * s_taps * dst_state_elem_size; + uint8_t * st_out_vtcm = dst_state_f16 ? (uint8_t *) hist : (uint8_t *) state_raw; + dma_queue_push(dma_q, dma_make_data(st_out_ddr, st_out_vtcm), st_out_sz, st_out_sz, st_out_sz, 1); + } + + dma_queue_flush(dma_q); + } + } + + FARF(HIGH, "ssm-conv-token-major %d/%d: (%u:%u) d_conv=%u n_t=%u n_s=%u\n", + ith, nth, ir0, ir1, d_conv, n_t, n_s); +} + int op_ssm_conv_f32(struct htp_ops_context * octx) { - const struct htp_tensor * src0 = octx->src[0]; - const struct htp_tensor * src1 = octx->src[1]; - const struct htp_tensor * dst = octx->dst; + const struct htp_tensor * src0 = octx->src[0]; + const struct htp_tensor * src2 = octx->src[2]; + const struct htp_tensor * dst = octx->dsts[0]; + const struct htp_tensor * dst_state = octx->dsts[1]; const struct htp_ssm_conv_kernel_params * kparams = (const struct htp_ssm_conv_kernel_params *) octx->kernel_params; @@ -566,10 +1524,10 @@ int op_ssm_conv_f32(struct htp_ops_context * octx) { uint32_t nrows = kparams->d_inner; if (octx->ctx->mdev.count > 1) { - const uint32_t elems_per_chunk = VLEN_FP32; + const uint32_t elems_per_chunk = (dst->type == HTP_TYPE_F16) ? VLEN_FP16 : VLEN_FP32; const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( kparams->d_inner, - htp_tensor_mdev_data_aligned(dst) ? elems_per_chunk : 0, + elems_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div @@ -589,34 +1547,107 @@ int op_ssm_conv_f32(struct htp_ops_context * octx) { const uint32_t n_hvx = octx->n_hvx; const uint32_t raw_rpt = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div); const uint32_t d_inner_per_hvx = hex_round_up(raw_rpt, VLEN_FP32); + const size_t src0_elem_size = (src0->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + const size_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); struct htp_ssm_conv_vtcm_layout L; - htp_ssm_conv_vtcm_layout_build(&L, d_inner_per_hvx, kparams->d_conv, kparams->n_t, kparams->d_inner_tile, n_hvx); + if (kparams->token_major) { + const size_t x_elem_size = (src2->type == HTP_TYPE_F16) ? sizeof(__fp16) : sizeof(float); + htp_ssm_conv_token_vtcm_layout_build(&L, d_inner_per_hvx, kparams->d_conv, kparams->n_t_tile, + kparams->d_inner_tile, n_hvx, x_elem_size, dst_elem_size); + } else { + htp_ssm_conv_vtcm_layout_build(&L, d_inner_per_hvx, kparams->d_conv, kparams->n_t, + kparams->d_inner_tile, n_hvx, src0_elem_size); + } uint8_t * const base = (uint8_t *) octx->ctx->vtcm_base; - octx->src0_spad.size_per_hvx = L.src0_bytes_per_hvx; - octx->src1_spad.size_per_hvx = L.src1_bytes_per_hvx; - octx->dst_spad.size_per_hvx = L.dst_bytes_per_hvx; + const bool src0_f16 = (src0->type == HTP_TYPE_F16); + const bool dst_f16 = (dst->type == HTP_TYPE_F16); + const bool apply_silu = kparams->silu != 0; + + if (kparams->token_major) { + const bool x_f16 = (src2->type == HTP_TYPE_F16); + const bool dst_st_f16 = (dst_state && dst_state->type == HTP_TYPE_F16); + const bool is_d4 = (kparams->d_conv == 4); + + htp_ssm_conv_token_step_fn_t token_step_fn; + if (is_d4) { + if (x_f16 && dst_f16) { + token_step_fn = apply_silu ? hvx_ssm_conv_token_4_f16_f16_silu : hvx_ssm_conv_token_4_f16_f16; + } else if (x_f16 && !dst_f16) { + token_step_fn = apply_silu ? hvx_ssm_conv_token_4_f16_f32_silu : hvx_ssm_conv_token_4_f16_f32; + } else if (!x_f16 && dst_f16) { + token_step_fn = apply_silu ? hvx_ssm_conv_token_4_f32_f16_silu : hvx_ssm_conv_token_4_f32_f16; + } else { + token_step_fn = apply_silu ? hvx_ssm_conv_token_4_f32_f32_silu : hvx_ssm_conv_token_4_f32_f32; + } + } else { + if (x_f16 && dst_f16) { + token_step_fn = apply_silu ? hvx_ssm_conv_token_gen_f16_f16_silu : hvx_ssm_conv_token_gen_f16_f16; + } else if (x_f16 && !dst_f16) { + token_step_fn = apply_silu ? hvx_ssm_conv_token_gen_f16_f32_silu : hvx_ssm_conv_token_gen_f16_f32; + } else if (!x_f16 && dst_f16) { + token_step_fn = apply_silu ? hvx_ssm_conv_token_gen_f32_f16_silu : hvx_ssm_conv_token_gen_f32_f16; + } else { + token_step_fn = apply_silu ? hvx_ssm_conv_token_gen_f32_f32_silu : hvx_ssm_conv_token_gen_f32_f32; + } + } - octx->src0_spad.size = L.src0_bytes; - octx->src1_spad.size = L.src1_bytes; - octx->dst_spad.size = L.dst_bytes; + const htp_ssm_conv_state_unpack_fn_t state_unpack_fn = + src0_f16 ? ssm_conv_state_unpack_f16_nat : ssm_conv_state_unpack_f32_nat; + + const htp_ssm_conv_state_pack_fn_t state_pack_fn = + dst_st_f16 ? ssm_conv_state_pack_f16_nat : ssm_conv_state_pack_f32_nat; + + struct htp_ssm_conv_context scctx = { + .octx = octx, + .kparams = kparams, + .layout = L, + .vtcm_base = base, + .nrows_per_hvx = d_inner_per_hvx, + .d_inner_tile = kparams->d_inner_tile, + .row_start = row_start, + .nrows = nrows, + .token_step_fn = token_step_fn, + .state_unpack_fn = state_unpack_fn, + .state_pack_fn = state_pack_fn, + }; + + work_queue_run(octx->ctx->hvx_queue, ssm_conv_thread_token_major, &scctx, n_hvx); + return HTP_STATUS_OK; + } + + const bool raw_dot = (kparams->d_conv == 4) && (nrows % VLEN_FP32 == 0); - octx->src0_spad.data = VTCM_LAYOUT_PTR(uint8_t, base, L.off_src0); - octx->src1_spad.data = VTCM_LAYOUT_PTR(uint8_t, base, L.off_src1); - octx->dst_spad.data = VTCM_LAYOUT_PTR(uint8_t, base, L.off_dst); - octx->src0_spad.src = NULL; - octx->src1_spad.src = NULL; - octx->dst_spad.src = NULL; + htp_ssm_conv_decode_dot_fn_t decode_dot_fn; + if (raw_dot) { + decode_dot_fn = src0_f16 ? ssm_conv_decode_dot_4_f16 : ssm_conv_decode_dot_4_f32; + } else { + decode_dot_fn = src0_f16 ? ssm_conv_decode_dot_gen_f16 : ssm_conv_decode_dot_gen_f32; + } + + htp_ssm_conv_epilogue_fn_t epilogue_fn; + if (apply_silu) { + epilogue_fn = dst_f16 ? ssm_conv_epilogue_silu_f16 : ssm_conv_epilogue_silu_f32; + } else { + epilogue_fn = dst_f16 ? ssm_conv_epilogue_f16 : ssm_conv_epilogue_f32; + } struct htp_ssm_conv_context scctx = { - .octx = octx, - .kparams = kparams, - .nrows_per_hvx = d_inner_per_hvx, - .d_inner_tile = kparams->d_inner_tile, - .row_start = row_start, - .nrows = nrows, + .octx = octx, + .kparams = kparams, + .layout = L, + .vtcm_base = base, + .nrows_per_hvx = d_inner_per_hvx, + .d_inner_tile = kparams->d_inner_tile, + .row_start = row_start, + .nrows = nrows, + .raw_dot = raw_dot, + .decode_dot_fn = decode_dot_fn, + .transpose_block_fn = src0_f16 ? hvx_ssm_conv_transpose_block_f16 : hvx_ssm_conv_transpose_block, + .prefill_dot_fn = (kparams->d_conv == 4) ? hvx_ssm_conv_prefill_dot_block_4 : hvx_ssm_conv_prefill_dot_block_gen, + .epilogue_fn = epilogue_fn, }; FARF(HIGH, "ssm-conv-f32: (%ux%ux%ux%u) x (%ux%ux%ux%u) -> (%ux%ux%ux%u) : mode %s\n", @@ -639,6 +1670,7 @@ int op_ssm_conv(struct htp_ops_context * octx) { switch (dst->type) { case HTP_TYPE_F32: + case HTP_TYPE_F16: return op_ssm_conv_f32(octx); default: return HTP_STATUS_NO_SUPPORT; diff --git a/ggml/src/ggml-hexagon/htp/ssm-conv.h b/ggml/src/ggml-hexagon/htp/ssm-conv.h index 7c3f3041ffdf..97a49c59f82e 100644 --- a/ggml/src/ggml-hexagon/htp/ssm-conv.h +++ b/ggml/src/ggml-hexagon/htp/ssm-conv.h @@ -18,6 +18,9 @@ struct htp_ssm_conv_kernel_params { uint32_t vtcm_size; uint32_t silu; + uint32_t token_major; + uint32_t n_t_tile; + uint32_t n_t_blocks; struct fastdiv_values div_d_inner_tile; }; @@ -35,13 +38,21 @@ struct htp_ssm_conv_vtcm_layout { size_t dst_bytes; }; +static inline size_t htp_ssm_conv_raw_stride_bytes(uint32_t ncs, size_t src0_elem_size) { + if (src0_elem_size == 2) { + return (size_t) hex_round_up(ncs, 2) * 2 + sizeof(float); + } + return (size_t) ncs * sizeof(float) + sizeof(float); +} + static inline void htp_ssm_conv_vtcm_layout_build( struct htp_ssm_conv_vtcm_layout * L, uint32_t d_inner_per_hvx, uint32_t d_conv, uint32_t n_t, uint32_t d_inner_tile, - uint32_t n_hvx + uint32_t n_hvx, + size_t src0_elem_size ) { const size_t src1_raw_bytes = hex_round_up((size_t) d_inner_per_hvx * d_conv * sizeof(float), 128) + 128; const size_t src1_T_bytes = hex_round_up((size_t) d_conv * d_inner_per_hvx * sizeof(float), 128); @@ -49,13 +60,14 @@ static inline void htp_ssm_conv_vtcm_layout_build( L->src1_bytes_per_hvx = src1_raw_bytes + src1_T_bytes; if (n_t == 1) { - const size_t src0_tile_raw_bytes = hex_round_up((size_t) d_inner_tile * d_conv * sizeof(float), 128); + const size_t raw_stride_bytes = (src0_elem_size == 2) ? ((size_t) hex_round_up(d_conv, 2) * 2) : ((size_t) d_conv * sizeof(float)); + const size_t src0_tile_raw_bytes = hex_round_up((size_t) d_inner_tile * raw_stride_bytes, 128); const size_t src0_T_bytes = hex_round_up((size_t) d_conv * d_inner_tile * sizeof(float), 128); L->src0_bytes_per_hvx = 2 * src0_tile_raw_bytes + src0_T_bytes; L->dst_bytes_per_hvx = 2 * hex_round_up((size_t) d_inner_tile * sizeof(float), 128); } else { const uint32_t ncs = d_conv - 1 + n_t; - const size_t raw_stride_bytes = ncs * sizeof(float) + sizeof(float); + const size_t raw_stride_bytes = htp_ssm_conv_raw_stride_bytes(ncs, src0_elem_size); const size_t src0_block_T = hex_round_up((size_t) ncs * 32 * sizeof(float), 128); const size_t src0_tile_raw = hex_round_up((size_t) d_inner_tile * raw_stride_bytes, 128); L->src0_bytes_per_hvx = 2 * src0_tile_raw + src0_block_T; @@ -73,6 +85,43 @@ static inline void htp_ssm_conv_vtcm_layout_build( L->total_bytes = off; } +static inline void htp_ssm_conv_token_vtcm_layout_build( + struct htp_ssm_conv_vtcm_layout * L, + uint32_t d_inner_per_hvx, + uint32_t d_conv, + uint32_t n_t_tile, + uint32_t d_inner_tile, + uint32_t n_hvx, + size_t x_elem_size, + size_t dst_elem_size +) { + const uint32_t w_stride = hex_round_up(d_inner_per_hvx, 64); + const uint32_t c_stride = hex_round_up(d_inner_tile, 64); + const size_t src1_raw = hex_round_up((size_t) w_stride * d_conv * sizeof(float), 128) + 128; + const size_t src1_T = hex_round_up((size_t) d_conv * w_stride * sizeof(float), 128); + const size_t x_row_stride = hex_round_up((size_t) c_stride * x_elem_size, 128); + const size_t x_tile_bytes = hex_round_up((size_t) n_t_tile * x_row_stride, 128); + const size_t state_raw = hex_round_up((size_t) c_stride * (d_conv - 1) * sizeof(float), 128) + 128; + const size_t hist_bytes = hex_round_up((size_t) (d_conv - 1) * c_stride * sizeof(float), 128); + const size_t d_row_stride = hex_round_up((size_t) c_stride * dst_elem_size, 128); + const size_t d_tile_bytes = hex_round_up((size_t) n_t_tile * d_row_stride, 128); + const size_t strip_bytes = hex_round_up((size_t) n_t_tile * 64 * sizeof(float), 128); + + L->src1_bytes_per_hvx = (src1_raw + src1_T) | 128; + L->src0_bytes_per_hvx = (2 * x_tile_bytes + state_raw + hist_bytes) | 128; + L->dst_bytes_per_hvx = (2 * d_tile_bytes + strip_bytes) | 128; + + L->src0_bytes = L->src0_bytes_per_hvx * n_hvx; + L->src1_bytes = L->src1_bytes_per_hvx * n_hvx; + L->dst_bytes = L->dst_bytes_per_hvx * n_hvx; + + size_t off = 0; + VTCM_LAYOUT_ALLOC(off, off_src0, L->src0_bytes); + VTCM_LAYOUT_ALLOC(off, off_src1, L->src1_bytes); + VTCM_LAYOUT_ALLOC(off, off_dst, L->dst_bytes); + L->total_bytes = off; +} + #if defined(__cplusplus) static_assert(sizeof(struct htp_ssm_conv_kernel_params) <= 128, "htp_ssm_conv_kernel_params is too large for kernel_params blob"); #else diff --git a/ggml/src/ggml-hexagon/htp/ssm-scan-ops.c b/ggml/src/ggml-hexagon/htp/ssm-scan-ops.c index 6ba2d4112dda..65892572c1c4 100644 --- a/ggml/src/ggml-hexagon/htp/ssm-scan-ops.c +++ b/ggml/src/ggml-hexagon/htp/ssm-scan-ops.c @@ -1,4 +1,5 @@ #include +#include #include #include "hvx-exp.h" @@ -44,6 +45,7 @@ struct htp_ssm_scan_context { struct htp_ops_context * octx; const struct htp_ssm_scan_kernel_params * kparams; struct htp_ssm_scan_vtcm_layout layout; + const int32_t * ids_data; uint32_t unit_start; uint32_t nunits; uint32_t units_per_hvx; @@ -355,8 +357,7 @@ static inline void ssm_scan_decode_push_inputs( const struct htp_tensor * A = octx->src[3]; const struct htp_tensor * B = octx->src[4]; const struct htp_tensor * C = octx->src[5]; - const struct htp_tensor * ids = octx->src[6]; - const int32_t id = ((const int32_t *) (uintptr_t) ids->data)[unit->q]; + const int32_t id = scctx->ids_data[unit->q]; const size_t state_row_bytes = (size_t) kparams->d_state * sizeof(float); const size_t state_row_stride = layout->state_row_stride; const size_t x_bytes = (size_t) unit->nrows * sizeof(float); @@ -498,7 +499,6 @@ static inline void ssm_scan_prefill_push_fetch( const struct htp_tensor * A = octx->src[3]; const struct htp_tensor * B = octx->src[4]; const struct htp_tensor * C = octx->src[5]; - const struct htp_tensor * ids = octx->src[6]; const struct htp_ssm_scan_unit unit = ssm_scan_decode_unit(kparams, unit_index); const uint32_t t0 = c * kparams->token_tile; const uint32_t nt = MIN(kparams->token_tile, kparams->n_tokens - t0); @@ -508,7 +508,7 @@ static inline void ssm_scan_prefill_push_fetch( const size_t row_bytes = (size_t) unit.nrows * sizeof(float); if (c == 0) { - const int32_t id = ((const int32_t *) (uintptr_t) ids->data)[unit.q]; + const int32_t id = scctx->ids_data[unit.q]; const size_t a_bytes = (size_t) kparams->n_a * sizeof(float); const dma_addr_t state_in = s->data + (size_t) id * s->nb[3] + (size_t) unit.head * s->nb[2] + (size_t) unit.row0 * s->nb[1]; const dma_addr_t A_in = A->data + (size_t) unit.head * A->nb[1]; @@ -1484,17 +1484,31 @@ static int op_ssm_scan_f32(struct htp_ops_context * octx) { const struct htp_ssm_scan_kernel_params * kparams = (const struct htp_ssm_scan_kernel_params *) octx->kernel_params; - if (htp_tensor_is_extended(ids)) { - return HTP_STATUS_NO_SUPPORT; + const size_t ids_bytes = hex_round_up(htp_tensor_nbytes(ids), 128); + void * ids_buf = (ids_bytes <= octx->ctx->ddr_spad_size) ? octx->ctx->ddr_spad_base : memalign(128, ids_bytes); + if (!ids_buf) { + return HTP_STATUS_INTERNAL_ERR; + } + if (htp_tensor_read(&octx->ctx->main_th, ids_buf, ids_bytes, ids) == 0) { + if (ids_buf != octx->ctx->ddr_spad_base) { + free(ids_buf); + } + return HTP_STATUS_INTERNAL_ERR; } - const int32_t * ids_data = (const int32_t *) ids->data; + const int32_t * ids_data = (const int32_t *) ids_buf; for (uint32_t q = 0; q < kparams->n_seqs; ++q) { if (ids_data[q] < 0 || (uint32_t) ids_data[q] >= s->ne[3]) { + if (ids_buf != octx->ctx->ddr_spad_base) { + free(ids_buf); + } return HTP_STATUS_INVAL_PARAMS; } } if (octx->flags & HTP_OPFLAGS_STUB) { + if (ids_buf != octx->ctx->ddr_spad_base) { + free(ids_buf); + } return HTP_STATUS_OK; } @@ -1509,6 +1523,9 @@ static int op_ssm_scan_f32(struct htp_ops_context * octx) { } if (nunits == 0) { + if (ids_buf != octx->ctx->ddr_spad_base) { + free(ids_buf); + } return HTP_STATUS_OK; } @@ -1520,6 +1537,7 @@ static int op_ssm_scan_f32(struct htp_ops_context * octx) { struct htp_ssm_scan_context scctx = { .octx = octx, .kparams = kparams, + .ids_data = ids_data, .unit_start = unit_start, .nunits = nunits, .units_per_hvx = units_per_hvx, @@ -1530,29 +1548,35 @@ static int op_ssm_scan_f32(struct htp_ops_context * octx) { kparams->kernel_type == HTP_SSM_SCAN_KERNEL_HMX ); - octx->n_hvx = n_hvx; - octx->src0_spad.data = octx->ctx->vtcm_base; - octx->src0_spad.size_per_hvx = kparams->vtcm_per_hvx; - octx->src0_spad.size = kparams->vtcm_size; + octx->n_hvx = n_hvx; + int status = HTP_STATUS_OK; switch (kparams->kernel_type) { case HTP_SSM_SCAN_KERNEL_HVX_DECODE: work_queue_run(octx->ctx->hvx_queue, ssm_scan_thread_f32_decode, &scctx, n_hvx); + status = octx->status; break; case HTP_SSM_SCAN_KERNEL_HVX_PREFILL: work_queue_run(octx->ctx->hvx_queue, ssm_scan_thread_f32_prefill, &scctx, n_hvx); + status = octx->status; break; case HTP_SSM_SCAN_KERNEL_HMX: ssm_scan_run_hmx_chunked(&scctx); + status = octx->status; break; default: - return HTP_STATUS_NO_SUPPORT; + status = HTP_STATUS_NO_SUPPORT; + break; + } + + if (ids_buf != octx->ctx->ddr_spad_base) { + free(ids_buf); } - return octx->status; + return status; } int op_ssm_scan(struct htp_ops_context * octx) { diff --git a/ggml/src/ggml-hexagon/htp/sum-rows-ops.c b/ggml/src/ggml-hexagon/htp/sum-rows-ops.c index b3f8a7090902..c226c1cea0f7 100644 --- a/ggml/src/ggml-hexagon/htp/sum-rows-ops.c +++ b/ggml/src/ggml-hexagon/htp/sum-rows-ops.c @@ -1,7 +1,3 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include @@ -9,6 +5,7 @@ #include #include "dma-queue.h" +#include "dma-pipeline.h" #include "hvx-utils.h" #define GGML_COMMON_DECL_C @@ -20,89 +17,329 @@ #include "htp-tensor.h" #include "sum-rows-ops.h" -#define sum_rows_preamble \ - const struct htp_tensor *src0 = octx->src[0]; \ - const struct htp_tensor *dst = octx->dst; \ - \ - const uint32_t ne00 = src0->ne[0]; \ - const uint32_t ne01 = src0->ne[1]; \ - const uint32_t ne02 = src0->ne[2]; \ - const uint32_t ne03 = src0->ne[3]; \ - \ - const uint32_t nb00 = src0->nb[0]; \ - const uint32_t nb01 = src0->nb[1]; \ - const uint32_t nb02 = src0->nb[2]; \ - const uint32_t nb03 = src0->nb[3]; \ - \ - const uint32_t ne0 = dst->ne[0]; \ - const uint32_t ne1 = dst->ne[1]; \ - const uint32_t ne2 = dst->ne[2]; \ - const uint32_t ne3 = dst->ne[3]; \ - \ - const uint32_t nb0 = dst->nb[0]; \ - const uint32_t nb1 = dst->nb[1]; \ - const uint32_t nb2 = dst->nb[2]; \ - const uint32_t nb3 = dst->nb[3]; \ +#define sum_rows_preamble \ + const struct htp_tensor *src0 = octx->src[0]; \ + const struct htp_tensor *dst = octx->dst; \ + \ + const uint32_t __attribute__((unused)) ne00 = src0->ne[0]; \ + const uint32_t __attribute__((unused)) ne01 = src0->ne[1]; \ + const uint32_t __attribute__((unused)) ne02 = src0->ne[2]; \ + const uint32_t __attribute__((unused)) ne03 = src0->ne[3]; \ + \ + const uint32_t __attribute__((unused)) nb00 = src0->nb[0]; \ + const uint32_t __attribute__((unused)) nb01 = src0->nb[1]; \ + const uint32_t __attribute__((unused)) nb02 = src0->nb[2]; \ + const uint32_t __attribute__((unused)) nb03 = src0->nb[3]; \ + \ + const uint32_t __attribute__((unused)) ne0 = dst->ne[0]; \ + const uint32_t __attribute__((unused)) ne1 = dst->ne[1]; \ + const uint32_t __attribute__((unused)) ne2 = dst->ne[2]; \ + const uint32_t __attribute__((unused)) ne3 = dst->ne[3]; \ + \ + const uint32_t __attribute__((unused)) nb0 = dst->nb[0]; \ + const uint32_t __attribute__((unused)) nb1 = dst->nb[1]; \ + const uint32_t __attribute__((unused)) nb2 = dst->nb[2]; \ + const uint32_t __attribute__((unused)) nb3 = dst->nb[3]; \ + +typedef void (*sum_rows_compute_fn_t)( + const uint8_t * restrict src, + uint8_t * restrict dst, + uint32_t ne00, + uint32_t nrows, + size_t src_row_stride +); struct sum_rows_context { - struct htp_ops_context * octx; - const uint8_t * src_data; - uint8_t * dst_data; - uint32_t ne00; - size_t src_stride; - size_t dst_stride; - uint32_t rows_per_hvx; - uint32_t total_rows; + struct htp_ops_context * octx; + const struct htp_sum_rows_kernel_params * kparams; + sum_rows_compute_fn_t compute; + dma_addr_t data_src0; + dma_addr_t data_dst; + uint8_t * vtcm_src0; + uint8_t * vtcm_dst; + size_t src0_data_row_size; + size_t src0_row_size_aligned; + size_t src0_vtcm_half_size; + size_t dst_vtcm_half_size; + size_t vtcm_src0_size_per_hvx; + size_t vtcm_dst_size_per_hvx; + size_t dst_elem_size; + uint32_t row_start; + uint32_t src0_nrows; + uint32_t src0_nrows_per_hvx; + uint32_t block; }; -static void sum_rows_thread_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void *data) { - const struct sum_rows_context * smctx = (const struct sum_rows_context *) data; +static inline size_t sum_rows_row_offset( + uint32_t ir, + uint32_t ne1, + uint32_t ne2, + const struct fastdiv_values * div_ne1, + const struct fastdiv_values * div_ne2, + const struct fastdiv_values * div_ne12, + size_t nb1, + size_t nb2, + size_t nb3 +) { + const uint32_t i1 = fastmodulo(ir, ne1, div_ne1); + const uint32_t ir_div_ne1 = fastdiv(ir, div_ne1); + const uint32_t i2 = fastmodulo(ir_div_ne1, ne2, div_ne2); + const uint32_t i3 = fastdiv(ir, div_ne12); + return (size_t) i1 * nb1 + (size_t) i2 * nb2 + (size_t) i3 * nb3; +} - const uint32_t rows_per_hvx = smctx->rows_per_hvx; - const uint32_t total_rows = smctx->total_rows; +static inline uint32_t sum_rows_block_size( + uint32_t ir, + uint32_t end_row, + uint32_t block, + bool contig, + uint32_t ne1, + const struct fastdiv_values * div_ne1 +) { + uint32_t limit = MIN(block, end_row - ir); + if (!contig) { + const uint32_t slice_end = (fastdiv(ir, div_ne1) + 1) * ne1; + limit = MIN(limit, slice_end - ir); + } + return limit; +} - const uint32_t start_row = rows_per_hvx * ith; - const uint32_t end_row = MIN(start_row + rows_per_hvx, total_rows); +static inline HVX_Vector hvx_vec_clamp_f16_f32(HVX_Vector v_sf) { + const HVX_Vector max_f16 = hvx_vec_splat_f32(65504.0f); + const HVX_Vector min_f16 = hvx_vec_splat_f32(-65504.0f); + return Q6_Vsf_vmax_VsfVsf(min_f16, Q6_Vsf_vmin_VsfVsf(max_f16, v_sf)); +} - if (start_row >= end_row) { - return; +static inline HVX_Vector hvx_row_reduce_sum_f32(const uint8_t * restrict src, uint32_t num_elems) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + + const uint32_t nvec = num_elems / VLEN_FP32; + const uint32_t nloe = num_elems % VLEN_FP32; + + HVX_Vector acc = Q6_V_vzero(); + uint32_t i = 0; + + #pragma unroll(4) + for (; i < nvec; i++) { + acc = Q6_Vqf32_vadd_Vqf32Vsf(acc, vsrc[i]); + } + if (nloe) { + const HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * sizeof(float)); + const HVX_Vector v = Q6_V_vand_QV(bmask, vsrc[i]); + acc = Q6_Vqf32_vadd_Vqf32Vsf(acc, v); } - const size_t src_stride = smctx->src_stride; - const size_t dst_stride = smctx->dst_stride; - const uint32_t ne00 = smctx->ne00; + return Q6_Vsf_equals_Vqf32(hvx_vec_reduce_sum_qf32(acc)); +} + +static inline HVX_Vector hvx_row_reduce_sum_f16(const uint8_t * restrict src, uint32_t num_elems) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; - const float * restrict src_th = (const float *) (smctx->src_data + (start_row * src_stride)); - float * restrict dst_th = (float *) (smctx->dst_data + (start_row * dst_stride)); + const uint32_t nvec = num_elems / VLEN_FP16; + const uint32_t nloe = num_elems % VLEN_FP16; - // Calculate actual number of rows for this thread - const uint32_t n_rows = end_row - start_row; + HVX_Vector acc = Q6_V_vzero(); + uint32_t i = 0; - struct htp_thread_trace * tr = th->trace; - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) start_row); + #pragma unroll(2) + for (; i < nvec; i++) { + const HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(vsrc[i]); + acc = Q6_Vqf32_vadd_Vqf32Vsf(acc, Q6_V_lo_W(p)); + acc = Q6_Vqf32_vadd_Vqf32Vsf(acc, Q6_V_hi_W(p)); + } + if (nloe) { + const HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * sizeof(__fp16)); + const HVX_Vector v = Q6_V_vand_QV(bmask, vsrc[i]); + const HVX_VectorPair p = hvx_vec_f16_to_f32_shuff(v); + acc = Q6_Vqf32_vadd_Vqf32Vsf(acc, Q6_V_lo_W(p)); + acc = Q6_Vqf32_vadd_Vqf32Vsf(acc, Q6_V_hi_W(p)); + } - for (uint32_t ir = 0; ir < n_rows; ir++) { - const float * restrict src_local = (const float *) ((const uint8_t *) src_th + ir * src_stride); - float * restrict dst_local = (float *) ((uint8_t *) dst_th + ir * dst_stride); + return Q6_Vsf_equals_Vqf32(hvx_vec_reduce_sum_qf32(acc)); +} - if (ir + 1 < n_rows) { - hex_l2fetch((const uint8_t *) src_local + src_stride, src_stride, src_stride, 1); - } +static void __attribute__((noinline)) sum_rows_block_f32_f32( + const uint8_t * restrict src, + uint8_t * restrict dst, + const uint32_t ne00, + const uint32_t nrows, + const size_t src_row_stride +) { + HVX_Vector * restrict v_dst = (HVX_Vector *) dst; + for (uint32_t b = 0; b < nrows; ++b) { + const HVX_Vector sum_sf = hvx_row_reduce_sum_f32(src + b * src_row_stride, ne00); + const uint32_t b_off = (b & 31u) * sizeof(float); + const HVX_VectorPred b_mask = Q6_Q_vsetq_R(b_off); + const HVX_VectorPred e_mask = Q6_Q_vsetq2_R(b_off + sizeof(float)); + Q6_vmem_QnRIV(Q6_Q_or_QQn(b_mask, e_mask), &v_dst[b >> 5], sum_sf); + } +} - *dst_local = hvx_reduce_sum_f32((const uint8_t *) src_local, ne00); +static void __attribute__((noinline)) sum_rows_block_f32_f16( + const uint8_t * restrict src, + uint8_t * restrict dst, + const uint32_t ne00, + const uint32_t nrows, + const size_t src_row_stride +) { + HVX_Vector * restrict v_dst = (HVX_Vector *) dst; + for (uint32_t b = 0; b < nrows; ++b) { + const HVX_Vector sum_sf = hvx_vec_clamp_f16_f32(hvx_row_reduce_sum_f32(src + b * src_row_stride, ne00)); + const HVX_Vector sum_hf = hvx_vec_f32_to_f16_shuff(sum_sf, sum_sf); + const uint32_t b_off = (b & 63u) * sizeof(__fp16); + const HVX_VectorPred b_mask = Q6_Q_vsetq_R(b_off); + const HVX_VectorPred e_mask = Q6_Q_vsetq2_R(b_off + sizeof(__fp16)); + Q6_vmem_QnRIV(Q6_Q_or_QQn(b_mask, e_mask), &v_dst[b >> 6], sum_hf); } +} - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) start_row); +static void __attribute__((noinline)) sum_rows_block_f16_f32( + const uint8_t * restrict src, + uint8_t * restrict dst, + const uint32_t ne00, + const uint32_t nrows, + const size_t src_row_stride +) { + HVX_Vector * restrict v_dst = (HVX_Vector *) dst; + for (uint32_t b = 0; b < nrows; ++b) { + const HVX_Vector sum_sf = hvx_row_reduce_sum_f16(src + b * src_row_stride, ne00); + const uint32_t b_off = (b & 31u) * sizeof(float); + const HVX_VectorPred b_mask = Q6_Q_vsetq_R(b_off); + const HVX_VectorPred e_mask = Q6_Q_vsetq2_R(b_off + sizeof(float)); + Q6_vmem_QnRIV(Q6_Q_or_QQn(b_mask, e_mask), &v_dst[b >> 5], sum_sf); + } } -int op_sum_rows(struct htp_ops_context * octx) { +static void __attribute__((noinline)) sum_rows_block_f16_f16( + const uint8_t * restrict src, + uint8_t * restrict dst, + const uint32_t ne00, + const uint32_t nrows, + const size_t src_row_stride +) { + HVX_Vector * restrict v_dst = (HVX_Vector *) dst; + for (uint32_t b = 0; b < nrows; ++b) { + const HVX_Vector sum_sf = hvx_vec_clamp_f16_f32(hvx_row_reduce_sum_f16(src + b * src_row_stride, ne00)); + const HVX_Vector sum_hf = hvx_vec_f32_to_f16_shuff(sum_sf, sum_sf); + const uint32_t b_off = (b & 63u) * sizeof(__fp16); + const HVX_VectorPred b_mask = Q6_Q_vsetq_R(b_off); + const HVX_VectorPred e_mask = Q6_Q_vsetq2_R(b_off + sizeof(__fp16)); + Q6_vmem_QnRIV(Q6_Q_or_QQn(b_mask, e_mask), &v_dst[b >> 6], sum_hf); + } +} + +struct sum_rows_pipe_state { + dma_addr_t data_src; + dma_addr_t data_dst; + sum_rows_compute_fn_t compute; + size_t src0_data_row_size; + size_t src0_row_size_aligned; + size_t dst_elem_size; + uint32_t ne00; + uint32_t ne01; + uint32_t ne02; + uint32_t nb01; + uint32_t nb02; + uint32_t nb03; + uint32_t block; + bool src0_contig; + const struct fastdiv_values * div_ne01; + const struct fastdiv_values * div_ne02; + const struct fastdiv_values * div_ne012; + uint32_t ir; + uint32_t ir_end; +}; + +static bool sum_rows_next_task(void * ctx, struct dma_pipe_task * task) { + struct sum_rows_pipe_state * s = (struct sum_rows_pipe_state *) ctx; + if (s->ir >= s->ir_end) { + return false; + } + const uint32_t block_size = sum_rows_block_size(s->ir, s->ir_end, s->block, s->src0_contig, s->ne01, s->div_ne01); + task->row = s->ir; + task->off = 0; + task->len = block_size; + task->aux = 0; + s->ir += block_size; + return true; +} + +static void sum_rows_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct sum_rows_pipe_state * s = (struct sum_rows_pipe_state *) ctx; + const size_t src0_off = s->src0_contig ? ((size_t) task->row * s->nb01) : + sum_rows_row_offset(task->row, s->ne01, s->ne02, s->div_ne01, s->div_ne02, s->div_ne012, s->nb01, s->nb02, s->nb03); + dma_queue_push(dma_q, dma_make_data(in_spad, s->data_src + src0_off), + s->src0_row_size_aligned, s->nb01, s->src0_data_row_size, task->len); +} + +static void sum_rows_pipe_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct sum_rows_pipe_state * s = (struct sum_rows_pipe_state *) ctx; + s->compute((const uint8_t *) in_spad, (uint8_t *) out_spad, s->ne00, task->len, s->src0_row_size_aligned); +} + +static void sum_rows_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) { + struct sum_rows_pipe_state * s = (struct sum_rows_pipe_state *) ctx; + const size_t dst_off = (size_t) task->row * s->dst_elem_size; + const size_t dst_bytes = (size_t) task->len * s->dst_elem_size; + dma_queue_push(dma_q, dma_make_data(s->data_dst + dst_off, out_spad), + dst_bytes, dst_bytes, dst_bytes, 1); +} + +static void sum_rows_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; + const struct sum_rows_context * smctx = (const struct sum_rows_context *) data; + struct htp_ops_context * octx = smctx->octx; + sum_rows_preamble; - if (octx->src[0]->type != HTP_TYPE_F32) { - return HTP_STATUS_NO_SUPPORT; + const uint32_t src0_nrows_per_hvx = smctx->src0_nrows_per_hvx; + const uint32_t src0_nrows = smctx->src0_nrows; + const uint32_t src0_start_row = smctx->row_start + src0_nrows_per_hvx * ith; + const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, smctx->row_start + src0_nrows); + + if (src0_start_row >= src0_end_row) { + return; } - if (htp_tensor_is_extended(src0) || htp_tensor_is_extended(dst)) { + uint8_t * src0_vtcm_data = smctx->vtcm_src0 + (ith * smctx->vtcm_src0_size_per_hvx); + uint8_t * dst_vtcm_data = smctx->vtcm_dst + (ith * smctx->vtcm_dst_size_per_hvx); + void * in_buf[2] = { src0_vtcm_data, src0_vtcm_data + smctx->src0_vtcm_half_size }; + void * out_buf[2] = { dst_vtcm_data, dst_vtcm_data + smctx->dst_vtcm_half_size }; + + struct sum_rows_pipe_state s = { + .data_src = smctx->data_src0, + .data_dst = smctx->data_dst, + .compute = smctx->compute, + .src0_data_row_size = smctx->src0_data_row_size, + .src0_row_size_aligned = smctx->src0_row_size_aligned, + .dst_elem_size = smctx->dst_elem_size, + .ne00 = ne00, + .ne01 = ne01, + .ne02 = ne02, + .nb01 = nb01, + .nb02 = nb02, + .nb03 = nb03, + .block = smctx->block, + .src0_contig = smctx->kparams->src0_contig, + .div_ne01 = &smctx->kparams->div_ne01, + .div_ne02 = &smctx->kparams->div_ne02, + .div_ne012 = &smctx->kparams->div_ne012, + .ir = src0_start_row, + .ir_end = src0_end_row, + }; + + dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, + sum_rows_next_task, sum_rows_push_in, sum_rows_pipe_compute, sum_rows_push_out); +} + +int op_sum_rows(struct htp_ops_context * octx) { + sum_rows_preamble; + + const bool src0_f16 = (src0->type == HTP_TYPE_F16); + const bool dst_f16 = (dst->type == HTP_TYPE_F16); + + if ((src0->type != HTP_TYPE_F32 && src0->type != HTP_TYPE_F16) || + (dst->type != HTP_TYPE_F32 && dst->type != HTP_TYPE_F16)) { return HTP_STATUS_NO_SUPPORT; } @@ -113,16 +350,17 @@ int op_sum_rows(struct htp_ops_context * octx) { return HTP_STATUS_INVAL_PARAMS; } - const uint32_t src0_nrows = ne01 * ne02 * ne03; - const size_t dst_data_row_size = dst->ne[0] * sizeof(float); + const size_t src0_elem_size = src0_f16 ? sizeof(__fp16) : sizeof(float); + const size_t dst_elem_size = dst_f16 ? sizeof(__fp16) : sizeof(float); + const size_t src0_data_row_size = (size_t) ne00 * src0_elem_size; + const uint32_t src0_nrows = ne01 * ne02 * ne03; uint32_t row_start = 0; uint32_t nrows = src0_nrows; if (octx->ctx->mdev.count > 1) { - uint32_t rows_per_chunk = 0; - htp_tensor_mdev_rows_per_chunk(dst, sizeof(float), (uint32_t) dst_data_row_size, &rows_per_chunk); - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( + src0_nrows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); row_start = range.start; nrows = range.count; } @@ -134,31 +372,133 @@ int op_sum_rows(struct htp_ops_context * octx) { const uint32_t n_hvx = octx->n_hvx; const uint32_t rows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div); + struct htp_sum_rows_vtcm_layout layout; + htp_sum_rows_vtcm_layout_build(&layout, src0_data_row_size, dst_elem_size, kparams->block, n_hvx); + + if (octx->ctx->vtcm_size < layout.total_bytes) { + FARF(ERROR, "sum_rows: VTCM size %zu is too small, needed %zu\n", octx->ctx->vtcm_size, layout.total_bytes); + return HTP_STATUS_VTCM_TOO_SMALL; + } + + sum_rows_compute_fn_t compute = NULL; + if (!src0_f16 && !dst_f16) { + compute = sum_rows_block_f32_f32; + } else if (!src0_f16 && dst_f16) { + compute = sum_rows_block_f32_f16; + } else if (src0_f16 && !dst_f16) { + compute = sum_rows_block_f16_f32; + } else { + compute = sum_rows_block_f16_f16; + } + + uint8_t * vtcm_base = octx->ctx->vtcm_base; + struct sum_rows_context smctx = { - .octx = octx, - .src_data = (const uint8_t *) src0->data + row_start * nb01, - .dst_data = (uint8_t *) dst->data + row_start * nb1, - .ne00 = ne00, - .src_stride = nb01, - .dst_stride = nb1, - .rows_per_hvx = rows_per_hvx, - .total_rows = nrows, + .octx = octx, + .kparams = kparams, + .compute = compute, + .data_src0 = (dma_addr_t) src0->data, + .data_dst = (dma_addr_t) dst->data, + .vtcm_src0 = vtcm_base + layout.src0_off, + .vtcm_dst = vtcm_base + layout.dst_off, + .src0_data_row_size = src0_data_row_size, + .src0_row_size_aligned = layout.src0_row_size_aligned, + .src0_vtcm_half_size = layout.src0_half_bytes, + .dst_vtcm_half_size = layout.dst_half_bytes, + .vtcm_src0_size_per_hvx = layout.src0_bytes_per_hvx, + .vtcm_dst_size_per_hvx = layout.dst_bytes_per_hvx, + .dst_elem_size = dst_elem_size, + .row_start = row_start, + .src0_nrows = nrows, + .src0_nrows_per_hvx = rows_per_hvx, + .block = kparams->block, }; - work_queue_run(octx->ctx->hvx_queue, sum_rows_thread_f32, &smctx, n_hvx); + work_queue_run(octx->ctx->hvx_queue, sum_rows_thread, &smctx, n_hvx); return HTP_STATUS_OK; } +static float __attribute__((noinline)) hvx_sum_chunk_f32(const uint8_t * restrict src, uint32_t num_elems) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + + const uint32_t nvec = num_elems / VLEN_FP32; + const uint32_t nloe = num_elems % VLEN_FP32; + + HVX_Vector acc = Q6_V_vzero(); + uint32_t i = 0; + #pragma unroll(4) + for (; i < nvec; i++) { + acc = Q6_Vqf32_vadd_Vqf32Vsf(acc, vsrc[i]); + } + if (nloe) { + const HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * sizeof(float)); + const HVX_Vector v = Q6_V_vand_QV(bmask, vsrc[i]); + acc = Q6_Vqf32_vadd_Vqf32Vsf(acc, v); + } + + return hvx_vec_get_f32(Q6_Vsf_equals_Vqf32(hvx_vec_reduce_sum_qf32(acc))); +} + +static float __attribute__((noinline)) hvx_sum_chunk_f16(const uint8_t * restrict src, uint32_t num_elems) { + return hvx_vec_get_f32(hvx_row_reduce_sum_f16(src, num_elems)); +} + +typedef float (*sum_chunk_fn_t)(const uint8_t * restrict src, uint32_t num_elems); + struct sum_context { struct htp_ops_context * octx; - const float * src_data; + sum_chunk_fn_t sum_chunk; + dma_addr_t data_src0; + uint8_t * vtcm_src0; + size_t src0_elem_size; + size_t chunk_bytes; + size_t src0_bytes_per_hvx; float partial_sums[HTP_MAX_NHVX]; uint32_t total_elems; uint32_t elems_per_hvx; + uint32_t chunk_elems; }; -static void sum_thread_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { +struct sum_pipe_state { + dma_addr_t data_src; + sum_chunk_fn_t sum_chunk; + size_t src0_elem_size; + size_t chunk_bytes; + uint32_t chunk_elems; + uint32_t pos; + uint32_t end; + float sum; +}; + +static bool sum_next_task(void * ctx, struct dma_pipe_task * task) { + struct sum_pipe_state * s = (struct sum_pipe_state *) ctx; + if (s->pos >= s->end) { + return false; + } + const uint32_t cnt = MIN(s->chunk_elems, s->end - s->pos); + task->row = s->pos; + task->off = 0; + task->len = cnt; + task->aux = 0; + s->pos += cnt; + return true; +} + +static void sum_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct sum_pipe_state * s = (struct sum_pipe_state *) ctx; + const size_t nb = (size_t) task->len * s->src0_elem_size; + dma_queue_push(dma_q, dma_make_data(in_spad, s->data_src + (size_t) task->row * s->src0_elem_size), + s->chunk_bytes, nb, nb, 1); +} + +static void sum_pipe_compute(void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct sum_pipe_state * s = (struct sum_pipe_state *) ctx; + s->sum += s->sum_chunk((const uint8_t *) in_spad, task->len); +} + +static void sum_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; struct sum_context * sctx = (struct sum_context *) data; const uint32_t start = sctx->elems_per_hvx * ith; const uint32_t end = MIN(start + sctx->elems_per_hvx, sctx->total_elems); @@ -168,28 +508,31 @@ static void sum_thread_f32(const htp_thread_t * th, unsigned int nth, unsigned i return; } - const uint32_t n = end - start; - const float * src = sctx->src_data + start; - - struct htp_thread_trace * tr = th->trace; - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) start); - - hex_l2fetch_block((const void *) src, n * sizeof(float)); + uint8_t * vtcm_src = sctx->vtcm_src0 + ith * sctx->src0_bytes_per_hvx; + void * in_buf[2] = { vtcm_src, vtcm_src + sctx->chunk_bytes }; + + struct sum_pipe_state s = { + .data_src = sctx->data_src0, + .sum_chunk = sctx->sum_chunk, + .src0_elem_size = sctx->src0_elem_size, + .chunk_bytes = sctx->chunk_bytes, + .chunk_elems = sctx->chunk_elems, + .pos = start, + .end = end, + .sum = 0.0f, + }; - sctx->partial_sums[ith] = hvx_reduce_sum_f32((const uint8_t *) src, n); + dma_pipe_in_run(th->dma_q, th->trace, &s, in_buf, sum_next_task, sum_push_in, sum_pipe_compute); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) start); + sctx->partial_sums[ith] = s.sum; } int op_sum(struct htp_ops_context * octx) { const struct htp_tensor * src0 = octx->src[0]; const struct htp_tensor * dst = octx->dst; - if (src0->type != HTP_TYPE_F32) { - return HTP_STATUS_NO_SUPPORT; - } - - if (htp_tensor_is_extended(src0) || htp_tensor_is_extended(dst)) { + if ((src0->type != HTP_TYPE_F32 && src0->type != HTP_TYPE_F16) || + (dst->type != HTP_TYPE_F32 && dst->type != HTP_TYPE_F16)) { return HTP_STATUS_NO_SUPPORT; } @@ -204,47 +547,228 @@ int op_sum(struct htp_ops_context * octx) { return HTP_STATUS_OK; } + const bool src0_f16 = (src0->type == HTP_TYPE_F16); + const bool dst_f16 = (dst->type == HTP_TYPE_F16); + const size_t src0_elem_size = src0_f16 ? sizeof(__fp16) : sizeof(float); + const size_t dst_elem_size = dst_f16 ? sizeof(__fp16) : sizeof(float); + const uint32_t n_hvx = octx->n_hvx; + + struct htp_sum_vtcm_layout layout; + htp_sum_vtcm_layout_build(&layout, kparams->chunk_elems, src0_elem_size, n_hvx); + if (octx->ctx->vtcm_size < layout.total_bytes) { + FARF(ERROR, "sum: VTCM size %zu is too small, needed %zu\n", octx->ctx->vtcm_size, layout.total_bytes); + return HTP_STATUS_VTCM_TOO_SMALL; + } + + uint8_t * vtcm_base = octx->ctx->vtcm_base; + uint8_t * vtcm_dst = vtcm_base + layout.dst_off; + const uint32_t total_elems = (uint32_t) (src0->ne[0] * src0->ne[1] * src0->ne[2] * src0->ne[3]); if (total_elems == 0) { - ((float *) dst->data)[0] = 0.0f; + hvx_vmem(vtcm_dst) = Q6_V_vzero(); + dma_sync_write(octx->ctx->dma[0], dst->data, vtcm_dst, dst_elem_size); return HTP_STATUS_OK; } - const uint32_t n_hvx = octx->n_hvx; - const uint32_t elems_per_hvx = kparams->elems_per_hvx; - struct sum_context sctx = { - .octx = octx, - .src_data = (const float *) src0->data, - .total_elems = total_elems, - .elems_per_hvx = elems_per_hvx, + .octx = octx, + .sum_chunk = src0_f16 ? hvx_sum_chunk_f16 : hvx_sum_chunk_f32, + .data_src0 = (dma_addr_t) src0->data, + .vtcm_src0 = vtcm_base + layout.src0_off, + .src0_elem_size = src0_elem_size, + .chunk_bytes = layout.chunk_bytes, + .src0_bytes_per_hvx = layout.src0_bytes_per_hvx, + .total_elems = total_elems, + .elems_per_hvx = kparams->elems_per_hvx, + .chunk_elems = kparams->chunk_elems, }; - work_queue_run(octx->ctx->hvx_queue, sum_thread_f32, &sctx, n_hvx); + work_queue_run(octx->ctx->hvx_queue, sum_thread, &sctx, n_hvx); float sum = 0.0f; for (uint32_t i = 0; i < n_hvx; i++) { sum += sctx.partial_sums[i]; } - ((float *) dst->data)[0] = sum; + + if (dst_f16) { + const HVX_Vector sum_sf = hvx_vec_clamp_f16_f32(hvx_vec_splat_f32(sum)); + hvx_vmem(vtcm_dst) = hvx_vec_f32_to_f16_shuff(sum_sf, sum_sf); + } else { + hvx_vmem(vtcm_dst) = hvx_vec_splat_f32(sum); + } + dma_sync_write(octx->ctx->dma[0], dst->data, vtcm_dst, dst_elem_size); return HTP_STATUS_OK; } -static inline void argmax_slice_f32( - const float * restrict src, - uint32_t n, - uint32_t offset, - float * out_val, - int32_t * out_idx +static void __attribute__((noinline)) hvx_argmax_chunk_f32( + const uint8_t * restrict src, + uint32_t cnt, + uint32_t base_idx, + float * best_val, + int32_t * best_idx ) { - hvx_argmax_f32(src, n, offset, out_val, out_idx); + static const int32_t c_lane_idx[32] __attribute__((aligned(128))) = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 + }; + + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + const HVX_Vector v_step = Q6_V_vsplat_R(32); + HVX_Vector v_cur_idx = Q6_Vw_vadd_VwVw(*(const HVX_Vector *) c_lane_idx, Q6_V_vsplat_R((int32_t) base_idx)); + HVX_Vector vmax = hvx_vec_splat_f32(-INFINITY); + HVX_Vector vidx = Q6_V_vsplat_R((int32_t) base_idx); + + const uint32_t nvec = cnt / VLEN_FP32; + const uint32_t nloe = cnt % VLEN_FP32; + + for (uint32_t vi = 0; vi < nvec; vi++) { + const HVX_Vector v = vsrc[vi]; + const HVX_VectorPred pred = Q6_Q_vcmp_gt_VsfVsf(v, vmax); + vmax = Q6_V_vmux_QVV(pred, v, vmax); + vidx = Q6_V_vmux_QVV(pred, v_cur_idx, vidx); + v_cur_idx = Q6_Vw_vadd_VwVw(v_cur_idx, v_step); + } + + if (nloe) { + const HVX_Vector v = vsrc[nvec]; + const HVX_VectorPred valid = Q6_Q_vsetq_R(nloe * sizeof(float)); + const HVX_VectorPred pred = Q6_Q_and_QQ(valid, Q6_Q_vcmp_gt_VsfVsf(v, vmax)); + vmax = Q6_V_vmux_QVV(pred, v, vmax); + vidx = Q6_V_vmux_QVV(pred, v_cur_idx, vidx); + } + + for (uint32_t shift = 64; shift >= 4; shift >>= 1) { + const HVX_Vector v_val_r = Q6_V_vror_VR(vmax, shift); + const HVX_Vector v_idx_r = Q6_V_vror_VR(vidx, shift); + const HVX_VectorPred gt = Q6_Q_vcmp_gt_VsfVsf(v_val_r, vmax); + const HVX_VectorPred eq = Q6_Q_vcmp_eq_VwVw(v_val_r, vmax); + const HVX_VectorPred lt_idx = Q6_Q_vcmp_gt_VwVw(vidx, v_idx_r); + const HVX_VectorPred take = Q6_Q_or_QQ(gt, Q6_Q_and_QQ(eq, lt_idx)); + vmax = Q6_V_vmux_QVV(take, v_val_r, vmax); + vidx = Q6_V_vmux_QVV(take, v_idx_r, vidx); + } + + const int32_t val_bits = Q6_R_vextract_VR(vmax, 0); + float c_val; + memcpy(&c_val, &val_bits, sizeof(float)); + const int32_t c_idx = Q6_R_vextract_VR(vidx, 0); + + if (c_val > *best_val) { + *best_val = c_val; + *best_idx = c_idx; + } +} + +static void __attribute__((noinline)) hvx_argmax_chunk_f16( + const uint8_t * restrict src, + uint32_t cnt, + uint32_t base_idx, + float * best_val, + int32_t * best_idx +) { + static const int32_t c_lane_idx[32] __attribute__((aligned(128))) = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 + }; + + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + const HVX_Vector v_step = Q6_V_vsplat_R(32); + HVX_Vector v_cur_idx = Q6_Vw_vadd_VwVw(*(const HVX_Vector *) c_lane_idx, Q6_V_vsplat_R((int32_t) base_idx)); + HVX_Vector vmax = hvx_vec_splat_f32(-INFINITY); + HVX_Vector vidx = Q6_V_vsplat_R((int32_t) base_idx); + + const uint32_t nvec = cnt / VLEN_FP16; + const uint32_t nloe = cnt % VLEN_FP16; + + for (uint32_t vi = 0; vi < nvec; vi++) { + const HVX_VectorPair p = hvx_vec_f16_to_f32(vsrc[vi]); + const HVX_Vector v0 = Q6_V_lo_W(p); + const HVX_VectorPred p0 = Q6_Q_vcmp_gt_VsfVsf(v0, vmax); + vmax = Q6_V_vmux_QVV(p0, v0, vmax); + vidx = Q6_V_vmux_QVV(p0, v_cur_idx, vidx); + v_cur_idx = Q6_Vw_vadd_VwVw(v_cur_idx, v_step); + + const HVX_Vector v1 = Q6_V_hi_W(p); + const HVX_VectorPred p1 = Q6_Q_vcmp_gt_VsfVsf(v1, vmax); + vmax = Q6_V_vmux_QVV(p1, v1, vmax); + vidx = Q6_V_vmux_QVV(p1, v_cur_idx, vidx); + v_cur_idx = Q6_Vw_vadd_VwVw(v_cur_idx, v_step); + } + + if (nloe) { + const HVX_VectorPair p = hvx_vec_f16_to_f32(vsrc[nvec]); + const HVX_Vector v0 = Q6_V_lo_W(p); + if (nloe >= VLEN_FP32) { + const HVX_VectorPred p0 = Q6_Q_vcmp_gt_VsfVsf(v0, vmax); + vmax = Q6_V_vmux_QVV(p0, v0, vmax); + vidx = Q6_V_vmux_QVV(p0, v_cur_idx, vidx); + v_cur_idx = Q6_Vw_vadd_VwVw(v_cur_idx, v_step); + + const uint32_t rem = nloe - VLEN_FP32; + if (rem) { + const HVX_Vector v1 = Q6_V_hi_W(p); + const HVX_VectorPred valid = Q6_Q_vsetq_R(rem * sizeof(float)); + const HVX_VectorPred p1 = Q6_Q_and_QQ(valid, Q6_Q_vcmp_gt_VsfVsf(v1, vmax)); + vmax = Q6_V_vmux_QVV(p1, v1, vmax); + vidx = Q6_V_vmux_QVV(p1, v_cur_idx, vidx); + } + } else { + const HVX_VectorPred valid = Q6_Q_vsetq_R(nloe * sizeof(float)); + const HVX_VectorPred p0 = Q6_Q_and_QQ(valid, Q6_Q_vcmp_gt_VsfVsf(v0, vmax)); + vmax = Q6_V_vmux_QVV(p0, v0, vmax); + vidx = Q6_V_vmux_QVV(p0, v_cur_idx, vidx); + } + } + + for (uint32_t shift = 64; shift >= 4; shift >>= 1) { + const HVX_Vector v_val_r = Q6_V_vror_VR(vmax, shift); + const HVX_Vector v_idx_r = Q6_V_vror_VR(vidx, shift); + const HVX_VectorPred gt = Q6_Q_vcmp_gt_VsfVsf(v_val_r, vmax); + const HVX_VectorPred eq = Q6_Q_vcmp_eq_VwVw(v_val_r, vmax); + const HVX_VectorPred lt_idx = Q6_Q_vcmp_gt_VwVw(vidx, v_idx_r); + const HVX_VectorPred take = Q6_Q_or_QQ(gt, Q6_Q_and_QQ(eq, lt_idx)); + vmax = Q6_V_vmux_QVV(take, v_val_r, vmax); + vidx = Q6_V_vmux_QVV(take, v_idx_r, vidx); + } + + const int32_t val_bits = Q6_R_vextract_VR(vmax, 0); + float c_val; + memcpy(&c_val, &val_bits, sizeof(float)); + const int32_t c_idx = Q6_R_vextract_VR(vidx, 0); + + if (c_val > *best_val) { + *best_val = c_val; + *best_idx = c_idx; + } +} + +typedef void (*argmax_chunk_fn_t)( + const uint8_t * restrict src, + uint32_t cnt, + uint32_t base_idx, + float * best_val, + int32_t * best_idx +); + +static void __attribute__((noinline)) hvx_vtcm_store_lane_i32(uint8_t * vtcm_dst, uint32_t lane, int32_t val) { + const uint32_t b_off = lane * sizeof(int32_t); + const HVX_VectorPred b_mask = Q6_Q_vsetq_R(b_off); + const HVX_VectorPred e_mask = Q6_Q_vsetq2_R(b_off + sizeof(int32_t)); + Q6_vmem_QnRIV(Q6_Q_or_QQn(b_mask, e_mask), (HVX_Vector *) vtcm_dst, Q6_V_vsplat_R(val)); } struct argmax_context { struct htp_ops_context * octx; - const float * src_data; - int32_t * dst_data; + argmax_chunk_fn_t argmax_chunk; + dma_addr_t data_src0; + dma_addr_t data_dst; + uint8_t * vtcm_src0; + uint8_t * vtcm_dst; + size_t src0_elem_size; + size_t chunk_bytes; + size_t src0_bytes_per_hvx; + size_t dst_bytes_per_hvx; uint32_t ne00; uint32_t src_stride; uint32_t dst_stride; @@ -252,12 +776,52 @@ struct argmax_context { uint32_t nrows; uint32_t rows_per_hvx; uint32_t elems_per_hvx; + uint32_t chunk_elems; float partial_max[HTP_MAX_NHVX]; int32_t partial_idx[HTP_MAX_NHVX]; }; +struct argmax_single_pipe_state { + dma_addr_t data_src; + argmax_chunk_fn_t argmax_chunk; + size_t src0_elem_size; + size_t chunk_bytes; + uint32_t chunk_elems; + uint32_t pos; + uint32_t end; + float best_val; + int32_t best_idx; +}; + +static bool argmax_single_next_task(void * ctx, struct dma_pipe_task * task) { + struct argmax_single_pipe_state * s = (struct argmax_single_pipe_state *) ctx; + if (s->pos >= s->end) { + return false; + } + const uint32_t cnt = MIN(s->chunk_elems, s->end - s->pos); + task->row = s->pos; + task->off = 0; + task->len = cnt; + task->aux = 0; + s->pos += cnt; + return true; +} + +static void argmax_single_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct argmax_single_pipe_state * s = (struct argmax_single_pipe_state *) ctx; + const size_t nb = (size_t) task->len * s->src0_elem_size; + dma_queue_push(dma_q, dma_make_data(in_spad, s->data_src + (size_t) task->row * s->src0_elem_size), + s->chunk_bytes, nb, nb, 1); +} + +static void argmax_single_compute(void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct argmax_single_pipe_state * s = (struct argmax_single_pipe_state *) ctx; + s->argmax_chunk((const uint8_t *) in_spad, task->len, task->row, &s->best_val, &s->best_idx); +} + static void argmax_thread_single_row(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; struct argmax_context * actx = (struct argmax_context *) data; const uint32_t start = actx->elems_per_hvx * ith; const uint32_t end = MIN(start + actx->elems_per_hvx, actx->ne00); @@ -268,25 +832,30 @@ static void argmax_thread_single_row(const htp_thread_t * th, unsigned int nth, return; } - const uint32_t n = end - start; - const float * src = actx->src_data + start; - - struct htp_thread_trace * tr = th->trace; - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) start); - - hex_l2fetch_block((const void *) src, n * sizeof(float)); - - float max_val; - int32_t max_idx; - argmax_slice_f32(src, n, start, &max_val, &max_idx); + uint8_t * vtcm_src = actx->vtcm_src0 + ith * actx->src0_bytes_per_hvx; + void * in_buf[2] = { vtcm_src, vtcm_src + actx->chunk_bytes }; + + struct argmax_single_pipe_state s = { + .data_src = actx->data_src0, + .argmax_chunk = actx->argmax_chunk, + .src0_elem_size = actx->src0_elem_size, + .chunk_bytes = actx->chunk_bytes, + .chunk_elems = actx->chunk_elems, + .pos = start, + .end = end, + .best_val = -INFINITY, + .best_idx = (int32_t) start, + }; - actx->partial_max[ith] = max_val; - actx->partial_idx[ith] = max_idx; + dma_pipe_in_run(th->dma_q, th->trace, &s, in_buf, + argmax_single_next_task, argmax_single_push_in, argmax_single_compute); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) start); + actx->partial_max[ith] = s.best_val; + actx->partial_idx[ith] = s.best_idx; } static void argmax_thread_multi_row(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; struct argmax_context * actx = (struct argmax_context *) data; const uint32_t r0 = actx->row_start + actx->rows_per_hvx * ith; const uint32_t r1 = MIN(r0 + actx->rows_per_hvx, actx->row_start + actx->nrows); @@ -295,46 +864,86 @@ static void argmax_thread_multi_row(const htp_thread_t * th, unsigned int nth, u return; } - struct htp_thread_trace * tr = th->trace; - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r0); + const dma_addr_t data_src = actx->data_src0; + const dma_addr_t data_dst = actx->data_dst; + uint8_t * vtcm_src = actx->vtcm_src0 + ith * actx->src0_bytes_per_hvx; + uint8_t * vtcm_dst = actx->vtcm_dst + ith * actx->dst_bytes_per_hvx; + const size_t src0_elem_size = actx->src0_elem_size; + const uint32_t ne00 = actx->ne00; + const uint32_t chunk_elems = actx->chunk_elems; + const size_t chunk_bytes = actx->chunk_bytes; + const uint32_t src_stride = actx->src_stride; + const uint32_t dst_stride = actx->dst_stride; + const argmax_chunk_fn_t argmax_chunk = actx->argmax_chunk; + + dma_queue * dma_q = th->dma_q; + struct htp_thread_trace * tr = th->trace; + + uint32_t dst_row0 = r0; + uint32_t dst_cnt = 0; for (uint32_t r = r0; r < r1; r++) { - const float * src_row = (const float *) ((const uint8_t *) actx->src_data + r * actx->src_stride); - int32_t * dst_val = (int32_t *) ((uint8_t *) actx->dst_data + r * actx->dst_stride); + const dma_addr_t src_row = data_src + (size_t) r * src_stride; + + uint32_t push_pos = 0; + for (uint32_t bi = 0; bi < 2 && push_pos < ne00; bi++) { + const uint32_t cnt = MIN(chunk_elems, ne00 - push_pos); + const size_t nb = (size_t) cnt * src0_elem_size; + dma_queue_push(dma_q, + dma_make_data(vtcm_src + bi * chunk_bytes, src_row + (size_t) push_pos * src0_elem_size), + chunk_bytes, nb, nb, 1); + push_pos += cnt; + } - hex_l2fetch_block((const void *) src_row, actx->ne00 * sizeof(float)); + float max_val = -INFINITY; + int32_t max_idx = 0; - float max_val; - int32_t max_idx; - argmax_slice_f32(src_row, actx->ne00, 0, &max_val, &max_idx); + for (uint32_t pos = 0; pos < ne00; ) { + const uint32_t cnt = MIN(chunk_elems, ne00 - pos); + uint8_t * buf = (uint8_t *) (uintptr_t) dma_queue_pop(dma_q).dst; - *dst_val = max_idx; - } + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r); + argmax_chunk(buf, cnt, pos, &max_val, &max_idx); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r); + + if (push_pos < ne00) { + const uint32_t pcnt = MIN(chunk_elems, ne00 - push_pos); + const size_t pnb = (size_t) pcnt * src0_elem_size; + dma_queue_push(dma_q, + dma_make_data(buf, src_row + (size_t) push_pos * src0_elem_size), + chunk_bytes, pnb, pnb, 1); + push_pos += pcnt; + } + pos += cnt; + } + + hvx_vtcm_store_lane_i32(vtcm_dst, dst_cnt, max_idx); + dst_cnt++; - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) r0); + if (dst_cnt == VLEN_FP32 || r + 1 == r1) { + dma_sync_write(dma_q, data_dst + (size_t) dst_row0 * dst_stride, vtcm_dst, (size_t) dst_cnt * sizeof(int32_t)); + dst_row0 = r + 1; + dst_cnt = 0; + } + } } int op_argmax(struct htp_ops_context * octx) { const struct htp_tensor * src0 = octx->src[0]; const struct htp_tensor * dst = octx->dst; - if (src0->type != HTP_TYPE_F32 || dst->type != HTP_TYPE_I32) { - return HTP_STATUS_NO_SUPPORT; - } - - if (htp_tensor_is_extended(src0) || htp_tensor_is_extended(dst)) { + if ((src0->type != HTP_TYPE_F32 && src0->type != HTP_TYPE_F16) || dst->type != HTP_TYPE_I32) { return HTP_STATUS_NO_SUPPORT; } const struct htp_sum_rows_kernel_params * kparams = (const struct htp_sum_rows_kernel_params *) octx->kernel_params; - if (!htp_ops_context_set_n_hvx(octx, kparams->n_hvx)) { - return HTP_STATUS_INVAL_PARAMS; - } - - const uint32_t ne00 = src0->ne[0]; - const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3]; + const bool src0_f16 = (src0->type == HTP_TYPE_F16); + const size_t src0_elem_size = src0_f16 ? sizeof(__fp16) : sizeof(float); + const argmax_chunk_fn_t argmax_chunk = src0_f16 ? hvx_argmax_chunk_f16 : hvx_argmax_chunk_f32; + const uint32_t ne00 = src0->ne[0]; + const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3]; if (ne00 == 0 || src0_nrows == 0) { return HTP_STATUS_OK; @@ -345,30 +954,52 @@ int op_argmax(struct htp_ops_context * octx) { return HTP_STATUS_OK; } + if (!htp_ops_context_set_n_hvx(octx, kparams->n_hvx)) { + return HTP_STATUS_INVAL_PARAMS; + } + + const uint32_t n_hvx = octx->n_hvx; + + struct htp_sum_vtcm_layout layout; + htp_sum_vtcm_layout_build(&layout, kparams->chunk_elems, src0_elem_size, n_hvx); + if (octx->ctx->vtcm_size < layout.total_bytes) { + FARF(ERROR, "argmax: VTCM size %zu is too small, needed %zu\n", octx->ctx->vtcm_size, layout.total_bytes); + return HTP_STATUS_VTCM_TOO_SMALL; + } + + uint8_t * vtcm_base = octx->ctx->vtcm_base; + uint8_t * vtcm_dst = vtcm_base + layout.dst_off; + if (ne00 == 1) { - ((int32_t *) dst->data)[0] = 0; + hvx_vmem(vtcm_dst) = Q6_V_vzero(); + dma_sync_write(octx->ctx->dma[0], dst->data, vtcm_dst, sizeof(int32_t)); return HTP_STATUS_OK; } - const uint32_t n_hvx = octx->n_hvx; - const uint32_t elems_per_hvx = kparams->elems_per_hvx; - struct argmax_context actx = { - .octx = octx, - .src_data = (const float *) src0->data, - .dst_data = (int32_t *) dst->data, - .ne00 = ne00, - .src_stride = src0->nb[1] > 0 ? (uint32_t) src0->nb[1] : (uint32_t) (ne00 * sizeof(float)), - .dst_stride = dst->nb[0] > 0 ? (uint32_t) dst->nb[0] : (uint32_t) sizeof(int32_t), - .row_start = 0, - .nrows = 1, - .rows_per_hvx = 1, - .elems_per_hvx = elems_per_hvx, + .octx = octx, + .argmax_chunk = argmax_chunk, + .data_src0 = (dma_addr_t) src0->data, + .data_dst = (dma_addr_t) dst->data, + .vtcm_src0 = vtcm_base + layout.src0_off, + .vtcm_dst = vtcm_dst, + .src0_elem_size = src0_elem_size, + .chunk_bytes = layout.chunk_bytes, + .src0_bytes_per_hvx = layout.src0_bytes_per_hvx, + .dst_bytes_per_hvx = layout.dst_bytes_per_hvx, + .ne00 = ne00, + .src_stride = src0->nb[1] > 0 ? (uint32_t) src0->nb[1] : (uint32_t) (ne00 * src0_elem_size), + .dst_stride = dst->nb[0] > 0 ? (uint32_t) dst->nb[0] : (uint32_t) sizeof(int32_t), + .row_start = 0, + .nrows = 1, + .rows_per_hvx = 1, + .elems_per_hvx = kparams->elems_per_hvx, + .chunk_elems = kparams->chunk_elems, }; work_queue_run(octx->ctx->hvx_queue, argmax_thread_single_row, &actx, n_hvx); - float best_val = actx.partial_max[0]; + float best_val = actx.partial_max[0]; int32_t best_idx = actx.partial_idx[0]; for (uint32_t i = 1; i < n_hvx; i++) { if (actx.partial_max[i] > best_val) { @@ -376,7 +1007,9 @@ int op_argmax(struct htp_ops_context * octx) { best_idx = actx.partial_idx[i]; } } - ((int32_t *) dst->data)[0] = best_idx; + + hvx_vmem(vtcm_dst) = Q6_V_vsplat_R(best_idx); + dma_sync_write(octx->ctx->dma[0], dst->data, vtcm_dst, sizeof(int32_t)); return HTP_STATUS_OK; } @@ -384,11 +1017,8 @@ int op_argmax(struct htp_ops_context * octx) { uint32_t nrows = src0_nrows; if (octx->ctx->mdev.count > 1) { - const bool can_split = htp_tensor_mdev_data_aligned(dst) && - htp_tensor_is_contiguous(dst, sizeof(int32_t)); - const uint32_t elems_per_chunk = can_split ? 32 : 0; const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( - src0_nrows, elems_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + src0_nrows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); row_start = range.start; nrows = range.count; } @@ -397,20 +1027,41 @@ int op_argmax(struct htp_ops_context * octx) { return HTP_STATUS_OK; } + if (!htp_ops_context_set_n_hvx(octx, MIN(kparams->n_hvx, nrows))) { + return HTP_STATUS_INVAL_PARAMS; + } + const uint32_t n_hvx = octx->n_hvx; const uint32_t rows_per_hvx = fastdiv(nrows + n_hvx - 1, &octx->n_hvx_div); + struct htp_sum_vtcm_layout layout; + htp_sum_vtcm_layout_build(&layout, kparams->chunk_elems, src0_elem_size, n_hvx); + if (octx->ctx->vtcm_size < layout.total_bytes) { + FARF(ERROR, "argmax: VTCM size %zu is too small, needed %zu\n", octx->ctx->vtcm_size, layout.total_bytes); + return HTP_STATUS_VTCM_TOO_SMALL; + } + + uint8_t * vtcm_base = octx->ctx->vtcm_base; + struct argmax_context actx = { - .octx = octx, - .src_data = (const float *) src0->data, - .dst_data = (int32_t *) dst->data, - .ne00 = ne00, - .src_stride = src0->nb[1] > 0 ? (uint32_t) src0->nb[1] : (uint32_t) (ne00 * sizeof(float)), - .dst_stride = dst->nb[0] > 0 ? (uint32_t) dst->nb[0] : (uint32_t) sizeof(int32_t), - .row_start = row_start, - .nrows = nrows, - .rows_per_hvx = rows_per_hvx, - .elems_per_hvx = 0, + .octx = octx, + .argmax_chunk = argmax_chunk, + .data_src0 = (dma_addr_t) src0->data, + .data_dst = (dma_addr_t) dst->data, + .vtcm_src0 = vtcm_base + layout.src0_off, + .vtcm_dst = vtcm_base + layout.dst_off, + .src0_elem_size = src0_elem_size, + .chunk_bytes = layout.chunk_bytes, + .src0_bytes_per_hvx = layout.src0_bytes_per_hvx, + .dst_bytes_per_hvx = layout.dst_bytes_per_hvx, + .ne00 = ne00, + .src_stride = src0->nb[1] > 0 ? (uint32_t) src0->nb[1] : (uint32_t) (ne00 * src0_elem_size), + .dst_stride = dst->nb[0] > 0 ? (uint32_t) dst->nb[0] : (uint32_t) sizeof(int32_t), + .row_start = row_start, + .nrows = nrows, + .rows_per_hvx = rows_per_hvx, + .elems_per_hvx = 0, + .chunk_elems = kparams->chunk_elems, }; work_queue_run(octx->ctx->hvx_queue, argmax_thread_multi_row, &actx, n_hvx); diff --git a/ggml/src/ggml-hexagon/htp/sum-rows-ops.h b/ggml/src/ggml-hexagon/htp/sum-rows-ops.h index 0b8acf030b0a..c8c3bfdf06a3 100644 --- a/ggml/src/ggml-hexagon/htp/sum-rows-ops.h +++ b/ggml/src/ggml-hexagon/htp/sum-rows-ops.h @@ -1,13 +1,82 @@ #ifndef HTP_SUM_ROWS_OPS_H #define HTP_SUM_ROWS_OPS_H +#include #include +#include "hex-common.h" +#include "hex-fastdiv.h" +#include "htp-vtcm.h" + struct htp_sum_rows_kernel_params { - uint32_t n_hvx; - uint32_t elems_per_hvx; + uint32_t n_hvx; + uint32_t elems_per_hvx; + uint32_t block; + uint32_t chunk_elems; + uint32_t src0_contig; + uint32_t vtcm_size; + struct fastdiv_values div_ne01; + struct fastdiv_values div_ne02; + struct fastdiv_values div_ne012; +}; + +struct htp_sum_vtcm_layout { + size_t chunk_bytes; + size_t src0_bytes_per_hvx; + size_t dst_bytes_per_hvx; + size_t src0_off; + size_t dst_off; + size_t total_bytes; }; +static inline void htp_sum_vtcm_layout_build( + struct htp_sum_vtcm_layout * L, + uint32_t chunk_elems, + size_t src0_elem_size, + uint32_t n_hvx +) { + size_t off = 0; + + L->chunk_bytes = hex_round_up((size_t) chunk_elems * src0_elem_size, 128); + L->src0_bytes_per_hvx = 2 * L->chunk_bytes; + L->dst_bytes_per_hvx = 128; + + VTCM_LAYOUT_ALLOC(off, src0_off, (size_t) n_hvx * L->src0_bytes_per_hvx); + VTCM_LAYOUT_ALLOC(off, dst_off, (size_t) n_hvx * L->dst_bytes_per_hvx); + L->total_bytes = off; +} + +struct htp_sum_rows_vtcm_layout { + size_t src0_row_size_aligned; + size_t src0_half_bytes; + size_t dst_half_bytes; + size_t src0_bytes_per_hvx; + size_t dst_bytes_per_hvx; + size_t src0_off; + size_t dst_off; + size_t total_bytes; +}; + +static inline void htp_sum_rows_vtcm_layout_build( + struct htp_sum_rows_vtcm_layout * L, + size_t src0_row_size, + size_t dst_elem_size, + uint32_t block, + uint32_t n_hvx +) { + size_t off = 0; + + L->src0_row_size_aligned = hex_round_up(src0_row_size, 128); + L->src0_half_bytes = L->src0_row_size_aligned * block; + L->dst_half_bytes = hex_round_up((size_t) block * dst_elem_size, 128); + L->src0_bytes_per_hvx = 2 * L->src0_half_bytes; + L->dst_bytes_per_hvx = 2 * L->dst_half_bytes; + + VTCM_LAYOUT_ALLOC(off, src0_off, (size_t) n_hvx * L->src0_bytes_per_hvx); + VTCM_LAYOUT_ALLOC(off, dst_off, (size_t) n_hvx * L->dst_bytes_per_hvx); + L->total_bytes = off; +} + #if defined(__cplusplus) static_assert(sizeof(struct htp_sum_rows_kernel_params) <= 128, "htp_sum_rows_kernel_params is too large for kernel_params blob"); #else diff --git a/ggml/src/ggml-hexagon/htp/timestep-ops.c b/ggml/src/ggml-hexagon/htp/timestep-ops.c index 28451e38b06d..4835df3bbcfe 100644 --- a/ggml/src/ggml-hexagon/htp/timestep-ops.c +++ b/ggml/src/ggml-hexagon/htp/timestep-ops.c @@ -1,7 +1,3 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include @@ -186,8 +182,6 @@ int op_timestep_embedding(struct htp_ops_context * octx) { const struct htp_timestep_kernel_params * kparams = (const struct htp_timestep_kernel_params *) octx->kernel_params; - const int32_t max_period = (int32_t) octx->op_params[1]; - // Only device 0 writes the output when running multi-device if (octx->ctx->mdev.count > 1 && octx->ctx->mdev.idx != 0) { return HTP_STATUS_OK; diff --git a/ggml/src/ggml-hexagon/htp/top-k-mask-ops.c b/ggml/src/ggml-hexagon/htp/top-k-mask-ops.c index 9c4dc583c495..6fefd2231a40 100644 --- a/ggml/src/ggml-hexagon/htp/top-k-mask-ops.c +++ b/ggml/src/ggml-hexagon/htp/top-k-mask-ops.c @@ -1,7 +1,3 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include #include diff --git a/ggml/src/ggml-hexagon/htp/unary-ops.c b/ggml/src/ggml-hexagon/htp/unary-ops.c index 19ade22f376b..258cafaff94b 100644 --- a/ggml/src/ggml-hexagon/htp/unary-ops.c +++ b/ggml/src/ggml-hexagon/htp/unary-ops.c @@ -1,7 +1,3 @@ -#pragma clang diagnostic ignored "-Wunused-variable" -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wunused-but-set-variable" - #include #include @@ -9,6 +5,7 @@ #include #include "dma-queue.h" +#include "dma-pipeline.h" #include "hex-fastdiv.h" #include "hvx-exp.h" #include "hvx-sigmoid.h" @@ -28,19 +25,22 @@ struct htp_unary_context; typedef void (*unary_compute_fn_t)(const void * restrict src, void * restrict dst, uint32_t num_rows, + uint32_t ne0, const struct htp_unary_context * uctx); typedef void (*unary_rms_norm_mul_compute_fn_t)(const void * restrict src, - const void * restrict weight, + const void * restrict mul, void * restrict dst, uint32_t num_rows, + uint32_t src1_row_start, const struct htp_unary_context * uctx); typedef void (*unary_rms_norm_mul_add_compute_fn_t)(const void * restrict src, - const void * restrict weight, + const void * restrict mul, const void * restrict add, void * restrict dst, uint32_t num_rows, + uint32_t src1_row_start, const struct htp_unary_context * uctx); typedef void (*unary_tri_compute_fn_t)(const void * restrict src, @@ -49,11 +49,6 @@ typedef void (*unary_tri_compute_fn_t)(const void * restrict src, uint32_t ir, const struct htp_unary_context * uctx); -typedef void (*unary_tile_compute_fn_t)(void * restrict dst, - const void * restrict src, - uint32_t tw, - const struct htp_unary_context * uctx); - typedef void (*unary_tiled_tri_compute_fn_t)(const void * restrict src, void * restrict dst, uint32_t tile_elems, @@ -62,27 +57,43 @@ typedef void (*unary_tiled_tri_compute_fn_t)(const void * restrict src, uint32_t ne0, int32_t ttype); +typedef float (*rms_tile_sum_sq_fn_t)(const uint8_t * restrict src, + uint32_t num_elems); + +typedef void (*rms_apply_row_fn_t)(const uint8_t * restrict src, + const uint8_t * restrict mul, + const uint8_t * restrict add, + uint8_t * restrict dst, + uint32_t n, + HVX_Vector scale_v); + struct htp_unary_context { struct htp_ops_context * octx; const struct htp_unary_kernel_params * kparams; void * compute; + rms_tile_sum_sq_fn_t rms_tile_sum_sq_fn; + rms_apply_row_fn_t rms_apply_row_fn; dma_addr_t data_src0; - dma_addr_t data_src1; // weight/scale tensor for RMS_NORM_MUL + dma_addr_t data_src1; // mul/scale tensor for RMS_NORM_MUL dma_addr_t data_src2; // residual tensor for RMS_NORM_MUL_ADD dma_addr_t data_dst; size_t src0_data_row_size; // actual data bytes per row size_t src1_data_row_size; + size_t src2_data_row_size; size_t dst_data_row_size; // actual data bytes per row size_t src0_row_size_aligned; size_t src1_row_size_aligned; + size_t src1_block_stride; + size_t src2_row_size_aligned; size_t dst_row_size_aligned; size_t src0_vtcm_half_size; size_t src1_vtcm_half_size; + size_t src2_vtcm_half_size; size_t dst_vtcm_half_size; uint32_t block; @@ -91,7 +102,12 @@ struct htp_unary_context { uint32_t row_start; uint32_t nc; uint32_t col_tile; // tiled mode - bool broadcast_weight; + uint32_t src1_nrows; + bool broadcast_src1; + bool src0_f16; + bool src1_f16; + bool src2_f16; + bool dst_f16; uint8_t * vtcm_src0; uint8_t * vtcm_src1; @@ -125,48 +141,100 @@ static inline uint32_t unary_block_size(uint32_t ir, uint32_t end_row, uint32_t block, bool contig, + bool slice_dma, uint32_t ne1, const struct fastdiv_values * div_ne1) { uint32_t limit = MIN(block, end_row - ir); if (!contig) { - const uint32_t slice_end = (fastdiv(ir, div_ne1) + 1) * ne1; + const uint32_t slice_idx = fastdiv(ir, div_ne1); + const uint32_t slice_start = slice_idx * ne1; + if (slice_dma && ir == slice_start && limit >= ne1) { + return fastdiv(limit, div_ne1) * ne1; + } + const uint32_t slice_end = slice_start + ne1; limit = MIN(limit, slice_end - ir); } return limit; } -#define htp_unary_preamble \ - const uint32_t ne00 = src->ne[0]; \ - const uint32_t ne01 = src->ne[1]; \ - const uint32_t ne02 = src->ne[2]; \ - const uint32_t ne03 = src->ne[3]; \ - \ - const uint32_t ne0 = dst->ne[0]; \ - const uint32_t ne1 = dst->ne[1]; \ - const uint32_t ne2 = dst->ne[2]; \ - const uint32_t ne3 = dst->ne[3]; \ - \ - const uint32_t nb00 = src->nb[0]; \ - const uint32_t nb01 = src->nb[1]; \ - const uint32_t nb02 = src->nb[2]; \ - const uint32_t nb03 = src->nb[3]; \ - \ - const uint32_t nb0 = dst->nb[0]; \ - const uint32_t nb1 = dst->nb[1]; \ - const uint32_t nb2 = dst->nb[2]; \ - const uint32_t nb3 = dst->nb[3]; - -#define htp_unary_op_preamble \ - int32_t * op_params = uctx->octx->op_params; \ - const uint32_t ne0 = uctx->nc; \ - const size_t src0_row_size_aligned = uctx->src0_row_size_aligned; \ +static inline void unary_push_src0_dma(dma_queue * dma_q, + void * dst_vtcm, + dma_addr_t data_src, + uint32_t ir, + uint32_t block_size, + bool src0_contig, + bool src0_slice_dma, + uint32_t ne01, + uint32_t ne02, + const struct fastdiv_values * div_ne01, + const struct fastdiv_values * div_ne02, + const struct fastdiv_values * div_ne012, + size_t nb01, + size_t nb02, + size_t nb03, + size_t src0_row_size_aligned, + size_t src0_data_row_size) { + if (src0_contig) { + dma_queue_push(dma_q, + dma_make_data(dst_vtcm, data_src + (size_t) ir * nb01), + src0_row_size_aligned, nb01, src0_data_row_size, block_size); + return; + } + if (src0_slice_dma) { + const uint32_t slice_idx = fastdiv(ir, div_ne01); + if (ir == slice_idx * ne01 && block_size >= ne01) { + const size_t slice_bytes = (size_t) ne01 * src0_data_row_size; + const uint32_t n_slices = fastdiv(block_size, div_ne01); + dma_queue_push(dma_q, + dma_make_data(dst_vtcm, data_src + (size_t) slice_idx * nb02), + slice_bytes, nb02, slice_bytes, n_slices); + return; + } + } + const size_t src0_off = unary_row_offset(ir, ne01, ne02, div_ne01, div_ne02, div_ne012, nb01, nb02, nb03); + dma_queue_push(dma_q, + dma_make_data(dst_vtcm, data_src + src0_off), + src0_row_size_aligned, nb01, src0_data_row_size, block_size); +} + +#define htp_unary_preamble \ + const uint32_t __attribute__((unused)) ne00 = src->ne[0]; \ + const uint32_t __attribute__((unused)) ne01 = src->ne[1]; \ + const uint32_t __attribute__((unused)) ne02 = src->ne[2]; \ + const uint32_t __attribute__((unused)) ne03 = src->ne[3]; \ + \ + const uint32_t __attribute__((unused)) ne0 = dst->ne[0]; \ + const uint32_t __attribute__((unused)) ne1 = dst->ne[1]; \ + const uint32_t __attribute__((unused)) ne2 = dst->ne[2]; \ + const uint32_t __attribute__((unused)) ne3 = dst->ne[3]; \ + \ + const uint32_t __attribute__((unused)) nb00 = src->nb[0]; \ + const uint32_t __attribute__((unused)) nb01 = src->nb[1]; \ + const uint32_t __attribute__((unused)) nb02 = src->nb[2]; \ + const uint32_t __attribute__((unused)) nb03 = src->nb[3]; \ + \ + const uint32_t __attribute__((unused)) nb0 = dst->nb[0]; \ + const uint32_t __attribute__((unused)) nb1 = dst->nb[1]; \ + const uint32_t __attribute__((unused)) nb2 = dst->nb[2]; \ + const uint32_t __attribute__((unused)) nb3 = dst->nb[3]; + +#define htp_unary_op_preamble \ + int32_t * __attribute__((unused)) op_params = uctx->octx->op_params; \ + const size_t src0_row_size_aligned = uctx->src0_row_size_aligned; \ const size_t dst_row_size_aligned = uctx->dst_row_size_aligned; +static inline HVX_Vector hvx_vec_clamp_f16_f32(HVX_Vector x) { + const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f); + const HVX_Vector f16_min = hvx_vec_neg_f32(f16_max); + return Q6_Vsf_vmin_VsfVsf(Q6_Vsf_vmax_VsfVsf(x, f16_min), f16_max); +} + static void scale_f32(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; float scale = 0.f; @@ -185,6 +253,7 @@ static void scale_f32(const void * restrict src, static void clamp_f32(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; float min = 0.f; @@ -196,13 +265,38 @@ static void clamp_f32(const void * restrict src, const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); - hvx_clamp_scalar_f32(dst_local, src_local, min, max, ne0); + hvx_clamp_scalar_f32_aa(dst_local, src_local, min, max, ne0); + } +} + +static inline HVX_Vector hvx_vec_leaky_relu_f32(HVX_Vector x, HVX_Vector slope, HVX_Vector zero) { + HVX_VectorPred pred = Q6_Q_vcmp_gt_VsfVsf(x, zero); + HVX_Vector neg = hvx_vec_mul_f32_f32(x, slope); + return Q6_V_vmux_QVV(pred, x, neg); +} + +static inline void unary_leaky_relu_f32_aa(uint8_t * restrict dst, const uint8_t * restrict src, float slope, uint32_t n) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + HVX_Vector * restrict vdst = (HVX_Vector *) dst; + + const HVX_Vector vslope = hvx_vec_splat_f32(slope); + const HVX_Vector vzero = Q6_V_vzero(); + + const uint32_t nvec = n / VLEN_FP32; + const uint32_t nloe = n % VLEN_FP32; + + for (uint32_t i = 0; i < nvec; i++) { + vdst[i] = hvx_vec_leaky_relu_f32(vsrc[i], vslope, vzero); + } + if (nloe) { + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(float), hvx_vec_leaky_relu_f32(vsrc[nvec], vslope, vzero)); } } static void leaky_relu_f32(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; float negative_slope = 0.f; @@ -212,74 +306,1316 @@ static void leaky_relu_f32(const void * restrict src, const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); - hvx_leaky_relu_scalar_f32(dst_local, src_local, negative_slope, ne0); + unary_leaky_relu_f32_aa(dst_local, src_local, negative_slope, ne0); } } -static void rms_norm_f32(const void * restrict src, - void * restrict dst, - const uint32_t num_rows, - const struct htp_unary_context * uctx) { - htp_unary_op_preamble; - float epsilon = 0.f; - float scale = 0.f; - memcpy(&epsilon, &op_params[0], sizeof(float)); - memcpy(&scale, &op_params[1], sizeof(float)); +static inline HVX_Vector rms_norm_sum_sq_f32(const uint8_t * restrict src, uint32_t num_elems, HVX_Vector sum_v) { + const HVX_Vector * restrict v_src = (const HVX_Vector *) src; + const uint32_t nvec = num_elems / VLEN_FP32; + const uint32_t nloe = num_elems % VLEN_FP32; - for (uint32_t ir = 0; ir < num_rows; ir++) { - const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); - uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); + #pragma unroll(4) + for (uint32_t i = 0; i < nvec; i++) { + HVX_Vector v1 = v_src[i]; + sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(v1, v1)); + } - hvx_fast_rms_norm_f32((const uint8_t *) src_local, (uint8_t *) dst_local, ne0, epsilon, scale); + if (nloe > 0) { + HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * sizeof(float)); + HVX_Vector v1 = Q6_V_vand_QV(bmask, v_src[nvec]); + sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vmpy_VsfVsf(v1, v1)); } + + return sum_v; } -static void rms_norm_mul_f32(const void * restrict src, - const void * restrict weight, - void * restrict dst, - const uint32_t num_rows, - const struct htp_unary_context * uctx) { - htp_unary_op_preamble; - float epsilon = 0.f; - float scale = 0.f; - memcpy(&epsilon, &op_params[0], sizeof(float)); - memcpy(&scale, &op_params[1], sizeof(float)); +static inline HVX_Vector rms_norm_sum_sq_f16(const uint8_t * restrict src, uint32_t num_elems, HVX_Vector sum_v) { + const HVX_Vector * restrict v_src = (const HVX_Vector *) src; + const uint32_t nvec = num_elems / VLEN_FP16; + const uint32_t nloe = num_elems % VLEN_FP16; - for (uint32_t ir = 0; ir < num_rows; ir++) { - const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); - const uint8_t * restrict w_local = (const uint8_t *)weight + (uctx->broadcast_weight ? 0 : ir * uctx->src1_row_size_aligned); - uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); +#if __HVX_ARCH__ >= 79 + HVX_VectorPair sum_p = Q6_W_vzero(); + + #pragma unroll(4) + for (uint32_t i = 0; i < nvec; i++) { + HVX_Vector v = v_src[i]; + sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, v, v); + } + + if (nloe > 0) { + HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * sizeof(_Float16)); + HVX_Vector v = Q6_V_vand_QV(bmask, v_src[nvec]); + sum_p = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p, v, v); + } + + sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vadd_VsfVsf(Q6_V_lo_W(sum_p), Q6_V_hi_W(sum_p))); +#else + HVX_Vector sum0 = Q6_V_vzero(); + HVX_Vector sum1 = Q6_V_vzero(); + + #pragma unroll(4) + for (uint32_t i = 0; i < nvec; i++) { + HVX_Vector v = v_src[i]; + HVX_VectorPair sq = Q6_Wqf32_vmpy_VhfVhf(v, v); + sum0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum0, Q6_V_lo_W(sq)); + sum1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum1, Q6_V_hi_W(sq)); + } + + if (nloe > 0) { + HVX_VectorPred bmask = Q6_Q_vsetq_R(nloe * sizeof(_Float16)); + HVX_Vector v = Q6_V_vand_QV(bmask, v_src[nvec]); + HVX_VectorPair sq = Q6_Wqf32_vmpy_VhfVhf(v, v); + sum0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum0, Q6_V_lo_W(sq)); + sum1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum1, Q6_V_hi_W(sq)); + } + + sum_v = Q6_Vqf32_vadd_Vqf32Vqf32(sum_v, Q6_Vqf32_vadd_Vqf32Vqf32(sum0, sum1)); +#endif + + return sum_v; +} + +static inline HVX_Vector rms_norm_scale_from_sum_precomp(HVX_Vector sum_v, + HVX_Vector inv_ne0_v, + HVX_Vector eps_v, + HVX_Vector scale_param_v) { + HVX_Vector mean_v = Q6_Vqf32_vmpy_VsfVsf(sum_v, inv_ne0_v); + HVX_Vector mean_epsilon_v = Q6_Vqf32_vadd_Vqf32Vsf(mean_v, eps_v); + HVX_Vector scale_v = hvx_vec_rsqrt_f32(Q6_Vsf_equals_Vqf32(mean_epsilon_v)); + return Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(scale_v, scale_param_v)); +} + +static inline HVX_Vector rms_norm_scale_from_sum_f32(HVX_Vector sum_v, uint32_t num_elems, float epsilon, float scale) { + const HVX_Vector inv_ne0_v = hvx_vec_inverse_f32(hvx_vec_splat_f32((float) (int32_t) num_elems)); + const HVX_Vector eps_v = hvx_vec_splat_f32(epsilon); + const HVX_Vector scale_param_v = hvx_vec_splat_f32((scale != 0.0f) ? scale : 1.0f); + return rms_norm_scale_from_sum_precomp(sum_v, inv_ne0_v, eps_v, scale_param_v); +} + +static inline HVX_Vector rms_norm_row_scale_precomp_f32(const uint8_t * restrict src, + uint32_t num_elems, + HVX_Vector inv_ne0_v, + HVX_Vector eps_v, + HVX_Vector scale_param_v) { + HVX_Vector sum_v = Q6_V_vsplat_R(0x00000000); + sum_v = rms_norm_sum_sq_f32(src, num_elems, sum_v); + sum_v = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_v)); + return rms_norm_scale_from_sum_precomp(sum_v, inv_ne0_v, eps_v, scale_param_v); +} + +static inline HVX_Vector rms_norm_row_scale_precomp_f16(const uint8_t * restrict src, + uint32_t num_elems, + HVX_Vector inv_ne0_v, + HVX_Vector eps_v, + HVX_Vector scale_param_v) { + HVX_Vector sum_v = Q6_V_vsplat_R(0x00000000); + sum_v = rms_norm_sum_sq_f16(src, num_elems, sum_v); + sum_v = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_v)); + return rms_norm_scale_from_sum_precomp(sum_v, inv_ne0_v, eps_v, scale_param_v); +} + +static inline void rms_norm_scale_4rows_from_sums(HVX_Vector_x4 sums, + HVX_Vector inv_ne0_v, + HVX_Vector eps_v, + HVX_Vector scale_param_v, + HVX_Vector * restrict scale_v0, + HVX_Vector * restrict scale_v1, + HVX_Vector * restrict scale_v2, + HVX_Vector * restrict scale_v3) { + HVX_Vector sum_x4 = hvx_vec_reduce_sum_f32x4(sums); + HVX_Vector scale_x4 = rms_norm_scale_from_sum_precomp(sum_x4, inv_ne0_v, eps_v, scale_param_v); + + HVX_VectorPair p01 = Q6_W_vshuff_VVR(scale_x4, scale_x4, 4); + HVX_VectorPair p02 = Q6_W_vshuff_VVR(Q6_V_lo_W(p01), Q6_V_lo_W(p01), 8); + HVX_VectorPair p13 = Q6_W_vshuff_VVR(Q6_V_hi_W(p01), Q6_V_hi_W(p01), 8); + + *scale_v0 = Q6_V_lo_W(p02); + *scale_v1 = Q6_V_lo_W(p13); + *scale_v2 = Q6_V_hi_W(p02); + *scale_v3 = Q6_V_hi_W(p13); +} + +static inline void rms_norm_4rows_scale_precomp_f32(const uint8_t * restrict src, + size_t stride, + uint32_t num_elems, + HVX_Vector inv_ne0_v, + HVX_Vector eps_v, + HVX_Vector scale_param_v, + HVX_Vector * restrict scale_v0, + HVX_Vector * restrict scale_v1, + HVX_Vector * restrict scale_v2, + HVX_Vector * restrict scale_v3) { + const uint32_t nvec = num_elems / VLEN_FP32; + + HVX_Vector sum0 = Q6_V_vzero(); + HVX_Vector sum1 = Q6_V_vzero(); + HVX_Vector sum2 = Q6_V_vzero(); + HVX_Vector sum3 = Q6_V_vzero(); + + const uint8_t * restrict s0 = src; + #pragma clang loop unroll(disable) + for (uint32_t i = 0; i < nvec; i++) { + const uint8_t * restrict s1 = s0 + stride; + const uint8_t * restrict s2 = s1 + stride; + const uint8_t * restrict s3 = s2 + stride; + HVX_Vector v0 = *(const HVX_Vector *) s0; + HVX_Vector v1 = *(const HVX_Vector *) s1; + HVX_Vector v2 = *(const HVX_Vector *) s2; + HVX_Vector v3 = *(const HVX_Vector *) s3; + s0 += VLEN; + sum0 = Q6_Vqf32_vadd_Vqf32Vqf32(sum0, Q6_Vqf32_vmpy_VsfVsf(v0, v0)); + sum1 = Q6_Vqf32_vadd_Vqf32Vqf32(sum1, Q6_Vqf32_vmpy_VsfVsf(v1, v1)); + sum2 = Q6_Vqf32_vadd_Vqf32Vqf32(sum2, Q6_Vqf32_vmpy_VsfVsf(v2, v2)); + sum3 = Q6_Vqf32_vadd_Vqf32Vqf32(sum3, Q6_Vqf32_vmpy_VsfVsf(v3, v3)); + } + + HVX_Vector_x4 sums = { .v = { + Q6_Vsf_equals_Vqf32(sum0), + Q6_Vsf_equals_Vqf32(sum1), + Q6_Vsf_equals_Vqf32(sum2), + Q6_Vsf_equals_Vqf32(sum3), + } }; + rms_norm_scale_4rows_from_sums(sums, inv_ne0_v, eps_v, scale_param_v, scale_v0, scale_v1, scale_v2, scale_v3); +} + +static inline void rms_norm_4rows_scale_precomp_f16(const uint8_t * restrict src, + size_t stride, + uint32_t num_elems, + HVX_Vector inv_ne0_v, + HVX_Vector eps_v, + HVX_Vector scale_param_v, + HVX_Vector * restrict scale_v0, + HVX_Vector * restrict scale_v1, + HVX_Vector * restrict scale_v2, + HVX_Vector * restrict scale_v3) { + const uint32_t nvec = num_elems / VLEN_FP16; + const uint8_t * restrict s0 = src; + +#if __HVX_ARCH__ >= 79 + HVX_VectorPair sum_p0 = Q6_W_vzero(); + HVX_VectorPair sum_p1 = Q6_W_vzero(); + HVX_VectorPair sum_p2 = Q6_W_vzero(); + HVX_VectorPair sum_p3 = Q6_W_vzero(); + + #pragma clang loop unroll(disable) + for (uint32_t i = 0; i < nvec; i++) { + const uint8_t * restrict s1 = s0 + stride; + const uint8_t * restrict s2 = s1 + stride; + const uint8_t * restrict s3 = s2 + stride; + HVX_Vector v0 = *(const HVX_Vector *) s0; + HVX_Vector v1 = *(const HVX_Vector *) s1; + HVX_Vector v2 = *(const HVX_Vector *) s2; + HVX_Vector v3 = *(const HVX_Vector *) s3; + s0 += VLEN; + sum_p0 = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p0, v0, v0); + sum_p1 = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p1, v1, v1); + sum_p2 = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p2, v2, v2); + sum_p3 = Q6_Wsf_vmpyacc_WsfVhfVhf(sum_p3, v3, v3); + } + + HVX_Vector_x4 sums = { .v = { + Q6_Vsf_vadd_VsfVsf(Q6_V_lo_W(sum_p0), Q6_V_hi_W(sum_p0)), + Q6_Vsf_vadd_VsfVsf(Q6_V_lo_W(sum_p1), Q6_V_hi_W(sum_p1)), + Q6_Vsf_vadd_VsfVsf(Q6_V_lo_W(sum_p2), Q6_V_hi_W(sum_p2)), + Q6_Vsf_vadd_VsfVsf(Q6_V_lo_W(sum_p3), Q6_V_hi_W(sum_p3)), + } }; +#else + HVX_Vector sum0_lo = Q6_V_vzero(), sum0_hi = Q6_V_vzero(); + HVX_Vector sum1_lo = Q6_V_vzero(), sum1_hi = Q6_V_vzero(); + HVX_Vector sum2_lo = Q6_V_vzero(), sum2_hi = Q6_V_vzero(); + HVX_Vector sum3_lo = Q6_V_vzero(), sum3_hi = Q6_V_vzero(); + + for (uint32_t i = 0; i < nvec; i++) { + const uint8_t * restrict s1 = s0 + stride; + const uint8_t * restrict s2 = s1 + stride; + const uint8_t * restrict s3 = s2 + stride; + HVX_Vector v0 = *(const HVX_Vector *) s0; + HVX_Vector v1 = *(const HVX_Vector *) s1; + HVX_Vector v2 = *(const HVX_Vector *) s2; + HVX_Vector v3 = *(const HVX_Vector *) s3; + s0 += VLEN; + HVX_VectorPair sq0 = Q6_Wqf32_vmpy_VhfVhf(v0, v0); + HVX_VectorPair sq1 = Q6_Wqf32_vmpy_VhfVhf(v1, v1); + HVX_VectorPair sq2 = Q6_Wqf32_vmpy_VhfVhf(v2, v2); + HVX_VectorPair sq3 = Q6_Wqf32_vmpy_VhfVhf(v3, v3); + sum0_lo = Q6_Vqf32_vadd_Vqf32Vqf32(sum0_lo, Q6_V_lo_W(sq0)); + sum0_hi = Q6_Vqf32_vadd_Vqf32Vqf32(sum0_hi, Q6_V_hi_W(sq0)); + sum1_lo = Q6_Vqf32_vadd_Vqf32Vqf32(sum1_lo, Q6_V_lo_W(sq1)); + sum1_hi = Q6_Vqf32_vadd_Vqf32Vqf32(sum1_hi, Q6_V_hi_W(sq1)); + sum2_lo = Q6_Vqf32_vadd_Vqf32Vqf32(sum2_lo, Q6_V_lo_W(sq2)); + sum2_hi = Q6_Vqf32_vadd_Vqf32Vqf32(sum2_hi, Q6_V_hi_W(sq2)); + sum3_lo = Q6_Vqf32_vadd_Vqf32Vqf32(sum3_lo, Q6_V_lo_W(sq3)); + sum3_hi = Q6_Vqf32_vadd_Vqf32Vqf32(sum3_hi, Q6_V_hi_W(sq3)); + } + + HVX_Vector_x4 sums = { .v = { + Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(sum0_lo, sum0_hi)), + Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(sum1_lo, sum1_hi)), + Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(sum2_lo, sum2_hi)), + Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(sum3_lo, sum3_hi)), + } }; +#endif + rms_norm_scale_4rows_from_sums(sums, inv_ne0_v, eps_v, scale_param_v, scale_v0, scale_v1, scale_v2, scale_v3); +} + +static __attribute__((noinline)) float rms_norm_tile_sum_sq_f32(const uint8_t * restrict src, + uint32_t num_elems) { + HVX_Vector sum_v = Q6_V_vsplat_R(0x00000000); + sum_v = rms_norm_sum_sq_f32(src, num_elems, sum_v); + sum_v = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_v)); + return hvx_vec_get_f32(sum_v); +} + +static __attribute__((noinline)) float rms_norm_tile_sum_sq_f16(const uint8_t * restrict src, + uint32_t num_elems) { + HVX_Vector sum_v = Q6_V_vsplat_R(0x00000000); + sum_v = rms_norm_sum_sq_f16(src, num_elems, sum_v); + sum_v = hvx_vec_reduce_sum_f32(Q6_Vsf_equals_Vqf32(sum_v)); + return hvx_vec_get_f32(sum_v); +} + +static inline HVX_VectorPair rms_load_pair_f32(const uint8_t * restrict ptr, uint32_t i, bool is_f16) { + const HVX_Vector * restrict v_ptr = (const HVX_Vector *) ptr; + if (is_f16) { + return hvx_vec_f16_to_f32(v_ptr[i >> 6]); + } + return Q6_W_vcombine_VV(v_ptr[(i >> 5) + 1], v_ptr[i >> 5]); +} + +static inline HVX_Vector rms_load_vec_f32(const uint8_t * restrict ptr, uint32_t i, bool is_f16) { + const HVX_Vector * restrict v_ptr = (const HVX_Vector *) ptr; + if (!is_f16) { + return v_ptr[i >> 5]; + } + HVX_VectorPair p = hvx_vec_f16_to_f32(v_ptr[i >> 6]); + return (i & 32u) ? Q6_V_hi_W(p) : Q6_V_lo_W(p); +} + +static inline void rms_store_pair_f32(uint8_t * restrict dst, uint32_t i, HVX_Vector r0, HVX_Vector r1, bool is_f16) { + HVX_Vector * restrict v_dst = (HVX_Vector *) dst; + if (is_f16) { + r0 = hvx_vec_clamp_f16_f32(r0); + r1 = hvx_vec_clamp_f16_f32(r1); + v_dst[i >> 6] = hvx_vec_f32_to_f16(r0, r1); + } else { + v_dst[(i >> 5) + 0] = r0; + v_dst[(i >> 5) + 1] = r1; + } +} - hvx_fast_rms_norm_mul_f32(src_local, w_local, dst_local, ne0, epsilon, scale); +static inline void rms_store_tail_f32(uint8_t * restrict dst, uint32_t i, uint32_t rem, HVX_Vector r0, HVX_Vector r1, bool is_f16) { + HVX_Vector * restrict v_dst = (HVX_Vector *) dst; + if (is_f16) { + r0 = hvx_vec_clamp_f16_f32(r0); + r1 = hvx_vec_clamp_f16_f32(r1); + HVX_Vector packed = hvx_vec_f32_to_f16(r0, r1); + hvx_vec_store_a(&v_dst[i >> 6], rem * sizeof(_Float16), packed); + } else if (rem <= 32) { + hvx_vec_store_a(&v_dst[i >> 5], rem * sizeof(float), r0); + } else { + v_dst[(i >> 5) + 0] = r0; + hvx_vec_store_a(&v_dst[(i >> 5) + 1], (rem - 32) * sizeof(float), r1); } } -static void rms_norm_mul_add_f32(const void * restrict src, - const void * restrict weight, - const void * restrict add, - void * restrict dst, - const uint32_t num_rows, - const struct htp_unary_context * uctx) { - htp_unary_op_preamble; +static inline HVX_Vector rms_clamp_pack_f16_shuff(HVX_Vector r0, HVX_Vector r1, HVX_Vector f16_min, HVX_Vector f16_max) { + r0 = Q6_Vsf_vmin_VsfVsf(Q6_Vsf_vmax_VsfVsf(r0, f16_min), f16_max); + r1 = Q6_Vsf_vmin_VsfVsf(Q6_Vsf_vmax_VsfVsf(r1, f16_min), f16_max); + return hvx_vec_f32_to_f16_shuff(r0, r1); +} + +static inline HVX_Vector rms_clamp_pack_f16(HVX_Vector r0, HVX_Vector r1, HVX_Vector f16_min, HVX_Vector f16_max) { + return Q6_Vh_vdeal_Vh(rms_clamp_pack_f16_shuff(r0, r1, f16_min, f16_max)); +} + +static inline void rms_norm_apply_row_f16(const uint8_t * restrict src, + uint8_t * restrict dst, + uint32_t n, + HVX_Vector scale_v) { + const HVX_Vector * restrict v_src = (const HVX_Vector *) src; + HVX_Vector * restrict v_dst = (HVX_Vector *) dst; + + const uint32_t nvec = n / VLEN_FP16; + const uint32_t nloe = n % VLEN_FP16; + + const HVX_Vector one_hf = hvx_vec_splat_f16(1.0f); + const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f); + const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f); +#if __HVX_ARCH__ < 79 + const HVX_Vector scale_qf = Q6_Vqf32_vadd_VsfVsf(scale_v, Q6_V_vzero()); +#endif + + #pragma unroll(2) + for (uint32_t k = 0; k < nvec; k++) { +#if __HVX_ARCH__ >= 79 + HVX_VectorPair sp = Q6_Wsf_vmpy_VhfVhf(v_src[k], one_hf); + HVX_Vector r0 = Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp), scale_v); + HVX_Vector r1 = Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp), scale_v); +#else + HVX_VectorPair sp = Q6_Wqf32_vmpy_VhfVhf(v_src[k], one_hf); + HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp), scale_qf)); + HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp), scale_qf)); +#endif + v_dst[k] = rms_clamp_pack_f16_shuff(r0, r1, f16_min, f16_max); + } + + if (nloe > 0) { +#if __HVX_ARCH__ >= 79 + HVX_VectorPair sp = Q6_Wsf_vmpy_VhfVhf(v_src[nvec], one_hf); + HVX_Vector r0 = Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp), scale_v); + HVX_Vector r1 = Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp), scale_v); +#else + HVX_VectorPair sp = Q6_Wqf32_vmpy_VhfVhf(v_src[nvec], one_hf); + HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp), scale_qf)); + HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp), scale_qf)); +#endif + HVX_Vector packed = rms_clamp_pack_f16_shuff(r0, r1, f16_min, f16_max); + hvx_vec_store_a(&v_dst[nvec], nloe * sizeof(_Float16), packed); + } +} + +static inline void rms_norm_apply_row_mul_f16_f32(const uint8_t * restrict src, + const uint8_t * restrict mul, + uint8_t * restrict dst, + uint32_t n, + HVX_Vector scale_v) { + const HVX_Vector * restrict v_src = (const HVX_Vector *) src; + const HVX_Vector * restrict v_w = (const HVX_Vector *) mul; + HVX_Vector * restrict v_dst = (HVX_Vector *) dst; + + const uint32_t nvec = n / VLEN_FP16; + const uint32_t nloe = n % VLEN_FP16; + + const HVX_Vector one_hf = hvx_vec_splat_f16(1.0); + const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f); + const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f); + + #pragma unroll(2) + for (uint32_t k = 0; k < nvec; k++) { +#if __HVX_ARCH__ >= 79 + HVX_VectorPair sp = Q6_Wsf_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_src[k]), one_hf); + HVX_Vector ws0 = Q6_Vsf_vmpy_VsfVsf(v_w[2 * k + 0], scale_v); + HVX_Vector ws1 = Q6_Vsf_vmpy_VsfVsf(v_w[2 * k + 1], scale_v); + HVX_Vector r0 = Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp), ws0); + HVX_Vector r1 = Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp), ws1); +#else + HVX_VectorPair sp = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_src[k]), one_hf); + HVX_Vector ws0 = Q6_Vqf32_vmpy_VsfVsf(v_w[2 * k + 0], scale_v); + HVX_Vector ws1 = Q6_Vqf32_vmpy_VsfVsf(v_w[2 * k + 1], scale_v); + HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp), ws0)); + HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp), ws1)); +#endif + v_dst[k] = rms_clamp_pack_f16(r0, r1, f16_min, f16_max); + } + + if (nloe > 0) { +#if __HVX_ARCH__ >= 79 + HVX_VectorPair sp = Q6_Wsf_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_src[nvec]), one_hf); + HVX_Vector ws0 = Q6_Vsf_vmpy_VsfVsf(v_w[2 * nvec + 0], scale_v); + HVX_Vector r0 = Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp), ws0); + HVX_Vector r1 = Q6_V_vzero(); + if (nloe > 32) { + HVX_Vector ws1 = Q6_Vsf_vmpy_VsfVsf(v_w[2 * nvec + 1], scale_v); + r1 = Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp), ws1); + } +#else + HVX_VectorPair sp = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_src[nvec]), one_hf); + HVX_Vector ws0 = Q6_Vqf32_vmpy_VsfVsf(v_w[2 * nvec + 0], scale_v); + HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp), ws0)); + HVX_Vector r1 = Q6_V_vzero(); + if (nloe > 32) { + HVX_Vector ws1 = Q6_Vqf32_vmpy_VsfVsf(v_w[2 * nvec + 1], scale_v); + r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp), ws1)); + } +#endif + HVX_Vector packed = rms_clamp_pack_f16(r0, r1, f16_min, f16_max); + hvx_vec_store_a(&v_dst[nvec], nloe * sizeof(_Float16), packed); + } +} + +static inline void rms_norm_apply_row_mul_f16_f16(const uint8_t * restrict src, + const uint8_t * restrict mul, + uint8_t * restrict dst, + uint32_t n, + HVX_Vector scale_v) { + const HVX_Vector * restrict v_src = (const HVX_Vector *) src; + const HVX_Vector * restrict v_w = (const HVX_Vector *) mul; + HVX_Vector * restrict v_dst = (HVX_Vector *) dst; + + const uint32_t nvec = n / VLEN_FP16; + const uint32_t nloe = n % VLEN_FP16; + + const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f); + const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f); +#if __HVX_ARCH__ < 79 + const HVX_Vector scale_qf = Q6_Vqf32_vadd_VsfVsf(scale_v, Q6_V_vzero()); +#endif + + #pragma unroll(2) + for (uint32_t k = 0; k < nvec; k++) { +#if __HVX_ARCH__ >= 79 + HVX_VectorPair sw = Q6_Wsf_vmpy_VhfVhf(v_src[k], v_w[k]); + HVX_Vector r0 = Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sw), scale_v); + HVX_Vector r1 = Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sw), scale_v); +#else + HVX_VectorPair sw = Q6_Wqf32_vmpy_VhfVhf(v_src[k], v_w[k]); + HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sw), scale_qf)); + HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sw), scale_qf)); +#endif + v_dst[k] = rms_clamp_pack_f16_shuff(r0, r1, f16_min, f16_max); + } + + if (nloe > 0) { +#if __HVX_ARCH__ >= 79 + HVX_VectorPair sw = Q6_Wsf_vmpy_VhfVhf(v_src[nvec], v_w[nvec]); + HVX_Vector r0 = Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sw), scale_v); + HVX_Vector r1 = Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sw), scale_v); +#else + HVX_VectorPair sw = Q6_Wqf32_vmpy_VhfVhf(v_src[nvec], v_w[nvec]); + HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sw), scale_qf)); + HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sw), scale_qf)); +#endif + HVX_Vector packed = rms_clamp_pack_f16_shuff(r0, r1, f16_min, f16_max); + hvx_vec_store_a(&v_dst[nvec], nloe * sizeof(_Float16), packed); + } +} + +static inline void rms_norm_apply_row_mul_add_f16_f32_f16(const uint8_t * restrict src, + const uint8_t * restrict mul, + const uint8_t * restrict add, + uint8_t * restrict dst, + uint32_t n, + HVX_Vector scale_v) { + const HVX_Vector * restrict v_src = (const HVX_Vector *) src; + const HVX_Vector * restrict v_w = (const HVX_Vector *) mul; + const HVX_Vector * restrict v_add = (const HVX_Vector *) add; + HVX_Vector * restrict v_dst = (HVX_Vector *) dst; + + const uint32_t nvec = n / VLEN_FP16; + const uint32_t nloe = n % VLEN_FP16; + + const HVX_Vector one_hf = hvx_vec_splat_f16(1.0); + const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f); + const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f); + + #pragma unroll(2) + for (uint32_t k = 0; k < nvec; k++) { +#if __HVX_ARCH__ >= 79 + HVX_VectorPair sp = Q6_Wsf_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_src[k]), one_hf); + HVX_VectorPair ap = Q6_Wsf_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_add[k]), one_hf); + HVX_Vector ws0 = Q6_Vsf_vmpy_VsfVsf(v_w[2 * k + 0], scale_v); + HVX_Vector ws1 = Q6_Vsf_vmpy_VsfVsf(v_w[2 * k + 1], scale_v); + HVX_Vector r0 = Q6_Vsf_vadd_VsfVsf(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp), ws0), Q6_V_lo_W(ap)); + HVX_Vector r1 = Q6_Vsf_vadd_VsfVsf(Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp), ws1), Q6_V_hi_W(ap)); +#else + HVX_VectorPair sp = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_src[k]), one_hf); + HVX_VectorPair ap = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_add[k]), one_hf); + HVX_Vector ws0 = Q6_Vqf32_vmpy_VsfVsf(v_w[2 * k + 0], scale_v); + HVX_Vector ws1 = Q6_Vqf32_vmpy_VsfVsf(v_w[2 * k + 1], scale_v); + HVX_Vector m0 = Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp), ws0); + HVX_Vector m1 = Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp), ws1); + HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(m0, Q6_V_lo_W(ap))); + HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(m1, Q6_V_hi_W(ap))); +#endif + v_dst[k] = rms_clamp_pack_f16(r0, r1, f16_min, f16_max); + } + + if (nloe > 0) { +#if __HVX_ARCH__ >= 79 + HVX_VectorPair sp = Q6_Wsf_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_src[nvec]), one_hf); + HVX_VectorPair ap = Q6_Wsf_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_add[nvec]), one_hf); + HVX_Vector ws0 = Q6_Vsf_vmpy_VsfVsf(v_w[2 * nvec + 0], scale_v); + HVX_Vector r0 = Q6_Vsf_vadd_VsfVsf(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp), ws0), Q6_V_lo_W(ap)); + HVX_Vector r1 = Q6_V_vzero(); + if (nloe > 32) { + HVX_Vector ws1 = Q6_Vsf_vmpy_VsfVsf(v_w[2 * nvec + 1], scale_v); + r1 = Q6_Vsf_vadd_VsfVsf(Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp), ws1), Q6_V_hi_W(ap)); + } +#else + HVX_VectorPair sp = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_src[nvec]), one_hf); + HVX_VectorPair ap = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(v_add[nvec]), one_hf); + HVX_Vector ws0 = Q6_Vqf32_vmpy_VsfVsf(v_w[2 * nvec + 0], scale_v); + HVX_Vector m0 = Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp), ws0); + HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(m0, Q6_V_lo_W(ap))); + HVX_Vector r1 = Q6_V_vzero(); + if (nloe > 32) { + HVX_Vector ws1 = Q6_Vqf32_vmpy_VsfVsf(v_w[2 * nvec + 1], scale_v); + HVX_Vector m1 = Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp), ws1); + r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(m1, Q6_V_hi_W(ap))); + } +#endif + HVX_Vector packed = rms_clamp_pack_f16(r0, r1, f16_min, f16_max); + hvx_vec_store_a(&v_dst[nvec], nloe * sizeof(_Float16), packed); + } +} + +static inline void rms_norm_apply_row_mul_add_f16_f16_f16(const uint8_t * restrict src, + const uint8_t * restrict mul, + const uint8_t * restrict add, + uint8_t * restrict dst, + uint32_t n, + HVX_Vector scale_v) { + const HVX_Vector * restrict v_src = (const HVX_Vector *) src; + const HVX_Vector * restrict v_w = (const HVX_Vector *) mul; + const HVX_Vector * restrict v_add = (const HVX_Vector *) add; + HVX_Vector * restrict v_dst = (HVX_Vector *) dst; + + const uint32_t nvec = n / VLEN_FP16; + const uint32_t nloe = n % VLEN_FP16; + + const HVX_Vector one_hf = hvx_vec_splat_f16(1.0); + const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f); + const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f); +#if __HVX_ARCH__ < 79 + const HVX_Vector scale_qf = Q6_Vqf32_vadd_VsfVsf(scale_v, Q6_V_vzero()); +#endif + + #pragma unroll(2) + for (uint32_t k = 0; k < nvec; k++) { +#if __HVX_ARCH__ >= 79 + HVX_VectorPair sw = Q6_Wsf_vmpy_VhfVhf(v_src[k], v_w[k]); + HVX_VectorPair ap = Q6_Wsf_vmpy_VhfVhf(v_add[k], one_hf); + HVX_Vector r0 = Q6_Vsf_vadd_VsfVsf(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sw), scale_v), Q6_V_lo_W(ap)); + HVX_Vector r1 = Q6_Vsf_vadd_VsfVsf(Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sw), scale_v), Q6_V_hi_W(ap)); +#else + HVX_VectorPair sw = Q6_Wqf32_vmpy_VhfVhf(v_src[k], v_w[k]); + HVX_VectorPair ap = Q6_Wqf32_vmpy_VhfVhf(v_add[k], one_hf); + HVX_Vector m0 = Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sw), scale_qf); + HVX_Vector m1 = Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sw), scale_qf); + HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(m0, Q6_V_lo_W(ap))); + HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(m1, Q6_V_hi_W(ap))); +#endif + v_dst[k] = rms_clamp_pack_f16_shuff(r0, r1, f16_min, f16_max); + } + + if (nloe > 0) { +#if __HVX_ARCH__ >= 79 + HVX_VectorPair sw = Q6_Wsf_vmpy_VhfVhf(v_src[nvec], v_w[nvec]); + HVX_VectorPair ap = Q6_Wsf_vmpy_VhfVhf(v_add[nvec], one_hf); + HVX_Vector r0 = Q6_Vsf_vadd_VsfVsf(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sw), scale_v), Q6_V_lo_W(ap)); + HVX_Vector r1 = Q6_Vsf_vadd_VsfVsf(Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sw), scale_v), Q6_V_hi_W(ap)); +#else + HVX_VectorPair sw = Q6_Wqf32_vmpy_VhfVhf(v_src[nvec], v_w[nvec]); + HVX_VectorPair ap = Q6_Wqf32_vmpy_VhfVhf(v_add[nvec], one_hf); + HVX_Vector m0 = Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sw), scale_qf); + HVX_Vector m1 = Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sw), scale_qf); + HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(m0, Q6_V_lo_W(ap))); + HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(m1, Q6_V_hi_W(ap))); +#endif + HVX_Vector packed = rms_clamp_pack_f16_shuff(r0, r1, f16_min, f16_max); + hvx_vec_store_a(&v_dst[nvec], nloe * sizeof(_Float16), packed); + } +} + +static inline void rms_norm_apply_row_inl_f16_f16(const uint8_t * restrict src, + const uint8_t * restrict mul, + const uint8_t * restrict add, + uint8_t * restrict dst, + uint32_t n, + HVX_Vector scale_v) { + (void) mul; + (void) add; + rms_norm_apply_row_f16(src, dst, n, scale_v); +} + +static inline void rms_norm_apply_row_inl_mul_f16_f32_f16(const uint8_t * restrict src, + const uint8_t * restrict mul, + const uint8_t * restrict add, + uint8_t * restrict dst, + uint32_t n, + HVX_Vector scale_v) { + (void) add; + rms_norm_apply_row_mul_f16_f32(src, mul, dst, n, scale_v); +} + +static inline void rms_norm_apply_row_inl_mul_f16_f16_f16(const uint8_t * restrict src, + const uint8_t * restrict mul, + const uint8_t * restrict add, + uint8_t * restrict dst, + uint32_t n, + HVX_Vector scale_v) { + (void) add; + rms_norm_apply_row_mul_f16_f16(src, mul, dst, n, scale_v); +} + +static inline void rms_norm_apply_row_inl_mul_add_f16_f32_f16_f16(const uint8_t * restrict src, + const uint8_t * restrict mul, + const uint8_t * restrict add, + uint8_t * restrict dst, + uint32_t n, + HVX_Vector scale_v) { + rms_norm_apply_row_mul_add_f16_f32_f16(src, mul, add, dst, n, scale_v); +} + +static inline void rms_norm_apply_row_inl_mul_add_f16_f16_f16_f16(const uint8_t * restrict src, + const uint8_t * restrict mul, + const uint8_t * restrict add, + uint8_t * restrict dst, + uint32_t n, + HVX_Vector scale_v) { + rms_norm_apply_row_mul_add_f16_f16_f16(src, mul, add, dst, n, scale_v); +} + +static inline void rms_norm_apply_4rows_inl_f16_f16(const uint8_t * restrict src, + size_t src_stride, + const uint8_t * restrict mul, + uint8_t * restrict dst, + size_t dst_stride, + uint32_t n, + HVX_Vector scale_v0, + HVX_Vector scale_v1, + HVX_Vector scale_v2, + HVX_Vector scale_v3) { + (void) mul; + const uint32_t nvec = n / VLEN_FP16; + const HVX_Vector one_hf = hvx_vec_splat_f16(1.0f); + const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f); + const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f); +#if __HVX_ARCH__ < 79 + const HVX_Vector scale_qf0 = Q6_Vqf32_vadd_VsfVsf(scale_v0, Q6_V_vzero()); + const HVX_Vector scale_qf1 = Q6_Vqf32_vadd_VsfVsf(scale_v1, Q6_V_vzero()); + const HVX_Vector scale_qf2 = Q6_Vqf32_vadd_VsfVsf(scale_v2, Q6_V_vzero()); + const HVX_Vector scale_qf3 = Q6_Vqf32_vadd_VsfVsf(scale_v3, Q6_V_vzero()); +#endif + + const uint8_t * restrict s0 = src; + uint8_t * restrict d0 = dst; + #pragma clang loop unroll(disable) pipeline(disable) + for (uint32_t k = 0; k < nvec; k++) { + const uint8_t * restrict s1 = s0 + src_stride; + const uint8_t * restrict s2 = s1 + src_stride; + const uint8_t * restrict s3 = s2 + src_stride; + uint8_t * restrict d1 = d0 + dst_stride; + uint8_t * restrict d2 = d1 + dst_stride; + uint8_t * restrict d3 = d2 + dst_stride; +#if __HVX_ARCH__ >= 79 + HVX_VectorPair sp0 = Q6_Wsf_vmpy_VhfVhf(*(const HVX_Vector *) s0, one_hf); + *(HVX_Vector *) d0 = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp0), scale_v0), + Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp0), scale_v0), f16_min, f16_max); + HVX_VectorPair sp1 = Q6_Wsf_vmpy_VhfVhf(*(const HVX_Vector *) s1, one_hf); + *(HVX_Vector *) d1 = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp1), scale_v1), + Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp1), scale_v1), f16_min, f16_max); + HVX_VectorPair sp2 = Q6_Wsf_vmpy_VhfVhf(*(const HVX_Vector *) s2, one_hf); + *(HVX_Vector *) d2 = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp2), scale_v2), + Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp2), scale_v2), f16_min, f16_max); + HVX_VectorPair sp3 = Q6_Wsf_vmpy_VhfVhf(*(const HVX_Vector *) s3, one_hf); + *(HVX_Vector *) d3 = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp3), scale_v3), + Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp3), scale_v3), f16_min, f16_max); +#else + HVX_VectorPair sp0 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_Vector *) s0, one_hf); + *(HVX_Vector *) d0 = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp0), scale_qf0)), + Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp0), scale_qf0)), f16_min, f16_max); + HVX_VectorPair sp1 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_Vector *) s1, one_hf); + *(HVX_Vector *) d1 = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp1), scale_qf1)), + Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp1), scale_qf1)), f16_min, f16_max); + HVX_VectorPair sp2 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_Vector *) s2, one_hf); + *(HVX_Vector *) d2 = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp2), scale_qf2)), + Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp2), scale_qf2)), f16_min, f16_max); + HVX_VectorPair sp3 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_Vector *) s3, one_hf); + *(HVX_Vector *) d3 = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp3), scale_qf3)), + Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp3), scale_qf3)), f16_min, f16_max); +#endif + s0 += VLEN; + d0 += VLEN; + } +} + +static inline void rms_norm_apply_4rows_inl_mul_f16_f32_f16(const uint8_t * restrict src, + size_t src_stride, + const uint8_t * restrict mul, + uint8_t * restrict dst, + size_t dst_stride, + uint32_t n, + HVX_Vector scale_v0, + HVX_Vector scale_v1, + HVX_Vector scale_v2, + HVX_Vector scale_v3) { + const HVX_Vector * restrict v_w = (const HVX_Vector *) mul; + + const uint32_t nvec = n / VLEN_FP16; + const HVX_Vector one_hf = hvx_vec_splat_f16(1.0f); + const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f); + const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f); + + const uint8_t * restrict s0 = src; + uint8_t * restrict d0 = dst; + #pragma clang loop unroll(disable) pipeline(disable) + for (uint32_t k = 0; k < nvec; k++) { + HVX_VectorPair wp = Q6_W_vdeal_VVR(v_w[2 * k + 1], v_w[2 * k + 0], -4); + HVX_Vector we = Q6_V_lo_W(wp); + HVX_Vector wo = Q6_V_hi_W(wp); + const uint8_t * restrict s1 = s0 + src_stride; + const uint8_t * restrict s2 = s1 + src_stride; + const uint8_t * restrict s3 = s2 + src_stride; + uint8_t * restrict d1 = d0 + dst_stride; + uint8_t * restrict d2 = d1 + dst_stride; + uint8_t * restrict d3 = d2 + dst_stride; +#if __HVX_ARCH__ >= 79 + HVX_VectorPair sp0 = Q6_Wsf_vmpy_VhfVhf(*(const HVX_Vector *) s0, one_hf); + *(HVX_Vector *) d0 = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp0), Q6_Vsf_vmpy_VsfVsf(we, scale_v0)), + Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp0), Q6_Vsf_vmpy_VsfVsf(wo, scale_v0)), f16_min, f16_max); + HVX_VectorPair sp1 = Q6_Wsf_vmpy_VhfVhf(*(const HVX_Vector *) s1, one_hf); + *(HVX_Vector *) d1 = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp1), Q6_Vsf_vmpy_VsfVsf(we, scale_v1)), + Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp1), Q6_Vsf_vmpy_VsfVsf(wo, scale_v1)), f16_min, f16_max); + HVX_VectorPair sp2 = Q6_Wsf_vmpy_VhfVhf(*(const HVX_Vector *) s2, one_hf); + *(HVX_Vector *) d2 = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp2), Q6_Vsf_vmpy_VsfVsf(we, scale_v2)), + Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp2), Q6_Vsf_vmpy_VsfVsf(wo, scale_v2)), f16_min, f16_max); + HVX_VectorPair sp3 = Q6_Wsf_vmpy_VhfVhf(*(const HVX_Vector *) s3, one_hf); + *(HVX_Vector *) d3 = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sp3), Q6_Vsf_vmpy_VsfVsf(we, scale_v3)), + Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sp3), Q6_Vsf_vmpy_VsfVsf(wo, scale_v3)), f16_min, f16_max); +#else + HVX_VectorPair sp0 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_Vector *) s0, one_hf); + *(HVX_Vector *) d0 = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp0), Q6_Vqf32_vmpy_VsfVsf(we, scale_v0))), + Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp0), Q6_Vqf32_vmpy_VsfVsf(wo, scale_v0))), f16_min, f16_max); + HVX_VectorPair sp1 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_Vector *) s1, one_hf); + *(HVX_Vector *) d1 = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp1), Q6_Vqf32_vmpy_VsfVsf(we, scale_v1))), + Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp1), Q6_Vqf32_vmpy_VsfVsf(wo, scale_v1))), f16_min, f16_max); + HVX_VectorPair sp2 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_Vector *) s2, one_hf); + *(HVX_Vector *) d2 = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp2), Q6_Vqf32_vmpy_VsfVsf(we, scale_v2))), + Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp2), Q6_Vqf32_vmpy_VsfVsf(wo, scale_v2))), f16_min, f16_max); + HVX_VectorPair sp3 = Q6_Wqf32_vmpy_VhfVhf(*(const HVX_Vector *) s3, one_hf); + *(HVX_Vector *) d3 = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sp3), Q6_Vqf32_vmpy_VsfVsf(we, scale_v3))), + Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sp3), Q6_Vqf32_vmpy_VsfVsf(wo, scale_v3))), f16_min, f16_max); +#endif + s0 += VLEN; + d0 += VLEN; + } +} + +static inline void rms_norm_apply_4rows_inl_mul_f16_f16_f16(const uint8_t * restrict src, + size_t src_stride, + const uint8_t * restrict mul, + uint8_t * restrict dst, + size_t dst_stride, + uint32_t n, + HVX_Vector scale_v0, + HVX_Vector scale_v1, + HVX_Vector scale_v2, + HVX_Vector scale_v3) { + const HVX_Vector * restrict v_src0 = (const HVX_Vector *) (src + 0 * src_stride); + const HVX_Vector * restrict v_src1 = (const HVX_Vector *) (src + 1 * src_stride); + const HVX_Vector * restrict v_src2 = (const HVX_Vector *) (src + 2 * src_stride); + const HVX_Vector * restrict v_src3 = (const HVX_Vector *) (src + 3 * src_stride); + const HVX_Vector * restrict v_w = (const HVX_Vector *) mul; + HVX_Vector * restrict v_dst0 = (HVX_Vector *) (dst + 0 * dst_stride); + HVX_Vector * restrict v_dst1 = (HVX_Vector *) (dst + 1 * dst_stride); + HVX_Vector * restrict v_dst2 = (HVX_Vector *) (dst + 2 * dst_stride); + HVX_Vector * restrict v_dst3 = (HVX_Vector *) (dst + 3 * dst_stride); + + const uint32_t nvec = n / VLEN_FP16; + const HVX_Vector f16_max = hvx_vec_splat_f32(65504.0f); + const HVX_Vector f16_min = hvx_vec_splat_f32(-65504.0f); +#if __HVX_ARCH__ < 79 + const HVX_Vector scale_qf0 = Q6_Vqf32_vadd_VsfVsf(scale_v0, Q6_V_vzero()); + const HVX_Vector scale_qf1 = Q6_Vqf32_vadd_VsfVsf(scale_v1, Q6_V_vzero()); + const HVX_Vector scale_qf2 = Q6_Vqf32_vadd_VsfVsf(scale_v2, Q6_V_vzero()); + const HVX_Vector scale_qf3 = Q6_Vqf32_vadd_VsfVsf(scale_v3, Q6_V_vzero()); +#endif + + #pragma clang loop unroll(disable) + for (uint32_t k = 0; k < nvec; k++) { + HVX_Vector wk = v_w[k]; +#if __HVX_ARCH__ >= 79 + HVX_VectorPair sw0 = Q6_Wsf_vmpy_VhfVhf(v_src0[k], wk); + HVX_VectorPair sw1 = Q6_Wsf_vmpy_VhfVhf(v_src1[k], wk); + v_dst0[k] = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sw0), scale_v0), + Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sw0), scale_v0), f16_min, f16_max); + v_dst1[k] = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sw1), scale_v1), + Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sw1), scale_v1), f16_min, f16_max); + + HVX_VectorPair sw2 = Q6_Wsf_vmpy_VhfVhf(v_src2[k], wk); + HVX_VectorPair sw3 = Q6_Wsf_vmpy_VhfVhf(v_src3[k], wk); + v_dst2[k] = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sw2), scale_v2), + Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sw2), scale_v2), f16_min, f16_max); + v_dst3[k] = rms_clamp_pack_f16_shuff(Q6_Vsf_vmpy_VsfVsf(Q6_V_lo_W(sw3), scale_v3), + Q6_Vsf_vmpy_VsfVsf(Q6_V_hi_W(sw3), scale_v3), f16_min, f16_max); +#else + HVX_VectorPair sw0 = Q6_Wqf32_vmpy_VhfVhf(v_src0[k], wk); + HVX_VectorPair sw1 = Q6_Wqf32_vmpy_VhfVhf(v_src1[k], wk); + v_dst0[k] = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sw0), scale_qf0)), + Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sw0), scale_qf0)), f16_min, f16_max); + v_dst1[k] = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sw1), scale_qf1)), + Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sw1), scale_qf1)), f16_min, f16_max); + + HVX_VectorPair sw2 = Q6_Wqf32_vmpy_VhfVhf(v_src2[k], wk); + HVX_VectorPair sw3 = Q6_Wqf32_vmpy_VhfVhf(v_src3[k], wk); + v_dst2[k] = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sw2), scale_qf2)), + Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sw2), scale_qf2)), f16_min, f16_max); + v_dst3[k] = rms_clamp_pack_f16_shuff(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(sw3), scale_qf3)), + Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(sw3), scale_qf3)), f16_min, f16_max); +#endif + } +} + +#define DEFINE_RMS_NORM_APPLY_ROW(SFX, HAS_MUL, HAS_ADD, S0_F16, S1_F16, S2_F16, D_F16) \ + static inline void rms_norm_apply_row_inl_##SFX(const uint8_t * restrict src, \ + const uint8_t * restrict mul, \ + const uint8_t * restrict add, \ + uint8_t * restrict dst, \ + uint32_t n, \ + HVX_Vector scale_v) { \ + (void) mul; \ + (void) add; \ + uint32_t i = 0; \ + for (; i + 64 <= n; i += 64) { \ + HVX_VectorPair sp = rms_load_pair_f32(src, i, S0_F16); \ + HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(sp), scale_v)); \ + HVX_Vector r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(sp), scale_v)); \ + if (HAS_MUL) { \ + HVX_VectorPair wp = rms_load_pair_f32(mul, i, S1_F16); \ + r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r0, Q6_V_lo_W(wp))); \ + r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r1, Q6_V_hi_W(wp))); \ + } \ + if (HAS_ADD) { \ + HVX_VectorPair ap = rms_load_pair_f32(add, i, S2_F16); \ + r0 = hvx_vec_add_f32_f32(r0, Q6_V_lo_W(ap)); \ + r1 = hvx_vec_add_f32_f32(r1, Q6_V_hi_W(ap)); \ + } \ + rms_store_pair_f32(dst, i, r0, r1, D_F16); \ + } \ + if (i < n) { \ + const uint32_t rem = n - i; \ + HVX_Vector r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(rms_load_vec_f32(src, i, S0_F16), scale_v)); \ + HVX_Vector r1 = Q6_V_vzero(); \ + if (rem > 32) { \ + r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(rms_load_vec_f32(src, i + 32, S0_F16), scale_v)); \ + } \ + if (HAS_MUL) { \ + r0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r0, rms_load_vec_f32(mul, i, S1_F16))); \ + if (rem > 32) { \ + r1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r1, rms_load_vec_f32(mul, i + 32, S1_F16))); \ + } \ + } \ + if (HAS_ADD) { \ + r0 = hvx_vec_add_f32_f32(r0, rms_load_vec_f32(add, i, S2_F16)); \ + if (rem > 32) { \ + r1 = hvx_vec_add_f32_f32(r1, rms_load_vec_f32(add, i + 32, S2_F16)); \ + } \ + } \ + rms_store_tail_f32(dst, i, rem, r0, r1, D_F16); \ + } \ + } + +#define DEFINE_RMS_NORM_APPLY_4ROWS(SFX, HAS_MUL, S0_F16, S1_F16, D_F16) \ + static inline void rms_norm_apply_4rows_inl_##SFX(const uint8_t * restrict src, \ + size_t src_stride, \ + const uint8_t * restrict mul, \ + uint8_t * restrict dst, \ + size_t dst_stride, \ + uint32_t n, \ + HVX_Vector scale_v0, \ + HVX_Vector scale_v1, \ + HVX_Vector scale_v2, \ + HVX_Vector scale_v3) { \ + (void) mul; \ + _Pragma("clang loop unroll(disable) pipeline(disable)") \ + for (uint32_t i = 0; i < n; i += 64) { \ + HVX_VectorPair wp = Q6_W_vzero(); \ + if (HAS_MUL) { \ + wp = rms_load_pair_f32(mul, i, S1_F16); \ + } \ + const uint8_t * restrict s = src; \ + uint8_t * restrict d = dst; \ + HVX_VectorPair sp0 = rms_load_pair_f32(s, i, S0_F16); \ + HVX_Vector r00 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(sp0), scale_v0)); \ + HVX_Vector r01 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(sp0), scale_v0)); \ + if (HAS_MUL) { \ + r00 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r00, Q6_V_lo_W(wp))); \ + r01 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r01, Q6_V_hi_W(wp))); \ + } \ + rms_store_pair_f32(d, i, r00, r01, D_F16); \ + s += src_stride; \ + d += dst_stride; \ + HVX_VectorPair sp1 = rms_load_pair_f32(s, i, S0_F16); \ + HVX_Vector r10 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(sp1), scale_v1)); \ + HVX_Vector r11 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(sp1), scale_v1)); \ + if (HAS_MUL) { \ + r10 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r10, Q6_V_lo_W(wp))); \ + r11 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r11, Q6_V_hi_W(wp))); \ + } \ + rms_store_pair_f32(d, i, r10, r11, D_F16); \ + s += src_stride; \ + d += dst_stride; \ + HVX_VectorPair sp2 = rms_load_pair_f32(s, i, S0_F16); \ + HVX_Vector r20 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(sp2), scale_v2)); \ + HVX_Vector r21 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(sp2), scale_v2)); \ + if (HAS_MUL) { \ + r20 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r20, Q6_V_lo_W(wp))); \ + r21 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r21, Q6_V_hi_W(wp))); \ + } \ + rms_store_pair_f32(d, i, r20, r21, D_F16); \ + s += src_stride; \ + d += dst_stride; \ + HVX_VectorPair sp3 = rms_load_pair_f32(s, i, S0_F16); \ + HVX_Vector r30 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_lo_W(sp3), scale_v3)); \ + HVX_Vector r31 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_hi_W(sp3), scale_v3)); \ + if (HAS_MUL) { \ + r30 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r30, Q6_V_lo_W(wp))); \ + r31 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vmpy_VsfVsf(r31, Q6_V_hi_W(wp))); \ + } \ + rms_store_pair_f32(d, i, r30, r31, D_F16); \ + } \ + } + +DEFINE_RMS_NORM_APPLY_ROW(f32_f32, false, false, false, false, false, false) +DEFINE_RMS_NORM_APPLY_ROW(f32_f16, false, false, false, false, false, true) +DEFINE_RMS_NORM_APPLY_ROW(f16_f32, false, false, true, false, false, false) + +DEFINE_RMS_NORM_APPLY_ROW(mul_f32_f32_f32, true, false, false, false, false, false) +DEFINE_RMS_NORM_APPLY_ROW(mul_f32_f16_f32, true, false, false, true, false, false) +DEFINE_RMS_NORM_APPLY_ROW(mul_f32_f32_f16, true, false, false, false, false, true) +DEFINE_RMS_NORM_APPLY_ROW(mul_f32_f16_f16, true, false, false, true, false, true) +DEFINE_RMS_NORM_APPLY_ROW(mul_f16_f32_f32, true, false, true, false, false, false) +DEFINE_RMS_NORM_APPLY_ROW(mul_f16_f16_f32, true, false, true, true, false, false) + +DEFINE_RMS_NORM_APPLY_4ROWS(f32_f32, false, false, false, false) +DEFINE_RMS_NORM_APPLY_4ROWS(f32_f16, false, false, false, true) +DEFINE_RMS_NORM_APPLY_4ROWS(f16_f32, false, true, false, false) + +DEFINE_RMS_NORM_APPLY_4ROWS(mul_f32_f32_f32, true, false, false, false) +DEFINE_RMS_NORM_APPLY_4ROWS(mul_f32_f16_f32, true, false, true, false) +DEFINE_RMS_NORM_APPLY_4ROWS(mul_f32_f32_f16, true, false, false, true) +DEFINE_RMS_NORM_APPLY_4ROWS(mul_f32_f16_f16, true, false, true, true) +DEFINE_RMS_NORM_APPLY_4ROWS(mul_f16_f32_f32, true, true, false, false) +DEFINE_RMS_NORM_APPLY_4ROWS(mul_f16_f16_f32, true, true, true, false) + +DEFINE_RMS_NORM_APPLY_ROW(mul_add_f32_f32_f32_f32, true, true, false, false, false, false) +DEFINE_RMS_NORM_APPLY_ROW(mul_add_f32_f32_f32_f16, true, true, false, false, false, true) +DEFINE_RMS_NORM_APPLY_ROW(mul_add_f32_f32_f16_f32, true, true, false, false, true, false) +DEFINE_RMS_NORM_APPLY_ROW(mul_add_f32_f32_f16_f16, true, true, false, false, true, true) +DEFINE_RMS_NORM_APPLY_ROW(mul_add_f32_f16_f32_f32, true, true, false, true, false, false) +DEFINE_RMS_NORM_APPLY_ROW(mul_add_f32_f16_f32_f16, true, true, false, true, false, true) +DEFINE_RMS_NORM_APPLY_ROW(mul_add_f32_f16_f16_f32, true, true, false, true, true, false) +DEFINE_RMS_NORM_APPLY_ROW(mul_add_f32_f16_f16_f16, true, true, false, true, true, true) +DEFINE_RMS_NORM_APPLY_ROW(mul_add_f16_f32_f32_f32, true, true, true, false, false, false) +DEFINE_RMS_NORM_APPLY_ROW(mul_add_f16_f32_f32_f16, true, true, true, false, false, true) +DEFINE_RMS_NORM_APPLY_ROW(mul_add_f16_f32_f16_f32, true, true, true, false, true, false) +DEFINE_RMS_NORM_APPLY_ROW(mul_add_f16_f16_f32_f32, true, true, true, true, false, false) +DEFINE_RMS_NORM_APPLY_ROW(mul_add_f16_f16_f32_f16, true, true, true, true, false, true) +DEFINE_RMS_NORM_APPLY_ROW(mul_add_f16_f16_f16_f32, true, true, true, true, true, false) + +#undef DEFINE_RMS_NORM_APPLY_ROW +#undef DEFINE_RMS_NORM_APPLY_4ROWS + +#define DEFINE_RMS_NORM_BLOCK_FNS(SFX, S0_TY) \ + static __attribute__((noinline)) void rms_norm_apply_tile_row_##SFX(const uint8_t * restrict src, \ + const uint8_t * restrict mul, \ + const uint8_t * restrict add, \ + uint8_t * restrict dst, \ + uint32_t n, \ + HVX_Vector scale_v) { \ + rms_norm_apply_row_inl_##SFX(src, mul, add, dst, n, scale_v); \ + } \ + static __attribute__((noinline)) void rms_norm_rows_##SFX(const void * restrict src, \ + void * restrict dst, \ + const uint32_t num_rows, \ + const uint32_t ne0, \ + const struct htp_unary_context * uctx) { \ + htp_unary_op_preamble; \ + float epsilon = 0.f; \ + float scale = 0.f; \ + memcpy(&epsilon, &op_params[0], sizeof(float)); \ + memcpy(&scale, &op_params[1], sizeof(float)); \ + const HVX_Vector inv_ne0_v = hvx_vec_inverse_f32(hvx_vec_splat_f32((float) (int32_t) ne0)); \ + const HVX_Vector eps_v = hvx_vec_splat_f32(epsilon); \ + const HVX_Vector scale_param_v = hvx_vec_splat_f32((scale != 0.0f) ? scale : 1.0f); \ + const uint8_t * restrict src_local = (const uint8_t *) src; \ + uint8_t * restrict dst_local = (uint8_t *) dst; \ + uint32_t ir = 0; \ + if ((ne0 & 63u) == 0) { \ + for (; ir + 4 <= num_rows; ir += 4) { \ + HVX_Vector scale_v0, scale_v1, scale_v2, scale_v3; \ + rms_norm_4rows_scale_precomp_##S0_TY(src_local, src0_row_size_aligned, ne0, \ + inv_ne0_v, eps_v, scale_param_v, \ + &scale_v0, &scale_v1, &scale_v2, &scale_v3); \ + rms_norm_apply_4rows_inl_##SFX(src_local, src0_row_size_aligned, NULL, \ + dst_local, dst_row_size_aligned, ne0, \ + scale_v0, scale_v1, scale_v2, scale_v3); \ + src_local += 4 * src0_row_size_aligned; \ + dst_local += 4 * dst_row_size_aligned; \ + } \ + } \ + for (; ir < num_rows; ir++) { \ + HVX_Vector scale_v = rms_norm_row_scale_precomp_##S0_TY(src_local, ne0, inv_ne0_v, eps_v, scale_param_v); \ + rms_norm_apply_row_inl_##SFX(src_local, NULL, NULL, dst_local, ne0, scale_v); \ + src_local += src0_row_size_aligned; \ + dst_local += dst_row_size_aligned; \ + } \ + } + +#define DEFINE_RMS_NORM_MUL_BLOCK_FNS(SFX, S0_TY) \ + static __attribute__((noinline)) void rms_norm_apply_tile_row_mul_##SFX(const uint8_t * restrict src, \ + const uint8_t * restrict mul, \ + const uint8_t * restrict add, \ + uint8_t * restrict dst, \ + uint32_t n, \ + HVX_Vector scale_v) { \ + rms_norm_apply_row_inl_mul_##SFX(src, mul, add, dst, n, scale_v); \ + } \ + static __attribute__((noinline)) void rms_norm_mul_rows_##SFX(const void * restrict src, \ + const void * restrict mul, \ + void * restrict dst, \ + const uint32_t num_rows, \ + const uint32_t src1_row_start, \ + const struct htp_unary_context * uctx) { \ + htp_unary_op_preamble; \ + const uint32_t ne0 = uctx->nc; \ + float epsilon = 0.f; \ + float scale = 0.f; \ + memcpy(&epsilon, &op_params[0], sizeof(float)); \ + memcpy(&scale, &op_params[1], sizeof(float)); \ + const HVX_Vector inv_ne0_v = hvx_vec_inverse_f32(hvx_vec_splat_f32((float) (int32_t) ne0)); \ + const HVX_Vector eps_v = hvx_vec_splat_f32(epsilon); \ + const HVX_Vector scale_param_v = hvx_vec_splat_f32((scale != 0.0f) ? scale : 1.0f); \ + const size_t mul_stride = uctx->src1_block_stride; \ + const uint8_t * mul_base = (const uint8_t *) mul; \ + const uint8_t * mul_end = (uctx->broadcast_src1 && uctx->src1_nrows > 1) \ + ? (mul_base + (size_t) uctx->src1_nrows * mul_stride) \ + : NULL; \ + const uint8_t * restrict src_local = (const uint8_t *) src; \ + const uint8_t * restrict mul_local = mul_base + (size_t) src1_row_start * mul_stride; \ + uint8_t * restrict dst_local = (uint8_t *) dst; \ + uint32_t ir = 0; \ + if ((ne0 & 63u) == 0 && mul_stride == 0) { \ + for (; ir + 4 <= num_rows; ir += 4) { \ + HVX_Vector scale_v0, scale_v1, scale_v2, scale_v3; \ + rms_norm_4rows_scale_precomp_##S0_TY(src_local, src0_row_size_aligned, ne0, \ + inv_ne0_v, eps_v, scale_param_v, \ + &scale_v0, &scale_v1, &scale_v2, &scale_v3); \ + rms_norm_apply_4rows_inl_mul_##SFX(src_local, src0_row_size_aligned, mul_base, \ + dst_local, dst_row_size_aligned, ne0, \ + scale_v0, scale_v1, scale_v2, scale_v3); \ + src_local += 4 * src0_row_size_aligned; \ + dst_local += 4 * dst_row_size_aligned; \ + } \ + } \ + for (; ir < num_rows; ir++) { \ + HVX_Vector scale_v = rms_norm_row_scale_precomp_##S0_TY(src_local, ne0, inv_ne0_v, eps_v, scale_param_v); \ + rms_norm_apply_row_inl_mul_##SFX(src_local, mul_local, NULL, dst_local, ne0, scale_v); \ + src_local += src0_row_size_aligned; \ + dst_local += dst_row_size_aligned; \ + mul_local += mul_stride; \ + if (mul_local == mul_end) { \ + mul_local = mul_base; \ + } \ + } \ + } + +#define DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(SFX, S0_TY) \ + static __attribute__((noinline)) void rms_norm_apply_tile_row_mul_add_##SFX(const uint8_t * restrict src, \ + const uint8_t * restrict mul, \ + const uint8_t * restrict add, \ + uint8_t * restrict dst, \ + uint32_t n, \ + HVX_Vector scale_v) { \ + rms_norm_apply_row_inl_mul_add_##SFX(src, mul, add, dst, n, scale_v); \ + } \ + static __attribute__((noinline)) void rms_norm_mul_add_rows_##SFX(const void * restrict src, \ + const void * restrict mul, \ + const void * restrict add, \ + void * restrict dst, \ + const uint32_t num_rows, \ + const uint32_t src1_row_start, \ + const struct htp_unary_context * uctx) { \ + htp_unary_op_preamble; \ + const uint32_t ne0 = uctx->nc; \ + const size_t src2_row_size_aligned = uctx->src2_row_size_aligned; \ + float epsilon = 0.f; \ + float scale = 0.f; \ + memcpy(&epsilon, &op_params[0], sizeof(float)); \ + memcpy(&scale, &op_params[1], sizeof(float)); \ + const HVX_Vector inv_ne0_v = hvx_vec_inverse_f32(hvx_vec_splat_f32((float) (int32_t) ne0)); \ + const HVX_Vector eps_v = hvx_vec_splat_f32(epsilon); \ + const HVX_Vector scale_param_v = hvx_vec_splat_f32((scale != 0.0f) ? scale : 1.0f); \ + const size_t mul_stride = uctx->src1_block_stride; \ + const uint8_t * mul_base = (const uint8_t *) mul; \ + const uint8_t * mul_end = (uctx->broadcast_src1 && uctx->src1_nrows > 1) \ + ? (mul_base + (size_t) uctx->src1_nrows * mul_stride) \ + : NULL; \ + const uint8_t * restrict src_local = (const uint8_t *) src; \ + const uint8_t * restrict mul_local = mul_base + (size_t) src1_row_start * mul_stride; \ + const uint8_t * restrict add_local = (const uint8_t *) add; \ + uint8_t * restrict dst_local = (uint8_t *) dst; \ + for (uint32_t ir = 0; ir < num_rows; ir++) { \ + HVX_Vector scale_v = rms_norm_row_scale_precomp_##S0_TY(src_local, ne0, inv_ne0_v, eps_v, scale_param_v); \ + rms_norm_apply_row_inl_mul_add_##SFX(src_local, mul_local, add_local, dst_local, ne0, scale_v); \ + src_local += src0_row_size_aligned; \ + add_local += src2_row_size_aligned; \ + dst_local += dst_row_size_aligned; \ + mul_local += mul_stride; \ + if (mul_local == mul_end) { \ + mul_local = mul_base; \ + } \ + } \ + } + +DEFINE_RMS_NORM_BLOCK_FNS(f32_f32, f32) +DEFINE_RMS_NORM_BLOCK_FNS(f32_f16, f32) +DEFINE_RMS_NORM_BLOCK_FNS(f16_f32, f16) +DEFINE_RMS_NORM_BLOCK_FNS(f16_f16, f16) + +DEFINE_RMS_NORM_MUL_BLOCK_FNS(f32_f32_f32, f32) +DEFINE_RMS_NORM_MUL_BLOCK_FNS(f32_f32_f16, f32) +DEFINE_RMS_NORM_MUL_BLOCK_FNS(f32_f16_f32, f32) +DEFINE_RMS_NORM_MUL_BLOCK_FNS(f32_f16_f16, f32) +DEFINE_RMS_NORM_MUL_BLOCK_FNS(f16_f32_f32, f16) +DEFINE_RMS_NORM_MUL_BLOCK_FNS(f16_f32_f16, f16) +DEFINE_RMS_NORM_MUL_BLOCK_FNS(f16_f16_f32, f16) +DEFINE_RMS_NORM_MUL_BLOCK_FNS(f16_f16_f16, f16) + +DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f32_f32_f32_f32, f32) +DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f32_f32_f32_f16, f32) +DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f32_f32_f16_f32, f32) +DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f32_f32_f16_f16, f32) +DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f32_f16_f32_f32, f32) +DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f32_f16_f32_f16, f32) +DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f32_f16_f16_f32, f32) +DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f32_f16_f16_f16, f32) +DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f16_f32_f32_f32, f16) +DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f16_f32_f32_f16, f16) +DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f16_f32_f16_f32, f16) +DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f16_f32_f16_f16, f16) +DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f16_f16_f32_f32, f16) +DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f16_f16_f32_f16, f16) +DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f16_f16_f16_f32, f16) +DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS(f16_f16_f16_f16, f16) + +#undef DEFINE_RMS_NORM_BLOCK_FNS +#undef DEFINE_RMS_NORM_MUL_BLOCK_FNS +#undef DEFINE_RMS_NORM_MUL_ADD_BLOCK_FNS + +static const rms_apply_row_fn_t rms_norm_apply_row_table[2][2] = { + { rms_norm_apply_tile_row_f32_f32, rms_norm_apply_tile_row_f32_f16 }, + { rms_norm_apply_tile_row_f16_f32, rms_norm_apply_tile_row_f16_f16 }, +}; + +static const rms_apply_row_fn_t rms_norm_mul_apply_row_table[2][2][2] = { + { + { rms_norm_apply_tile_row_mul_f32_f32_f32, rms_norm_apply_tile_row_mul_f32_f32_f16 }, + { rms_norm_apply_tile_row_mul_f32_f16_f32, rms_norm_apply_tile_row_mul_f32_f16_f16 }, + }, + { + { rms_norm_apply_tile_row_mul_f16_f32_f32, rms_norm_apply_tile_row_mul_f16_f32_f16 }, + { rms_norm_apply_tile_row_mul_f16_f16_f32, rms_norm_apply_tile_row_mul_f16_f16_f16 }, + }, +}; + +static const rms_apply_row_fn_t rms_norm_mul_add_apply_row_table[2][2][2][2] = { + { + { + { rms_norm_apply_tile_row_mul_add_f32_f32_f32_f32, rms_norm_apply_tile_row_mul_add_f32_f32_f32_f16 }, + { rms_norm_apply_tile_row_mul_add_f32_f32_f16_f32, rms_norm_apply_tile_row_mul_add_f32_f32_f16_f16 }, + }, + { + { rms_norm_apply_tile_row_mul_add_f32_f16_f32_f32, rms_norm_apply_tile_row_mul_add_f32_f16_f32_f16 }, + { rms_norm_apply_tile_row_mul_add_f32_f16_f16_f32, rms_norm_apply_tile_row_mul_add_f32_f16_f16_f16 }, + }, + }, + { + { + { rms_norm_apply_tile_row_mul_add_f16_f32_f32_f32, rms_norm_apply_tile_row_mul_add_f16_f32_f32_f16 }, + { rms_norm_apply_tile_row_mul_add_f16_f32_f16_f32, rms_norm_apply_tile_row_mul_add_f16_f32_f16_f16 }, + }, + { + { rms_norm_apply_tile_row_mul_add_f16_f16_f32_f32, rms_norm_apply_tile_row_mul_add_f16_f16_f32_f16 }, + { rms_norm_apply_tile_row_mul_add_f16_f16_f16_f32, rms_norm_apply_tile_row_mul_add_f16_f16_f16_f16 }, + }, + }, +}; + +static const unary_compute_fn_t rms_norm_rows_table[2][2] = { + { rms_norm_rows_f32_f32, rms_norm_rows_f32_f16 }, + { rms_norm_rows_f16_f32, rms_norm_rows_f16_f16 }, +}; + +static void rms_norm_mul_rows_f16_f32_f16_ne128_bc(const void * restrict src, + const void * restrict mul, + void * restrict dst, + const uint32_t num_rows, + const uint32_t src1_row_start, + const struct htp_unary_context * uctx) { + (void) src1_row_start; + const int32_t * op_params = uctx->octx->op_params; float epsilon = 0.f; float scale = 0.f; memcpy(&epsilon, &op_params[0], sizeof(float)); memcpy(&scale, &op_params[1], sizeof(float)); + hvx_rms_norm_mul_f16_w32_ne128_bcast_rows((const uint8_t *) src, (const uint8_t *) mul, (uint8_t *) dst, + num_rows, uctx->src0_row_size_aligned, uctx->dst_row_size_aligned, + epsilon, scale); +} + +static void rms_norm_mul_rows_f16_f32_f16_ne256_bc(const void * restrict src, + const void * restrict mul, + void * restrict dst, + const uint32_t num_rows, + const uint32_t src1_row_start, + const struct htp_unary_context * uctx) { + (void) src1_row_start; + const int32_t * op_params = uctx->octx->op_params; + float epsilon = 0.f; + float scale = 0.f; + memcpy(&epsilon, &op_params[0], sizeof(float)); + memcpy(&scale, &op_params[1], sizeof(float)); + hvx_rms_norm_mul_f16_w32_ne256_bcast_rows((const uint8_t *) src, (const uint8_t *) mul, (uint8_t *) dst, + num_rows, uctx->src0_row_size_aligned, uctx->dst_row_size_aligned, + epsilon, scale); +} + +static const unary_rms_norm_mul_compute_fn_t rms_norm_mul_rows_table[2][2][2] = { + { + { rms_norm_mul_rows_f32_f32_f32, rms_norm_mul_rows_f32_f32_f16 }, + { rms_norm_mul_rows_f32_f16_f32, rms_norm_mul_rows_f32_f16_f16 }, + }, + { + { rms_norm_mul_rows_f16_f32_f32, rms_norm_mul_rows_f16_f32_f16 }, + { rms_norm_mul_rows_f16_f16_f32, rms_norm_mul_rows_f16_f16_f16 }, + }, +}; - const uint8_t * restrict w_local = (const uint8_t *) weight; - - for (uint32_t ir = 0; ir < num_rows; ir++) { - const uint8_t * restrict src_local = (const uint8_t *) src + (ir * src0_row_size_aligned); - const uint8_t * restrict add_local = (const uint8_t *) add + (ir * src0_row_size_aligned); - uint8_t * restrict dst_local = (uint8_t *) dst + (ir * dst_row_size_aligned); +static const unary_rms_norm_mul_add_compute_fn_t rms_norm_mul_add_rows_table[2][2][2][2] = { + { + { + { rms_norm_mul_add_rows_f32_f32_f32_f32, rms_norm_mul_add_rows_f32_f32_f32_f16 }, + { rms_norm_mul_add_rows_f32_f32_f16_f32, rms_norm_mul_add_rows_f32_f32_f16_f16 }, + }, + { + { rms_norm_mul_add_rows_f32_f16_f32_f32, rms_norm_mul_add_rows_f32_f16_f32_f16 }, + { rms_norm_mul_add_rows_f32_f16_f16_f32, rms_norm_mul_add_rows_f32_f16_f16_f16 }, + }, + }, + { + { + { rms_norm_mul_add_rows_f16_f32_f32_f32, rms_norm_mul_add_rows_f16_f32_f32_f16 }, + { rms_norm_mul_add_rows_f16_f32_f16_f32, rms_norm_mul_add_rows_f16_f32_f16_f16 }, + }, + { + { rms_norm_mul_add_rows_f16_f16_f32_f32, rms_norm_mul_add_rows_f16_f16_f32_f16 }, + { rms_norm_mul_add_rows_f16_f16_f16_f32, rms_norm_mul_add_rows_f16_f16_f16_f16 }, + }, + }, +}; - hvx_fast_rms_norm_mul_add_f32(src_local, w_local, add_local, dst_local, ne0, epsilon, scale); - } +static __attribute__((noinline)) void rms_norm_apply_tile(const uint8_t * restrict src, + const uint8_t * restrict mul, + const uint8_t * restrict add, + uint8_t * restrict dst, + uint32_t n, + uint32_t ne0, + float sum_sq, + float epsilon, + float scale, + const struct htp_unary_context * uctx) { + const HVX_Vector scale_v = rms_norm_scale_from_sum_f32(hvx_vec_splat_f32(sum_sq), ne0, epsilon, scale); + uctx->rms_apply_row_fn(src, mul, add, dst, n, scale_v); } static void norm_f32(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; float epsilon = 0.f; @@ -296,6 +1632,7 @@ static void norm_f32(const void * restrict src, static void sqr_f32(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; @@ -310,6 +1647,7 @@ static void sqr_f32(const void * restrict src, static void sqrt_f32(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; @@ -324,6 +1662,7 @@ static void sqrt_f32(const void * restrict src, static void scale_f16(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; float scale = 0.f; @@ -342,6 +1681,7 @@ static void scale_f16(const void * restrict src, static void clamp_f16(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; float min = 0.f; @@ -353,29 +1693,55 @@ static void clamp_f16(const void * restrict src, const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); - hvx_clamp_scalar_f16(dst_local, src_local, (_Float16) min, (_Float16) max, ne0); + hvx_clamp_scalar_f16_aa(dst_local, src_local, (_Float16) min, (_Float16) max, ne0); } } -static void rms_norm_f16(const void * restrict src, - void * restrict dst, - const uint32_t num_rows, - const struct htp_unary_context * uctx) { +static inline void hvx_leaky_relu_scalar_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src, float slope, uint32_t n) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + HVX_Vector * restrict vdst = (HVX_Vector *) dst; + + const HVX_Vector vslope = hvx_vec_splat_f32(slope); + const HVX_Vector vzero = Q6_V_vzero(); + + const uint32_t nvec = n / VLEN_FP16; + const uint32_t nloe = n % VLEN_FP16; + + for (uint32_t i = 0; i < nvec; i++) { + HVX_VectorPair f32p = hvx_vec_f16_to_f32(vsrc[i]); + HVX_Vector lo = hvx_vec_clamp_f16_f32(hvx_vec_leaky_relu_f32(Q6_V_lo_W(f32p), vslope, vzero)); + HVX_Vector hi = hvx_vec_clamp_f16_f32(hvx_vec_leaky_relu_f32(Q6_V_hi_W(f32p), vslope, vzero)); + vdst[i] = hvx_vec_f32_to_f16(lo, hi); + } + if (nloe) { + HVX_VectorPair f32p = hvx_vec_f16_to_f32(vsrc[nvec]); + HVX_Vector lo = hvx_vec_clamp_f16_f32(hvx_vec_leaky_relu_f32(Q6_V_lo_W(f32p), vslope, vzero)); + HVX_Vector hi = hvx_vec_clamp_f16_f32(hvx_vec_leaky_relu_f32(Q6_V_hi_W(f32p), vslope, vzero)); + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), hvx_vec_f32_to_f16(lo, hi)); + } +} + +static void leaky_relu_f16(const void * restrict src, + void * restrict dst, + const uint32_t num_rows, + const uint32_t ne0, + const struct htp_unary_context * uctx) { htp_unary_op_preamble; - float epsilon = 0.f; - memcpy(&epsilon, op_params, sizeof(float)); + float negative_slope = 0.f; + memcpy(&negative_slope, &op_params[0], sizeof(float)); for (uint32_t ir = 0; ir < num_rows; ir++) { const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); - hvx_fast_rms_norm_f16((const uint8_t *) src_local, (uint8_t *) dst_local, ne0, epsilon); + hvx_leaky_relu_scalar_f16_aa(dst_local, src_local, negative_slope, ne0); } } static void norm_f16(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; float epsilon = 0.f; @@ -392,6 +1758,7 @@ static void norm_f16(const void * restrict src, static void sqr_f16(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; @@ -406,6 +1773,7 @@ static void sqr_f16(const void * restrict src, static void sqrt_f16(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; @@ -420,6 +1788,7 @@ static void sqrt_f16(const void * restrict src, static void abs_f16(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; @@ -434,6 +1803,7 @@ static void abs_f16(const void * restrict src, static void log_f16(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; @@ -448,6 +1818,7 @@ static void log_f16(const void * restrict src, static void step_f16(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; @@ -462,6 +1833,7 @@ static void step_f16(const void * restrict src, static void ceil_f16(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; @@ -476,6 +1848,7 @@ static void ceil_f16(const void * restrict src, static void sgn_f16(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; @@ -490,6 +1863,7 @@ static void sgn_f16(const void * restrict src, static void l2_norm_f16(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; float epsilon = 0.f; @@ -506,6 +1880,7 @@ static void l2_norm_f16(const void * restrict src, static void neg_f32(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; @@ -517,9 +1892,31 @@ static void neg_f32(const void * restrict src, } } -static void exp_f32(const void * restrict src, +static inline void unary_neg_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + HVX_Vector * restrict vdst = (HVX_Vector *) dst; + + const uint32_t nvec = n / VLEN_FP16; + const uint32_t nloe = n % VLEN_FP16; + + for (uint32_t i = 0; i < nvec; i++) { + HVX_VectorPair f32p = hvx_vec_f16_to_f32(vsrc[i]); + HVX_Vector lo = hvx_vec_neg_f32(Q6_V_lo_W(f32p)); + HVX_Vector hi = hvx_vec_neg_f32(Q6_V_hi_W(f32p)); + vdst[i] = hvx_vec_f32_to_f16(lo, hi); + } + if (nloe) { + HVX_VectorPair f32p = hvx_vec_f16_to_f32(vsrc[nvec]); + HVX_Vector lo = hvx_vec_neg_f32(Q6_V_lo_W(f32p)); + HVX_Vector hi = hvx_vec_neg_f32(Q6_V_hi_W(f32p)); + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), hvx_vec_f32_to_f16(lo, hi)); + } +} + +static void neg_f16(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; @@ -527,123 +1924,375 @@ static void exp_f32(const void * restrict src, const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); - hvx_exp_f32(dst_local, src_local, ne0, false); + unary_neg_f16_aa(dst_local, src_local, ne0); } } -static void sigmoid_f32(const void * restrict src, - void * restrict dst, - const uint32_t num_rows, - const struct htp_unary_context * uctx) { - htp_unary_op_preamble; +static __attribute__((noinline)) HVX_Vector unary_vec_exp_f32(HVX_Vector x) { + return hvx_vec_exp_f32_guard(x, hvx_vec_splat_f32(88.7228f), hvx_vec_splat_f32(INFINITY)); +} - for (uint32_t ir = 0; ir < num_rows; ir++) { - const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); - uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); +static inline void unary_exp_f32_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + HVX_Vector * restrict vdst = (HVX_Vector *) dst; + + const uint32_t nvec = n / VLEN_FP32; + const uint32_t nloe = n % VLEN_FP32; - hvx_sigmoid_f32_aa(dst_local, src_local, ne0); + for (uint32_t i = 0; i < nvec; i++) { + vdst[i] = unary_vec_exp_f32(vsrc[i]); + } + if (nloe) { + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(float), unary_vec_exp_f32(vsrc[nvec])); } } -// silu(x) = x * sigmoid(x) -static void silu_f32(const void * restrict src, - void * restrict dst, - const uint32_t num_rows, - const struct htp_unary_context * uctx) { +static void exp_f32(const void * restrict src, + void * restrict dst, + const uint32_t num_rows, + const uint32_t ne0, + const struct htp_unary_context * uctx) { htp_unary_op_preamble; for (uint32_t ir = 0; ir < num_rows; ir++) { const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); - hvx_sigmoid_f32_aa(dst_local, src_local, ne0); - hvx_mul_f32_aaa(dst_local, src_local, dst_local, ne0); + unary_exp_f32_aa(dst_local, src_local, ne0); } } -// GELU uses the tanh approximation. -static __attribute__((noinline)) HVX_Vector hvx_vec_gelu_f32(HVX_Vector x) { - const HVX_Vector half = hvx_vec_splat_f32(0.5f); - const HVX_Vector one = hvx_vec_splat_f32(1.0f); - - HVX_Vector inner = hvx_vec_mul_f32_f32(x, x); - inner = hvx_vec_mul_f32_f32(inner, hvx_vec_splat_f32(0.044715f)); - inner = hvx_vec_add_f32_f32(inner, one); - inner = hvx_vec_mul_f32_f32(inner, x); - inner = hvx_vec_mul_f32_f32(inner, hvx_vec_splat_f32(0.7978845608028654f)); - - return hvx_vec_mul_f32_f32(hvx_vec_mul_f32_f32(half, x), - hvx_vec_add_f32_f32(one, hvx_vec_tanh_f32(inner))); +static __attribute__((noinline)) HVX_Vector unary_vec_exp_f16(HVX_Vector v) { + const HVX_Vector max_exp = hvx_vec_splat_f32(87.0f); + HVX_VectorPair f32p = hvx_vec_f16_to_f32(v); + HVX_Vector lo = hvx_vec_clamp_f16_f32(hvx_vec_exp_f32(Q6_Vsf_vmin_VsfVsf(Q6_V_lo_W(f32p), max_exp))); + HVX_Vector hi = hvx_vec_clamp_f16_f32(hvx_vec_exp_f32(Q6_Vsf_vmin_VsfVsf(Q6_V_hi_W(f32p), max_exp))); + return hvx_vec_f32_to_f16(lo, hi); } -static inline void hvx_gelu_f32_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) { - assert((unsigned long) dst % 128 == 0); - assert((unsigned long) src % 128 == 0); - - HVX_Vector * restrict vdst = (HVX_Vector *) dst; - HVX_Vector * restrict vsrc = (HVX_Vector *) src; +static inline void hvx_exp_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + HVX_Vector * restrict vdst = (HVX_Vector *) dst; - const uint32_t nvec = n / VLEN_FP32; - const uint32_t nloe = n % VLEN_FP32; + const uint32_t nvec = n / VLEN_FP16; + const uint32_t nloe = n % VLEN_FP16; - uint32_t i = 0; - _Pragma("unroll(4)") - for (; i < nvec; i++) { - vdst[i] = hvx_vec_gelu_f32(vsrc[i]); + for (uint32_t i = 0; i < nvec; i++) { + vdst[i] = unary_vec_exp_f16(vsrc[i]); } if (nloe) { - hvx_vec_store_a(&vdst[i], nloe * sizeof(float), hvx_vec_gelu_f32(vsrc[i])); + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), unary_vec_exp_f16(vsrc[nvec])); } } -// GELU_QUICK uses x * sigmoid(1.702 * x). -static __attribute__((noinline)) HVX_Vector hvx_vec_gelu_quick_f32(HVX_Vector x) { - const HVX_Vector one = hvx_vec_splat_f32(1.0f); - const HVX_Vector max_exp = hvx_vec_splat_f32(87.0f); - const HVX_Vector min_exp = hvx_vec_splat_f32(-87.0f); - const HVX_Vector scaled = hvx_vec_mul_f32_f32(x, hvx_vec_splat_f32(1.702f)); - const HVX_Vector sigmoid = hvx_vec_fast_sigmoid_f32_guard(scaled, one, max_exp, min_exp); +static void exp_f16(const void * restrict src, + void * restrict dst, + const uint32_t num_rows, + const uint32_t ne0, + const struct htp_unary_context * uctx) { + htp_unary_op_preamble; - return hvx_vec_mul_f32_f32(x, sigmoid); + for (uint32_t ir = 0; ir < num_rows; ir++) { + const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); + uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); + + hvx_exp_f16_aa(dst_local, src_local, ne0); + } } -static inline void hvx_gelu_quick_f32_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) { - assert((unsigned long) dst % 128 == 0); - assert((unsigned long) src % 128 == 0); +static __attribute__((noinline)) HVX_Vector unary_vec_sigmoid_f32(HVX_Vector x) { + return hvx_vec_sigmoid_f32(x); +} - HVX_Vector * restrict vdst = (HVX_Vector *) dst; - HVX_Vector * restrict vsrc = (HVX_Vector *) src; +static inline void unary_sigmoid_f32_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + HVX_Vector * restrict vdst = (HVX_Vector *) dst; const uint32_t nvec = n / VLEN_FP32; const uint32_t nloe = n % VLEN_FP32; - uint32_t i = 0; - _Pragma("unroll(4)") - for (; i < nvec; i++) { - vdst[i] = hvx_vec_gelu_quick_f32(vsrc[i]); + for (uint32_t i = 0; i < nvec; i++) { + vdst[i] = unary_vec_sigmoid_f32(vsrc[i]); } if (nloe) { - hvx_vec_store_a(&vdst[i], nloe * sizeof(float), hvx_vec_gelu_quick_f32(vsrc[i])); + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(float), unary_vec_sigmoid_f32(vsrc[nvec])); } } -static void gelu_f32(const void * restrict src, - void * restrict dst, - const uint32_t num_rows, - const struct htp_unary_context * uctx) { +static void sigmoid_f32(const void * restrict src, + void * restrict dst, + const uint32_t num_rows, + const uint32_t ne0, + const struct htp_unary_context * uctx) { htp_unary_op_preamble; for (uint32_t ir = 0; ir < num_rows; ir++) { const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); - hvx_gelu_f32_aa(dst_local, src_local, ne0); + unary_sigmoid_f32_aa(dst_local, src_local, ne0); } } -static void gelu_quick_f32(const void * restrict src, +static void sigmoid_f16(const void * restrict src, + void * restrict dst, + const uint32_t num_rows, + const uint32_t ne0, + const struct htp_unary_context * uctx) { + htp_unary_op_preamble; + + for (uint32_t ir = 0; ir < num_rows; ir++) { + const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); + uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); + + hvx_sigmoid_f16_aa(dst_local, src_local, ne0); + } +} + +static __attribute__((noinline)) HVX_Vector unary_vec_silu_f32(HVX_Vector x) { + return hvx_vec_silu_f32(x); +} + +static inline void unary_silu_f32_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + HVX_Vector * restrict vdst = (HVX_Vector *) dst; + + const uint32_t nvec = n / VLEN_FP32; + const uint32_t nloe = n % VLEN_FP32; + + for (uint32_t i = 0; i < nvec; i++) { + vdst[i] = unary_vec_silu_f32(vsrc[i]); + } + if (nloe) { + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(float), unary_vec_silu_f32(vsrc[nvec])); + } +} + +// silu(x) = x * sigmoid(x) +static void silu_f32(const void * restrict src, + void * restrict dst, + const uint32_t num_rows, + const uint32_t ne0, + const struct htp_unary_context * uctx) { + htp_unary_op_preamble; + + for (uint32_t ir = 0; ir < num_rows; ir++) { + const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); + uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); + + unary_silu_f32_aa(dst_local, src_local, ne0); + } +} + +static inline HVX_Vector hvx_vec_silu_f16(HVX_Vector x) { + return hvx_vec_mul_f16_f16(x, hvx_vec_fast_sigmoid_f16(x)); +} + +static inline void hvx_silu_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + HVX_Vector * restrict vdst = (HVX_Vector *) dst; + + const uint32_t nvec = n / VLEN_FP16; + const uint32_t nloe = n % VLEN_FP16; + + _Pragma("clang loop unroll(disable)") + for (uint32_t i = 0; i < nvec; i++) { + vdst[i] = hvx_vec_silu_f16(vsrc[i]); + } + if (nloe) { + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), hvx_vec_silu_f16(vsrc[nvec])); + } +} + +static void silu_f16(const void * restrict src, + void * restrict dst, + const uint32_t num_rows, + const uint32_t ne0, + const struct htp_unary_context * uctx) { + htp_unary_op_preamble; + + for (uint32_t ir = 0; ir < num_rows; ir++) { + const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); + uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); + + hvx_silu_f16_aa(dst_local, src_local, ne0); + } +} + +// GELU uses the tanh approximation. +static inline HVX_Vector hvx_vec_gelu_f32_inline(HVX_Vector x) { + const HVX_Vector half = hvx_vec_splat_f32(0.5f); + const HVX_Vector one = hvx_vec_splat_f32(1.0f); + + HVX_Vector inner = hvx_vec_mul_f32_f32(x, x); + inner = hvx_vec_mul_f32_f32(inner, hvx_vec_splat_f32(0.044715f)); + inner = hvx_vec_add_f32_f32(inner, one); + inner = hvx_vec_mul_f32_f32(inner, x); + inner = hvx_vec_mul_f32_f32(inner, hvx_vec_splat_f32(0.7978845608028654f)); + + return hvx_vec_mul_f32_f32(hvx_vec_mul_f32_f32(half, x), + hvx_vec_add_f32_f32(one, hvx_vec_tanh_f32(inner))); +} + +static __attribute__((noinline)) HVX_Vector hvx_vec_gelu_f32(HVX_Vector x) { + return hvx_vec_gelu_f32_inline(x); +} + +static inline void hvx_gelu_f32_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) { + assert((unsigned long) dst % 128 == 0); + assert((unsigned long) src % 128 == 0); + + HVX_Vector * restrict vdst = (HVX_Vector *) dst; + HVX_Vector * restrict vsrc = (HVX_Vector *) src; + + const uint32_t nvec = n / VLEN_FP32; + const uint32_t nloe = n % VLEN_FP32; + + uint32_t i = 0; + for (; i < nvec; i++) { + vdst[i] = hvx_vec_gelu_f32(vsrc[i]); + } + if (nloe) { + hvx_vec_store_a(&vdst[i], nloe * sizeof(float), hvx_vec_gelu_f32(vsrc[i])); + } +} + +static inline HVX_Vector hvx_vec_gelu_f16(HVX_Vector x) { + const HVX_Vector v_coef_a = hvx_vec_splat_f16(0.044715f); + const HVX_Vector v_two_sqrt_2_pi = hvx_vec_splat_f16(1.5957691216057308f); + const HVX_Vector v_one = hvx_vec_splat_f16(1.0f); + + HVX_Vector x2 = hvx_vec_mul_f16_f16(x, x); + HVX_Vector coef = hvx_vec_add_f16_f16(hvx_vec_mul_f16_f16(x2, v_coef_a), v_one); + HVX_Vector y2 = hvx_vec_mul_f16_f16(hvx_vec_mul_f16_f16(x, coef), v_two_sqrt_2_pi); + return hvx_vec_mul_f16_f16(x, hvx_vec_fast_sigmoid_f16(y2)); +} + +static inline void hvx_gelu_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + HVX_Vector * restrict vdst = (HVX_Vector *) dst; + + const uint32_t nvec = n / VLEN_FP16; + const uint32_t nloe = n % VLEN_FP16; + + _Pragma("unroll(2)") + for (uint32_t i = 0; i < nvec; i++) { + vdst[i] = hvx_vec_gelu_f16(vsrc[i]); + } + if (nloe) { + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), hvx_vec_gelu_f16(vsrc[nvec])); + } +} + +// GELU_QUICK uses x * sigmoid(1.702 * x). +static inline HVX_Vector hvx_vec_gelu_quick_f32_inline(HVX_Vector x) { + const HVX_Vector scaled = hvx_vec_mul_f32_f32(x, hvx_vec_splat_f32(1.702f)); + const HVX_Vector sigmoid = hvx_vec_sigmoid_f32(scaled); + + return hvx_vec_mul_f32_f32(x, sigmoid); +} + +static __attribute__((noinline)) HVX_Vector hvx_vec_gelu_quick_f32(HVX_Vector x) { + return hvx_vec_gelu_quick_f32_inline(x); +} + +static inline void hvx_gelu_quick_f32_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) { + assert((unsigned long) dst % 128 == 0); + assert((unsigned long) src % 128 == 0); + + HVX_Vector * restrict vdst = (HVX_Vector *) dst; + HVX_Vector * restrict vsrc = (HVX_Vector *) src; + + const uint32_t nvec = n / VLEN_FP32; + const uint32_t nloe = n % VLEN_FP32; + + uint32_t i = 0; + for (; i < nvec; i++) { + vdst[i] = hvx_vec_gelu_quick_f32(vsrc[i]); + } + if (nloe) { + hvx_vec_store_a(&vdst[i], nloe * sizeof(float), hvx_vec_gelu_quick_f32(vsrc[i])); + } +} + +static inline HVX_Vector hvx_vec_gelu_quick_f16(HVX_Vector x) { + const HVX_Vector v_scale = hvx_vec_splat_f16(1.702f); + HVX_Vector scaled = hvx_vec_mul_f16_f16(x, v_scale); + return hvx_vec_mul_f16_f16(x, hvx_vec_fast_sigmoid_f16(scaled)); +} + +static inline void hvx_gelu_quick_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + HVX_Vector * restrict vdst = (HVX_Vector *) dst; + + const uint32_t nvec = n / VLEN_FP16; + const uint32_t nloe = n % VLEN_FP16; + + _Pragma("clang loop pipeline(disable) unroll(disable)") + for (uint32_t i = 0; i < nvec; i++) { + vdst[i] = hvx_vec_gelu_quick_f16(vsrc[i]); + } + if (nloe) { + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), hvx_vec_gelu_quick_f16(vsrc[nvec])); + } +} + +static __attribute__((noinline)) HVX_Vector unary_vec_gelu_erf_f16(HVX_Vector v) { + HVX_VectorPair f32p = hvx_vec_f16_to_f32(v); + HVX_Vector lo = hvx_vec_clamp_f16_f32(hvx_vec_gelu_erf_f32(Q6_V_lo_W(f32p))); + HVX_Vector hi = hvx_vec_clamp_f16_f32(hvx_vec_gelu_erf_f32(Q6_V_hi_W(f32p))); + return hvx_vec_f32_to_f16(lo, hi); +} + +static inline void hvx_gelu_erf_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + HVX_Vector * restrict vdst = (HVX_Vector *) dst; + + const uint32_t nvec = n / VLEN_FP16; + const uint32_t nloe = n % VLEN_FP16; + + for (uint32_t i = 0; i < nvec; i++) { + vdst[i] = unary_vec_gelu_erf_f16(vsrc[i]); + } + if (nloe) { + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), unary_vec_gelu_erf_f16(vsrc[nvec])); + } +} + +static void gelu_f32(const void * restrict src, + void * restrict dst, + const uint32_t num_rows, + const uint32_t ne0, + const struct htp_unary_context * uctx) { + htp_unary_op_preamble; + + for (uint32_t ir = 0; ir < num_rows; ir++) { + const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); + uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); + + hvx_gelu_f32_aa(dst_local, src_local, ne0); + } +} + +static void gelu_f16(const void * restrict src, + void * restrict dst, + const uint32_t num_rows, + const uint32_t ne0, + const struct htp_unary_context * uctx) { + htp_unary_op_preamble; + + for (uint32_t ir = 0; ir < num_rows; ir++) { + const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); + uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); + + hvx_gelu_f16_aa(dst_local, src_local, ne0); + } +} + +static void gelu_quick_f32(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; @@ -655,9 +2304,25 @@ static void gelu_quick_f32(const void * restrict src, } } +static void gelu_quick_f16(const void * restrict src, + void * restrict dst, + const uint32_t num_rows, + const uint32_t ne0, + const struct htp_unary_context * uctx) { + htp_unary_op_preamble; + + for (uint32_t ir = 0; ir < num_rows; ir++) { + const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); + uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); + + hvx_gelu_quick_f16_aa(dst_local, src_local, ne0); + } +} + static void gelu_erf_f32(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; @@ -669,12 +2334,28 @@ static void gelu_erf_f32(const void * restrict src, } } +static void gelu_erf_f16(const void * restrict src, + void * restrict dst, + const uint32_t num_rows, + const uint32_t ne0, + const struct htp_unary_context * uctx) { + htp_unary_op_preamble; + + for (uint32_t ir = 0; ir < num_rows; ir++) { + const uint8_t * restrict src_local = (const uint8_t *) src + (ir * src0_row_size_aligned); + uint8_t * restrict dst_local = (uint8_t *) dst + (ir * dst_row_size_aligned); + + hvx_gelu_erf_f16_aa(dst_local, src_local, ne0); + } +} + static void tri_f32(const void * restrict src, void * restrict dst, const uint32_t num_rows, const uint32_t ir, const struct htp_unary_context * uctx) { htp_unary_op_preamble; + const uint32_t ne0 = uctx->nc; const int32_t ttype = op_params[0]; const HVX_Vector zero = hvx_vec_splat_f32(0.0f); const uint32_t nvec = ne0 / VLEN_FP32; @@ -757,38 +2438,62 @@ static void tri_f32(const void * restrict src, // softplus(x) = log(1 + exp(x)) // Match CPU reference: return x for x > 20 to avoid overflow. +static inline HVX_Vector hvx_vec_softplus_f32_inline(HVX_Vector x) { + const HVX_Vector twenty = hvx_vec_splat_f32(20.0f); + const HVX_Vector one = hvx_vec_splat_f32(1.0f); + + HVX_VectorPred pred_gt20 = Q6_Q_vcmp_gt_VsfVsf(x, twenty); + HVX_Vector expx = hvx_vec_exp_f32(x); + HVX_Vector logv = hvx_vec_log_f32(hvx_vec_add_f32_f32(one, expx)); + return Q6_V_vmux_QVV(pred_gt20, x, logv); +} + +static __attribute__((noinline)) HVX_Vector hvx_vec_softplus_f32(HVX_Vector x) { + return hvx_vec_softplus_f32_inline(x); +} + static inline void hvx_softplus_f32_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) { const HVX_Vector * restrict v_src = (const HVX_Vector *) src; HVX_Vector * restrict v_dst = (HVX_Vector *) dst; - const HVX_Vector twenty = hvx_vec_splat_f32(20.0f); - const HVX_Vector one = hvx_vec_splat_f32(1.0f); - const uint32_t nvec = n / VLEN_FP32; const uint32_t nloe = n % VLEN_FP32; - #pragma unroll(4) for (uint32_t i = 0; i < nvec; i++) { - HVX_Vector x = v_src[i]; - HVX_VectorPred pred_gt20 = Q6_Q_vcmp_gt_VsfVsf(x, twenty); - HVX_Vector expx = hvx_vec_exp_f32(x); - HVX_Vector logv = hvx_vec_log_f32(hvx_vec_add_f32_f32(one, expx)); - v_dst[i] = Q6_V_vmux_QVV(pred_gt20, x, logv); + v_dst[i] = hvx_vec_softplus_f32(v_src[i]); } if (nloe > 0) { - HVX_Vector x = v_src[nvec]; - HVX_VectorPred pred_gt20 = Q6_Q_vcmp_gt_VsfVsf(x, twenty); - HVX_Vector expx = hvx_vec_exp_f32(x); - HVX_Vector logv = hvx_vec_log_f32(hvx_vec_add_f32_f32(one, expx)); - HVX_Vector sp = Q6_V_vmux_QVV(pred_gt20, x, logv); - hvx_vec_store_a((void *) &v_dst[nvec], nloe * sizeof(float), sp); + hvx_vec_store_a((void *) &v_dst[nvec], nloe * sizeof(float), hvx_vec_softplus_f32(v_src[nvec])); + } +} + +static __attribute__((noinline)) HVX_Vector unary_vec_softplus_f16(HVX_Vector v) { + HVX_VectorPair f32p = hvx_vec_f16_to_f32(v); + HVX_Vector lo = hvx_vec_clamp_f16_f32(hvx_vec_softplus_f32_inline(Q6_V_lo_W(f32p))); + HVX_Vector hi = hvx_vec_clamp_f16_f32(hvx_vec_softplus_f32_inline(Q6_V_hi_W(f32p))); + return hvx_vec_f32_to_f16(lo, hi); +} + +static inline void hvx_softplus_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + HVX_Vector * restrict vdst = (HVX_Vector *) dst; + + const uint32_t nvec = n / VLEN_FP16; + const uint32_t nloe = n % VLEN_FP16; + + for (uint32_t i = 0; i < nvec; i++) { + vdst[i] = unary_vec_softplus_f16(vsrc[i]); + } + if (nloe) { + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), unary_vec_softplus_f16(vsrc[nvec])); } } static void softplus_f32(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; @@ -800,9 +2505,25 @@ static void softplus_f32(const void * restrict src, } } +static void softplus_f16(const void * restrict src, + void * restrict dst, + const uint32_t num_rows, + const uint32_t ne0, + const struct htp_unary_context * uctx) { + htp_unary_op_preamble; + + for (uint32_t ir = 0; ir < num_rows; ir++) { + const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); + uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); + + hvx_softplus_f16_aa(dst_local, src_local, ne0); + } +} + static void l2_norm_f32(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; float epsilon = 0.f; @@ -926,6 +2647,7 @@ static inline void hvx_fwht_row_f16(const uint8_t * restrict src, uint8_t * rest static void hadamard_f32(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; const HVX_Vector v_scale = hvx_vec_splat_f32(1.0f / sqrtf((float) ne0)); @@ -941,6 +2663,7 @@ static void hadamard_f32(const void * restrict src, static void hadamard_f16(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; const HVX_Vector v_scale = hvx_vec_splat_f32(1.0f / sqrtf((float) ne0)); @@ -953,9 +2676,29 @@ static void hadamard_f16(const void * restrict src, } } +static __attribute__((noinline)) HVX_Vector unary_vec_tanh_f32(HVX_Vector x) { + return hvx_vec_tanh_f32(x); +} + +static inline void unary_tanh_f32_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + HVX_Vector * restrict vdst = (HVX_Vector *) dst; + + const uint32_t nvec = n / VLEN_FP32; + const uint32_t nloe = n % VLEN_FP32; + + for (uint32_t i = 0; i < nvec; i++) { + vdst[i] = unary_vec_tanh_f32(vsrc[i]); + } + if (nloe) { + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(float), unary_vec_tanh_f32(vsrc[nvec])); + } +} + static void tanh_f32(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; @@ -963,15 +2706,216 @@ static void tanh_f32(const void * restrict src, const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); - hvx_tanh_f32_aa(dst_local, src_local, ne0); + unary_tanh_f32_aa(dst_local, src_local, ne0); } } -static void abs_f32(const void * restrict src, - void * restrict dst, - const uint32_t num_rows, - const struct htp_unary_context * uctx) { - htp_unary_op_preamble; +static inline void unary_tanh_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + HVX_Vector * restrict vdst = (HVX_Vector *) dst; + + const uint32_t nvec = n / VLEN_FP16; + const uint32_t nloe = n % VLEN_FP16; + + _Pragma("clang loop unroll(disable)") + for (uint32_t i = 0; i < nvec; i++) { + vdst[i] = hvx_vec_tanh_f16(vsrc[i]); + } + if (nloe) { + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), hvx_vec_tanh_f16(vsrc[nvec])); + } +} + +static void tanh_f16(const void * restrict src, + void * restrict dst, + const uint32_t num_rows, + const uint32_t ne0, + const struct htp_unary_context * uctx) { + htp_unary_op_preamble; + + for (uint32_t ir = 0; ir < num_rows; ir++) { + const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); + uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); + + unary_tanh_f16_aa(dst_local, src_local, ne0); + } +} + +static inline HVX_Vector hvx_vec_exp_clamped_f32(HVX_Vector x) { + return hvx_vec_exp_f32(Q6_Vsf_vmin_VsfVsf(x, hvx_vec_splat_f32(88.0f))); +} + +static inline HVX_Vector hvx_vec_clamp_sig_f16_f32(HVX_Vector x) { + const HVX_Vector vmax = hvx_vec_splat_f32(24.0f); + const HVX_Vector vmin = hvx_vec_splat_f32(-24.0f); + return Q6_Vsf_vmin_VsfVsf(Q6_Vsf_vmax_VsfVsf(x, vmin), vmax); +} + +static inline void hvx_vec_sigmoid_pair_f16_f32(HVX_Vector u_lo, + HVX_Vector u_hi, + HVX_Vector * restrict y_lo, + HVX_Vector * restrict y_hi) { + HVX_Vector u_f16 = hvx_vec_f32_to_f16_shuff(hvx_vec_clamp_sig_f16_f32(u_lo), hvx_vec_clamp_sig_f16_f32(u_hi)); + HVX_Vector s_f16 = hvx_vec_fast_sigmoid_f16(u_f16); + HVX_VectorPair sp = hvx_vec_f16_to_f32_shuff(s_f16); + *y_lo = Q6_V_lo_W(sp); + *y_hi = Q6_V_hi_W(sp); +} + +static inline void hvx_vec_silu_pair_f16_f32(HVX_Vector u_lo, + HVX_Vector u_hi, + HVX_Vector * restrict y_lo, + HVX_Vector * restrict y_hi) { + HVX_Vector u_f16 = hvx_vec_f32_to_f16_shuff(hvx_vec_clamp_sig_f16_f32(u_lo), hvx_vec_clamp_sig_f16_f32(u_hi)); + HVX_Vector s_f16 = hvx_vec_fast_sigmoid_f16(u_f16); + HVX_VectorPair sp = hvx_vec_f16_to_f32_shuff(s_f16); + *y_lo = hvx_vec_mul_f32_f32(u_lo, Q6_V_lo_W(sp)); + *y_hi = hvx_vec_mul_f32_f32(u_hi, Q6_V_hi_W(sp)); +} + +static inline void hvx_vec_gelu_quick_pair_f16_f32(HVX_Vector u_lo, + HVX_Vector u_hi, + HVX_Vector * restrict y_lo, + HVX_Vector * restrict y_hi) { + const HVX_Vector c_1702 = hvx_vec_splat_f32(1.702f); + HVX_Vector in_lo = hvx_vec_clamp_sig_f16_f32(hvx_vec_mul_f32_f32(u_lo, c_1702)); + HVX_Vector in_hi = hvx_vec_clamp_sig_f16_f32(hvx_vec_mul_f32_f32(u_hi, c_1702)); + HVX_Vector s_f16 = hvx_vec_fast_sigmoid_f16(hvx_vec_f32_to_f16_shuff(in_lo, in_hi)); + HVX_VectorPair sp = hvx_vec_f16_to_f32_shuff(s_f16); + *y_lo = hvx_vec_mul_f32_f32(u_lo, Q6_V_lo_W(sp)); + *y_hi = hvx_vec_mul_f32_f32(u_hi, Q6_V_hi_W(sp)); +} + +#define DEFINE_UNARY_SCALE_BIAS_FNS_EX(NAME, VEC_ATTR, VEC_FN, PAIR_F16_FN) \ + static VEC_ATTR HVX_Vector unary_vec_##NAME##_scale_bias_f32( \ + HVX_Vector x, \ + HVX_Vector v_in_s, \ + HVX_Vector v_in_b, \ + HVX_Vector v_out_s, \ + HVX_Vector v_out_b \ + ) { \ + HVX_Vector u = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(x, v_in_s), v_in_b); \ + HVX_Vector y = VEC_FN(u); \ + return hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(y, v_out_s), v_out_b); \ + } \ + static inline HVX_Vector unary_vec_##NAME##_scale_bias_f16( \ + HVX_Vector v, \ + HVX_Vector v_in_s, \ + HVX_Vector v_in_b, \ + HVX_Vector v_out_s, \ + HVX_Vector v_out_b \ + ) { \ + HVX_VectorPair f32p = hvx_vec_f16_to_f32_shuff(v); \ + HVX_Vector u_lo = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(Q6_V_lo_W(f32p), v_in_s), v_in_b); \ + HVX_Vector u_hi = hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(Q6_V_hi_W(f32p), v_in_s), v_in_b); \ + HVX_Vector y_lo; \ + HVX_Vector y_hi; \ + PAIR_F16_FN(u_lo, u_hi, &y_lo, &y_hi); \ + HVX_Vector lo = hvx_vec_clamp_f16_f32(hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(y_lo, v_out_s), v_out_b)); \ + HVX_Vector hi = hvx_vec_clamp_f16_f32(hvx_vec_add_f32_f32(hvx_vec_mul_f32_f32(y_hi, v_out_s), v_out_b)); \ + return hvx_vec_f32_to_f16_shuff(lo, hi); \ + } \ + static void NAME##_scale_bias_f32(const void * restrict src, \ + void * restrict dst, \ + const uint32_t num_rows, \ + const uint32_t ne0, \ + const struct htp_unary_context * uctx) { \ + const struct htp_unary_kernel_params * kp = uctx->kparams; \ + const size_t src0_row_size_aligned = uctx->src0_row_size_aligned; \ + const size_t dst_row_size_aligned = uctx->dst_row_size_aligned; \ + const HVX_Vector v_in_s = hvx_vec_splat_f32(kp->in_scale); \ + const HVX_Vector v_in_b = hvx_vec_splat_f32(kp->in_bias); \ + const HVX_Vector v_out_s = hvx_vec_splat_f32(kp->out_scale); \ + const HVX_Vector v_out_b = hvx_vec_splat_f32(kp->out_bias); \ + const uint32_t nvec = ne0 / VLEN_FP32; \ + const uint32_t nloe = ne0 % VLEN_FP32; \ + if (nloe == 0) { \ + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; \ + HVX_Vector * restrict vdst = (HVX_Vector *) dst; \ + const uint32_t total_vec = num_rows * nvec; \ + _Pragma("clang loop pipeline(disable) unroll(disable)") \ + for (uint32_t i = 0; i < total_vec; i++) { \ + vdst[i] = unary_vec_##NAME##_scale_bias_f32(vsrc[i], v_in_s, v_in_b, v_out_s, v_out_b); \ + } \ + return; \ + } \ + for (uint32_t ir = 0; ir < num_rows; ir++) { \ + const HVX_Vector * restrict vsrc = \ + (const HVX_Vector *) ((const uint8_t *) src + ir * src0_row_size_aligned); \ + HVX_Vector * restrict vdst = (HVX_Vector *) ((uint8_t *) dst + ir * dst_row_size_aligned); \ + _Pragma("clang loop pipeline(disable) unroll(disable)") \ + for (uint32_t i = 0; i < nvec; i++) { \ + vdst[i] = unary_vec_##NAME##_scale_bias_f32(vsrc[i], v_in_s, v_in_b, v_out_s, v_out_b); \ + } \ + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(float), \ + unary_vec_##NAME##_scale_bias_f32(vsrc[nvec], v_in_s, v_in_b, v_out_s, v_out_b)); \ + } \ + } \ + static void NAME##_scale_bias_f16(const void * restrict src, \ + void * restrict dst, \ + const uint32_t num_rows, \ + const uint32_t ne0, \ + const struct htp_unary_context * uctx) { \ + const struct htp_unary_kernel_params * kp = uctx->kparams; \ + const size_t src0_row_size_aligned = uctx->src0_row_size_aligned; \ + const size_t dst_row_size_aligned = uctx->dst_row_size_aligned; \ + const HVX_Vector v_in_s = hvx_vec_splat_f32(kp->in_scale); \ + const HVX_Vector v_in_b = hvx_vec_splat_f32(kp->in_bias); \ + const HVX_Vector v_out_s = hvx_vec_splat_f32(kp->out_scale); \ + const HVX_Vector v_out_b = hvx_vec_splat_f32(kp->out_bias); \ + const uint32_t nvec = ne0 / VLEN_FP16; \ + const uint32_t nloe = ne0 % VLEN_FP16; \ + if (nloe == 0) { \ + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; \ + HVX_Vector * restrict vdst = (HVX_Vector *) dst; \ + const uint32_t total_vec = num_rows * nvec; \ + _Pragma("clang loop pipeline(disable) unroll(disable)") \ + for (uint32_t i = 0; i < total_vec; i++) { \ + vdst[i] = unary_vec_##NAME##_scale_bias_f16(vsrc[i], v_in_s, v_in_b, v_out_s, v_out_b); \ + } \ + return; \ + } \ + for (uint32_t ir = 0; ir < num_rows; ir++) { \ + const HVX_Vector * restrict vsrc = \ + (const HVX_Vector *) ((const uint8_t *) src + ir * src0_row_size_aligned); \ + HVX_Vector * restrict vdst = (HVX_Vector *) ((uint8_t *) dst + ir * dst_row_size_aligned); \ + _Pragma("clang loop pipeline(disable) unroll(disable)") \ + for (uint32_t i = 0; i < nvec; i++) { \ + vdst[i] = unary_vec_##NAME##_scale_bias_f16(vsrc[i], v_in_s, v_in_b, v_out_s, v_out_b); \ + } \ + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), \ + unary_vec_##NAME##_scale_bias_f16(vsrc[nvec], v_in_s, v_in_b, v_out_s, v_out_b)); \ + } \ + } + +#define DEFINE_UNARY_SCALE_BIAS_FNS(NAME, F32_ATTR, F16_HELPER_ATTR, VEC_FN) \ + static F16_HELPER_ATTR HVX_Vector hvx_vec_##NAME##_f32_helper(HVX_Vector u) { \ + return VEC_FN(u); \ + } \ + static inline void hvx_vec_##NAME##_pair_f32(HVX_Vector u_lo, \ + HVX_Vector u_hi, \ + HVX_Vector * restrict y_lo, \ + HVX_Vector * restrict y_hi) { \ + *y_lo = hvx_vec_##NAME##_f32_helper(u_lo); \ + *y_hi = hvx_vec_##NAME##_f32_helper(u_hi); \ + } \ + DEFINE_UNARY_SCALE_BIAS_FNS_EX(NAME, F32_ATTR, VEC_FN, hvx_vec_##NAME##_pair_f32) + +DEFINE_UNARY_SCALE_BIAS_FNS(exp, __attribute__((noinline)), __attribute__((noinline)), hvx_vec_exp_clamped_f32) +DEFINE_UNARY_SCALE_BIAS_FNS_EX(sigmoid, inline, hvx_vec_sigmoid_f32, hvx_vec_sigmoid_pair_f16_f32) +DEFINE_UNARY_SCALE_BIAS_FNS_EX(silu, inline, hvx_vec_silu_f32, hvx_vec_silu_pair_f16_f32) +DEFINE_UNARY_SCALE_BIAS_FNS(gelu, inline, __attribute__((noinline)), hvx_vec_gelu_f32_inline) +DEFINE_UNARY_SCALE_BIAS_FNS_EX(gelu_quick, inline, hvx_vec_gelu_quick_f32_inline, hvx_vec_gelu_quick_pair_f16_f32) +DEFINE_UNARY_SCALE_BIAS_FNS(gelu_erf, __attribute__((noinline)), __attribute__((noinline)), hvx_vec_gelu_erf_f32) +DEFINE_UNARY_SCALE_BIAS_FNS(softplus, __attribute__((noinline)), __attribute__((noinline)), hvx_vec_softplus_f32_inline) +DEFINE_UNARY_SCALE_BIAS_FNS(tanh, inline, __attribute__((noinline)), hvx_vec_tanh_f32) + +static void abs_f32(const void * restrict src, + void * restrict dst, + const uint32_t num_rows, + const uint32_t ne0, + const struct htp_unary_context * uctx) { + htp_unary_op_preamble; for (uint32_t ir = 0; ir < num_rows; ir++) { const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); @@ -984,6 +2928,40 @@ static void abs_f32(const void * restrict src, static void relu_f32(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, + const struct htp_unary_context * uctx) { + htp_unary_op_preamble; + + for (uint32_t ir = 0; ir < num_rows; ir++) { + const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); + uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); + + hvx_max_scalar_f32_aa(dst_local, src_local, 0.0f, ne0); + } +} + +static inline void hvx_relu_f16_aa(uint8_t * restrict dst, const uint8_t * restrict src, uint32_t n) { + const HVX_Vector * restrict vsrc = (const HVX_Vector *) src; + HVX_Vector * restrict vdst = (HVX_Vector *) dst; + + const HVX_Vector zero = Q6_V_vzero(); + + const uint32_t nvec = n / VLEN_FP16; + const uint32_t nloe = n % VLEN_FP16; + + _Pragma("unroll(4)") + for (uint32_t i = 0; i < nvec; i++) { + vdst[i] = Q6_Vhf_vmax_VhfVhf(vsrc[i], zero); + } + if (nloe) { + hvx_vec_store_a(&vdst[nvec], nloe * sizeof(_Float16), Q6_Vhf_vmax_VhfVhf(vsrc[nvec], zero)); + } +} + +static void relu_f16(const void * restrict src, + void * restrict dst, + const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; @@ -991,13 +2969,14 @@ static void relu_f32(const void * restrict src, const uint8_t * restrict src_local = (const uint8_t *)src + (ir * src0_row_size_aligned); uint8_t * restrict dst_local = (uint8_t *)dst + (ir * dst_row_size_aligned); - hvx_max_scalar_f32(dst_local, src_local, 0.0f, ne0); + hvx_relu_f16_aa(dst_local, src_local, ne0); } } static void step_f32(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; @@ -1012,6 +2991,7 @@ static void step_f32(const void * restrict src, static void ceil_f32(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; @@ -1026,6 +3006,7 @@ static void ceil_f32(const void * restrict src, static void sgn_f32(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; @@ -1040,6 +3021,7 @@ static void sgn_f32(const void * restrict src, static void log_f32(const void * restrict src, void * restrict dst, const uint32_t num_rows, + const uint32_t ne0, const struct htp_unary_context * uctx) { htp_unary_op_preamble; @@ -1051,115 +3033,6 @@ static void log_f32(const void * restrict src, } } -#// Pointwise unary ops on one column tile in VTCM. -static void tile_scale_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) { - float scale = 0.f; - float bias = 0.f; - memcpy(&scale, &uctx->octx->op_params[0], sizeof(float)); - memcpy(&bias, &uctx->octx->op_params[1], sizeof(float)); - hvx_scale_offset_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw, scale, bias); -} - -static void tile_clamp_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) { - float min = 0.f; - float max = 0.f; - memcpy(&min, &uctx->octx->op_params[0], sizeof(float)); - memcpy(&max, &uctx->octx->op_params[1], sizeof(float)); - hvx_clamp_scalar_f32((uint8_t *) dst, (const uint8_t *) src, min, max, tw); -} - -static void tile_leaky_relu_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) { - float negative_slope = 0.f; - memcpy(&negative_slope, &uctx->octx->op_params[0], sizeof(float)); - hvx_leaky_relu_scalar_f32((uint8_t *) dst, (const uint8_t *) src, negative_slope, tw); -} - -static void tile_sqr_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) { - (void) uctx; - hvx_sqr_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw); -} - -static void tile_sqrt_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) { - (void) uctx; - hvx_sqrt_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw); -} - -static void tile_neg_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) { - (void) uctx; - hvx_scale_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw, -1.0f); -} - -static void tile_exp_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) { - (void) uctx; - hvx_exp_f32((uint8_t *) dst, (const uint8_t *) src, tw, false); -} - -static void tile_sigmoid_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) { - (void) uctx; - hvx_sigmoid_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw); -} - -static void tile_silu_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) { - (void) uctx; - hvx_sigmoid_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw); - hvx_mul_f32_aaa((uint8_t *) dst, (const uint8_t *) src, (uint8_t *) dst, tw); -} - -static void tile_gelu_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) { - (void) uctx; - hvx_gelu_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw); -} - -static void tile_gelu_quick_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) { - (void) uctx; - hvx_gelu_quick_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw); -} - -static void tile_gelu_erf_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) { - (void) uctx; - hvx_gelu_erf_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw); -} - -static void tile_softplus_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) { - (void) uctx; - hvx_softplus_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw); -} - -static void tile_tanh_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) { - (void) uctx; - hvx_tanh_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw); -} - -static void tile_abs_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) { - (void) uctx; - hvx_abs_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw); -} - -static void tile_log_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) { - (void) uctx; - hvx_log_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw); -} - -static void tile_relu_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) { - (void) uctx; - hvx_max_scalar_f32((uint8_t *) dst, (const uint8_t *) src, 0.0f, tw); -} - -static void tile_step_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) { - (void) uctx; - hvx_step_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw); -} - -static void tile_ceil_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) { - (void) uctx; - hvx_ceil_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw); -} - -static void tile_sgn_f32(void * restrict dst, const void * restrict src, uint32_t tw, const struct htp_unary_context * uctx) { - (void) uctx; - hvx_sgn_f32_aa((uint8_t *) dst, (const uint8_t *) src, tw); -} - static void tri_apply_tile_f32(const void * restrict src, void * restrict dst, uint32_t tile_elems, uint32_t col_start, uint32_t i01, uint32_t ne0, int32_t ttype) { @@ -1232,239 +3105,308 @@ static void tri_apply_tile_f32(const void * restrict src, void * restrict dst, } } -// 1. Standard row-block unary task (F32 and F16). -static void unary_thread_row_block(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { - (void) nth; - const struct htp_unary_context * uctx = (const struct htp_unary_context *) data; - struct htp_ops_context * octx = uctx->octx; - const struct htp_tensor * src = octx->src[0]; - const struct htp_tensor * dst = octx->dst; - struct htp_thread_trace * tr = th->trace; - - htp_unary_preamble; - - const uint32_t src0_nrows_per_hvx = uctx->src0_nrows_per_hvx; - const size_t src0_data_row_size = uctx->src0_data_row_size; - const size_t dst_data_row_size = uctx->dst_data_row_size; - const size_t src0_row_size_aligned = uctx->src0_row_size_aligned; - const size_t dst_row_size_aligned = uctx->dst_row_size_aligned; - - const uint32_t src0_nrows = uctx->src0_nrows; - const uint32_t src0_start_row = uctx->row_start + src0_nrows_per_hvx * ith; - const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, uctx->row_start + src0_nrows); +struct unary_row_pipe_state { + const struct htp_unary_context * uctx; + dma_addr_t data_src0; + dma_addr_t data_src1; + dma_addr_t data_src2; + dma_addr_t data_dst; + uint8_t * src1_vtcm_bc; + uint32_t ne0, ne01, ne02; + uint32_t nb01, nb02, nb03; + uint32_t nb11, nb12, nb13; + uint32_t nb21, nb22, nb23; + uint32_t nb1; + uint32_t block; + bool src0_contig; + bool src1_contig; + bool block_contig; + bool src0_slice_dma; + uint32_t ir; + uint32_t ir_end; +}; - if (src0_start_row >= src0_end_row) { - return; +static bool unary_row_next_task(void * ctx, struct dma_pipe_task * task) { + struct unary_row_pipe_state * s = (struct unary_row_pipe_state *) ctx; + if (s->ir >= s->ir_end) { + return false; } + const uint32_t block_size = unary_block_size(s->ir, s->ir_end, s->block, s->block_contig, s->src0_slice_dma, + s->ne01, &s->uctx->kparams->div_ne01); + task->row = s->ir; + task->off = 0; + task->len = block_size; + task->aux = 0; + s->ir += block_size; + return true; +} - const dma_addr_t data_src = uctx->data_src0; - const dma_addr_t data_dst = uctx->data_dst; +static void unary_row_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct unary_row_pipe_state * s = (struct unary_row_pipe_state *) ctx; + const struct htp_unary_context * uctx = s->uctx; + unary_push_src0_dma(dma_q, (uint8_t *) in_spad, s->data_src0, + task->row, task->len, s->src0_contig, s->src0_slice_dma, s->ne01, s->ne02, + &uctx->kparams->div_ne01, &uctx->kparams->div_ne02, &uctx->kparams->div_ne012, + s->nb01, s->nb02, s->nb03, uctx->src0_row_size_aligned, uctx->src0_data_row_size); +} - uint8_t * src0_vtcm_data = uctx->vtcm_src0 + (ith * uctx->vtcm_src0_size_per_hvx); - uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx); +static void unary_row_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) { + struct unary_row_pipe_state * s = (struct unary_row_pipe_state *) ctx; + const struct htp_unary_context * uctx = s->uctx; + const size_t dst_off = (size_t) task->row * s->nb1; + dma_queue_push(dma_q, dma_make_data(s->data_dst + dst_off, out_spad), + s->nb1, uctx->dst_row_size_aligned, uctx->dst_data_row_size, task->len); +} - const size_t src0_vtcm_half_size = uctx->src0_vtcm_half_size; - const size_t dst_vtcm_half_size = uctx->dst_vtcm_half_size; +static void unary_row_block_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct unary_row_pipe_state * s = (struct unary_row_pipe_state *) ctx; + unary_compute_fn_t compute = (unary_compute_fn_t) s->uctx->compute; + compute(in_spad, out_spad, task->len, s->ne0, s->uctx); +} - const bool src0_contig = uctx->kparams->src0_contig; - const uint32_t BLOCK = uctx->block; +static void unary_rms_norm_mul_bc_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct unary_row_pipe_state * s = (struct unary_row_pipe_state *) ctx; + const struct htp_unary_context * uctx = s->uctx; + const uint32_t src1_row_start = (uctx->src1_nrows <= 1) ? 0 : fastmodulo(task->row, uctx->src1_nrows, &uctx->kparams->div_ne01); + unary_rms_norm_mul_compute_fn_t compute = (unary_rms_norm_mul_compute_fn_t) uctx->compute; + compute(in_spad, s->src1_vtcm_bc, out_spad, task->len, src1_row_start, uctx); +} +static void unary_rms_norm_mul_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in0_spad, void * in1_spad) { + struct unary_row_pipe_state * s = (struct unary_row_pipe_state *) ctx; + const struct htp_unary_context * uctx = s->uctx; const struct fastdiv_values * div_ne01 = &uctx->kparams->div_ne01; const struct fastdiv_values * div_ne02 = &uctx->kparams->div_ne02; const struct fastdiv_values * div_ne012 = &uctx->kparams->div_ne012; - dma_queue * dma_q = th->dma_q; - - for (uint32_t ir = src0_start_row, vtcm_idx = 0; ir < src0_end_row && vtcm_idx < 2; vtcm_idx++) { - const uint32_t block_size = unary_block_size(ir, src0_end_row, BLOCK, src0_contig, ne01, div_ne01); + const size_t src0_off = s->src0_contig ? ((size_t) task->row * s->nb01) : + unary_row_offset(task->row, s->ne01, s->ne02, div_ne01, div_ne02, div_ne012, s->nb01, s->nb02, s->nb03); + const size_t src1_off = s->src1_contig ? ((size_t) task->row * s->nb11) : + unary_row_offset(task->row, s->ne01, s->ne02, div_ne01, div_ne02, div_ne012, s->nb11, s->nb12, s->nb13); - dma_queue_push(dma_q, - dma_make_data(data_dst, dst_vtcm_data + (vtcm_idx * dst_vtcm_half_size)), - nb1, dst_row_size_aligned, dst_data_row_size, 0); + dma_queue_push(dma_q, dma_make_data(in0_spad, s->data_src0 + src0_off), + uctx->src0_row_size_aligned, s->nb01, uctx->src0_data_row_size, task->len); + dma_queue_push(dma_q, dma_make_data(in1_spad, s->data_src1 + src1_off), + uctx->src1_row_size_aligned, s->nb11, uctx->src1_data_row_size, task->len); +} - const size_t src0_off = src0_contig ? ((size_t) ir * nb01) : - unary_row_offset(ir, ne01, ne02, div_ne01, div_ne02, div_ne012, nb01, nb02, nb03); - dma_queue_push(dma_q, - dma_make_data(src0_vtcm_data + (vtcm_idx * src0_vtcm_half_size), data_src + src0_off), - src0_row_size_aligned, nb01, src0_data_row_size, block_size); +static void unary_rms_norm_mul_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in0_spad, void * in1_spad) { + struct unary_row_pipe_state * s = (struct unary_row_pipe_state *) ctx; + unary_rms_norm_mul_compute_fn_t compute = (unary_rms_norm_mul_compute_fn_t) s->uctx->compute; + compute(in0_spad, in1_spad, out_spad, task->len, 0, s->uctx); +} - ir += block_size; - } +static void unary_rms_norm_mul_add_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in0_spad, void * in2_spad) { + struct unary_row_pipe_state * s = (struct unary_row_pipe_state *) ctx; + const struct htp_unary_context * uctx = s->uctx; + const struct fastdiv_values * div_ne01 = &uctx->kparams->div_ne01; + const struct fastdiv_values * div_ne02 = &uctx->kparams->div_ne02; + const struct fastdiv_values * div_ne012 = &uctx->kparams->div_ne012; - unary_compute_fn_t compute = (unary_compute_fn_t) uctx->compute; + const size_t src0_off = s->src0_contig ? ((size_t) task->row * s->nb01) : + unary_row_offset(task->row, s->ne01, s->ne02, div_ne01, div_ne02, div_ne012, s->nb01, s->nb02, s->nb03); + const size_t src2_off = s->src0_contig ? ((size_t) task->row * s->nb21) : + unary_row_offset(task->row, s->ne01, s->ne02, div_ne01, div_ne02, div_ne012, s->nb21, s->nb22, s->nb23); - for (uint32_t ir = src0_start_row; ir < src0_end_row; ) { - const uint32_t block_size = unary_block_size(ir, src0_end_row, BLOCK, src0_contig, ne01, div_ne01); + dma_queue_push(dma_q, dma_make_data(in0_spad, s->data_src0 + src0_off), + uctx->src0_row_size_aligned, s->nb01, uctx->src0_data_row_size, task->len); + dma_queue_push(dma_q, dma_make_data(in2_spad, s->data_src2 + src2_off), + uctx->src2_row_size_aligned, s->nb21, uctx->src2_data_row_size, task->len); +} - void * dst_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).src; - void * src0_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).dst; +static void unary_rms_norm_mul_add_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in0_spad, void * in2_spad) { + struct unary_row_pipe_state * s = (struct unary_row_pipe_state *) ctx; + const struct htp_unary_context * uctx = s->uctx; + const uint32_t src1_row_start = (uctx->src1_nrows <= 1) ? 0 : fastmodulo(task->row, uctx->src1_nrows, &uctx->kparams->div_ne01); + unary_rms_norm_mul_add_compute_fn_t compute = (unary_rms_norm_mul_add_compute_fn_t) uctx->compute; + compute(in0_spad, s->src1_vtcm_bc, in2_spad, out_spad, task->len, src1_row_start, uctx); +} - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir); - compute(src0_vtcm, dst_vtcm, block_size, uctx); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir); +// 1. Standard row-block unary task (F32 and F16). +static void unary_thread_row_block(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; + const struct htp_unary_context * uctx = (const struct htp_unary_context *) data; + struct htp_ops_context * octx = uctx->octx; + const struct htp_tensor * src = octx->src[0]; + const struct htp_tensor * dst = octx->dst; + htp_unary_preamble; - const size_t dst_off = (size_t) ir * nb1; - dma_queue_push(dma_q, - dma_make_data(data_dst + dst_off, dst_vtcm), - nb1, dst_row_size_aligned, dst_data_row_size, block_size); - - const uint32_t next_ir = ir + block_size; - if (next_ir < src0_end_row) { - const uint32_t next_block_size = unary_block_size(next_ir, src0_end_row, BLOCK, src0_contig, - ne01, div_ne01); - const uint32_t pref_ir = next_ir + next_block_size; - if (pref_ir < src0_end_row) { - const uint32_t pref_block_size = unary_block_size(pref_ir, src0_end_row, BLOCK, src0_contig, - ne01, div_ne01); - const size_t src0_pref_off = src0_contig ? ((size_t) pref_ir * nb01) : - unary_row_offset(pref_ir, ne01, ne02, div_ne01, div_ne02, div_ne012, nb01, nb02, nb03); - dma_queue_push(dma_q, - dma_make_data(src0_vtcm, data_src + src0_pref_off), - src0_row_size_aligned, nb01, src0_data_row_size, pref_block_size); - } - } - ir += block_size; + const uint32_t src0_start_row = uctx->row_start + uctx->src0_nrows_per_hvx * ith; + const uint32_t src0_end_row = MIN(src0_start_row + uctx->src0_nrows_per_hvx, uctx->row_start + uctx->src0_nrows); + if (src0_start_row >= src0_end_row) { + return; } - dma_queue_flush(dma_q); + uint8_t * src0_vtcm_data = uctx->vtcm_src0 + (ith * uctx->vtcm_src0_size_per_hvx); + uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx); + void * in_buf[2] = { src0_vtcm_data, src0_vtcm_data + uctx->src0_vtcm_half_size }; + void * out_buf[2] = { dst_vtcm_data, dst_vtcm_data + uctx->dst_vtcm_half_size }; + + struct unary_row_pipe_state s = { + .uctx = uctx, + .data_src0 = uctx->data_src0, + .data_dst = uctx->data_dst, + .ne0 = ne0, .ne01 = ne01, .ne02 = ne02, + .nb01 = nb01, .nb02 = nb02, .nb03 = nb03, + .nb1 = nb1, + .block = uctx->block, + .src0_contig = uctx->kparams->src0_contig, + .block_contig = uctx->kparams->src0_contig, + .src0_slice_dma = uctx->kparams->src0_slice_dma, + .ir = src0_start_row, + .ir_end = src0_end_row, + }; + + dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, + unary_row_next_task, unary_row_push_in, unary_row_block_compute, unary_row_push_out); } -// 2. RMS_NORM_MUL row-block task with weight buffer. -static void unary_thread_rms_norm_mul_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { +// 2a. RMS_NORM_MUL row-block task with broadcast src1 buffer. +static void unary_thread_rms_norm_mul_bc(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { (void) nth; const struct htp_unary_context * uctx = (const struct htp_unary_context *) data; struct htp_ops_context * octx = uctx->octx; const struct htp_tensor * src = octx->src[0]; const struct htp_tensor * dst = octx->dst; - struct htp_thread_trace * tr = th->trace; - htp_unary_preamble; - const uint32_t src0_nrows_per_hvx = uctx->src0_nrows_per_hvx; - const size_t src0_data_row_size = uctx->src0_data_row_size; - const size_t dst_data_row_size = uctx->dst_data_row_size; - const size_t src0_row_size_aligned = uctx->src0_row_size_aligned; - const size_t dst_row_size_aligned = uctx->dst_row_size_aligned; - - const uint32_t src0_nrows = uctx->src0_nrows; - const uint32_t src0_start_row = uctx->row_start + src0_nrows_per_hvx * ith; - const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, uctx->row_start + src0_nrows); - + const uint32_t src0_start_row = uctx->row_start + uctx->src0_nrows_per_hvx * ith; + const uint32_t src0_end_row = MIN(src0_start_row + uctx->src0_nrows_per_hvx, uctx->row_start + uctx->src0_nrows); if (src0_start_row >= src0_end_row) { return; } - const dma_addr_t data_src = uctx->data_src0; - const dma_addr_t data_src1 = uctx->data_src1; - const dma_addr_t data_dst = uctx->data_dst; - const struct htp_tensor * src1 = octx->src[1]; - const uint32_t nb11 = src1->nb[1]; - const uint32_t nb12 = src1->nb[2]; - const uint32_t nb13 = src1->nb[3]; - uint8_t * src0_vtcm_data = uctx->vtcm_src0 + (ith * uctx->vtcm_src0_size_per_hvx); - uint8_t * src1_vtcm_data = uctx->vtcm_src1 ? (uctx->vtcm_src1 + (ith * uctx->vtcm_src1_size_per_hvx)) : NULL; - uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx); + uint8_t * src1_vtcm_data = uctx->vtcm_src1 + (ith * uctx->vtcm_src1_size_per_hvx); + uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx); + void * in_buf[2] = { src0_vtcm_data, src0_vtcm_data + uctx->src0_vtcm_half_size }; + void * out_buf[2] = { dst_vtcm_data, dst_vtcm_data + uctx->dst_vtcm_half_size }; - const size_t src0_vtcm_half_size = uctx->src0_vtcm_half_size; - const size_t src1_vtcm_half_size = uctx->src1_vtcm_half_size; - const size_t dst_vtcm_half_size = uctx->dst_vtcm_half_size; + dma_queue * dma_q = th->dma_q; + dma_queue_push(dma_q, dma_make_data(src1_vtcm_data, uctx->data_src1), + uctx->src1_row_size_aligned, src1->nb[1], uctx->src1_data_row_size, uctx->src1_nrows); + dma_queue_flush(dma_q); - const bool src0_contig = uctx->kparams->src0_contig; - const bool src1_contig = uctx->kparams->src1_contig; - const bool block_contig = src0_contig && src1_contig; - const uint32_t BLOCK = uctx->block; + struct unary_row_pipe_state s = { + .uctx = uctx, + .data_src0 = uctx->data_src0, + .data_dst = uctx->data_dst, + .src1_vtcm_bc = src1_vtcm_data, + .ne0 = ne0, .ne01 = ne01, .ne02 = ne02, + .nb01 = nb01, .nb02 = nb02, .nb03 = nb03, + .nb1 = nb1, + .block = uctx->block, + .src0_contig = uctx->kparams->src0_contig, + .block_contig = uctx->kparams->src0_contig, + .src0_slice_dma = uctx->kparams->src0_slice_dma, + .ir = src0_start_row, + .ir_end = src0_end_row, + }; - const struct fastdiv_values * div_ne01 = &uctx->kparams->div_ne01; - const struct fastdiv_values * div_ne02 = &uctx->kparams->div_ne02; - const struct fastdiv_values * div_ne012 = &uctx->kparams->div_ne012; + dma_pipe_io_run(dma_q, th->trace, &s, in_buf, out_buf, + unary_row_next_task, unary_row_push_in, unary_rms_norm_mul_bc_compute, unary_row_push_out); +} - dma_queue * dma_q = th->dma_q; +// 2b. RMS_NORM_MUL row-block task with dynamic non-broadcast src1 buffer. +static void unary_thread_rms_norm_mul(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; + const struct htp_unary_context * uctx = (const struct htp_unary_context *) data; + struct htp_ops_context * octx = uctx->octx; + const struct htp_tensor * src = octx->src[0]; + const struct htp_tensor * dst = octx->dst; + htp_unary_preamble; - if (uctx->broadcast_weight) { - dma_queue_push(dma_q, dma_make_data(src1_vtcm_data, data_src1), - uctx->src1_row_size_aligned, 0, uctx->src1_data_row_size, 1); - dma_queue_flush(dma_q); + const uint32_t src0_start_row = uctx->row_start + uctx->src0_nrows_per_hvx * ith; + const uint32_t src0_end_row = MIN(src0_start_row + uctx->src0_nrows_per_hvx, uctx->row_start + uctx->src0_nrows); + if (src0_start_row >= src0_end_row) { + return; } - for (uint32_t ir = src0_start_row, vtcm_idx = 0; ir < src0_end_row && vtcm_idx < 2; vtcm_idx++) { - const uint32_t block_size = unary_block_size(ir, src0_end_row, BLOCK, block_contig, ne01, div_ne01); - - dma_queue_push(dma_q, - dma_make_data(data_dst, dst_vtcm_data + (vtcm_idx * dst_vtcm_half_size)), - nb1, dst_row_size_aligned, dst_data_row_size, 0); + const struct htp_tensor * src1 = octx->src[1]; + uint8_t * src0_vtcm_data = uctx->vtcm_src0 + (ith * uctx->vtcm_src0_size_per_hvx); + uint8_t * src1_vtcm_data = uctx->vtcm_src1 + (ith * uctx->vtcm_src1_size_per_hvx); + uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx); + void * in0_buf[2] = { src0_vtcm_data, src0_vtcm_data + uctx->src0_vtcm_half_size }; + void * in1_buf[2] = { src1_vtcm_data, src1_vtcm_data + uctx->src1_vtcm_half_size }; + void * out_buf[2] = { dst_vtcm_data, dst_vtcm_data + uctx->dst_vtcm_half_size }; + + struct unary_row_pipe_state s = { + .uctx = uctx, + .data_src0 = uctx->data_src0, + .data_src1 = uctx->data_src1, + .data_dst = uctx->data_dst, + .ne0 = ne0, .ne01 = ne01, .ne02 = ne02, + .nb01 = nb01, .nb02 = nb02, .nb03 = nb03, + .nb11 = src1->nb[1], .nb12 = src1->nb[2], .nb13 = src1->nb[3], + .nb1 = nb1, + .block = uctx->block, + .src0_contig = uctx->kparams->src0_contig, + .src1_contig = uctx->kparams->src1_contig, + .block_contig = uctx->kparams->src0_contig && uctx->kparams->src1_contig, + .src0_slice_dma = false, + .ir = src0_start_row, + .ir_end = src0_end_row, + }; - const size_t src0_off = src0_contig ? ((size_t) ir * nb01) : - unary_row_offset(ir, ne01, ne02, div_ne01, div_ne02, div_ne012, nb01, nb02, nb03); - dma_queue_push(dma_q, - dma_make_data(src0_vtcm_data + (vtcm_idx * src0_vtcm_half_size), data_src + src0_off), - src0_row_size_aligned, nb01, src0_data_row_size, block_size); + dma_pipe_io2_run(th->dma_q, th->trace, &s, in0_buf, in1_buf, out_buf, + unary_row_next_task, unary_rms_norm_mul_push_in, unary_rms_norm_mul_compute, unary_row_push_out); +} - if (!uctx->broadcast_weight) { - const size_t src1_off = src1_contig ? ((size_t) ir * nb11) : - unary_row_offset(ir, ne01, ne02, div_ne01, div_ne02, div_ne012, nb11, nb12, nb13); - dma_queue_push(dma_q, - dma_make_data(src1_vtcm_data + (vtcm_idx * src1_vtcm_half_size), data_src1 + src1_off), - uctx->src1_row_size_aligned, nb11, uctx->src1_data_row_size, block_size); - } +// 2b. RMS_NORM_MUL_ADD row-block task with broadcast src1 and residual add. +static void unary_thread_rms_norm_mul_add(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; + const struct htp_unary_context * uctx = (const struct htp_unary_context *) data; + struct htp_ops_context * octx = uctx->octx; + const struct htp_tensor * src = octx->src[0]; + const struct htp_tensor * dst = octx->dst; + htp_unary_preamble; - ir += block_size; + const uint32_t src0_start_row = uctx->row_start + uctx->src0_nrows_per_hvx * ith; + const uint32_t src0_end_row = MIN(src0_start_row + uctx->src0_nrows_per_hvx, uctx->row_start + uctx->src0_nrows); + if (src0_start_row >= src0_end_row) { + return; } - unary_rms_norm_mul_compute_fn_t compute = (unary_rms_norm_mul_compute_fn_t) uctx->compute; - - for (uint32_t ir = src0_start_row; ir < src0_end_row; ) { - const uint32_t block_size = unary_block_size(ir, src0_end_row, BLOCK, block_contig, ne01, div_ne01); - - void * dst_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).src; - void * src0_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).dst; - void * src1_vtcm = NULL; - if (!uctx->broadcast_weight) { - src1_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).dst; - } - - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir); - const void * w = uctx->broadcast_weight ? (const void *) src1_vtcm_data : src1_vtcm; - compute(src0_vtcm, w, dst_vtcm, block_size, uctx); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir); + const struct htp_tensor * src1 = octx->src[1]; + const struct htp_tensor * src2 = octx->src[2]; + uint8_t * src0_vtcm_data = uctx->vtcm_src0 + (ith * uctx->vtcm_src0_size_per_hvx); + uint8_t * src1_vtcm_data = uctx->vtcm_src1 + (ith * uctx->vtcm_src1_size_per_hvx); + uint8_t * src2_vtcm_data = uctx->vtcm_src2 + (ith * uctx->vtcm_src2_size_per_hvx); + uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx); + void * in0_buf[2] = { src0_vtcm_data, src0_vtcm_data + uctx->src0_vtcm_half_size }; + void * in2_buf[2] = { src2_vtcm_data, src2_vtcm_data + uctx->src2_vtcm_half_size }; + void * out_buf[2] = { dst_vtcm_data, dst_vtcm_data + uctx->dst_vtcm_half_size }; - const size_t dst_off = (size_t) ir * nb1; - dma_queue_push(dma_q, - dma_make_data(data_dst + dst_off, dst_vtcm), - nb1, dst_row_size_aligned, dst_data_row_size, block_size); - - const uint32_t next_ir = ir + block_size; - if (next_ir < src0_end_row) { - const uint32_t next_block_size = unary_block_size(next_ir, src0_end_row, BLOCK, block_contig, - ne01, div_ne01); - const uint32_t pref_ir = next_ir + next_block_size; - if (pref_ir < src0_end_row) { - const uint32_t pref_block_size = unary_block_size(pref_ir, src0_end_row, BLOCK, block_contig, - ne01, div_ne01); - const size_t src0_pref_off = src0_contig ? ((size_t) pref_ir * nb01) : - unary_row_offset(pref_ir, ne01, ne02, div_ne01, div_ne02, div_ne012, nb01, nb02, nb03); - dma_queue_push(dma_q, - dma_make_data(src0_vtcm, data_src + src0_pref_off), - src0_row_size_aligned, nb01, src0_data_row_size, pref_block_size); + dma_queue * dma_q = th->dma_q; + dma_queue_push(dma_q, dma_make_data(src1_vtcm_data, uctx->data_src1), + uctx->src1_row_size_aligned, src1->nb[1], uctx->src1_data_row_size, uctx->src1_nrows); + dma_queue_flush(dma_q); - if (!uctx->broadcast_weight) { - const size_t src1_pref_off = src1_contig ? ((size_t) pref_ir * nb11) : - unary_row_offset(pref_ir, ne01, ne02, div_ne01, div_ne02, div_ne012, nb11, nb12, nb13); - dma_queue_push(dma_q, - dma_make_data(src1_vtcm, data_src1 + src1_pref_off), - uctx->src1_row_size_aligned, nb11, uctx->src1_data_row_size, pref_block_size); - } - } - } - ir += block_size; - } + struct unary_row_pipe_state s = { + .uctx = uctx, + .data_src0 = uctx->data_src0, + .data_src2 = uctx->data_src2, + .data_dst = uctx->data_dst, + .src1_vtcm_bc = src1_vtcm_data, + .ne0 = ne0, .ne01 = ne01, .ne02 = ne02, + .nb01 = nb01, .nb02 = nb02, .nb03 = nb03, + .nb21 = src2->nb[1], .nb22 = src2->nb[2], .nb23 = src2->nb[3], + .nb1 = nb1, + .block = uctx->block, + .src0_contig = uctx->kparams->src0_contig, + .block_contig = uctx->kparams->src0_contig, + .src0_slice_dma = false, + .ir = src0_start_row, + .ir_end = src0_end_row, + }; - dma_queue_flush(dma_q); + dma_pipe_io2_run(dma_q, th->trace, &s, in0_buf, in2_buf, out_buf, + unary_row_next_task, unary_rms_norm_mul_add_push_in, unary_rms_norm_mul_add_compute, unary_row_push_out); } -// 2b. RMS_NORM_MUL_ADD row-block task with broadcast weight and residual add. -static void unary_thread_rms_norm_mul_add_f32(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { +// 2c. 2-pass column-tiled task for wide-row RMS_NORM / RMS_NORM_MUL / RMS_NORM_MUL_ADD. +static void unary_thread_tiled_rms_norm(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { (void) nth; const struct htp_unary_context * uctx = (const struct htp_unary_context *) data; struct htp_ops_context * octx = uctx->octx; @@ -1475,10 +3417,7 @@ static void unary_thread_rms_norm_mul_add_f32(const htp_thread_t * th, unsigned htp_unary_preamble; const uint32_t src0_nrows_per_hvx = uctx->src0_nrows_per_hvx; - const size_t src0_data_row_size = uctx->src0_data_row_size; - const size_t dst_data_row_size = uctx->dst_data_row_size; - const size_t src0_row_size_aligned = uctx->src0_row_size_aligned; - const size_t dst_row_size_aligned = uctx->dst_row_size_aligned; + const uint32_t col_tile = uctx->col_tile; const uint32_t src0_nrows = uctx->src0_nrows; const uint32_t src0_start_row = uctx->row_start + src0_nrows_per_hvx * ith; @@ -1488,91 +3427,169 @@ static void unary_thread_rms_norm_mul_add_f32(const htp_thread_t * th, unsigned return; } + const bool has_src1_mul = (octx->op == HTP_OP_RMS_NORM_MUL || octx->op == HTP_OP_RMS_NORM_MUL_ADD); + const bool has_src2_add = (octx->op == HTP_OP_RMS_NORM_MUL_ADD); + + const struct htp_tensor * src1 = has_src1_mul ? octx->src[1] : NULL; + const struct htp_tensor * src2 = has_src2_add ? octx->src[2] : NULL; + + const uint32_t nb10 = has_src1_mul ? src1->nb[0] : 0; + const uint32_t nb11 = has_src1_mul ? src1->nb[1] : 0; + const uint32_t nb12 = has_src1_mul ? src1->nb[2] : 0; + const uint32_t nb13 = has_src1_mul ? src1->nb[3] : 0; + + const uint32_t nb20 = has_src2_add ? src2->nb[0] : 0; + const uint32_t nb21 = has_src2_add ? src2->nb[1] : 0; + const uint32_t nb22 = has_src2_add ? src2->nb[2] : 0; + const uint32_t nb23 = has_src2_add ? src2->nb[3] : 0; + const dma_addr_t data_src = uctx->data_src0; const dma_addr_t data_src1 = uctx->data_src1; const dma_addr_t data_src2 = uctx->data_src2; const dma_addr_t data_dst = uctx->data_dst; uint8_t * src0_vtcm_data = uctx->vtcm_src0 + (ith * uctx->vtcm_src0_size_per_hvx); - uint8_t * src1_vtcm_data = uctx->vtcm_src1 + (ith * uctx->vtcm_src1_size_per_hvx); - uint8_t * src2_vtcm_data = uctx->vtcm_src2 + (ith * uctx->vtcm_src2_size_per_hvx); + uint8_t * src1_vtcm_data = uctx->vtcm_src1 ? (uctx->vtcm_src1 + (ith * uctx->vtcm_src1_size_per_hvx)) : NULL; + uint8_t * src2_vtcm_data = uctx->vtcm_src2 ? (uctx->vtcm_src2 + (ith * uctx->vtcm_src2_size_per_hvx)) : NULL; uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx); - const size_t src0_vtcm_half_size = uctx->src0_vtcm_half_size; - const size_t dst_vtcm_half_size = uctx->dst_vtcm_half_size; - - const bool src0_contig = uctx->kparams->src0_contig; - const uint32_t BLOCK = uctx->block; + const size_t src0_half = uctx->src0_vtcm_half_size; + const size_t src1_half = uctx->src1_vtcm_half_size; + const size_t src2_half = uctx->src2_vtcm_half_size; + const size_t dst_half = uctx->dst_vtcm_half_size; const struct fastdiv_values * div_ne01 = &uctx->kparams->div_ne01; const struct fastdiv_values * div_ne02 = &uctx->kparams->div_ne02; const struct fastdiv_values * div_ne012 = &uctx->kparams->div_ne012; - dma_queue * dma_q = th->dma_q; - - dma_queue_push(dma_q, dma_make_data(src1_vtcm_data, data_src1), - uctx->src1_row_size_aligned, 0, uctx->src1_data_row_size, 1); - dma_queue_flush(dma_q); + const uint32_t tiles_per_row = uctx->kparams->tiles_per_row; + const bool src0_contig = uctx->kparams->src0_contig; + const bool src1_contig = uctx->kparams->src1_contig; - for (uint32_t ir = src0_start_row, vtcm_idx = 0; ir < src0_end_row && vtcm_idx < 2; vtcm_idx++) { - const uint32_t block_size = unary_block_size(ir, src0_end_row, BLOCK, src0_contig, ne01, div_ne01); + float epsilon = 0.f; + float scale = 0.f; + memcpy(&epsilon, &octx->op_params[0], sizeof(float)); + memcpy(&scale, &octx->op_params[1], sizeof(float)); - dma_queue_push(dma_q, - dma_make_data(data_dst, dst_vtcm_data + (vtcm_idx * dst_vtcm_half_size)), - nb1, dst_row_size_aligned, dst_data_row_size, 0); + dma_queue * dma_q = th->dma_q; + const rms_tile_sum_sq_fn_t tile_sum_sq_fn = uctx->rms_tile_sum_sq_fn; + + for (uint32_t row = src0_start_row; row < src0_end_row; row++) { + const uint32_t src1_row = (!has_src1_mul || !uctx->broadcast_src1) ? row : + ((uctx->src1_nrows <= 1) ? 0 : fastmodulo(row, uctx->src1_nrows, div_ne01)); + const size_t src0_row_off = src0_contig ? ((size_t) row * nb01) : + unary_row_offset(row, ne01, ne02, div_ne01, div_ne02, div_ne012, nb01, nb02, nb03); + const size_t src1_row_off = !has_src1_mul ? 0 : + (uctx->broadcast_src1 ? ((size_t) src1_row * nb11) : + (src1_contig ? ((size_t) row * nb11) : + unary_row_offset(row, ne01, ne02, div_ne01, div_ne02, div_ne012, nb11, nb12, nb13))); + const size_t src2_row_off = !has_src2_add ? 0 : + (src0_contig ? ((size_t) row * nb21) : + unary_row_offset(row, ne01, ne02, div_ne01, div_ne02, div_ne012, nb21, nb22, nb23)); + const size_t dst_row_off = (size_t) row * nb1; + + for (uint32_t t = 0; t < tiles_per_row && t < 2; t++) { + const uint32_t col = t * col_tile; + const uint32_t tw = MIN(col_tile, ne0 - col); + const size_t tb0 = (size_t) tw * nb00; + dma_queue_push(dma_q, + dma_make_data(src0_vtcm_data + (t * src0_half), data_src + src0_row_off + (size_t) col * nb00), + tb0, tb0, tb0, 1); + } - const size_t src0_off = src0_contig ? ((size_t) ir * nb01) : - unary_row_offset(ir, ne01, ne02, div_ne01, div_ne02, div_ne012, nb01, nb02, nb03); - dma_queue_push(dma_q, - dma_make_data(src0_vtcm_data + (vtcm_idx * src0_vtcm_half_size), data_src + src0_off), - src0_row_size_aligned, nb01, src0_data_row_size, block_size); - dma_queue_push(dma_q, - dma_make_data(src2_vtcm_data + (vtcm_idx * src0_vtcm_half_size), data_src2 + src0_off), - src0_row_size_aligned, nb01, src0_data_row_size, block_size); + float sum_sq = 0.0f; + for (uint32_t t = 0; t < tiles_per_row; t++) { + const uint32_t col = t * col_tile; + const uint32_t tw = MIN(col_tile, ne0 - col); + const uint8_t * s0 = (const uint8_t *) (uintptr_t) dma_queue_pop(dma_q).dst; + + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, row); + sum_sq += tile_sum_sq_fn(s0, tw); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, row); + + const uint32_t pt = t + 2; + if (pt < tiles_per_row) { + const uint32_t pcol = pt * col_tile; + const uint32_t ptw = MIN(col_tile, ne0 - pcol); + const size_t ptb0 = (size_t) ptw * nb00; + dma_queue_push(dma_q, + dma_make_data((void *) s0, data_src + src0_row_off + (size_t) pcol * nb00), + ptb0, ptb0, ptb0, 1); + } + } - ir += block_size; - } + for (uint32_t t = 0; t < tiles_per_row && t < 2; t++) { + const uint32_t col = t * col_tile; + const uint32_t tw = MIN(col_tile, ne0 - col); + const size_t tb0 = (size_t) tw * nb00; - unary_rms_norm_mul_add_compute_fn_t compute = (unary_rms_norm_mul_add_compute_fn_t) uctx->compute; + dma_queue_push(dma_q, dma_make_data(data_dst, dst_vtcm_data + (t * dst_half)), 0, 0, 0, 0); + dma_queue_push(dma_q, + dma_make_data(src0_vtcm_data + (t * src0_half), data_src + src0_row_off + (size_t) col * nb00), + tb0, tb0, tb0, 1); + if (has_src1_mul) { + const size_t tb1 = (size_t) tw * nb10; + dma_queue_push(dma_q, + dma_make_data(src1_vtcm_data + (t * src1_half), data_src1 + src1_row_off + (size_t) col * nb10), + tb1, tb1, tb1, 1); + } + if (has_src2_add) { + const size_t tb2 = (size_t) tw * nb20; + dma_queue_push(dma_q, + dma_make_data(src2_vtcm_data + (t * src2_half), data_src2 + src2_row_off + (size_t) col * nb20), + tb2, tb2, tb2, 1); + } + } - for (uint32_t ir = src0_start_row; ir < src0_end_row; ) { - const uint32_t block_size = unary_block_size(ir, src0_end_row, BLOCK, src0_contig, ne01, div_ne01); + for (uint32_t t = 0; t < tiles_per_row; t++) { + const uint32_t col = t * col_tile; + const uint32_t tw = MIN(col_tile, ne0 - col); - void * dst_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).src; - void * src0_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).dst; - void * src2_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).dst; + uint8_t * d_vtcm = (uint8_t *) (uintptr_t) dma_queue_pop(dma_q).src; + const uint8_t * s0_vtcm = (const uint8_t *) (uintptr_t) dma_queue_pop(dma_q).dst; + const uint8_t * s1_vtcm = has_src1_mul ? (const uint8_t *) (uintptr_t) dma_queue_pop(dma_q).dst : NULL; + const uint8_t * s2_vtcm = has_src2_add ? (const uint8_t *) (uintptr_t) dma_queue_pop(dma_q).dst : NULL; - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir); - compute(src0_vtcm, src1_vtcm_data, src2_vtcm, dst_vtcm, block_size, uctx); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir); + htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, row); + rms_norm_apply_tile(s0_vtcm, s1_vtcm, s2_vtcm, d_vtcm, tw, ne0, sum_sq, epsilon, scale, uctx); + htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, row); - const size_t dst_off = (size_t) ir * nb1; - dma_queue_push(dma_q, - dma_make_data(data_dst + dst_off, dst_vtcm), - nb1, dst_row_size_aligned, dst_data_row_size, block_size); - - const uint32_t next_ir = ir + block_size; - if (next_ir < src0_end_row) { - const uint32_t next_block_size = unary_block_size(next_ir, src0_end_row, BLOCK, src0_contig, - ne01, div_ne01); - const uint32_t pref_ir = next_ir + next_block_size; - if (pref_ir < src0_end_row) { - const uint32_t pref_block_size = unary_block_size(pref_ir, src0_end_row, BLOCK, src0_contig, - ne01, div_ne01); - const size_t src0_pref_off = src0_contig ? ((size_t) pref_ir * nb01) : - unary_row_offset(pref_ir, ne01, ne02, div_ne01, div_ne02, div_ne012, nb01, nb02, nb03); - dma_queue_push(dma_q, - dma_make_data(src0_vtcm, data_src + src0_pref_off), - src0_row_size_aligned, nb01, src0_data_row_size, pref_block_size); + const size_t tb_dst = (size_t) tw * nb0; + dma_queue_push(dma_q, + dma_make_data(data_dst + dst_row_off + (size_t) col * nb0, d_vtcm), + tb_dst, tb_dst, tb_dst, 1); + + const uint32_t pt = t + 2; + if (pt < tiles_per_row) { + const uint32_t pcol = pt * col_tile; + const uint32_t ptw = MIN(col_tile, ne0 - pcol); + const size_t ptb0 = (size_t) ptw * nb00; dma_queue_push(dma_q, - dma_make_data(src2_vtcm, data_src2 + src0_pref_off), - src0_row_size_aligned, nb01, src0_data_row_size, pref_block_size); + dma_make_data((void *) s0_vtcm, data_src + src0_row_off + (size_t) pcol * nb00), + ptb0, ptb0, ptb0, 1); + if (has_src1_mul) { + const size_t ptb1 = (size_t) ptw * nb10; + dma_queue_push(dma_q, + dma_make_data((void *) s1_vtcm, data_src1 + src1_row_off + (size_t) pcol * nb10), + ptb1, ptb1, ptb1, 1); + } + if (has_src2_add) { + const size_t ptb2 = (size_t) ptw * nb20; + dma_queue_push(dma_q, + dma_make_data((void *) s2_vtcm, data_src2 + src2_row_off + (size_t) pcol * nb20), + ptb2, ptb2, ptb2, 1); + } } } - ir += block_size; + + dma_queue_flush(dma_q); } +} - dma_queue_flush(dma_q); +static void unary_tri_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct unary_row_pipe_state * s = (struct unary_row_pipe_state *) ctx; + unary_tri_compute_fn_t compute = (unary_tri_compute_fn_t) s->uctx->compute; + compute(in_spad, out_spad, task->len, task->row, s->uctx); } // 3. TRI row-block task with row index ir. @@ -1582,84 +3599,111 @@ static void unary_thread_tri_f32(const htp_thread_t * th, unsigned int nth, unsi struct htp_ops_context * octx = uctx->octx; const struct htp_tensor * src = octx->src[0]; const struct htp_tensor * dst = octx->dst; - struct htp_thread_trace * tr = th->trace; - htp_unary_preamble; - const uint32_t src0_nrows_per_hvx = uctx->src0_nrows_per_hvx; - const size_t src0_data_row_size = uctx->src0_data_row_size; - const size_t dst_data_row_size = uctx->dst_data_row_size; - const size_t src0_row_size_aligned = uctx->src0_row_size_aligned; - const size_t dst_row_size_aligned = uctx->dst_row_size_aligned; - - const uint32_t src0_nrows = uctx->src0_nrows; - const uint32_t src0_start_row = uctx->row_start + src0_nrows_per_hvx * ith; - const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, uctx->row_start + src0_nrows); - + const uint32_t src0_start_row = uctx->row_start + uctx->src0_nrows_per_hvx * ith; + const uint32_t src0_end_row = MIN(src0_start_row + uctx->src0_nrows_per_hvx, uctx->row_start + uctx->src0_nrows); if (src0_start_row >= src0_end_row) { return; } - const dma_addr_t data_src = uctx->data_src0; - const dma_addr_t data_dst = uctx->data_dst; - uint8_t * src0_vtcm_data = uctx->vtcm_src0 + (ith * uctx->vtcm_src0_size_per_hvx); - uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx); - - const size_t src0_vtcm_half_size = uctx->src0_vtcm_half_size; - const size_t dst_vtcm_half_size = uctx->dst_vtcm_half_size; - const uint32_t BLOCK = uctx->block; - - dma_queue * dma_q = th->dma_q; - - for (uint32_t ir = src0_start_row, vtcm_idx = 0; ir < src0_end_row && vtcm_idx < 2; vtcm_idx++) { - const uint32_t block_size = MIN(BLOCK, src0_end_row - ir); - - dma_queue_push(dma_q, - dma_make_data(data_dst, dst_vtcm_data + (vtcm_idx * dst_vtcm_half_size)), - nb1, dst_row_size_aligned, dst_data_row_size, 0); + uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx); + void * in_buf[2] = { src0_vtcm_data, src0_vtcm_data + uctx->src0_vtcm_half_size }; + void * out_buf[2] = { dst_vtcm_data, dst_vtcm_data + uctx->dst_vtcm_half_size }; + + struct unary_row_pipe_state s = { + .uctx = uctx, + .data_src0 = uctx->data_src0, + .data_dst = uctx->data_dst, + .ne0 = ne0, .ne01 = ne01, .ne02 = ne02, + .nb01 = nb01, .nb02 = nb02, .nb03 = nb03, + .nb1 = nb1, + .block = uctx->block, + .src0_contig = true, + .block_contig = true, + .src0_slice_dma = false, + .ir = src0_start_row, + .ir_end = src0_end_row, + }; - const size_t src0_off = (size_t) ir * nb01; - dma_queue_push(dma_q, - dma_make_data(src0_vtcm_data + (vtcm_idx * src0_vtcm_half_size), data_src + src0_off), - src0_row_size_aligned, nb01, src0_data_row_size, block_size); + dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, + unary_row_next_task, unary_row_push_in, unary_tri_compute, unary_row_push_out); +} + +struct unary_tiled_pipe_state { + const struct htp_unary_context * uctx; + dma_addr_t data_src0; + dma_addr_t data_dst; + uint32_t ne0, ne01, ne02; + uint32_t nb00, nb01, nb02, nb03; + uint32_t nb0, nb1; + uint32_t col_tile; + uint32_t tiles_per_row; + uint32_t row; + uint32_t row_end; + uint32_t col; + uint32_t tile_in_row; + uint32_t i01; + int32_t tri_ttype; + bool src0_contig; +}; - ir += block_size; +static bool unary_tiled_next_task(void * ctx, struct dma_pipe_task * task) { + struct unary_tiled_pipe_state * s = (struct unary_tiled_pipe_state *) ctx; + if (s->row >= s->row_end) { + return false; + } + + const uint32_t tw = MIN(s->col_tile, s->ne0 - s->col); + task->row = s->row; + task->off = s->col; + task->len = tw; + task->aux = s->i01; + + s->tile_in_row++; + s->col += s->col_tile; + if (s->tile_in_row == s->tiles_per_row) { + s->tile_in_row = 0; + s->col = 0; + s->row++; + s->i01++; + if (s->i01 == s->ne01) { + s->i01 = 0; + } } + return true; +} - unary_tri_compute_fn_t compute = (unary_tri_compute_fn_t) uctx->compute; - - for (uint32_t ir = src0_start_row; ir < src0_end_row; ) { - const uint32_t block_size = MIN(BLOCK, src0_end_row - ir); - - void * dst_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).src; - void * src0_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).dst; +static void unary_tiled_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct unary_tiled_pipe_state * s = (struct unary_tiled_pipe_state *) ctx; + const struct htp_unary_context * uctx = s->uctx; + const size_t tb = (size_t) task->len * s->nb00; + const size_t soff = (s->src0_contig ? ((size_t) task->row * s->nb01) : + unary_row_offset(task->row, s->ne01, s->ne02, + &uctx->kparams->div_ne01, &uctx->kparams->div_ne02, &uctx->kparams->div_ne012, + s->nb01, s->nb02, s->nb03)) + + (size_t) task->off * s->nb00; + dma_queue_push(dma_q, dma_make_data(in_spad, s->data_src0 + soff), tb, tb, tb, 1); +} - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, ir); - compute(src0_vtcm, dst_vtcm, block_size, ir, uctx); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, ir); +static void unary_tiled_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) { + struct unary_tiled_pipe_state * s = (struct unary_tiled_pipe_state *) ctx; + const size_t doff = (size_t) task->row * s->nb1 + (size_t) task->off * s->nb0; + const size_t tb = (size_t) task->len * s->nb0; + dma_queue_push(dma_q, dma_make_data(s->data_dst + doff, out_spad), tb, tb, tb, 1); +} - const size_t dst_off = (size_t) ir * nb1; - dma_queue_push(dma_q, - dma_make_data(data_dst + dst_off, dst_vtcm), - nb1, dst_row_size_aligned, dst_data_row_size, block_size); - - const uint32_t next_ir = ir + block_size; - if (next_ir < src0_end_row) { - const uint32_t next_block_size = MIN(BLOCK, src0_end_row - next_ir); - const uint32_t pref_ir = next_ir + next_block_size; - if (pref_ir < src0_end_row) { - const uint32_t pref_block_size = MIN(BLOCK, src0_end_row - pref_ir); - const size_t src0_pref_off = (size_t) pref_ir * nb01; - dma_queue_push(dma_q, - dma_make_data(src0_vtcm, data_src + src0_pref_off), - src0_row_size_aligned, nb01, src0_data_row_size, pref_block_size); - } - } - ir += block_size; - } +static void unary_tiled_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct unary_tiled_pipe_state * s = (struct unary_tiled_pipe_state *) ctx; + unary_compute_fn_t compute = (unary_compute_fn_t) s->uctx->compute; + compute(in_spad, out_spad, 1, task->len, s->uctx); +} - dma_queue_flush(dma_q); +static void unary_tiled_tri_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct unary_tiled_pipe_state * s = (struct unary_tiled_pipe_state *) ctx; + unary_tiled_tri_compute_fn_t compute = (unary_tiled_tri_compute_fn_t) s->uctx->compute; + compute(in_spad, out_spad, task->len, task->off, task->aux, s->ne0, s->tri_ttype); } // 4. Pointwise tiled unary task. @@ -1669,108 +3713,39 @@ static void unary_thread_tiled(const htp_thread_t * th, unsigned int nth, unsign struct htp_ops_context * octx = uctx->octx; const struct htp_tensor * src = octx->src[0]; const struct htp_tensor * dst = octx->dst; - struct htp_thread_trace * tr = th->trace; - htp_unary_preamble; - const uint32_t src0_nrows_per_hvx = uctx->src0_nrows_per_hvx; - const uint32_t col_tile = uctx->col_tile; - - const uint32_t src0_nrows = uctx->src0_nrows; - const uint32_t src0_start_row = uctx->row_start + src0_nrows_per_hvx * ith; - const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, uctx->row_start + src0_nrows); - + const uint32_t src0_start_row = uctx->row_start + uctx->src0_nrows_per_hvx * ith; + const uint32_t src0_end_row = MIN(src0_start_row + uctx->src0_nrows_per_hvx, uctx->row_start + uctx->src0_nrows); if (src0_start_row >= src0_end_row) { return; } - const dma_addr_t data_src = uctx->data_src0; - const dma_addr_t data_dst = uctx->data_dst; - uint8_t * src0_vtcm_data = uctx->vtcm_src0 + (ith * uctx->vtcm_src0_size_per_hvx); - uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx); - - const size_t src0_half = uctx->src0_vtcm_half_size; - const size_t dst_half = uctx->dst_vtcm_half_size; - - dma_queue * dma_q = th->dma_q; - - const struct fastdiv_values * div_ne01 = &uctx->kparams->div_ne01; - const struct fastdiv_values * div_ne02 = &uctx->kparams->div_ne02; - const struct fastdiv_values * div_ne012 = &uctx->kparams->div_ne012; - const struct fastdiv_values * div_tpr = &uctx->kparams->div_tpr; - - const uint32_t tiles_per_row = uctx->kparams->tiles_per_row; - const bool src0_contig = uctx->kparams->src0_contig; - - const uint32_t total_tiles = (src0_end_row - src0_start_row) * tiles_per_row; - - for (uint32_t t = 0, vtcm_idx = 0; t < total_tiles && vtcm_idx < 2; t++, vtcm_idx++) { - const uint32_t row = src0_start_row + fastdiv(t, div_tpr); - const uint32_t col = fastmodulo(t, tiles_per_row, div_tpr) * col_tile; - const uint32_t tw = MIN(col_tile, ne0 - col); - const size_t tb = (size_t) tw * sizeof(float); - const size_t soff = (src0_contig ? ((size_t) row * nb01) : - unary_row_offset(row, ne01, ne02, div_ne01, div_ne02, div_ne012, nb01, nb02, nb03)) + - (size_t) col * sizeof(float); - - dma_queue_push(dma_q, dma_make_data(data_dst, dst_vtcm_data + (vtcm_idx * dst_half)), 0, 0, 0, 0); - dma_queue_push(dma_q, dma_make_data(src0_vtcm_data + (vtcm_idx * src0_half), data_src + soff), tb, tb, tb, 1); - } - - unary_tile_compute_fn_t compute = (unary_tile_compute_fn_t) uctx->compute; - - uint32_t row = src0_start_row; - uint32_t col = 0; - uint32_t tile_in_row = 0; - - uint32_t prow = src0_start_row + fastdiv(2, div_tpr); - uint32_t pcol = fastmodulo(2, tiles_per_row, div_tpr) * col_tile; - uint32_t ptile_in_row = fastmodulo(2, tiles_per_row, div_tpr); - - for (uint32_t t = 0; t < total_tiles; t++) { - void * dst_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).src; - void * src_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).dst; - - const uint32_t tw = MIN(col_tile, ne0 - col); - - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, t); - compute(dst_vtcm, src_vtcm, tw, uctx); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, t); - - const size_t doff = (size_t) row * nb1 + (size_t) col * sizeof(float); - const size_t tb = (size_t) tw * sizeof(float); - dma_queue_push(dma_q, dma_make_data(data_dst + doff, dst_vtcm), tb, tb, tb, 1); - - const uint32_t pt = t + 2; - if (pt < total_tiles) { - const uint32_t ptw = MIN(col_tile, ne0 - pcol); - const size_t ptb = (size_t) ptw * sizeof(float); - const size_t psoff = (src0_contig ? ((size_t) prow * nb01) : - unary_row_offset(prow, ne01, ne02, div_ne01, div_ne02, div_ne012, nb01, nb02, - nb03)) + - (size_t) pcol * sizeof(float); - dma_queue_push(dma_q, dma_make_data(src_vtcm, data_src + psoff), ptb, ptb, ptb, 1); - } - - tile_in_row++; - col += col_tile; - if (tile_in_row == tiles_per_row) { - tile_in_row = 0; - col = 0; - row++; - } - - ptile_in_row++; - pcol += col_tile; - if (ptile_in_row == tiles_per_row) { - ptile_in_row = 0; - pcol = 0; - prow++; - } - } + uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx); + void * in_buf[2] = { src0_vtcm_data, src0_vtcm_data + uctx->src0_vtcm_half_size }; + void * out_buf[2] = { dst_vtcm_data, dst_vtcm_data + uctx->dst_vtcm_half_size }; + + struct unary_tiled_pipe_state s = { + .uctx = uctx, + .data_src0 = uctx->data_src0, + .data_dst = uctx->data_dst, + .ne0 = ne0, .ne01 = ne01, .ne02 = ne02, + .nb00 = nb00, .nb01 = nb01, .nb02 = nb02, .nb03 = nb03, + .nb0 = nb0, .nb1 = nb1, + .col_tile = uctx->col_tile, + .tiles_per_row = uctx->kparams->tiles_per_row, + .row = src0_start_row, + .row_end = src0_end_row, + .col = 0, + .tile_in_row = 0, + .i01 = 0, + .tri_ttype = 0, + .src0_contig = uctx->kparams->src0_contig, + }; - dma_queue_flush(dma_q); + dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, + unary_tiled_next_task, unary_tiled_push_in, unary_tiled_compute, unary_tiled_push_out); } // 5. TRI tiled task. @@ -1780,107 +3755,39 @@ static void unary_thread_tiled_tri_f32(const htp_thread_t * th, unsigned int nth struct htp_ops_context * octx = uctx->octx; const struct htp_tensor * src = octx->src[0]; const struct htp_tensor * dst = octx->dst; - struct htp_thread_trace * tr = th->trace; - htp_unary_preamble; - const uint32_t src0_nrows_per_hvx = uctx->src0_nrows_per_hvx; - const int32_t * op_params = octx->op_params; - const uint32_t col_tile = uctx->col_tile; - - const uint32_t src0_nrows = uctx->src0_nrows; - const uint32_t src0_start_row = uctx->row_start + src0_nrows_per_hvx * ith; - const uint32_t src0_end_row = MIN(src0_start_row + src0_nrows_per_hvx, uctx->row_start + src0_nrows); - + const uint32_t src0_start_row = uctx->row_start + uctx->src0_nrows_per_hvx * ith; + const uint32_t src0_end_row = MIN(src0_start_row + uctx->src0_nrows_per_hvx, uctx->row_start + uctx->src0_nrows); if (src0_start_row >= src0_end_row) { return; } - const dma_addr_t data_src = uctx->data_src0; - const dma_addr_t data_dst = uctx->data_dst; - uint8_t * src0_vtcm_data = uctx->vtcm_src0 + (ith * uctx->vtcm_src0_size_per_hvx); - uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx); - - const size_t src0_half = uctx->src0_vtcm_half_size; - const size_t dst_half = uctx->dst_vtcm_half_size; - - dma_queue * dma_q = th->dma_q; - - const struct fastdiv_values * div_ne01 = &uctx->kparams->div_ne01; - const struct fastdiv_values * div_tpr = &uctx->kparams->div_tpr; - - const uint32_t tiles_per_row = uctx->kparams->tiles_per_row; - const int32_t tri_ttype = op_params[0]; - - const uint32_t total_tiles = (src0_end_row - src0_start_row) * tiles_per_row; - - for (uint32_t t = 0, vtcm_idx = 0; t < total_tiles && vtcm_idx < 2; t++, vtcm_idx++) { - const uint32_t row = src0_start_row + fastdiv(t, div_tpr); - const uint32_t col = fastmodulo(t, tiles_per_row, div_tpr) * col_tile; - const uint32_t tw = MIN(col_tile, ne0 - col); - const size_t tb = (size_t) tw * sizeof(float); - const size_t soff = (size_t) row * nb01 + (size_t) col * sizeof(float); - - dma_queue_push(dma_q, dma_make_data(data_dst, dst_vtcm_data + (vtcm_idx * dst_half)), 0, 0, 0, 0); - dma_queue_push(dma_q, dma_make_data(src0_vtcm_data + (vtcm_idx * src0_half), data_src + soff), tb, tb, tb, 1); - } - - unary_tiled_tri_compute_fn_t compute = (unary_tiled_tri_compute_fn_t) uctx->compute; - - uint32_t row = src0_start_row; - uint32_t col = 0; - uint32_t tile_in_row = 0; - uint32_t i01 = fastmodulo(row, ne01, div_ne01); - - uint32_t prow = src0_start_row + fastdiv(2, div_tpr); - uint32_t pcol = fastmodulo(2, tiles_per_row, div_tpr) * col_tile; - uint32_t ptile_in_row = fastmodulo(2, tiles_per_row, div_tpr); - - for (uint32_t t = 0; t < total_tiles; t++) { - void * dst_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).src; - void * src_vtcm = (void *) (uintptr_t) dma_queue_pop(dma_q).dst; - - const uint32_t tw = MIN(col_tile, ne0 - col); - - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, t); - compute(src_vtcm, dst_vtcm, tw, col, i01, ne0, tri_ttype); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, t); - - const size_t doff = (size_t) row * nb1 + (size_t) col * sizeof(float); - const size_t tb = (size_t) tw * sizeof(float); - dma_queue_push(dma_q, dma_make_data(data_dst + doff, dst_vtcm), tb, tb, tb, 1); - - const uint32_t pt = t + 2; - if (pt < total_tiles) { - const uint32_t ptw = MIN(col_tile, ne0 - pcol); - const size_t ptb = (size_t) ptw * sizeof(float); - const size_t psoff = (size_t) prow * nb01 + (size_t) pcol * sizeof(float); - dma_queue_push(dma_q, dma_make_data(src_vtcm, data_src + psoff), ptb, ptb, ptb, 1); - } - - tile_in_row++; - col += col_tile; - if (tile_in_row == tiles_per_row) { - tile_in_row = 0; - col = 0; - row++; - i01++; - if (i01 == ne01) { - i01 = 0; - } - } - - ptile_in_row++; - pcol += col_tile; - if (ptile_in_row == tiles_per_row) { - ptile_in_row = 0; - pcol = 0; - prow++; - } - } + uint8_t * dst_vtcm_data = uctx->vtcm_dst + (ith * uctx->vtcm_dst_size_per_hvx); + void * in_buf[2] = { src0_vtcm_data, src0_vtcm_data + uctx->src0_vtcm_half_size }; + void * out_buf[2] = { dst_vtcm_data, dst_vtcm_data + uctx->dst_vtcm_half_size }; + + struct unary_tiled_pipe_state s = { + .uctx = uctx, + .data_src0 = uctx->data_src0, + .data_dst = uctx->data_dst, + .ne0 = ne0, .ne01 = ne01, .ne02 = ne02, + .nb00 = sizeof(float), .nb01 = nb01, .nb02 = nb02, .nb03 = nb03, + .nb0 = sizeof(float), .nb1 = nb1, + .col_tile = uctx->col_tile, + .tiles_per_row = uctx->kparams->tiles_per_row, + .row = src0_start_row, + .row_end = src0_end_row, + .col = 0, + .tile_in_row = 0, + .i01 = fastmodulo(src0_start_row, ne01, &uctx->kparams->div_ne01), + .tri_ttype = octx->op_params[0], + .src0_contig = true, + }; - dma_queue_flush(dma_q); + dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, + unary_tiled_next_task, unary_tiled_push_in, unary_tiled_tri_compute, unary_tiled_push_out); } static int execute_op_unary(struct htp_ops_context * octx) { @@ -1894,33 +3801,33 @@ static int execute_op_unary(struct htp_ops_context * octx) { const char * op_type = NULL; switch (octx->op) { - case HTP_OP_NORM: op_type = is_f16 ? "norm-f16" : "norm-f32"; break; - case HTP_OP_RMS_NORM: op_type = is_f16 ? "rmsnorm-f16" : "rmsnorm-f32"; break; - case HTP_OP_RMS_NORM_MUL: op_type = "rmsnorm-mul-f32"; break; - case HTP_OP_RMS_NORM_MUL_ADD: op_type = "rmsnorm-mul-add-f32"; break; - case HTP_OP_SCALE: op_type = is_f16 ? "scale-f16" : "scale-f32"; break; - case HTP_OP_CLAMP: op_type = is_f16 ? "clamp-f16" : "clamp-f32"; break; - case HTP_OP_LEAKY_RELU: op_type = "leaky-relu-f32"; break; - case HTP_OP_SQR: op_type = is_f16 ? "sqr-f16" : "sqr-f32"; break; - case HTP_OP_SQRT: op_type = is_f16 ? "sqrt-f16" : "sqrt-f32"; break; - case HTP_OP_UNARY_NEG: op_type = "neg-f32"; break; - case HTP_OP_UNARY_EXP: op_type = "exp-f32"; break; - case HTP_OP_UNARY_SIGMOID: op_type = "sigmoid-f32"; break; - case HTP_OP_UNARY_SILU: op_type = "silu-f32"; break; - case HTP_OP_UNARY_GELU: op_type = "gelu-f32"; break; - case HTP_OP_UNARY_GELU_QUICK: op_type = "gelu-quick-f32"; break; - case HTP_OP_UNARY_GELU_ERF: op_type = "gelu-erf-f32"; break; - case HTP_OP_UNARY_SOFTPLUS: op_type = "softplus-f32"; break; - case HTP_OP_UNARY_TANH: op_type = "tanh-f32"; break; - case HTP_OP_UNARY_ABS: op_type = is_f16 ? "abs-f16" : "abs-f32"; break; - case HTP_OP_UNARY_LOG: op_type = is_f16 ? "log-f16" : "log-f32"; break; - case HTP_OP_UNARY_RELU: op_type = "relu-f32"; break; - case HTP_OP_UNARY_STEP: op_type = is_f16 ? "step-f16" : "step-f32"; break; - case HTP_OP_UNARY_CEIL: op_type = is_f16 ? "ceil-f16" : "ceil-f32"; break; - case HTP_OP_UNARY_SGN: op_type = is_f16 ? "sgn-f16" : "sgn-f32"; break; - case HTP_OP_L2_NORM: op_type = is_f16 ? "l2norm-f16" : "l2norm-f32"; break; - case HTP_OP_TRI: op_type = "tri-f32"; break; - case HTP_OP_HADAMARD: op_type = is_f16 ? "hadamard-f16" : "hadamard-f32"; break; + case HTP_OP_NORM: op_type = is_f16 ? "norm-f16" : "norm-f32"; break; + case HTP_OP_RMS_NORM: op_type = is_f16 ? "rmsnorm-f16" : "rmsnorm-f32"; break; + case HTP_OP_RMS_NORM_MUL: op_type = is_f16 ? "rmsnorm-mul-f16" : "rmsnorm-mul-f32"; break; + case HTP_OP_RMS_NORM_MUL_ADD: op_type = is_f16 ? "rmsnorm-mul-add-f16" : "rmsnorm-mul-add-f32"; break; + case HTP_OP_SCALE: op_type = is_f16 ? "scale-f16" : "scale-f32"; break; + case HTP_OP_CLAMP: op_type = is_f16 ? "clamp-f16" : "clamp-f32"; break; + case HTP_OP_LEAKY_RELU: op_type = is_f16 ? "leaky-relu-f16" : "leaky-relu-f32"; break; + case HTP_OP_SQR: op_type = is_f16 ? "sqr-f16" : "sqr-f32"; break; + case HTP_OP_SQRT: op_type = is_f16 ? "sqrt-f16" : "sqrt-f32"; break; + case HTP_OP_UNARY_NEG: op_type = is_f16 ? "neg-f16" : "neg-f32"; break; + case HTP_OP_UNARY_EXP: op_type = is_f16 ? "exp-f16" : "exp-f32"; break; + case HTP_OP_UNARY_SIGMOID: op_type = is_f16 ? "sigmoid-f16" : "sigmoid-f32"; break; + case HTP_OP_UNARY_SILU: op_type = is_f16 ? "silu-f16" : "silu-f32"; break; + case HTP_OP_UNARY_GELU: op_type = is_f16 ? "gelu-f16" : "gelu-f32"; break; + case HTP_OP_UNARY_GELU_QUICK: op_type = is_f16 ? "gelu-quick-f16" : "gelu-quick-f32"; break; + case HTP_OP_UNARY_GELU_ERF: op_type = is_f16 ? "gelu-erf-f16" : "gelu-erf-f32"; break; + case HTP_OP_UNARY_SOFTPLUS: op_type = is_f16 ? "softplus-f16" : "softplus-f32"; break; + case HTP_OP_UNARY_TANH: op_type = is_f16 ? "tanh-f16" : "tanh-f32"; break; + case HTP_OP_UNARY_ABS: op_type = is_f16 ? "abs-f16" : "abs-f32"; break; + case HTP_OP_UNARY_LOG: op_type = is_f16 ? "log-f16" : "log-f32"; break; + case HTP_OP_UNARY_RELU: op_type = is_f16 ? "relu-f16" : "relu-f32"; break; + case HTP_OP_UNARY_STEP: op_type = is_f16 ? "step-f16" : "step-f32"; break; + case HTP_OP_UNARY_CEIL: op_type = is_f16 ? "ceil-f16" : "ceil-f32"; break; + case HTP_OP_UNARY_SGN: op_type = is_f16 ? "sgn-f16" : "sgn-f32"; break; + case HTP_OP_L2_NORM: op_type = is_f16 ? "l2norm-f16" : "l2norm-f32"; break; + case HTP_OP_TRI: op_type = "tri-f32"; break; + case HTP_OP_HADAMARD: op_type = is_f16 ? "hadamard-f16" : "hadamard-f32"; break; default: FARF(ERROR, "Unsupported unary Op %u\n", octx->op); return HTP_STATUS_NO_SUPPORT; @@ -1932,19 +3839,28 @@ static int execute_op_unary(struct htp_ops_context * octx) { return HTP_STATUS_INVAL_PARAMS; } + const bool has_src1_mul = (octx->op == HTP_OP_RMS_NORM_MUL || octx->op == HTP_OP_RMS_NORM_MUL_ADD); + const bool has_src2_add = (octx->op == HTP_OP_RMS_NORM_MUL_ADD); + + const struct htp_tensor * src1 = has_src1_mul ? octx->src[1] : NULL; + const struct htp_tensor * src2 = has_src2_add ? octx->src[2] : NULL; + const size_t src0_elem_size = is_f16 ? sizeof(_Float16) : sizeof(float); const size_t dst_elem_size = (dst->type == HTP_TYPE_F16) ? sizeof(_Float16) : sizeof(float); + const size_t src1_elem_size = (has_src1_mul && src1->type == HTP_TYPE_F16) ? sizeof(_Float16) : sizeof(float); + const size_t src2_elem_size = (has_src2_add && src2->type == HTP_TYPE_F16) ? sizeof(_Float16) : sizeof(float); + const uint32_t src0_nrows = src0->ne[1] * src0->ne[2] * src0->ne[3]; const size_t src0_data_row_size = src0->ne[0] * src0_elem_size; const size_t dst_data_row_size = dst->ne[0] * dst_elem_size; + const size_t src1_data_row_size = has_src1_mul ? (src1->ne[0] * src1_elem_size) : 0; + const size_t src2_data_row_size = has_src2_add ? (src2->ne[0] * src2_elem_size) : 0; uint32_t row_start = 0; uint32_t nrows = src0_nrows; if (octx->ctx->mdev.count > 1) { - uint32_t rows_per_chunk = 0; - htp_tensor_mdev_rows_per_chunk(dst, (uint32_t) dst_elem_size, (uint32_t) dst_data_row_size, &rows_per_chunk); - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(src0_nrows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); row_start = range.start; nrows = range.count; } @@ -1955,36 +3871,21 @@ static int execute_op_unary(struct htp_ops_context * octx) { const uint32_t n_hvx = octx->n_hvx; - // Always 0 for F16 - htp_unary_solve_layout() keeps F16 on the row-block path, - // since only F32 has unary_task_f32_tiled_* kernels. const uint32_t col_tile = kparams->col_tile; - size_t src1_data_row_size = 0; - bool broadcast_weight = kparams->broadcast_weight; - const struct htp_tensor * src1 = NULL; - - const bool has_weight = (octx->op == HTP_OP_RMS_NORM_MUL || octx->op == HTP_OP_RMS_NORM_MUL_ADD); - const bool has_src2 = (octx->op == HTP_OP_RMS_NORM_MUL_ADD); - - // RMS_NORM_MUL* fusion is F32-only (its weight tensor is always F32; see - // try_fuse_node()'s type guard), so this never triggers when is_f16 is true. - if (has_weight) { - src1 = octx->src[1]; - src1_data_row_size = src1->ne[0] * sizeof(float); - } + bool broadcast_src1 = kparams->broadcast_src1; + const uint32_t src1_nrows = broadcast_src1 ? (uint32_t) src1->ne[1] : 0; if ((!col_tile && kparams->block == 0) || octx->ctx->vtcm_size < (size_t) kparams->vtcm_size) { FARF(ERROR, "unary-%s : current VTCM reservation %zu is too small, needed %zu\n", op_type, octx->ctx->vtcm_size, (size_t) kparams->vtcm_size); return HTP_STATUS_VTCM_TOO_SMALL; } - octx->src0_spad.src = NULL; - octx->src1_spad.src = NULL; - octx->dst_spad.src = NULL; struct htp_unary_vtcm_layout L; - htp_unary_vtcm_layout_build(&L, octx->op, src0_data_row_size, dst_data_row_size, src1_data_row_size, - src0_elem_size, col_tile, kparams->block, broadcast_weight, kparams->n_hvx); + htp_unary_vtcm_layout_build(&L, octx->op, src0_data_row_size, dst_data_row_size, src1_data_row_size, src2_data_row_size, + src0_elem_size, dst_elem_size, src1_elem_size, src2_elem_size, + col_tile, kparams->block, broadcast_src1, src1_nrows, kparams->n_hvx); FARF(HIGH, "%s: (%ux%ux%ux%u) -> (%ux%ux%ux%u) : src0-vtcm-size %zu src1-vtcm-size %zu dst-vtcm-size %zu\n", op_type, src0->ne[0], src0->ne[1], src0->ne[2], src0->ne[3], dst->ne[0], dst->ne[1], dst->ne[2], dst->ne[3], @@ -1999,26 +3900,35 @@ static int execute_op_unary(struct htp_ops_context * octx) { .row_start = row_start, .data_src0 = src0->data, - .data_src1 = has_weight ? src1->data : 0, - .data_src2 = has_src2 ? octx->src[2]->data : 0, + .data_src1 = has_src1_mul ? src1->data : 0, + .data_src2 = has_src2_add ? src2->data : 0, .data_dst = dst->data, .src0_data_row_size = src0_data_row_size, .src1_data_row_size = src1_data_row_size, + .src2_data_row_size = src2_data_row_size, .dst_data_row_size = dst_data_row_size, .src0_row_size_aligned = L.src0_row_size_aligned, .src1_row_size_aligned = L.src1_row_size_aligned, + .src1_block_stride = (broadcast_src1 && src1_nrows <= 1) ? 0 : L.src1_row_size_aligned, + .src2_row_size_aligned = L.src2_row_size_aligned, .dst_row_size_aligned = L.dst_row_size_aligned, .src0_vtcm_half_size = L.src0_bytes >> 1, - .src1_vtcm_half_size = has_weight ? (L.src1_bytes >> (broadcast_weight ? 0 : 1)) : 0, + .src1_vtcm_half_size = has_src1_mul ? (L.src1_bytes >> ((broadcast_src1 && !col_tile) ? 0 : 1)) : 0, + .src2_vtcm_half_size = L.src2_bytes >> 1, .dst_vtcm_half_size = L.dst_bytes >> 1, .block = kparams->block, .nc = src0->ne[0], .col_tile = col_tile, - .broadcast_weight = broadcast_weight, + .src1_nrows = src1_nrows, + .broadcast_src1 = broadcast_src1, + .src0_f16 = is_f16, + .src1_f16 = has_src1_mul && (src1->type == HTP_TYPE_F16), + .src2_f16 = has_src2_add && (src2->type == HTP_TYPE_F16), + .dst_f16 = (dst->type == HTP_TYPE_F16), .vtcm_src0 = VTCM_LAYOUT_PTR(uint8_t, base, L.off_src0), .vtcm_src1 = VTCM_LAYOUT_PTR_OPTIONAL(uint8_t, base, L.off_src1, L.src1_bytes > 0), @@ -2033,96 +3943,98 @@ static int execute_op_unary(struct htp_ops_context * octx) { FARF(HIGH, "%s: %s mode (col_tile %u)\n", op_type, col_tile ? "tiled" : "row-block", col_tile); - work_queue_func_t task_func = NULL; + work_queue_func_t task_func = col_tile ? unary_thread_tiled : unary_thread_row_block; void * compute_func = NULL; - if (col_tile) { - task_func = unary_thread_tiled; - switch (octx->op) { - case HTP_OP_SCALE: compute_func = (void *) tile_scale_f32; break; - case HTP_OP_CLAMP: compute_func = (void *) tile_clamp_f32; break; - case HTP_OP_LEAKY_RELU: compute_func = (void *) tile_leaky_relu_f32; break; - case HTP_OP_SQR: compute_func = (void *) tile_sqr_f32; break; - case HTP_OP_SQRT: compute_func = (void *) tile_sqrt_f32; break; - case HTP_OP_UNARY_NEG: compute_func = (void *) tile_neg_f32; break; - case HTP_OP_UNARY_EXP: compute_func = (void *) tile_exp_f32; break; - case HTP_OP_UNARY_SIGMOID: compute_func = (void *) tile_sigmoid_f32; break; - case HTP_OP_UNARY_SILU: compute_func = (void *) tile_silu_f32; break; - case HTP_OP_UNARY_GELU: compute_func = (void *) tile_gelu_f32; break; - case HTP_OP_UNARY_GELU_QUICK: compute_func = (void *) tile_gelu_quick_f32; break; - case HTP_OP_UNARY_GELU_ERF: compute_func = (void *) tile_gelu_erf_f32; break; - case HTP_OP_UNARY_SOFTPLUS: compute_func = (void *) tile_softplus_f32; break; - case HTP_OP_UNARY_TANH: compute_func = (void *) tile_tanh_f32; break; - case HTP_OP_UNARY_ABS: compute_func = (void *) tile_abs_f32; break; - case HTP_OP_UNARY_LOG: compute_func = (void *) tile_log_f32; break; - case HTP_OP_UNARY_RELU: compute_func = (void *) tile_relu_f32; break; - case HTP_OP_UNARY_STEP: compute_func = (void *) tile_step_f32; break; - case HTP_OP_UNARY_CEIL: compute_func = (void *) tile_ceil_f32; break; - case HTP_OP_UNARY_SGN: compute_func = (void *) tile_sgn_f32; break; - case HTP_OP_TRI: - task_func = unary_thread_tiled_tri_f32; - compute_func = (void *) tri_apply_tile_f32; - break; - default: break; - } - } else if (is_f16) { - task_func = unary_thread_row_block; + switch (octx->op) { + case HTP_OP_RMS_NORM: + task_func = col_tile ? unary_thread_tiled_rms_norm : unary_thread_row_block; + compute_func = (void *) rms_norm_rows_table[is_f16][uctx.dst_f16]; + uctx.rms_tile_sum_sq_fn = is_f16 ? rms_norm_tile_sum_sq_f16 : rms_norm_tile_sum_sq_f32; + uctx.rms_apply_row_fn = rms_norm_apply_row_table[is_f16][uctx.dst_f16]; + break; + case HTP_OP_RMS_NORM_MUL: + task_func = col_tile ? unary_thread_tiled_rms_norm : (broadcast_src1 ? unary_thread_rms_norm_mul_bc : unary_thread_rms_norm_mul); + compute_func = (void *) rms_norm_mul_rows_table[is_f16][uctx.src1_f16][uctx.dst_f16]; + if (!col_tile && broadcast_src1 && uctx.src1_nrows == 1 && is_f16 && !uctx.src1_f16 && uctx.dst_f16) { + if (src0->ne[0] == 128) { + compute_func = (void *) rms_norm_mul_rows_f16_f32_f16_ne128_bc; + } else if (src0->ne[0] == 256) { + compute_func = (void *) rms_norm_mul_rows_f16_f32_f16_ne256_bc; + } + } + uctx.rms_tile_sum_sq_fn = is_f16 ? rms_norm_tile_sum_sq_f16 : rms_norm_tile_sum_sq_f32; + uctx.rms_apply_row_fn = rms_norm_mul_apply_row_table[is_f16][uctx.src1_f16][uctx.dst_f16]; + break; + case HTP_OP_RMS_NORM_MUL_ADD: + task_func = col_tile ? unary_thread_tiled_rms_norm : unary_thread_rms_norm_mul_add; + compute_func = (void *) rms_norm_mul_add_rows_table[is_f16][uctx.src1_f16][uctx.src2_f16][uctx.dst_f16]; + uctx.rms_tile_sum_sq_fn = is_f16 ? rms_norm_tile_sum_sq_f16 : rms_norm_tile_sum_sq_f32; + uctx.rms_apply_row_fn = rms_norm_mul_add_apply_row_table[is_f16][uctx.src1_f16][uctx.src2_f16][uctx.dst_f16]; + break; + default: + break; + } + + const bool has_scale_bias = (kparams->has_scale_bias != 0); + + if (!compute_func && is_f16) { switch (octx->op) { - case HTP_OP_NORM: compute_func = (void *) norm_f16; break; - case HTP_OP_RMS_NORM: compute_func = (void *) rms_norm_f16; break; - case HTP_OP_SCALE: compute_func = (void *) scale_f16; break; - case HTP_OP_CLAMP: compute_func = (void *) clamp_f16; break; - case HTP_OP_SQR: compute_func = (void *) sqr_f16; break; - case HTP_OP_SQRT: compute_func = (void *) sqrt_f16; break; - case HTP_OP_L2_NORM: compute_func = (void *) l2_norm_f16; break; - case HTP_OP_UNARY_ABS: compute_func = (void *) abs_f16; break; - case HTP_OP_UNARY_LOG: compute_func = (void *) log_f16; break; - case HTP_OP_UNARY_STEP: compute_func = (void *) step_f16; break; - case HTP_OP_UNARY_CEIL: compute_func = (void *) ceil_f16; break; - case HTP_OP_UNARY_SGN: compute_func = (void *) sgn_f16; break; - case HTP_OP_HADAMARD: compute_func = (void *) hadamard_f16; break; - default: break; + case HTP_OP_NORM: compute_func = (void *) norm_f16; break; + case HTP_OP_SCALE: compute_func = (void *) scale_f16; break; + case HTP_OP_CLAMP: compute_func = (void *) clamp_f16; break; + case HTP_OP_LEAKY_RELU: compute_func = (void *) leaky_relu_f16; break; + case HTP_OP_SQR: compute_func = (void *) sqr_f16; break; + case HTP_OP_SQRT: compute_func = (void *) sqrt_f16; break; + case HTP_OP_UNARY_NEG: compute_func = (void *) neg_f16; break; + case HTP_OP_UNARY_EXP: compute_func = (void *) (has_scale_bias ? exp_scale_bias_f16 : exp_f16); break; + case HTP_OP_UNARY_SIGMOID: compute_func = (void *) (has_scale_bias ? sigmoid_scale_bias_f16 : sigmoid_f16); break; + case HTP_OP_UNARY_SILU: compute_func = (void *) (has_scale_bias ? silu_scale_bias_f16 : silu_f16); break; + case HTP_OP_UNARY_GELU: compute_func = (void *) (has_scale_bias ? gelu_scale_bias_f16 : gelu_f16); break; + case HTP_OP_UNARY_GELU_QUICK: compute_func = (void *) (has_scale_bias ? gelu_quick_scale_bias_f16 : gelu_quick_f16); break; + case HTP_OP_UNARY_GELU_ERF: compute_func = (void *) (has_scale_bias ? gelu_erf_scale_bias_f16 : gelu_erf_f16); break; + case HTP_OP_UNARY_SOFTPLUS: compute_func = (void *) (has_scale_bias ? softplus_scale_bias_f16 : softplus_f16); break; + case HTP_OP_UNARY_TANH: compute_func = (void *) (has_scale_bias ? tanh_scale_bias_f16 : tanh_f16); break; + case HTP_OP_UNARY_ABS: compute_func = (void *) abs_f16; break; + case HTP_OP_UNARY_LOG: compute_func = (void *) log_f16; break; + case HTP_OP_UNARY_RELU: compute_func = (void *) relu_f16; break; + case HTP_OP_UNARY_STEP: compute_func = (void *) step_f16; break; + case HTP_OP_UNARY_CEIL: compute_func = (void *) ceil_f16; break; + case HTP_OP_UNARY_SGN: compute_func = (void *) sgn_f16; break; + case HTP_OP_L2_NORM: compute_func = (void *) l2_norm_f16; break; + case HTP_OP_HADAMARD: compute_func = (void *) hadamard_f16; break; + default: break; } - } else { - task_func = unary_thread_row_block; + } else if (!compute_func) { switch (octx->op) { - case HTP_OP_NORM: compute_func = (void *) norm_f32; break; - case HTP_OP_RMS_NORM: compute_func = (void *) rms_norm_f32; break; - case HTP_OP_RMS_NORM_MUL: - task_func = unary_thread_rms_norm_mul_f32; - compute_func = (void *) rms_norm_mul_f32; - break; - case HTP_OP_RMS_NORM_MUL_ADD: - task_func = unary_thread_rms_norm_mul_add_f32; - compute_func = (void *) rms_norm_mul_add_f32; - break; - case HTP_OP_SCALE: compute_func = (void *) scale_f32; break; - case HTP_OP_CLAMP: compute_func = (void *) clamp_f32; break; - case HTP_OP_LEAKY_RELU: compute_func = (void *) leaky_relu_f32; break; - case HTP_OP_SQR: compute_func = (void *) sqr_f32; break; - case HTP_OP_SQRT: compute_func = (void *) sqrt_f32; break; - case HTP_OP_UNARY_NEG: compute_func = (void *) neg_f32; break; - case HTP_OP_UNARY_EXP: compute_func = (void *) exp_f32; break; - case HTP_OP_UNARY_SIGMOID: compute_func = (void *) sigmoid_f32; break; - case HTP_OP_UNARY_SILU: compute_func = (void *) silu_f32; break; - case HTP_OP_UNARY_GELU: compute_func = (void *) gelu_f32; break; - case HTP_OP_UNARY_GELU_QUICK: compute_func = (void *) gelu_quick_f32; break; - case HTP_OP_UNARY_GELU_ERF: compute_func = (void *) gelu_erf_f32; break; - case HTP_OP_UNARY_SOFTPLUS: compute_func = (void *) softplus_f32; break; - case HTP_OP_UNARY_TANH: compute_func = (void *) tanh_f32; break; - case HTP_OP_UNARY_ABS: compute_func = (void *) abs_f32; break; - case HTP_OP_UNARY_LOG: compute_func = (void *) log_f32; break; - case HTP_OP_UNARY_RELU: compute_func = (void *) relu_f32; break; - case HTP_OP_UNARY_STEP: compute_func = (void *) step_f32; break; - case HTP_OP_UNARY_CEIL: compute_func = (void *) ceil_f32; break; - case HTP_OP_UNARY_SGN: compute_func = (void *) sgn_f32; break; - case HTP_OP_L2_NORM: compute_func = (void *) l2_norm_f32; break; - case HTP_OP_HADAMARD: compute_func = (void *) hadamard_f32; break; + case HTP_OP_NORM: compute_func = (void *) norm_f32; break; + case HTP_OP_SCALE: compute_func = (void *) scale_f32; break; + case HTP_OP_CLAMP: compute_func = (void *) clamp_f32; break; + case HTP_OP_LEAKY_RELU: compute_func = (void *) leaky_relu_f32; break; + case HTP_OP_SQR: compute_func = (void *) sqr_f32; break; + case HTP_OP_SQRT: compute_func = (void *) sqrt_f32; break; + case HTP_OP_UNARY_NEG: compute_func = (void *) neg_f32; break; + case HTP_OP_UNARY_EXP: compute_func = (void *) (has_scale_bias ? exp_scale_bias_f32 : exp_f32); break; + case HTP_OP_UNARY_SIGMOID: compute_func = (void *) (has_scale_bias ? sigmoid_scale_bias_f32 : sigmoid_f32); break; + case HTP_OP_UNARY_SILU: compute_func = (void *) (has_scale_bias ? silu_scale_bias_f32 : silu_f32); break; + case HTP_OP_UNARY_GELU: compute_func = (void *) (has_scale_bias ? gelu_scale_bias_f32 : gelu_f32); break; + case HTP_OP_UNARY_GELU_QUICK: compute_func = (void *) (has_scale_bias ? gelu_quick_scale_bias_f32 : gelu_quick_f32); break; + case HTP_OP_UNARY_GELU_ERF: compute_func = (void *) (has_scale_bias ? gelu_erf_scale_bias_f32 : gelu_erf_f32); break; + case HTP_OP_UNARY_SOFTPLUS: compute_func = (void *) (has_scale_bias ? softplus_scale_bias_f32 : softplus_f32); break; + case HTP_OP_UNARY_TANH: compute_func = (void *) (has_scale_bias ? tanh_scale_bias_f32 : tanh_f32); break; + case HTP_OP_UNARY_ABS: compute_func = (void *) abs_f32; break; + case HTP_OP_UNARY_LOG: compute_func = (void *) log_f32; break; + case HTP_OP_UNARY_RELU: compute_func = (void *) relu_f32; break; + case HTP_OP_UNARY_STEP: compute_func = (void *) step_f32; break; + case HTP_OP_UNARY_CEIL: compute_func = (void *) ceil_f32; break; + case HTP_OP_UNARY_SGN: compute_func = (void *) sgn_f32; break; + case HTP_OP_L2_NORM: compute_func = (void *) l2_norm_f32; break; + case HTP_OP_HADAMARD: compute_func = (void *) hadamard_f32; break; case HTP_OP_TRI: - task_func = unary_thread_tri_f32; - compute_func = (void *) tri_f32; + task_func = col_tile ? unary_thread_tiled_tri_f32 : unary_thread_tri_f32; + compute_func = col_tile ? (void *) tri_apply_tile_f32 : (void *) tri_f32; break; - default: break; + default: break; } } diff --git a/ggml/src/ggml-hexagon/htp/unary-ops.h b/ggml/src/ggml-hexagon/htp/unary-ops.h index e03b2ac73fac..da11e3d769ea 100644 --- a/ggml/src/ggml-hexagon/htp/unary-ops.h +++ b/ggml/src/ggml-hexagon/htp/unary-ops.h @@ -11,14 +11,21 @@ struct htp_unary_kernel_params { uint32_t n_hvx; uint32_t col_tile; uint32_t block; - uint32_t broadcast_weight; + uint32_t broadcast_src1; uint32_t src0_contig; uint32_t src1_contig; + uint32_t src0_slice_dma; uint32_t vtcm_size; uint32_t tiles_per_row; + uint32_t has_scale_bias; + float in_scale; + float in_bias; + float out_scale; + float out_bias; + // Fastdiv helpers struct fastdiv_values div_ne01; struct fastdiv_values div_ne02; @@ -94,6 +101,7 @@ struct htp_unary_vtcm_layout { size_t src0_row_size_aligned; size_t src1_row_size_aligned; + size_t src2_row_size_aligned; size_t dst_row_size_aligned; size_t src0_bytes; @@ -108,30 +116,36 @@ static inline void htp_unary_vtcm_layout_build( size_t src0_data_row_size, size_t dst_data_row_size, size_t src1_data_row_size, - size_t elem_size, + size_t src2_data_row_size, + size_t src0_elem_size, + size_t dst_elem_size, + size_t src1_elem_size, + size_t src2_elem_size, uint32_t col_tile, uint32_t block, - bool broadcast_weight, + bool broadcast_src1, + uint32_t src1_nrows, uint32_t n_hvx ) { - const bool has_weight = (op == HTP_OP_RMS_NORM_MUL || op == HTP_OP_RMS_NORM_MUL_ADD); + const bool has_src1_mul = (op == HTP_OP_RMS_NORM_MUL || op == HTP_OP_RMS_NORM_MUL_ADD); + const bool has_src2_add = (op == HTP_OP_RMS_NORM_MUL_ADD); L->src0_row_size_aligned = hex_round_up(src0_data_row_size, 128); L->dst_row_size_aligned = hex_round_up(dst_data_row_size, 128); - L->src1_row_size_aligned = has_weight ? hex_round_up(src1_data_row_size, 128) : 0; + L->src1_row_size_aligned = has_src1_mul ? hex_round_up(src1_data_row_size, 128) : 0; + L->src2_row_size_aligned = has_src2_add ? hex_round_up(src2_data_row_size, 128) : 0; if (col_tile > 0) { - const size_t col_tile_bytes = col_tile * elem_size; - L->src0_bytes = col_tile_bytes * 2; - L->dst_bytes = col_tile_bytes * 2; - L->src1_bytes = 0; - L->src2_bytes = 0; + L->src0_bytes = (size_t) col_tile * src0_elem_size * 2; + L->dst_bytes = (size_t) col_tile * dst_elem_size * 2; + L->src1_bytes = has_src1_mul ? ((size_t) col_tile * src1_elem_size * 2) : 0; + L->src2_bytes = has_src2_add ? ((size_t) col_tile * src2_elem_size * 2) : 0; } else { L->src0_bytes = L->src0_row_size_aligned * block * 2; - L->src2_bytes = (op == HTP_OP_RMS_NORM_MUL_ADD) ? L->src0_bytes : 0; + L->src2_bytes = has_src2_add ? (L->src2_row_size_aligned * block * 2) : 0; L->dst_bytes = L->dst_row_size_aligned * block * 2; - if (has_weight) { - L->src1_bytes = broadcast_weight ? L->src1_row_size_aligned : (L->src1_row_size_aligned * block * 2); + if (has_src1_mul) { + L->src1_bytes = broadcast_src1 ? (L->src1_row_size_aligned * src1_nrows) : (L->src1_row_size_aligned * block * 2); } else { L->src1_bytes = 0; } @@ -152,36 +166,43 @@ static inline void htp_unary_solve_layout( uint32_t ne10, uint32_t ne11, uint32_t max_block, - bool broadcast_weight, + bool broadcast_src1, + uint32_t src1_nrows, uint32_t n_hvx, size_t vtcm_size, - size_t elem_size, + size_t src0_elem_size, + size_t dst_elem_size, + size_t src1_elem_size, + size_t src2_elem_size, uint32_t * out_col_tile, uint32_t * out_vtcm_row_per_hvx ) { - const bool has_weight = (op == HTP_OP_RMS_NORM_MUL || op == HTP_OP_RMS_NORM_MUL_ADD); + const bool has_src1_mul = (op == HTP_OP_RMS_NORM_MUL || op == HTP_OP_RMS_NORM_MUL_ADD); + const bool has_src2_add = (op == HTP_OP_RMS_NORM_MUL_ADD); - const size_t dst_elem_size = (op == HTP_OP_HADAMARD) ? sizeof(float) : elem_size; - const size_t src0_data_row_size = ne00 * elem_size; - const size_t dst_data_row_size = ne10 * dst_elem_size; - const size_t src1_data_row_size = has_weight ? (ne11 * sizeof(float)) : 0; + const size_t eff_dst_elem_size = (op == HTP_OP_HADAMARD) ? sizeof(float) : dst_elem_size; + const size_t src0_data_row_size = ne00 * src0_elem_size; + const size_t dst_data_row_size = ne10 * eff_dst_elem_size; + const size_t src1_data_row_size = has_src1_mul ? (ne11 * src1_elem_size) : 0; + const size_t src2_data_row_size = has_src2_add ? (ne00 * src2_elem_size) : 0; const size_t src0_row_size_aligned = hex_round_up(src0_data_row_size, 128); const size_t dst_row_size_aligned = hex_round_up(dst_data_row_size, 128); - const size_t src1_row_size_aligned = has_weight ? hex_round_up(src1_data_row_size, 128) : 0; + const size_t src1_row_size_aligned = has_src1_mul ? hex_round_up(src1_data_row_size, 128) : 0; + const size_t src2_row_size_aligned = has_src2_add ? hex_round_up(src2_data_row_size, 128) : 0; size_t vtcm_size_per_row = 0; size_t vtcm_row_per_hvx = 0; if (op == HTP_OP_RMS_NORM_MUL_ADD) { - size_t src1_vtcm_total = n_hvx * src1_row_size_aligned; + size_t src1_vtcm_total = n_hvx * src1_row_size_aligned * src1_nrows; size_t available_vtcm = (vtcm_size > src1_vtcm_total) ? (vtcm_size - src1_vtcm_total) : 0; - vtcm_size_per_row = 2 * (2 * src0_row_size_aligned + dst_row_size_aligned); + vtcm_size_per_row = 2 * (src0_row_size_aligned + src2_row_size_aligned + dst_row_size_aligned); vtcm_row_per_hvx = available_vtcm / (n_hvx * vtcm_size_per_row); } else if (op == HTP_OP_RMS_NORM_MUL) { - if (broadcast_weight) { + if (broadcast_src1) { size_t available_vtcm = vtcm_size; - size_t src1_vtcm_total = n_hvx * src1_row_size_aligned; + size_t src1_vtcm_total = n_hvx * src1_row_size_aligned * src1_nrows; if (available_vtcm > src1_vtcm_total) { available_vtcm -= src1_vtcm_total; } else { @@ -202,27 +223,22 @@ static inline void htp_unary_solve_layout( vtcm_row_per_hvx = max_block; } - const bool is_reduction = (op == HTP_OP_NORM || op == HTP_OP_RMS_NORM || - op == HTP_OP_RMS_NORM_MUL || op == HTP_OP_RMS_NORM_MUL_ADD || - op == HTP_OP_L2_NORM || op == HTP_OP_HADAMARD); - // The tiled fallback path below only has F32 task functions (unary_task_f32_tiled_*); - // F16 has no tiled kernels, so it must stay on the row-block path like reduction ops. - // NOTE: if F16 ends up with vtcm_row_per_hvx == 0 here (row too large for the VTCM - // budget), execute_op_unary() will see BLOCK == 0 and skip computation for that op - // (logged via FARF(ERROR, ...)) since there is no F16 tiled fallback. This is a known - // limitation; supporting it would require adding F16 tiled kernels. - const bool is_f16 = (elem_size == sizeof(_Float16)); + const bool is_rms_norm = (op == HTP_OP_RMS_NORM || op == HTP_OP_RMS_NORM_MUL || op == HTP_OP_RMS_NORM_MUL_ADD); + const bool is_reduction = (op == HTP_OP_NORM || is_rms_norm || op == HTP_OP_L2_NORM || op == HTP_OP_HADAMARD); uint32_t col_tile = 0; - if (vtcm_row_per_hvx == 0 && !is_reduction && !is_f16) { + if (vtcm_row_per_hvx == 0 && (!is_reduction || is_rms_norm)) { const size_t per_hvx_budget = vtcm_size / n_hvx; - const size_t col_tile_bytes = hex_align_down(per_hvx_budget / 4, 128); - col_tile = (uint32_t) (col_tile_bytes / elem_size); + const size_t tile_elem_bytes = 2 * (src0_elem_size + eff_dst_elem_size + + (has_src1_mul ? src1_elem_size : 0) + + (has_src2_add ? src2_elem_size : 0)); + col_tile = (uint32_t) hex_align_down(per_hvx_budget / tile_elem_bytes, 64); } const uint32_t block = col_tile ? 0 : (uint32_t) vtcm_row_per_hvx; - htp_unary_vtcm_layout_build(L, op, src0_data_row_size, dst_data_row_size, src1_data_row_size, - elem_size, col_tile, block, broadcast_weight, n_hvx); + htp_unary_vtcm_layout_build(L, op, src0_data_row_size, dst_data_row_size, src1_data_row_size, src2_data_row_size, + src0_elem_size, eff_dst_elem_size, src1_elem_size, src2_elem_size, + col_tile, block, broadcast_src1, src1_nrows, n_hvx); *out_col_tile = col_tile; *out_vtcm_row_per_hvx = (uint32_t) vtcm_row_per_hvx; diff --git a/ggml/src/ggml-hexagon/htp/upscale-ops.c b/ggml/src/ggml-hexagon/htp/upscale-ops.c index 59ab7914ad62..fe68a70d7c0e 100644 --- a/ggml/src/ggml-hexagon/htp/upscale-ops.c +++ b/ggml/src/ggml-hexagon/htp/upscale-ops.c @@ -1,11 +1,10 @@ -#pragma clang diagnostic ignored "-Wunused-variable" - #include #include #include #include "hex-common.h" #include "dma-queue.h" +#include "dma-pipeline.h" #include "htp-trace.h" #include "htp-ctx.h" #include "htp-ops.h" @@ -756,7 +755,64 @@ static inline void dma_push_src_chunk( } } -static void upscale_worker(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { +struct upscale_pipe_state { + struct upscale_context * ctx; + const struct htp_upscale_kernel_params * p; + const struct htp_tensor * src0; + const struct htp_tensor * dst; + const void * lut_y; + float * R_buf; + float * gather_tmp; + uint32_t dst_row_size; + uint32_t dst_stride; + uint32_t chunk; + uint32_t chunk_end; +}; + +static bool upscale_next_task(void * ctx, struct dma_pipe_task * task) { + struct upscale_pipe_state * s = (struct upscale_pipe_state *) ctx; + if (s->chunk >= s->chunk_end) { + return false; + } + task->row = s->chunk++; + task->off = 0; + task->len = 0; + task->aux = 0; + return true; +} + +static void upscale_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct upscale_pipe_state * s = (struct upscale_pipe_state *) ctx; + dma_addr_t slice_src_off; + uint32_t src_ys, src_yc; + resolve_src_slice(s->src0, s->dst, s->p, s->lut_y, task->row, &slice_src_off, &src_ys, &src_yc); + dma_push_src_chunk(dma_q, (float *) in_spad, s->src0, slice_src_off, src_ys, src_yc); +} + +static void upscale_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + struct upscale_pipe_state * s = (struct upscale_pipe_state *) ctx; + dma_addr_t slice_dst_off; + uint32_t dst_ys, dst_yc; + resolve_dst_slice(s->dst, s->p, task->row, &slice_dst_off, &dst_ys, &dst_yc); + + uint32_t src_ys, src_yc; + get_src_y_window(s->src0, s->dst, s->p, s->lut_y, dst_ys, dst_yc, &src_ys, &src_yc); + + s->ctx->compute_chunk(s->ctx, (const float *) in_spad, (float *) out_spad, s->R_buf, s->gather_tmp, dst_ys, dst_yc, src_ys); +} + +static void upscale_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) { + struct upscale_pipe_state * s = (struct upscale_pipe_state *) ctx; + dma_addr_t slice_dst_off; + uint32_t dst_ys, dst_yc; + resolve_dst_slice(s->dst, s->p, task->row, &slice_dst_off, &dst_ys, &dst_yc); + + const dma_addr_t dst_addr = s->dst->data + slice_dst_off + (dma_addr_t) dst_ys * s->dst_stride; + dma_queue_push(dma_q, dma_make_data(dst_addr, out_spad), s->dst_stride, s->dst_row_size, s->dst_row_size, dst_yc); +} + +static void upscale_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + (void) nth; struct upscale_context * ctx = (struct upscale_context *) data; const struct htp_upscale_kernel_params * p = ctx->kparams; const struct htp_upscale_vtcm_layout * L = &ctx->layout; @@ -770,74 +826,31 @@ static void upscale_worker(const htp_thread_t * th, unsigned int nth, unsigned i return; } - 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; uint8_t * vtcm_base = (uint8_t *) ctx->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 * R_buf = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_r) + ith * (L->r_bytes_per_hvx / sizeof(float)); - float * gather_tmp = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_gather) + ith * (L->gather_bytes_per_hvx / sizeof(float)); - const void * lut_y = ctx->lut_y; - - float * srcb2[2] = { (float *) src_spad, (float *) (src_spad + src_spad_half) }; - float * dstb2[2] = { (float *) dst_spad, (float *) (dst_spad + dst_spad_half) }; - - const uint32_t dst_row_size = dst->ne[0] * sizeof(float); - const uint32_t dst_stride = dst->nb[1]; - - const uint32_t total = last - first; - - // Warmup: prime pipeline with initial transfers - for (uint32_t i = 0; i < total && i < 2; ++i) { - dma_queue_push(dma_q, dma_make_data(dst->data, dstb2[i]), dst_stride, dst_row_size, dst_row_size, 0); - - dma_addr_t slice_src_off; - uint32_t src_ys, src_yc; - resolve_src_slice(src0, dst, p, lut_y, first + i, &slice_src_off, &src_ys, &src_yc); - - dma_push_src_chunk(dma_q, srcb2[i], src0, slice_src_off, src_ys, src_yc); - } - - // Steady state loop - for (uint32_t i = 0; i < total; ++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); - - dma_addr_t slice_dst_off; - uint32_t dst_ys, dst_yc; - resolve_dst_slice(dst, p, first + i, &slice_dst_off, &dst_ys, &dst_yc); - - uint32_t src_ys, src_yc; - get_src_y_window(src0, dst, p, lut_y, dst_ys, dst_yc, &src_ys, &src_yc); - - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) (first + i)); - ctx->compute_chunk(ctx, srcb, dstb, R_buf, gather_tmp, dst_ys, dst_yc, src_ys); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) (first + i)); - - const dma_addr_t dst_addr = dst->data + slice_dst_off + (dma_addr_t) dst_ys * dst_stride; - dma_queue_push(dma_q, dma_make_data(dst_addr, dstb), dst_stride, dst_row_size, dst_row_size, dst_yc); - - const uint32_t next = i + 2; - if (next < total) { - dma_addr_t next_src_off; - uint32_t next_src_ys, next_src_yc; - resolve_src_slice(src0, dst, p, lut_y, first + next, &next_src_off, &next_src_ys, &next_src_yc); - - dma_push_src_chunk(dma_q, srcb, src0, next_src_off, next_src_ys, next_src_yc); - } - } - - dma_queue_flush(dma_q); + void * in_buf[2] = { src_spad, src_spad + src_spad_half }; + void * out_buf[2] = { dst_spad, dst_spad + dst_spad_half }; + + struct upscale_pipe_state s = { + .ctx = ctx, + .p = p, + .src0 = src0, + .dst = dst, + .lut_y = ctx->lut_y, + .R_buf = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_r) + ith * (L->r_bytes_per_hvx / sizeof(float)), + .gather_tmp = VTCM_LAYOUT_PTR(float, vtcm_base, L->off_gather) + ith * (L->gather_bytes_per_hvx / sizeof(float)), + .dst_row_size = dst->ne[0] * sizeof(float), + .dst_stride = dst->nb[1], + .chunk = first, + .chunk_end = last, + }; - (void) nth; + dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, + upscale_next_task, upscale_push_in, upscale_compute, upscale_push_out); } int op_upscale(struct htp_ops_context * octx) { @@ -856,7 +869,7 @@ int op_upscale(struct htp_ops_context * octx) { if (octx->ctx->mdev.count > 1) { const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( - chunk_count, htp_tensor_mdev_data_aligned(dst) ? p->chunks_per_group : 0, + chunk_count, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); chunk_start = range.start; chunk_count = range.count; @@ -952,7 +965,7 @@ int op_upscale(struct htp_ops_context * octx) { htp_upscale_vtcm_layout_build(&ctx.layout, src_x, src_y, dst_x, dst_y, p->dst_nrows_per_chunk, p->inv_sf1, p->filter_radius1, n_hvx); - work_queue_run(octx->ctx->hvx_queue, upscale_worker, &ctx, n_hvx); + work_queue_run(octx->ctx->hvx_queue, upscale_thread, &ctx, n_hvx); return HTP_STATUS_OK; } diff --git a/ggml/src/ggml-hexagon/htp/upscale-ops.h b/ggml/src/ggml-hexagon/htp/upscale-ops.h index 592bf7f000a8..b98d6cadb43f 100644 --- a/ggml/src/ggml-hexagon/htp/upscale-ops.h +++ b/ggml/src/ggml-hexagon/htp/upscale-ops.h @@ -44,7 +44,6 @@ struct htp_upscale_kernel_params { float invscale1; uint32_t n_hvx; - uint32_t chunks_per_group; uint32_t dst_nrows_per_chunk; uint32_t chunks_per_slice; diff --git a/ggml/src/ggml-hexagon/htp/work-queue.c b/ggml/src/ggml-hexagon/htp/work-queue.c index 5d274274a5e7..9839e10239bf 100644 --- a/ggml/src/ggml-hexagon/htp/work-queue.c +++ b/ggml/src/ggml-hexagon/htp/work-queue.c @@ -14,38 +14,30 @@ #define LOWEST_USABLE_QURT_PRIO (254) -// internal structure kept in thread-local storage per instance of work queue typedef struct { htp_thread_t th; work_queue_t queue; } worker_context_t; -struct work_queue_task_s { +struct work_queue_s { + // Hot dispatch state: written by main thread, read by workers + // seqn encodes (counter << 8) | (n_threads & 0xff) work_queue_func_t func; void * data; + atomic_uint seqn; + atomic_uint active; + atomic_bool killed; + + // Completion barrier: decremented by all workers on every seqn + atomic_uint barrier __attribute__((aligned(HEX_L2_LINE_SIZE))); + + // Cold metadata + uint32_t last_seqn; + qurt_thread_t thread[HTP_MAX_NTHREADS]; + worker_context_t context[HTP_MAX_NTHREADS]; + void * stack[HTP_MAX_NTHREADS]; unsigned int n_threads; - atomic_uint barrier; -}; - -// internal structure kept in thread-local storage per instance of work queue -struct work_queue_s { - atomic_uint seqn; // seqno used to detect new jobs - atomic_uint idx_read; // Updated by producer (pop/reclaim) - atomic_uint idx_write; // Updated by producer (push) - uint32_t idx_mask; - uint32_t capacity; - - qurt_thread_t thread[HTP_MAX_NTHREADS]; // thread ID's of the workers - worker_context_t context[HTP_MAX_NTHREADS]; // worker contexts (0 = main, 1..n_workers = workers) - void * stack[HTP_MAX_NTHREADS]; // thread stack pointers - unsigned int n_threads; // total threads (workers + main) - unsigned int n_workers; // number of active threads (just workers) - - atomic_uint active; // workers are polling/active - atomic_bool killed; // threads need to exit - bool external_mem; // memory owned externally - - struct work_queue_task_s queue[] __attribute__((aligned(HEX_L2_LINE_SIZE))); + unsigned int n_workers; }; static void work_queue_thread(void * context) { @@ -57,7 +49,7 @@ static void work_queue_thread(void * context) { unsigned int prev_seqn = 0; - while (!atomic_load_explicit(&q->killed, memory_order_relaxed)) { + while (!atomic_load_explicit(&q->killed, memory_order_acquire)) { unsigned int seqn = atomic_load_explicit(&q->seqn, memory_order_acquire); if (seqn == prev_seqn) { if (atomic_load_explicit(&q->active, memory_order_relaxed)) { @@ -71,34 +63,24 @@ static void work_queue_thread(void * context) { prev_seqn = seqn; - // Process all active tasks in the queue - unsigned int ir = atomic_load_explicit(&q->idx_read, memory_order_relaxed); - unsigned int iw = atomic_load_explicit(&q->idx_write, memory_order_relaxed); - - while (ir != iw) { - struct work_queue_task_s * task = &q->queue[ir]; - - unsigned int n = task->n_threads; - if (id < n) { - task->func(&me->th, n, id, task->data); - - atomic_fetch_sub_explicit(&task->barrier, 1, memory_order_release); - } else { - while (atomic_load_explicit(&task->barrier, memory_order_relaxed) > 0) { - hex_pause(); - } - } - - ir = (ir + 1) & q->idx_mask; + unsigned int n = seqn & 0xffu; + if (id < n) { + q->func(&me->th, n, id, q->data); } + + atomic_fetch_sub_explicit(&q->barrier, 1, memory_order_release); } FARF(HIGH, "work-queue: thread %u (tid %u) stopped", id, me->th.tid); } bool work_queue_run(work_queue_t q, work_queue_func_t func, void * data, unsigned int n) { - if (n <= 1) { - func(&q->context[0].th, n, 0, data); + if (n == 0) { + return true; + } + + if (n == 1) { + func(&q->context[0].th, 1, 0, data); return true; } @@ -107,46 +89,33 @@ bool work_queue_run(work_queue_t q, work_queue_func_t func, void * data, unsigne return false; } - unsigned int ir = atomic_load_explicit(&q->idx_read, memory_order_relaxed); - unsigned int iw = atomic_load_explicit(&q->idx_write, memory_order_relaxed); - - if (((iw + 1) & q->idx_mask) == ir) { - FARF(ERROR, "work-queue-push: queue is full\n"); - return false; + if (!atomic_load_explicit(&q->active, memory_order_relaxed)) { + work_queue_wakeup(q); } - struct work_queue_task_s * task = &q->queue[iw]; - task->func = func; - task->data = data; - task->n_threads = n; - atomic_store_explicit(&task->barrier, n, memory_order_relaxed); - - atomic_store_explicit(&q->idx_write, (iw + 1) & q->idx_mask, memory_order_relaxed); + q->func = func; + q->data = data; + atomic_store_explicit(&q->barrier, q->n_workers, memory_order_relaxed); - // publish job to workers (already awake and polling) - atomic_fetch_add_explicit(&q->seqn, 1, memory_order_release); + // publish job to all workers (every worker decrements barrier before returning) + atomic_store_explicit(&q->seqn, (++q->last_seqn << 8) | (n & 0xffu), memory_order_release); // main thread runs job #0 func(&q->context[0].th, n, 0, data); - atomic_fetch_sub_explicit(&task->barrier, 1, memory_order_release); - - while (atomic_load_explicit(&task->barrier, memory_order_relaxed) > 0) { + while (atomic_load_explicit(&q->barrier, memory_order_relaxed) > 0) { hex_pause(); } atomic_thread_fence(memory_order_acquire); - atomic_store_explicit(&q->idx_read, (ir + 1) & q->idx_mask, memory_order_relaxed); - return true; } -size_t work_queue_sizeof(uint32_t n_threads, uint32_t capacity, uint32_t stack_size) { - capacity = hex_ceil_pow2(capacity); - uint32_t n_workers = n_threads > 1 ? n_threads - 1 : 0; - size_t size_stacks = stack_size * n_workers; - size_t size_q = hex_align_up(sizeof(struct work_queue_s) + capacity * sizeof(struct work_queue_task_s), HEX_L2_LINE_SIZE); +size_t work_queue_sizeof(uint32_t n_threads, uint32_t stack_size) { + uint32_t n_workers = n_threads > 1 ? n_threads - 1 : 0; + size_t size_stacks = hex_align_up((size_t) stack_size * n_workers, HEX_L2_LINE_SIZE); + size_t size_q = hex_align_up(sizeof(struct work_queue_s), HEX_L2_LINE_SIZE); return size_stacks + size_q; } @@ -154,18 +123,22 @@ size_t work_queue_alignof(void) { return 4096; } -work_queue_t work_queue_init(void * ptr, uint32_t n_threads, uint32_t capacity, uint32_t stack_size, dma_queue_t * dma, struct htp_thread_trace * trace) { - capacity = hex_ceil_pow2(capacity); - uint32_t n_workers = n_threads > 1 ? n_threads - 1 : 0; - unsigned char * mem_blob = (unsigned char *) ptr; +work_queue_t work_queue_init(void * ptr, uint32_t n_threads, uint32_t stack_size, dma_queue_t * dma, struct htp_thread_trace * trace) { + if (n_threads == 0 || n_threads > HTP_MAX_NTHREADS) { + FARF(ERROR, "work-queue: invalid n_threads %u (max %u)", n_threads, HTP_MAX_NTHREADS); + return NULL; + } + + uint32_t n_workers = n_threads > 1 ? n_threads - 1 : 0; + size_t size_stacks = hex_align_up((size_t) stack_size * n_workers, HEX_L2_LINE_SIZE); + unsigned char * mem_blob = (unsigned char *) ptr; - work_queue_t q = (work_queue_t) (mem_blob + stack_size * n_workers); - memset(q, 0, sizeof(struct work_queue_s) + capacity * sizeof(struct work_queue_task_s)); + work_queue_t q = (work_queue_t) (mem_blob + size_stacks); + memset(q, 0, sizeof(struct work_queue_s)); q->n_threads = n_threads; q->n_workers = n_workers; - q->external_mem = true; - q->capacity = capacity; + q->last_seqn = 0; for (unsigned int i = 0; i < n_threads; i++) { htp_thread_init(&q->context[i].th, dma, trace); @@ -173,22 +146,15 @@ work_queue_t work_queue_init(void * ptr, uint32_t n_threads, uint32_t capacity, } for (unsigned int i = 0; i < n_workers; i++) { - q->stack[i] = mem_blob; mem_blob += stack_size; + q->stack[i] = mem_blob; + mem_blob += stack_size; q->thread[i] = 0; } - atomic_init(&q->idx_read, 0); - atomic_init(&q->idx_write, 0); - atomic_init(&q->seqn, 0); - atomic_init(&q->active, 0); - q->idx_mask = capacity - 1; - q->killed = 0; - for (int i = 0; i < (int) capacity; i++) { - atomic_init(&q->queue[i].barrier, 0); - q->queue[i].func = NULL; - q->queue[i].data = NULL; - q->queue[i].n_threads = 0; - } + atomic_init(&q->seqn, 0); + atomic_init(&q->active, 0); + atomic_init(&q->killed, false); + atomic_init(&q->barrier, 0); // launch the workers qurt_thread_attr_t attr; @@ -225,12 +191,15 @@ work_queue_t work_queue_init(void * ptr, uint32_t n_threads, uint32_t capacity, } void work_queue_free(work_queue_t q) { - if (!q) { return; } + if (!q) { + return; + } - atomic_store_explicit(&q->killed, 1, memory_order_relaxed); - atomic_store_explicit(&q->active, 1, memory_order_release); - atomic_fetch_add_explicit(&q->seqn, 1, memory_order_release); - qurt_futex_wake(&q->active, q->n_workers); + atomic_store_explicit(&q->killed, true, memory_order_release); + atomic_store_explicit(&q->active, 1, memory_order_release); + if (q->n_workers > 0) { + qurt_futex_wake(&q->active, q->n_workers); + } for (unsigned int i = 0; i < q->n_workers; i++) { if (q->thread[i]) { @@ -243,7 +212,9 @@ void work_queue_free(work_queue_t q) { void work_queue_wakeup(work_queue_t q) { if (!atomic_load_explicit(&q->active, memory_order_relaxed)) { atomic_store_explicit(&q->active, 1, memory_order_release); - qurt_futex_wake(&q->active, q->n_workers); + if (q->n_workers > 0) { + qurt_futex_wake(&q->active, q->n_workers); + } } } diff --git a/ggml/src/ggml-hexagon/htp/work-queue.h b/ggml/src/ggml-hexagon/htp/work-queue.h index 446b72c46026..bc5e4a3d6bd3 100644 --- a/ggml/src/ggml-hexagon/htp/work-queue.h +++ b/ggml/src/ggml-hexagon/htp/work-queue.h @@ -12,9 +12,9 @@ typedef void (*work_queue_func_t)(const htp_thread_t * th, unsigned int n, unsig struct work_queue_s; typedef struct work_queue_s * work_queue_t; -size_t work_queue_sizeof(uint32_t n_threads, uint32_t capacity, uint32_t stack_size); +size_t work_queue_sizeof(uint32_t n_threads, uint32_t stack_size); size_t work_queue_alignof(void); -work_queue_t work_queue_init(void * ptr, uint32_t n_threads, uint32_t capacity, uint32_t stack_size, dma_queue_t * dma, struct htp_thread_trace * trace); +work_queue_t work_queue_init(void * ptr, uint32_t n_threads, uint32_t stack_size, dma_queue_t * dma, struct htp_thread_trace * trace); void work_queue_free(work_queue_t q); void work_queue_wakeup(work_queue_t q); diff --git a/ggml/src/ggml-hip/CMakeLists.txt b/ggml/src/ggml-hip/CMakeLists.txt index 35a898e23091..7d9b71d1cb1c 100644 --- a/ggml/src/ggml-hip/CMakeLists.txt +++ b/ggml/src/ggml-hip/CMakeLists.txt @@ -61,16 +61,12 @@ file(GLOB GGML_HEADERS_ROCM "../ggml-cuda/*.cuh") list(APPEND GGML_HEADERS_ROCM "../../include/ggml-cuda.h") file(GLOB GGML_SOURCES_ROCM "../ggml-cuda/*.cu") -file(GLOB SRCS "../ggml-cuda/template-instances/fattn-tile*.cu") -list(APPEND GGML_SOURCES_ROCM ${SRCS}) -file(GLOB SRCS "../ggml-cuda/template-instances/fattn-mma*.cu") -list(APPEND GGML_SOURCES_ROCM ${SRCS}) file(GLOB SRCS "../ggml-cuda/template-instances/mmq*.cu") list(APPEND GGML_SOURCES_ROCM ${SRCS}) file(GLOB SRCS "../ggml-cuda/template-instances/mmf*.cu") list(APPEND GGML_SOURCES_ROCM ${SRCS}) -ggml_cuda_fattn_vec_instances(${CMAKE_CURRENT_SOURCE_DIR}/../ggml-cuda SRCS) +ggml_cuda_fattn_instances(${CMAKE_CURRENT_SOURCE_DIR}/../ggml-cuda SRCS) list(APPEND GGML_SOURCES_ROCM ${SRCS}) ggml_add_backend_library(ggml-hip diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp index c4e6ded8b721..47a1b7c07837 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.cpp +++ b/ggml/src/ggml-metal/ggml-metal-device.cpp @@ -1067,8 +1067,8 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mv(ggml_meta { if (ne00 < 32) { nsg = 1; - nr0 = 32; - nr1 = 1; + nr0 = std::min(ne01, 32); + nr1 = 32/nr0; suffix = "_short"; } else { nsg = std::min(4, (ne00 + 127) / 128); diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index da2f0acee316..f7f05b6bbcbf 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1536,6 +1536,11 @@ static bool ggml_metal_supports_mul_mat_op( return false; } + // BF16 src1 kernels: mul_mv for F32 and BF16 src0, mul_mm for BF16 src0 + if (op->src[1]->type == GGML_TYPE_BF16) { + return op->op == GGML_OP_MUL_MAT && (op->src[0]->type == GGML_TYPE_BF16 || (op->src[0]->type == GGML_TYPE_F32 && !mm_path)); + } + if (op->src[1]->type != GGML_TYPE_F16) { return true; } diff --git a/ggml/src/ggml-metal/ggml-metal.cpp b/ggml/src/ggml-metal/ggml-metal.cpp index 7aee237cc123..bcd70c797f54 100644 --- a/ggml/src/ggml-metal/ggml-metal.cpp +++ b/ggml/src/ggml-metal/ggml-metal.cpp @@ -9,8 +9,6 @@ #include "ggml-metal-ops.h" #include "ggml-metal-tuning.h" -#include - #include #include @@ -655,13 +653,6 @@ 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)); @@ -713,7 +704,7 @@ ggml_backend_t ggml_backend_metal_init(void) { /* .context = */ ctx, }; - ggml_backend_metal_set_n_cb(backend, GGML_METAL_DEFAULT_N_CB); + ggml_backend_metal_set_n_cb(backend, 1); return backend; } @@ -809,7 +800,7 @@ static ggml_backend_t ggml_backend_metal_device_init_backend(ggml_backend_dev_t /* .context = */ ctx, }; - ggml_backend_metal_set_n_cb(backend, GGML_METAL_DEFAULT_N_CB); + ggml_backend_metal_set_n_cb(backend, 1); return backend; diff --git a/ggml/src/ggml-metal/kernels/mul_mv.metal b/ggml/src/ggml-metal/kernels/mul_mv.metal index 1d6123f42e97..08873502e4db 100644 --- a/ggml/src/ggml-metal/kernels/mul_mv.metal +++ b/ggml/src/ggml-metal/kernels/mul_mv.metal @@ -1187,11 +1187,14 @@ void kernel_mul_mv_t_t_short_impl( device char * dst, uint3 tgpig, ushort tiisg) { - const int r0 = tgpig.x*32 + tiisg; - const int r1 = tgpig.y; + const int n0 = args.nr0; + const int n1 = 32/n0; + + const int r0 = tgpig.x*n0 + tiisg%n0; + const int r1 = tgpig.y*n1 + tiisg/n0; const int im = tgpig.z; - if (r0 >= args.ne01) { + if (tiisg >= n0*n1 || r0 >= args.ne01 || r1 >= args.ne11) { return; } diff --git a/ggml/src/ggml-musa/CMakeLists.txt b/ggml/src/ggml-musa/CMakeLists.txt index 721621a1d815..c48fb8106a81 100644 --- a/ggml/src/ggml-musa/CMakeLists.txt +++ b/ggml/src/ggml-musa/CMakeLists.txt @@ -33,10 +33,6 @@ if (MUSAToolkit_FOUND) list(APPEND GGML_HEADERS_MUSA "../ggml-musa/mudnn.cuh") file(GLOB GGML_SOURCES_MUSA "../ggml-cuda/*.cu") - file(GLOB SRCS "../ggml-cuda/template-instances/fattn-tile*.cu") - list(APPEND GGML_SOURCES_MUSA ${SRCS}) - file(GLOB SRCS "../ggml-cuda/template-instances/fattn-mma*.cu") - list(APPEND GGML_SOURCES_MUSA ${SRCS}) file(GLOB SRCS "../ggml-cuda/template-instances/mmq*.cu") list(APPEND GGML_SOURCES_MUSA ${SRCS}) @@ -46,7 +42,7 @@ if (MUSAToolkit_FOUND) add_compile_definitions(GGML_MUSA_MUDNN_COPY) endif() - ggml_cuda_fattn_vec_instances(${CMAKE_CURRENT_SOURCE_DIR}/../ggml-cuda SRCS) + ggml_cuda_fattn_instances(${CMAKE_CURRENT_SOURCE_DIR}/../ggml-cuda SRCS) list(APPEND GGML_SOURCES_MUSA ${SRCS}) set_source_files_properties(${GGML_SOURCES_MUSA} PROPERTIES LANGUAGE CXX) diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index 18d8b9ce56ea..dfda021f1dfb 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -1215,6 +1215,14 @@ struct ggml_backend_opencl_context { 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 @@ -7808,6 +7816,150 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { } } + // 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 @@ -11080,6 +11232,76 @@ static bool ggml_opencl_can_fuse_moe_bias_glu(const struct ggml_cgraph * cgraph, 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( @@ -11958,8 +12180,12 @@ static bool adreno_e17_compiler_quirks(const ggml_backend_opencl_context *backen backend_ctx->adreno_cl_compiler_version.type != ADRENO_CL_COMPILER_TYPE::E17) { return false; } - const char * env = getenv("GGML_OPENCL_ADRENO_E17_QUIRKS"); - return !(env && env[0] == '0'); + + 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) { @@ -12989,7 +13215,7 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te return true; } #endif - // The E17 compilers segfault while building FA kernels, skip E17 for now + // Some E17 compilers crash while building FA kernels. if (adreno_e17_compiler_quirks(backend_ctx)) { return false; } @@ -36913,6 +37139,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0, 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"); @@ -37217,6 +37461,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0, 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"); @@ -37496,6 +37758,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0, } } + // 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"); @@ -37695,6 +37975,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0, 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"); @@ -38179,6 +38477,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0, 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"); @@ -38518,6 +38834,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0, } } + // 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_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"); @@ -38738,6 +39072,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0, 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"); @@ -39038,6 +39390,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0, 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; diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 5791ea3011f5..634301ee88c0 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -2046,6 +2046,9 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { return {false, "MUL_MAT_ID with single-expert or empty ne[2] <= 1 (ne[2]=" + std::to_string(op->src[0]->ne[2]) + ") is not supported"}; } + if (op->src[1] != nullptr && op->src[1]->type == GGML_TYPE_BF16) { + return {false, "MUL_MAT_ID with a BF16 src1 is not supported"}; + } // The GPU plugin's GatherMatmul returns wrong values for the layouts test-backend-ops // produces: it builds a rank-4 input layout ([n_used, n_tokens, k, 1]) instead of rank 3 // and the kernel misreads it, silently returning garbage (NMSE ~86) rather than asserting. diff --git a/ggml/src/ggml-sycl/common.hpp b/ggml/src/ggml-sycl/common.hpp index ae156acca75f..f9b7a28215ec 100644 --- a/ggml/src/ggml-sycl/common.hpp +++ b/ggml/src/ggml-sycl/common.hpp @@ -71,6 +71,7 @@ void ggml_sycl_host_free(void* ptr); 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_fuse_conv_window; extern int g_ggml_sycl_enable_esimd; extern int g_ggml_sycl_mmid_esimd; extern int g_ggml_sycl_mmvq_wide; diff --git a/ggml/src/ggml-sycl/fattn.cpp b/ggml/src/ggml-sycl/fattn.cpp index 525e6fd8c095..d37e99d9b817 100644 --- a/ggml/src/ggml-sycl/fattn.cpp +++ b/ggml/src/ggml-sycl/fattn.cpp @@ -416,10 +416,6 @@ bool ggml_sycl_flash_attn_ext_supported(int device, const ggml_tensor * dst) { return ggml_sycl_get_best_fattn_kernel(device, dst) != BEST_FATTN_KERNEL_NONE; } -bool ggml_sycl_flash_attn_ext_needs_sync(int device, const ggml_tensor * dst) { - return ggml_sycl_get_best_fattn_kernel(device, dst) == BEST_FATTN_KERNEL_MKL; -} - bool ggml_sycl_flash_attn_ext_uses_onednn(int device, const ggml_tensor * dst) { return ggml_sycl_get_best_fattn_kernel(device, dst) == BEST_FATTN_KERNEL_ONEDNN; } diff --git a/ggml/src/ggml-sycl/fattn.hpp b/ggml/src/ggml-sycl/fattn.hpp index 8ba634223be3..cfecf80771af 100644 --- a/ggml/src/ggml-sycl/fattn.hpp +++ b/ggml/src/ggml-sycl/fattn.hpp @@ -19,9 +19,6 @@ void ggml_sycl_flash_attn_ext(ggml_backend_sycl_context & ctx, ggml_tensor * dst bool ggml_sycl_flash_attn_ext_supported(int device, const ggml_tensor * dst); -// Reports if flash attention runs this node with the oneMKL kernel, which waits on the host -bool ggml_sycl_flash_attn_ext_needs_sync(int device, const ggml_tensor * dst); - // Reports if flash attention runs this node with the oneDNN kernel bool ggml_sycl_flash_attn_ext_uses_onednn(int device, const ggml_tensor * dst); diff --git a/ggml/src/ggml-sycl/gated_delta_net.cpp b/ggml/src/ggml-sycl/gated_delta_net.cpp index 63535a945e61..af123b6e8213 100644 --- a/ggml/src/ggml-sycl/gated_delta_net.cpp +++ b/ggml/src/ggml-sycl/gated_delta_net.cpp @@ -5,6 +5,73 @@ #include "gated_delta_net.hpp" #include +#ifdef GGML_SYCL_DMMV_HAS_ESIMD +# include + +static void launch_gated_delta_net_esimd(const float * q, + const float * k, + const float * v, + const float * g, + const float * beta, + const float * curr_state, + float * dst, + float * state, + int64_t H, + int64_t n_tokens, + int64_t n_seqs, + int64_t sq1, + int64_t sq2, + int64_t sq3, + 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, + dpct::queue_ptr stream) { + constexpr int S_v = 128; + stream->parallel_for( + sycl::nd_range<3>(sycl::range<3>((size_t) n_seqs, (size_t) H, S_v), sycl::range<3>(1, 1, 16)), + [=](sycl::nd_item<3> it) [[intel::sycl_explicit_simd]] { + using namespace sycl::ext::intel::esimd; + const int col = it.get_global_id(2); + const int h_idx = it.get_group(1); + const int sequence = it.get_group(0); + const int iq1 = h_idx % (int) neqk1; + const int iq3 = sequence / (int) rq3; + + const int64_t head = sequence * H + h_idx; + simd s = block_load(curr_state + head * S_v * S_v + col * S_v); + float * state_col = state + head * S_v * S_v + col * S_v; + float * attn = dst + (sequence * n_tokens * H + h_idx) * S_v + col; + + for (int t = 0; t < n_tokens; ++t) { + const simd q_t = block_load(q + iq3 * sq3 + t * sq2 + iq1 * sq1); + const simd k_t = block_load(k + iq3 * sq3 + t * sq2 + iq1 * sq1); + const float v_val = v[sequence * sv3 + t * sv2 + h_idx * sv1 + col]; + const int64_t gb = sequence * sb3 + t * sb2 + h_idx * sb1; + const float g_val = exp(g[gb]); + const float beta_val = beta[gb]; + + // kv = S^T k, delta = (v - g kv) beta, S = g S + k delta, attn = S^T q + const float kv = reduce(s * k_t, std::plus<>()); + const float delta = (v_val - g_val * kv) * beta_val; + s = g_val * s + k_t * delta; + attn[(int64_t) t * S_v * H] = reduce(s * q_t, std::plus<>()) * scale; + + const int slot = (int) n_tokens - 1 - t; + if (slot < K) { + block_store(state_col + slot * state_slot_stride, s); + } + } + }); +} +#endif // 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; @@ -366,6 +433,14 @@ static void ggml_sycl_op_gated_delta_net_impl(ggml_backend_sycl_context & ctx, g state_slot_stride = cache->slot_stride; } +#ifdef GGML_SYCL_DMMV_HAS_ESIMD + if (!kda && S_v == 128 && g_ggml_sycl_enable_esimd && state_slot_stride % 4 == 0 && (uintptr_t) state_d % 16 == 0) { + launch_gated_delta_net_esimd(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, rq3, scale, state_slot_stride, K, stream); + return; + } +#endif + 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, diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp index 2630b8e7238a..20ba4217bfbe 100644 --- a/ggml/src/ggml-sycl/ggml-sycl.cpp +++ b/ggml/src/ggml-sycl/ggml-sycl.cpp @@ -110,6 +110,7 @@ int g_ggml_sycl_memtrace = 0; 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_fuse_conv_window = 1; int g_ggml_sycl_enable_esimd = 1; int g_ggml_sycl_mmid_esimd = 1; int g_ggml_sycl_mmvq_wide = 1; @@ -444,6 +445,7 @@ static void ggml_check_sycl() try { g_ggml_sycl_memtrace_step = ggml_sycl_get_env("GGML_SYCL_MEMTRACE_STEP", 64); 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_fuse_conv_window = ggml_sycl_get_env("GGML_SYCL_FUSE_CONV_WINDOW", 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); @@ -594,6 +596,7 @@ static void ggml_check_sycl() try { #endif GGML_LOG_INFO(" GGML_SYCL_ENABLE_FUSION: %d\n", g_ggml_sycl_enable_fusion); + GGML_LOG_INFO(" GGML_SYCL_FUSE_CONV_WINDOW: %d\n", g_ggml_sycl_fuse_conv_window); GGML_LOG_INFO(" GGML_SYCL_UPLOAD_STAGING_SLOTS: %d\n", g_ggml_sycl_upload_staging_slots); #if defined(__INTEL_LLVM_COMPILER) @@ -6698,6 +6701,7 @@ static int ggml_sycl_try_gdn_cache_fusion(const ggml_cgraph * cgraph, int node_i } static void ggml_backend_sycl_graph_compute_impl(ggml_backend_sycl_context * sycl_ctx, ggml_cgraph * cgraph) { + ggml_sycl_conv_window_match conv_window; for (int i = 0; i < cgraph->n_nodes; i++) { ggml_tensor * node = cgraph->nodes[i]; if (ggml_sycl_is_view_or_noop(node)) { @@ -6707,6 +6711,24 @@ static void ggml_backend_sycl_graph_compute_impl(ggml_backend_sycl_context * syc continue; } + // Run the window and cache updates at the convolution. + if (conv_window.concat == nullptr && node->op == GGML_OP_CONCAT && + ggml_sycl_match_conv_window(cgraph, i, conv_window)) { + continue; + } + if (conv_window.concat != nullptr) { + if (std::find(conv_window.cont, conv_window.cont + conv_window.n_slots, node) != conv_window.cont + conv_window.n_slots || + std::find(conv_window.cpy, conv_window.cpy + conv_window.n_slots, node) != conv_window.cpy + conv_window.n_slots) { + continue; + } + if (node == conv_window.conv) { + ggml_sycl_ssm_conv_window(*sycl_ctx, conv_window); + i = conv_window.last_idx; + conv_window = {}; + continue; + } + } + const int nodes_to_skip = ggml_sycl_fuse(*sycl_ctx, cgraph, i); if (nodes_to_skip != 0) { i += nodes_to_skip; @@ -7008,11 +7030,6 @@ static bool check_graph_compatibility(ggml_backend_sycl_context * ctx, ggml_cgra } break; case GGML_OP_FLASH_ATTN_EXT: - if (ggml_sycl_flash_attn_ext_needs_sync(ctx->device, node)) { - GGML_LOG_DEBUG("%s: disabling SYCL graphs due to host wait in %s\n", __func__, - ggml_op_name(node_op)); - return false; - } #ifndef GGML_SYCL_GRAPH_DNNL_SUPPORTED if (ggml_sycl_flash_attn_ext_uses_onednn(ctx->device, node)) { GGML_LOG_DEBUG("%s: disabling SYCL graphs due to %s using oneDNN\n", __func__, @@ -7194,6 +7211,22 @@ static void ggml_backend_sycl_event_wait(ggml_backend_t backend, ggml_backend_ev std::exit(1); } +static void ggml_backend_sycl_graph_optimize(ggml_backend_t backend, ggml_cgraph * cgraph, + ggml_backend_graph_optimize_params * params) { + GGML_UNUSED(backend); + for (int i = 0; i < cgraph->n_nodes; ++i) { + ggml_sycl_conv_window_match match; + if (cgraph->nodes[i]->op != GGML_OP_CONCAT || !ggml_sycl_match_conv_window(cgraph, i, match)) { + continue; + } + // Inputs and delayed cache writes must stay allocated until the fused kernel. + for (ggml_tensor * t : { match.concat->src[0], match.concat->src[1], match.cpy[0]->src[1] }) { + params->add_alloc_dep(params->user_data, t->view_src ? t->view_src : t, match.silu); + } + i = match.last_idx; + } +} + static ggml_backend_i ggml_backend_sycl_interface = { /* .get_name = */ ggml_backend_sycl_get_name, /* .free = */ ggml_backend_sycl_free, @@ -7212,7 +7245,7 @@ static ggml_backend_i ggml_backend_sycl_interface = { /* .graph_compute = */ ggml_backend_sycl_graph_compute, /* .event_record = */ ggml_backend_sycl_event_record, /* .event_wait = */ ggml_backend_sycl_event_wait, - /* .graph_optimize = */ NULL, + /* .graph_optimize = */ ggml_backend_sycl_graph_optimize, }; static ggml_guid_t ggml_backend_sycl_guid() { @@ -7402,6 +7435,11 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons return false; } + // MUL_MAT_ID copies the src1 rows as F32 + if (op->op == GGML_OP_MUL_MAT_ID && b->type != GGML_TYPE_F32) { + return false; + } + if (op->op == GGML_OP_MUL_MAT && (ggml_prec_get_src(op, 1) == GGML_PREC_BF16 || ggml_prec_get_src(op, 1) == GGML_PREC_F32)) { return false; diff --git a/ggml/src/ggml-sycl/ssm_conv.cpp b/ggml/src/ggml-sycl/ssm_conv.cpp index a8714351866f..d6fb7d3952f0 100644 --- a/ggml/src/ggml-sycl/ssm_conv.cpp +++ b/ggml/src/ggml-sycl/ssm_conv.cpp @@ -1,7 +1,10 @@ #include "ssm_conv.hpp" #include "common.hpp" #include "element_wise.hpp" +#include "fusion.hpp" +#include +#include #include using namespace sycl; @@ -359,3 +362,290 @@ void ggml_sycl_ssm_conv_fused(ggml_backend_sycl_context & ctx, ggml_tensor * dst } ggml_sycl_op_ssm_conv(ctx, dst, silu_dst, bias); } + +static const ggml_tensor * conv_window_base(const ggml_tensor * t) { + return t->view_src ? t->view_src : t; +} + +static bool conv_window_f32_strides(const ggml_tensor * t) { + for (int d = 0; d < GGML_MAX_DIMS; ++d) { + if (t->nb[d] % sizeof(float) != 0) { + return false; + } + } + return true; +} + +bool ggml_sycl_match_conv_window(const ggml_cgraph * cgraph, int node_idx, ggml_sycl_conv_window_match & m) { + if (!g_ggml_sycl_fuse_conv_window || !g_ggml_sycl_enable_fusion) { + return false; + } + + const ggml_tensor * concat = cgraph->nodes[node_idx]; + if (concat->op != GGML_OP_CONCAT || ggml_get_op_params_i32(concat, 0) != 0 || concat->type != GGML_TYPE_F32 || + (concat->flags & GGML_TENSOR_FLAG_OUTPUT) || concat->ne[3] != 1 || !ggml_is_contiguous(concat)) { + return false; + } + + const ggml_tensor * state = concat->src[0]; + const ggml_tensor * xt = concat->src[1]; + if (state->type != GGML_TYPE_F32 || xt->type != GGML_TYPE_F32 || !conv_window_f32_strides(state) || + !conv_window_f32_strides(xt)) { + return false; + } + + // the kernel is written for d_conv == 4: three state columns + const int64_t state_cols = state->ne[0]; + const int64_t channels = concat->ne[1]; + const int64_t n_seqs = concat->ne[2]; + if (state_cols != 3 || channels <= 0 || channels > INT_MAX - 255 || + xt->ne[0] <= 0 || xt->ne[0] > INT_MAX - 7 || n_seqs <= 0 || n_seqs > INT_MAX) { + return false; + } + + ggml_sycl_conv_window_match r; + r.concat = concat; + + const ggml_tensor * cache = nullptr; + const ggml_tensor * pending = nullptr; // a cont still waiting for its cpy + int n_views = 0; + + // Check intervening nodes after the cache is known. + const int end = std::min(cgraph->n_nodes, node_idx + 64); + for (int j = node_idx + 1; j < end && r.conv == nullptr; ++j) { + ggml_tensor * n = cgraph->nodes[j]; + if (n->op == GGML_OP_VIEW && n->src[0] == concat) { + if ((n->flags & GGML_TENSOR_FLAG_OUTPUT) || n->ne[0] != state_cols || n->ne[1] != channels || n->ne[2] != n_seqs || n->ne[3] != 1 || + n->nb[1] != concat->nb[1] || n->nb[2] != concat->nb[2] || n->view_offs % sizeof(float) != 0 || + ggml_node_get_use_count(cgraph, j) != 1) { + return false; + } + n_views++; + } else if (n->op == GGML_OP_CONT && n->src[0]->op == GGML_OP_VIEW && n->src[0]->src[0] == concat) { + if (pending != nullptr || r.n_slots == GGML_SYCL_CONV_WINDOW_MAX_SLOTS || + !ggml_node_has_n_uses(cgraph, j, 1)) { + return false; + } + pending = n; + } else if (n->op == GGML_OP_CPY && ((pending != nullptr && n->src[0] == pending) || + (pending == nullptr && n->src[0]->op == GGML_OP_VIEW && n->src[0]->src[0] == concat))) { + if (r.n_slots == GGML_SYCL_CONV_WINDOW_MAX_SLOTS) { + return false; + } + // dst is a [state_cols * channels, n_seqs] view of the cache rows + const ggml_tensor * dst = n->src[1]; + if (dst->type != GGML_TYPE_F32 || dst->ne[0] != state_cols * channels || dst->ne[1] != n_seqs || + dst->ne[2] != 1 || dst->ne[3] != 1 || dst->nb[0] != sizeof(float) || dst->nb[1] % sizeof(float) != 0 || dst->nb[1] < dst->ne[0] * sizeof(float)) { + return false; + } + if (cache == nullptr) { + cache = conv_window_base(dst); + } + // one seq stride for all slots, and the tail must stay inside one channel row + const ggml_tensor * tail = pending != nullptr ? pending->src[0] : n->src[0]; + const int64_t s_idx = tail->view_offs / sizeof(float); + if (conv_window_base(dst) != cache || (r.n_slots > 0 && dst->nb[1] != r.cpy[0]->src[1]->nb[1]) || + s_idx + state_cols > concat->ne[0]) { + return false; + } + for (int p = 0; p < r.n_slots; ++p) { + const ggml_tensor * prev = r.cpy[p]->src[1]; + if (dst->view_offs >= prev->view_offs ? dst->view_offs - prev->view_offs < ggml_nbytes(prev) : + prev->view_offs - dst->view_offs < ggml_nbytes(dst)) { + return false; + } + } + r.cont[r.n_slots] = pending; + r.cpy[r.n_slots] = n; + r.n_slots++; + pending = nullptr; + } else if (n->op == GGML_OP_SSM_CONV && n->src[0] == concat) { + r.conv = n; + r.conv_idx = j; + } + } + + if (r.conv == nullptr || r.n_slots == 0 || pending != nullptr || n_views != r.n_slots || + ggml_node_get_use_count(cgraph, node_idx) != n_views + 1) { + return false; + } + + const ggml_tensor * weights = r.conv->src[1]; + if (weights->type != GGML_TYPE_F32 || weights->ne[0] != state_cols + 1 || !ggml_is_contiguous(weights) || + r.conv->type != GGML_TYPE_F32 || conv_window_base(weights) == cache) { + return false; + } + + // the window reads state and x, the kernel writes the cache: they must not overlap + const ggml_tensor * state_base = conv_window_base(state); + const ggml_tensor * x_base = conv_window_base(xt); + if (state_base == cache || x_base == cache) { + return false; + } + + // Delayed cache copies must not cross a reader or an input write. + for (int j = node_idx + 1; j < r.conv_idx; ++j) { + const ggml_tensor * n = cgraph->nodes[j]; + if ((n->flags & GGML_TENSOR_FLAG_COMPUTE) == 0 || n->op == GGML_OP_VIEW || n->op == GGML_OP_RESHAPE || + n->op == GGML_OP_TRANSPOSE || n->op == GGML_OP_PERMUTE || n->op == GGML_OP_NONE) { + continue; + } + if (std::find(r.cont, r.cont + r.n_slots, n) != r.cont + r.n_slots || + std::find(r.cpy, r.cpy + r.n_slots, n) != r.cpy + r.n_slots) { + continue; + } + for (int s = 0; s < GGML_MAX_SRC; ++s) { + const ggml_tensor * src = n->src[s]; + if (src == nullptr) { + continue; + } + const ggml_tensor * b = conv_window_base(src); + if (b == cache || b == concat || std::find(r.cont, r.cont + r.n_slots, b) != r.cont + r.n_slots) { + return false; + } + } + const ggml_tensor * b = conv_window_base(n); + if (b == cache || b == state_base || b == x_base) { + return false; + } + } + + if (ggml_sycl_can_fuse(cgraph, r.conv_idx, { GGML_OP_SSM_CONV, GGML_OP_ADD, GGML_OP_UNARY }, { GGML_UNARY_OP_SILU })) { + r.add = cgraph->nodes[r.conv_idx + 1]; + r.silu = cgraph->nodes[r.conv_idx + 2]; + r.last_idx = r.conv_idx + 2; + } else if (ggml_sycl_can_fuse(cgraph, r.conv_idx, { GGML_OP_SSM_CONV, GGML_OP_UNARY }, { GGML_UNARY_OP_SILU })) { + r.silu = cgraph->nodes[r.conv_idx + 1]; + r.last_idx = r.conv_idx + 1; + } else { + return false; + } + if (r.silu->type != GGML_TYPE_F32 || !ggml_is_contiguous(r.silu)) { + return false; + } + + if (r.add != nullptr) { + const ggml_tensor * bias = r.add->src[0] == r.conv ? r.add->src[1] : r.add->src[0]; + if (conv_window_base(bias) == cache) { + return false; + } + } + + m = r; + return true; +} + +struct conv_window_slots { + float * dst[GGML_SYCL_CONV_WINDOW_MAX_SLOTS]; + int s_idx[GGML_SYCL_CONV_WINDOW_MAX_SLOTS]; + int n; +}; + +// Each work-item slides a four-value window over up to eight tokens. +// Token max(0, w - 3) writes cache column w, so each cache value has one writer. +static void kernel_ssm_conv_window(queue & q, const float * state, const float * x, const float * weights, + const float * bias, float * dst, conv_window_slots slots, int d_inner, int n_t, + int n_s, int64_t st_col, int64_t st_ch, int64_t st_seq, int64_t x_tok, + int64_t x_ch, int64_t x_seq, int64_t cache_seq) { + constexpr int DC = 4; + constexpr int NC = DC - 1; + constexpr int TT = 8; + + // a 3D range: 64-bit div/mod of a flat index is emulated and costs a lot at the prefill shape + const int wg = 256; + const int c_pad = (d_inner + wg - 1) / wg * wg; + const int n_tb = (n_t + TT - 1) / TT; + + q.parallel_for(nd_range<3>(range<3>(n_s, n_tb, c_pad), range<3>(1, 1, wg)), [=](nd_item<3> item) { + const int c = static_cast(item.get_global_id(2)); + const int t0 = static_cast(item.get_global_id(1)) * TT; + const int s = static_cast(item.get_global_id(0)); + if (c >= d_inner) { + return; + } + const int t1 = sycl::min(t0 + TT, n_t); + + const float * sp = state + s * st_seq + c * st_ch; + const float * xp = x + s * x_seq + c * x_ch; + + float win[DC]; +#pragma unroll + for (int k = 0; k < NC; ++k) { + const int w = t0 + k; + win[k + 1] = w < NC ? sp[w * st_col] : xp[(w - NC) * x_tok]; + } + + float cw[DC]; +#pragma unroll + for (int k = 0; k < DC; ++k) { + cw[k] = weights[static_cast(c) * DC + k]; + } + const float b = bias != nullptr ? bias[c] : 0.0f; + + for (int t = t0; t < t1; ++t) { +#pragma unroll + for (int k = 0; k < NC; ++k) { + win[k] = win[k + 1]; + } + win[NC] = xp[t * x_tok]; + + float sumf = 0.0f; +#pragma unroll + for (int k = 0; k < DC; ++k) { + sumf += win[k] * cw[k]; + } + if (bias != nullptr) { + sumf += b; + } + dst[(static_cast(s) * n_t + t) * d_inner + c] = op_silu(sumf); + + // constant win[] indices keep the window in registers + for (int p = 0; p < slots.n; ++p) { + float * cd = slots.dst[p] + s * cache_seq + static_cast(c) * NC; +#pragma unroll + for (int k = 0; k < DC; ++k) { + const int w = t + k; + const int j = w - slots.s_idx[p]; + if (j >= 0 && j < NC && sycl::max(w - NC, 0) == t) { + cd[j] = win[k]; + } + } + } + } + }); +} + +void ggml_sycl_ssm_conv_window(ggml_backend_sycl_context & ctx, const ggml_sycl_conv_window_match & m) { + const ggml_tensor * state = m.concat->src[0]; + const ggml_tensor * xt = m.concat->src[1]; + + const int d_inner = m.concat->ne[1]; + const int n_t = xt->ne[0]; + const int n_s = m.concat->ne[2]; + + GGML_ASSERT(m.conv->ne[0] == d_inner && m.conv->ne[1] == n_t && m.conv->ne[2] == n_s); + + conv_window_slots slots = {}; + slots.n = m.n_slots; + for (int p = 0; p < m.n_slots; ++p) { + const ggml_tensor * tail = m.cpy[p]->src[0]; + if (tail->op == GGML_OP_CONT) { + tail = tail->src[0]; + } + slots.dst[p] = static_cast(m.cpy[p]->src[1]->data); + slots.s_idx[p] = static_cast(tail->view_offs / sizeof(float)); + } + + const float * bias = nullptr; + if (m.add != nullptr) { + const ggml_tensor * bias_t = (m.add->src[0] == m.conv) ? m.add->src[1] : m.add->src[0]; + bias = static_cast(bias_t->data); + } + + constexpr int64_t fs = sizeof(float); + kernel_ssm_conv_window(*ctx.stream(), static_cast(state->data), + static_cast(xt->data), static_cast(m.conv->src[1]->data), + bias, static_cast(m.silu->data), slots, d_inner, n_t, n_s, state->nb[0] / fs, + state->nb[1] / fs, state->nb[2] / fs, xt->nb[0] / fs, xt->nb[1] / fs, xt->nb[2] / fs, + m.cpy[0]->src[1]->nb[1] / fs); +} diff --git a/ggml/src/ggml-sycl/ssm_conv.hpp b/ggml/src/ggml-sycl/ssm_conv.hpp index 72c9066232ef..6308c4d463f4 100644 --- a/ggml/src/ggml-sycl/ssm_conv.hpp +++ b/ggml/src/ggml-sycl/ssm_conv.hpp @@ -4,3 +4,22 @@ void ggml_sycl_ssm_conv(ggml_backend_sycl_context & ctx, ggml_tensor * dst); void ggml_sycl_ssm_conv_fused(ggml_backend_sycl_context & ctx, ggml_tensor * dst, ggml_tensor * add, ggml_tensor * silu_dst); + +#define GGML_SYCL_CONV_WINDOW_MAX_SLOTS 8 + +// Match the recurrent window, rollback cache copies, convolution and SiLU. +struct ggml_sycl_conv_window_match { + const ggml_tensor * concat = nullptr; + ggml_tensor * conv = nullptr; + ggml_tensor * add = nullptr; + ggml_tensor * silu = nullptr; + int conv_idx = -1; + int last_idx = -1; // the silu node: the last node the kernel writes + int n_slots = 0; + const ggml_tensor * cont[GGML_SYCL_CONV_WINDOW_MAX_SLOTS] = {}; + const ggml_tensor * cpy[GGML_SYCL_CONV_WINDOW_MAX_SLOTS] = {}; +}; + +// Purely structural, so graph_optimize and the compute loop see the same answer. +bool ggml_sycl_match_conv_window(const ggml_cgraph * cgraph, int node_idx, ggml_sycl_conv_window_match & m); +void ggml_sycl_ssm_conv_window(ggml_backend_sycl_context & ctx, const ggml_sycl_conv_window_match & m); diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index f28690f68215..e6649b86c279 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -23,7 +23,10 @@ static vk_device_architecture get_device_architecture(const vk::PhysicalDevice& } } - if (!amd_shader_core_properties || !integer_dot_product || !subgroup_size_control) { + if (!subgroup_size_control) { + return vk_device_architecture::AMD_GCN; + } + if (!amd_shader_core_properties) { return vk_device_architecture::OTHER; } @@ -33,8 +36,10 @@ static vk_device_architecture get_device_architecture(const vk::PhysicalDevice& vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props; props2.pNext = &shader_core_props_amd; - shader_core_props_amd.pNext = &integer_dot_props; - integer_dot_props.pNext = &subgroup_size_control_props; + shader_core_props_amd.pNext = &subgroup_size_control_props; + if (integer_dot_product) { + subgroup_size_control_props.pNext = &integer_dot_props; + } device.getProperties2(&props2); @@ -49,7 +54,7 @@ static vk_device_architecture get_device_architecture(const vk::PhysicalDevice& if (shader_float8) { return vk_device_architecture::AMD_RDNA4; } - if (integer_dot_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) { + if (integer_dot_product && integer_dot_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) { return vk_device_architecture::AMD_RDNA3; } return vk_device_architecture::AMD_RDNA2; @@ -1215,7 +1220,8 @@ static vk_fa_tuning_params get_fa_tuning_params_scalar(const vk_device& device, // Disable subgroup use due to performance issues when enforcing subgroup sizes result.subgroup_size = 32; result.disable_subgroups = true; - } else if (device->vendor_id == VK_VENDOR_ID_AMD && device->architecture != AMD_GCN) { + } else if (device->vendor_id == VK_VENDOR_ID_AMD && device->architecture != AMD_GCN && + device->subgroup_size_control && device->subgroup_min_size <= 32) { result.subgroup_size = n_rows < 4 ? 32 : device->subgroup_size; } else { result.subgroup_size = device->subgroup_size; diff --git a/ggml/src/ggml-zendnn/ggml-zendnn.cpp b/ggml/src/ggml-zendnn/ggml-zendnn.cpp index 68f4a1249793..c25aab552efc 100644 --- a/ggml/src/ggml-zendnn/ggml-zendnn.cpp +++ b/ggml/src/ggml-zendnn/ggml-zendnn.cpp @@ -721,6 +721,11 @@ static bool ggml_backend_zendnn_device_supports_op(ggml_backend_dev_t dev, const return false; } + // the inputs are read as F32; only BF16 weights also take BF16 inputs as they are + if (inputs->type != GGML_TYPE_F32 && !(inputs->type == GGML_TYPE_BF16 && weights->type == GGML_TYPE_BF16)) { + return false; + } + if (ggml_prec_get_src(op, 1) == GGML_PREC_BF16 || ggml_prec_get_src(op, 1) == GGML_PREC_F32) { return false; } diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index c616fa39bf96..126167098cfa 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -7271,6 +7271,13 @@ static void ggml_compute_backward( ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, grad, ggml_sigmoid(ctx, src0))); } } break; + case GGML_UNARY_OP_TANH: { + if (src0_needs_grads) { + struct ggml_tensor * tanh_sq = ggml_sqr(ctx, tensor); + struct ggml_tensor * one_m_sq = ggml_scale_bias(ctx, tanh_sq, -1.0f, 1.0f); + ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, grad, one_m_sq)); + } + } break; default: { fprintf(stderr, "%s: unsupported unary op for backward pass: %s\n", __func__, ggml_unary_op_name(ggml_get_unary_op(tensor))); diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py index 57852fad6bcf..347378e612fa 100644 --- a/gguf-py/gguf/constants.py +++ b/gguf-py/gguf/constants.py @@ -175,6 +175,7 @@ class LLM: CONV_GROUP_SIZE = "{arch}.conv_group_size" SELECTOR_RANK = "{arch}.selector_rank" SELECTOR_TOP_K = "{arch}.selector_top_k" + SELECTOR_SOFTCAP_AFTER_CORRECTION = "{arch}.selector_softcap_after_correction" SAMPLE_FROM_ANCHOR = "{arch}.sample_from_anchor" HAS_CONFIDENCE_HEAD = "{arch}.has_confidence_head" HAS_MARKOV_CONTEXT = "{arch}.has_markov_context" @@ -199,6 +200,7 @@ class Attention: VALUE_LENGTH = "{arch}.attention.value_length" LAYERNORM_EPS = "{arch}.attention.layer_norm_epsilon" LAYERNORM_RMS_EPS = "{arch}.attention.layer_norm_rms_epsilon" + LATENT_NORM_RMS_EPS = "{arch}.attention.latent_norm_rms_epsilon" GROUPNORM_EPS = "{arch}.attention.group_norm_epsilon" GROUPNORM_GROUPS = "{arch}.attention.group_norm_groups" CAUSAL = "{arch}.attention.causal" @@ -740,6 +742,7 @@ class MODEL_ARCH(IntEnum): HUNYUAN_VL = auto() HY_V3 = auto() HY_V4 = auto() + HY_V4_FLASH = auto() SMOLLM3 = auto() GPT_OSS = auto() LFM2 = auto() @@ -774,6 +777,7 @@ class MODEL_ARCH(IntEnum): KIMI_LINEAR = auto() KIMI_K3 = auto() KIMI_K31 = auto() + RAON1_MINI = auto() TALKIE = auto() MELLUM = auto() NANBEIGE = auto() @@ -977,6 +981,7 @@ class MODEL_TENSOR(IntEnum): SSM_F_A = auto() # Kimi Linear SSM_F_B = auto() # Kimi Linear SSM_BETA = auto() # Kimi Linear qwen3.5 + SSM_RDA = auto() # Raon-1 mini SSM_G_A = auto() # Kimi Linear SSM_G_B = auto() # Kimi Linear SSM_G = auto() # Kimi K3 (full-rank KDA gate, replaces SSM_G_A/SSM_G_B) @@ -1159,6 +1164,7 @@ class MODEL_TENSOR(IntEnum): INDEXER_COMPRESSOR_NORM = auto() INDEXER_KPOOL_GATE = auto() INDEXER_KPOOL_APE = auto() + INDEXER_KPOOL_VALUE = auto() ATTN_V_GATE = auto() # k2-horizon MoVA router ATTN_V_EXP = auto() # k2-horizon MoVA value experts # vision @@ -1541,6 +1547,10 @@ class MODEL_TENSOR(IntEnum): DSPARK_MARKOV_CTX_NORM = auto() # rnn markov head: target feature norm ENGRAM_KV = auto() ENGRAM_GATE = auto() + ENGRAM_KV_B = auto() + ENGRAM_LOOKUP_NORM = auto() + ENGRAM_PRE_GAMMA = auto() + ENGRAM_HC_SCALE = auto() DFLASH_ATTN_CONV_BASE = auto() DFLASH_ATTN_CONV_PROJ = auto() DFLASH_FFN_CONV_BASE = auto() @@ -1763,6 +1773,7 @@ class MODEL_TENSOR(IntEnum): MODEL_ARCH.HUNYUAN_VL: "hunyuan_vl", MODEL_ARCH.HY_V3: "hy_v3", MODEL_ARCH.HY_V4: "hy_v4", + MODEL_ARCH.HY_V4_FLASH: "hy_v4_flash", MODEL_ARCH.SMOLLM3: "smollm3", MODEL_ARCH.GPT_OSS: "gpt-oss", MODEL_ARCH.LFM2: "lfm2", @@ -1797,6 +1808,7 @@ class MODEL_TENSOR(IntEnum): MODEL_ARCH.KIMI_LINEAR: "kimi-linear", MODEL_ARCH.KIMI_K3: "kimi-k3", MODEL_ARCH.KIMI_K31: "kimi-k31", + MODEL_ARCH.RAON1_MINI: "raon1", MODEL_ARCH.TALKIE: "talkie", MODEL_ARCH.MELLUM: "mellum", MODEL_ARCH.NANBEIGE: "nanbeige", @@ -1998,6 +2010,7 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.SSM_F_A: "blk.{bid}.ssm_f_a", # Kimi Linear MODEL_TENSOR.SSM_F_B: "blk.{bid}.ssm_f_b", # Kimi Linear MODEL_TENSOR.SSM_BETA: "blk.{bid}.ssm_beta", # Kimi Linear qwen3.5 + MODEL_TENSOR.SSM_RDA: "blk.{bid}.ssm_rda", # Raon-1 mini MODEL_TENSOR.SSM_G_A: "blk.{bid}.ssm_g_a", # Kimi Linear MODEL_TENSOR.SSM_G_B: "blk.{bid}.ssm_g_b", # Kimi Linear MODEL_TENSOR.SSM_G: "blk.{bid}.ssm_g", # Kimi K3 @@ -2180,6 +2193,7 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.INDEXER_COMPRESSOR_NORM: "blk.{bid}.indexer_compressor_norm", MODEL_TENSOR.INDEXER_KPOOL_GATE: "blk.{bid}.indexer_compressor_gate", MODEL_TENSOR.INDEXER_KPOOL_APE: "blk.{bid}.indexer_compressor_ape", + MODEL_TENSOR.INDEXER_KPOOL_VALUE: "blk.{bid}.indexer_compressor_value", # vision MODEL_TENSOR.V_MMPROJ: "mm.{bid}", MODEL_TENSOR.V_MMPROJ_FC: "mm.model.fc", @@ -2602,6 +2616,10 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.DSPARK_MARKOV_CTX_NORM: "markov_ctx_norm", MODEL_TENSOR.ENGRAM_KV: "blk.{bid}.engram_kv", MODEL_TENSOR.ENGRAM_GATE: "blk.{bid}.engram_gate", + MODEL_TENSOR.ENGRAM_KV_B: "blk.{bid}.engram_kv_b", + MODEL_TENSOR.ENGRAM_LOOKUP_NORM: "blk.{bid}.engram_lookup_norm", + MODEL_TENSOR.ENGRAM_PRE_GAMMA: "blk.{bid}.engram_pre_gamma", + MODEL_TENSOR.ENGRAM_HC_SCALE: "blk.{bid}.engram_hc_scale", MODEL_TENSOR.DFLASH_ATTN_CONV_BASE: "blk.{bid}.attn_conv_base", MODEL_TENSOR.DFLASH_ATTN_CONV_PROJ: "blk.{bid}.attn_conv_proj", MODEL_TENSOR.DFLASH_FFN_CONV_BASE: "blk.{bid}.ffn_conv_base", @@ -6102,6 +6120,67 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.FFN_DOWN_SHEXP, MODEL_TENSOR.FFN_UP_SHEXP, ], + MODEL_ARCH.HY_V4_FLASH: [ + MODEL_TENSOR.TOKEN_EMBD, + MODEL_TENSOR.OUTPUT_NORM, + MODEL_TENSOR.OUTPUT, + MODEL_TENSOR.ROPE_FREQS, + MODEL_TENSOR.HC_HEAD_FN, + MODEL_TENSOR.HC_HEAD_BASE, + MODEL_TENSOR.HC_HEAD_SCALE, + MODEL_TENSOR.ATTN_NORM, + MODEL_TENSOR.ATTN_SINKS, + MODEL_TENSOR.ATTN_Q_A, + MODEL_TENSOR.ATTN_Q_A_NORM, + MODEL_TENSOR.ATTN_Q_B, + MODEL_TENSOR.ATTN_KV_A_MQA, + MODEL_TENSOR.ATTN_KV_A_NORM, + MODEL_TENSOR.ATTN_K_B, + MODEL_TENSOR.ATTN_V_B, + MODEL_TENSOR.ATTN_OUT, + MODEL_TENSOR.ATTN_GATE, + MODEL_TENSOR.INDEXER_K_NORM, + MODEL_TENSOR.INDEXER_PROJ, + MODEL_TENSOR.INDEXER_ATTN_K, + MODEL_TENSOR.INDEXER_ATTN_Q_B, + MODEL_TENSOR.HC_ATTN_FN, + MODEL_TENSOR.HC_ATTN_BASE, + MODEL_TENSOR.HC_ATTN_SCALE, + MODEL_TENSOR.HC_FFN_FN, + MODEL_TENSOR.HC_FFN_BASE, + MODEL_TENSOR.HC_FFN_SCALE, + MODEL_TENSOR.FFN_GATE_INP, + MODEL_TENSOR.FFN_EXP_PROBS_B, + MODEL_TENSOR.FFN_NORM, + MODEL_TENSOR.FFN_GATE, + MODEL_TENSOR.FFN_DOWN, + MODEL_TENSOR.FFN_UP, + MODEL_TENSOR.FFN_GATE_EXP, + MODEL_TENSOR.FFN_DOWN_EXP, + MODEL_TENSOR.FFN_UP_EXP, + MODEL_TENSOR.FFN_GATE_SHEXP, + MODEL_TENSOR.FFN_DOWN_SHEXP, + MODEL_TENSOR.FFN_UP_SHEXP, + MODEL_TENSOR.ATTN_POST_NORM, + MODEL_TENSOR.FFN_POST_NORM, + MODEL_TENSOR.FFN_ROUTED_DOWN, + MODEL_TENSOR.FFN_ROUTED_UP, + MODEL_TENSOR.PER_LAYER_TOKEN_EMBD, + MODEL_TENSOR.ENGRAM_KV, + MODEL_TENSOR.ENGRAM_GATE, + MODEL_TENSOR.ENGRAM_KV_B, + MODEL_TENSOR.ENGRAM_LOOKUP_NORM, + MODEL_TENSOR.ENGRAM_PRE_GAMMA, + MODEL_TENSOR.ENGRAM_HC_SCALE, + MODEL_TENSOR.INDEXER_KPOOL_GATE, + MODEL_TENSOR.INDEXER_KPOOL_APE, + MODEL_TENSOR.INDEXER_KPOOL_VALUE, + MODEL_TENSOR.INDEXER_COMPRESSOR_NORM, + MODEL_TENSOR.NEXTN_EH_PROJ, + MODEL_TENSOR.NEXTN_ENORM, + MODEL_TENSOR.NEXTN_HNORM, + MODEL_TENSOR.NEXTN_SHARED_HEAD_NORM, + ], MODEL_ARCH.SMOLLM3: [ MODEL_TENSOR.TOKEN_EMBD, MODEL_TENSOR.OUTPUT_NORM, @@ -6903,6 +6982,56 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.FFN_ROUTED_UP, MODEL_TENSOR.FFN_ROUTED_NORM, ], + MODEL_ARCH.RAON1_MINI: [ + MODEL_TENSOR.TOKEN_EMBD, + MODEL_TENSOR.OUTPUT_NORM, + MODEL_TENSOR.OUTPUT, + MODEL_TENSOR.ATTN_NORM, + # MLA (full-attention layers) + MODEL_TENSOR.ATTN_Q, + MODEL_TENSOR.ATTN_K, + MODEL_TENSOR.ATTN_V, + MODEL_TENSOR.ATTN_OUT, + MODEL_TENSOR.ATTN_GATE, + MODEL_TENSOR.ATTN_Q_A, + MODEL_TENSOR.ATTN_Q_B, + MODEL_TENSOR.ATTN_KV_A_MQA, + MODEL_TENSOR.ATTN_K_B, + MODEL_TENSOR.ATTN_V_B, + MODEL_TENSOR.ATTN_Q_A_NORM, + MODEL_TENSOR.ATTN_KV_A_NORM, + # RDA (linear-attention layers) + MODEL_TENSOR.SSM_CONV1D_Q, + MODEL_TENSOR.SSM_CONV1D_K, + MODEL_TENSOR.SSM_CONV1D_V, + MODEL_TENSOR.SSM_F_A, + MODEL_TENSOR.SSM_F_B, + MODEL_TENSOR.SSM_BETA, + MODEL_TENSOR.SSM_RDA, + MODEL_TENSOR.SSM_A, + MODEL_TENSOR.SSM_G, + MODEL_TENSOR.SSM_DT, + MODEL_TENSOR.SSM_NORM, + MODEL_TENSOR.HC_ATTN_FN, + MODEL_TENSOR.HC_ATTN_BASE, + MODEL_TENSOR.HC_ATTN_SCALE, + MODEL_TENSOR.HC_FFN_FN, + MODEL_TENSOR.HC_FFN_BASE, + MODEL_TENSOR.HC_FFN_SCALE, + # FFN + MODEL_TENSOR.FFN_NORM, + MODEL_TENSOR.FFN_GATE, + MODEL_TENSOR.FFN_DOWN, + MODEL_TENSOR.FFN_UP, + MODEL_TENSOR.FFN_GATE_INP, + MODEL_TENSOR.FFN_EXP_PROBS_B, + MODEL_TENSOR.FFN_GATE_EXP, + MODEL_TENSOR.FFN_DOWN_EXP, + MODEL_TENSOR.FFN_UP_EXP, + MODEL_TENSOR.FFN_GATE_SHEXP, + MODEL_TENSOR.FFN_DOWN_SHEXP, + MODEL_TENSOR.FFN_UP_SHEXP, + ], MODEL_ARCH.TALKIE: [ MODEL_TENSOR.TOKEN_EMBD, MODEL_TENSOR.OUTPUT, @@ -7282,6 +7411,10 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.ROPE_FREQS, MODEL_TENSOR.ATTN_ROT_EMBD, ], + MODEL_ARCH.HY_V4_FLASH: [ + MODEL_TENSOR.ROPE_FREQS, + MODEL_TENSOR.ATTN_ROT_EMBD, + ], MODEL_ARCH.XING4_0: [ MODEL_TENSOR.ROPE_FREQS, MODEL_TENSOR.ATTN_ROT_EMBD, @@ -7570,6 +7703,7 @@ class VisionProjectorType: KOKORO = "kokoro" # audio generation: StyleTTS2 prosody predictor + iSTFTNet decoder TINY_VOCA = "tiny_voca" # audio generation: duration predictor, frame transformers, source-filter vocoder HUNYUANVL = "hunyuanvl" + HY_V4_FLASH = "hy_v4_flash" PARAKEET = "parakeet" # audio MINIMAXM3 = "minimax_m3" MINICPMV4_6 = "minicpmv4_6" diff --git a/gguf-py/gguf/gguf_writer.py b/gguf-py/gguf/gguf_writer.py index 900aef6141a3..887352b2619d 100644 --- a/gguf-py/gguf/gguf_writer.py +++ b/gguf-py/gguf/gguf_writer.py @@ -1053,6 +1053,9 @@ def add_layer_norm_eps(self, value: float) -> None: def add_layer_norm_rms_eps(self, value: float) -> None: self.add_float32(Keys.Attention.LAYERNORM_RMS_EPS.format(arch=self.arch), value) + def add_latent_norm_rms_eps(self, value: float) -> None: + self.add_float32(Keys.Attention.LATENT_NORM_RMS_EPS.format(arch=self.arch), value) + def add_group_norm_eps(self, value: float) -> None: self.add_float32(Keys.Attention.GROUPNORM_EPS.format(arch=self.arch), value) @@ -1104,6 +1107,9 @@ def add_selector_rank(self, value: int) -> None: def add_selector_top_k(self, value: int) -> None: self.add_uint32(Keys.LLM.SELECTOR_TOP_K.format(arch=self.arch), value) + def add_selector_softcap_after_correction(self, value: bool) -> None: + self.add_bool(Keys.LLM.SELECTOR_SOFTCAP_AFTER_CORRECTION.format(arch=self.arch), value) + def add_sample_from_anchor(self, value: bool) -> None: self.add_bool(Keys.LLM.SAMPLE_FROM_ANCHOR.format(arch=self.arch), value) diff --git a/gguf-py/gguf/tensor_mapping.py b/gguf-py/gguf/tensor_mapping.py index c0bbfde2298d..a8e7367c396b 100644 --- a/gguf-py/gguf/tensor_mapping.py +++ b/gguf-py/gguf/tensor_mapping.py @@ -442,6 +442,7 @@ class TensorNameMap: "model.layers.layers.{bid}.post_mixer_norm.weight", # plamo2 "model.layers.{bid}.post_operator_norm", # lfm3 "model.layers.{bid}.post_attention_norm", # domynedge + "model.layers.{bid}.self_attn.post_proj_norm", # hy-v4-flash ), # Rotary embeddings @@ -663,6 +664,8 @@ class TensorNameMap: "model.layers.{bid}.post_mlp_layernorm", # glm-4-0414 "model.layers.{bid}.post_ffn_norm", # kolibri1 "model.layers.layers.{bid}.post_mlp_norm.weight", # plamo2 + "model.layers.{bid}.mlp.combine_output_norm", # hy-v4-flash (MoE layers) + "model.layers.{bid}.mlp.post_fc2_norm", # hy-v4-flash (dense layers) "model.layers.{bid}.feed_forward.up_proj", "model.layers.{bid}.post_moe_norm", # grok-2 "model.layers.{bid}.post_ffn_norm", # lfm3 @@ -716,6 +719,7 @@ class TensorNameMap: "backbone.layers.{bid}.mixer.gate.e_score_correction", # nemotron-h-moe "model.layers.{bid}.mlp.e_score_correction", # exaone-moe "model.layers.{bid}.block_sparse_moe.gate.e_score_correction", # kimi + "model.layers.{bid}.moe.gate.e_score_correction", # raon1_mini "model.layers.{bid}.moe.router_bias", # step3.5 expert selection bias "model.layers.{bid}.mlp.experts.e_score_correction", # laguna ), @@ -789,6 +793,7 @@ class TensorNameMap: "layers.{bid}.shared_experts.w3", # mistral-large "backbone.layers.{bid}.mixer.shared_experts.up_proj", # nemotron-h-moe "model.layers.{bid}.block_sparse_moe.shared_experts.up_proj", # kimi + "model.layers.{bid}.moe.shared_experts.up_proj", # raon1_mini "model.layers.{bid}.share_expert.up_proj", # step3.5 ), @@ -842,6 +847,7 @@ class TensorNameMap: "model.layers.{bid}.mlp.shared_mlp.gate_proj", # hunyuan "layers.{bid}.shared_experts.w1", # mistral-large "model.layers.{bid}.block_sparse_moe.shared_experts.gate_proj", # kimi + "model.layers.{bid}.moe.shared_experts.gate_proj", # raon1_mini "model.layers.{bid}.share_expert.gate_proj", # step3.5 ), @@ -1024,6 +1030,7 @@ class TensorNameMap: "layers.{bid}.shared_experts.w2", # mistral-large "backbone.layers.{bid}.mixer.shared_experts.down_proj", # nemotron-h-moe "model.layers.{bid}.block_sparse_moe.shared_experts.down_proj", # kimi + "model.layers.{bid}.moe.shared_experts.down_proj", # raon1_mini "model.layers.{bid}.share_expert.down_proj", # step3.5 "layers.{bid}.moe.shared_expert.down", # metis16 ), @@ -1286,13 +1293,19 @@ class TensorNameMap: "model.layers.{bid}.self_attn.b_proj", # Kimi Linear "model.layers.{bid}.attention.b_proj", # bailingmoe3 ), + # Raon-1 mini RDA: per-head write-gate offset + MODEL_TENSOR.SSM_RDA: ( + "model.layers.{bid}.self_attn.rda_w_proj", + ), # Kimi K3 latent MoE: routed experts operate in a down-projected space MODEL_TENSOR.FFN_ROUTED_DOWN: ( "model.layers.{bid}.block_sparse_moe.routed_expert_down_proj", + "model.layers.{bid}.mlp.routed_expert_down_proj", # hy-v4-flash ), MODEL_TENSOR.FFN_ROUTED_UP: ( "model.layers.{bid}.block_sparse_moe.routed_expert_up_proj", + "model.layers.{bid}.mlp.routed_expert_up_proj", # hy-v4-flash ), MODEL_TENSOR.FFN_ROUTED_NORM: ( @@ -2707,6 +2720,7 @@ class TensorNameMap: MODEL_TENSOR.V_MM_PRE_NORM: ( "vit.perceive.before_rms", # HunyuanVL + "vit.perceive.norm", # hy-v4-flash ), MODEL_TENSOR.V_TOK_IMG_BEGIN: ( diff --git a/models/templates/KRAFTON-Raon-1-mini-preview.jinja b/models/templates/KRAFTON-Raon-1-mini-preview.jinja new file mode 100644 index 000000000000..eff7831afcc4 --- /dev/null +++ b/models/templates/KRAFTON-Raon-1-mini-preview.jinja @@ -0,0 +1,134 @@ +{#- Text-only ChatML SFT protocol for raon-1-mini. -#} +{%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else false %} +{%- macro render_content(content, is_system_content=false) %} + {%- if content is string %} + {{- content }} + {%- elif content is iterable and content is not mapping %} + {%- for item in content %} + {%- if 'text' in item %} + {{- item.text }} + {%- else %} + {{- raise_exception('raon-1-mini supports text content only.') }} + {%- endif %} + {%- endfor %} + {%- elif content is none or content is undefined %} + {{- '' }} + {%- else %} + {{- raise_exception('Unexpected content type.') }} + {%- endif %} +{%- endmacro %} +{%- macro render_assistant_body(message, content, reasoning_content, preserve_reasoning) %} + {%- if preserve_reasoning and reasoning_content|trim %} + {{- '\n' + reasoning_content|trim + '\n\n\n' }} + {%- else %} + {{- '\n\n' }} + {%- endif %} + {{- content }} + {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if loop.first %} + {%- if content|trim %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n\n' }} + {%- endif %} + {%- else %} + {{- '\n\n\n' }} + {%- endif %} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' }} + {%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %} + {{- args_value }} + {{- '\n\n' }} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>' }} +{%- endmacro %} +{%- if not messages %} + {{- raise_exception('No messages provided.') }} +{%- endif %} +{%- if tools and tools is iterable and tools is not mapping %} + {{- '<|im_start|>system\n' }} + {{- '# Tools\n\nYou have access to the following functions:\n\n' }} + {%- for tool in tools %} + {{- '\n' }} + {{- tool | tojson }} + {%- endfor %} + {{- '\n' }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, true)|trim %} + {%- if content %} + {{- '\n\n' + content }} + {%- endif %} + {%- endif %} + {{- '<|im_end|>\n' }} +{%- elif messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, true)|trim %} + {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == 'user' %} + {%- set content = render_content(message.content)|trim %} + {%- if not(content.startswith('') and content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- for message in messages %} + {%- set content = render_content(message.content)|trim %} + {%- if message.role == 'system' %} + {%- if not loop.first %} + {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} + {%- endif %} + {%- elif message.role == 'user' %} + {{- '<|im_start|>user\n' + content + '<|im_end|>\n' }} + {%- elif message.role == 'assistant' %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- elif content.startswith('') and '' in content %} + {%- set thinking_parts = content.split('', 1) %} + {%- set reasoning_content = thinking_parts[0][7:].strip('\n') %} + {%- set content = thinking_parts[1].lstrip('\n') %} + {%- endif %} + {{- '<|im_start|>assistant\n' }} + {%- set preserve_reasoning = (not truncate_history_thinking) or (loop.index0 > ns.last_query_index) %} + {%- if message.loss is defined and message.loss is false %} + {{- render_assistant_body(message, content, reasoning_content, preserve_reasoning) }} + {%- else %} + {%- generation %} + {{- render_assistant_body(message, content, reasoning_content, preserve_reasoning) }} + {%- endgeneration %} + {%- endif %} + {{- '\n' }} + {%- elif message.role == 'tool' %} + {%- if loop.previtem and loop.previtem.role != 'tool' %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' + content + '\n' }} + {%- if loop.last or loop.nextitem.role != 'tool' %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- raise_exception('Unexpected message role.') }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n' }} + {%- else %} + {{- '\n' }} + {%- endif %} +{%- endif %} diff --git a/scripts/hip/gcn-cdna-metrics.py b/scripts/hip/gcn-cdna-metrics.py new file mode 100644 index 000000000000..8b8ae3b2504e --- /dev/null +++ b/scripts/hip/gcn-cdna-metrics.py @@ -0,0 +1,365 @@ +#!/usr/bin/env python3 + +# Check HIP VGPR limits, compare kernel resource usage, and generate a report. +# Read Clang optimization records produced with -fsave-optimization-record=yaml +# and -Rpass-analysis=kernel-resource-usage. + +import argparse +import sys +from collections import defaultdict +from pathlib import Path +from typing import cast + +import yaml + +try: + from itanium_demangler import parse as demangle # ty: ignore[import-not-found] +except ImportError: + demangle = None + +METRICS = ('occupancy', 'vgpr_spill', 'sgpr_spill') +REPORT_METRICS = METRICS + ('vgpr_total',) +RULES = { + 'vgpr_limit': 'blocking', + 'vgpr_spill_increase': 'blocking', + 'sgpr_spill_increase': 'blocking', + 'occupancy_vgpr_increase': 'blocking', + 'occupancy_drop': 'warning', +} +REMARK_NAMES = {'NumVGPR': 'vgprs', 'Occupancy': 'occupancy', 'VGPRSpill': 'vgpr_spill', 'SGPRSpill': 'sgpr_spill'} +METRIC_NAMES = {'occupancy': 'Occupancy [waves/SIMD]', 'vgpr_spill': 'VGPRs Spill', 'sgpr_spill': 'SGPRs Spill', 'vgpr_total': 'Total VGPRs (limit 256)'} + +IGNORED_VGPR = { + + '_ZL13rwkv_wkv7_f32ILi128EEviiiiPKfS1_S1_S1_S1_S1_S1_Pf', + '_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_f16ILi576ELi512ELi16ELi4ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi16ELb0ELb1ELb1EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi32ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi16ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi32ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_f16ILi576ELi512ELi4ELi16ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_f16ILi576ELi512ELi8ELi4ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type2ELS0_2ELb0EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb0EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill', + '_ZL21gated_linear_attn_f32ILi128EEviiiifPKfS1_S1_S1_S1_Pf', +} + + +class RemarkLoader(yaml.SafeLoader): + pass + + +def construct_remark(loader, tag, node): + return loader.construct_mapping(node) + + +RemarkLoader.add_multi_constructor('!', construct_remark) + + +def format_name(name): + if demangle is None: + return name + try: + demangled = demangle(name) + except Exception: + return name + return f'{name} [{demangled}]' if demangled is not None else name + + +def parse_remarks(filepath): + path = Path(filepath) + files = sorted(path.rglob('*.opt.yaml')) if path.is_dir() else [path] if path.is_file() else [] + if not files: + raise ValueError(f'No optimization records found in {filepath}') + + functions = defaultdict(lambda: {'vgprs': [], 'occupancy': [], 'vgpr_spill': [], 'sgpr_spill': [], 'location': ''}) + for file in files: + with file.open('r') as f: + for remark in yaml.load_all(f, Loader=RemarkLoader): + if not isinstance(remark, dict) or remark.get('Pass') != 'kernel-resource-usage': + continue + key = remark.get('Name') + if key not in REMARK_NAMES: + continue + name = remark.get('Function') + if not isinstance(name, str) or not name: + continue + values = [arg[key] for arg in remark.get('Args', []) if isinstance(arg, dict) and key in arg] + if len(values) != 1: + raise ValueError(f'Invalid {key} remark for {name} in {file}') + try: + value = int(values[0]) + except (TypeError, ValueError) as exc: + raise ValueError(f'Invalid {key} value for {name} in {file}') from exc + cast(list[int], functions[name][REMARK_NAMES[key]]).append(value) + location = remark.get('DebugLoc') or {} + if location.get('File') and location.get('Line'): + functions[name]['location'] = f"{Path(location['File']).name}:{location['Line']}" + + if not functions: + raise ValueError(f'No kernel resource usage remarks found in {filepath}') + return functions + + +def load_ignore_file(filepath): + ignored = set() + with open(filepath, 'r') as f: + for line in f: + name = line.strip() + if name and not name.startswith('#'): + ignored.add(name) + return ignored + + +def check_vgpr(functions, filepath, rows=None): + found_issues = False + for ignored in (True, False): + for name, data in sorted(functions.items()): + if (name in IGNORED_VGPR) != ignored: + continue + vgprs = data['vgprs'][-1] if data['vgprs'] else 0 + spill = data['vgpr_spill'][-1] if data['vgpr_spill'] else 0 + total_vgprs = vgprs + spill + if total_vgprs <= 256: + continue + location = data['location'] or filepath + suffix = ' [IGNORED]' if ignored else ' ' + message = f"{location}: {format_name(name)} - Total VGPRs: {total_vgprs} ({vgprs} + {spill}){suffix}" + blocking = RULES['vgpr_limit'] == 'blocking' + color = '91' if blocking else '93' + print(message if ignored else f'\033[{color}m{message}\033[0m') # noqa: NP100 + if not ignored: + found_issues |= blocking + if rows is not None: + rows.append(('vgpr_total', name, location, 256, total_vgprs, 'regression' if blocking else 'warning')) + return int(found_issues) + + +def worst(values, metric): + return min(values) if metric == 'occupancy' else max(values) + + +def compare_metric(base, pr, names, metric, tolerance=0): + regressions = [] + gains = [] + for name in names: + if not base[name][metric] or not pr[name][metric]: + continue + base_val = worst(base[name][metric], metric) + pr_val = worst(pr[name][metric], metric) + if metric == 'occupancy': + if pr_val < base_val - tolerance: + regressions.append((name, base_val, pr_val)) + elif pr_val > base_val: + gains.append((name, base_val, pr_val)) + else: + if pr_val > base_val: + regressions.append((name, base_val, pr_val)) + elif pr_val < base_val: + gains.append((name, base_val, pr_val)) + return regressions, gains + + +def dump_tsv(path, baseline_log, pr_log, base_count, pr_count, common_count, rows): + with open(path, 'w') as f: + f.write(f'#baseline_log\t{baseline_log}\n') + f.write(f'#pr_log\t{pr_log}\n') + f.write(f'#baseline_kernels\t{base_count}\n') + f.write(f'#pr_kernels\t{pr_count}\n') + f.write(f'#kernels_compared\t{common_count}\n') + f.write('metric\tkernel\tlocation\tbaseline\tpr\tstatus\n') + for row in rows: + f.write('\t'.join(str(col) for col in row) + '\n') + + +def check_comparison(base, pr, baseline_log, pr_log, tolerance=0, ignored=None, dump=None): + ignored = ignored or set() + base_names = {name for name, data in base.items() if any(data[metric] for metric in METRICS)} - ignored + pr_names = {name for name, data in pr.items() if any(data[metric] for metric in METRICS)} - ignored + common = base_names & pr_names + added = pr_names - base_names + removed = base_names - pr_names + locations = {name: data['location'] for name, data in base.items()} + locations.update({name: data['location'] for name, data in pr.items()}) + + changes = {metric: compare_metric(base, pr, common, metric, tolerance) for metric in METRICS} + issues = [] # metric, kernel, baseline, PR, severity, extra details + for metric, rule in (('vgpr_spill', 'vgpr_spill_increase'), ('sgpr_spill', 'sgpr_spill_increase')): + for name, base_val, pr_val in changes[metric][0]: + issues.append((metric, name, base_val, pr_val, RULES[rule], '')) + for name, base_val, pr_val in changes['occupancy'][0]: + base_vgprs = worst(base[name]['vgprs'], 'vgprs') if base[name]['vgprs'] else None + pr_vgprs = worst(pr[name]['vgprs'], 'vgprs') if pr[name]['vgprs'] else None + increasing = base_vgprs is not None and pr_vgprs is not None and pr_vgprs > base_vgprs + rule = 'occupancy_vgpr_increase' if increasing else 'occupancy_drop' + detail = f', VGPRs: {base_vgprs} -> {pr_vgprs}' if increasing else '' + issues.append(('occupancy', name, base_val, pr_val, RULES[rule], detail)) + + print(f'Kernels compared: {len(common)} (baseline {len(base_names)}, PR {len(pr_names)})') # noqa: NP100 + print(f'Added kernels: {len(added)}, removed kernels: {len(removed)}') # noqa: NP100 + for severity, color, label in (('blocking', '91', 'REGRESSION'), ('warning', '93', 'WARNING')): + for metric, name, base_val, pr_val, level, detail in sorted(issues): + if level == severity: + print(f"\033[{color}m{locations[name]}: {name} - {METRIC_NAMES[metric]}: {base_val} -> {pr_val}{detail} ({label})\033[0m") # noqa: NP100 + for metric in METRICS: + for name, base_val, pr_val in sorted(changes[metric][1]): + print(f"\033[92m{locations[name]}: {name} - {METRIC_NAMES[metric]}: {base_val} -> {pr_val} (improved)\033[0m") # noqa: NP100 + for name in sorted(added): + print(f'note: new kernel in PR: {name}') # noqa: NP100 + for name in sorted(removed): + print(f'note: kernel only in baseline: {name}') # noqa: NP100 + + # Check the absolute VGPR limit as well, even for kernels excluded from comparisons. + vgpr_rows = [] + vgpr_failed = check_vgpr(pr, pr_log, vgpr_rows) + if dump: + rows = [] + for metric, name, base_val, pr_val, severity, _ in issues: + rows.append((metric, name, locations[name], base_val, pr_val, 'regression' if severity == 'blocking' else 'warning')) + for metric in METRICS: + for name, base_val, pr_val in sorted(changes[metric][1]): + rows.append((metric, name, locations[name], base_val, pr_val, 'improved')) + rows.extend(vgpr_rows) + for name in sorted(added): + for metric in METRICS: + if pr[name][metric]: + rows.append((metric, name, locations[name], '', worst(pr[name][metric], metric), 'added')) + for name in sorted(removed): + for metric in METRICS: + if base[name][metric]: + rows.append((metric, name, locations[name], worst(base[name][metric], metric), '', 'removed')) + dump_tsv(dump, baseline_log, pr_log, len(base_names), len(pr_names), len(common), rows) + print(f'Deltas written to {dump}') # noqa: NP100 + + blocking = sum(severity == 'blocking' for _, _, _, _, severity, _ in issues) + warnings = sum(severity == 'warning' for _, _, _, _, severity, _ in issues) + blocking += sum(row[5] == 'regression' for row in vgpr_rows) + warnings += sum(row[5] == 'warning' for row in vgpr_rows) + if blocking or warnings: + print(f'{blocking} blocking regression(s), {warnings} warning(s)') # noqa: NP100 + else: + print('No regressions found') # noqa: NP100 + return int(bool(blocking or vgpr_failed)) + + +def read_deltas(filepath): + meta = {} + rows = [] + try: + with open(filepath, 'r') as f: + for line in f: + line = line.rstrip('\n') + if line.startswith('#'): + parts = line[1:].split('\t') + if len(parts) == 2: + meta[parts[0].strip()] = parts[1].strip() + continue + cols = line.split('\t') + if len(cols) == 6 and cols[0] in REPORT_METRICS: + rows.append(cols) + except FileNotFoundError: + print(f"Error: File {filepath} not found", file=sys.stderr) # noqa: NP100 + sys.exit(1) + return meta, rows + + +def write_report(path, meta, rows): + tables = {} # (metric, status) -> list of (kernel, location, baseline, pr) + added = {} # kernel -> [location, {metric: value}] + removed = {} # kernel -> [location, {metric: value}] + for metric, kernel, location, baseline, pr, status in rows: + if status in ('regression', 'warning', 'improved'): + tables.setdefault((metric, status), []).append((kernel, location, baseline, pr)) + elif status == 'added': + added.setdefault(kernel, [location, {}])[1][metric] = pr + elif status == 'removed': + removed.setdefault(kernel, [location, {}])[1][metric] = baseline + + with open(path, 'w') as f: + f.write('# HIP kernel metrics comparison\n\n') + f.write(f"- Baseline: `{meta.get('baseline_log', '?')}`\n") + f.write(f"- PR: `{meta.get('pr_log', '?')}`\n\n") + f.write(f"Kernels compared: {meta.get('kernels_compared', '?')} " + f"(baseline {meta.get('baseline_kernels', '?')}, PR {meta.get('pr_kernels', '?')}). " + f"Added kernels: {len(added)}, removed kernels: {len(removed)}.\n\n") + + for metric in REPORT_METRICS: + name = METRIC_NAMES[metric] + statuses = (('regression', 'regressions'), ('improved', 'improvements')) + if metric == 'occupancy': + statuses = (('regression', 'regressions'), ('warning', 'warnings'), ('improved', 'improvements')) + elif metric == 'vgpr_total': + statuses = (('regression', 'regressions'), ('warning', 'warnings')) + if metric == 'vgpr_total': + f.write('The baseline value for total VGPRs is the 256-register threshold.\n\n') + for status, title in statuses: + entries = tables.get((metric, status), []) + f.write(f'## {name} {title} ({len(entries)})\n\n') + if entries: + f.write('| Location | Kernel | Baseline | PR |\n|---|---|---|---|\n') + for kernel, location, baseline, pr in entries: + f.write(f'| {location} | `{kernel}` | {baseline} | {pr} |\n') + else: + f.write('None.\n') + f.write('\n') + + for title, kernels in (('Added kernels', added), ('Removed kernels', removed)): + f.write(f'## {title} ({len(kernels)})\n\n') + if kernels: + f.write('| Location | Kernel | Occupancy | VGPRs Spill | SGPRs Spill |\n|---|---|---|---|---|\n') + for kernel in sorted(kernels): + location, values = kernels[kernel] + occupancy = values.get('occupancy', '') + vspill = values.get('vgpr_spill', '') + sspill = values.get('sgpr_spill', '') + f.write(f'| {location} | `{kernel}` | {occupancy} | {vspill} | {sspill} |\n') + else: + f.write('None.\n') + f.write('\n') + + +def main(): + parser = argparse.ArgumentParser(description='Check HIP kernel resource usage and generate reports') + commands = parser.add_subparsers(dest='command', required=True) + vgpr = commands.add_parser('vgpr', help='check the 256 VGPR limit') + vgpr.add_argument('records', help='directory of Clang .opt.yaml files') + compare = commands.add_parser('compare', help='compare occupancy and register spills') + compare.add_argument('baseline_log', help='baseline optimization records') + compare.add_argument('pr_log', help='PR optimization records') + compare.add_argument('-t', '--tolerance', type=int, default=0, help='allowed occupancy drop in waves/SIMD') + compare.add_argument('--ignore', help='file with kernel symbols to exclude, one per line') + compare.add_argument('--dump', help='write all deltas to a TSV file') + report = commands.add_parser('report', help='generate the Markdown report from a TSV dump') + report.add_argument('deltas_tsv', help='TSV deltas from compare --dump') + report.add_argument('-o', '--output', default='hip-kernel-metrics-report.md', help='output Markdown file') + args = parser.parse_args() + try: + if args.command == 'vgpr': + return check_vgpr(parse_remarks(args.records), args.records) + if args.command == 'compare': + ignored = load_ignore_file(args.ignore) if args.ignore else set() + return check_comparison(parse_remarks(args.baseline_log), parse_remarks(args.pr_log), args.baseline_log, args.pr_log, args.tolerance, ignored, args.dump) + meta, rows = read_deltas(args.deltas_tsv) + write_report(args.output, meta, rows) + print(f'Report written to {args.output}') # noqa: NP100 + return 0 + except (OSError, ValueError, yaml.YAMLError) as exc: + print(f'Error: {exc}', file=sys.stderr) # noqa: NP100 + return 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/scripts/hip/gcn-cdna-vgpr-check.py b/scripts/hip/gcn-cdna-vgpr-check.py deleted file mode 100644 index d6a7fc45009d..000000000000 --- a/scripts/hip/gcn-cdna-vgpr-check.py +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/env python3 - -import sys -from collections import defaultdict -import re - -try: - from itanium_demangler import parse as demangle # ty: ignore[import-not-found] -except ImportError: - demangle = None - - -def format_name(name): - if demangle is None: - return name - try: - demangled = demangle(name) - except Exception: - return name - return f"{name} [{demangled}]" if demangled is not None else name - - -def parse_log_file(filepath): - functions = defaultdict(lambda: {'vgprs': 0, 'spill': 0, 'location': ''}) - func_stack = [] - - try: - with open(filepath, 'r') as f: - for line in f: - # Match function name lines - func_match = re.search(r'remark: ([^:]+):(\d+):\d+: Function Name: (\S+)', line) - if func_match: - location = func_match.group(1) + ':' + func_match.group(2) - func_name = func_match.group(3) - # Extract just the filename and line number - parts = location.split('/') - short_location = parts[-1] if len(parts) > 0 else location - functions[func_name]['location'] = short_location - # Push function onto stack with its location - func_stack.append({'name': func_name, 'location': location}) - continue - - # Match VGPR usage lines (only if we have functions in stack) - vgpr_match = re.search(r'remark: ([^:]+):(\d+):\d+:\s+VGPRs: (\d+)', line) - if vgpr_match: - location = vgpr_match.group(1) + ':' + vgpr_match.group(2) - # Find the most recent function with matching location - for i in range(len(func_stack) - 1, -1, -1): - if func_stack[i]['location'] == location: - functions[func_stack[i]['name']]['vgprs'] = int(vgpr_match.group(3)) - break - continue - - spill_match = re.search(r'remark: ([^:]+):(\d+):\d+:\s+VGPRs Spill: (\d+)', line) - if spill_match: - location = spill_match.group(1) + ':' + spill_match.group(2) - # Find the most recent function with matching location - for i in range(len(func_stack) - 1, -1, -1): - if func_stack[i]['location'] == location: - functions[func_stack[i]['name']]['spill'] = int(spill_match.group(3)) - break - continue - except FileNotFoundError: - print(f"Error: File {filepath} not found", file=sys.stderr) # noqa: NP100 - sys.exit(1) - - return functions - - -def main(): - if len(sys.argv) < 2: - print("Usage: ./vgpr_check.py ", file=sys.stderr) # noqa: NP100 - sys.exit(1) - - log_file = sys.argv[1] - ignored = { - '_ZL13rwkv_wkv7_f32ILi128EEviiiiPKfS1_S1_S1_S1_S1_S1_Pf', - '_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb0ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb1ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb0ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb1ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb0ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb1ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb0ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb1ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb0ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb1ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb0ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb1ELb0ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_f16ILi576ELi512ELi16ELi4ELb0ELb1ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi16ELb0ELb1ELb1EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi32ELb0ELb1ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi16ELb0ELb1ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi32ELb0ELb1ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_f16ILi576ELi512ELi4ELi16ELb0ELb1ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_f16ILi576ELi512ELi8ELi4ELb0ELb1ELb0EEvPKcS1_S1_S1_S1_PKiS3_PfP15HIP_vector_typeIfLj2EEffffjfiS5_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type2ELS0_2ELb0EEvPKcS2_S2_S2_S2_PKiS4_PfP15HIP_vector_typeIfLj2EEffffjfiS6_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb0EEvPKcS2_S2_S2_S2_PKiS4_PfP15HIP_vector_typeIfLj2EEffffjfiS6_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb1EEvPKcS2_S2_S2_S2_PKiS4_PfP15HIP_vector_typeIfLj2EEffffjfiS6_IjLj3EEiiiiiiiiiiiliiliiiill', - '_ZL21gated_linear_attn_f32ILi128EEviiiifPKfS1_S1_S1_S1_Pf', - } - - functions = parse_log_file(log_file) - found_issues = False - - # First print all ignored functions (deduplicated) - printed_ignored = set() - for func_name, data in sorted(functions.items()): - total_vgprs = int(data['vgprs']) + int(data['spill']) - if total_vgprs > 256 and func_name in ignored and func_name not in printed_ignored: - location = data.get('location', log_file) - print(f"{location}: {format_name(func_name)} - Total VGPRs: {total_vgprs} ({data['vgprs']} + {data['spill']}) [IGNORED]") # noqa: NP100 - printed_ignored.add(func_name) - - # Then print new functions with issues in red - for func_name, data in sorted(functions.items()): - total_vgprs = int(data['vgprs']) + int(data['spill']) - if total_vgprs > 256 and func_name not in ignored: - status = "[IGNORED]" if func_name in ignored else "" - location = data.get('location', log_file) - # Print in red if not ignored - color_code = "\033[91m" if func_name not in ignored else "" - reset_code = "\033[0m" if func_name not in ignored else "" - print(f"{color_code}{location}: {format_name(func_name)} - Total VGPRs: {total_vgprs} ({data['vgprs']} + {data['spill']}) {status}{reset_code}") # noqa: NP100 - if func_name not in ignored: - found_issues = True - - sys.exit(1 if found_issues else 0) - - -if __name__ == "__main__": - main() diff --git a/scripts/hip/test_gcn_cdna_metrics.py b/scripts/hip/test_gcn_cdna_metrics.py new file mode 100644 index 000000000000..aae646eba2a0 --- /dev/null +++ b/scripts/hip/test_gcn_cdna_metrics.py @@ -0,0 +1,253 @@ +#!/usr/bin/env python3 + +import importlib.util +import io +import tempfile +import unittest +from contextlib import redirect_stdout +from pathlib import Path +from unittest.mock import patch + +import yaml + +SCRIPT = Path(__file__).with_name('gcn-cdna-metrics.py') +spec = importlib.util.spec_from_file_location('gcn_cdna_metrics', SCRIPT) +if spec is None or spec.loader is None: + raise RuntimeError(f'Cannot load {SCRIPT}') +metrics = importlib.util.module_from_spec(spec) +spec.loader.exec_module(metrics) + + +def write_records(directory, filename, kernels): + path = directory / filename + path.parent.mkdir(parents=True, exist_ok=True) + with path.open('w') as f: + for name, values in kernels.items(): + for key, value in values.items(): + f.write('--- !Analysis\n') + yaml.safe_dump({'Pass': 'kernel-resource-usage', 'Name': key, 'Function': name, + 'DebugLoc': {'File': 'wkv.cu', 'Line': 69, 'Column': 1}, + 'Args': [{'String': key + ': '}, {key: str(value)}]}, f, sort_keys=False) + f.write('...\n') + return path + + +class MetricsTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.base = self.root / 'baseline' + self.pr = self.root / 'pr' + self.base.mkdir() + self.pr.mkdir() + + def compare(self, **kwargs): + with redirect_stdout(io.StringIO()) as out: + result = metrics.check_comparison(metrics.parse_remarks(self.base), metrics.parse_remarks(self.pr), + 'baseline', 'PR', **kwargs) + return result, out.getvalue() + + def test_same_source_location_does_not_swap_kernel_specializations(self): + write_records(self.pr, 'kernels.opt.yaml', {'_Zkernel64': {'NumVGPR': 64, 'VGPRSpill': 360}, + '_Zkernel128': {'NumVGPR': 64, 'VGPRSpill': 0}}) + data = metrics.parse_remarks(self.pr) + self.assertEqual(data['_Zkernel64']['vgpr_spill'], [360]) + self.assertEqual(data['_Zkernel128']['vgpr_spill'], [0]) + self.assertEqual(data['_Zkernel64']['location'], 'wkv.cu:69') + + def test_vgpr_limit_and_allowlist(self): + write_records(self.pr, 'kernels.opt.yaml', {'bad': {'NumVGPR': 255, 'VGPRSpill': 2}, + 'allowed': {'NumVGPR': 256, 'VGPRSpill': 4}, + 'good': {'NumVGPR': 256, 'VGPRSpill': 0}}) + metrics.IGNORED_VGPR.add('allowed') + self.addCleanup(metrics.IGNORED_VGPR.discard, 'allowed') + with redirect_stdout(io.StringIO()) as out: + code = metrics.check_vgpr(metrics.parse_remarks(self.pr), 'PR') + self.assertEqual(code, 1) + self.assertIn('allowed - Total VGPRs: 260 (256 + 4) [IGNORED]', out.getvalue()) + self.assertIn('bad - Total VGPRs: 257 (255 + 2)', out.getvalue()) + self.assertNotIn('good - Total VGPRs', out.getvalue()) + + def test_occupancy_spill_regressions_and_tolerance(self): + write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5, 'VGPRSpill': 0, 'SGPRSpill': 1}}) + write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'VGPRSpill': 1, 'SGPRSpill': 0}}) + code, output = self.compare() + self.assertEqual(code, 1) + self.assertIn('Occupancy [waves/SIMD]: 5 -> 4 (WARNING)', output) + self.assertIn('VGPRs Spill: 0 -> 1 (REGRESSION)', output) + self.assertIn('SGPRs Spill: 1 -> 0 (improved)', output) + code, output = self.compare(tolerance=1) + self.assertEqual(code, 1) + self.assertNotIn('Occupancy [waves/SIMD]: 5 -> 4 (WARNING)', output) + + def test_duplicate_kernel_uses_worst_per_metric(self): + write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 6, 'VGPRSpill': 0}}) + write_records(self.base, 'sub/b.opt.yaml', {'same': {'Occupancy': 5, 'VGPRSpill': 2}}) + write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 6, 'VGPRSpill': 1}}) + code, output = self.compare() + self.assertEqual(code, 0) + self.assertIn('VGPRs Spill: 2 -> 1 (improved)', output) + self.assertIn('Occupancy [waves/SIMD]: 5 -> 6 (improved)', output) + + def test_added_removed_deltas_and_markdown(self): + write_records(self.base, 'a.opt.yaml', {'removed': {'Occupancy': 5, 'VGPRSpill': 2}, 'same': {'Occupancy': 4}}) + write_records(self.pr, 'a.opt.yaml', {'added': {'Occupancy': 6, 'SGPRSpill': 1}, 'same': {'Occupancy': 5}}) + tsv = self.root / 'diff.tsv' + report = self.root / 'report.md' + code, _ = self.compare(dump=tsv) + self.assertEqual(code, 0) + self.assertIn('occupancy\tadded\twkv.cu:69\t\t6\tadded', tsv.read_text()) + meta, rows = metrics.read_deltas(tsv) + metrics.write_report(report, meta, rows) + result = report.read_text() + self.assertIn('# HIP kernel metrics comparison', result) + self.assertIn('## Occupancy [waves/SIMD] improvements (1)', result) + self.assertIn('## Added kernels (1)', result) + self.assertIn('## Removed kernels (1)', result) + self.assertIn('| wkv.cu:69 | ' + chr(96) + 'same' + chr(96) + ' | 4 | 5 |', result) + + def test_ignore_only_comparison_not_vgpr(self): + write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5}}) + write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 1}}) + code, output = self.compare(ignored={'same'}) + self.assertEqual(code, 0) + self.assertIn('Kernels compared: 0', output) + + def test_vgpr_only_records_are_not_compared(self): + write_records(self.base, 'a.opt.yaml', {'vgpr_only': {'NumVGPR': 64}, 'same': {'Occupancy': 4}}) + write_records(self.pr, 'a.opt.yaml', {'vgpr_only': {'NumVGPR': 128}, 'same': {'Occupancy': 4}}) + code, output = self.compare() + self.assertEqual(code, 0) + self.assertIn('Kernels compared: 1 (baseline 1, PR 1)', output) + + def test_occupancy_drop_with_more_vgprs_blocks(self): + write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5, 'NumVGPR': 64}}) + write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'NumVGPR': 96}}) + tsv = self.root / 'diff.tsv' + code, output = self.compare(dump=tsv) + self.assertEqual(code, 1) + self.assertIn('Occupancy [waves/SIMD]: 5 -> 4, VGPRs: 64 -> 96 (REGRESSION)', output) + self.assertIn('1 blocking regression(s), 0 warning(s)', output) + self.assertIn('occupancy\tsame\twkv.cu:69\t5\t4\tregression', tsv.read_text()) + + def test_occupancy_drop_with_fewer_vgprs_warns(self): + write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5, 'NumVGPR': 96}}) + write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'NumVGPR': 64}}) + tsv = self.root / 'diff.tsv' + report = self.root / 'report.md' + code, output = self.compare(dump=tsv) + self.assertEqual(code, 0) + self.assertIn('Occupancy [waves/SIMD]: 5 -> 4 (WARNING)', output) + self.assertIn('0 blocking regression(s), 1 warning(s)', output) + self.assertIn('occupancy\tsame\twkv.cu:69\t5\t4\twarning', tsv.read_text()) + meta, rows = metrics.read_deltas(tsv) + metrics.write_report(report, meta, rows) + self.assertIn('## Occupancy [waves/SIMD] warnings (1)', report.read_text()) + self.assertIn('| wkv.cu:69 | `same` | 5 | 4 |', report.read_text()) + + def test_occupancy_drop_without_vgpr_increase_warns(self): + write_records(self.base, 'a.opt.yaml', {'unchanged': {'Occupancy': 5, 'NumVGPR': 64}, + 'missing': {'Occupancy': 5}}) + write_records(self.pr, 'a.opt.yaml', {'unchanged': {'Occupancy': 4, 'NumVGPR': 64}, + 'missing': {'Occupancy': 4}}) + code, output = self.compare() + self.assertEqual(code, 0) + self.assertEqual(output.count('(WARNING)'), 2) + self.assertIn('0 blocking regression(s), 2 warning(s)', output) + + def test_vgpr_and_sgpr_spill_increases_block_independently(self): + write_records(self.base, 'a.opt.yaml', {'vgpr': {'VGPRSpill': 0}, 'sgpr': {'SGPRSpill': 0}}) + write_records(self.pr, 'a.opt.yaml', {'vgpr': {'VGPRSpill': 1}, 'sgpr': {'SGPRSpill': 1}}) + code, output = self.compare() + self.assertEqual(code, 1) + self.assertIn('vgpr - VGPRs Spill: 0 -> 1 (REGRESSION)', output) + self.assertIn('sgpr - SGPRs Spill: 0 -> 1 (REGRESSION)', output) + self.assertIn('2 blocking regression(s), 0 warning(s)', output) + + def test_vgpr_limit_blocks_comparison_and_appears_in_report(self): + write_records(self.base, 'a.opt.yaml', {'same': {'NumVGPR': 256, 'VGPRSpill': 0}}) + write_records(self.pr, 'a.opt.yaml', {'same': {'NumVGPR': 256, 'VGPRSpill': 1}}) + tsv = self.root / 'diff.tsv' + report = self.root / 'report.md' + code, output = self.compare(dump=tsv) + self.assertEqual(code, 1) + self.assertIn('Total VGPRs: 257 (256 + 1)', output) + self.assertIn('2 blocking regression(s), 0 warning(s)', output) + self.assertIn('vgpr_total\tsame\twkv.cu:69\t256\t257\tregression', tsv.read_text()) + meta, rows = metrics.read_deltas(tsv) + metrics.write_report(report, meta, rows) + self.assertIn('## Total VGPRs (limit 256) regressions (1)', report.read_text()) + self.assertIn('| wkv.cu:69 | `same` | 256 | 257 |', report.read_text()) + + def test_existing_vgpr_allowlist_preserves_comparison_checks(self): + write_records(self.base, 'a.opt.yaml', {'allowed': {'NumVGPR': 255, 'VGPRSpill': 3}}) + write_records(self.pr, 'a.opt.yaml', {'allowed': {'NumVGPR': 255, 'VGPRSpill': 4}}) + metrics.IGNORED_VGPR.add('allowed') + self.addCleanup(metrics.IGNORED_VGPR.discard, 'allowed') + code, output = self.compare() + self.assertEqual(code, 1) + self.assertIn('Total VGPRs: 259 (255 + 4) [IGNORED]', output) + self.assertIn('VGPRs Spill: 3 -> 4 (REGRESSION)', output) + self.assertIn('1 blocking regression(s), 0 warning(s)', output) + + def test_comparison_ignore_does_not_disable_vgpr_limit(self): + write_records(self.base, 'a.opt.yaml', {'ignored': {'NumVGPR': 256, 'VGPRSpill': 0}}) + write_records(self.pr, 'a.opt.yaml', {'ignored': {'NumVGPR': 256, 'VGPRSpill': 1}}) + code, output = self.compare(ignored={'ignored'}) + self.assertEqual(code, 1) + self.assertIn('Kernels compared: 0 (baseline 0, PR 0)', output) + self.assertIn('Total VGPRs: 257 (256 + 1)', output) + + def test_occupancy_tolerance_applies_to_blocking_rule(self): + write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5, 'NumVGPR': 64}}) + write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'NumVGPR': 96}}) + code, output = self.compare(tolerance=1) + self.assertEqual(code, 0) + self.assertNotIn('Occupancy [waves/SIMD]: 5 -> 4', output) + self.assertIn('No regressions found', output) + + def test_all_rules_complete_and_return_error_after_dump(self): + write_records(self.base, 'a.opt.yaml', {'occb': {'Occupancy': 5, 'NumVGPR': 64}, + 'occw': {'Occupancy': 5, 'NumVGPR': 80}, + 'spill': {'SGPRSpill': 0}}) + write_records(self.pr, 'a.opt.yaml', {'occb': {'Occupancy': 4, 'NumVGPR': 96}, + 'occw': {'Occupancy': 4, 'NumVGPR': 64}, + 'spill': {'SGPRSpill': 1}}) + tsv = self.root / 'diff.tsv' + code, output = self.compare(dump=tsv) + self.assertEqual(code, 1) + self.assertIn('occb - Occupancy [waves/SIMD]: 5 -> 4, VGPRs: 64 -> 96 (REGRESSION)', output) + self.assertIn('occw - Occupancy [waves/SIMD]: 5 -> 4 (WARNING)', output) + self.assertIn('spill - SGPRs Spill: 0 -> 1 (REGRESSION)', output) + self.assertIn('2 blocking regression(s), 1 warning(s)', output) + self.assertTrue(tsv.is_file()) + + def test_cli_returns_success_for_warnings_and_generates_report_after_failure(self): + write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5, 'NumVGPR': 96}}) + write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'NumVGPR': 64}}) + tsv = self.root / 'diff.tsv' + report = self.root / 'report.md' + argv = ['gcn-cdna-metrics.py', 'compare', str(self.base), str(self.pr), '--dump', str(tsv)] + with patch('sys.argv', argv), redirect_stdout(io.StringIO()): + self.assertEqual(metrics.main(), 0) + self.assertIn('warning', tsv.read_text()) + + write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'NumVGPR': 128}}) + with patch('sys.argv', argv), redirect_stdout(io.StringIO()): + self.assertEqual(metrics.main(), 1) + self.assertIn('regression', tsv.read_text()) + with patch('sys.argv', ['gcn-cdna-metrics.py', 'report', str(tsv), '-o', str(report)]), redirect_stdout(io.StringIO()): + self.assertEqual(metrics.main(), 0) + self.assertIn('## Occupancy [waves/SIMD] regressions (1)', report.read_text()) + + def test_missing_or_invalid_records_fail(self): + with self.assertRaisesRegex(ValueError, 'No optimization records'): + metrics.parse_remarks(self.pr) + write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 'invalid'}}) + with self.assertRaisesRegex(ValueError, 'Invalid Occupancy value'): + metrics.parse_remarks(self.pr) + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/snapdragon/ggml-hexagon-trace.py b/scripts/snapdragon/ggml-hexagon-trace.py index 308591b83f80..b9cae66fb37f 100755 --- a/scripts/snapdragon/ggml-hexagon-trace.py +++ b/scripts/snapdragon/ggml-hexagon-trace.py @@ -414,10 +414,107 @@ def write_trace_packet_to_file(f, packet_bytes): # Write as field 1 of top-level Trace message f.write(pb_length_delimited(1, packet_bytes)) + # --- End Protobuf Encoder --- +MERGE_DMA_DEFAULT_DEPTH = 8 + + +def merge_dma_events(completed_events: List[Dict[str, Any]], max_depth: int) -> List[Dict[str, Any]]: + other_events: List[Dict[str, Any]] = [] + dma_by_thread: Dict[Any, List[Dict[str, Any]]] = defaultdict(list) + + for e in completed_events: + if normalize_event_name(e['event'], e['info']) == "DMA": + dma_by_thread[(e['device'], e['thread'])].append(e) + else: + other_events.append(e) + + if not dma_by_thread: + return completed_events -def generate_perfetto_trace(filtered_ops, trace_events, output_path): + merged_dma: List[Dict[str, Any]] = [] + merged_events_cnt = 0 + merged_bursts_cnt = 0 + + for th_events in dma_by_thread.values(): + th_events.sort(key=lambda e: (e['ts_ns'], e['ts_ns'] + e['dur_ns'])) + + clusters: List[List[Dict[str, Any]]] = [] + cur_cluster = [th_events[0]] + cur_end = th_events[0]['ts_ns'] + th_events[0]['dur_ns'] + + for e in th_events[1:]: + e_end = e['ts_ns'] + e['dur_ns'] + if e['ts_ns'] < cur_end: + cur_cluster.append(e) + if e_end > cur_end: + cur_end = e_end + else: + clusters.append(cur_cluster) + cur_cluster = [e] + cur_end = e_end + clusters.append(cur_cluster) + + for cluster in clusters: + if len(cluster) <= max_depth: + merged_dma.extend(cluster) + continue + + # (-1) sorts before (+1) at equal timestamps so back-to-back slices reuse slots + endpoints = [] + for e in cluster: + endpoints.append((e['ts_ns'], 1)) + endpoints.append((e['ts_ns'] + e['dur_ns'], -1)) + endpoints.sort() + + depth = 0 + peak_depth = 0 + for _, delta in endpoints: + depth += delta + if depth > peak_depth: + peak_depth = depth + + if peak_depth <= max_depth: + merged_dma.extend(cluster) + continue + + start_ts = cluster[0]['ts_ns'] + end_ts = max(e['ts_ns'] + e['dur_ns'] for e in cluster) + first = cluster[0] + line_nums = [e['line_num'] for e in cluster if e.get('line_num') is not None] + + merged_evt: Dict[str, Any] = { + 'thread': first['thread'], + 'event': first['event'], + 'info': first['info'], + 'start_cyc': min(e['start_cyc'] for e in cluster), + 'end_cyc': max(e['end_cyc'] for e in cluster), + 'ts_ns': start_ts, + 'dur_ns': max(end_ts - start_ts, 1), + 'line_num': min(line_nums) if line_nums else None, + 'device': first['device'], + 'merged_count': len(cluster), + 'max_depth': peak_depth, + } + if any(e.get('missing_start') for e in cluster): + merged_evt['missing_start'] = True + if any(e.get('missing_stop') for e in cluster): + merged_evt['missing_stop'] = True + + merged_dma.append(merged_evt) + merged_events_cnt += len(cluster) + merged_bursts_cnt += 1 + + if merged_bursts_cnt > 0: + logger.info(f"Merged {merged_events_cnt} DMA events into {merged_bursts_cnt} slices (max_depth > {max_depth})") + + result = other_events + merged_dma + result.sort(key=lambda e: (e['ts_ns'], e['start_cyc'])) + return result + + +def generate_perfetto_trace(filtered_ops, trace_events, output_path, merge_dma=None): if not filtered_ops: logger.warning("No operators found after filtering.") return @@ -516,6 +613,9 @@ def generate_perfetto_trace(filtered_ops, trace_events, output_path): dur_ns = tm.dur_cycles_to_ns(e['start_cyc'], e['end_cyc'] - e['start_cyc']) e['dur_ns'] = max(dur_ns, 1) + if merge_dma is not None: + completed_events = merge_dma_events(completed_events, merge_dma) + # Identify HMX threads dynamically from HMX* events hmx_threads = {(e['device'], e['thread']) for e in completed_events if e['event'].startswith('HMX')} @@ -688,7 +788,10 @@ def generate_perfetto_trace(filtered_ops, trace_events, output_path): for e in completed_events: norm_name = normalize_event_name(e['event'], e['info']) if norm_name == "DMA": - name = f"DMA {e['info']}" + if 'merged_count' in e: + name = f"DMA x{e['merged_count']}" + else: + name = f"DMA {e['info']}" elif norm_name == "FENCE": name = f"FENCE {e['info']}" if e.get('info') is not None and e['info'] != 0 else "FENCE" else: @@ -702,6 +805,9 @@ def generate_perfetto_trace(filtered_ops, trace_events, output_path): debug_annots.append(make_debug_annotation("line", int_val=e['line_num'])) if norm_name == "FENCE" and e.get('info') is not None: debug_annots.append(make_debug_annotation("seq", int_val=e['info'])) + elif norm_name == "DMA" and 'merged_count' in e: + debug_annots.append(make_debug_annotation("count", int_val=e['merged_count'])) + debug_annots.append(make_debug_annotation("max_depth", int_val=e['max_depth'])) elif norm_name == "DMA" and e.get('info') is not None: debug_annots.append(make_debug_annotation("channel", int_val=e['info'])) elif e.get('info') is not None and e['info'] != 0: @@ -731,12 +837,35 @@ def main(): parser.add_argument("-o", "--output", default="optrace.perfetto-trace", help="Output trace file path (default: optrace.perfetto-trace)") parser.add_argument("--filter", type=str, help="Regex filter matching against the original profile-op line") parser.add_argument("--device", type=str, help="Device to filter by (e.g. HTP0, HTP0:0) or 'split' to generate separate files per device") + parser.add_argument("--merge-dma", type=int, nargs="?", const=MERGE_DMA_DEFAULT_DEPTH, default=None, metavar="MAX_DEPTH", + help=f"Merge overlapping DMA bursts deeper than MAX_DEPTH into a single slice (default: {MERGE_DMA_DEFAULT_DEPTH}, use 1 to merge all)") group = parser.add_mutually_exclusive_group() group.add_argument("--head", type=int, help="Limit to first N ops") group.add_argument("--tail", type=int, help="Limit to last N ops") - args = parser.parse_args() + # Prevent nargs='?' on --merge-dma from consuming the positional logfile when no integer follows + raw_args = sys.argv[1:] + norm_args = [] + i = 0 + while i < len(raw_args): + if raw_args[i] == "--": + norm_args.extend(raw_args[i:]) + break + if raw_args[i] == "--merge-dma": + if i + 1 < len(raw_args) and re.fullmatch(r"-?\d+", raw_args[i + 1]): + norm_args.append(f"--merge-dma={raw_args[i + 1]}") + i += 2 + continue + norm_args.append(f"--merge-dma={MERGE_DMA_DEFAULT_DEPTH}") + i += 1 + continue + norm_args.append(raw_args[i]) + i += 1 + + args = parser.parse_args(norm_args) + if args.merge_dma is not None and args.merge_dma < 1: + parser.error("--merge-dma MAX_DEPTH must be >= 1") logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stdout) op_filter_re = None @@ -814,9 +943,9 @@ def main(): dev_ops = [op for op in ops if device_matches(op['device'], dev)] dev_traces = [t for t in traces if device_matches(t['device'], dev)] out_path = get_split_output_path(args.output, dev) - generate_perfetto_trace(dev_ops, dev_traces, out_path) + generate_perfetto_trace(dev_ops, dev_traces, out_path, merge_dma=args.merge_dma) else: - generate_perfetto_trace(ops, traces, args.output) + generate_perfetto_trace(ops, traces, args.output, merge_dma=args.merge_dma) if __name__ == "__main__": diff --git a/scripts/snapdragon/run.py b/scripts/snapdragon/run.py index 91b39a3f7473..88b70ef96c79 100755 --- a/scripts/snapdragon/run.py +++ b/scripts/snapdragon/run.py @@ -20,6 +20,7 @@ "GGML_HEXAGON_PROFILE", "GGML_HEXAGON_NHVX", "GGML_HEXAGON_NHMX", + "GGML_HEXAGON_POWER_MODE", "GGML_HEXAGON_HOSTBUF", "GGML_HEXAGON_DMA64", "GGML_HEXAGON_OPBATCH", @@ -27,12 +28,14 @@ "GGML_HEXAGON_OPPOLL", "GGML_HEXAGON_OPFILTER", "GGML_HEXAGON_OPFUSION", + "GGML_HEXAGON_OPLOWER", "GGML_HEXAGON_RT_REPACK", "GGML_HEXAGON_VMEM", + "GGML_HEXAGON_VTCM_SIZE", "GGML_HEXAGON_MBUF", "GGML_HEXAGON_MM_SELECT", "GGML_HEXAGON_FA_SELECT", - "GGML_HEXAGON_FA_HEAD_SPLIT", + "GGML_HEXAGON_FA_SPLIT", "GGML_HEXAGON_LI_SELECT", "GGML_HEXAGON_GDN_SELECT", "GGML_HEXAGON_SSM_SELECT", @@ -212,15 +215,16 @@ def main(): parser.add_argument("--hex-dma64", nargs="?", const="1", help="Enable (1) or disable (0) 64-bit DMA for model weights (GGML_HEXAGON_DMA64)") parser.add_argument("--hex-opbatch", help="Maximum number of operations to batch into a single HTP execution (GGML_HEXAGON_OPBATCH)") parser.add_argument("--hex-opqueue", help="Size of the asynchronous NPU operation queue (GGML_HEXAGON_OPQUEUE)") - parser.add_argument("--hex-oppoll", default="1", help="Enable (1) or Disable (0) polling for NPU opbatch completion (GGML_HEXAGON_OPPOLL) (default: 1)") + parser.add_argument("--hex-oppoll", default=None, help="NPU opbatch polling: 0=block, 1=poll, >1=hybrid poll budget in ms (GGML_HEXAGON_OPPOLL)") parser.add_argument("--hex-opfilter", help="Regex pattern to filter/select which operators are offloaded to NPU (GGML_HEXAGON_OPFILTER)") parser.add_argument("--hex-opfusion", help="NPU graph node fusion optimization level (0: disabled, 1: enabled) (GGML_HEXAGON_OPFUSION)") - parser.add_argument("--hex-rt-repack", help="Runtime weight repacking mode (0: disabled, 1: quantized only, 2: always) (GGML_HEXAGON_RT_REPACK)") + parser.add_argument("--hex-oplower", help="NPU graph FP16 activation lowering (0: disabled, 1: enabled) (GGML_HEXAGON_OPLOWER)") + parser.add_argument("--hex-rt-repack", help="Runtime weight repacking mode (0: disabled, 1: all tileable weights) (GGML_HEXAGON_RT_REPACK)") parser.add_argument("--hex-vmem", help="Maximum NPU VMEM size limit in MB to allocate (GGML_HEXAGON_VMEM)") parser.add_argument("--hex-mbuf", help="Host buffer size limits in MB (supports K/M/G suffix): [,[,]] (default: 512,1024,0) (GGML_HEXAGON_MBUF)") - parser.add_argument("--hex-mm-select", help="Select MUL_MAT and MUL_MAT_ID kernel (GGML_HEXAGON_MM_SELECT) 2:HMX,1:HVX,0:disable") - parser.add_argument("--hex-fa-select", help="Select Flash Attention kernel (GGML_HEXAGON_FA_SELECT) 2:HMX,1:HVX,0:disable") - parser.add_argument("--hex-fa-head-split", help="Enable (1) or disable (0) head-parallel flash_attn partitioning (GGML_HEXAGON_FA_HEAD_SPLIT)") + parser.add_argument("--hex-mm-select", help="Select MUL_MAT and MUL_MAT_ID kernel (GGML_HEXAGON_MM_SELECT) 4:HMX-W8A8,3:HMX-W8A8-hybrid,2:HMX,1:HVX,0:disable") + parser.add_argument("--hex-fa-select", help="Select Flash Attention kernel (GGML_HEXAGON_FA_SELECT) 3:HMX-W8A8,2:HMX,1:HVX,0:disable") + parser.add_argument("--hex-fa-split", "--hex-fa-head-split", dest="hex_fa_split", help="Enable (1) or disable (0) Flash Attention head/team split (GGML_HEXAGON_FA_SPLIT)") parser.add_argument("--hex-li-select", help="Select Lightning Indexer kernel (GGML_HEXAGON_LI_SELECT) 2:HMX,1:HVX,0:disable") parser.add_argument("--hex-gdn-select", help="Select Gated Delta Net kernel (GGML_HEXAGON_GDN_SELECT) 2:HMX,1:HVX,0:disable") parser.add_argument("--hex-ssm-select", help="Select SSM Scan kernel (GGML_HEXAGON_SSM_SELECT) 2:HMX,1:HVX,0:disable") @@ -371,12 +375,13 @@ def set_env(env_name, opt_val): set_env("GGML_HEXAGON_OPPOLL", args.hex_oppoll) set_env("GGML_HEXAGON_OPFILTER", args.hex_opfilter) set_env("GGML_HEXAGON_OPFUSION", args.hex_opfusion) + set_env("GGML_HEXAGON_OPLOWER", args.hex_oplower) set_env("GGML_HEXAGON_RT_REPACK", args.hex_rt_repack) set_env("GGML_HEXAGON_VMEM", args.hex_vmem) set_env("GGML_HEXAGON_MBUF", args.hex_mbuf) set_env("GGML_HEXAGON_MM_SELECT", args.hex_mm_select) set_env("GGML_HEXAGON_FA_SELECT", args.hex_fa_select) - set_env("GGML_HEXAGON_FA_HEAD_SPLIT", args.hex_fa_head_split) + set_env("GGML_HEXAGON_FA_SPLIT", args.hex_fa_split) set_env("GGML_HEXAGON_LI_SELECT", args.hex_li_select) set_env("GGML_HEXAGON_GDN_SELECT", args.hex_gdn_select) set_env("GGML_HEXAGON_SSM_SELECT", args.hex_ssm_select) @@ -407,7 +412,7 @@ def set_env(env_name, opt_val): # Resolve executable path executable = cmd_args[0] - known_binaries = ["llama-cli", "llama-bench", "llama-completion", "llama-mtmd-cli", "test-backend-ops", "test-llama-archs"] + known_binaries = ["llama-cli", "llama-bench", "llama-completion", "llama-mtmd-cli", "llama-perplexity", "test-backend-ops", "test-llama-archs"] if executable in known_binaries: if target_type in ("android", "linux"): resolved_exec = f"./bin/{executable}" diff --git a/scripts/sync-ggml.last b/scripts/sync-ggml.last index fdc4bbc9a093..7ab1de63728e 100644 --- a/scripts/sync-ggml.last +++ b/scripts/sync-ggml.last @@ -1 +1 @@ -2ca32666e16586ff4e8008b8c92f2e534b8e4f51 +bb877c0c51f38c52ee2d5e41d58e3d0c20f3fed4 diff --git a/skills/ui-demo/SKILL.md b/skills/ui-demo/SKILL.md new file mode 100644 index 000000000000..8fc7c7319d7a --- /dev/null +++ b/skills/ui-demo/SKILL.md @@ -0,0 +1,232 @@ +--- +name: ui-demo +description: Demo, test and document a change in Llama Chat (ui/apps/chat) or Llama UI (ui/lib/ui) with the Playwright demo harness - record a video for the PR, turn the same flow into an e2e check, and capture docs videos and screenshots. Use when a UI change needs a demo video, a Playwright check, or docs media. +--- + +# Demo, test and document a UI change + +One scripted flow serves three ends: a **demo** video in the PR, a Playwright **check** in `tests/e2e`, and **docs** media. The harness is `ui/lib/demo/`, and Llama Chat's fixtures for it are in `ui/apps/chat/demo/` (read both `README.md` files once). Everything below runs from `ui/apps/chat`. + +Use it when a change in `ui/apps/chat` or `ui/lib/ui` is visible: a new or changed screen, flow or component. Skip it for refactors with no visible effect. + +AGENTS.md still applies: the contributor writes the PR description and owns the script. `demo:pr` only fills the managed `## Demo` section. + +## Pick the target + +| Change in | Record | How | +| --------------------------------- | ---------------------- | --------------------------------------------- | +| Llama Chat flow or screen | the app, on vite dev | default | +| Llama UI component (`ui/lib/ui`) | its Storybook story | `test.use({ story })` + `DEMO_STORYBOOK=ui` | +| Llama Chat component in isolation | Chat's Storybook story | `test.use({ story })` + `DEMO_STORYBOOK=chat` | + +A Storybook story is the harness page for a component: if none shows the state you need, add a story next to the others (`tests/stories/` in that package) rather than a new page. + +## Setup (once) + +```bash +cd ui/apps/chat && npm ci +``` + +```bash +npx playwright install chromium +``` + +Also `ffmpeg`, and `npm ci` in `ui/lib/ui` for Llama UI stories. `demo:pr` needs `gh` (edit rights on the PR) and, to link the video, an `hf` login plus `DEMO_STORAGE` and `DEMO_STORAGE_PUBLIC_URL` in `ui/apps/chat/.env` (see `.env.example`). + +## 1. Demo + +### Write the script + +Scripts get `test` and `expect` from `helpers.ts`. Drive the page with `demo.*` (visible cursor, human timing), assert with `expect`, set the scene with `test.use`: + +- `demo.click`, `demo.hover`, `demo.type`, `demo.press`, `demo.scroll`, `demo.pause`, `demo.caption(text, ms)` (a chip under the window), `demo.zoom(target, scale, ms)` (the camera moves onto a small detail and back), `demo.zoomIn(target, scale)` ... `demo.zoomOut()` (the camera stays on it across the actions between). +- `test.use({ settings: {...} })` seeds UI settings, `startPath: '/#/...'` starts on a route. +- Fixtures, so no real data or third-party server is needed: + - **MCP servers:** two fixture servers (Weather, Notes) are always configured; see `demo/fixtures/demo-config.ts`. + - **Conversations:** `traces: ['long-chat', 'agentic-debugging']` imports built-in chats (`demo/fixtures/traces.ts`); other names come from `DEMO_TRACES_DATASET`. + - **Models and replies:** `mockServer: { models: ['org/Model-GGUF:Q4_K_M'], reply: 'Markdown **reply**' }` answers llama-server's endpoints in the browser (`demo/fixtures/llama-server.ts`): the model list, props, load, tools and a streamed reply. Nothing reaches a server and no model loads. Use it for any demo that sends a message. + - **Stories:** `story: 'ui-forms-switch--default'`, the id from the Storybook URL (`?path=/story/`). + +Without `mockServer` the app talks to the llama-server at `DEMO_SERVER_ORIGIN` (default `:9931`, started from `build/bin/llama-server` when none runs). Sending a message there loads a model: do not do that on someone's running server without asking. + +### Shape the video + +The video is rendered from the recording, not the raw screencast: the app in a window on a Llama brand ground, camera moves over the whole stage with motion blur, captions under the window, and on a touch viewport taps in place of the cursor (see "The render" in the harness README). Write for that: + +- **One thing per video.** A PR that changes several things gets several short `test()`s, not one long walk. +- **Captions** are in the brand's voice: plain words, real numbers, no emoji, one line. `demo.caption(text, ms)` holds the caption for `ms` and the demo waits, so show it while the screen is still (before or after an action, not over one). A demo with no captions gets no caption row, and the window is larger. +- **Zooms** are for a detail too small to read in the frame. The camera aims where the target is when the zoom starts and does not follow it, so zoom after the layout settles (wait with `expect` first), and zoom out before an action that moves the target, such as sending a message. Zoom on desktop demos; a phone's UI already fills a portrait video, so leave phone demos unzoomed unless a detail is too small to read even there. +- **Phones:** `test.use({ hasTouch: true, isMobile: true, viewport: { height: 844, width: 390 } })` gives a 1080x1920 video with a phone's corners, and every click shows as a fingertip tap. +- **Dark mode:** `test.use({ colorScheme: 'dark' })` records the dark theme on the night sky. +- **Timing:** the harness adds the render's time to the test's timeout after the demo, so a demo needs no long `test.setTimeout`. + +`DEMO_POLISH_LOGO=end` adds a Llama logo card, for a video that goes out on its own; `DEMO_POLISH=0` gives the plain screencast. + +### Try it locally + +Save it as `demo/.demo.ts` (git-ignored), importing from `./helpers.ts`, and run: + +```bash +npm run demo:record -- demo/ +``` + +Add `DEMO_STORYBOOK=ui` (or `chat`) when the script has a `story`. `DEMO_POLISH=0` records faster while iterating (the render takes a few times the video's length). The mp4 lands in `demo/videos/`. Look at it before going further: a sheet of frames shows the whole flow, the camera moves and the captions at once, where one still frame misses most of it: + +```bash +ffmpeg -loglevel error -i demo/videos/.mp4 -vf "fps=2,scale=480:-1,tile=6x4" -frames:v 1 demo/videos/-sheet.png +``` + +Check that each caption is readable and on screen long enough, that every zoom lands on its detail, and that nothing is cut off at the window's edge. + +`npm run demo:codegen` opens Playwright codegen on `:5180` for a first draft of the selectors. + +### Put it in the PR + +Paste the script into the PR description as a `ts demo` block, inside the last collapsible block of Additional information: + +````md +
+Demo script + +```ts demo +test("demo", async ({ demo, page }) => { + // ... +}); +``` + +
+```` + +Push the branch first: `demo:pr` records the PR's head commit as GitHub has it. Then record it and write the `## Demo` section (between `` and ``): + +```bash +npm run demo:pr -- +``` + +It takes a few minutes, so run it in the background. The app's UI comes from the PR's head, in a temporary worktree, but the harness and fixtures come from your checkout: a PR that changes the harness itself is recorded with the harness you have checked out. Run it again after each push that changes what the videos show. + +- Each `test()` becomes its own video, shown in a table under its title. Give each test `{ annotation: { type: 'description', description: '...' } }` to get one video to a row with its description beside it, which reads better when the videos show different things (see the worked example). Group tests with their own `test.use` in `test.describe(() => { ... })`. +- In a PR block, the helpers import is replaced with `test` and `expect`, so reach fixtures through `test.use` options only. +- A PR on a fork: `DEMO_GITHUB_REPO=/llama.cpp`. A PR by someone else: read its diff and demo block, then pass `--trust `. + +## 2. Test + +Turn the same flow into a check in `tests/e2e/.e2e.ts`, which CI runs (`npm run test:e2e`) against the built app on `:8181`, with no llama-server: + +- `@playwright/test` instead of the helpers: `locator.click()` / `fill()` for `demo.*`, keep every `expect`, drop captions and pauses. +- `mockLlamaServer(page, {...})` before `page.goto`, since nothing serves the API. +- `importTraces(page, file)` and `generateTrace(name)` seed conversations, as in a demo. + +```bash +npx playwright test tests/e2e/.e2e.ts +``` + +Locally it uses the installed Chrome with its sandbox on; in CI, Playwright's Chromium. + +For a component on its own, a `play` function on its story is the check instead (as in `ui/apps/chat/tests/stories/app/PwaRefreshAlert.stories.svelte`): both packages run their stories as vitest browser tests, `npm run test:ui` in `ui/apps/chat` and `npm test` in `ui/lib/ui`. + +## 3. Document + +- **Docs videos:** put the script in the storage target as `scripts/docs/.demo.ts` (import `'../helpers.ts'`), then `npm run demo:docs` records every docs script and uploads `videos/docs/.{mp4,gif}`. `DEMO_STORAGE=file:///some/dir` tries it without a bucket. +- **Screenshots:** in any demo, `await page.screenshot({ path: 'demo/videos/.png' })` for the frame, or `await locator.screenshot({ path })` for one component, rendered at `DEMO_SCALE` (2x by default). Paths are relative to `ui/apps/chat`. +- **Component docs** belong in the package's Storybook: a story per state, prose in a `.svx` page (see `ui/apps/chat/AGENTS.md`). + +## Worked example + +A demo of chat search, then a reply from the mocked server, then a Llama UI story, in one PR block, each video with its description beside it in the `## Demo` table (record with `DEMO_STORYBOOK=ui npm run demo:pr -- `): + +```ts +const describe = (description: string) => ({ + annotation: { description, type: "description" }, +}); + +test.describe(() => { + test.use({ traces: ["long-chat", "agentic-debugging"] }); + + test( + "Search finds a chat by its title", + describe( + "Typing a word from a chat's title lists it, and opening the result shows the conversation.", + ), + async ({ demo, page }) => { + await demo.click(page.getByLabel("Expand navigation")); + await demo.click(page.getByRole("button", { name: /^Search/ })); + + const search = page.getByRole("dialog", { name: "Search" }); + + await demo.type( + search.getByRole("combobox", { name: "Search" }), + "flaky", + ); + + const result = search.getByRole("option", { + name: /Fix the flaky cache tests/, + }); + + await expect(result).toBeVisible(); + await demo.click(result, 1200); + await expect(page.getByRole("main")).toContainText( + "All 48 cache tests pass now", + ); + }, + ); +}); + +test.describe(() => { + test.use({ + mockServer: { + reply: "Rust is a systems language focused on **safety** and *speed*.", + }, + }); + + test( + "A reply from a mocked server, no model loaded", + describe( + "The reply streams from mockServer, so the video looks the same on every machine.", + ), + async ({ demo, page }) => { + await demo.type( + page.getByRole("textbox", { name: "Type a message..." }), + "What is Rust?", + ); + await demo.press("Enter", 1500); + await expect(page.getByRole("main")).toContainText( + "focused on safety", + ); + }, + ); +}); + +test.describe(() => { + // a small viewport frames a small component, recorded at the same scale + test.use({ + story: "ui-forms-switch--default", + viewport: { height: 450, width: 720 }, + }); + + test( + "A Llama UI story: Switch", + describe( + "The Switch from Llama UI, recorded from its Storybook story.", + ), + async ({ demo, page }) => { + const off = page.getByRole("switch").first(); + + await demo.click(off, 900); + await expect(off).toBeChecked(); + }, + ); +}); +``` + +The same search flow as a check is `tests/e2e/search-chats.e2e.ts`. + +## Pitfalls + +- **Ports:** vite dev `:5180` (`DEMO_UI_PORT`), fixture MCP `:8765`, llama-server `:9931`, Storybook `:6007` (`DEMO_STORYBOOK_PORT`), e2e `:8181`. Every server is reused when something already answers there, even another checkout's: stop stale servers, or pick other ports. `demo:pr` picks free ports itself. +- **Chrome sandbox:** demos record in Playwright's bundled Chromium with the sandbox on (headless installed Chrome ignores the viewport in screencasts); local e2e runs in the installed Chrome with the sandbox on. Do not turn the sandbox off to make a run pass: a PR demo runs that PR's code. +- **Waits:** wait on state, never on time. `expect(locator).toBeVisible()` / `toContainText()` before acting on something that appears late; `demo.pause` is pacing for the viewer only. The first load of a cold dev server reloads the page once; the harness waits for it before recording, so do not add sleeps for it. +- **Selectors:** use roles and accessible names. Some names match twice (`Expand navigation` is both the logo and the button: use `page.getByLabel('Expand navigation')`); scope to a dialog with `page.getByRole('dialog', { name })`. A strict-mode error names both matches. +- **Real server:** without `mockServer`, the model list and any reply come from the real llama-server and differ per machine. Mock them for anything a viewer should see the same way twice. +- **Preview size:** keep a demo short (under ~20 s per test): the GIF preview must stay under 5 MB, so a long one is shrunk until it is hard to read. +- **Chromium only:** the screencast and the render run on the Chrome DevTools Protocol, so a demo in Firefox or WebKit fails at its start. Show a Safari-only fix with a check in `tests/e2e`, not a demo. diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index 4b7e786fa771..327e62571ebd 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -134,6 +134,7 @@ static const std::map LLM_ARCH_NAMES = { { LLM_ARCH_HUNYUAN_VL, "hunyuan_vl" }, { LLM_ARCH_HY_V3, "hy_v3" }, { LLM_ARCH_HY_V4, "hy_v4" }, + { LLM_ARCH_HY_V4_FLASH, "hy_v4_flash" }, { LLM_ARCH_SMOLLM3, "smollm3" }, { LLM_ARCH_OPENAI_MOE, "gpt-oss" }, { LLM_ARCH_LFM2, "lfm2" }, @@ -170,6 +171,7 @@ static const std::map LLM_ARCH_NAMES = { { LLM_ARCH_KIMI_LINEAR, "kimi-linear" }, { LLM_ARCH_KIMI_K3, "kimi-k3" }, { LLM_ARCH_KIMI_K31, "kimi-k31" }, + { LLM_ARCH_RAON1_MINI, "raon1" }, { LLM_ARCH_GLM5_NEXT, "glm5-next" }, { LLM_ARCH_TALKIE, "talkie" }, { LLM_ARCH_MELLUM, "mellum" }, @@ -308,6 +310,7 @@ static const std::map LLM_KV_NAMES = { { LLM_KV_ATTENTION_VALUE_LENGTH, "%s.attention.value_length" }, { LLM_KV_ATTENTION_LAYERNORM_EPS, "%s.attention.layer_norm_epsilon" }, { LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, "%s.attention.layer_norm_rms_epsilon" }, + { LLM_KV_ATTENTION_LATENT_NORM_RMS_EPS, "%s.attention.latent_norm_rms_epsilon" }, { LLM_KV_ATTENTION_GROUPNORM_EPS, "%s.attention.group_norm_epsilon" }, { LLM_KV_ATTENTION_GROUPNORM_GROUPS, "%s.attention.group_norm_groups" }, { LLM_KV_ATTENTION_CAUSAL, "%s.attention.causal" }, @@ -447,12 +450,13 @@ static const std::map LLM_KV_NAMES = { { LLM_KV_NORM_BEFORE_RESIDUAL, "%s.norm_before_residual" }, { LLM_KV_NORM_BEFORE_FC, "%s.norm_before_fc" }, - { LLM_KV_DFLASH_BLOCK_SIZE, "%s.block_size" }, - { LLM_KV_DFLASH_CONV_KERNEL_SIZE, "%s.conv_kernel_size" }, - { LLM_KV_DFLASH_CONV_GROUP_SIZE, "%s.conv_group_size" }, - { LLM_KV_DFLASH_SELECTOR_RANK, "%s.selector_rank" }, - { LLM_KV_DFLASH_SELECTOR_TOP_K, "%s.selector_top_k" }, - { LLM_KV_DFLASH_HAS_MARKOV_CONTEXT, "%s.has_markov_context" }, + { LLM_KV_DFLASH_BLOCK_SIZE, "%s.block_size" }, + { LLM_KV_DFLASH_CONV_KERNEL_SIZE, "%s.conv_kernel_size" }, + { LLM_KV_DFLASH_CONV_GROUP_SIZE, "%s.conv_group_size" }, + { LLM_KV_DFLASH_SELECTOR_RANK, "%s.selector_rank" }, + { LLM_KV_DFLASH_SELECTOR_TOP_K, "%s.selector_top_k" }, + { LLM_KV_DFLASH_SELECTOR_SOFTCAP_AFTER_CORRECTION, "%s.selector_softcap_after_correction" }, + { LLM_KV_DFLASH_HAS_MARKOV_CONTEXT, "%s.has_markov_context" }, { LLM_KV_LILICORR_HIDDEN_SIZE, "lilicorr.hidden_size" }, { LLM_KV_LILICORR_CANDIDATE_TOPK, "lilicorr.candidate_topk" }, @@ -702,6 +706,7 @@ static const std::map LLM_TENSOR_NAMES = { { LLM_TENSOR_SSM_F_A, "blk.%d.ssm_f_a" }, { LLM_TENSOR_SSM_F_B, "blk.%d.ssm_f_b" }, { LLM_TENSOR_SSM_BETA, "blk.%d.ssm_beta" }, + { LLM_TENSOR_SSM_RDA, "blk.%d.ssm_rda" }, { LLM_TENSOR_SSM_G_A, "blk.%d.ssm_g_a" }, { LLM_TENSOR_SSM_G, "blk.%d.ssm_g" }, { LLM_TENSOR_ATTN_RES_SCORE, "blk.%d.attn_res_score" }, @@ -904,6 +909,7 @@ static const std::map LLM_TENSOR_NAMES = { { LLM_TENSOR_INDEXER_COMPRESSOR_NORM, "blk.%d.indexer_compressor_norm" }, { LLM_TENSOR_INDEXER_KPOOL_GATE, "blk.%d.indexer_compressor_gate" }, { LLM_TENSOR_INDEXER_KPOOL_APE, "blk.%d.indexer_compressor_ape" }, + { LLM_TENSOR_INDEXER_KPOOL_VALUE, "blk.%d.indexer_compressor_value" }, { LLM_TENSOR_FFN_GATE_TID2EID, "blk.%d.ffn_gate_tid2eid" }, { LLM_TENSOR_MASKED_EMBD_CENTROIDS, "masked_embd_centroids" }, { LLM_TENSOR_MASKED_EMBD_ORDERING, "masked_embd_ordering" }, @@ -918,6 +924,10 @@ static const std::map LLM_TENSOR_NAMES = { { LLM_TENSOR_DSPARK_MARKOV_CTX_NORM, "markov_ctx_norm" }, { LLM_TENSOR_ENGRAM_KV, "blk.%d.engram_kv" }, { LLM_TENSOR_ENGRAM_GATE, "blk.%d.engram_gate" }, + { LLM_TENSOR_ENGRAM_KV_B, "blk.%d.engram_kv_b" }, + { LLM_TENSOR_ENGRAM_LOOKUP_NORM, "blk.%d.engram_lookup_norm" }, + { LLM_TENSOR_ENGRAM_PRE_GAMMA, "blk.%d.engram_pre_gamma" }, + { LLM_TENSOR_ENGRAM_HC_SCALE, "blk.%d.engram_hc_scale" }, { LLM_TENSOR_DFLASH_ATTN_CONV_BASE, "blk.%d.attn_conv_base" }, { LLM_TENSOR_DFLASH_ATTN_CONV_PROJ, "blk.%d.attn_conv_proj" }, { LLM_TENSOR_DFLASH_FFN_CONV_BASE, "blk.%d.ffn_conv_base" }, @@ -1140,6 +1150,7 @@ static const std::map LLM_TENSOR_INFOS = { {LLM_TENSOR_SSM_F_A, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_SSM_F_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_SSM_BETA, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_SSM_RDA, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_SSM_G_A, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_SSM_G, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_ATTN_RES_SCORE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, @@ -1269,6 +1280,7 @@ static const std::map LLM_TENSOR_INFOS = { {LLM_TENSOR_INDEXER_COMPRESSOR_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, {LLM_TENSOR_INDEXER_KPOOL_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_INDEXER_KPOOL_APE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}}, + {LLM_TENSOR_INDEXER_KPOOL_VALUE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_FFN_GATE_TID2EID, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_GET_ROWS}}, {LLM_TENSOR_NEXTN_PROJ_PRE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_NEXTN_PROJ_POST, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, @@ -1352,6 +1364,10 @@ static const std::map LLM_TENSOR_INFOS = { {LLM_TENSOR_DSPARK_MARKOV_CTX_NORM, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL}}, {LLM_TENSOR_ENGRAM_KV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_ENGRAM_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, + {LLM_TENSOR_ENGRAM_KV_B, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}}, + {LLM_TENSOR_ENGRAM_LOOKUP_NORM, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, + {LLM_TENSOR_ENGRAM_PRE_GAMMA, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, + {LLM_TENSOR_ENGRAM_HC_SCALE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_ADD}}, {LLM_TENSOR_DFLASH_ATTN_CONV_BASE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, {LLM_TENSOR_DFLASH_ATTN_CONV_PROJ, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_DFLASH_FFN_CONV_BASE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL}}, @@ -1486,6 +1502,7 @@ bool llm_arch_is_hybrid(const llm_arch & arch) { case LLM_ARCH_BAILINGMOE3: case LLM_ARCH_KIMI_K3: case LLM_ARCH_KIMI_K31: + case LLM_ARCH_RAON1_MINI: case LLM_ARCH_GLM5_NEXT: case LLM_ARCH_QWEN35: case LLM_ARCH_QWEN35MOE: @@ -1519,6 +1536,7 @@ bool llm_arch_supports_rs_rollback(const llm_arch & arch) { switch (arch) { case LLM_ARCH_KIMI_K3: case LLM_ARCH_KIMI_K31: + case LLM_ARCH_RAON1_MINI: case LLM_ARCH_QWEN35: case LLM_ARCH_QWEN35MOE: case LLM_ARCH_CLOVER_MOE: @@ -1579,6 +1597,7 @@ bool llm_arch_supports_sm_tensor(const llm_arch & arch) { case LLM_ARCH_DEEPSEEK2: case LLM_ARCH_DEEPSEEK32: case LLM_ARCH_HY_V4: + case LLM_ARCH_HY_V4_FLASH: case LLM_ARCH_DOTS3NOTE: case LLM_ARCH_XING4_0: case LLM_ARCH_GLM_DSA: @@ -1599,6 +1618,7 @@ bool llm_arch_supports_sm_tensor(const llm_arch & arch) { case LLM_ARCH_BAILINGMOE3: case LLM_ARCH_KIMI_K3: case LLM_ARCH_KIMI_K31: + case LLM_ARCH_RAON1_MINI: case LLM_ARCH_QWEN3TTS: case LLM_ARCH_LIMITE: return false; diff --git a/src/llama-arch.h b/src/llama-arch.h index 74ca69fe7e9b..54acd537c8da 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -138,6 +138,7 @@ enum llm_arch { LLM_ARCH_HUNYUAN_VL, LLM_ARCH_HY_V3, LLM_ARCH_HY_V4, + LLM_ARCH_HY_V4_FLASH, LLM_ARCH_SMOLLM3, LLM_ARCH_OPENAI_MOE, LLM_ARCH_LFM2, @@ -168,6 +169,7 @@ enum llm_arch { LLM_ARCH_KIMI_LINEAR, LLM_ARCH_KIMI_K3, LLM_ARCH_KIMI_K31, + LLM_ARCH_RAON1_MINI, LLM_ARCH_GLM5_NEXT, LLM_ARCH_TALKIE, LLM_ARCH_MELLUM, @@ -314,6 +316,7 @@ enum llm_kv { LLM_KV_ATTENTION_VALUE_LENGTH, LLM_KV_ATTENTION_LAYERNORM_EPS, LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, + LLM_KV_ATTENTION_LATENT_NORM_RMS_EPS, LLM_KV_ATTENTION_GROUPNORM_EPS, LLM_KV_ATTENTION_GROUPNORM_GROUPS, LLM_KV_ATTENTION_CAUSAL, @@ -498,6 +501,7 @@ enum llm_kv { LLM_KV_DFLASH_CONV_GROUP_SIZE, LLM_KV_DFLASH_SELECTOR_RANK, LLM_KV_DFLASH_SELECTOR_TOP_K, + LLM_KV_DFLASH_SELECTOR_SOFTCAP_AFTER_CORRECTION, LLM_KV_DFLASH_HAS_MARKOV_CONTEXT, LLM_KV_LILICORR_HIDDEN_SIZE, LLM_KV_LILICORR_CANDIDATE_TOPK, @@ -709,6 +713,7 @@ enum llm_tensor { LLM_TENSOR_SSM_F_A, // kimi: forget gate projection A LLM_TENSOR_SSM_F_B, // kimi: forget gate projection B LLM_TENSOR_SSM_BETA, // kimi: beta mixing coefficient and qwen3.5 + LLM_TENSOR_SSM_RDA, // raon1_mini: write gate offset LLM_TENSOR_SSM_G_A, // kimi: output gate projection A LLM_TENSOR_SSM_G_B, // kimi: output gate projection B LLM_TENSOR_SSM_G, // kimi-k3: full-rank KDA gate @@ -897,6 +902,7 @@ enum llm_tensor { LLM_TENSOR_INDEXER_COMPRESSOR_NORM, LLM_TENSOR_INDEXER_KPOOL_GATE, // glm5-next: k-pool gate scores LLM_TENSOR_INDEXER_KPOOL_APE, // glm5-next: k-pool position bias + LLM_TENSOR_INDEXER_KPOOL_VALUE, // hy_v4_flash: what the k-pool actually pools LLM_TENSOR_FFN_GATE_TID2EID, LLM_TENSOR_NEXTN_PROJ_PRE, LLM_TENSOR_NEXTN_PROJ_POST, @@ -923,6 +929,10 @@ enum llm_tensor { LLM_TENSOR_DSPARK_MARKOV_CTX_NORM, LLM_TENSOR_ENGRAM_KV, LLM_TENSOR_ENGRAM_GATE, + LLM_TENSOR_ENGRAM_KV_B, // hy_v4_flash: bias on the fused key/value projections + LLM_TENSOR_ENGRAM_LOOKUP_NORM, // hy_v4_flash: per-head RMSNorm of the looked-up rows + LLM_TENSOR_ENGRAM_PRE_GAMMA, // hy_v4_flash: scales the normed value before the gate + LLM_TENSOR_ENGRAM_HC_SCALE, // hy_v4_flash: per-hc per-channel additive gate offset LLM_TENSOR_DFLASH_ATTN_CONV_BASE, LLM_TENSOR_DFLASH_ATTN_CONV_PROJ, LLM_TENSOR_DFLASH_FFN_CONV_BASE, diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 89465d0cee91..aa0b93045b91 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -196,7 +196,7 @@ llama_context::llama_context( 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); + model.arch == LLM_ARCH_BAILINGMOE3 || model.arch == LLM_ARCH_RAON1_MINI); cparams.n_threads = params.n_threads; cparams.n_threads_batch = params.n_threads_batch; @@ -375,6 +375,13 @@ llama_context::llama_context( cparams.op_offload = params.op_offload; cparams.kv_unified = params.kv_unified; + + // the Hy4 flash pools gather their members from a single KV stream + if (model.arch == LLM_ARCH_HY_V4_FLASH && !cparams.kv_unified && cparams.n_seq_max > 1) { + LLAMA_LOG_WARN("%s: %s needs a unified KV cache, the sequences share n_ctx\n", __func__, llm_arch_name(model.arch)); + cparams.kv_unified = true; + } + cparams.moe_cache_size = params.moe_cache_size; cparams.moe_cache_cpu_share = params.moe_cache_cpu_share; diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 5fef4c42168a..a96577f11cef 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -2609,7 +2609,7 @@ ggml_tensor * llm_graph_context::build_moe_ffn( const float limit = hparams.swiglu_clamp_exp[il]; constexpr float eps = 1e-6f; if (limit > eps) { - if (arch == LLM_ARCH_MAPLE || arch == LLM_ARCH_DEEPSEEK4 || arch == LLM_ARCH_DEEPSEEK41 || arch == LLM_ARCH_GLM5_NEXT || (arch == LLM_ARCH_DFLASH && hparams.dsv4_hc_mult > 0) || arch == LLM_ARCH_HY_V4) { + if (arch == LLM_ARCH_MAPLE || arch == LLM_ARCH_DEEPSEEK4 || arch == LLM_ARCH_DEEPSEEK41 || arch == LLM_ARCH_GLM5_NEXT || (arch == LLM_ARCH_DFLASH && hparams.dsv4_hc_mult > 0) || arch == LLM_ARCH_HY_V4 || arch == LLM_ARCH_HY_V4_FLASH) { cur = ggml_swiglu_clamp(ctx0, cur, up, limit); } else { up = ggml_clamp(ctx0, up, -limit, limit); @@ -3148,7 +3148,9 @@ ggml_tensor * llm_graph_context::build_attn_mha( ggml_tensor * v_mla, int64_t n_kv_max, float kq_scale, - int il) const { + int il, + ggml_tensor * bias_table, + ggml_tensor * bias_indices) const { const bool v_trans = v->nb[1] > v->nb[2]; // split the batch into streams if needed @@ -3163,12 +3165,28 @@ ggml_tensor * llm_graph_context::build_attn_mha( k = ggml_permute(ctx0, k, 0, 2, 1, 3); v = ggml_permute(ctx0, v, 0, 2, 1, 3); + auto dense_bias_mask = [&]() { + ggml_tensor * table = ggml_cont(ctx0, ggml_permute(ctx0, bias_table, 1, 0, 2, 3)); + ggml_tensor * bias = ggml_get_rows(ctx0, table, bias_indices); + bias = ggml_reshape_4d(ctx0, bias, q->ne[2], bias_indices->ne[0], q->ne[1], n_stream); + bias = ggml_cont(ctx0, ggml_permute(ctx0, bias, 2, 0, 1, 3)); + cb(bias, "kq_b", il); + + ggml_tensor * mask = kq_mask->type == GGML_TYPE_F32 ? kq_mask : ggml_cast(ctx0, kq_mask, GGML_TYPE_F32); + mask = ggml_add(ctx0, bias, mask); + if (cparams.flash_attn) { + mask = ggml_cast(ctx0, mask, GGML_TYPE_F16); + } + cb(mask, "kq_mask_rel_pos", il); + return mask; + }; + ggml_tensor * cur; const bool use_flash_attn = cparams.flash_attn && kq_b == nullptr; GGML_ASSERT(use_flash_attn || kv_rows == nullptr); if (use_flash_attn) { - GGML_ASSERT(kq_b == nullptr && "Flash attention does not support KQ bias yet"); + GGML_ASSERT(kq_b == nullptr && "Flash attention does not support dense KQ bias"); if (v_trans) { v = ggml_transpose(ctx0, v); @@ -3197,6 +3215,16 @@ ggml_tensor * llm_graph_context::build_attn_mha( ggml_flash_attn_ext_set_n_kv_max(cur, static_cast(n_kv_max)); ggml_prec_set_acc(cur, GGML_PREC_F32); + if (bias_table) { + ggml_flash_attn_ext_add_indexed_bias(cur, bias_table, bias_indices); + auto * dev = model.dev_layer(il); + if ((!cparams.offload_kqv && ggml_backend_dev_type(dev) != GGML_BACKEND_DEVICE_TYPE_CPU) || !ggml_backend_dev_supports_op(dev, cur)) { + // Keep ordinary flash attention on the layer device. + ggml_flash_attn_ext_add_indexed_bias(cur, nullptr, nullptr); + cur->src[3] = dense_bias_mask(); + } + } + if (v_mla) { #if 0 // v_mla can be applied as a matrix-vector multiplication with broadcasting across dimension 3 == n_tokens. @@ -3216,6 +3244,9 @@ ggml_tensor * llm_graph_context::build_attn_mha( cur = ggml_reshape_2d(ctx0, cur, cur->ne[0]*cur->ne[1], cur->ne[2]*cur->ne[3]); } else { + if (bias_table) { + kq_mask = dense_bias_mask(); + } ggml_tensor * kq = ggml_mul_mat(ctx0, k, q); cb(kq, "kq", il); @@ -3725,7 +3756,9 @@ static ggml_tensor * build_attn_iswa_impl( ggml_tensor * sinks, ggml_tensor * v_mla, float kq_scale, - int il) { + int il, + ggml_tensor * bias_table = nullptr, + ggml_tensor * bias_indices = nullptr) { ggml_context * ctx0 = gctx.ctx0; ggml_cgraph * gf = gctx.gf; @@ -3791,7 +3824,7 @@ static ggml_tensor * build_attn_iswa_impl( ggml_tensor * k = use_kv_cur ? k_cur : mctx_cur->get_k(ctx0, il); ggml_tensor * v = use_kv_cur ? v_cur : mctx_cur->get_v(ctx0, il); - ggml_tensor * cur = gctx.build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il); + ggml_tensor * cur = gctx.build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il, bias_table, bias_indices); cur = build_attn_scale_kv_output(ctx0, mctx_cur, cur, il); gctx.cb(cur, "kqv_out", il); @@ -4454,7 +4487,7 @@ ggml_tensor * llm_graph_context::build_attn( ggml_tensor * q_cur, ggml_tensor * k_cur, ggml_tensor * v_cur, - ggml_tensor * kq_b, + ggml_tensor * bias_table, ggml_tensor * sinks, float kq_scale, int il) const { @@ -4464,22 +4497,11 @@ ggml_tensor * llm_graph_context::build_attn( const auto & attn_mask = is_swa ? inp_attn->self_attn_mask_swa : inp_attn->self_attn_mask; - // TODO: support kv_rows - fill the distances over the kv_rows cell lists and pass the rows to build_attn_mha, - // needs a kv_rows flash attention with a per-head mask (CUDA has none) GGML_ASSERT(attn_mask.rows == nullptr); + ggml_tensor * indices = is_swa ? inp->self_rel_pos_swa : inp->self_rel_pos; - // a mask per head, in the dense layout of the input mask, which flash attention takes in F16 - ggml_tensor * kq_mask = attn_mask.raw; - if (kq_mask->type != GGML_TYPE_F32) { - kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F32); - } - kq_mask = ggml_add(ctx0, kq_b, kq_mask); - if (cparams.flash_attn) { - kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F16); - } - cb(kq_mask, "kq_mask_rel_pos", il); - - return build_attn_iswa_impl(*this, inp_attn, wo, wo_b, wo_s, q_cur, k_cur, v_cur, nullptr, kq_mask, nullptr, sinks, nullptr, kq_scale, il); + return build_attn_iswa_impl(*this, inp_attn, wo, wo_b, wo_s, q_cur, k_cur, v_cur, nullptr, attn_mask.raw, nullptr, + sinks, nullptr, kq_scale, il, bias_table, indices); } void llm_graph_context::build_dense_out( diff --git a/src/llama-graph.h b/src/llama-graph.h index ff155f14d2f6..508d05531531 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -1349,7 +1349,9 @@ struct llm_graph_context { ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v] int64_t n_kv_max, float kq_scale, - int il) const; + int il, + ggml_tensor * bias_table = nullptr, // [n_bins, n_head_q, n_tokens] + ggml_tensor * bias_indices = nullptr) const; llm_graph_input_attn_no_cache * build_attn_inp_no_cache() const; @@ -1547,7 +1549,6 @@ struct llm_graph_context { uint32_t extent, uint32_t extent_swa) const; - // kq_b is added to the KQ mask, after the KQ scale ggml_tensor * build_attn( llm_graph_input_mem_hybrid_iswa_rel * inp, ggml_tensor * wo, @@ -1556,7 +1557,7 @@ struct llm_graph_context { ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens] ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens] ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens] - ggml_tensor * kq_b, // [n_kv, n_tokens/n_stream, n_head_q, n_stream] + ggml_tensor * bias_table, // [n_bins, n_head_q, n_tokens] ggml_tensor * sinks, // [n_head_q] float kq_scale, int il) const; diff --git a/src/llama-hparams.h b/src/llama-hparams.h index b6a373bfe5cf..3e846be030fd 100644 --- a/src/llama-hparams.h +++ b/src/llama-hparams.h @@ -146,6 +146,7 @@ struct llama_hparams { float f_norm_eps; float f_norm_rms_eps; float f_norm_group_eps; + float f_norm_rms_eps_latent = 0.0f; // RMS norm of the MLA q/kv latents (Raon-1 mini) // post norms use their own epsilon float f_post_norm_eps = 0.0f; @@ -304,6 +305,7 @@ struct llama_hparams { uint32_t dflash_conv_group_size = 0; uint32_t dflash_selector_rank = 0; uint32_t dflash_selector_top_k = 0; + bool dflash_softcap_post = false; // DFlash2 softcaps the selector scores instead of the logits bool dspark_f_rnn = false; // rnn markov head reads f_rnn from embd_state uint32_t lilicorr_hidden_size = 0; uint32_t lilicorr_candidate_topk = 0; diff --git a/src/llama-kv-cache-dsa.cpp b/src/llama-kv-cache-dsa.cpp index 1221f7f2bfae..42d2ae2631af 100644 --- a/src/llama-kv-cache-dsa.cpp +++ b/src/llama-kv-cache-dsa.cpp @@ -45,6 +45,13 @@ llama_kv_cache_dsa::llama_kv_cache_dsa( std::fill(hparams_lid.n_head_kv_arr.begin(), hparams_lid.n_head_kv_arr.end(), 1); hparams_lid.n_embd_head_k_full = model.hparams.indexer_head_size; + // a pooled indexer (hy_v4_flash) caches the value and the gate of each token, the pooled key is built from them in the graph + // the cached rows carry no position, the pooled key is rotated in the graph, so a K-shift must leave them alone + if (model.hparams.indexer_kpool > 0) { + hparams_lid.n_embd_head_k_full *= 2; + std::fill(hparams_lid.rope_pattern.begin(), hparams_lid.rope_pattern.end(), 0); + } + // KV sharing applies to the MLA cache only, each indexer owns its keys std::iota(hparams_lid.kv_source_impl.begin(), hparams_lid.kv_source_impl.end(), 0); diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index bb546f7cdec8..c7444319bcf5 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -2002,6 +2002,126 @@ void llama_kv_cache::set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch } } +void llama_kv_cache::set_input_kpool(ggml_tensor * pool_idxs, ggml_tensor * pool_pos, ggml_tensor * pool_mask, ggml_tensor * tail_idxs, + const llama_ubatch * ubatch, const slot_info & sinfo, uint32_t kpool, uint32_t n_kv) const { + GGML_ASSERT(n_stream == 1 && "TODO: support multiple streams"); + GGML_ASSERT(pool_idxs->ne[0] == kpool && tail_idxs->ne[0] == kpool); + GGML_ASSERT(pool_mask->type == GGML_TYPE_F16); + GGML_ASSERT(sinfo.idxs.size() == 1 && sinfo.idxs[0].size() == ubatch->n_tokens); + + const auto & cells = v_cells[0]; + + const int64_t n_tokens = ubatch->n_tokens; + const int64_t n_pool = pool_idxs->ne[1]; + const uint32_t n_planes = hparams.n_pos_per_embd(); + GGML_ASSERT(pool_mask->ne[0] == n_pool && pool_pos->ne[0] == n_pool*n_planes && n_kv <= cells.size()); + + // one pool per kpool consecutive tokens of each sequence of the ubatch, in sequence order + // the order is the position, then the cell: the tokens of an image share their position with M-RoPE + // sequences that share a prefix share its pools, a lone sequence has nothing to share + std::vector idxs; + std::vector first; + std::map, int32_t> pool_of; + const bool dedup = ubatch->n_seqs_unq > 1; + + // the pool of each group of each sequence + std::vector> seq_pools(ubatch->n_seqs_unq); + + // the cells of each sequence in order, and the rank of each cell in its sequence + std::vector> order(ubatch->n_seqs_unq); + std::vector> rank (ubatch->n_seqs_unq); + + std::vector> seq_cells; + std::vector members(kpool); + for (uint32_t s = 0; s < ubatch->n_seqs_unq; ++s) { + const llama_seq_id seq_id = ubatch->seq_id_unq[s]; + + seq_cells.clear(); + for (uint32_t j = 0; j < n_kv; ++j) { + if (!cells.is_empty(j) && cells.seq_has(j, seq_id)) { + seq_cells.emplace_back(cells.pos_get(j), (int32_t) j); + } + } + if (!std::is_sorted(seq_cells.begin(), seq_cells.end())) { + std::sort(seq_cells.begin(), seq_cells.end()); + } + + auto & ord = order[s]; + auto & rnk = rank[s]; + ord.resize(seq_cells.size()); + rnk.assign(n_kv, -1); + for (size_t r = 0; r < seq_cells.size(); ++r) { + ord[r] = seq_cells[r].second; + rnk[ord[r]] = (int32_t) r; + } + + for (int32_t g = 0; (size_t) (g + 1)*kpool <= ord.size(); ++g) { + const auto beg = ord.begin() + g*kpool; + const auto end = beg + kpool; + int32_t k = (int32_t) first.size(); + if (dedup) { + members.assign(beg, end); + k = pool_of.try_emplace(members, k).first->second; + } + if (k == (int32_t) first.size()) { + idxs.insert(idxs.end(), beg, end); + first.push_back(*beg); + } + seq_pools[s].push_back(k); + } + } + + if ((int64_t) first.size() > n_pool) { + GGML_ABORT("the ubatch has %zu pools, the graph has room for %lld", first.size(), (long long) n_pool); + } + + // an unused pool is never picked, its score is -inf, but its members are still gathered: any cell does + std::vector pool_idxs_data(kpool*n_pool, 0); + std::copy(idxs.begin(), idxs.end(), pool_idxs_data.begin()); + + // the pooled key is rotated at the position of its first member, the M-RoPE planes are t, y, x, t + std::vector pool_pos_data(n_pool*n_planes, 0); + for (size_t k = 0; k < first.size(); ++k) { + const llama_pos t = cells.pos_get(first[k]); + pool_pos_data[k] = t; + if (n_planes == 4) { + const auto & e = cells.ext_get(first[k]); + pool_pos_data[1*n_pool + k] = e.y; + pool_pos_data[2*n_pool + k] = e.x; + pool_pos_data[3*n_pool + k] = t; + } + } + + std::vector pool_mask_data(n_pool*n_tokens, ggml_fp32_to_fp16(-INFINITY)); + std::vector tail_idxs_data(kpool*n_tokens, 0); + + const ggml_fp16_t zero = ggml_fp32_to_fp16(0.0f); + for (int64_t i = 0; i < n_tokens; ++i) { + // a token shared by several sequences has the same history in each, so its first one stands for all + const llama_seq_id seq_id = ubatch->seq_id[i][0]; + const uint32_t s = ubatch->seq_idx[seq_id]; + const int32_t r = rank[s][sinfo.idxs[0][i]]; + GGML_ASSERT(r >= 0); + const int32_t group = r/kpool; + + // the token sees the full pools of its sequence before its own + for (int32_t g = 0; g < group; ++g) { + pool_mask_data[i*n_pool + seq_pools[s][g]] = zero; + } + + // the token's own pool, up to the token itself, the token's cell again for the members it does not have yet + for (int32_t m = 0; m < (int32_t) kpool; ++m) { + const int32_t rm = group*(int32_t) kpool + m; + tail_idxs_data[i*kpool + m] = rm <= r ? order[s][rm] : (int32_t) sinfo.idxs[0][i]; + } + } + + ggml_backend_tensor_set(pool_idxs, pool_idxs_data.data(), 0, ggml_nbytes(pool_idxs)); + ggml_backend_tensor_set(pool_pos, pool_pos_data.data(), 0, ggml_nbytes(pool_pos)); + ggml_backend_tensor_set(pool_mask, pool_mask_data.data(), 0, ggml_nbytes(pool_mask)); + ggml_backend_tensor_set(tail_idxs, tail_idxs_data.data(), 0, ggml_nbytes(tail_idxs)); +} + bool llama_kv_cache::has_cell_ext() const { // M-RoPE needs the 2D position, the PLE / Engram n-gram hashes need the token id return hparams.n_pos_per_embd() > 1 || hparams.ple_n_heads > 0; @@ -3124,6 +3244,11 @@ void llama_kv_cache_context::set_input_pos_bucket(ggml_tensor * dst, const llama kv->set_input_pos_bucket(dst, ubatch); } +void llama_kv_cache_context::set_input_kpool(ggml_tensor * pool_idxs, ggml_tensor * pool_pos, ggml_tensor * pool_mask, ggml_tensor * tail_idxs, + const llama_ubatch * ubatch, uint32_t kpool) const { + kv->set_input_kpool(pool_idxs, pool_pos, pool_mask, tail_idxs, ubatch, sinfos[i_cur], kpool, n_kv); +} + void llama_kv_cache_context::set_input_relative_pos(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const { kv->set_input_relative_pos(dst, ubatch, extent); } diff --git a/src/llama-kv-cache.h b/src/llama-kv-cache.h index 1b40f6fc41d5..acff46e19c59 100644 --- a/src/llama-kv-cache.h +++ b/src/llama-kv-cache.h @@ -249,6 +249,15 @@ class llama_kv_cache : public llama_memory_i { void set_input_attn_mask (const llm_attn_mask & attn_mask, const llama_ubatch * ubatch, bool causal_attn) const; void set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const; + + // pools of kpool consecutive tokens of a sequence, in the order of their positions, for a pooled indexer (hy_v4_flash) + // the pools are rebuilt from the cells for every ubatch, so no sequence edit can leave them stale + // pool_idxs [kpool, n_pool] I32: member cells of each complete pool, cell 0 for an unused one + // pool_pos [n_pool*n_pos_per_embd] I32: position of the first member, where the pooled key is rotated + // pool_mask [n_pool, n_tokens] F16: 0 for a pool of the token's sequence that ends before the token's own pool, else -inf + // tail_idxs [kpool, n_tokens] I32: cells of the token's own pool, the token's cell for the members it does not have yet + void set_input_kpool(ggml_tensor * pool_idxs, ggml_tensor * pool_pos, ggml_tensor * pool_mask, ggml_tensor * tail_idxs, + const llama_ubatch * ubatch, const slot_info & sinfo, uint32_t kpool, uint32_t n_kv) const; void set_input_relative_pos(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const; // true if llama_kv_cell_ext holds information that has to survive a state save/restore @@ -454,6 +463,8 @@ class llama_kv_cache_context : public llama_memory_context_i { void set_input_k_shift (ggml_tensor * dst) const; void set_input_attn_mask (const llm_attn_mask & attn_mask, const llama_ubatch * ubatch, bool causal_attn) const; void set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const; + void set_input_kpool(ggml_tensor * pool_idxs, ggml_tensor * pool_pos, ggml_tensor * pool_mask, ggml_tensor * tail_idxs, + const llama_ubatch * ubatch, uint32_t kpool) const; void set_input_relative_pos(ggml_tensor * dst, const llama_ubatch * ubatch, uint32_t extent) const; // see llama_kv_cache::get_prev_tokens() diff --git a/src/llama-model-saver.cpp b/src/llama-model-saver.cpp index 4a62064e7dc6..00b169ef641c 100644 --- a/src/llama-model-saver.cpp +++ b/src/llama-model-saver.cpp @@ -268,6 +268,7 @@ void llama_model_saver::add_kv_from_model() { add_kv(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps); add_kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); add_kv(LLM_KV_POST_NORM_EPS, hparams.f_post_norm_eps); + add_kv(LLM_KV_ATTENTION_LATENT_NORM_RMS_EPS, hparams.f_norm_rms_eps_latent); add_kv(LLM_KV_ATTENTION_GROUPNORM_EPS, hparams.f_norm_group_eps); add_kv(LLM_KV_ATTENTION_GROUPNORM_GROUPS, hparams.n_norm_groups); add_kv(LLM_KV_ATTENTION_VALUE_EXPERT_COUNT, hparams.n_value_expert); @@ -370,6 +371,11 @@ void llama_model_saver::add_kv_from_model() { } } + if (model->arch == LLM_ARCH_HY_V4_FLASH && hparams.ple_n_heads > 0) { + add_kv(LLM_KV_ENGRAM_PAD_TOKEN_ID, hparams.engram_pad_id); + add_kv(LLM_KV_ENGRAM_TOKEN_MAP, model->engram_token_map); + } + // the PLE group only means anything whole: write all of it or none if (hparams.ple_n_heads > 0) { std::vector ple_layers; @@ -384,9 +390,13 @@ void llama_model_saver::add_kv_from_model() { add_kv(LLM_KV_PLE_CONV_KERNEL, hparams.ple_conv_kernel); add_kv(LLM_KV_PLE_EOS_TOKEN_ID, hparams.ple_eos_token_id); add_kv(LLM_KV_EMBEDDING_LENGTH_PER_LAYER, hparams.ple_head_dim); - add_kv(LLM_KV_PLE_LAYER_MULTIPLIERS, std::vector( - hparams.ple_layer_multipliers.begin(), - hparams.ple_layer_multipliers.begin() + hparams.ple_n_modules*hparams.ple_ngram_size)); + if (model->arch == LLM_ARCH_HY_V4_FLASH) { + add_kv(LLM_KV_PLE_LAYER_MULTIPLIERS, model->engram_multipliers); + } else { + add_kv(LLM_KV_PLE_LAYER_MULTIPLIERS, std::vector( + hparams.ple_layer_multipliers.begin(), + hparams.ple_layer_multipliers.begin() + hparams.ple_n_modules*hparams.ple_ngram_size)); + } add_kv(LLM_KV_PLE_HEAD_OFFSETS, std::vector( hparams.ple_head_offsets.begin(), hparams.ple_head_offsets.begin() + hparams.ple_n_modules*hparams.ple_n_heads)); diff --git a/src/llama-model.cpp b/src/llama-model.cpp index 74abd222de58..b836366317e7 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -321,6 +321,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params return new llama_model_hy_v3(params); case LLM_ARCH_HY_V4: return new llama_model_hy_v4(params); + case LLM_ARCH_HY_V4_FLASH: + return new llama_model_hy_v4_flash(params); case LLM_ARCH_SMOLLM3: return new llama_model_smollm3(params); case LLM_ARCH_OPENAI_MOE: @@ -389,6 +391,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params return new llama_model_kimi_k3(params); case LLM_ARCH_KIMI_K31: return new llama_model_kimi_k31(params); + case LLM_ARCH_RAON1_MINI: + return new llama_model_raon1_mini(params); case LLM_ARCH_GLM5_NEXT: return new llama_model_glm5_next(params); case LLM_ARCH_STEP35: @@ -1193,6 +1197,7 @@ const char * llm_type_name(llm_type type) { case LLM_TYPE_21B_A3B: return "21B.A3B"; case LLM_TYPE_24B_A2B: return "24B.A2B"; case LLM_TYPE_26B_A4B: return "26B.A4B"; + case LLM_TYPE_29B_A4B: return "29B.A4B"; case LLM_TYPE_30B_A3B: return "30B.A3B"; case LLM_TYPE_31B_A3_5B: return "31B.A3.5B"; case LLM_TYPE_32B_A9B: return "32B.A9B"; @@ -2343,6 +2348,12 @@ void llama_model_base::load_hparams_hadamard(llama_model_loader & ml) { throw std::runtime_error(format("unsupported prism.hadamard.version: %u", hadamard_version)); } + // the rotation blocks of the inputs of ffn_down, attn_output and ssm_out would straddle the device slices, + // and the sign vectors and the grouped GDN head order of ssm_out have no tensor split state + if (split_mode() == LLAMA_SPLIT_MODE_TENSOR) { + throw std::runtime_error("LLAMA_SPLIT_MODE_TENSOR is not supported for models with Hadamard-folded weights (prism.hadamard), use -sm layer"); + } + if ((hadamard_version == 2) != hdmd.tied_output) { throw std::runtime_error("prism.hadamard version 2 requires tied_output=true; version 1 forbids it"); } @@ -2901,7 +2912,8 @@ void llama_model::print_info() const { if (arch == LLM_ARCH_DEEPSEEK2 || arch == LLM_ARCH_DEEPSEEK2OCR || arch == LLM_ARCH_DEEPSEEK32 || arch == LLM_ARCH_GLM_DSA || arch == LLM_ARCH_DOTS3NOTE || arch == LLM_ARCH_MISTRAL4 || - arch == LLM_ARCH_MISTRAL_LARGE4 || arch == LLM_ARCH_HY_V4) { + arch == LLM_ARCH_MISTRAL_LARGE4 || arch == LLM_ARCH_HY_V4 || + arch == LLM_ARCH_HY_V4_FLASH) { LLAMA_LOG_INFO("%s: n_layer_dense_lead = %d\n", __func__, hparams.n_layer_dense_lead); LLAMA_LOG_INFO("%s: n_lora_q = %d\n", __func__, hparams.n_lora_q); LLAMA_LOG_INFO("%s: n_lora_kv = %d\n", __func__, hparams.n_lora_kv); @@ -3347,6 +3359,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, } } break; case LLM_ARCH_DOTS3NOTE: + case LLM_ARCH_HY_V4_FLASH: { GGML_ASSERT(hparams.swa_type != LLAMA_SWA_TYPE_NONE); @@ -3888,6 +3901,7 @@ llama_rope_type llama_model_rope_type(const llama_model * model) { case LLM_ARCH_KIMI_LINEAR: case LLM_ARCH_KIMI_K3: case LLM_ARCH_KIMI_K31: + case LLM_ARCH_RAON1_MINI: case LLM_ARCH_GLM5_NEXT: case LLM_ARCH_STARCODER: case LLM_ARCH_INKLING2: @@ -3953,6 +3967,9 @@ llama_rope_type llama_model_rope_type(const llama_model * model) { // HY_V4 rotates consecutive pairs, matching the reference implementation case LLM_ARCH_HY_V4: return LLAMA_ROPE_TYPE_NORM; + // HY_V4_FLASH keeps the interleaved rope rows and reorders them in the graph for M-RoPE (see src/models/hy-v4-flash.cpp) + case LLM_ARCH_HY_V4_FLASH: + return model->hparams.use_mrope() ? LLAMA_ROPE_TYPE_IMROPE : LLAMA_ROPE_TYPE_NORM; // the pairs of head values are offset by n_rot/2 case LLM_ARCH_FALCON: diff --git a/src/llama-model.h b/src/llama-model.h index e0273d7d106b..62fbda68ae0b 100644 --- a/src/llama-model.h +++ b/src/llama-model.h @@ -130,6 +130,7 @@ enum llm_type { LLM_TYPE_21B_A3B, // Ernie MoE small LLM_TYPE_24B_A2B, // lfm2moe LLM_TYPE_26B_A4B, // Gemma4 + LLM_TYPE_29B_A4B, // Raon-1 mini LLM_TYPE_30B_A3B, LLM_TYPE_31B_A3_5B, LLM_TYPE_32B_A9B, // Granite4 Hybrid @@ -612,6 +613,7 @@ struct llama_layer { struct ggml_tensor * ssm_f_a = nullptr; struct ggml_tensor * ssm_f_b = nullptr; struct ggml_tensor * ssm_beta = nullptr; + struct ggml_tensor * ssm_rda = nullptr; struct ggml_tensor * ssm_g_a = nullptr; struct ggml_tensor * ssm_g_b = nullptr; struct ggml_tensor * ssm_o_norm = nullptr; @@ -642,10 +644,17 @@ struct llama_layer { // glm5-next k-pool indexer struct ggml_tensor * indexer_kpool_gate = nullptr; struct ggml_tensor * indexer_kpool_ape = nullptr; + // hy_v4_flash: what the k-pool pools + struct ggml_tensor * indexer_kpool_value = nullptr; // deepseek41 struct ggml_tensor * engram_kv = nullptr; struct ggml_tensor * engram_gate = nullptr; // q_weight*k_weight folded + // hy_v4_flash: engram_kv bias, per-head norm of the looked-up rows, scale and offset of the delta + struct ggml_tensor * engram_kv_b = nullptr; + struct ggml_tensor * engram_lookup_norm = nullptr; + struct ggml_tensor * engram_pre_gamma = nullptr; + struct ggml_tensor * engram_hc_scale = nullptr; // MSA struct ggml_tensor * index_q_proj = nullptr; @@ -855,6 +864,8 @@ struct llama_model { // deepseek41 Engram: token id -> id of its normalized form, hashed into the n-grams std::vector engram_token_map; + // hy_v4_flash Engram: n_modules*ngram_size hash multipliers, more than hparams.ple_layer_multipliers holds + std::vector engram_multipliers; struct ggml_tensor * tok_embd = nullptr; struct ggml_tensor * type_embd = nullptr; diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp index d1fc91b1024a..c1fab892fa1a 100644 --- a/src/llama-quant.cpp +++ b/src/llama-quant.cpp @@ -310,6 +310,13 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param // Engram gate is an elementwise weight (ggml_mul), not a matmul operand quantize &= name.find("engram_gate.weight") == std::string::npos; + // hy_v4_flash: these are ggml_add operands + if (arch == LLM_ARCH_HY_V4_FLASH) { + quantize &= name.find("engram_kv_b.weight") == std::string::npos; + quantize &= name.find("engram_hc_scale.weight") == std::string::npos; + quantize &= name.find("indexer_compressor_ape.weight") == std::string::npos; + } + // these are very small (e.g. 4x4) quantize &= name.find("altup") == std::string::npos; quantize &= name.find("laurel") == std::string::npos; @@ -400,6 +407,15 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param quantize &= name.find("hc_") == std::string::npos; } + // raon1_mini: mHC selectors and small RDA gate projections + if (arch == LLM_ARCH_RAON1_MINI) { + quantize &= name.find("hc_") == std::string::npos; + quantize &= name.find("ssm_f_a.weight") == std::string::npos; + quantize &= name.find("ssm_f_b.weight") == std::string::npos; + quantize &= name.find("ssm_beta.weight") == std::string::npos; + quantize &= name.find("ssm_rda.weight") == std::string::npos; + } + // the decision head of vllm-decision2 is small and computed in F32 if (arch == LLM_ARCH_VLLM_DECISION2) { quantize &= name.compare(0, 9, "decision.") != 0; @@ -493,6 +509,10 @@ static ggml_type tensor_type_fallback(quantize_state_impl & qs, const ggml_tenso return fallback_type; } +static double bits_per_weight(ggml_type t) { + return 8.0 * ggml_type_size(t) / ggml_blck_size(t); +} + // 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); @@ -531,11 +551,19 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type } } + // raon1_mini: at Q6_K and Q8_0, where the floors below do not apply, keep the MLA latent projections at source precision: + // quantizing them costs +5.8% mean KL in Q8_0 for 44 MB. --pure and --tensor-type bypass this, as for the floors + if (arch == LLM_ARCH_RAON1_MINI && (ftype == LLAMA_FTYPE_MOSTLY_Q6_K || ftype == LLAMA_FTYPE_MOSTLY_Q8_0) && ( + name.find("attn_kv_a_mqa.weight") != std::string::npos || + name.find("attn_k_b.weight") != std::string::npos || + name.find("attn_v_b.weight") != std::string::npos)) { + return tensor->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; } } @@ -717,6 +745,34 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type ++qs.i_ffn_up; } + // raon1_mini: the dense attention projections and the shared expert carry most of the low-bit loss, attn_output and attn_gate most of all + // only raise to a floor, after the counters above are updated, so the rest of the mixture does not change + if (arch == LLM_ARCH_RAON1_MINI && ggml_is_quantized(new_type)) { + const bool k_4_5 = ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || + ftype == LLAMA_FTYPE_MOSTLY_Q5_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M; + // IQ4_XS/NL and the 1-3 bit K and IQ mixtures (not Q2_0, TQ1_0, TQ2_0 or Q1_0) + const bool low = ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || + ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || + ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S || + ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S || + ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || + ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M; + ggml_type floor_type = GGML_TYPE_COUNT; + if (category == TENSOR_CATEGORY_ATTENTION_OUTPUT || category == TENSOR_CATEGORY_ATTENTION_GATE) { + floor_type = k_4_5 ? GGML_TYPE_Q8_0 : low ? GGML_TYPE_Q6_K : GGML_TYPE_COUNT; + } else if (name.find("attn_q_a.weight") != std::string::npos || name.find("attn_q_b.weight") != std::string::npos || + name.find("attn_k_b.weight") != std::string::npos || name.find("attn_kv_a_mqa.weight") != std::string::npos || + name.find("attn_v_b.weight") != std::string::npos || name.find("_shexp.weight") != std::string::npos) { + floor_type = k_4_5 || low ? GGML_TYPE_Q6_K : GGML_TYPE_COUNT; + } else if (category == TENSOR_CATEGORY_ATTENTION_Q || category == TENSOR_CATEGORY_ATTENTION_K || + category == TENSOR_CATEGORY_ATTENTION_V || name.find("ssm_g.weight") != std::string::npos) { + floor_type = k_4_5 ? GGML_TYPE_Q6_K : GGML_TYPE_COUNT; + } + if (floor_type != GGML_TYPE_COUNT && bits_per_weight(new_type) < bits_per_weight(floor_type)) { + new_type = floor_type; + } + } + return new_type; } diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp index 9e83a983ef6a..674daaa23fd7 100644 --- a/src/llama-vocab.cpp +++ b/src/llama-vocab.cpp @@ -401,6 +401,12 @@ struct llm_tokenizer_bpe : llm_tokenizer { "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", }; break; + case LLAMA_VOCAB_PRE_TYPE_RAON: + regex_exprs = { + // regex from tokenizer.json (the CJK ranges are literal characters there), matched byte for byte in unicode_regex_split_custom() + " ?[\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff]+| ?(?:(?:(?![\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff])\\p{L})\\p{M}*)+(?: (?:(?:(?![\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff])\\p{L})\\p{M}*)+)*|\\p{N}{1,3}(?=(?:\\p{N}{3})*(?!\\p{N}))| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+", + }; + break; case LLAMA_VOCAB_PRE_TYPE_QWEN35: regex_exprs = { // original regex from tokenizer.json @@ -685,6 +691,14 @@ struct llm_tokenizer_bpe_session { } } word_collection = unicode_regex_split(normalized_text, tokenizer.regex_exprs, tokenizer.byte_encode); + } else if (tok_pre == LLAMA_VOCAB_PRE_TYPE_RAON) { + // Raon-1 mini's HF tokenizer applies an NFC normalizer before pre-tokenization. + // TODO: the converter also writes tokenizer.ggml.normalizer.nfc (read for UGM only); gate BPE on that flag once #30708 lands + std::string normalized_text; + for (const uint32_t cpt : unicode_cpts_normalize_nfc(unicode_cpts_from_utf8(text))) { + normalized_text += unicode_cpt_to_utf8(cpt); + } + word_collection = unicode_regex_split(normalized_text, tokenizer.regex_exprs, tokenizer.byte_encode); } else { word_collection = unicode_regex_split(text, tokenizer.regex_exprs, tokenizer.byte_encode); } @@ -2561,6 +2575,9 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { tokenizer_pre == "domyn-edge") { pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN2; clean_spaces = false; + } else if (tokenizer_pre == "raon") { + pre_type = LLAMA_VOCAB_PRE_TYPE_RAON; + clean_spaces = false; } else if ( tokenizer_pre == "qwen35") { pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN35; diff --git a/src/llama-vocab.h b/src/llama-vocab.h index 425a3236c879..b3e8cd7e18b6 100644 --- a/src/llama-vocab.h +++ b/src/llama-vocab.h @@ -77,6 +77,7 @@ enum llama_vocab_pre_type { LLAMA_VOCAB_PRE_TYPE_SOPRANO = 65, LLAMA_VOCAB_PRE_TYPE_TEKKEN_NUM3 = 66, LLAMA_VOCAB_PRE_TYPE_ZONOS3 = 67, + LLAMA_VOCAB_PRE_TYPE_RAON = 68, }; // HF Metaspace pre-tokenizer prepend_scheme diff --git a/src/models/delta-net-base.cpp b/src/models/delta-net-base.cpp index f05bd8c0a2ba..f71e7fddda37 100644 --- a/src/models/delta-net-base.cpp +++ b/src/models/delta-net-base.cpp @@ -80,6 +80,50 @@ ggml_tensor * llm_build_delta_net_base::build_conv_state( return conv_input; } +// qkv selects one third of the shared convolution state row: Q, K or V. +ggml_tensor * llm_build_delta_net_base::build_kda_conv1d( + llm_graph_input_rs * inp, + ggml_tensor * conv_states_all, + ggml_tensor * conv_states_seq, + int64_t qkv, + ggml_tensor * x_proj, + ggml_tensor * conv_w, + int64_t d_conv, + int64_t head_dim, + int64_t n_heads, + int64_t n_seq_tokens, + int64_t n_seqs, + int il) { + const int64_t d_inner = head_dim * n_heads; + const int64_t conv_state_size = (d_conv - 1) * d_inner; + const int64_t n_embd_r_total = 3 * conv_state_size; + + ggml_tensor * x_3d = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs); + + 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, conv_states_all, x_3d, d_conv - 1, d_inner, il, conv_states_seq, qkv); + } else { + ggml_tensor * conv_state = ggml_view_3d(ctx0, conv_states_seq, d_conv - 1, d_inner, n_seqs, + (d_conv - 1) * ggml_element_size(conv_states_seq), + n_embd_r_total * ggml_element_size(conv_states_seq), + qkv * conv_state_size * ggml_element_size(conv_states_seq)); + + conv_x = ggml_concat(ctx0, conv_state, ggml_transpose(ctx0, x_3d), 0); + + build_conv_state_store(inp, 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 * conv_out = ggml_ssm_conv(ctx0, conv_x, conv_weight); + conv_out = ggml_reshape_2d(ctx0, conv_out, d_inner, n_tokens); + conv_out = ggml_silu(ctx0, conv_out); + + return ggml_reshape_4d(ctx0, conv_out, head_dim, n_heads, n_seq_tokens, n_seqs); +} + // [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 diff --git a/src/models/dflash.cpp b/src/models/dflash.cpp index 6200b6c44809..d6b8d87135e4 100644 --- a/src/models/dflash.cpp +++ b/src/models/dflash.cpp @@ -47,6 +47,7 @@ void llama_model_dflash::load_arch_hparams(llama_model_loader & ml) { } } else if (has_selector) { variant = VARIANT_DFLASH2; + ml.get_key(LLM_KV_DFLASH_SELECTOR_SOFTCAP_AFTER_CORRECTION, hparams.dflash_softcap_post, false); } else if (has_lilicorr) { variant = VARIANT_LILICORR; load_hparams_lilicorr(ml); @@ -447,6 +448,9 @@ ggml_tensor * llama_model_dflash::graph_base::build_layers(ggml_tensor * inp_tok ggml_tensor * inpL = model.dspark_mask_embd ? build_dspark_inp_block(*this, model, inp_tokens) : ggml_get_rows(ctx0, get_tok_embd(*this, model), inp_tokens); + if (model.tok_norm && !model.dspark_mask_embd) { + inpL = build_norm(inpL, model.tok_norm, nullptr, LLM_NORM_RMS, -1); + } if (hparams.f_embedding_scale != 0.0f) { inpL = ggml_scale(ctx0, inpL, hparams.f_embedding_scale); } @@ -569,7 +573,7 @@ ggml_tensor * llama_model_dflash::graph_base::build_logits(ggml_tensor * cur) { if (hparams.f_logit_scale != 0.0f) { cur = ggml_scale(ctx0, cur, hparams.f_logit_scale); } - if (hparams.f_final_logit_softcapping > 0.0f) { + if (hparams.f_final_logit_softcapping > 0.0f && !hparams.dflash_softcap_post) { cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_final_logit_softcapping); cur = ggml_tanh(ctx0, cur); cur = ggml_scale(ctx0, cur, hparams.f_final_logit_softcapping); diff --git a/src/models/dflash2.cpp b/src/models/dflash2.cpp index b384d952738c..c37e962b98ee 100644 --- a/src/models/dflash2.cpp +++ b/src/models/dflash2.cpp @@ -177,6 +177,10 @@ static void build_dflash2_selector(llm_graph_context & g, const llama_model & mo } ggml_tensor * unary_bcast = ggml_reshape_4d(ctx0, unary_run, top_k, 1, n_pos, n_blocks); score = ggml_add(ctx0, score, ggml_repeat(ctx0, unary_bcast, score)); + if (hparams.dflash_softcap_post && hparams.f_final_logit_softcapping > 0.0f) { + const float cap = hparams.f_final_logit_softcapping; + score = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, score, 1.0f / cap)), cap); + } ggml_tensor * row = ggml_concat(ctx0, ggml_cast(ctx0, cand_run, GGML_TYPE_F32), diff --git a/src/models/hy-v4-flash.cpp b/src/models/hy-v4-flash.cpp new file mode 100644 index 000000000000..7f5c39232ec6 --- /dev/null +++ b/src/models/hy-v4-flash.cpp @@ -0,0 +1,1081 @@ +#include "models.h" + +#include "llama-kv-cache.h" +#include "llama-kv-cache-dsa.h" +#include "llama-kv-cache-dsa-iswa.h" + +#include + +// hy_v4 iHC, gated MLA and sinks, plus: sparse and sliding-window layers over one MLA geometry, +// sandwich norms, and routed experts at n_expert_latent instead of n_embd + +// a token that cannot be hashed: outside the map, or an embedding (image) position +static constexpr int64_t HY_V4_FLASH_ENGRAM_DEAD = -1; + +// the reference Engram norms leave eps unset, so they use the fp32 machine epsilon, not rms_norm_eps +static constexpr float HY_V4_FLASH_ENGRAM_EPS = 1.1920929e-07f; + +// the weights keep the reference's interleaved rope pairs, the M-RoPE kernels need NeoX halves +// q and k get the same reorder, so their dot product does not change +static ggml_tensor * hy_v4_flash_rope_to_neox(ggml_context * ctx, ggml_tensor * x) { + const int64_t n_rot = x->ne[0]; + x = ggml_reshape_4d(ctx, ggml_cont(ctx, x), 2, n_rot/2, x->ne[1], x->ne[2]); + x = ggml_cont(ctx, ggml_permute(ctx, x, 1, 0, 2, 3)); + return ggml_reshape_3d(ctx, x, n_rot, x->ne[2], x->ne[3]); +} + +// IMROPE rotates the last pairs with the 4th position, the reference uses t there +static ggml_tensor * hy_v4_flash_pos(ggml_context * ctx, ggml_tensor * pos, int64_t n_tokens) { + return ggml_concat(ctx, ggml_view_1d(ctx, pos, 3*n_tokens, 0), ggml_view_1d(ctx, pos, n_tokens, 0), 0); +} + +static size_t hy_v4_flash_elem_offset(const ggml_tensor * t, int64_t i) { + return ggml_row_size(t->type, i); +} + +static ggml_tensor * hy_v4_flash_view_1d(ggml_context * ctx, ggml_tensor * t, int64_t ne0, int64_t i0) { + return ggml_view_1d(ctx, t, ne0, hy_v4_flash_elem_offset(t, i0)); +} + +static ggml_tensor * hy_v4_flash_view_2d(ggml_context * ctx, ggml_tensor * t, int64_t ne0, int64_t ne1, int64_t i0) { + return ggml_view_2d(ctx, t, ne0, ne1, t->nb[1], hy_v4_flash_elem_offset(t, i0)); +} + +void llama_model_hy_v4_flash::load_arch_hparams(llama_model_loader & ml) { + ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); + ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT, hparams.n_layer_dense_lead, false); + ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q); + ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv); + ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH_MLA, hparams.n_embd_head_k_mla_impl); + ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH_MLA, hparams.n_embd_head_v_mla_impl); + ml.get_key_or_arr(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp_arr, hparams.n_layer_all); + ml.get_key(LLM_KV_EXPERT_SHARED_COUNT, hparams.n_expert_shared); + ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale, false); + ml.get_key(LLM_KV_EXPERT_WEIGHTS_NORM, hparams.expert_weights_norm, false); + ml.get_key(LLM_KV_EXPERT_GATING_FUNC, hparams.expert_gating_func, false); + ml.get_key(LLM_KV_EXPERT_LATENT_LENGTH, hparams.n_expert_latent, false); + + // routed experts only; the shared and dense FFNs are not clamped + ml.get_key_or_arr(LLM_KV_SWIGLU_CLAMP_EXP, hparams.swiglu_clamp_exp, hparams.n_layer_all, false); + + ml.get_key(LLM_KV_HYPER_CONNECTION_COUNT, hparams.dsv4_hc_mult); + ml.get_key(LLM_KV_HYPER_CONNECTION_EPSILON, hparams.dsv4_hc_eps); + ml.get_key(LLM_KV_HYPER_CONNECTION_MAGNITUDE, hparams.hc_magnitude); + + hparams.swa_type = LLAMA_SWA_TYPE_STANDARD; + ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa); + ml.get_key(LLM_KV_ROPE_FREQ_BASE_SWA, hparams.rope_freq_base_train_swa); + hparams.rope_freq_scale_train_swa = hparams.rope_freq_scale_train; + ml.get_arr(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, hparams.is_swa_impl); + + // the sections are only used by the VL path (M-RoPE), a text-only file runs the normal rope + ml.get_key_or_arr(LLM_KV_ROPE_DIMENSION_SECTIONS, hparams.rope_sections, 4, false); + if (hparams.use_mrope()) { + const auto & s = hparams.rope_sections; + if (s[0] < 0 || s[1] < 0 || s[2] < 0 || s[3] < 0 || 2 * ((int64_t) s[0] + s[1] + s[2] + s[3]) != (int64_t) hparams.n_rot()) { + throw std::runtime_error("hy_v4_flash: rope sections must sum to n_rot / 2"); + } + } + + // the sparse layers select their context with a pooled indexer + ml.get_key(LLM_KV_ATTENTION_INDEXER_TOP_K, hparams.indexer_top_k); + { + ml.get_key(LLM_KV_ATTENTION_INDEXER_HEAD_COUNT, hparams.indexer_n_head); + ml.get_key(LLM_KV_ATTENTION_INDEXER_KEY_LENGTH, hparams.indexer_head_size); + ml.get_key(LLM_KV_ATTENTION_INDEXER_KPOOL, hparams.indexer_kpool); + ml.get_key(LLM_KV_ATTENTION_INDEXER_KPOOL_SELECT_TAIL, hparams.indexer_kpool_select_tail, false); + ml.get_key_or_arr(LLM_KV_ATTENTION_INDEXER_TYPES, hparams.is_indexer_full_impl, hparams.n_layer(), false); + + // indexer.types says which layers own an indexer, none means no indexer + bool any = false; + for (uint32_t il = 0; il < hparams.n_layer(); ++il) { + any = any || hparams.is_indexer_full(il); + } + + if (!any) { + throw std::runtime_error("hy_v4_flash: no layer owns an indexer"); + } else { + if (hparams.indexer_kpool < 2 || hparams.indexer_top_k % hparams.indexer_kpool != 0) { + throw std::runtime_error(format( + "hy_v4_flash: indexer top_k %u must be a multiple of the pool size %u", + hparams.indexer_top_k, hparams.indexer_kpool)); + } + if (hparams.indexer_kpool_select_tail && hparams.indexer_top_k / hparams.indexer_kpool < 2) { + throw std::runtime_error("hy_v4_flash: indexer top_k must reserve at least one history group and one tail group"); + } + // the indexer cache mirrors the full-attention child, so a window layer cannot own one + for (uint32_t il = 0; il < hparams.n_layer(); ++il) { + if (!hparams.is_indexer_full(il)) { + continue; + } + if (hparams.is_swa(il)) { + throw std::runtime_error(format( + "hy_v4_flash: layer %u is a sliding-window layer and cannot own an indexer", il)); + } + // the indexer splits each head into a nope front and a rope tail, so the tail must fit + if (hparams.n_rot(il) >= hparams.indexer_head_size) { + throw std::runtime_error(format( + "hy_v4_flash: layer %u indexer key length %u must be larger than the rope dimension %u", + il, hparams.indexer_head_size, hparams.n_rot(il))); + } + } + } + } + + GGML_ASSERT(hparams.is_mla()); + + if (!hparams.is_swa_any()) { + throw std::runtime_error("hy_v4_flash: no sliding-window layer, expected a hybrid stack"); + } + + // both layer types share one MLA geometry, only the head count differs + uint32_t n_embd_head_k_mla_swa = 0; + uint32_t n_embd_head_v_mla_swa = 0; + ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH_MLA_SWA, n_embd_head_k_mla_swa, false); + ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH_MLA_SWA, n_embd_head_v_mla_swa, false); + + if ((n_embd_head_k_mla_swa && n_embd_head_k_mla_swa != hparams.n_embd_head_k_mla()) || + (n_embd_head_v_mla_swa && n_embd_head_v_mla_swa != hparams.n_embd_head_v_mla())) { + throw std::runtime_error(format( + "hy_v4_flash: needs one MLA geometry for both layer types, but the " + "sliding-window layers declare key/value %u/%u against %u/%u", + n_embd_head_k_mla_swa, n_embd_head_v_mla_swa, + hparams.n_embd_head_k_mla(), hparams.n_embd_head_v_mla())); + } + + // MLA runs as MQA: one latent row per token + for (uint32_t il = 0; il < hparams.n_layer(); ++il) { + if (hparams.n_head_kv(il) != 1) { + throw std::runtime_error(format( + "hy_v4_flash: layer %u has n_head_kv %u, expected 1 for MLA", + il, hparams.n_head_kv(il))); + } + } + + // Engram is optional: deepseek41 n-gram hash tables, one module per Engram layer + // multipliers, primes and offsets are flat [module][...] arrays, so their lengths give the module count + std::vector e_layers; + ml.get_arr(LLM_KV_PLE_LAYERS, e_layers, false); + if (!e_layers.empty()) { + std::vector mult; + std::vector offsets; + std::vector primes; + ml.get_key(LLM_KV_PLE_NGRAM_SIZE, hparams.ple_ngram_size); + ml.get_key(LLM_KV_PLE_HEADS_PER_NGRAM, hparams.ple_heads_per_ngram); + ml.get_key(LLM_KV_EMBEDDING_LENGTH_PER_LAYER, hparams.ple_head_dim); + ml.get_arr(LLM_KV_PLE_LAYER_MULTIPLIERS, mult); + ml.get_arr(LLM_KV_PLE_HEAD_OFFSETS, offsets); + ml.get_arr(LLM_KV_PLE_HEAD_VOCAB_SIZES, primes); + ml.get_key(LLM_KV_ENGRAM_PAD_TOKEN_ID, hparams.engram_pad_id); + ml.get_arr(LLM_KV_ENGRAM_TOKEN_MAP, engram_token_map); + + const size_t n_e = e_layers.size(); + const size_t n_gram = hparams.ple_ngram_size; + const size_t n_cols = n_gram >= 2 ? (n_gram - 1)*hparams.ple_heads_per_ngram : 0; + if (n_cols == 0 || hparams.ple_head_dim == 0 || + mult.size() != n_e*n_gram || primes.size() != n_e*n_cols || offsets.size() != n_e*n_cols || + primes.size() > LLAMA_MAX_PLE_HEADS || + hparams.engram_pad_id >= engram_token_map.size()) { + throw std::runtime_error("hy_v4_flash engram metadata is inconsistent"); + } + for (size_t e = 0; e < n_e; ++e) { + if (e_layers[e] >= hparams.n_layer() || (e > 0 && e_layers[e] <= e_layers[e - 1])) { + throw std::runtime_error(format("hy_v4_flash engram layer %u is out of range or out of order", e_layers[e])); + } + hparams.is_ple_impl.set(e_layers[e]); + } + for (size_t c = 0; c < n_e*n_cols; ++c) { + // a bucket count of 0 traps in the hash; row ids are int32 + if (primes[c] < 2 || offsets[c] > (uint64_t) INT32_MAX || primes[c] > (uint64_t) INT32_MAX - offsets[c]) { + throw std::runtime_error(format("hy_v4_flash engram head %zu: bucket range out of range", c)); + } + hparams.ple_head_offsets[c] = (uint32_t) offsets[c]; + hparams.ple_head_vocab_sizes[c] = (uint32_t) primes[c]; + } + engram_multipliers = std::move(mult); + hparams.ple_n_heads = (uint32_t) n_cols; + hparams.ple_n_modules = (uint32_t) n_e; + } + + type = LLM_TYPE_UNKNOWN; +} + +void llama_model_hy_v4_flash::load_arch_tensors(llama_model_loader &) { + LLAMA_LOAD_LOCALS; + + const int64_t n_embd_head_k_mla = hparams.n_embd_head_k_mla(); + const int64_t n_embd_head_v_mla = hparams.n_embd_head_v_mla(); + const int64_t n_embd_head_qk_rope = hparams.n_rot(); + const int64_t n_embd_head_qk_nope = n_embd_head_k_mla - n_embd_head_qk_rope; + GGML_ASSERT(n_embd_head_qk_nope >= 1); + + const int64_t q_lora_rank = hparams.n_lora_q; + const int64_t kv_lora_rank = hparams.n_lora_kv; + const int64_t n_ff_exp = hparams.n_ff_exp(); + const int64_t n_expert_shared = hparams.n_expert_shared; + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t n_embd_latent = hparams.n_expert_latent ? hparams.n_expert_latent : n_embd; + + 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}, 0); + + hc_head_fn = create_tensor(tn(LLM_TENSOR_HC_HEAD_FN, "weight"), {hc * n_embd, hc}, 0); + hc_head_base = create_tensor(tn(LLM_TENSOR_HC_HEAD_BASE, "weight"), {hc}, 0); + hc_head_scale = create_tensor(tn(LLM_TENSOR_HC_HEAD_SCALE, "weight"), {1}, 0); + + const int64_t ple_n_heads = hparams.ple_n_heads; + const int64_t ple_head_dim = hparams.ple_head_dim; + if (ple_n_heads > 0) { + // all modules share one table, so the row count is the end of the last bucket + int64_t n_rows = 0; + for (size_t c = 0; c < (size_t) hparams.ple_n_modules*ple_n_heads; ++c) { + n_rows = std::max(n_rows, (int64_t) hparams.ple_head_offsets[c] + hparams.ple_head_vocab_sizes[c]); + } + // 118 GiB at the full size: read lazily, so only the rows a batch hashes to are faulted in + per_layer_tok_embd = create_tensor(tn(LLM_TENSOR_PER_LAYER_TOKEN_EMBD, "weight"), {ple_head_dim, n_rows}, TENSOR_READ_LAZY); + } + + // the MTP block is a sparse layer after the trunk, without hyper-connections + for (int i = 0; i < (int) hparams.n_layer_all; ++i) { + auto & layer = layers[i]; + const bool is_nextn = i >= n_layer; + + // the MTP block is not supported yet, its tensors are skipped + const int flags = is_nextn ? TENSOR_SKIP | TENSOR_NOT_REQUIRED : 0; + + // the sliding-window layers carry more heads over the same latent geometry + const int64_t n_head_l = hparams.n_head(i); + + layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, flags); + layer.attn_sinks = create_tensor(tn(LLM_TENSOR_ATTN_SINKS, "weight", i), {n_head_l}, flags); + + layer.wq_a = create_tensor(tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank}, flags); + layer.attn_q_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank}, flags); + layer.wq_b = create_tensor(tn(LLM_TENSOR_ATTN_Q_B, "weight", i), {q_lora_rank, n_head_l * n_embd_head_k_mla}, flags); + layer.wkv_a_mqa = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_MQA, "weight", i), {n_embd, kv_lora_rank + n_embd_head_qk_rope}, flags); + layer.attn_kv_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank}, flags); + layer.wk_b = create_tensor(tn(LLM_TENSOR_ATTN_K_B, "weight", i), {n_embd_head_qk_nope, kv_lora_rank, n_head_l}, flags); + layer.wv_b = create_tensor(tn(LLM_TENSOR_ATTN_V_B, "weight", i), {kv_lora_rank, n_embd_head_v_mla, n_head_l}, flags); + layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_head_l * n_embd_head_v_mla, n_embd}, flags); + layer.wqkv_gate = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "weight", i), {n_embd, n_head_l * n_embd_head_v_mla}, flags); + layer.attn_post_norm = create_tensor(tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), {n_embd}, flags); + + if (!is_nextn) { + layer.hc_attn_fn = create_tensor(tn(LLM_TENSOR_HC_ATTN_FN, "weight", i), {hc * n_embd, 2 * hc}, flags); + layer.hc_attn_base = create_tensor(tn(LLM_TENSOR_HC_ATTN_BASE, "weight", i), {2 * hc}, flags); + layer.hc_attn_scale = create_tensor(tn(LLM_TENSOR_HC_ATTN_SCALE, "weight", i), {2}, flags); + layer.hc_ffn_fn = create_tensor(tn(LLM_TENSOR_HC_FFN_FN, "weight", i), {hc * n_embd, 2 * hc}, flags); + layer.hc_ffn_base = create_tensor(tn(LLM_TENSOR_HC_FFN_BASE, "weight", i), {2 * hc}, flags); + layer.hc_ffn_scale = create_tensor(tn(LLM_TENSOR_HC_FFN_SCALE, "weight", i), {2}, flags); + } else { + // the draft block folds the next token's embedding into the trunk's final hidden state + layer.nextn.enorm = create_tensor(tn(LLM_TENSOR_NEXTN_ENORM, "weight", i), {n_embd}, flags); + layer.nextn.hnorm = create_tensor(tn(LLM_TENSOR_NEXTN_HNORM, "weight", i), {n_embd}, flags); + layer.nextn.eh_proj = create_tensor(tn(LLM_TENSOR_NEXTN_EH_PROJ, "weight", i), {2 * n_embd, n_embd}, flags); + layer.nextn.shared_head_norm = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, "weight", i), {n_embd}, flags); + } + + layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, flags); + layer.ffn_post_norm = create_tensor(tn(LLM_TENSOR_FFN_POST_NORM, "weight", i), {n_embd}, flags); + + // is_indexer_full() only covers the trunk, and the draft block always owns an indexer + if (is_nextn || hparams.is_indexer_full(i)) { + const int64_t n_idx = hparams.indexer_head_size; + const int64_t n_idx_head = hparams.indexer_n_head; + const int64_t kpool = hparams.indexer_kpool; + + layer.indexer_attn_k = create_tensor(tn(LLM_TENSOR_INDEXER_ATTN_K, "weight", i), {n_embd, n_idx}, flags); + layer.indexer_k_norm = create_tensor(tn(LLM_TENSOR_INDEXER_K_NORM, "weight", i), {n_idx}, flags); + // the pool averages a projection of the normed key, weighted by another projection of it + layer.indexer_kpool_value = create_tensor(tn(LLM_TENSOR_INDEXER_KPOOL_VALUE, "weight", i), {n_idx, n_idx}, flags); + layer.indexer_kpool_gate = create_tensor(tn(LLM_TENSOR_INDEXER_KPOOL_GATE, "weight", i), {n_idx, n_idx}, flags); + layer.indexer_kpool_ape = create_tensor(tn(LLM_TENSOR_INDEXER_KPOOL_APE, "weight", i), {n_idx, kpool}, flags); + layer.indexer_comp_norm = create_tensor(tn(LLM_TENSOR_INDEXER_COMPRESSOR_NORM, "weight", i), {n_idx}, flags); + layer.indexer_attn_q_b = create_tensor(tn(LLM_TENSOR_INDEXER_ATTN_Q_B, "weight", i), {q_lora_rank, n_idx*n_idx_head}, flags); + layer.indexer_proj = create_tensor(tn(LLM_TENSOR_INDEXER_PROJ, "weight", i), {n_embd, n_idx_head}, flags); + } + + if (!is_nextn && engram_index(i) >= 0) { + // hc key projections and the value projection fused into one matmul, as deepseek41, plus a bias + layer.engram_kv = create_tensor(tn(LLM_TENSOR_ENGRAM_KV, "weight", i), {ple_n_heads * ple_head_dim, n_embd * (hc + 1)}, flags); + layer.engram_kv_b = create_tensor(tn(LLM_TENSOR_ENGRAM_KV_B, "weight", i), {n_embd, hc + 1}, flags); + layer.engram_gate = create_tensor(tn(LLM_TENSOR_ENGRAM_GATE, "weight", i), {n_embd, hc}, flags); + layer.engram_lookup_norm = create_tensor(tn(LLM_TENSOR_ENGRAM_LOOKUP_NORM, "weight", i), {ple_head_dim, ple_n_heads}, flags); + layer.engram_pre_gamma = create_tensor(tn(LLM_TENSOR_ENGRAM_PRE_GAMMA, "weight", i), {n_embd}, flags); + layer.engram_hc_scale = create_tensor(tn(LLM_TENSOR_ENGRAM_HC_SCALE, "weight", i), {n_embd, hc}, flags); + } + + if (!is_nextn && i < (int) hparams.n_layer_dense_lead) { + layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, flags); + layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), { n_ff, n_embd}, flags); + layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, flags); + } else { + if (n_expert == 0 || n_expert_used == 0) { + throw std::runtime_error("hy_v4_flash: n_expert and n_expert_used must be > 0"); + } + + layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, flags); + layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, TENSOR_NOT_REQUIRED | flags); + + if (hparams.n_expert_latent) { + layer.ffn_routed_down = create_tensor(tn(LLM_TENSOR_FFN_ROUTED_DOWN, "weight", i), {n_embd, n_embd_latent}, flags); + layer.ffn_routed_up = create_tensor(tn(LLM_TENSOR_FFN_ROUTED_UP, "weight", i), {n_embd_latent, n_embd}, flags); + } + + layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd_latent, n_ff_exp, n_expert}, flags); + layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd_latent, n_ff_exp, n_expert}, flags); + layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd_latent, n_expert}, flags); + + layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {n_embd, n_ff_exp * n_expert_shared}, flags); + layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_exp * n_expert_shared, n_embd}, flags); + layer.ffn_up_shexp = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), {n_embd, n_ff_exp * n_expert_shared}, flags); + } + } +} + +int llama_model_hy_v4_flash::engram_index(int il) const { + if (hparams.ple_n_heads == 0 || !hparams.is_ple(il)) { + return -1; + } + int e = 0; + for (int j = 0; j < il; ++j) { + e += hparams.is_ple(j); + } + return e; +} + +void llama_model_hy_v4_flash::engram_hash(int e, const llama_ubatch & ubatch, + const std::vector & prev, + std::vector & ids, std::vector & valid) const { + const int64_t n_gram = hparams.ple_ngram_size; + const int64_t n_prev = n_gram - 1; + const int64_t n_head = hparams.ple_heads_per_ngram; + const int64_t n_cols = hparams.ple_n_heads; + + const uint64_t * mult = engram_multipliers.data() + (size_t) e*n_gram; + const uint32_t * primes = hparams.ple_head_vocab_sizes.data() + (size_t) e*n_cols; + const uint32_t * offs = hparams.ple_head_offsets.data() + (size_t) e*n_cols; + const int64_t pad = engram_token_map[hparams.engram_pad_id]; + + const auto cid = [&](llama_token t) -> int64_t { + return t < 0 || t >= (llama_token) engram_token_map.size() ? HY_V4_FLASH_ENGRAM_DEAD : engram_token_map[t]; + }; + + ids.resize(ubatch.n_tokens*n_cols); + valid.resize(ubatch.n_tokens*n_cols); + + std::vector toks(n_gram); + + for (int64_t i = 0; i < ubatch.n_tokens; ++i) { + // a short history is padded with the pad id, only an embedding position is invalid + const bool is_embd = !ubatch.token || (ubatch.is_mixed() && ubatch.type[i]); + int64_t c = is_embd ? HY_V4_FLASH_ENGRAM_DEAD : cid(ubatch.token[i]); + const bool dead = c == HY_V4_FLASH_ENGRAM_DEAD; + toks[0] = dead ? pad : c; + for (int64_t s = 1; s < n_gram; ++s) { + c = ubatch.pos[i] - s < 0 ? HY_V4_FLASH_ENGRAM_DEAD : cid(prev[i*n_prev + (n_prev - s)]); + toks[s] = c == HY_V4_FLASH_ENGRAM_DEAD ? pad : c; + } + + uint64_t rolling = toks[0]*mult[0]; + for (int64_t o = 1; o < n_gram; ++o) { + rolling ^= toks[o]*mult[o]; + for (int64_t h = 0; h < n_head; ++h) { + const int64_t col = (o - 1)*n_head + h; + ids [i*n_cols + col] = (int32_t) (rolling % primes[col] + offs[col]); + valid[i*n_cols + col] = dead ? 0.0f : 1.0f; + } + } + } +} + +// the row ids and their validity are host-side, so they are graph inputs rather than computed +class llm_graph_input_hy_v4_flash : public llm_graph_input_i { +public: + llm_graph_input_hy_v4_flash(const llama_model_hy_v4_flash & model, + const llama_kv_cache_context * mctx) : model(model), mctx(mctx) {} + + void set_input(const llama_ubatch * ubatch) override; + bool can_reuse(const llm_graph_params & params) override; + + std::vector engram_ids; + std::vector engram_valid; + + const llama_model_hy_v4_flash & model; + const llama_kv_cache_context * mctx; +}; + +void llm_graph_input_hy_v4_flash::set_input(const llama_ubatch * ubatch) { + if (engram_ids.empty()) { + return; + } + + // a token shared by several sequences has the same history in each, so its first one resolves it + std::vector prev; + mctx->get_prev_tokens(*ubatch, model.hparams.ple_ngram_size - 1, prev); + + // hash every module before the first gather, so a lazily read table gets one batched readahead + std::vector> ids(engram_ids.size()); + std::vector> valid(engram_ids.size()); + std::vector all; + for (size_t e = 0; e < engram_ids.size(); ++e) { + model.engram_hash((int) e, *ubatch, prev, ids[e], valid[e]); + all.insert(all.end(), ids[e].begin(), ids[e].end()); + } + if (model.can_prefetch.count(model.per_layer_tok_embd)) { + llama_prefetch_rows(model.per_layer_tok_embd, all.data(), all.size()); + } + for (size_t e = 0; e < engram_ids.size(); ++e) { + if (engram_ids[e]->buffer) { + ggml_backend_tensor_set(engram_ids[e], ids[e].data(), 0, ids[e].size()*sizeof(int32_t)); + } + if (engram_valid[e]->buffer) { + ggml_backend_tensor_set(engram_valid[e], valid[e].data(), 0, valid[e].size()*sizeof(float)); + } + } +} + +bool llm_graph_input_hy_v4_flash::can_reuse(const llm_graph_params & params) { + // the memory context is rebuilt for every batch, re-fetch it as deepseek41 does + mctx = static_cast(params.mctx)->get_dsa()->get_mla(); + + bool res = true; + for (auto * t : engram_ids) { + res &= t->ne[0] == (int64_t) (model.hparams.ple_n_heads*params.ubatch.n_tokens); + } + return res; +} + +std::unique_ptr llama_model_hy_v4_flash::build_arch_graph(const llm_graph_params & params) const { + if (params.gtype == LLM_GRAPH_TYPE_DECODER_MTP) { + throw std::runtime_error("hy_v4_flash: the MTP block is not supported yet"); + } + return std::make_unique(*this, params); +} + +ggml_tensor * llama_model_hy_v4_flash::graph::build_engram( + const llama_model & model, + ggml_tensor * x, + ggml_tensor * rows, + ggml_tensor * valid, + int il) const { + const auto & layer = model.layers[il]; + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nt = x->ne[2]; + const int64_t n_cols = hparams.ple_n_heads; + const int64_t head_dim = hparams.ple_head_dim; + + GGML_ASSERT(rows->ne[0] == head_dim && rows->ne[1] == n_cols && rows->ne[2] == nt); + + // unlike deepseek41, each looked-up row is RMS-normed and scaled by its head weight + ggml_tensor * r = ggml_rms_norm(ctx0, rows, HY_V4_FLASH_ENGRAM_EPS); + r = ggml_mul(ctx0, r, layer.engram_lookup_norm); + r = ggml_mul(ctx0, r, ggml_reshape_3d(ctx0, valid, 1, n_cols, nt)); + r = ggml_reshape_2d(ctx0, r, head_dim*n_cols, nt); + cb(r, "engram_rows_normed", il); + + // the fused key/value projection has a bias + ggml_tensor * kv = build_lora_mm(layer.engram_kv, r); + kv = ggml_add(ctx0, ggml_reshape_3d(ctx0, kv, n_embd, hc + 1, nt), layer.engram_kv_b); + cb(kv, "engram_kv", il); + + ggml_tensor * key = ggml_cont(ctx0, ggml_view_3d(ctx0, kv, n_embd, hc, nt, kv->nb[1], kv->nb[2], 0)); + ggml_tensor * value = ggml_cont(ctx0, ggml_view_3d(ctx0, kv, n_embd, 1, nt, kv->nb[1], kv->nb[2], hc*kv->nb[1])); + + // the gate is deepseek41's: engram_gate folds norm_key.w * norm_query.w + ggml_tensor * egate = ggml_is_quantized(layer.engram_gate->type) ? ggml_cast(ctx0, layer.engram_gate, GGML_TYPE_F32) : layer.engram_gate; + ggml_tensor * dot = ggml_mul(ctx0, ggml_mul(ctx0, ggml_rms_norm(ctx0, x, HY_V4_FLASH_ENGRAM_EPS), ggml_rms_norm(ctx0, key, HY_V4_FLASH_ENGRAM_EPS)), egate); + dot = ggml_scale(ctx0, ggml_sum_rows(ctx0, dot), 1.0f/sqrtf((float) n_embd)); + cb(dot, "engram_dot", il); + + // sigmoid(copysign(sqrt(max(|dot|, 1e-6)), dot)); sign(0) = +1 as in copysign + ggml_tensor * mag = ggml_sqrt(ctx0, ggml_clamp(ctx0, ggml_abs(ctx0, dot), 1e-6f, INFINITY)); + ggml_tensor * sign = ggml_scale_bias(ctx0, ggml_step(ctx0, ggml_neg(ctx0, dot)), -2.0f, 1.0f); + ggml_tensor * gate = ggml_sigmoid(ctx0, ggml_mul(ctx0, mag, sign)); + cb(gate, "engram_gate", il); + + // the delta is the normed value scaled by a learned gamma + ggml_tensor * signal = ggml_mul(ctx0, ggml_rms_norm(ctx0, value, HY_V4_FLASH_ENGRAM_EPS), layer.engram_pre_gamma); + // the per-hc offset is additive and per channel + ggml_tensor * scale = ggml_add(ctx0, ggml_repeat_4d(ctx0, gate, n_embd, hc, nt, 1), layer.engram_hc_scale); + cb(scale, "engram_scale", il); + + ggml_tensor * delta = ggml_mul(ctx0, ggml_repeat_4d(ctx0, signal, n_embd, hc, nt, 1), scale); + + // mask the whole delta of a token without a valid n-gram, as the bias still reaches the value path + ggml_tensor * any = ggml_sum_rows(ctx0, ggml_reshape_2d(ctx0, valid, n_cols, nt)); + any = ggml_step(ctx0, any); + delta = ggml_mul(ctx0, delta, ggml_reshape_3d(ctx0, any, 1, 1, nt)); + cb(delta, "engram_delta", il); + + return ggml_add(ctx0, x, delta); +} + +// reduce hc streams x[:,i,:] weighted by w[i,:] -> [n_embd, n_tokens] +ggml_tensor * llama_model_hy_v4_flash::graph::build_hc_reduce( + ggml_tensor * x, + ggml_tensor * weights, + int il) const { + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nt = x->ne[2]; + GGML_ASSERT(x->ne[0] == n_embd); + GGML_ASSERT(x->ne[1] == hc); + + // the fused node is registered per layer, so the head reduce (il < 0) keeps the loop + if (cparams.fused_dsv4_hc_pre && il >= 0) { + ggml_tensor * result = ggml_dsv4_hc_pre(ctx0, x, weights); + res->add_fused_node({LLM_FUSED_OP_DSV4_HC_PRE, result, il}); + return result; + } + + ggml_tensor * result = nullptr; + for (int64_t ih = 0; ih < hc; ++ih) { + ggml_tensor * xh = ggml_view_2d(ctx0, x, n_embd, nt, x->nb[2], ih * x->nb[1]); + ggml_tensor * wh = ggml_view_2d(ctx0, weights, 1, nt, weights->nb[1], ih * weights->nb[0]); + ggml_tensor * cur = ggml_mul(ctx0, xh, wh); + result = result ? ggml_add(ctx0, result, cur) : cur; + } + return result; +} + +llama_model_hy_v4_flash::graph::hc_pre +llama_model_hy_v4_flash::graph::build_hc_pre( + ggml_tensor * x, + ggml_tensor * hc_fn, + ggml_tensor * hc_scale, + ggml_tensor * hc_base, + int il) const { + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nt = x->ne[2]; + GGML_ASSERT(x->ne[0] == n_embd && x->ne[1] == hc); + + ggml_tensor * flat = ggml_reshape_2d(ctx0, x, hc * n_embd, nt); + ggml_tensor * flat_norm = ggml_rms_norm(ctx0, flat, hparams.f_norm_rms_eps); + ggml_tensor * mixes = ggml_mul_mat(ctx0, hc_fn, flat_norm); + cb(mixes, "hc_mixes", il); + + ggml_tensor * scale_pre = hy_v4_flash_view_1d(ctx0, hc_scale, 1, 0); + ggml_tensor * scale_post = hy_v4_flash_view_1d(ctx0, hc_scale, 1, 1); + ggml_tensor * base_pre = hy_v4_flash_view_1d(ctx0, hc_base, hc, 0); + ggml_tensor * base_post = hy_v4_flash_view_1d(ctx0, hc_base, hc, hc); + + ggml_tensor * pre = hy_v4_flash_view_2d(ctx0, mixes, hc, nt, 0); + pre = ggml_mul(ctx0, pre, scale_pre); + pre = ggml_add(ctx0, pre, base_pre); + pre = ggml_sigmoid(ctx0, pre); + pre = ggml_scale_bias(ctx0, pre, 1.0f, hparams.dsv4_hc_eps); + cb(pre, "hc_pre", il); + + ggml_tensor * post = hy_v4_flash_view_2d(ctx0, mixes, hc, nt, hc); + post = ggml_mul(ctx0, post, scale_post); + post = ggml_add(ctx0, post, base_post); + post = ggml_sigmoid(ctx0, post); + post = ggml_scale(ctx0, post, hparams.hc_magnitude); + post = ggml_scale_bias(ctx0, post, 1.0f, hparams.dsv4_hc_eps); + cb(post, "hc_post_gate", il); + + return { build_hc_reduce(x, pre, il), post }; +} + +ggml_tensor * llama_model_hy_v4_flash::graph::build_hc_post( + ggml_tensor * x, + ggml_tensor * residual, + ggml_tensor * post, + int il) const { + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nt = x->ne[1]; + GGML_ASSERT(x->ne[0] == n_embd); + GGML_ASSERT(residual->ne[1] == hc); + + // comb is the identity here: each stream keeps its own residual, hy_v4 has no cross-stream mix + if (cparams.fused_dsv4_hc_post) { + ggml_tensor * result = ggml_dsv4_hc_post(ctx0, x, residual, post, nullptr); + res->add_fused_node({LLM_FUSED_OP_DSV4_HC_POST, result, il}); + return result; + } + + ggml_tensor * out = nullptr; + for (int64_t i = 0; i < hc; ++i) { + ggml_tensor * res_i = ggml_view_2d(ctx0, residual, n_embd, nt, residual->nb[2], i * residual->nb[1]); + ggml_tensor * post_i = ggml_view_2d(ctx0, post, 1, nt, post->nb[1], i * post->nb[0]); + ggml_tensor * cur = ggml_add(ctx0, res_i, ggml_mul(ctx0, x, post_i)); + cur = ggml_reshape_3d(ctx0, cur, n_embd, 1, nt); + out = out ? ggml_concat(ctx0, out, cur, 1) : cur; + } + + return out; +} + +ggml_tensor * llama_model_hy_v4_flash::graph::build_hc_head( + ggml_tensor * x, + ggml_tensor * hc_fn, + ggml_tensor * hc_scale, + ggml_tensor * hc_base) const { + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nt = x->ne[2]; + + ggml_tensor * flat = ggml_reshape_2d(ctx0, x, hc * n_embd, nt); + ggml_tensor * flat_norm = ggml_rms_norm(ctx0, flat, hparams.f_norm_rms_eps); + ggml_tensor * mixes = ggml_mul_mat(ctx0, hc_fn, flat_norm); + cb(mixes, "hc_head_mixes", -1); + + ggml_tensor * pre = ggml_mul(ctx0, mixes, hc_scale); + pre = ggml_add(ctx0, pre, hc_base); + pre = ggml_sigmoid(ctx0, pre); + pre = ggml_scale_bias(ctx0, pre, 1.0f, hparams.dsv4_hc_eps); + cb(pre, "hc_head_pre", -1); + + return build_hc_reduce(x, pre, -1); +} + +// the pools of the indexer, rebuilt from the cells of the indexer cache for every ubatch +class llama_model_hy_v4_flash::llm_graph_input_pool : public llm_graph_input_i { +public: + llm_graph_input_pool(const llama_kv_cache_context * mctx, uint32_t kpool) : mctx(mctx), kpool(kpool) {} + virtual ~llm_graph_input_pool() = default; + + void set_input(const llama_ubatch * ubatch) override { + mctx->set_input_kpool(pool_idxs, pool_pos, pool_mask, tail_idxs, ubatch, kpool); + } + + bool can_reuse(const llm_graph_params & params) override { + mctx = static_cast(params.mctx)->get_dsa()->get_lid(); + + bool res = true; + res &= pool_idxs->ne[1] == n_pool(mctx, params.cparams.n_seq_max, kpool); + res &= tail_idxs->ne[1] == params.ubatch.n_tokens; + return res; + } + + // every cell can start a pool, plus one misaligned pool per sequence + static int64_t n_pool(const llama_kv_cache_context * mctx, uint32_t n_seq_max, uint32_t kpool) { + return mctx->get_n_kv()/kpool + n_seq_max; + } + + ggml_tensor * pool_idxs = nullptr; // I32 [kpool, n_pool] + ggml_tensor * pool_pos = nullptr; // I32 [n_pool*n_pos_per_embd] + ggml_tensor * pool_mask = nullptr; // F16 [n_pool, n_tokens] + ggml_tensor * tail_idxs = nullptr; // I32 [kpool, n_tokens] + + const llama_kv_cache_context * mctx; + const uint32_t kpool; +}; + +llama_model_hy_v4_flash::llm_graph_input_pool * llama_model_hy_v4_flash::graph::build_inp_pool( + llm_graph_input_attn_k_dsa_iswa * inp_attn) { + const auto * mctx_lid = inp_attn->get_dsa()->mctx->get_lid(); + + const uint32_t kpool = hparams.indexer_kpool; + const int64_t n_pool = llm_graph_input_pool::n_pool(mctx_lid, cparams.n_seq_max, kpool); + + auto inp = std::make_unique(mctx_lid, kpool); + + inp->pool_idxs = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, kpool, n_pool); + inp->pool_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_pool*hparams.n_pos_per_embd()); + 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, n_tokens); + + ggml_set_input(inp->pool_idxs); + ggml_set_input(inp->pool_pos); + ggml_set_input(inp->pool_mask); + ggml_set_input(inp->tail_idxs); + + return (llm_graph_input_pool *) res->add_input(std::move(inp)); +} + +// rotate only the trailing n_rot of each indexer head, leaving the head's front half untouched +ggml_tensor * llama_model_hy_v4_flash::graph::build_indexer_rope( + ggml_tensor * x, ggml_tensor * pos, int64_t n_idx, float freq_base, int il) const { + const int64_t n_nope = n_idx - n_rot; + GGML_ASSERT(n_nope > 0); + + ggml_tensor * front = ggml_view_3d(ctx0, x, n_nope, x->ne[1], x->ne[2], + x->nb[1], x->nb[2], 0); + ggml_tensor * back = ggml_view_3d(ctx0, x, n_rot, x->ne[1], x->ne[2], + x->nb[1], x->nb[2], ggml_row_size(x->type, n_nope)); + + // the same base the layer's own attention uses, so a cparams override reaches the indexer too + if (hparams.use_mrope()) { + int sections[GGML_MROPE_SECTIONS]; + std::copy(hparams.rope_sections.begin(), hparams.rope_sections.end(), sections); + + back = ggml_rope_multi(ctx0, hy_v4_flash_rope_to_neox(ctx0, back), pos, nullptr, n_rot, sections, rope_type, n_ctx_orig, + freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow); + } else { + back = ggml_rope_ext(ctx0, ggml_cont(ctx0, back), pos, nullptr, n_rot, rope_type, n_ctx_orig, + freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow); + } + cb(back, "indexer_rope", il); + + return ggml_concat(ctx0, ggml_cont(ctx0, front), back, 0); +} + +// the cells a token attends to: the best scored pools of its sequence plus its own pool +ggml_tensor * llama_model_hy_v4_flash::graph::build_pool_select( + ggml_tensor * cur, ggml_tensor * qr, ggml_tensor * inp_pos, float freq_base, + const llama_layer & layer, + llm_graph_input_attn_k_dsa_iswa * inp_attn, llm_graph_input_pool * inp_pool, + ggml_tensor * kq_mask, int il) { + const auto * inp_dsa = inp_attn->get_dsa(); + const auto * mctx_lid = inp_dsa->mctx->get_lid(); + + const int64_t n_idx_head = hparams.indexer_n_head; + const int64_t n_idx = hparams.indexer_head_size; + const int64_t kpool = hparams.indexer_kpool; + const int64_t n_pool = inp_pool->pool_idxs->ne[1]; + const int64_t n_kv = mctx_lid->get_n_kv(); + + // the query comes from the q lora residual of the main attention + ggml_tensor * iq = build_lora_mm(layer.indexer_attn_q_b, qr); + iq = ggml_reshape_3d(ctx0, iq, n_idx, n_idx_head, n_tokens); + iq = build_indexer_rope(iq, inp_pos, n_idx, freq_base, il); + cb(iq, "indexer_q", il); + + // key side: weight-only RMSNorm, unlike glm5-next's LayerNorm with a bias this model lacks + ggml_tensor * ik = build_lora_mm(layer.indexer_attn_k, cur); + ik = build_norm(ik, layer.indexer_k_norm, nullptr, LLM_NORM_RMS, il); + cb(ik, "indexer_k", il); + + // the value and the gate are linear in the token's key, so the cache holds them and the pools are built from them + ggml_tensor * iv = build_lora_mm(layer.indexer_kpool_value, ik); + ggml_tensor * ig = build_lora_mm(layer.indexer_kpool_gate, ik); + cb(ig, "indexer_gate", il); + + ggml_tensor * packed = ggml_reshape_3d(ctx0, ggml_concat(ctx0, iv, ig, 0), 2*n_idx, 1, n_tokens); + ggml_build_forward_expand(gf, mctx_lid->cpy_k(ctx0, packed, inp_dsa->get_k_idxs_lid(), il)); + + // the members of every pool, from the cache this ubatch just wrote to + ggml_tensor * k_lid = mctx_lid->get_k(ctx0, il); + GGML_ASSERT(k_lid->ne[0] == 2*n_idx && k_lid->ne[1] == 1 && k_lid->ne[2] == n_kv && k_lid->ne[3] == 1); + k_lid = ggml_view_2d(ctx0, k_lid, 2*n_idx, n_kv, k_lid->nb[2], 0); + + ggml_tensor * rows = ggml_get_rows(ctx0, k_lid, ggml_reshape_1d(ctx0, inp_pool->pool_idxs, kpool*n_pool)); + rows = ggml_reshape_3d(ctx0, rows, 2*n_idx, kpool, n_pool); + + ggml_tensor * pv = ggml_view_3d(ctx0, rows, n_idx, kpool, n_pool, rows->nb[1], rows->nb[2], 0); + ggml_tensor * pg = ggml_view_3d(ctx0, rows, n_idx, kpool, n_pool, rows->nb[1], rows->nb[2], + ggml_row_size(rows->type, n_idx)); + + // per channel softmax over the members of the gate plus the member's position bias, then the weighted sum of the values + ggml_tensor * logits = ggml_add(ctx0, pg, layer.indexer_kpool_ape); + logits = ggml_cont(ctx0, ggml_permute(ctx0, logits, 1, 0, 2, 3)); // [kpool, n_idx, n_pool] + // fold the pool axis into rows: soft_max maps ne[2] to a CUDA gridDim.y that caps at 65535 + ggml_tensor * probs = ggml_soft_max(ctx0, ggml_reshape_2d(ctx0, logits, kpool, n_idx*n_pool)); + probs = ggml_reshape_3d(ctx0, probs, kpool, n_idx, n_pool); + + pv = ggml_cont(ctx0, ggml_permute(ctx0, pv, 1, 0, 2, 3)); + ggml_tensor * pooled = ggml_sum_rows(ctx0, ggml_mul(ctx0, probs, pv)); // [1, n_idx, n_pool] + pooled = ggml_reshape_2d(ctx0, pooled, n_idx, n_pool); + + // the pooled key is normed, then rotated at the position of its first member + pooled = build_norm(pooled, layer.indexer_comp_norm, nullptr, LLM_NORM_RMS, il); + pooled = build_indexer_rope(ggml_reshape_3d(ctx0, pooled, n_idx, 1, n_pool), inp_pool->pool_pos, n_idx, freq_base, il); + cb(pooled, "indexer_pool_k", il); + + ggml_tensor * weights = build_lora_mm(layer.indexer_proj, cur); + weights = ggml_scale(ctx0, weights, 1.0f / sqrtf(float(n_idx * n_idx_head))); + cb(weights, "indexer_weights", il); + + ggml_tensor * score = ggml_lightning_indexer(ctx0, iq, pooled, weights, inp_pool->pool_mask); + cb(score, "indexer_score", il); + + // the token's own pool is always kept, so it does not take a pick + const int64_t n_top_pool = std::min(n_pool, hparams.indexer_top_k / kpool - hparams.indexer_kpool_select_tail); + ggml_tensor * top_k = ggml_top_k(ctx0, score, n_top_pool); // [n_top_pool, n_tokens], unordered + + ggml_tensor * tail = hparams.indexer_kpool_select_tail ? inp_pool->tail_idxs : nullptr; + + if (cparams.fused_top_k_mask) { + // a pick scored -inf (another sequence, a later or unused pool) is dropped + ggml_tensor * sel = ggml_top_k_mask(ctx0, kq_mask, top_k, score, inp_pool->pool_idxs, tail); + res->add_fused_node({LLM_FUSED_OP_TOP_K_MASK, sel, il}); + cb(sel, "indexer_sel", il); + + return sel; + } + + // without the fused op, the picks are expanded to their cells + // a pick scored -inf is only taken once every visible pool is, so its cells are either hidden by the kq_mask or already kept + ggml_tensor * cells = ggml_get_rows(ctx0, inp_pool->pool_idxs, + ggml_reshape_1d(ctx0, ggml_cont(ctx0, top_k), n_top_pool*n_tokens)); // [kpool, n_top_pool*n_tokens] + cells = ggml_reshape_2d(ctx0, cells, kpool*n_top_pool, n_tokens); + if (tail) { + cells = ggml_concat(ctx0, cells, tail, 0); + } + + ggml_tensor * sel = build_top_k_mask(kq_mask, cells, il); + cb(sel, "indexer_sel", il); + + return sel; +} + +ggml_tensor * llama_model_hy_v4_flash::graph::build_attention( + const llama_model & model, + llm_graph_input_attn_k_dsa_iswa * inp_attn, + llm_graph_input_pool * inp_pool, + ggml_tensor * cur, + ggml_tensor * inp_pos, + int il) { + const auto & layer = model.layers[il]; + + const int64_t n_head_l = hparams.n_head(il); + const int64_t n_embd_head_k = hparams.n_embd_head_k_mla(); + const int64_t n_embd_head_qk_rope = hparams.n_rot(); + const int64_t n_embd_head_qk_nope = n_embd_head_k - n_embd_head_qk_rope; + const uint32_t kv_lora_rank = hparams.n_lora_kv; + + const float kq_scale = 1.0f / sqrtf(float(n_embd_head_k)); + const float freq_base_l = model.get_rope_freq_base(cparams, il); + + ggml_tensor * qr = build_lora_mm(layer.wq_a, cur); + qr = build_norm(qr, layer.attn_q_a_norm, nullptr, LLM_NORM_RMS, il); + cb(qr, "q_resid", il); + + ggml_tensor * q = build_lora_mm(layer.wq_b, qr); + + ggml_tensor * q_nope = ggml_view_3d(ctx0, q, n_embd_head_qk_nope, n_head_l, n_tokens, + ggml_row_size(q->type, n_embd_head_k), ggml_row_size(q->type, n_embd_head_k) * n_head_l, 0); + ggml_tensor * q_pe = ggml_view_3d(ctx0, q, n_embd_head_qk_rope, n_head_l, n_tokens, + ggml_row_size(q->type, n_embd_head_k), ggml_row_size(q->type, n_embd_head_k) * n_head_l, + ggml_row_size(q->type, n_embd_head_qk_nope)); + + ggml_tensor * kv_cmpr_pe = build_lora_mm(layer.wkv_a_mqa, cur); + ggml_tensor * kv_cmpr = ggml_view_2d(ctx0, kv_cmpr_pe, kv_lora_rank, n_tokens, + ggml_row_size(kv_cmpr_pe->type, kv_lora_rank + n_embd_head_qk_rope), 0); + ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_cmpr_pe, n_embd_head_qk_rope, 1, n_tokens, + ggml_row_size(kv_cmpr_pe->type, kv_lora_rank + n_embd_head_qk_rope), + ggml_row_size(kv_cmpr_pe->type, kv_lora_rank + n_embd_head_qk_rope), + ggml_row_size(kv_cmpr_pe->type, kv_lora_rank)); + + if (hparams.use_mrope()) { + q_pe = hy_v4_flash_rope_to_neox(ctx0, q_pe); + k_pe = hy_v4_flash_rope_to_neox(ctx0, k_pe); + } + q_pe = build_rope(q_pe, inp_pos, il); + cb(q_pe, "q_pe", il); + k_pe = build_rope(k_pe, inp_pos, il); + cb(k_pe, "k_pe", il); + + kv_cmpr = build_norm(kv_cmpr, layer.attn_kv_a_norm, nullptr, LLM_NORM_RMS, il); + cb(kv_cmpr, "kv_cmpr", il); + + q_nope = ggml_permute(ctx0, q_nope, 0, 2, 1, 3); + ggml_tensor * q_nope_absorbed = ggml_mul_mat(ctx0, layer.wk_b, q_nope); + q_nope_absorbed = ggml_permute(ctx0, q_nope_absorbed, 0, 2, 1, 3); + + // rope goes last so build_rope_shift() can shift the cache in place + ggml_tensor * Qcur = ggml_concat(ctx0, q_nope_absorbed, q_pe, 0); + + kv_cmpr = ggml_reshape_3d(ctx0, kv_cmpr, kv_lora_rank, 1, n_tokens); + ggml_tensor * Kcur = ggml_concat(ctx0, kv_cmpr, k_pe, 0); + ggml_tensor * Vcur = kv_cmpr; + + ggml_tensor * attn; + + if (hparams.is_swa(il)) { + attn = build_attn(inp_attn->get_swa(), + nullptr, nullptr, nullptr, + Qcur, Kcur, Vcur, nullptr, layer.attn_sinks, layer.wv_b, kq_scale, il); + } else { + // as build_attn of the DSA input, with the cells of the picked pools instead of a top-k of cells + auto * inp_dsa = inp_attn->get_dsa(); + const auto * mctx_mla = inp_dsa->mctx->get_mla(); + + ggml_build_forward_expand(gf, Qcur); + ggml_build_forward_expand(gf, Vcur); + ggml_build_forward_expand(gf, Kcur); + ggml_build_forward_expand(gf, mctx_mla->cpy_k(ctx0, Kcur, inp_dsa->get_k_idxs_mla(), il)); + + ggml_tensor * sel = build_pool_select(cur, qr, inp_pos, freq_base_l, layer, + inp_attn, inp_pool, inp_dsa->self_attn_mask_mla.raw, il); + + const int64_t n_sel = hparams.indexer_top_k; + + ggml_tensor * k = mctx_mla->get_k(ctx0, il); + ggml_tensor * v = ggml_view_4d(ctx0, k, kv_lora_rank, k->ne[1], k->ne[2], k->ne[3], k->nb[1], k->nb[2], k->nb[3], 0); + + attn = build_attn_mha(Qcur, k, v, nullptr, sel, nullptr, layer.attn_sinks, layer.wv_b, n_sel, kq_scale, il); + } + cb(attn, "attn_kqv", il); + + ggml_tensor * gate = build_lora_mm(layer.wqkv_gate, cur); + gate = ggml_sigmoid(ctx0, gate); + attn = ggml_mul(ctx0, attn, gate); + cb(attn, "attn_gated", il); + + ggml_tensor * out = build_lora_mm(layer.wo, attn); + out = build_norm(out, layer.attn_post_norm, nullptr, LLM_NORM_RMS, il); + cb(out, "attn_out", il); + + return out; +} + +ggml_tensor * llama_model_hy_v4_flash::graph::build_latent_moe( + const llama_model & model, + ggml_tensor * cur, + int il) const { + const auto & layer = model.layers[il]; + + // the router scores the full-width input, the experts take the latent one + ggml_tensor * logits = build_lora_mm(layer.ffn_gate_inp, cur); + cb(logits, "ffn_moe_logits", il); + + ggml_tensor * routed_in = layer.ffn_routed_down + ? build_lora_mm(layer.ffn_routed_down, cur) + : cur; + + ggml_tensor * moe_out = build_moe_ffn(routed_in, + nullptr, + layer.ffn_up_exps, + layer.ffn_gate_exps, + layer.ffn_down_exps, + layer.ffn_exp_probs_b, + n_expert, n_expert_used, + LLM_FFN_SILU, hparams.expert_weights_norm, + hparams.expert_weights_scale, + (llama_expert_gating_func_type) hparams.expert_gating_func, + il, + logits); + cb(moe_out, "ffn_moe_out", il); + + if (layer.ffn_routed_up) { + moe_out = build_lora_mm(layer.ffn_routed_up, moe_out); + cb(moe_out, "ffn_moe_up", il); + } + + ggml_tensor * shexp = build_ffn(cur, + layer.ffn_up_shexp, NULL, NULL, + layer.ffn_gate_shexp, NULL, NULL, + layer.ffn_down_shexp, NULL, NULL, + NULL, LLM_FFN_SILU, LLM_FFN_PAR, il); + cb(shexp, "ffn_shexp", il); + + return ggml_add(ctx0, moe_out, shexp); +} + +llama_model_hy_v4_flash::graph::graph(const llama_model & model, const llm_graph_params & params) : + llm_graph_context(params) { + const int64_t hc = hparams.dsv4_hc_mult; + + ggml_tensor * cur; + + ggml_tensor * inp_pos = build_inp_pos(); + if (hparams.use_mrope()) { + inp_pos = hy_v4_flash_pos(ctx0, inp_pos, n_tokens); + } + + // the sparse layers are in the DSA cache with their indexer, the sliding-window layers in the SWA cache + llm_graph_input_attn_k_dsa_iswa * inp_attn = build_attn_inp_k_dsa_iswa(); + + llm_graph_input_pool * inp_pool = build_inp_pool(inp_attn); + + ggml_tensor * inp_out_ids = build_inp_out_ids(); + + // Engram gathers go before the token embeddings, so the mixed embd copies after them land on the GPU + // and the host split keeps only small single threaded lookups + auto inp_eng = std::make_unique( + static_cast(model), inp_attn->get_dsa()->mctx->get_mla()); + std::vector engram_rows; + std::vector engram_valid; + for (int il = 0; ubatch.token && hparams.ple_n_heads > 0 && il < n_layer; ++il) { + if (!hparams.is_ple(il)) { + continue; + } + const int64_t n_cols = hparams.ple_n_heads; + + ggml_tensor * ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_cols*n_tokens); + ggml_set_input(ids); + ggml_set_name(ids, ("engram_ids-" + std::to_string(il)).c_str()); + inp_eng->engram_ids.push_back(ids); + + ggml_tensor * valid = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_cols*n_tokens); + ggml_set_input(valid); + ggml_set_name(valid, ("engram_valid-" + std::to_string(il)).c_str()); + inp_eng->engram_valid.push_back(valid); + engram_valid.push_back(valid); + + ggml_tensor * rows = ggml_get_rows(ctx0, model.per_layer_tok_embd, ids); + rows = ggml_reshape_3d(ctx0, rows, hparams.ple_head_dim, n_cols, n_tokens); + cb(rows, "engram_rows", il); + ggml_build_forward_expand(gf, rows); + engram_rows.push_back(rows); + } + res->add_input(std::move(inp_eng)); + + ggml_tensor * inp = build_inp_embd(model.tok_embd); + + // one embedding feeds hc parallel residual streams + ggml_tensor * inpL = ggml_reshape_3d(ctx0, inp, n_embd, 1, n_tokens); + inpL = ggml_repeat_4d(ctx0, inpL, n_embd, hc, n_tokens, 1); + cb(inpL, "hc_init", -1); + + for (int il = 0; il < n_layer; ++il) { + const auto & layer = model.layers[il]; + + // Engram writes into the streams before the attention pre-mix reads them + const int e = static_cast(model).engram_index(il); + if (e >= 0 && !engram_rows.empty()) { + inpL = build_engram(model, inpL, engram_rows[e], engram_valid[e], il); + cb(inpL, "engram_out", il); + } + + ggml_tensor * residual = inpL; + hc_pre attn_hc = build_hc_pre(inpL, layer.hc_attn_fn, layer.hc_attn_scale, layer.hc_attn_base, il); + cur = build_norm(attn_hc.cur, layer.attn_norm, nullptr, LLM_NORM_RMS, il); + cb(cur, "attn_norm", il); + + cur = build_attention(model, inp_attn, inp_pool, cur, inp_pos, il); + + inpL = build_hc_post(cur, residual, attn_hc.post, il); + cb(inpL, "hc_attn_out", il); + + residual = inpL; + hc_pre ffn_hc = build_hc_pre(inpL, layer.hc_ffn_fn, layer.hc_ffn_scale, layer.hc_ffn_base, il); + cur = build_norm(ffn_hc.cur, layer.ffn_norm, nullptr, LLM_NORM_RMS, il); + cb(cur, "ffn_norm", il); + + if ((uint32_t) il < hparams.n_layer_dense_lead) { + cur = build_ffn(cur, + layer.ffn_up, NULL, NULL, + layer.ffn_gate, NULL, NULL, + layer.ffn_down, NULL, NULL, + NULL, LLM_FFN_SILU, LLM_FFN_PAR, il); + } else { + cur = build_latent_moe(model, cur, il); + } + + cur = build_norm(cur, layer.ffn_post_norm, nullptr, LLM_NORM_RMS, il); + cb(cur, "ffn_out", il); + + inpL = build_hc_post(cur, residual, ffn_hc.post, il); + cb(inpL, "l_out", il); + } + + // prune the output rows after all streams, or after the nextn state when it needs every row + if (crop_before_nextn(inp_out_ids)) { + ggml_tensor * flat = ggml_reshape_2d(ctx0, inpL, n_embd * hc, n_tokens); + flat = ggml_get_rows(ctx0, flat, inp_out_ids); + inpL = ggml_reshape_3d(ctx0, flat, n_embd, hc, n_outputs); + } + + cur = build_hc_head(inpL, model.hc_head_fn, model.hc_head_scale, model.hc_head_base); + cb(cur, "hc_head", -1); + + cur = build_norm(cur, model.output_norm, nullptr, LLM_NORM_RMS, -1); + + // the draft block reads this state through its hnorm + cb(cur, "h_nextn", -1); + res->t_h_nextn = cur; + + if (crop_after_nextn(inp_out_ids)) { + cur = ggml_get_rows(ctx0, cur, inp_out_ids); + } + cb(cur, "result_norm", -1); + res->t_embd = cur; + + cur = build_lora_mm(model.output, cur); + cb(cur, "result_output", -1); + res->t_logits = cur; +} + diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index bdd1f18d67ed..f55e4ac56247 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -220,6 +220,11 @@ ggml_tensor * llama_model_inkling2::graph::convolve( const int64_t n_seq_tokens = ubatch.n_seq_tokens; const int64_t n_seqs = ubatch.n_seqs; + // add the taps input first and the result right after the state store, so the conv ops are consecutive and backends can fuse them + if (dynamic) { + ggml_build_forward_expand(gf, dynamic); + } + ggml_tensor * past = ggml_view_3d(ctx0, history, n_conv - 1, n_channels, n_seqs, history->nb[1], history->nb[2], offset*history->nb[1]); ggml_tensor * x = ggml_transpose(ctx0, ggml_reshape_3d(ctx0, cur, n_channels, n_seq_tokens, n_seqs)); @@ -248,7 +253,10 @@ 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)); + out = ggml_scale(ctx0, ggml_add(ctx0, cur, out), 1.0f/sqrtf((dynamic ? 2 : 1)*n_conv + 1)); + ggml_build_forward_expand(gf, out); + + return out; } // mix a cross-pass message into a looped layer input: (1 - forget)*cur + gain*message, both gated on cur and message @@ -266,7 +274,6 @@ ggml_tensor * llama_model_inkling2::graph::control(ggml_tensor * cur, ggml_tenso 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(); @@ -276,6 +283,7 @@ ggml_tensor * llama_model_inkling2::graph::build_inputs() { 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); + ggml_build_forward_expand(gf, tau); ggml_tensor * cur = build_inp_embd(model.tok_embd); @@ -363,24 +371,12 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens cb(Vcur, "Vcur", il); cb(Rcur, "Rcur", il); - 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]; - 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); // 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); // one zero tensor per head count for the whole graph ggml_tensor *& zero = zero_sinks[n_head]; @@ -391,7 +387,7 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens cur = build_attn(inp, nullptr, nullptr, nullptr, - Qcur, Kcur, Vcur, kq_b, sinks, 1.0f/sqrtf(n_embd_head), il); + Qcur, Kcur, Vcur, table, 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); @@ -403,6 +399,7 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens blocks.push_back(inpSA); } else { cur = ggml_add(ctx0, inpSA, cur); + ggml_build_forward_expand(gf, cur); // right after the conv, so backends can fuse the add into it } ggml_tensor * ffn_inp = cur; @@ -434,6 +431,7 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens cb(cur, "ffn_out", il); cur = ggml_add(ctx0, ffn_inp, cur); + ggml_build_forward_expand(gf, cur); cb(cur, "l_out", il); return cur; diff --git a/src/models/kimi-k3.cpp b/src/models/kimi-k3.cpp index e0ef7b6cd40a..846a4886618e 100644 --- a/src/models/kimi-k3.cpp +++ b/src/models/kimi-k3.cpp @@ -351,42 +351,6 @@ llama_model_kimi_k3::graph::graph(const llm_graph_params & params) : // KDA layer // -// causal conv1d over one of Q/K/V. `qkv` selects which third of the conv state to use -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, 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 * 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 = 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); - Xcur = ggml_reshape_2d(ctx0, Xcur, d_inner, n_tokens); - Xcur = ggml_silu(ctx0, Xcur); - - return ggml_reshape_4d(ctx0, Xcur, head_dim, n_head_kda, n_seq_tokens, n_seqs); -} - ggml_tensor * llama_model_kimi_k3::graph::build_kda_layer( ggml_tensor * cur, const llama_layer & layer, llm_graph_input_rs * inp_rs, int64_t d_conv, int64_t head_dim, int64_t n_head_kda, @@ -397,9 +361,12 @@ ggml_tensor * llama_model_kimi_k3::graph::build_kda_layer( ggml_tensor * conv_states_all = mctx_cur->get_r_l(il); 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, 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); + ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, ggml_mul_mat(ctx0, layer.wq, cur), + 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, ggml_mul_mat(ctx0, layer.wk, cur), + 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, ggml_mul_mat(ctx0, layer.wv, cur), + 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 d61469120f42..85b97dda0963 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -55,6 +55,20 @@ struct llm_build_delta_net_base : public llm_graph_context { int64_t conv_channels, int il); + ggml_tensor * build_kda_conv1d( + llm_graph_input_rs * inp, + ggml_tensor * conv_states_all, + ggml_tensor * conv_states_seq, + int64_t qkv, + ggml_tensor * x_proj, + ggml_tensor * conv_w, + int64_t d_conv, + int64_t head_dim, + int64_t n_heads, + int64_t n_seq_tokens, + int64_t n_seqs, + int il); + // run delta-net attention and write the new recurrent state(s) back to ssm_states_all // s: (head_v_dim, head_v_dim, num_v_heads, n_seqs); returns output: (head_v_dim, num_v_heads, n_seq_tokens, n_seqs) ggml_tensor * build_recurrent_attn( @@ -2469,6 +2483,100 @@ struct llama_model_hy_v4 : public llama_model_base { std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; }; +// hy_v4 iHC, gated MLA and sinks, with sparse and sliding-window layers, sandwich norms and latent routed experts +struct llama_model_hy_v4_flash : public llama_model_base { + llama_model_hy_v4_flash(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; + uint32_t graph_nodes_per_tensor() const override { return 32; } + + // -1 when the layer has no Engram module, else its index among the Engram layers + int engram_index(int il) const; + + // n-gram hash of module e: one row id and one validity per (token, column) + void engram_hash(int e, const llama_ubatch & ubatch, const std::vector & prev, + std::vector & ids, std::vector & valid) const; + + class llm_graph_input_pool; + + struct graph : public llm_graph_context { + graph(const llama_model & model, const llm_graph_params & params); + + // iHC, same layout as hy_v4 + struct hc_pre { + ggml_tensor * cur; + ggml_tensor * post; + }; + + // reduce the hc streams to one, weighted by the pre gates + ggml_tensor * build_hc_reduce( + ggml_tensor * x, + ggml_tensor * weights, + int il) const; + + hc_pre build_hc_pre( + ggml_tensor * x, + ggml_tensor * hc_fn, + ggml_tensor * hc_scale, + ggml_tensor * hc_base, + int il) const; + + ggml_tensor * build_hc_post( + ggml_tensor * x, + ggml_tensor * residual, + ggml_tensor * post, + int il) const; + + ggml_tensor * build_hc_head( + ggml_tensor * x, + ggml_tensor * hc_fn, + ggml_tensor * hc_scale, + ggml_tensor * hc_base) const; + + ggml_tensor * build_attention( + const llama_model & model, + llm_graph_input_attn_k_dsa_iswa * inp_attn, + llm_graph_input_pool * inp_pool, + ggml_tensor * cur, + ggml_tensor * inp_pos, + int il); + + llm_graph_input_pool * build_inp_pool(llm_graph_input_attn_k_dsa_iswa * inp_attn); + + // rotate only the trailing n_rot of each indexer head + ggml_tensor * build_indexer_rope(ggml_tensor * x, ggml_tensor * pos, int64_t n_idx, + float freq_base, int il) const; + + // the kq_mask of the sparse layer, opened on the best scored pools plus the token's own pool + ggml_tensor * build_pool_select( + ggml_tensor * cur, + ggml_tensor * qr, + ggml_tensor * inp_pos, + float freq_base, + const llama_layer & layer, + llm_graph_input_attn_k_dsa_iswa * inp_attn, + llm_graph_input_pool * inp_pool, + ggml_tensor * kq_mask, + int il); + + // routed experts run at n_expert_latent, the router and the shared expert at n_embd + ggml_tensor * build_latent_moe( + const llama_model & model, + ggml_tensor * cur, + int il) const; + + // Engram adds its delta to the hc streams before the attention + ggml_tensor * build_engram( + const llama_model & model, + ggml_tensor * x, + ggml_tensor * rows, + ggml_tensor * valid, + int il) const; + }; + + std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; +}; + struct llama_model_hunyuan_vl : public llama_model_base { llama_model_hunyuan_vl(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; @@ -2574,7 +2682,6 @@ struct llama_model_inkling2 : public llama_model_base { 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; @@ -3203,11 +3310,6 @@ struct llama_model_kimi_k3 : public llama_model_base { int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t d_inner, int64_t n_seq_tokens, int64_t n_seqs, int il); - // 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, int il); - ggml_tensor * build_mla_layer(ggml_tensor * cur, const llama_layer & layer, llm_graph_input_attn_k * inp_attn_k, llm_graph_input_attn_kv * inp_attn_kv, @@ -3270,6 +3372,39 @@ struct llama_model_kimi_k31 : public llama_model_base { std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; }; +struct llama_model_raon1_mini : public llama_model_base { + llama_model_raon1_mini(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; + uint32_t graph_nodes_per_tensor() const override { return 64; } + std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; + + struct graph : public llm_build_delta_net_base { + graph(const llm_graph_params & params); + + ggml_tensor * helmert = nullptr; + ggml_tensor * identity = nullptr; + ggml_tensor * chart_base = nullptr; + + ggml_tensor * build_hc_pre(ggml_tensor * x, ggml_tensor * fn, ggml_tensor * scale, + ggml_tensor * base, ggml_tensor ** post, ggml_tensor ** comb, int il); + + ggml_tensor * build_hc_post(ggml_tensor * x, ggml_tensor * branch, + ggml_tensor * post, ggml_tensor * comb, int il); + + ggml_tensor * build_rda_gate(ggml_tensor * x, ggml_tensor * ssm_a); + + ggml_tensor * build_rda_layer(ggml_tensor * cur, const llama_layer & layer, + llm_graph_input_rs * inp_rs, int il); + + ggml_tensor * build_mla_layer(ggml_tensor * cur, const llama_layer & layer, + llm_graph_input_attn_k * inp_attn_k, int il); + + ggml_tensor * build_situ_ffn(ggml_tensor * cur, ggml_tensor * up, ggml_tensor * gate, + ggml_tensor * down, int il); + }; +}; + struct llama_model_glm5_next : public llama_model_base { llama_model_glm5_next(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; diff --git a/src/models/raon1-mini.cpp b/src/models/raon1-mini.cpp new file mode 100644 index 000000000000..e5b1671ecdd4 --- /dev/null +++ b/src/models/raon1-mini.cpp @@ -0,0 +1,484 @@ +#include "models.h" + +#include "llama-impl.h" + +#include "llama-memory-recurrent.h" + +void llama_model_raon1_mini::load_arch_hparams(llama_model_loader & ml) { + ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); + ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH_MLA, hparams.n_embd_head_k_mla_impl); + ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH_MLA, hparams.n_embd_head_v_mla_impl); + ml.get_key(LLM_KV_ATTENTION_Q_LORA_RANK, hparams.n_lora_q); + ml.get_key(LLM_KV_ATTENTION_KV_LORA_RANK, hparams.n_lora_kv); + ml.get_key(LLM_KV_SSM_CONV_KERNEL, hparams.ssm_d_conv); + ml.get_key(LLM_KV_KDA_HEAD_DIM, hparams.n_embd_head_kda); + ml.get_key(LLM_KV_KDA_GATE_LOWER_BOUND, hparams.kda_gate_lower_bound, false); + + uint32_t n_rda = 0; + for (uint32_t i = 0; i < hparams.n_layer(); ++i) { + hparams.is_recr_impl[i] = hparams.n_head_kv(i) == 0; + n_rda += hparams.is_recr_impl[i]; + if (!hparams.is_recr_impl[i] && hparams.n_head_kv(i) != 1) { + throw std::runtime_error(format("Raon-1 mini MLA layers must have one KV head, layer %u has %u", i, hparams.n_head_kv(i))); + } + } + // the hybrid memory needs both kinds: RDA layers (head_count_kv 0) and MLA layers (head_count_kv 1) + if (n_rda == 0 || n_rda == hparams.n_layer()) { + throw std::runtime_error(format("Raon-1 mini needs both RDA and MLA layers, got %u RDA of %u layers", n_rda, hparams.n_layer())); + } + + ml.get_key_or_arr(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp_arr, hparams.n_layer_all); + ml.get_key(LLM_KV_EXPERT_SHARED_COUNT, hparams.n_expert_shared); + ml.get_key(LLM_KV_LEADING_DENSE_BLOCK_COUNT, hparams.n_layer_dense_lead); + ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale); + ml.get_key(LLM_KV_EXPERT_WEIGHTS_NORM, hparams.expert_weights_norm); + ml.get_key(LLM_KV_EXPERT_GATING_FUNC, hparams.expert_gating_func); + + ml.get_key(LLM_KV_ATTENTION_LATENT_NORM_RMS_EPS, hparams.f_norm_rms_eps_latent); + ml.get_key(LLM_KV_SSM_TIME_STEP_RANK, hparams.ssm_dt_rank); + ml.get_key(LLM_KV_HYPER_CONNECTION_COUNT, hparams.dsv4_hc_mult); + ml.get_key(LLM_KV_HYPER_CONNECTION_EPSILON, hparams.dsv4_hc_eps); + ml.get_key(LLM_KV_HYPER_CONNECTION_MAGNITUDE, hparams.hc_magnitude); + ml.get_key(LLM_KV_ACTIVATION_SITU_BETA, hparams.situ_beta); + ml.get_key(LLM_KV_ACTIVATION_SITU_LINEAR_BETA, hparams.situ_linear_beta); + + // The Raon router normalizes selected scores by sum(scores) + 1e-20. + hparams.expert_weights_norm_eps = 1e-20f; + + auto require = [](bool ok, const std::string & what) { + if (!ok) { + throw std::runtime_error("invalid Raon-1 mini hyperparameters: " + what); + } + }; + // accepted ranges; only 2-4 mHC streams and a conv width of 4 have been run (the released model uses 4 streams) + require(hparams.dsv4_hc_mult >= 2 && hparams.dsv4_hc_mult <= 8, format("hyper_connection.count %u is not in [2, 8]", hparams.dsv4_hc_mult)); + require(hparams.ssm_d_conv == 4, format("ssm.conv_kernel %u is not 4", hparams.ssm_d_conv)); + require(hparams.ssm_dt_rank > 0, "ssm.time_step_rank is 0"); + require(hparams.n_lora_q > 0 && hparams.n_lora_kv > 0, "q_lora_rank or kv_lora_rank is 0"); + // the absorbed MLA attends over the latent: V is the kv_lora_rank-wide latent + require(hparams.n_embd_head_v_full == hparams.n_lora_kv, format("the MLA value length %u is not kv_lora_rank %u", hparams.n_embd_head_v_full, hparams.n_lora_kv)); + require(hparams.n_embd_head_k_mla() > hparams.n_rot(), format("the MLA key length %u is not larger than the RoPE dimension %u", hparams.n_embd_head_k_mla(), hparams.n_rot())); + require(hparams.f_norm_rms_eps_latent > 0 && hparams.dsv4_hc_eps > 0, "a normalization epsilon is not positive"); + require(hparams.hc_magnitude > 0, "hyper_connection.magnitude is not positive"); + require(hparams.situ_beta > 0 && hparams.situ_linear_beta > 0, "a SiTU beta is not positive"); + require(hparams.n_layer_dense_lead <= hparams.n_layer(), format("leading_dense_block_count %u is larger than block_count %u", hparams.n_layer_dense_lead, hparams.n_layer())); + const auto head_dim = hparams.n_embd_head_kda; + require(head_dim == 16 || head_dim == 32 || head_dim == 64 || head_dim == 128, + format("RDA head dimension %u is not 16, 32, 64 or 128", head_dim)); + + switch (hparams.n_layer()) { + case 25: type = LLM_TYPE_29B_A4B; break; + default: type = LLM_TYPE_UNKNOWN; + } +} + +void llama_model_raon1_mini::load_arch_tensors(llama_model_loader &) { + LLAMA_LOAD_LOCALS; + + const int64_t hc = hparams.dsv4_hc_mult; + // selector width per mHC site: pre (hc) + post (hc) + combination ((hc-1)^2, Helmert coordinates) + const int64_t hc_mix_dim = 2*hc + (hc - 1)*(hc - 1); + + 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}, 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); + layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0); + + layer.hc_attn_fn = create_tensor(tn(LLM_TENSOR_HC_ATTN_FN, "weight", i), {hc*n_embd, hc_mix_dim}, 0); + layer.hc_attn_base = create_tensor(tn(LLM_TENSOR_HC_ATTN_BASE, "weight", i), {hc_mix_dim}, 0); + // scale: alpha_pre, alpha_post, alpha_z, eta + layer.hc_attn_scale = create_tensor(tn(LLM_TENSOR_HC_ATTN_SCALE, "weight", i), {4}, 0); + layer.hc_ffn_fn = create_tensor(tn(LLM_TENSOR_HC_FFN_FN, "weight", i), {hc*n_embd, hc_mix_dim}, 0); + layer.hc_ffn_base = create_tensor(tn(LLM_TENSOR_HC_FFN_BASE, "weight", i), {hc_mix_dim}, 0); + layer.hc_ffn_scale = create_tensor(tn(LLM_TENSOR_HC_FFN_SCALE, "weight", i), {4}, 0); + + const int64_t head_dim = hparams.n_embd_head_kda; + const int64_t d_conv = hparams.ssm_d_conv; + const int64_t d_inner = head_dim * n_head; + + if (hparams.is_recr(i)) { + layer.ssm_q_conv = create_tensor(tn(LLM_TENSOR_SSM_CONV1D_Q, "weight", i), {d_conv, 1, d_inner, 1}, 0); + layer.ssm_k_conv = create_tensor(tn(LLM_TENSOR_SSM_CONV1D_K, "weight", i), {d_conv, 1, d_inner, 1}, 0); + layer.ssm_v_conv = create_tensor(tn(LLM_TENSOR_SSM_CONV1D_V, "weight", i), {d_conv, 1, d_inner, 1}, 0); + + create_tensor_qkv(layer, i, n_embd, d_inner, d_inner, d_inner, 0); + + layer.ssm_f_a = create_tensor(tn(LLM_TENSOR_SSM_F_A, "weight", i), {n_embd, hparams.ssm_dt_rank}, 0); + layer.ssm_f_b = create_tensor(tn(LLM_TENSOR_SSM_F_B, "weight", i), {hparams.ssm_dt_rank, d_inner}, 0); + layer.ssm_beta = create_tensor(tn(LLM_TENSOR_SSM_BETA, "weight", i), {n_embd, n_head}, 0); + layer.ssm_rda = create_tensor(tn(LLM_TENSOR_SSM_RDA, "weight", i), {n_embd, n_head}, 0); + + layer.ssm_a = create_tensor(tn(LLM_TENSOR_SSM_A_NOSCAN, i), {n_head}, 0); + layer.ssm_dt_b = create_tensor(tn(LLM_TENSOR_SSM_DT, "bias", i), {d_inner}, 0); + + layer.ssm_g = create_tensor(tn(LLM_TENSOR_SSM_G, "weight", i), {n_embd, d_inner}, 0); + layer.ssm_o_norm = create_tensor(tn(LLM_TENSOR_SSM_NORM, "weight", i), {head_dim}, 0); + layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {d_inner, n_embd}, 0); + } else { + const int64_t q_lora_rank = hparams.n_lora_q; + const int64_t kv_lora_rank = hparams.n_lora_kv; + const int64_t n_embd_head_k = hparams.n_embd_head_k_mla(); + const int64_t n_embd_head_v = hparams.n_embd_head_v_mla(); + const int64_t qk_rope_head_dim = hparams.n_rot(); + const int64_t qk_nope_head_dim = n_embd_head_k - qk_rope_head_dim; + + layer.attn_q_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_A_NORM, "weight", i), {q_lora_rank}, 0); + layer.attn_kv_a_norm = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_NORM, "weight", i), {kv_lora_rank}, 0); + layer.wq_a = create_tensor(tn(LLM_TENSOR_ATTN_Q_A, "weight", i), {n_embd, q_lora_rank}, 0); + layer.wq_b = create_tensor(tn(LLM_TENSOR_ATTN_Q_B, "weight", i), {q_lora_rank, n_head*n_embd_head_k}, 0); + layer.wkv_a_mqa = create_tensor(tn(LLM_TENSOR_ATTN_KV_A_MQA, "weight", i), {n_embd, kv_lora_rank + qk_rope_head_dim}, 0); + layer.wk_b = create_tensor(tn(LLM_TENSOR_ATTN_K_B, "weight", i), {qk_nope_head_dim, kv_lora_rank, n_head}, 0); + layer.wv_b = create_tensor(tn(LLM_TENSOR_ATTN_V_B, "weight", i), {kv_lora_rank, n_embd_head_v, n_head}, 0); + layer.wqkv_gate = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "weight", i), {n_embd, n_head*n_embd_head_v}, 0); + + layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_head * n_embd_head_v, n_embd}, 0); + } + + if (i < (int) hparams.n_layer_dense_lead) { + layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0); + layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0); + layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0); + } else { + const int64_t n_ff_exp = hparams.n_ff_exp(); + + layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0); + layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, 0); + + layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff_exp, n_expert}, 0); + layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert}, 0); + layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff_exp, n_expert}, 0); + + if (hparams.n_expert_shared > 0) { + const int64_t n_ff_shexp = n_ff_exp * hparams.n_expert_shared; + layer.ffn_gate_shexp = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "weight", i), {n_embd, n_ff_shexp}, 0); + layer.ffn_down_shexp = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "weight", i), {n_ff_shexp, n_embd}, 0); + layer.ffn_up_shexp = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP, "weight", i), {n_embd, n_ff_shexp}, 0); + } + } + } +} + +std::unique_ptr llama_model_raon1_mini::build_arch_graph(const llm_graph_params & params) const { + return std::make_unique(params); +} + +// decay gate from x = f_b(f_a(cur)) + dt_bias; ssm_a holds -exp(A_log) +// with gate_lower_bound: g = lower_bound * sigmoid(exp(A_log) * x), else g = -softplus(exp(A_log) * x) +ggml_tensor * llama_model_raon1_mini::graph::build_rda_gate(ggml_tensor * x, ggml_tensor * ssm_a) { + const int64_t head_dim = hparams.n_embd_head_kda; + + ggml_tensor * A = ggml_reshape_3d(ctx0, ssm_a, 1, n_head, 1); + + x = ggml_reshape_3d(ctx0, x, head_dim, n_head, n_tokens); + x = ggml_mul(ctx0, x, A); + + // gate_lower_bound is not a clamp - when set, it swaps the decay gate activation + if (hparams.kda_gate_lower_bound > -INFINITY) { + x = ggml_sigmoid(ctx0, ggml_scale(ctx0, x, -1.0f)); + return ggml_scale(ctx0, x, hparams.kda_gate_lower_bound); + } + + return ggml_neg(ctx0, ggml_softplus(ctx0, ggml_neg(ctx0, x))); +} + +// Raon delta attention: a gated delta-rule layer whose write gate differs from its erase gate +ggml_tensor * llama_model_raon1_mini::graph::build_rda_layer( + ggml_tensor * cur, const llama_layer & layer, llm_graph_input_rs * inp_rs, int il) { + const int64_t head_dim = hparams.n_embd_head_kda; + const int64_t d_conv = hparams.ssm_d_conv; + const int64_t d_inner = head_dim * n_head; + const int64_t n_seq_tokens = ubatch.n_seq_tokens; + const int64_t n_seqs = ubatch.n_seqs; + + ggml_tensor * conv_states_all = inp_rs->mctx->get_r_l(il); + ggml_tensor * conv_states_seq = 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_states_seq, 0, build_lora_mm(layer.wq, cur), + layer.ssm_q_conv, d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il); + ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_states_seq, 1, build_lora_mm(layer.wk, cur), + layer.ssm_k_conv, d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il); + ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_states_seq, 2, build_lora_mm(layer.wv, cur), + layer.ssm_v_conv, d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il); + cb(Qcur, "rda_q_conv", il); + cb(Kcur, "rda_k_conv", il); + cb(Vcur, "rda_v_conv", il); + + ggml_tensor * f_a = build_lora_mm(layer.ssm_f_a, cur); + ggml_tensor * g1 = build_lora_mm(layer.ssm_f_b, f_a); + g1 = ggml_add(ctx0, g1, layer.ssm_dt_b); + g1 = build_rda_gate(g1, layer.ssm_a); + cb(g1, "rda_g1", il); + + g1 = ggml_reshape_4d(ctx0, g1, head_dim, n_head, n_seq_tokens, n_seqs); + + // erase gate sigmoid(beta), write gate sigmoid(beta + delta); the write/erase ratio is folded into V + ggml_tensor * beta = build_lora_mm(layer.ssm_beta, cur); + beta = ggml_reshape_4d(ctx0, beta, 1, n_head, n_seq_tokens, n_seqs); + ggml_tensor * delta = build_lora_mm(layer.ssm_rda, cur); + delta = ggml_reshape_4d(ctx0, delta, 1, n_head, n_seq_tokens, n_seqs); + ggml_tensor * erase = ggml_softplus(ctx0, ggml_neg(ctx0, beta)); + ggml_tensor * write = ggml_softplus(ctx0, ggml_neg(ctx0, ggml_add(ctx0, beta, delta))); + Vcur = ggml_mul(ctx0, Vcur, ggml_exp(ctx0, ggml_sub(ctx0, erase, write))); + cb(Vcur, "rda_v_scaled", il); + beta = ggml_sigmoid(ctx0, beta); + cb(beta, "rda_beta", il); + + // same as HF F.normalize(eps=1e-6): x / max(||x||, eps) + const float eps_norm = 1e-6f; + Qcur = ggml_l2_norm(ctx0, Qcur, eps_norm); + Kcur = ggml_l2_norm(ctx0, Kcur, eps_norm); + + ggml_tensor * g2 = build_lora_mm(layer.ssm_g, cur); + + // scan and state update + ggml_tensor * ssm_states_all = inp_rs->mctx->get_s_l(il); + ggml_tensor * state = build_rs(inp_rs, ssm_states_all, hparams.n_embd_s(), n_seqs); + state = ggml_reshape_4d(ctx0, state, head_dim, head_dim, n_head, n_seqs); + + ggml_tensor * output = build_recurrent_attn(inp_rs, ssm_states_all, Qcur, Kcur, Vcur, g1, beta, state, il); + output = ggml_cont(ctx0, output); + cb(output, "rda_scan_out", il); + + // output gate, then RMSNorm(o) * sigmoid(g2) + g2 = ggml_reshape_3d(ctx0, g2, head_dim, n_head, n_tokens); + + ggml_tensor * o = ggml_reshape_3d(ctx0, output, head_dim, n_head, n_tokens); + ggml_tensor * normed = build_norm(o, layer.ssm_o_norm, nullptr, LLM_NORM_RMS, il); + cb(g2, "rda_g2", il); + cb(normed, "rda_normed", il); + ggml_tensor * gated = ggml_mul(ctx0, normed, ggml_sigmoid(ctx0, g2)); + + gated = ggml_cont_2d(ctx0, gated, d_inner, n_tokens); + cur = build_lora_mm(layer.wo, gated); + cb(cur, "rda_out", il); + + return cur; +} + +ggml_tensor * llama_model_raon1_mini::graph::build_hc_pre( + ggml_tensor * x, ggml_tensor * fn, ggml_tensor * scale, ggml_tensor * base, + ggml_tensor ** post, ggml_tensor ** comb, int il) { + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nm = hc - 1; + const int64_t nt = x->ne[2]; + ggml_tensor * flat = ggml_reshape_2d(ctx0, x, n_embd*hc, nt); + ggml_tensor * rms = ggml_sqrt(ctx0, ggml_scale_bias(ctx0, ggml_mean(ctx0, ggml_sqr(ctx0, flat)), 1.0f, hparams.dsv4_hc_eps)); + ggml_tensor * mixes = ggml_div(ctx0, build_lora_mm(fn, flat), rms); + cb(mixes, "hc_mixes", il); + + auto affine = [&](int64_t offset, int64_t width, int64_t si) { + ggml_tensor * z = ggml_view_2d(ctx0, mixes, width, nt, mixes->nb[1], offset*mixes->nb[0]); + ggml_tensor * a = ggml_view_1d(ctx0, scale, 1, si*scale->nb[0]); + ggml_tensor * b = ggml_view_1d(ctx0, base, width, offset*base->nb[0]); + return ggml_add(ctx0, ggml_mul(ctx0, z, a), b); + }; + ggml_tensor * pre = ggml_sigmoid(ctx0, affine(0, hc, 0)); + *post = ggml_scale(ctx0, ggml_sigmoid(ctx0, affine(hc, hc, 1)), hparams.hc_magnitude); + // combination: z ((hc-1)^2 Helmert coordinates) -> e = H z H^T, rho = 1 + max(0, max(-e / chart_base)), + // phi = chart_base + e / rho (doubly stochastic), comb = I + sigmoid(eta) * (phi - I) + ggml_tensor * z = ggml_cont_3d(ctx0, affine(2*hc, nm*nm, 2), nm, nm, nt); + ggml_tensor * e = ggml_mul_mat(ctx0, helmert, z); + e = ggml_mul_mat(ctx0, helmert, ggml_cont(ctx0, ggml_transpose(ctx0, e))); + ggml_tensor * ratio = ggml_neg(ctx0, ggml_div(ctx0, e, chart_base)); + ratio = ggml_reshape_2d(ctx0, ratio, hc*hc, nt); + ggml_tensor * rho = ggml_pool_1d(ctx0, ratio, GGML_OP_POOL_MAX, hc*hc, hc*hc, 0); + rho = ggml_scale_bias(ctx0, ggml_clamp(ctx0, rho, 0.0f, INFINITY), 1.0f, 1.0f); + rho = ggml_reshape_3d(ctx0, rho, 1, 1, nt); + ggml_tensor * phi = ggml_add(ctx0, ggml_div(ctx0, e, rho), chart_base); + ggml_tensor * gamma = ggml_sigmoid(ctx0, ggml_view_1d(ctx0, scale, 1, 3*scale->nb[0])); + *comb = ggml_add(ctx0, ggml_mul(ctx0, ggml_sub(ctx0, phi, identity), gamma), identity); + cb(*comb, "hc_comb", il); + cb(pre, "hc_pre", il); + cb(*post, "hc_post", il); + + if (cparams.fused_dsv4_hc_pre) { + ggml_tensor * result = ggml_dsv4_hc_pre(ctx0, x, pre); + res->add_fused_node({LLM_FUSED_OP_DSV4_HC_PRE, result, il}); + return result; + } + + ggml_tensor * result = nullptr; + for (int64_t i = 0; i < hc; ++i) { + ggml_tensor * xi = ggml_view_2d(ctx0, x, n_embd, nt, x->nb[2], i*x->nb[1]); + ggml_tensor * wi = ggml_view_2d(ctx0, pre, 1, nt, pre->nb[1], i*pre->nb[0]); + ggml_tensor * term = ggml_mul(ctx0, xi, wi); + result = result ? ggml_add(ctx0, result, term) : term; + } + return result; +} + +ggml_tensor * llama_model_raon1_mini::graph::build_hc_post( + ggml_tensor * x, ggml_tensor * branch, ggml_tensor * post, ggml_tensor * comb, int il) { + if (cparams.fused_dsv4_hc_post) { + ggml_tensor * result = ggml_dsv4_hc_post(ctx0, branch, x, post, comb); + res->add_fused_node({LLM_FUSED_OP_DSV4_HC_POST, result, il}); + return result; + } + + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nt = x->ne[2]; + ggml_tensor * result = nullptr; + for (int64_t dst = 0; dst < hc; ++dst) { + ggml_tensor * sum = nullptr; + for (int64_t src = 0; src < hc; ++src) { + ggml_tensor * xi = ggml_view_2d(ctx0, x, n_embd, nt, x->nb[2], src*x->nb[1]); + ggml_tensor * wi = ggml_view_2d(ctx0, comb, 1, nt, comb->nb[2], dst*comb->nb[0] + src*comb->nb[1]); + ggml_tensor * term = ggml_mul(ctx0, xi, wi); + sum = sum ? ggml_add(ctx0, sum, term) : term; + } + ggml_tensor * wi = ggml_view_2d(ctx0, post, 1, nt, post->nb[1], dst*post->nb[0]); + sum = ggml_add(ctx0, sum, ggml_mul(ctx0, branch, wi)); + sum = ggml_reshape_3d(ctx0, sum, n_embd, 1, nt); + result = result ? ggml_concat(ctx0, result, sum, 1) : sum; + } + return result; +} + +ggml_tensor * llama_model_raon1_mini::graph::build_mla_layer( + ggml_tensor * cur, const llama_layer & layer, llm_graph_input_attn_k * inp_attn_k, int il) { + const int64_t nr = hparams.n_rot(); + const int64_t nk = hparams.n_embd_head_k_mla(); + const int64_t nn = nk - nr; + const int64_t rank = hparams.n_lora_kv; + // Raon defines a separate RMSNorm epsilon for its Q and KV latent projections. + const float eps = hparams.f_norm_rms_eps_latent; + ggml_tensor * q = build_lora_mm(layer.wq_a, cur); + q = ggml_mul(ctx0, ggml_rms_norm(ctx0, q, eps), layer.attn_q_a_norm); + cb(q, "mla_q_norm", il); + q = build_lora_mm(layer.wq_b, q); + ggml_tensor * kv = build_lora_mm(layer.wkv_a_mqa, cur); + ggml_tensor * latent = ggml_view_2d(ctx0, kv, rank, n_tokens, kv->nb[1], 0); + latent = ggml_mul(ctx0, ggml_rms_norm(ctx0, latent, eps), layer.attn_kv_a_norm); + cb(latent, "mla_kv_norm", il); + // NoPE: the "rope" dims of q and k are concatenated as they are, without rotation + ggml_tensor * extra = ggml_view_3d(ctx0, kv, nr, 1, n_tokens, kv->nb[1], kv->nb[1], rank*kv->nb[0]); + ggml_tensor * q_nope = ggml_view_3d(ctx0, q, nn, n_head, n_tokens, nk*q->nb[0], q->nb[1], 0); + ggml_tensor * q_extra = ggml_view_3d(ctx0, q, nr, n_head, n_tokens, nk*q->nb[0], q->nb[1], nn*q->nb[0]); + q_nope = ggml_permute(ctx0, q_nope, 0, 2, 1, 3); + q_nope = build_lora_mm(layer.wk_b, q_nope); + q_nope = ggml_permute(ctx0, q_nope, 0, 2, 1, 3); + q = ggml_concat(ctx0, q_nope, q_extra, 0); + latent = ggml_reshape_3d(ctx0, latent, rank, 1, n_tokens); + ggml_tensor * k = ggml_concat(ctx0, latent, extra, 0); + ggml_tensor * out = build_attn(inp_attn_k, nullptr, nullptr, nullptr, q, k, latent, + nullptr, nullptr, layer.wv_b, 1.0f/sqrtf(nk), il); + out = ggml_mul(ctx0, out, ggml_sigmoid(ctx0, build_lora_mm(layer.wqkv_gate, cur))); + cb(out, "mla_gated", il); + return build_lora_mm(layer.wo, out); +} + +// dense SiTU-GLU feed-forward for the lead layers and the shared expert: +// situ(gate, up) = beta*tanh(gate/beta)*sigmoid(gate) * lb*tanh(up/lb) +// build_ffn has no SiTU case; the routed experts go through build_moe_ffn, which has one +ggml_tensor * llama_model_raon1_mini::graph::build_situ_ffn( + ggml_tensor * cur, ggml_tensor * up, ggml_tensor * gate, ggml_tensor * down, int il) { + const float beta = hparams.situ_beta; + const float lb = hparams.situ_linear_beta; + + ggml_tensor * u = build_lora_mm(up, cur); + cb(u, "ffn_up", il); + ggml_tensor * g = build_lora_mm(gate, cur); + cb(g, "ffn_gate", il); + + ggml_tensor * act = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, g, 1.0f/beta)), beta); + act = ggml_mul(ctx0, act, ggml_sigmoid(ctx0, g)); + u = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, u, 1.0f/lb)), lb); + cur = ggml_mul(ctx0, act, u); + cb(cur, "ffn_situ", il); + + cur = build_lora_mm(down, cur); + cb(cur, "ffn_out", il); + return cur; +} + +llama_model_raon1_mini::graph::graph(const llm_graph_params & params) : llm_build_delta_net_base(params) { + const int64_t hc = hparams.dsv4_hc_mult; + const int64_t nm = hc - 1; + helmert = nullptr; + for (int64_t i = 0; i < hc; ++i) { + ggml_tensor * row = nullptr; + for (int64_t j = 0; j < nm; ++j) { + const float v = (i <= j ? 1.0f : i == j + 1 ? -(float) (j + 1) : 0.0f)/sqrtf((j + 1)*(j + 2)); + ggml_tensor * c = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1), v); + row = row ? ggml_concat(ctx0, row, c, 0) : c; + } + row = ggml_reshape_2d(ctx0, row, nm, 1); + helmert = helmert ? ggml_concat(ctx0, helmert, row, 1) : row; + } + identity = ggml_diag(ctx0, ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, hc), 1.0f)); + chart_base = ggml_scale_bias(ctx0, identity, 0.5f, 0.5f/hc); + + ggml_tensor * inp = build_inp_embd(model.tok_embd); + inp = ggml_reshape_3d(ctx0, inp, n_embd, 1, n_tokens); + inp = ggml_repeat_4d(ctx0, inp, n_embd, hc, n_tokens, 1); + auto * inputs = build_inp_mem_hybrid_k(); + auto * inp_rs = inputs->get_recr(); + auto * inp_attn = inputs->get_attn(); + auto * out_ids = build_inp_out_ids(); + GGML_ASSERT(ubatch.n_seqs != 0 && ubatch.equal_seqs()); + GGML_ASSERT(ubatch.n_tokens == ubatch.n_seq_tokens*ubatch.n_seqs); + + for (int il = 0; il < n_layer; ++il) { + const auto & layer = model.layers[il]; + ggml_tensor * post; + ggml_tensor * comb; + ggml_tensor * cur = build_hc_pre(inp, layer.hc_attn_fn, layer.hc_attn_scale, layer.hc_attn_base, &post, &comb, il); + cur = build_norm(cur, layer.attn_norm, nullptr, LLM_NORM_RMS, il); + cb(cur, "attn_norm", il); + if (hparams.is_recr(il)) { + cur = build_rda_layer(cur, layer, inp_rs, il); + } else { + cur = build_mla_layer(cur, layer, inp_attn, il); + } + inp = build_hc_post(inp, cur, post, comb, il); + cb(inp, "hc_attn_out", il); + cur = build_hc_pre(inp, layer.hc_ffn_fn, layer.hc_ffn_scale, layer.hc_ffn_base, &post, &comb, il); + cur = build_norm(cur, layer.ffn_norm, nullptr, LLM_NORM_RMS, il); + cb(cur, "ffn_norm", il); + if (il < (int) hparams.n_layer_dense_lead) { + cur = build_situ_ffn(cur, layer.ffn_up, layer.ffn_gate, layer.ffn_down, il); + } else { + ggml_tensor * moe = build_moe_ffn(cur, + layer.ffn_gate_inp, + layer.ffn_up_exps, + layer.ffn_gate_exps, + layer.ffn_down_exps, + layer.ffn_exp_probs_b, + hparams.n_expert, hparams.n_expert_used(), + LLM_FFN_SITU, hparams.expert_weights_norm, + hparams.expert_weights_scale, + (llama_expert_gating_func_type) hparams.expert_gating_func, + il); + if (layer.ffn_gate_shexp) { + ggml_tensor * shared = build_situ_ffn(cur, layer.ffn_up_shexp, layer.ffn_gate_shexp, + layer.ffn_down_shexp, il); + moe = ggml_add(ctx0, moe, shared); + } + cur = moe; + } + inp = build_hc_post(inp, cur, post, comb, il); + inp = build_cvec(inp, il); + cb(inp, "l_out", il); + } + ggml_tensor * cur = nullptr; + for (int64_t i = 0; i < hc; ++i) { + ggml_tensor * x = ggml_view_2d(ctx0, inp, n_embd, n_tokens, inp->nb[2], i*inp->nb[1]); + cur = cur ? ggml_add(ctx0, cur, x) : x; + } + cur = ggml_scale(ctx0, cur, 1.0f/hc); + if (out_ids) { + cur = ggml_get_rows(ctx0, cur, out_ids); + } + cur = build_norm(cur, model.output_norm, nullptr, LLM_NORM_RMS, -1); + cb(cur, "result_norm", -1); + res->t_embd = cur; + cur = build_lora_mm(model.output, cur); + cb(cur, "result_output", -1); + res->t_logits = cur; +} diff --git a/src/unicode.cpp b/src/unicode.cpp index 9226c73db66e..ea5957514bdd 100644 --- a/src/unicode.cpp +++ b/src/unicode.cpp @@ -1221,6 +1221,178 @@ static std::vector unicode_regex_split_custom_newlines(const std::string return bpe_offsets; } +// regex: ?[\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff]+| ?(?:(?:(?![\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff])\p{L})\p{M}*)+(?: (?:(?:(?![\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff])\p{L})\p{M}*)+)*|\p{N}{1,3}(?=(?:\p{N}{3})*(?!\p{N}))| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+ +// Raon-1 mini: CJK runs are split from other letters, letter runs keep marks and can span one space, digits are grouped by 3 from the right +static std::vector unicode_regex_split_custom_raon(const std::string & text, const std::vector & offsets) { + std::vector bpe_offsets; + bpe_offsets.reserve(offsets.size()); + + const auto cpts = unicode_cpts_from_utf8(text); + + size_t start = 0; + for (auto offset : offsets) { + const size_t offset_ini = start; + const size_t offset_end = start + offset; + assert(offset_end <= cpts.size()); + start = offset_end; + + static const uint32_t OUT_OF_RANGE = 0xFFFFFFFF; + auto _get_cpt = [&] (const size_t pos) -> uint32_t { + return (offset_ini <= pos && pos < offset_end) ? cpts[pos] : OUT_OF_RANGE; + }; + + auto _get_flags = [&] (const size_t pos) -> unicode_cpt_flags { + return (offset_ini <= pos && pos < offset_end) ? unicode_cpt_flags_from_cpt(cpts[pos]) : unicode_cpt_flags{}; + }; + + // [\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff] + auto _is_cjk = [&] (const size_t pos) -> bool { + const uint32_t cpt = _get_cpt(pos); + return (0x4e00 <= cpt && cpt <= 0x9fa5) || (0x3040 <= cpt && cpt <= 0x30ff); + }; + + // (?![CJK])\p{L} + auto _is_letter = [&] (const size_t pos) -> bool { + return _get_flags(pos).is_letter && !_is_cjk(pos); + }; + + // [^\s\p{L}\p{N}] + auto _is_punct = [&] (const size_t pos) -> bool { + if (pos < offset_ini || offset_end <= pos) { + return false; + } + const auto flags = _get_flags(pos); + return !flags.is_whitespace && !flags.is_letter && !flags.is_number; + }; + + size_t _prev_end = offset_ini; + auto _add_token = [&] (const size_t end) -> size_t { + assert(_prev_end <= end && end <= offset_end); + size_t len = end - _prev_end; + if (len > 0) { + bpe_offsets.push_back(len); + } + _prev_end = end; + return len; + }; + + for (size_t pos = offset_ini; pos < offset_end; ) { + const uint32_t cpt = _get_cpt(pos); + const auto flags = _get_flags(pos); + + // the CJK, letter and punctuation alternatives accept one optional leading space + size_t pos2 = pos + (cpt == ' '); + + // regex: ' ?[CJK]+' + if (_is_cjk(pos2)) { + do { + pos2++; + } while (_is_cjk(pos2)); + pos += _add_token(pos2); + continue; + } + + // regex: ' ?(?:(?:(?![CJK])\p{L})\p{M}*)+(?: (?:(?:(?![CJK])\p{L})\p{M}*)+)*' + if (_is_letter(pos2)) { + while (true) { + pos2++; + while (_get_flags(pos2).is_accent_mark) { + pos2++; + } + if (_is_letter(pos2)) { + continue; + } + // a single space joins two letter runs + if (_get_cpt(pos2) == ' ' && _is_letter(pos2 + 1)) { + pos2++; + continue; + } + break; + } + pos += _add_token(pos2); + continue; + } + + // regex: '\p{N}{1,3}(?=(?:\p{N}{3})*(?!\p{N}))' - groups of three from the right + if (flags.is_number) { + size_t digit_start = pos; + size_t digit_count = 0; + + // Count consecutive digits + while (_get_flags(pos).is_number && pos < offset_end) { + digit_count++; + pos++; + } + + // Split based on total length modulo 3 + size_t remainder = digit_count % 3; + size_t current = digit_start; + + // Emit leading 1-2 digits if needed + if (remainder > 0) { + _add_token(current + remainder); + current += remainder; + } + + // Emit groups of 3 + while (current < digit_start + digit_count) { + _add_token(current + 3); + current += 3; + } + continue; + } + + // regex: ' ?[^\s\p{L}\p{N}]+[\r\n/]*' + if (_is_punct(pos2)) { + do { + pos2++; + } while (_is_punct(pos2)); + uint32_t cpt2 = _get_cpt(pos2); + while (cpt2 == '\r' || cpt2 == '\n' || cpt2 == '/') { + cpt2 = _get_cpt(++pos2); + } + pos += _add_token(pos2); + continue; + } + + // regex: '\s*[\r\n]+' + size_t num_whitespaces = 0; + size_t last_end_r_or_n = 0; + while (_get_flags(pos + num_whitespaces).is_whitespace) { + const uint32_t cpt2 = _get_cpt(pos + num_whitespaces); + if (cpt2 == '\r' || cpt2 == '\n') { + last_end_r_or_n = pos + num_whitespaces + 1; + } + num_whitespaces++; + } + if (last_end_r_or_n > 0) { + pos = last_end_r_or_n; + _add_token(pos); + continue; + } + + // regex: '\s+(?!\S)' + if (num_whitespaces > 1 && _get_cpt(pos + num_whitespaces) != OUT_OF_RANGE) { + pos += num_whitespaces - 1; + _add_token(pos); + continue; + } + + // regex: '\s+' + if (num_whitespaces > 0) { + pos += num_whitespaces; + _add_token(pos); + continue; + } + + // no matches + _add_token(++pos); + } + } + + return bpe_offsets; +} + static std::vector unicode_regex_split_custom(const std::string & text, const std::string & regex_expr, const std::vector & offsets) { std::vector bpe_offsets; @@ -1255,6 +1427,9 @@ static std::vector unicode_regex_split_custom(const std::string & text, // Splits digits into groups of 3 from the right (e.g., 1234567 -> 1, 234, 567) // TODO: Revisit this regex, in case there are any subtle tokenization differences with the original regex. bpe_offsets = unicode_regex_split_custom_afmoe(text, offsets); + } else if (regex_expr == " ?[\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff]+| ?(?:(?:(?![\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff])\\p{L})\\p{M}*)+(?: (?:(?:(?![\u4e00-\u9fa5\u3040-\u309f\u30a0-\u30ff])\\p{L})\\p{M}*)+)*|\\p{N}{1,3}(?=(?:\\p{N}{3})*(?!\\p{N}))| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+") { + // Raon-1 mini: must match the LLAMA_VOCAB_PRE_TYPE_RAON regex in llama-vocab.cpp byte for byte + bpe_offsets = unicode_regex_split_custom_raon(text, offsets); } return bpe_offsets; diff --git a/tests/fusion/MTL.csv b/tests/fusion/MTL.csv index 2a4f4b36192c..65dbfde15f13 100644 --- a/tests/fusion/MTL.csv +++ b/tests/fusion/MTL.csv @@ -5,9 +5,9 @@ afmoe ,1 ,any ,RMS_NORM+MUL , 10 afmoe ,1 ,any ,RMS_NORM+MUL+ADD , 3 afmoe ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 arcee ,0 ,any ,RMS_NORM+MUL , 5 -arctic ,0 ,any ,MUL+ADD , 4 -arctic ,0 ,any ,RMS_NORM+MUL , 7 -arctic ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 +arctic ,1 ,any ,MUL+ADD , 4 +arctic ,1 ,any ,RMS_NORM+MUL , 7 +arctic ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 baichuan ,0 ,any ,RMS_NORM+MUL , 5 bailingmoe ,1 ,any ,ADD+ADD , 2 bailingmoe ,1 ,any ,MUL+ADD , 4 @@ -23,8 +23,8 @@ bailingmoe3 ,1 ,any ,MUL+ADD , 2 bailingmoe3 ,1 ,any ,RMS_NORM+MUL , 8 bailingmoe3 ,1 ,any ,RMS_NORM+SCALE , 2 bailingmoe3 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 -beam ,0 ,any ,MUL+ADD , 6 -beam ,0 ,any ,RMS_NORM+MUL , 25 +beam ,1 ,any ,MUL+ADD , 6 +beam ,1 ,any ,RMS_NORM+MUL , 25 bloom ,0 ,any ,NORM+MUL+ADD , 6 chatglm ,0 ,any ,RMS_NORM+MUL , 5 clover_moe ,1 ,any ,ADD+ADD , 2 @@ -43,45 +43,45 @@ 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 -dbrx ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 +dbrx ,1 ,any ,MUL+ADD , 4 +dbrx ,1 ,any ,NORM+MUL , 5 +dbrx ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 deci ,0 ,any ,RMS_NORM+MUL , 5 -deepseek ,0 ,any ,ADD+ADD , 1 -deepseek ,0 ,any ,MUL+ADD , 2 -deepseek ,0 ,any ,RMS_NORM+MUL , 5 -deepseek ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS , 1 -deepseek2 ,0 ,any ,ADD+ADD , 1 -deepseek2 ,0 ,any ,MUL+ADD , 2 -deepseek2 ,0 ,any ,RMS_NORM+MUL , 9 -deepseek2 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 -deepseek32 ,0 ,any ,ADD+ADD , 1 -deepseek32 ,0 ,any ,MUL+ADD , 2 -deepseek32 ,0 ,any ,NORM+MUL+ADD , 2 -deepseek32 ,0 ,any ,RMS_NORM+MUL , 9 -deepseek32 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 -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 , 31 -deepseek41 ,0 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV, 6 +deepseek ,1 ,any ,ADD+ADD , 1 +deepseek ,1 ,any ,MUL+ADD , 2 +deepseek ,1 ,any ,RMS_NORM+MUL , 5 +deepseek ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS , 1 +deepseek2 ,1 ,any ,ADD+ADD , 1 +deepseek2 ,1 ,any ,MUL+ADD , 2 +deepseek2 ,1 ,any ,RMS_NORM+MUL , 9 +deepseek2 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 +deepseek32 ,1 ,any ,ADD+ADD , 1 +deepseek32 ,1 ,any ,MUL+ADD , 2 +deepseek32 ,1 ,any ,NORM+MUL+ADD , 2 +deepseek32 ,1 ,any ,RMS_NORM+MUL , 9 +deepseek32 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 +deepseek4 ,1 ,any ,MUL+ADD , 8 +deepseek4 ,1 ,any ,RMS_NORM+MUL , 20 +deepseek4 ,1 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 4 +deepseek41 ,1 ,any ,MUL+ADD , 12 +deepseek41 ,1 ,any ,RMS_NORM+MUL , 31 +deepseek41 ,1 ,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 -dots1 ,0 ,any ,ADD+ADD , 1 -dots1 ,0 ,any ,MUL+ADD , 2 -dots1 ,0 ,any ,RMS_NORM+MUL , 9 -dots1 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 -dots3note ,0 ,any ,ADD+ADD , 1 -dots3note ,0 ,any ,MUL+ADD , 2 -dots3note ,0 ,any ,NORM+MUL+ADD , 1 -dots3note ,0 ,any ,RMS_NORM+MUL , 11 -dots3note ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 +dots1 ,1 ,any ,ADD+ADD , 1 +dots1 ,1 ,any ,MUL+ADD , 2 +dots1 ,1 ,any ,RMS_NORM+MUL , 9 +dots1 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 +dots3note ,1 ,any ,ADD+ADD , 1 +dots3note ,1 ,any ,MUL+ADD , 2 +dots3note ,1 ,any ,NORM+MUL+ADD , 1 +dots3note ,1 ,any ,RMS_NORM+MUL , 11 +dots3note ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 dream ,0 ,any ,RMS_NORM+MUL , 5 ernie4_5-moe ,1 ,any ,ADD+ADD , 1 ernie4_5-moe ,1 ,any ,MUL+ADD , 2 ernie4_5-moe ,1 ,any ,RMS_NORM+MUL , 5 -ernie4_5 ,0 ,any ,RMS_NORM+MUL , 5 +ernie4_5 ,1 ,any ,RMS_NORM+MUL , 5 exaone ,0 ,any ,RMS_NORM+MUL , 5 exaone-moe ,1 ,any ,ADD+ADD , 1 exaone-moe ,1 ,any ,MUL+ADD , 2 @@ -93,10 +93,10 @@ falcon ,0 ,any ,ADD+ADD , 2 falcon ,0 ,any ,NORM+MUL+ADD , 5 falcon-h1 ,0 ,any ,ADD+ADD , 2 falcon-h1 ,0 ,any ,RMS_NORM+MUL , 9 -flint ,0 ,any ,ADD+ADD , 1 -flint ,0 ,any ,MUL+ADD , 2 -flint ,0 ,any ,RMS_NORM+MUL , 9 -flint ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1 +flint ,1 ,any ,ADD+ADD , 1 +flint ,1 ,any ,MUL+ADD , 2 +flint ,1 ,any ,RMS_NORM+MUL , 9 +flint ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1 gemma ,0 ,any ,RMS_NORM+MUL , 5 gemma2 ,0 ,any ,RMS_NORM+MUL , 5 gemma2 ,0 ,any ,RMS_NORM+MUL+ADD , 4 @@ -104,42 +104,42 @@ gemma3 ,0 ,any ,RMS_NORM+MUL , 9 gemma3 ,0 ,any ,RMS_NORM+MUL+ADD , 4 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 -glm-dsa ,0 ,any ,RMS_NORM+MUL , 9 -glm-dsa ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 +glm-dsa ,1 ,any ,ADD+ADD , 1 +glm-dsa ,1 ,any ,MUL+ADD , 2 +glm-dsa ,1 ,any ,NORM+MUL+ADD , 2 +glm-dsa ,1 ,any ,RMS_NORM+MUL , 9 +glm-dsa ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 glm4 ,0 ,any ,RMS_NORM+MUL , 5 glm4 ,0 ,any ,RMS_NORM+MUL+ADD , 4 glm4moe ,1 ,any ,ADD+ADD , 1 glm4moe ,1 ,any ,MUL+ADD , 2 glm4moe ,1 ,any ,RMS_NORM+MUL , 9 glm4moe ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 -glm5-next ,0 ,any ,ADD+ADD+ADD , 1 -glm5-next ,0 ,any ,GATED_DELTA_NET+CPY , 1 -glm5-next ,0 ,any ,MUL+ADD , 2 -glm5-next ,0 ,any ,NORM+MUL+ADD , 1 -glm5-next ,0 ,any ,RMS_NORM+MUL , 8 -glm5-next ,0 ,any ,RMS_NORM+SCALE , 2 -glm5-next ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 -gpt-oss ,0 ,any ,MUL+ADD , 4 -gpt-oss ,0 ,any ,RMS_NORM+MUL , 5 +glm5-next ,1 ,any ,ADD+ADD+ADD , 1 +glm5-next ,1 ,any ,GATED_DELTA_NET+CPY , 1 +glm5-next ,1 ,any ,MUL+ADD , 2 +glm5-next ,1 ,any ,NORM+MUL+ADD , 1 +glm5-next ,1 ,any ,RMS_NORM+MUL , 8 +glm5-next ,1 ,any ,RMS_NORM+SCALE , 2 +glm5-next ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 +gpt-oss ,1 ,any ,MUL+ADD , 4 +gpt-oss ,1 ,any ,RMS_NORM+MUL , 5 gpt2 ,0 ,any ,NORM+MUL+ADD , 5 gptneox ,0 ,any ,NORM+MUL+ADD , 5 granite ,0 ,any ,RMS_NORM+MUL , 5 -granite ,0 ,any ,MUL+ADD , 4 -granite ,0 ,any ,RMS_NORM+MUL , 5 -granite ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 +granite ,1 ,any ,MUL+ADD , 4 +granite ,1 ,any ,RMS_NORM+MUL , 5 +granite ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 granite_swa ,0 ,any ,RMS_NORM+MUL , 5 granitehybrid ,0 ,any ,RMS_NORM+MUL , 6 -granitemoe ,1 ,any ,RMS_NORM+MUL , 5 +granitemoe ,0 ,any ,RMS_NORM+MUL , 5 granitemoe ,1 ,any ,MUL+ADD , 4 granitemoe ,1 ,any ,RMS_NORM+MUL , 5 granitemoe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 -grok ,0 ,any ,MUL+ADD , 4 -grok ,0 ,any ,RMS_NORM+MUL , 5 -grok ,0 ,any ,RMS_NORM+MUL+ADD , 4 -grok ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 +grok ,1 ,any ,MUL+ADD , 4 +grok ,1 ,any ,RMS_NORM+MUL , 5 +grok ,1 ,any ,RMS_NORM+MUL+ADD , 4 +grok ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 grovemoe ,1 ,any ,ADD+ADD , 2 grovemoe ,1 ,any ,MUL+ADD , 8 grovemoe ,1 ,any ,RMS_NORM+MUL , 9 @@ -149,50 +149,53 @@ hunyuan-moe ,1 ,any ,MUL+ADD , 4 hunyuan-moe ,1 ,any ,RMS_NORM+MUL , 9 hunyuan-moe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 hunyuan_vl ,0 ,any ,RMS_NORM+MUL , 9 -hy_v3 ,0 ,any ,ADD+ADD , 2 -hy_v3 ,0 ,any ,MUL+ADD , 4 -hy_v3 ,0 ,any ,RMS_NORM+MUL , 9 -hy_v3 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 2 -hy_v4 ,0 ,any ,MUL+ADD , 2 -hy_v4 ,0 ,any ,NORM+MUL+ADD , 1 -hy_v4 ,0 ,any ,RMS_NORM+MUL , 9 -hy_v4 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1 -inkling2 ,0 ,any ,MUL+ADD , 6 -inkling2 ,0 ,any ,RMS_NORM+MUL , 10 -inkling2 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV+SCALE, 3 +hy_v3 ,1 ,any ,ADD+ADD , 2 +hy_v3 ,1 ,any ,MUL+ADD , 4 +hy_v3 ,1 ,any ,RMS_NORM+MUL , 9 +hy_v3 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 2 +hy_v4 ,1 ,any ,MUL+ADD , 2 +hy_v4 ,1 ,any ,NORM+MUL+ADD , 1 +hy_v4 ,1 ,any ,RMS_NORM+MUL , 9 +hy_v4 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1 +hy_v4_flash ,1 ,any ,MUL+ADD , 6 +hy_v4_flash ,1 ,any ,RMS_NORM+MUL , 32 +hy_v4_flash ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 3 +inkling2 ,1 ,any ,MUL+ADD , 6 +inkling2 ,1 ,any ,RMS_NORM+MUL , 10 +inkling2 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV+SCALE, 3 internlm2 ,0 ,any ,RMS_NORM+MUL , 5 jais ,0 ,any ,NORM+MUL+ADD , 5 jais2 ,0 ,any ,NORM+MUL+ADD , 5 jamba ,0 ,any ,RMS_NORM+MUL , 8 k2-horizon ,0 ,any ,RMS_NORM+MUL , 4 -k2-horizon ,0 ,any ,ADD+ADD , 1 -k2-horizon ,0 ,any ,MUL+ADD , 2 -k2-horizon ,0 ,any ,RMS_NORM+MUL , 4 -k2-horizon ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 -kimi-k3 ,0 ,any ,GATED_DELTA_NET+CPY , 1 -kimi-k3 ,0 ,any ,MUL+ADD , 2 -kimi-k3 ,0 ,any ,RMS_NORM+MUL , 17 -kimi-k3 ,0 ,any ,RMS_NORM+SCALE , 2 -kimi-k3 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 -kimi-k31 ,0 ,any ,GATED_DELTA_NET+CPY , 1 -kimi-k31 ,0 ,any ,MUL+ADD , 2 -kimi-k31 ,0 ,any ,NORM+MUL+ADD , 1 -kimi-k31 ,0 ,any ,RMS_NORM+MUL , 17 -kimi-k31 ,0 ,any ,RMS_NORM+SCALE , 2 -kimi-k31 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 -kimi-linear ,0 ,any ,ADD+ADD , 1 -kimi-linear ,0 ,any ,GATED_DELTA_NET+CPY , 1 -kimi-linear ,0 ,any ,MUL+ADD , 2 -kimi-linear ,0 ,any ,RMS_NORM+MUL , 7 -kimi-linear ,0 ,any ,RMS_NORM+SCALE , 2 -kimi-linear ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1 -kolibri1 ,0 ,any ,MUL+ADD , 4 -kolibri1 ,0 ,any ,RMS_NORM+MUL , 10 -kolibri1 ,0 ,any ,RMS_NORM+MUL+ADD , 3 -laguna ,0 ,any ,ADD+ADD , 1 -laguna ,0 ,any ,MUL+ADD , 2 -laguna ,0 ,any ,RMS_NORM+MUL , 9 -laguna ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 +k2-horizon ,1 ,any ,ADD+ADD , 1 +k2-horizon ,1 ,any ,MUL+ADD , 2 +k2-horizon ,1 ,any ,RMS_NORM+MUL , 4 +k2-horizon ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 +kimi-k3 ,1 ,any ,GATED_DELTA_NET+CPY , 1 +kimi-k3 ,1 ,any ,MUL+ADD , 2 +kimi-k3 ,1 ,any ,RMS_NORM+MUL , 17 +kimi-k3 ,1 ,any ,RMS_NORM+SCALE , 2 +kimi-k3 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 +kimi-k31 ,1 ,any ,GATED_DELTA_NET+CPY , 1 +kimi-k31 ,1 ,any ,MUL+ADD , 2 +kimi-k31 ,1 ,any ,NORM+MUL+ADD , 1 +kimi-k31 ,1 ,any ,RMS_NORM+MUL , 17 +kimi-k31 ,1 ,any ,RMS_NORM+SCALE , 2 +kimi-k31 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 +kimi-linear ,1 ,any ,ADD+ADD , 1 +kimi-linear ,1 ,any ,GATED_DELTA_NET+CPY , 1 +kimi-linear ,1 ,any ,MUL+ADD , 2 +kimi-linear ,1 ,any ,RMS_NORM+MUL , 7 +kimi-linear ,1 ,any ,RMS_NORM+SCALE , 2 +kimi-linear ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1 +kolibri1 ,1 ,any ,MUL+ADD , 4 +kolibri1 ,1 ,any ,RMS_NORM+MUL , 10 +kolibri1 ,1 ,any ,RMS_NORM+MUL+ADD , 3 +laguna ,1 ,any ,ADD+ADD , 1 +laguna ,1 ,any ,MUL+ADD , 2 +laguna ,1 ,any ,RMS_NORM+MUL , 9 +laguna ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 lfm2 ,0 ,any ,RMS_NORM+MUL , 7 lfm2moe ,1 ,any ,MUL+ADD , 2 lfm2moe ,1 ,any ,RMS_NORM+MUL , 7 @@ -204,69 +207,69 @@ llada-moe ,1 ,any ,MUL+ADD , 4 llada-moe ,1 ,any ,RMS_NORM+MUL , 9 llada-moe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS , 2 llama ,0 ,any ,RMS_NORM+MUL , 5 -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 +llama ,1 ,any ,MUL+ADD , 4 +llama ,1 ,any ,RMS_NORM+MUL , 5 +llama ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 +llama4 ,1 ,any ,ADD+ADD , 2 +llama4 ,1 ,any ,MUL+ADD , 4 +llama4 ,1 ,any ,RMS_NORM+MUL , 9 maincoder ,0 ,any ,RMS_NORM+MUL , 9 -maion-coder ,0 ,any ,MUL+ADD , 4 -maion-coder ,0 ,any ,RMS_NORM+MUL , 17 -maion-coder ,0 ,any ,RMS_NORM+MUL+ADD , 8 -maion-coder ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 +maion-coder ,1 ,any ,MUL+ADD , 4 +maion-coder ,1 ,any ,RMS_NORM+MUL , 17 +maion-coder ,1 ,any ,RMS_NORM+MUL+ADD , 8 +maion-coder ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 mamba ,0 ,any ,RMS_NORM+MUL , 3 mamba2 ,0 ,any ,RMS_NORM+MUL , 5 -maple ,0 ,any ,MUL+ADD , 4 -maple ,0 ,any ,RMS_NORM+MUL , 9 -maple ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 -mellum ,0 ,any ,MUL+ADD , 4 -mellum ,0 ,any ,RMS_NORM+MUL , 9 -mellum ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 -metis16 ,0 ,any ,MUL+ADD , 8 -metis16 ,0 ,any ,RMS_NORM+MUL , 11 -mimo2 ,0 ,any ,MUL+ADD , 4 -mimo2 ,0 ,any ,RMS_NORM+MUL , 5 -mimo2 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 +maple ,1 ,any ,MUL+ADD , 4 +maple ,1 ,any ,RMS_NORM+MUL , 9 +maple ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 +mellum ,1 ,any ,MUL+ADD , 4 +mellum ,1 ,any ,RMS_NORM+MUL , 9 +mellum ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 +metis16 ,1 ,any ,MUL+ADD , 8 +metis16 ,1 ,any ,RMS_NORM+MUL , 11 +mimo2 ,1 ,any ,MUL+ADD , 4 +mimo2 ,1 ,any ,RMS_NORM+MUL , 5 +mimo2 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 minicpm ,0 ,any ,RMS_NORM+MUL , 5 -minicpm ,0 ,any ,MUL+ADD , 4 -minicpm ,0 ,any ,RMS_NORM+MUL , 5 -minicpm ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 +minicpm ,1 ,any ,MUL+ADD , 4 +minicpm ,1 ,any ,RMS_NORM+MUL , 5 +minicpm ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 minicpm3 ,0 ,any ,RMS_NORM+MUL , 9 -minimax-01 ,0 ,any ,MUL+ADD , 4 -minimax-01 ,0 ,any ,RMS_NORM+MUL , 6 -minimax-01 ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 -minimax-m2 ,0 ,any ,MUL+ADD , 4 -minimax-m2 ,0 ,any ,RMS_NORM+MUL , 9 -minimax-m2 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 -minimax-m3 ,0 ,any ,ADD+ADD , 1 -minimax-m3 ,0 ,any ,MUL+ADD , 2 -minimax-m3 ,0 ,any ,RMS_NORM+MUL , 11 -minimax-m3 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 -mistral-large4 ,0 ,any ,ADD+ADD , 3 -mistral-large4 ,0 ,any ,MUL+ADD , 6 -mistral-large4 ,0 ,any ,NORM+MUL+ADD , 6 -mistral-large4 ,0 ,any ,RMS_NORM+MUL , 12 -mistral3 ,0 ,any ,RMS_NORM+MUL , 5 -mistral3 ,0 ,any ,MUL+ADD , 4 +minimax-01 ,1 ,any ,MUL+ADD , 4 +minimax-01 ,1 ,any ,RMS_NORM+MUL , 6 +minimax-01 ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 +minimax-m2 ,1 ,any ,MUL+ADD , 4 +minimax-m2 ,1 ,any ,RMS_NORM+MUL , 9 +minimax-m2 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 +minimax-m3 ,1 ,any ,ADD+ADD , 1 +minimax-m3 ,1 ,any ,MUL+ADD , 2 +minimax-m3 ,1 ,any ,RMS_NORM+MUL , 11 +minimax-m3 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 +mistral-large4 ,1 ,any ,ADD+ADD , 3 +mistral-large4 ,1 ,any ,MUL+ADD , 6 +mistral-large4 ,1 ,any ,NORM+MUL+ADD , 6 +mistral-large4 ,1 ,any ,RMS_NORM+MUL , 12 mistral3 ,0 ,any ,RMS_NORM+MUL , 5 -mistral3 ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 -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 +mistral3 ,1 ,any ,MUL+ADD , 4 +mistral3 ,1 ,any ,RMS_NORM+MUL , 5 +mistral3 ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 +mistral4 ,1 ,any ,ADD+ADD , 1 +mistral4 ,1 ,any ,MUL+ADD , 2 +mistral4 ,1 ,any ,RMS_NORM+MUL , 9 +mistral4 ,1 ,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 -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 +muse-spark ,1 ,any ,MUL+ADD , 4 +muse-spark ,1 ,any ,RMS_NORM+MUL , 11 +muse-spark ,1 ,any ,RMS_NORM+MUL+ADD , 3 +muse-spark ,1 ,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 nemotron_h ,0 ,any ,RMS_NORM+MUL , 5 -nemotron_h_moe ,1 ,any ,RMS_NORM+MUL , 5 +nemotron_h_moe ,0 ,any ,RMS_NORM+MUL , 5 olmo2 ,0 ,any ,RMS_NORM+MUL , 5 olmo2 ,0 ,any ,RMS_NORM+MUL+ADD , 4 olmoe ,1 ,any ,MUL+ADD , 4 @@ -274,7 +277,7 @@ olmoe ,1 ,any ,RMS_NORM+MUL , 9 olmoe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS , 2 openelm ,0 ,any ,RMS_NORM+MUL , 9 orion ,0 ,any ,NORM+MUL+ADD , 5 -paddleocr ,0 ,any ,RMS_NORM+MUL , 5 +paddleocr ,1 ,any ,RMS_NORM+MUL , 5 pangu-embedded ,0 ,any ,RMS_NORM+MUL , 5 phi2 ,0 ,any ,ADD+ADD , 2 phi2 ,0 ,any ,NORM+MUL+ADD , 3 @@ -312,35 +315,40 @@ qwen35moe ,1 ,any ,SSM_CONV+UNARY , 1 qwen3moe ,1 ,any ,MUL+ADD , 4 qwen3moe ,1 ,any ,RMS_NORM+MUL , 9 qwen3moe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 -qwen3next ,0 ,any ,ADD+ADD , 2 -qwen3next ,0 ,any ,GATED_DELTA_NET+CPY , 1 -qwen3next ,0 ,any ,MUL+ADD , 4 -qwen3next ,0 ,any ,RMS_NORM+MUL , 8 -qwen3next ,0 ,any ,RMS_NORM+SCALE , 2 -qwen3next ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 -qwen3next ,0 ,any ,SSM_CONV+UNARY , 1 +qwen3next ,1 ,any ,ADD+ADD , 2 +qwen3next ,1 ,any ,GATED_DELTA_NET+CPY , 1 +qwen3next ,1 ,any ,MUL+ADD , 4 +qwen3next ,1 ,any ,RMS_NORM+MUL , 8 +qwen3next ,1 ,any ,RMS_NORM+SCALE , 2 +qwen3next ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 +qwen3next ,1 ,any ,SSM_CONV+UNARY , 1 qwen3tts ,0 ,any ,RMS_NORM+MUL , 9 qwen3vl ,0 ,any ,RMS_NORM+MUL , 9 qwen3vlmoe ,1 ,any ,MUL+ADD , 4 qwen3vlmoe ,1 ,any ,RMS_NORM+MUL , 9 qwen3vlmoe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 -qwen4exp ,0 ,any ,ADD+ADD+ADD , 2 -qwen4exp ,0 ,any ,GATED_DELTA_NET+CPY , 1 -qwen4exp ,0 ,any ,MUL+ADD , 4 -qwen4exp ,0 ,any ,RMS_NORM+MUL , 13 -qwen4exp ,0 ,any ,RMS_NORM+SCALE , 2 -qwen4exp ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 -qwen4exp ,0 ,any ,SSM_CONV+UNARY , 1 -refact ,0 ,any ,RMS_NORM+MUL , 5 +qwen4exp ,1 ,any ,ADD+ADD+ADD , 2 +qwen4exp ,1 ,any ,GATED_DELTA_NET+CPY , 1 +qwen4exp ,1 ,any ,MUL+ADD , 4 +qwen4exp ,1 ,any ,RMS_NORM+MUL , 13 +qwen4exp ,1 ,any ,RMS_NORM+SCALE , 2 +qwen4exp ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 +qwen4exp ,1 ,any ,SSM_CONV+UNARY , 1 +raon1 ,1 ,any ,ADD+ADD+ADD , 1 +raon1 ,1 ,any ,GATED_DELTA_NET+CPY , 1 +raon1 ,1 ,any ,MUL+ADD , 2 +raon1 ,1 ,any ,RMS_NORM+MUL , 8 +raon1 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV, 1 refact ,0 ,any ,RMS_NORM+MUL , 5 +refact ,1 ,any ,RMS_NORM+MUL , 5 ricursive ,0 ,any ,RMS_NORM+MUL , 9 ricursive ,0 ,any ,RMS_NORM+MUL+ADD , 4 -rnd1 ,0 ,any ,MUL+ADD , 4 -rnd1 ,0 ,any ,RMS_NORM+MUL , 9 -rnd1 ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 +rnd1 ,1 ,any ,MUL+ADD , 4 +rnd1 ,1 ,any ,RMS_NORM+MUL , 9 +rnd1 ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 seed_oss ,0 ,any ,RMS_NORM+MUL , 5 -smallthinker ,0 ,any ,MUL+ADD , 4 -smallthinker ,0 ,any ,RMS_NORM+MUL , 5 +smallthinker ,1 ,any ,MUL+ADD , 4 +smallthinker ,1 ,any ,RMS_NORM+MUL , 5 smollm3 ,0 ,any ,RMS_NORM+MUL , 5 spark2_5 ,0 ,any ,RMS_NORM+MUL , 5 stablelm ,0 ,any ,NORM+MUL , 4 @@ -348,14 +356,14 @@ stablelm ,0 ,any ,NORM+MUL+ADD , 5 starcoder ,0 ,any ,NORM+MUL+ADD , 5 starcoder2 ,0 ,any ,NORM+MUL+ADD , 5 talkie ,0 ,any ,ADD+ADD , 2 -xing4_0 ,0 ,any ,ADD+ADD+ADD , 1 -xing4_0 ,0 ,any ,MUL+ADD , 2 -xing4_0 ,0 ,any ,RMS_NORM+MUL , 9 -xing4_0 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 +xing4_0 ,1 ,any ,ADD+ADD+ADD , 1 +xing4_0 ,1 ,any ,MUL+ADD , 2 +xing4_0 ,1 ,any ,RMS_NORM+MUL , 9 +xing4_0 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 xverse ,0 ,any ,RMS_NORM+MUL , 5 -zaya1 ,0 ,any ,RMS_NORM+MUL , 7 -zonos3 ,0 ,any ,GATED_DELTA_NET+CPY , 1 -zonos3 ,0 ,any ,MUL+ADD , 2 -zonos3 ,0 ,any ,RMS_NORM+MUL , 12 -zonos3 ,0 ,any ,RMS_NORM+SCALE , 2 -zonos3 ,0 ,any ,SSM_CONV+UNARY , 1 +zaya1 ,1 ,any ,RMS_NORM+MUL , 7 +zonos3 ,1 ,any ,GATED_DELTA_NET+CPY , 1 +zonos3 ,1 ,any ,MUL+ADD , 2 +zonos3 ,1 ,any ,RMS_NORM+MUL , 12 +zonos3 ,1 ,any ,RMS_NORM+SCALE , 2 +zonos3 ,1 ,any ,SSM_CONV+UNARY , 1 diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index d0deb9109b68..411258871c69 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -1263,6 +1263,11 @@ struct test_case { return build_graph(ctx); } + static bool is_htp_backend(ggml_backend_t backend) { + ggml_backend_reg_t reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(backend)); + return reg && strcmp(ggml_backend_reg_name(reg), "HTP") == 0; + } + virtual double max_nmse_err() { return 1e-7; } @@ -2176,7 +2181,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_SIGMOID; + op == GGML_UNARY_OP_EXPM1 || op == GGML_UNARY_OP_SOFTPLUS || op == GGML_UNARY_OP_SIGMOID || op == GGML_UNARY_OP_TANH; ggml_tensor * a; if (v & 1) { @@ -2218,8 +2223,8 @@ 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) { + // saturated inputs give zero analytic and numeric gradients, which the grad check cannot compare + if (mode == MODE_GRAD && (op == GGML_UNARY_OP_SIGMOID || op == GGML_UNARY_OP_TANH)) { min = -2.f; max = 2.f; } @@ -2231,16 +2236,19 @@ struct test_unary : public test_case { } float grad_eps() override { + if (op == GGML_UNARY_OP_TANH) { + return 0.15f; + } return op == GGML_UNARY_OP_SIGMOID ? 0.25f : 15.0f; } bool grad_precise() override { - return op == GGML_UNARY_OP_SIGMOID; + return op == GGML_UNARY_OP_SIGMOID || op == GGML_UNARY_OP_TANH; } - // f32 rounding of a large summed loss exceeds the tolerance, so only the small sigmoid case is grad checked + // f32 rounding of a large summed loss exceeds the tolerance, so only the small cases are grad checked int64_t grad_nmax() override { - return op == GGML_UNARY_OP_SIGMOID ? 64 : test_case::grad_nmax(); + return (op == GGML_UNARY_OP_SIGMOID || op == GGML_UNARY_OP_TANH) ? 64 : test_case::grad_nmax(); } std::vector grad_expect() override { @@ -2596,6 +2604,7 @@ struct test_get_rows : public test_case { } } } + }; // GGML_OP_GET_ROWS on a weight also used by GGML_OP_MUL_MAT (tied embeddings) @@ -3624,6 +3633,7 @@ struct test_bin_bcast : public test_case { bool src_overlap; // src0 and src1 are overlapping views of the same buffer const ggml_type type_b; // type of src1, GGML_TYPE_COUNT -> same as src0 bool weights; + const ggml_type type_dst; // GGML_TYPE_COUNT -> op default bool run_whole_graph() override { return nf > 1; } @@ -3635,6 +3645,9 @@ struct test_bin_bcast : public test_case { if (weights) { s += ",weights=1"; } + if (type_dst != GGML_TYPE_COUNT) { + s += "," + VAR_TO_STR(type_dst); + } return s; } @@ -3647,8 +3660,9 @@ struct test_bin_bcast : public test_case { std::array nr = {1, 2, 1, 1}, int nf = 1, bool perm1 = false, bool src_overlap = false, - ggml_type type_b = GGML_TYPE_COUNT, bool weights = false) - : op(op), type(type), ne(ne), nr(nr), nf(nf), perm1(perm1), src_overlap(src_overlap), type_b(type_b), weights(weights) {} + ggml_type type_b = GGML_TYPE_COUNT, bool weights = false, + ggml_type type_dst = GGML_TYPE_COUNT) + : op(op), type(type), ne(ne), nr(nr), nf(nf), perm1(perm1), src_overlap(src_overlap), type_b(type_b), weights(weights), type_dst(type_dst) {} bool use_weight_context() override { return weights; @@ -3684,7 +3698,7 @@ struct test_bin_bcast : public test_case { } // The backward pass supports broadcasting only for GGML_ADD: - const bool grad_supported = op == ggml_add && ggml_are_same_shape(a, b[0]) && nf == 1 && !perm1; + const bool grad_supported = op == ggml_add && type_dst == GGML_TYPE_COUNT && ggml_are_same_shape(a, b[0]) && nf == 1 && !perm1; if (grad_supported) { ggml_set_param(a); ggml_set_param(b[0]); @@ -3699,7 +3713,7 @@ struct test_bin_bcast : public test_case { } for (int i = 0; i < nf; ++i) { - out = op(ctx, out, b[i]); + out = type_dst == GGML_TYPE_COUNT ? op(ctx, out, b[i]) : ggml_add_cast(ctx, out, b[i], type_dst); } ggml_set_name(out, "out"); @@ -4204,10 +4218,11 @@ struct test_rms_norm_mul_add : public test_case { const bool multi_add; // test a sequence of adds feeding into rms_norm const bool post_mul; const bool alias_rms_input; - const bool weight_broadcast; + const int 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 + const bool has_add; std::string op_desc(ggml_tensor * t) override { GGML_UNUSED(t); @@ -4227,17 +4242,20 @@ struct test_rms_norm_mul_add : public test_case { if (swap) { s += "," + VAR_TO_STR(swap); } + if (!has_add) { + s += "," + VAR_TO_STR(has_add); + } return s; } test_rms_norm_mul_add(ggml_type type = GGML_TYPE_F32, 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, bool swap = false) + bool alias_rms_input = false, int weight_broadcast = 0, ggml_type type_w = GGML_TYPE_COUNT, + ggml_type type_add = GGML_TYPE_COUNT, bool swap = false, bool has_add = true) : 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), - swap(swap) {} + swap(swap), has_add(has_add) {} ggml_tensor * build_graph(ggml_context * ctx) override { std::array broadcast_dims = {ne[0]*2, ne[1]*3, ne[2]*3, ne[3]*4}; @@ -4246,7 +4264,7 @@ struct test_rms_norm_mul_add : public test_case { const ggml_type ta = type_add == GGML_TYPE_COUNT ? tw : type_add; ggml_tensor * a = ggml_new_tensor(ctx, type, 4, broadcast ? broadcast_dims.data() : ne.data()); - ggml_tensor * b = weight_broadcast ? ggml_new_tensor_1d(ctx, tw, ne[0]) : ggml_new_tensor(ctx, tw, 4, ne.data()); + ggml_tensor * b = weight_broadcast > 0 ? ggml_new_tensor_2d(ctx, tw, ne[0], weight_broadcast) : ggml_new_tensor(ctx, tw, 4, ne.data()); ggml_tensor * c = ggml_new_tensor(ctx, ta, 4, ne.data()); ggml_tensor * d = nullptr; @@ -4270,7 +4288,7 @@ struct test_rms_norm_mul_add : public test_case { } 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); + ggml_tensor * out = !has_add ? mul : (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); } @@ -4287,7 +4305,10 @@ struct test_rms_norm_mul_add : public test_case { double max_nmse_err() override { // fused ops round to BF16 once, the CPU rounds after each op - return type == GGML_TYPE_BF16 ? 1e-4 : test_case::max_nmse_err(); + if (type == GGML_TYPE_BF16) { + return 1e-4; + } + return test_case::max_nmse_err(); } float grad_eps() override { @@ -4730,9 +4751,384 @@ struct test_add_unary_mul : public test_case { } }; +struct test_unary_scale_fusion : public test_case { + const ggml_unary_op op; + const ggml_type type; + const std::array ne; + const float in_scale; + const float in_bias; + const float out_scale; + const float out_bias; + const std::string mode_str; + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "UNARY_SCALE_FUSION"; + } + + bool run_whole_graph() override { return true; } + + double max_nmse_err(ggml_backend_t backend) override { + if (type == GGML_TYPE_F16 || (mode_str == "lower" && is_htp_backend(backend))) { + return 5e-5; + } + return 1e-6; + } + + std::string vars() override { + std::string op_name = ggml_unary_op_name(op); + return VARS_TO_STR8(op_name, type, ne, in_scale, in_bias, out_scale, out_bias, mode_str); + } + + test_unary_scale_fusion( + ggml_unary_op op, + ggml_type type, + std::array ne, + float in_scale, + float in_bias, + float out_scale, + float out_bias, + std::string mode_str = "pre_post") + : op(op), type(type), ne(ne), + in_scale(in_scale), in_bias(in_bias), + out_scale(out_scale), out_bias(out_bias), + mode_str(std::move(mode_str)) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * a = (mode_str == "lower") + ? ggml_new_tensor_4d(ctx, type, ne[0], 1, 1, 1) + : ggml_new_tensor(ctx, type, 4, ne.data()); + ggml_set_name(a, "a"); + + ggml_tensor * cur = a; + if (mode_str == "lower") { + ggml_tensor * b_shape = ggml_new_tensor(ctx, type, 4, ne.data()); + ggml_set_name(b_shape, "b_shape"); + cur = ggml_repeat(ctx, cur, b_shape); + ggml_set_name(cur, "rep"); + } + if (mode_str == "pre" || mode_str == "pre_post" || mode_str == "lower" || mode_str == "glu_guard") { + cur = (in_bias != 0.0f) ? ggml_scale_bias(ctx, cur, in_scale, in_bias) : ggml_scale(ctx, cur, in_scale); + ggml_set_name(cur, "scale_in"); + } + cur = ggml_unary(ctx, cur, op); + ggml_set_name(cur, "unary"); + if (mode_str == "post" || mode_str == "pre_post" || mode_str == "lower") { + cur = (out_bias != 0.0f) ? ggml_scale_bias(ctx, cur, out_scale, out_bias) : ggml_scale(ctx, cur, out_scale); + ggml_set_name(cur, "scale_out"); + } + if (mode_str == "glu_guard") { + ggml_tensor * b = ggml_new_tensor(ctx, type, 4, ne.data()); + ggml_set_name(b, "b"); + cur = ggml_mul(ctx, cur, b); + } else if (mode_str == "lower") { + ggml_tensor * b = ggml_new_tensor(ctx, type, 4, ne.data()); + ggml_set_name(b, "b"); + cur = ggml_add(ctx, cur, b); + } + ggml_set_name(cur, "out"); + return cur; + } +}; + // SNAKE activation fusion: y = x + sin(a*x)^2 * inv_b // CUDA backend matches the naive 5-op chain (mul, sin, sqr, mul, add) // and dispatches a single fused kernel. +// the situ activation of the Inkling 2 experts on the halves of a merged gate_up, as build_moe_ffn builds it +struct test_situ : public test_case { + const std::array ne; // n_ff, n_expert_used, n_tokens + const float beta; + const float lb; + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "SITU"; + } + + bool run_whole_graph() override { return true; } + + std::string vars() override { + return VARS_TO_STR3(ne, beta, lb); + } + + test_situ(std::array ne = {1152, 8, 1}, float beta = 4.0f, float lb = 25.0f) : ne(ne), beta(beta), lb(lb) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * gu = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, 2*ne[0], ne[1], ne[2]); + ggml_set_name(gu, "gate_up"); + gu = ggml_scale(ctx, gu, 1.0f); + + ggml_tensor * g = ggml_view_3d(ctx, gu, ne[0], ne[1], ne[2], gu->nb[1], gu->nb[2], 0); + ggml_tensor * u = ggml_view_3d(ctx, gu, ne[0], ne[1], ne[2], gu->nb[1], gu->nb[2], ne[0]*gu->nb[0]); + + ggml_tensor * act = ggml_scale(ctx, ggml_tanh(ctx, ggml_scale(ctx, g, 1.0f/beta)), beta); + act = ggml_mul(ctx, act, ggml_sigmoid(ctx, g)); + u = ggml_scale(ctx, ggml_tanh(ctx, ggml_scale(ctx, u, 1.0f/lb)), lb); + ggml_tensor * out = ggml_mul(ctx, act, u); + 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, -40.0f, 40.0f); + } + } +}; + +// the row L2 clip of Inkling 2: [x*w ->] l2_norm(x, t)*t [-> *f with one f per token] +struct test_l2_clip : public test_case { + const std::array ne; + const bool with_w; + const bool with_f; + const float thr; + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "L2_CLIP"; + } + + bool run_whole_graph() override { return true; } + + std::string vars() override { + return VARS_TO_STR4(ne, with_w, with_f, thr); + } + + test_l2_clip(std::array ne = {128, 24, 3, 1}, bool with_w = true, bool with_f = false, float thr = 22.6f) + : ne(ne), with_w(with_w), with_f(with_f), thr(thr) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * a = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne.data()); + ggml_set_name(a, "a"); + ggml_tensor * cur = ggml_scale(ctx, a, 1.0f); + if (with_w) { + ggml_tensor * w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, ne[0], ne[1]); + ggml_set_name(w, "w"); + cur = ggml_mul(ctx, cur, w); + } + cur = ggml_scale(ctx, ggml_l2_norm(ctx, cur, thr), thr); + if (with_f) { + ggml_tensor * f = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 1, 1, ne[2], ne[3]); + ggml_set_name(f, "f"); + cur = ggml_mul(ctx, cur, f); + } + ggml_set_name(cur, "out"); + return cur; + } + + void initialize_tensors(ggml_context * ctx) override { + // rows with norms both below and above the threshold + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + init_tensor_uniform(t, -4.0f, 4.0f); + } + } +}; + +// the causal short conv of Inkling 2 as convolve() builds it: CONCAT(past, cur^T), the state store (a CPY of the last +// columns, or SET_ROWS of the windows of n_slots rollback slots), SSM_CONV, the optional input-dependent taps of H heads, +// the residual ADD and SCALE, and an optional residual add after it +struct test_short_conv : public test_case { + const int64_t C, Ts, S, H, n_slots; + const bool res; + const int64_t K; // the conv width + + std::vector verify; + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "SHORT_CONV"; + } + + bool run_whole_graph() override { return true; } + std::vector fusion_test_nodes() override { return verify; } + + std::string vars() override { + return VARS_TO_STR7(C, Ts, S, H, n_slots, res, K); + } + + test_short_conv(int64_t C = 1024, int64_t Ts = 1, int64_t S = 1, int64_t H = 0, int64_t n_slots = 0, bool res = false, int64_t K = 4) + : C(C), Ts(Ts), S(S), H(H), n_slots(n_slots), res(res), K(K) {} + + // the inputs only: the rollback windows are an overlapping view + 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->op == GGML_OP_NONE && t->view_src == NULL) { + init_tensor_uniform(t); + } + } + } + + ggml_tensor * build_graph(ggml_context * ctx) override { + verify.clear(); + const int64_t K1 = K - 1; + const int64_t T = Ts*S; + + ggml_tensor * hist = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, K1, C + 64, S); + ggml_tensor * past = ggml_view_3d(ctx, hist, K1, C, S, hist->nb[1], hist->nb[2], 32*hist->nb[1]); + ggml_tensor * cur = ggml_scale(ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, C, T), 0.5f); + ggml_tensor * w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, K, C); + ggml_set_name(hist, "hist"); + + ggml_tensor * dyn = nullptr; + if (H) { + dyn = ggml_scale(ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, K*H, T), 1.0f); + if (gf) { + ggml_build_forward_expand(gf, dyn); + } + } + + const int64_t n_planes = std::max(1, n_slots); + ggml_tensor * state = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, K1*(C + 64), S*n_planes); + ggml_set_name(state, "state"); + const size_t row_size = state->nb[1]; + + ggml_tensor * x = ggml_concat(ctx, past, ggml_transpose(ctx, ggml_reshape_3d(ctx, cur, C, Ts, S)), 0); + + ggml_tensor * st; + if (n_slots == 0) { + ggml_tensor * tail = ggml_view_3d(ctx, x, K1, C, S, x->nb[1], x->nb[2], Ts*sizeof(float)); + ggml_tensor * cell = ggml_view_2d(ctx, state, K1*C, S, row_size, 32*K1*sizeof(float)); + st = ggml_cpy(ctx, tail, cell); + } else { + const int64_t kw = std::min(Ts, n_slots); + ggml_tensor * order = ggml_arange(ctx, 0.0f, (float) n_slots, 1.0f); + order = ggml_cast(ctx, ggml_scale_bias(ctx, order, -1.0f, (float) (n_slots - 1)), GGML_TYPE_I32); + order = ggml_view_1d(ctx, order, kw, (n_slots - kw)*sizeof(int32_t)); + ggml_tensor * windows = ggml_view_4d(ctx, x, K1, kw, C, S, sizeof(float), x->nb[1], x->nb[2], (Ts - (kw - 1))*sizeof(float)); + ggml_tensor * slots = ggml_view_4d(ctx, state, K1, n_slots, C, S, S*row_size, K1*sizeof(float), row_size, 32*K1*sizeof(float)); + st = ggml_set_rows(ctx, slots, windows, order); + } + if (gf) { + ggml_build_forward_expand(gf, st); + } + verify.push_back(st); + + ggml_tensor * out = ggml_reshape_2d(ctx, ggml_ssm_conv(ctx, x, w), C, T); + if (dyn) { + ggml_tensor * d3 = ggml_reshape_3d(ctx, dyn, K, H, T); + for (int64_t lag = 0; lag < K; ++lag) { + ggml_tensor * tap = ggml_view_3d(ctx, d3, 1, H, T, d3->nb[1], d3->nb[2], lag*d3->nb[0]); + ggml_tensor * window = ggml_view_3d(ctx, x, Ts, C, S, x->nb[1], x->nb[2], (K1 - lag)*x->nb[0]); + window = ggml_reshape_3d(ctx, ggml_cont(ctx, ggml_transpose(ctx, window)), C/H, H, T); + out = ggml_add(ctx, out, ggml_reshape_2d(ctx, ggml_mul(ctx, window, tap), C, T)); + } + } + out = ggml_scale(ctx, ggml_add(ctx, cur, out), 1.0f/sqrtf((float) ((H ? 2 : 1)*K + 1))); + if (res) { + out = ggml_add(ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, C, T), out); + } + ggml_set_name(out, "out"); + verify.push_back(out); + return out; + } +}; + +// the depth mix of Inkling 2 as mix() builds it: states = [stack; rms_norm(cur)], softmax of the scores against Q queries, +// the weighted sum as [Q, n, T]; shared_norm: the norm of cur also has another use, so it is computed before the mix +struct test_depth_mix : public test_case { + const int64_t n, B, Q, T; + const bool shared_norm; + + std::vector verify; + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "DEPTH_MIX"; + } + + bool run_whole_graph() override { return true; } + std::vector fusion_test_nodes() override { return verify; } + + std::string vars() override { + return VARS_TO_STR5(n, B, Q, T, shared_norm); + } + + test_depth_mix(int64_t n = 2304, int64_t B = 8, int64_t Q = 1, int64_t T = 1, bool shared_norm = false) + : n(n), B(B), Q(Q), T(T), shared_norm(shared_norm) {} + + double max_nmse_err() override { + return 5e-4; + } + + ggml_tensor * build_graph(ggml_context * ctx) override { + verify.clear(); + ggml_tensor * stack = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n, B, T); + ggml_tensor * cur = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n, T); + ggml_tensor * query = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n, Q); + ggml_set_name(stack, "stack"); + ggml_set_name(cur, "cur"); + + ggml_tensor * norm = ggml_rms_norm(ctx, ggml_reshape_3d(ctx, cur, n, 1, T), 1e-6f); + if (shared_norm) { + ggml_tensor * other = ggml_scale(ctx, norm, 2.0f); + if (gf) { + ggml_build_forward_expand(gf, other); + } + verify.push_back(other); + } + + ggml_tensor * states = ggml_concat(ctx, stack, norm, 1); + ggml_tensor * queries = T == 1 ? query : ggml_repeat(ctx, query, ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n, Q, T)); + ggml_tensor * scores = ggml_soft_max_ext(ctx, ggml_mul_mat(ctx, states, queries), nullptr, 1.0f/sqrtf((float) n), 0.0f); + ggml_tensor * out = ggml_mul_mat(ctx, scores, ggml_cont(ctx, ggml_transpose(ctx, states))); + ggml_set_name(out, "out"); + verify.push_back(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, -3.0f, 3.0f); + } + } +}; + +// the loop controller of Inkling 2 as control() builds it: one rms_norm of [cur; msg], the rank r down projection, the gain +// and forget projections and (cur - tanh(forget)*cur) + tanh(gain)*msg +struct test_loop_ctrl : public test_case { + const int64_t n, r, T; + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "LOOP_CTRL"; + } + + bool run_whole_graph() override { return true; } + + std::string vars() override { + return VARS_TO_STR3(n, r, T); + } + + test_loop_ctrl(int64_t n = 2304, int64_t r = 64, int64_t T = 1) : n(n), r(r), T(T) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * cur = ggml_scale(ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n, T), 1.0f); + ggml_tensor * msg = ggml_scale(ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n, T), 1.0f); + ggml_tensor * wd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 2*n, r); + ggml_tensor * wg = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, r, n); + ggml_tensor * wf = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, r, n); + ggml_set_name(cur, "cur"); + ggml_set_name(msg, "msg"); + + ggml_tensor * gate = ggml_concat(ctx, ggml_reshape_3d(ctx, cur, n, 1, T), ggml_reshape_3d(ctx, msg, n, 1, T), 1); + gate = ggml_reshape_2d(ctx, ggml_rms_norm(ctx, gate, 1e-6f), 2*n, T); + gate = ggml_mul_mat(ctx, wd, gate); + + ggml_tensor * gain = ggml_tanh(ctx, ggml_mul_mat(ctx, wg, gate)); + ggml_tensor * forget = ggml_tanh(ctx, ggml_mul_mat(ctx, wf, gate)); + + ggml_tensor * out = ggml_add(ctx, ggml_sub(ctx, cur, ggml_mul(ctx, forget, cur)), ggml_mul(ctx, gain, msg)); + 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, -0.5f, 0.5f); + } + } +}; + struct test_snake_fuse : public test_case { const ggml_type type; const std::array ne; // [T, C, D2, D3] @@ -4981,24 +5377,120 @@ struct test_dsv4_hc_post : public test_dsv4_hc { } }; +struct test_dsv4_hc_chain : public test_case { + const ggml_type wtype; + const int64_t n_embd; + const int64_t n_tokens; + const bool gated_pre; + const bool identity_post; + + test_dsv4_hc_chain(ggml_type wtype = GGML_TYPE_Q4_0, int64_t n_embd = 96, int64_t n_tokens = 1, + bool gated_pre = true, bool identity_post = true) + : wtype(wtype), n_embd(n_embd), n_tokens(n_tokens), gated_pre(gated_pre), identity_post(identity_post) {} + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "DSV4_HC_POST"; + } + + std::string vars() override { + return VARS_TO_STR5(wtype, n_embd, n_tokens, gated_pre, identity_post); + } + + bool run_whole_graph() override { return true; } + + double max_nmse_err(ggml_backend_t backend) override { + return is_htp_backend(backend) ? 5e-3 : 5e-4; + } + + ggml_tensor * build_graph(ggml_context * ctx) override { + constexpr int64_t n_hc = 4; + constexpr int64_t n_vocab = 64; + + ggml_tensor * tok_embd = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab); + ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_tokens); + ggml_tensor * embd = ggml_get_rows(ctx, tok_embd, inp_tokens); + ggml_tensor * res_hc = ggml_repeat_4d(ctx, ggml_reshape_3d(ctx, embd, n_embd, 1, n_tokens), n_embd, n_hc, n_tokens, 1); + + for (int l = 0; l < 2; ++l) { + ggml_tensor * w_norm = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_hc); + ggml_tensor * xn = ggml_mul(ctx, ggml_rms_norm(ctx, res_hc, 1e-5f), w_norm); + ggml_tensor * xn_2d = ggml_reshape_2d(ctx, xn, n_hc * n_embd, n_tokens); + + ggml_tensor * mixed = nullptr; + if (gated_pre) { + ggml_tensor * w_gate = ggml_new_tensor_2d(ctx, wtype, n_hc * n_embd, n_hc * n_embd); + ggml_tensor * gate = ggml_mul_mat(ctx, w_gate, xn_2d); + mixed = ggml_dsv4_hc_pre_gated(ctx, xn, ggml_reshape_3d(ctx, gate, n_embd, n_hc, n_tokens), 1.0f / (float) n_hc); + } else { + ggml_tensor * w_pre = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_hc * n_embd, n_hc); + ggml_tensor * pre_w = ggml_sigmoid(ctx, ggml_mul_mat(ctx, w_pre, xn_2d)); + mixed = ggml_dsv4_hc_pre(ctx, xn, pre_w); + } + + ggml_tensor * w_blk = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd); + ggml_tensor * blk_out = ggml_mul_mat(ctx, w_blk, mixed); + + ggml_tensor * w_post = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_hc * n_embd, n_hc); + ggml_tensor * post_w = ggml_scale(ctx, ggml_sigmoid(ctx, ggml_scale(ctx, ggml_mul_mat(ctx, w_post, xn_2d), 1.0f / (float) n_hc)), 2.0f); + + ggml_tensor * comb_w = nullptr; + if (!identity_post) { + ggml_tensor * w_comb = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_hc * n_embd, n_hc * n_hc); + comb_w = ggml_reshape_3d(ctx, ggml_soft_max(ctx, ggml_mul_mat(ctx, w_comb, xn_2d)), n_hc, n_hc, n_tokens); + } + + res_hc = ggml_dsv4_hc_post(ctx, blk_out, res_hc, post_w, comb_w); + } + + ggml_set_name(res_hc, "out"); + return res_hc; + } + + void initialize_tensors(ggml_context * ctx) override { + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) { + if (t->op != GGML_OP_NONE) { + continue; + } + if (t->type == GGML_TYPE_I32) { + std::vector data(ggml_nelements(t)); + for (size_t i = 0; i < data.size(); ++i) { + data[i] = (int32_t) (i % 64); + } + ggml_backend_tensor_set(t, data.data(), 0, data.size() * sizeof(int32_t)); + } else { + init_tensor_uniform(t, -0.1f, 0.1f); + } + } + } +}; + // GGML_OP_SSM_CONV struct test_ssm_conv : public test_case { const ggml_type type; const std::array ne_a; const std::array ne_b; + const bool non_cont; std::string vars() override { - return VARS_TO_STR3(type, ne_a, ne_b); + return VARS_TO_STR4(type, ne_a, ne_b, non_cont); } test_ssm_conv(ggml_type type = GGML_TYPE_F32, std::array ne_a = {10, 10, 10, 1}, - std::array ne_b = {3, 3, 1, 1}) - : type(type), ne_a(ne_a), ne_b(ne_b) {} + std::array ne_b = {3, 3, 1, 1}, + bool non_cont = false) + : type(type), ne_a(ne_a), ne_b(ne_b), non_cont(non_cont) {} ggml_tensor * build_graph(ggml_context * ctx) override { - ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne_a.data()); + ggml_tensor * a; + if (non_cont) { + ggml_tensor * a_full = ggml_new_tensor_4d(ctx, type, ne_a[0], ne_a[1], 2 * ne_a[2], ne_a[3]); + a = ggml_view_3d(ctx, a_full, ne_a[0], ne_a[1], ne_a[2], a_full->nb[1], 2 * a_full->nb[2], a_full->nb[2]); + } else { + a = ggml_new_tensor(ctx, type, 4, ne_a.data()); + } ggml_tensor * b = ggml_new_tensor(ctx, type, 4, ne_b.data()); ggml_tensor * out = ggml_ssm_conv(ctx, a, b); return out; @@ -5011,6 +5503,7 @@ struct test_ssm_conv_bias_silu : public test_case { const std::array ne_a; const std::array ne_b; const bool fuse_bias; + const bool non_cont; std::string op_desc(ggml_tensor * t) override { GGML_UNUSED(t); @@ -5020,15 +5513,22 @@ struct test_ssm_conv_bias_silu : public test_case { bool run_whole_graph() override { return true; } std::string vars() override { - return VARS_TO_STR4(type, ne_a, ne_b, fuse_bias); + return VARS_TO_STR5(type, ne_a, ne_b, fuse_bias, non_cont); } test_ssm_conv_bias_silu(ggml_type type, std::array ne_a, std::array ne_b, - bool fuse_bias) - : type(type), ne_a(ne_a), ne_b(ne_b), fuse_bias(fuse_bias) {} + bool fuse_bias, bool non_cont = false) + : type(type), ne_a(ne_a), ne_b(ne_b), fuse_bias(fuse_bias), non_cont(non_cont) {} ggml_tensor * build_graph(ggml_context * ctx) override { - ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne_a.data()); + ggml_tensor * a; + if (non_cont) { + ggml_tensor * a_full = ggml_new_tensor_4d(ctx, type, ne_a[0], ne_a[1], 2 * ne_a[2], ne_a[3]); + ggml_set_name(a_full, "a_full"); + a = ggml_view_3d(ctx, a_full, ne_a[0], ne_a[1], ne_a[2], a_full->nb[1], 2 * a_full->nb[2], a_full->nb[2]); + } else { + a = ggml_new_tensor(ctx, type, 4, ne_a.data()); + } ggml_tensor * b = ggml_new_tensor(ctx, type, 4, ne_b.data()); ggml_set_name(a, "a"); ggml_set_name(b, "b"); @@ -5048,6 +5548,103 @@ struct test_ssm_conv_bias_silu : public test_case { } }; +// GGML_OP_CONCAT(conv_state, transpose(x), 0) + optional GGML_OP_CPY(state_out) + GGML_OP_SSM_CONV + optional GGML_OP_UNARY(SILU) +struct test_ssm_conv_concat_fusion : public test_case { + const ggml_type type; + const int64_t d_conv; + const int64_t d_inner; + const int64_t n_t; + const int64_t n_s; + const bool use_silu; + const bool has_state_cpy; + + ggml_tensor * conv_out_node = nullptr; + ggml_tensor * state_out_node = nullptr; + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "SSM_CONV_CONCAT_FUSION"; + } + + bool run_whole_graph() override { return true; } + + std::string vars() override { + return VARS_TO_STR7(type, d_conv, d_inner, n_t, n_s, use_silu, has_state_cpy); + } + + test_ssm_conv_concat_fusion(ggml_type type, int64_t d_conv, int64_t d_inner, int64_t n_t, int64_t n_s, + bool use_silu, bool has_state_cpy) + : type(type), d_conv(d_conv), d_inner(d_inner), n_t(n_t), n_s(n_s), + use_silu(use_silu), has_state_cpy(has_state_cpy) {} + + double max_nmse_err(ggml_backend_t backend) override { + return is_htp_backend(backend) ? 1e-4 : test_case::max_nmse_err(backend); + } + + std::vector fusion_test_nodes() override { + if (has_state_cpy && state_out_node) { + return { conv_out_node, state_out_node }; + } + return { conv_out_node }; + } + + ggml_tensor * build_graph(ggml_context * ctx) override { + const int64_t s_cols = d_conv - 1; + + ggml_tensor * state = ggml_new_tensor_3d(ctx, type, s_cols, d_inner, n_s); + ggml_set_name(state, "state"); + + ggml_tensor * x_raw = ggml_new_tensor_3d(ctx, type, d_inner, n_t, n_s); + ggml_set_name(x_raw, "x_raw"); + + // Feed rms_norm output into concat/ssm_conv so internal activations can be lowered while state stays F32 + ggml_tensor * x = ggml_rms_norm(ctx, x_raw, 1e-5f); + ggml_set_name(x, "x"); + + ggml_tensor * weight = ggml_new_tensor_2d(ctx, type, d_conv, d_inner); + ggml_set_name(weight, "weight"); + + ggml_tensor * conv_x = ggml_concat(ctx, state, ggml_transpose(ctx, x), 0); + ggml_set_name(conv_x, "conv_x"); + + if (has_state_cpy) { + const int64_t mem_size = n_s + 2; + const int64_t kv_head = 1; + + ggml_tensor * last = ggml_view_3d(ctx, conv_x, + s_cols, d_inner, n_s, + conv_x->nb[1], conv_x->nb[2], + ggml_row_size(conv_x->type, n_t)); + ggml_set_name(last, "conv_x_tail"); + + ggml_tensor * cache = ggml_new_tensor_2d(ctx, type, s_cols * d_inner, mem_size); + ggml_set_name(cache, "cache"); + + ggml_tensor * cell = ggml_view_2d(ctx, cache, + s_cols * d_inner, n_s, + cache->nb[1], kv_head * cache->nb[1]); + ggml_set_name(cell, "cell"); + + state_out_node = ggml_cpy(ctx, last, cell); + ggml_set_name(state_out_node, "state_cpy"); + ggml_build_forward_expand(gf, state_out_node); + } + + ggml_tensor * out = ggml_ssm_conv(ctx, conv_x, weight); + ggml_set_name(out, "conv_raw"); + + if (use_silu) { + out = ggml_silu(ctx, out); + ggml_set_name(out, "conv_silu"); + } + + // Consume conv output via rms_norm so conv output is an internal activation + conv_out_node = ggml_rms_norm(ctx, out, 1e-5f); + ggml_set_name(conv_out_node, "out"); + return conv_out_node; + } +}; + // GGML_OP_SSM_SCAN struct test_ssm_scan : public test_case { const ggml_type type; @@ -5399,6 +5996,13 @@ struct test_gated_delta_net : public test_case { return s; } + double max_nmse_err(ggml_backend_t backend) override { + if (is_htp_backend(backend) && !kda && (head_size == 64 || head_size == 128) && n_seq_tokens >= 8) { + return 5e-3; + } + return test_case::max_nmse_err(backend); + } + 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, bool correlated = false, bool padded_v = false, bool padded_q = false, bool permuted_k = false, float g_min = -20.0f) @@ -5411,21 +6015,27 @@ struct test_gated_delta_net : public test_case { ggml_tensor * v; if (permuted) { // create with dims 1 and 2 swapped, then permute back to get non-contiguous layout - q = ggml_permute(ctx, ggml_new_tensor_4d(ctx, type, head_size, n_seq_tokens, head_count, n_seqs), 0, 2, 1, 3); - k = ggml_permute(ctx, ggml_new_tensor_4d(ctx, type, head_size, n_seq_tokens, head_count, n_seqs), 0, 2, 1, 3); - v = ggml_permute(ctx, ggml_new_tensor_4d(ctx, type, head_size + padded_v, n_seq_tokens, head_count * v_repeat, n_seqs), 0, 2, 1, 3); + q = ggml_new_tensor_4d(ctx, type, head_size, n_seq_tokens, head_count, n_seqs); + k = ggml_new_tensor_4d(ctx, type, head_size, n_seq_tokens, head_count, n_seqs); + v = ggml_new_tensor_4d(ctx, type, head_size + padded_v, n_seq_tokens, head_count * v_repeat, n_seqs); + ggml_set_name(q, "q"); + ggml_set_name(k, "k"); + ggml_set_name(v, "v"); + q = ggml_permute(ctx, q, 0, 2, 1, 3); + k = ggml_permute(ctx, k, 0, 2, 1, 3); + v = ggml_permute(ctx, v, 0, 2, 1, 3); } else { q = ggml_new_tensor_4d(ctx, type, head_size, head_count, n_seq_tokens, n_seqs); k = ggml_new_tensor_4d(ctx, type, head_size, head_count, n_seq_tokens, n_seqs); v = ggml_new_tensor_4d(ctx, type, head_size + padded_v, head_count * v_repeat, n_seq_tokens, n_seqs); + ggml_set_name(q, "q"); + ggml_set_name(k, "k"); + ggml_set_name(v, "v"); } if (padded_v) { - ggml_set_name(v, "v"); v = ggml_view_4d(ctx, v, head_size, head_count * v_repeat, n_seq_tokens, n_seqs, v->nb[1], v->nb[2], v->nb[3], 0); } - ggml_set_name(q, "q"); - ggml_set_name(k, "k"); - ggml_set_name(v, "v"); + const int64_t g_ne0 = kda ? head_size : 1; ggml_tensor * g = ggml_new_tensor_4d(ctx, type, g_ne0, head_count * v_repeat, n_seq_tokens, n_seqs); ggml_tensor * beta = ggml_new_tensor_4d(ctx, type, 1, head_count * v_repeat, n_seq_tokens, n_seqs); @@ -5490,6 +6100,13 @@ struct test_gated_delta_net_replay : public test_case { return VARS_TO_STR8(head_count, head_size, n_seq_tokens, n_seqs, v_repeat, kda, n_pend, keep); } + double max_nmse_err(ggml_backend_t backend) override { + if (is_htp_backend(backend) && !kda && (head_size == 64 || head_size == 128) && n_seq_tokens >= 8) { + return 5e-3; + } + return test_case::max_nmse_err(backend); + } + 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), @@ -5595,16 +6212,35 @@ 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 bool kda; + const int64_t n_slots; // >0: use GET_ROWS(state_cache, s_copy) with non-zero slot index - ggml_tensor * cpy_node = nullptr; + ggml_tensor * cpy_node = nullptr; + ggml_tensor * attn_out_node = nullptr; std::string vars() override { - return VARS_TO_STR5(type, head_count, head_size, n_seq_tokens, n_seqs); + std::string s = VARS_TO_STR5(type, head_count, head_size, n_seq_tokens, n_seqs); + if (kda) { + s += "," + VAR_TO_STR(kda); + } + if (n_slots > 0) { + s += "," + VAR_TO_STR(n_slots); + } + return s; + } + + double max_nmse_err(ggml_backend_t backend) override { + if (is_htp_backend(backend) && !kda && (head_size == 64 || head_size == 128) && n_seq_tokens >= 64) { + return 2e-2; + } + return is_htp_backend(backend) ? 1e-4 : test_case::max_nmse_err(backend); } 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) - : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs) {} + int64_t head_count = 4, int64_t head_size = 32, int64_t n_seq_tokens = 2, int64_t n_seqs = 1, + bool kda = false, int64_t n_slots = 0) + : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), + kda(kda), n_slots(n_slots) {} ggml_tensor * build_graph(ggml_context * ctx) override { const int64_t S_v = head_size; @@ -5612,17 +6248,31 @@ struct test_gated_delta_net_cache_fusion : public test_case { const int64_t H_k = head_count; const int64_t D = S_v * S_v * H_v; - 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); - ggml_tensor * v = ggml_new_tensor_4d(ctx, type, head_size, H_v, n_seq_tokens, n_seqs); + 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); + ggml_tensor * v = ggml_new_tensor_4d(ctx, type, head_size, H_v, n_seq_tokens, n_seqs); ggml_set_name(q, "q"); ggml_set_name(k, "k"); ggml_set_name(v, "v"); - ggml_tensor * g = ggml_new_tensor_4d(ctx, type, 1, H_v, n_seq_tokens, n_seqs); + + const int64_t g_ne0 = kda ? head_size : 1; + ggml_tensor * g = ggml_new_tensor_4d(ctx, type, g_ne0, H_v, n_seq_tokens, n_seqs); ggml_tensor * beta = ggml_new_tensor_4d(ctx, type, 1, H_v, n_seq_tokens, n_seqs); - ggml_tensor * state = ggml_new_tensor_4d(ctx, type, head_size, head_size, H_v, n_seqs); ggml_set_name(g, "g"); ggml_set_name(beta, "beta"); + + ggml_tensor * state = nullptr; + if (n_slots > 0) { + ggml_tensor * state_cache = ggml_new_tensor_2d(ctx, type, D, n_slots); + ggml_tensor * s_copy = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_seqs); + ggml_set_name(state_cache, "state_cache"); + ggml_set_name(s_copy, "s_copy"); + ggml_tensor * states_all = ggml_get_rows(ctx, state_cache, s_copy); + ggml_tensor * states_view = ggml_view_2d(ctx, states_all, D, n_seqs, states_all->nb[1], 0); + state = ggml_reshape_4d(ctx, states_view, head_size, head_size, H_v, n_seqs); + } else { + state = ggml_new_tensor_4d(ctx, type, head_size, head_size, H_v, n_seqs); + } ggml_set_name(state, "state"); q = ggml_l2_norm(ctx, q, 1e-6f); @@ -5657,9 +6307,13 @@ struct test_gated_delta_net_cache_fusion : public test_case { ggml_set_name(cpy, "gdn_cache_cpy"); cpy_node = cpy; - // read the cpy output (not the plain dst view, which would not pull the cpy into the graph) - // so that neither the gdn nor the cpy is the graph output - ggml_tensor * out = ggml_sum(ctx, cpy); + ggml_tensor * attn_out = ggml_dup(ctx, attn); + ggml_set_name(attn_out, "attn_out"); + ggml_set_output(attn_out); + attn_out_node = attn_out; + + // read both cpy and attn_out so that cpy immediately follows gdn_out and attn view is live + ggml_tensor * out = ggml_add(ctx, ggml_sum(ctx, cpy), ggml_sum(ctx, attn_out)); return out; } @@ -5669,7 +6323,7 @@ struct test_gated_delta_net_cache_fusion : public test_case { } bool run_whole_graph() override { return true; } - std::vector fusion_test_nodes() override { return { cpy_node }; } + std::vector fusion_test_nodes() override { return { cpy_node, attn_out_node }; } uint64_t op_flops(ggml_tensor * t) override { GGML_UNUSED(t); @@ -5683,7 +6337,13 @@ struct test_gated_delta_net_cache_fusion : public test_case { void initialize_tensors(ggml_context * ctx) override { 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) { + if (strcmp(t->name, "s_copy") == 0) { + std::vector ids(n_seqs); + for (int64_t i = 0; i < n_seqs; ++i) { + ids[i] = (int32_t) ((2 + i) % n_slots); + } + ggml_backend_tensor_set(t, ids.data(), 0, ids.size() * sizeof(int32_t)); + } else 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); @@ -8034,6 +8694,121 @@ struct test_top_k_inf : public test_top_k { } }; +// MoE router pattern: MUL_MAT[prec=F32] -> SOFT_MAX -> ARGSORT -> VIEW +struct test_moe_router_prec_f32 : public test_case { + const int64_t k_dim; + const int64_t n_exp; + const int64_t n_tok; + const int64_t top_k; + + test_moe_router_prec_f32(int64_t k_dim = 128, int64_t n_exp = 64, int64_t n_tok = 4, int64_t top_k = 8) + : k_dim(k_dim), n_exp(n_exp), n_tok(n_tok), top_k(top_k) {} + + std::string vars() override { + return VARS_TO_STR4(k_dim, n_exp, n_tok, top_k); + } + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "ARGSORT"; + } + + bool run_whole_graph() override { return true; } + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, k_dim, n_exp); + ggml_tensor * x = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, k_dim, n_tok); + ggml_set_name(w, "gate_inp_w"); + ggml_set_name(x, "ffn_norm"); + + ggml_tensor * logits = ggml_mul_mat(ctx, w, x); + ggml_prec_set_acc(logits, GGML_PREC_F32); + ggml_set_name(logits, "router_logits"); + + ggml_tensor * probs = ggml_soft_max(ctx, logits); + ggml_set_name(probs, "router_probs"); + + ggml_tensor * sorted = ggml_argsort(ctx, probs, GGML_SORT_ORDER_DESC); + ggml_set_name(sorted, "router_sorted"); + + ggml_tensor * top = ggml_view_2d(ctx, sorted, top_k, n_tok, sorted->nb[1], 0); + ggml_tensor * out = ggml_cont(ctx, top); + 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)) { + if (strcmp(t->name, "gate_inp_w") == 0) { + std::vector data(k_dim * n_exp, 0.0f); + for (int64_t r = 0; r < n_exp; ++r) { + data[r * k_dim + (r % k_dim)] = 1.0f + 0.03125f * (float) (r + 1); + } + ggml_backend_tensor_set(t, data.data(), 0, data.size() * sizeof(float)); + } else if (strcmp(t->name, "ffn_norm") == 0) { + std::vector data(k_dim * n_tok); + for (int64_t tok = 0; tok < n_tok; ++tok) { + for (int64_t c = 0; c < k_dim; ++c) { + data[tok * k_dim + c] = 1.0f + 0.015625f * (float) ((c + tok * 7) % k_dim); + } + } + ggml_backend_tensor_set(t, data.data(), 0, data.size() * sizeof(float)); + } else if (t->type == GGML_TYPE_I32) { + std::vector data(ggml_nelements(t), 0); + ggml_backend_tensor_set(t, data.data(), 0, ggml_nbytes(t)); + } else if (t->type == GGML_TYPE_F32) { + init_tensor_uniform(t); + } + } + } +}; + +// Two-block pre-norm FFN residual chain: rms_norm -> mul -> mul_mat -> silu -> mul_mat -> add +struct test_ffn_residual_fusion : public test_case { + const ggml_type wtype; + const int64_t n_embd; + const int64_t n_ff; + const int64_t n_tok; + + test_ffn_residual_fusion(ggml_type wtype = GGML_TYPE_Q4_0, int64_t n_embd = 128, int64_t n_ff = 256, int64_t n_tok = 4) + : wtype(wtype), n_embd(n_embd), n_ff(n_ff), n_tok(n_tok) {} + + std::string vars() override { + return VARS_TO_STR4(wtype, n_embd, n_ff, n_tok); + } + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "MUL_MAT_FUSION"; + } + + bool run_whole_graph() override { return true; } + + double max_nmse_err(ggml_backend_t backend) override { + return is_htp_backend(backend) ? 5e-3 : 5e-4; + } + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * inpL = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_tok); + ggml_tensor * nw0 = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); + ggml_tensor * wu0 = ggml_new_tensor_2d(ctx, wtype, n_embd, n_ff); + ggml_tensor * wd0 = ggml_new_tensor_2d(ctx, wtype, n_ff, n_embd); + ggml_tensor * nw1 = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); + ggml_tensor * wu1 = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd); + + ggml_tensor * cur0 = ggml_mul(ctx, ggml_rms_norm(ctx, inpL, 1e-5f), nw0); + cur0 = ggml_silu(ctx, ggml_mul_mat(ctx, wu0, cur0)); + cur0 = ggml_mul_mat(ctx, wd0, cur0); + ggml_tensor * res0 = ggml_add(ctx, cur0, inpL); + + ggml_tensor * cur1 = ggml_mul(ctx, ggml_rms_norm(ctx, res0, 1e-5f), nw1); + cur1 = ggml_mul_mat(ctx, wu1, cur1); + ggml_tensor * out = ggml_add(ctx, cur1, res0); + ggml_set_name(out, "out"); + return out; + } +}; + // qwen4exp QSA indexer top-k fusion: expand per-block scores to cells, add the f16 mask, top-k. struct test_topk_qsa : public test_case { const int64_t n_blocks; @@ -8532,19 +9307,25 @@ struct test_mul_mat_fusion : public test_case { const bool with_lane_scale; std::array batch_dims; const bool skip; // set some ids to a negative value (only for use_id) + const ggml_type type_b; // type of the input test_mul_mat_fusion(ggml_type type, ggml_glu_op op, int64_t m, int64_t n, int64_t k, bool use_id = false, int n_mats = 1, int n_used = 1, bool b = false, bool with_bias = false, bool with_gate = true, - bool with_lane_scale = false, std::array batch_dims = {4, 2}, bool skip = false) + bool with_lane_scale = false, std::array batch_dims = {4, 2}, bool skip = false, + ggml_type type_b = GGML_TYPE_F32) : type(type), glu_op(op), m(m), n(n), k(k), use_id(use_id), n_mats(n_mats), n_used(n_used), b(b), with_bias(with_bias), - with_gate(with_gate), with_lane_scale(with_lane_scale), batch_dims(batch_dims), skip(skip) { + with_gate(with_gate), with_lane_scale(with_lane_scale), batch_dims(batch_dims), skip(skip), type_b(type_b) { if (use_id) { GGML_ASSERT(n_used <= n_mats); } } std::string vars() override { - return VARS_TO_STR14(type, glu_op, m, n, k, use_id, n_mats, n_used, b, with_bias, with_gate, with_lane_scale, batch_dims, skip); + std::string s = VARS_TO_STR14(type, glu_op, m, n, k, use_id, n_mats, n_used, b, with_bias, with_gate, with_lane_scale, batch_dims, skip); + if (type_b != GGML_TYPE_F32) { + s += "," + VAR_TO_STR(type_b); + } + return s; } std::string op_desc(ggml_tensor * t) override { @@ -8598,7 +9379,7 @@ struct test_mul_mat_fusion : public test_case { std::array ne = { k, m, channels, samples }; std::array ne0 = { k, n, channels, samples }; - ggml_tensor * cur = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne.data()); + ggml_tensor * cur = ggml_new_tensor(ctx, type_b, 4, ne.data()); ggml_tensor * gate = with_gate ? ggml_new_tensor(ctx, type, 4, ne0.data()) : nullptr; ggml_tensor * up = ggml_new_tensor(ctx, type, 4, ne0.data()); @@ -8648,7 +9429,7 @@ struct test_mul_mat_fusion : public test_case { ids = ggml_view_2d(ctx, ids, n_used, m, ids->nb[1], 0); } - ggml_tensor * cur = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, k, this->b ? 1 : n_used, m); + ggml_tensor * cur = ggml_new_tensor_3d(ctx, type_b, k, this->b ? 1 : n_used, m); ggml_set_name(cur, "cur"); auto build_lane_up = [&]() { @@ -11168,10 +11949,19 @@ static std::vector> make_test_cases_eval() { } test_cases.emplace_back(new test_unary((ggml_unary_op) op, type, { 128, 2, 2, 2 }, v)); test_cases.emplace_back(new test_unary((ggml_unary_op) op, type, { 5, 7, 11, 13 }, v)); + if (type == GGML_TYPE_F16) { + test_cases.emplace_back(new test_unary((ggml_unary_op) op, type, { 33, 2, 2, 2 }, v)); + test_cases.emplace_back(new test_unary((ggml_unary_op) op, type, { 65, 2, 2, 2 }, v)); + test_cases.emplace_back(new test_unary((ggml_unary_op) op, type, { 127, 2, 2, 2 }, v)); + if (v == 0) { + test_cases.emplace_back(new test_unary((ggml_unary_op) op, type, { 65536, 2, 1, 1 }, v)); + } + } } } } test_cases.emplace_back(new test_unary(GGML_UNARY_OP_SIGMOID, GGML_TYPE_F32, { 16, 4, 1, 1 })); + test_cases.emplace_back(new test_unary(GGML_UNARY_OP_TANH, GGML_TYPE_F32, { 16, 4, 1, 1 })); // fused relu + sqr (squared ReLU) for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32}) { @@ -11219,6 +12009,25 @@ static std::vector> make_test_cases_eval() { // a unary op with no fused kernel must fall back to the three-op chain test_cases.emplace_back(new test_add_unary_mul(GGML_UNARY_OP_GELU, GGML_TYPE_F32, { 32, 7, 1, 1 })); + // fused [SCALE ->] UNARY [-> SCALE] chains + for (ggml_type type : { GGML_TYPE_F32, GGML_TYPE_F16 }) { + test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_EXP, type, { 256, 16, 1, 1 }, -0.5f, 0.0f, 2.0f, 0.0f, "pre_post")); + test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_SIGMOID, type, { 256, 16, 1, 1 }, 0.25f, 0.0f, 2.0f, 0.0f, "pre_post")); + test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_SIGMOID, type, { 133, 7, 1, 1 }, 0.25f, 0.0f, 2.0f, 0.0f, "pre_post")); + test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_SILU, type, { 256, 16, 1, 1 }, 0.25f, 0.0f, 1.0f, 0.0f, "pre")); + test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_SIGMOID, type, { 256, 16, 1, 1 }, 1.0f, 0.0f, 1.0f, 1e-4f, "post")); + test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_GELU, type, { 256, 16, 1, 1 }, 0.5f, 0.1f, 1.5f, -0.1f, "pre_post")); + test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_GELU_QUICK, type, { 256, 16, 1, 1 }, 0.5f, 0.1f, 1.5f, -0.1f, "pre_post")); + test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_GELU_ERF, type, { 256, 16, 1, 1 }, 0.5f, 0.1f, 1.5f, -0.1f, "pre_post")); + test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_SOFTPLUS, type, { 256, 16, 1, 1 }, 0.69314718f, 0.0f, 1.44269504f, 0.0f, "pre_post")); + test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_TANH, type, { 256, 16, 1, 1 }, 1.0f / 30.0f, 0.0f, 30.0f, 0.0f, "pre_post")); + test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_TANH, type, { 32768, 2, 1, 1 }, 1.0f / 30.0f, 0.0f, 30.0f, 0.0f, "pre_post")); + test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_TANH, type, { 100032, 8, 1, 1 }, 1.0f / 30.0f, 0.0f, 30.0f, 0.0f, "pre_post")); + test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_SILU, type, { 256, 16, 1, 1 }, 0.25f, 0.0f, 1.0f, 0.0f, "glu_guard")); + test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_GELU, type, { 256, 16, 1, 1 }, 0.25f, 0.0f, 1.0f, 0.0f, "glu_guard")); + } + test_cases.emplace_back(new test_unary_scale_fusion(GGML_UNARY_OP_SIGMOID, GGML_TYPE_F32, { 256, 16, 1, 1 }, 0.25f, 0.0f, 2.0f, 0.0f, "lower")); + // SNAKE activation fusion: x + sin(a*x)^2 * inv_b for (ggml_type type : { GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16 }) { test_cases.emplace_back(new test_snake_fuse(type, { 5, 7, 1, 1})); // primes sub-block @@ -11232,6 +12041,47 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_snake_fuse(type, { 64, 32, 2, 3})); // ne[2] > 1 and ne[3] > 1 } + // the fused op chains of the Inkling 2 graph + for (int64_t n_tokens : { 1, 3, 32 }) { + test_cases.emplace_back(new test_situ({1152, 8, n_tokens}, 4.0f, 25.0f)); + } + test_cases.emplace_back(new test_situ({64, 2, 5}, 2.0f, 10.0f)); + for (bool with_w : { false, true }) { + for (bool with_f : { false, true }) { + for (std::array ne : std::initializer_list>{ {128, 24, 1, 1}, {128, 4, 7, 1}, {16, 24, 3, 1}, {1500, 2, 3, 2} }) { + test_cases.emplace_back(new test_l2_clip(ne, with_w, with_f, ne[0] == 16 ? 8.0f : 22.6f)); + } + } + } + for (int64_t H : { 0, 8 }) { + for (int64_t n_slots : { 0, 4 }) { + for (bool res : { false, true }) { + for (int64_t Ts : { 1, 3, 5, 33 }) { + for (int64_t S : { 1, 2 }) { + test_cases.emplace_back(new test_short_conv(1024, Ts, S, H, n_slots, res)); + } + } + } + } + } + for (int64_t K : { 2, 3, 8 }) { + test_cases.emplace_back(new test_short_conv(256, 5, 2, 4, 0, true, K)); + test_cases.emplace_back(new test_short_conv(256, 3, 1, 0, 6, false, K)); + } + for (int64_t T : { 1, 3 }) { + for (int64_t Q : { 1, 3, 4 }) { + for (int64_t B : { 1, 3, 12 }) { + test_cases.emplace_back(new test_depth_mix(2304, B, Q, T)); + } + } + test_cases.emplace_back(new test_depth_mix(2304, 5, 3, T, true)); + test_cases.emplace_back(new test_depth_mix(100, 2, 2, T)); + } + for (int64_t T : { 1, 4, 8 }) { + test_cases.emplace_back(new test_loop_ctrl(2304, 64, T)); + } + test_cases.emplace_back(new test_loop_ctrl(256, 40, 3)); + test_cases.emplace_back(new test_dsv4_hc_comb(1, 1)); test_cases.emplace_back(new test_dsv4_hc_comb(17, 4)); test_cases.emplace_back(new test_dsv4_hc_comb(257, 8)); @@ -11264,6 +12114,12 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_dsv4_hc_post(31, 17, false, true)); test_cases.emplace_back(new test_dsv4_hc_post(4096, 1)); // DeepSeek-V4-Flash decode test_cases.emplace_back(new test_dsv4_hc_post(2560, 1, true, true)); // Qwen4-Exp decode + for (int64_t n_embd : {96, 256}) { + for (int64_t n_tokens : {1, 64}) { + test_cases.emplace_back(new test_dsv4_hc_chain(GGML_TYPE_Q4_0, n_embd, n_tokens, true, true)); + test_cases.emplace_back(new test_dsv4_hc_chain(GGML_TYPE_Q4_0, n_embd, n_tokens, false, false)); + } + } for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32}) { // blocks with extra cells and scores (k-pool) @@ -11371,6 +12227,11 @@ static std::vector> make_test_cases_eval() { } } test_cases.emplace_back(new test_get_rows(GGML_TYPE_F32, 256, 8, 2, 1, 1, false, true, 3)); + test_cases.emplace_back(new test_get_rows(GGML_TYPE_F16, 256, 8, 2, 1, 1, false, true, 3)); + for (int n : { 31, 33, 64, 128, 256 }) { + test_cases.emplace_back(new test_get_rows(GGML_TYPE_F16, n, 8, 5, 3, 2, false, false)); + test_cases.emplace_back(new test_get_rows(GGML_TYPE_F16, n, 8, 5, 3, 2, false, true, 4)); + } test_cases.emplace_back(new test_get_rows_back(GGML_TYPE_F32, 1, 8, 2, 1, false)); test_cases.emplace_back(new test_get_rows_back(GGML_TYPE_F32, 1, 70000, 4, 1, false)); // row count > CUDA grid-y limit (65535) @@ -11413,6 +12274,22 @@ static std::vector> make_test_cases_eval() { } test_cases.emplace_back(new test_set_rows(GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_I32, { 256, 5, 1, 3 }, { 1, 1, }, 1, false)); test_cases.emplace_back(new test_set_rows(GGML_TYPE_BF16, GGML_TYPE_F16, GGML_TYPE_I64, { 1, 8, 1, 3 }, { 1, 1 }, 2, false)); + for (ggml_type dst_type : {GGML_TYPE_F16, GGML_TYPE_F32}) { + for (ggml_type idx_type : {GGML_TYPE_I32, GGML_TYPE_I64}) { + for (int64_t ne0 : {31, 33, 64, 128, 256}) { + for (bool v : {false, true}) { + test_cases.emplace_back(new test_set_rows(GGML_TYPE_F16, dst_type, idx_type, { ne0, 5, 2, 2 }, { 1, 1 }, 4, v)); + } + } + } + } + for (ggml_type idx_type : {GGML_TYPE_I32, GGML_TYPE_I64}) { + for (int64_t ne0 : {64, 128, 256}) { + for (bool v : {false, true}) { + test_cases.emplace_back(new test_set_rows(GGML_TYPE_F16, GGML_TYPE_Q8_0, idx_type, { ne0, 5, 2, 2 }, { 1, 1 }, 4, v)); + } + } + } for (int mode : { GGML_ROPE_TYPE_NORMAL, GGML_ROPE_TYPE_NEOX, GGML_ROPE_TYPE_MROPE, GGML_ROPE_TYPE_VISION, GGML_ROPE_TYPE_IMROPE }) { for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32}) { @@ -12103,6 +12980,16 @@ static std::vector> make_test_cases_eval() { } } + for (auto op : {ggml_add, ggml_sub, ggml_mul, ggml_div}) { + test_cases.emplace_back(new test_bin_bcast(op, GGML_TYPE_F16, {33, 5, 2, 1}, {1, 1, 1, 1}, 1, false, false, GGML_TYPE_F32)); + test_cases.emplace_back(new test_bin_bcast(op, GGML_TYPE_F16, {127, 1, 1, 1}, {1, 5, 2, 1}, 1, false, false, GGML_TYPE_F32)); + test_cases.emplace_back(new test_bin_bcast(op, GGML_TYPE_F16, {1, 1, 1, 1}, {256, 5, 2, 1}, 1, false, false, GGML_TYPE_F32)); + test_cases.emplace_back(new test_bin_bcast(op, GGML_TYPE_F16, {33, 2, 1, 1}, {2, 3, 1, 1}, 1, false, false, GGML_TYPE_F32)); + test_cases.emplace_back(new test_bin_bcast(op, GGML_TYPE_F16, {33, 5, 4, 3}, {1, 1, 1, 1}, 1, true, false, GGML_TYPE_F32)); + test_cases.emplace_back(new test_bin_bcast(op, GGML_TYPE_F16, {256, 3, 2, 1}, {1, 1, 1, 1}, 1, false, false, GGML_TYPE_F32)); + } + test_cases.emplace_back(new test_bin_bcast(ggml_add, GGML_TYPE_F16, {127, 5, 2, 1}, {1, 1, 1, 1}, 1, false, false, GGML_TYPE_F32, false, GGML_TYPE_F32)); + for (auto op : {ggml_add, ggml_mul}) { test_cases.emplace_back(new test_bin_bcast(op, GGML_TYPE_F32, {1, 2, 2, 2}, {17, 1, 1, 1}, 1, false, false, GGML_TYPE_COUNT, true)); } @@ -12196,7 +13083,7 @@ static std::vector> make_test_cases_eval() { for (uint32_t n : {1, 127, 129, 511, 513, 2816, 4096, 16385}) { test_cases.emplace_back(new test_rms_norm(GGML_TYPE_F32, {n, 3, 2, 1})); test_cases.emplace_back(new test_rms_norm_mul_rope({n, 3, 2, 1}, 1e-6f, false, false, true, GGML_ROPE_TYPE_NORMAL, true, false)); - test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, {n, 3, 2, 1}, 1e-6f, false, false, false, false, true)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, {n, 3, 2, 1}, 1e-6f, false, false, false, false, 1)); } // BF16 x with F32 weights, n > 1 because the NMSE of a single BF16 output is too noisy @@ -12204,11 +13091,11 @@ static std::vector> make_test_cases_eval() { for (uint32_t n : {127, 128, 512, 1024, 2048, 2816, 4096, 8192, 16385}) { test_cases.emplace_back(new test_rms_norm(GGML_TYPE_BF16, {n, 3, 2, 1})); test_cases.emplace_back(new test_rms_norm_mul_rope({n, 3, 2, 1}, 1e-6f, false, false, true, GGML_ROPE_TYPE_NORMAL, true, false, GGML_TYPE_F16, false, true, GGML_TYPE_BF16)); - test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, {n, 3, 2, 1}, 1e-6f, false, false, false, false, true, GGML_TYPE_F32)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, {n, 3, 2, 1}, 1e-6f, false, false, false, false, 1, GGML_TYPE_F32)); // BF16 residual added after the norm (post-norm models, e.g. Gemma) - test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, {n, 3, 2, 1}, 1e-6f, false, false, false, false, true, GGML_TYPE_F32, GGML_TYPE_BF16)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, {n, 3, 2, 1}, 1e-6f, false, false, false, false, 1, GGML_TYPE_F32, GGML_TYPE_BF16)); for (bool multi_add : {false, true}) { - test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, {n, 1, 1, 1}, 1e-6f, false, multi_add, false, false, false, GGML_TYPE_F32)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, {n, 1, 1, 1}, 1e-6f, false, multi_add, false, false, 0, GGML_TYPE_F32)); } } @@ -12226,10 +13113,10 @@ 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)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, false, false, false, false, 0, 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, 0, 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, 0, 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, 0, GGML_TYPE_F32, GGML_TYPE_BF16)); test_cases.emplace_back(new test_norm_mul_add(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, false)); test_cases.emplace_back(new test_norm_mul_add(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, true)); test_cases.emplace_back(new test_add_rms_norm(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, false)); @@ -12269,13 +13156,29 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 1536, 1, 1, 1 }, 1e-6f, false, false, true)); test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 256, 4, 1, 1 }, 1e-6f, false, false, true)); test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 256, 4, 3, 2 }, 1e-6f, false, false, true)); - test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 256, 4, 3, 2 }, 1e-6f, false, false, true, false, true)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 256, 4, 3, 2 }, 1e-6f, false, false, true, false, 1)); test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 1536, 1, 1, 1 }, 1e-6f, false, false, false, true)); test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 256, 4, 1, 1 }, 1e-6f, false, false, false, true)); - test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 1536, 1, 1, 1 }, 1e-6f, false, false, true, false, false, GGML_TYPE_F32)); - test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 1536, 1, 1, 1 }, 1e-6f, false, false, true, false, false, GGML_TYPE_F32, GGML_TYPE_BF16)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 1536, 1, 1, 1 }, 1e-6f, false, false, true, false, 0, GGML_TYPE_F32)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 1536, 1, 1, 1 }, 1e-6f, false, false, true, false, 0, GGML_TYPE_F32, GGML_TYPE_BF16)); // the ADD operand is the BF16 input itself, added in place - test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 1536, 1, 1, 1 }, 1e-6f, false, false, false, true, false, GGML_TYPE_F32)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 1536, 1, 1, 1 }, 1e-6f, false, false, false, true, 0, GGML_TYPE_F32)); + // dim-1 broadcast weights [ne0, ne1, 1, 1] across [ne0, ne1, ne2, ne3] + for (bool has_add : { false, true }) { + for (bool post_mul : { false, true }) { + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 256, 4, 3, 2 }, 1e-6f, false, false, post_mul, false, 4, GGML_TYPE_COUNT, GGML_TYPE_COUNT, false, has_add)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 2560, 4, 33, 1 }, 1e-6f, false, false, post_mul, false, 4, GGML_TYPE_COUNT, GGML_TYPE_COUNT, false, has_add)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 5120, 4, 33, 1 }, 1e-6f, false, false, post_mul, false, 4, GGML_TYPE_COUNT, GGML_TYPE_COUNT, false, has_add)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { 256, 3, 5, 2 }, 1e-6f, false, false, post_mul, false, 3, GGML_TYPE_COUNT, GGML_TYPE_COUNT, false, has_add)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 256, 4, 3, 2 }, 1e-6f, false, false, post_mul, false, 4, GGML_TYPE_F32, GGML_TYPE_COUNT, false, has_add)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 256, 3, 5, 2 }, 1e-6f, false, false, post_mul, false, 3, GGML_TYPE_F32, GGML_TYPE_COUNT, false, has_add)); + if (has_add) { + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 256, 4, 3, 2 }, 1e-6f, false, false, post_mul, false, 4, GGML_TYPE_F32, GGML_TYPE_BF16, false, true)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { 256, 3, 5, 2 }, 1e-6f, false, false, post_mul, false, 3, GGML_TYPE_F32, GGML_TYPE_BF16, false, true)); + } + } + } + test_cases.emplace_back(new test_rms_norm_mul_rope({128, 4, 7, 2})); test_cases.emplace_back(new test_rms_norm_mul_rope({128, 4, 7, 2}, 1e-6f, false, true)); @@ -12354,6 +13257,30 @@ static std::vector> make_test_cases_eval() { } } + for (bool use_silu : {false, true}) { + for (bool has_state_cpy : {false, true}) { + for (int64_t n_t : {1, 2, 64, 200}) { + for (int64_t n_s : {1, 2}) { + test_cases.emplace_back(new test_ssm_conv_concat_fusion( + GGML_TYPE_F32, 4, 256, n_t, n_s, use_silu, has_state_cpy)); + } + test_cases.emplace_back(new test_ssm_conv_concat_fusion( + GGML_TYPE_F32, 4, 160, n_t, 1, use_silu, has_state_cpy)); + test_cases.emplace_back(new test_ssm_conv_concat_fusion( + GGML_TYPE_F32, 4, 144, n_t, 2, use_silu, has_state_cpy)); + } + for (int64_t d_conv : {3, 5}) { + for (int64_t n_t : {1, 2, 64}) { + test_cases.emplace_back(new test_ssm_conv_concat_fusion( + GGML_TYPE_F32, d_conv, 256, n_t, 1, use_silu, has_state_cpy)); + test_cases.emplace_back(new test_ssm_conv_concat_fusion( + GGML_TYPE_F32, d_conv, 160, n_t, 2, use_silu, has_state_cpy)); + } + } + } + } + + test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 16, 1, 1024, 1, 32, 4)); // Mamba-1 test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 64, 64, 112, 2, 32, 4)); // Zamba2 (real hparams: d_inner=7168, dt_rank=112, n_group=2 -> head_dim=7168/112=64) test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 64, 64, 112, 2, 1, 1)); // Zamba2 decode (single-token, matches real per-token decode workload) @@ -12520,6 +13447,8 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_F32, GGML_TYPE_F32, 4, 2, false, 64, 33792, 64)); // kernel_mul_mm_id: > 2^31-element dst (8.7 GB), about 45 GB peak memory. Tokens 32514+ have a dst offset past INT32_MAX, tokens 32768+ also need a 32-bit token index. test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_F32, GGML_TYPE_F32, 16, 8, false, 8256, 32832, 64)); + // CUDA mul_mat_f_ids: 160 F16 experts of 4096 x 7168 (9.4 GB), about 36 GB peak memory. Experts 147-159 start past INT32_MAX half2 values, 32 tokens x 8 random experts. + test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_F16, GGML_TYPE_F32, 160, 8, true, 4096, 32, 7168)); #endif #if 0 @@ -12570,6 +13499,7 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q8_0, GGML_TYPE_F32, 2880, 32, 2880, {1, 1}, {1, 1})); test_cases.emplace_back(new test_mul_mat(GGML_TYPE_MXFP4, GGML_TYPE_F32, 2880, 32, 2880, {1, 1}, {1, 1})); + // m == 1, with n on both sides of MMVF_MAX_BATCH_SIZE (8): mmvf below, operand swap above for (int64_t n : {1, 7, 8, 9, 16, 127, 128, 511, 512}) { test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, 1, n, 2048, {1, 1}, {1, 1})); @@ -12602,6 +13532,15 @@ static std::vector> make_test_cases_eval() { #endif test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, 31, 509, 2051, {1, 1}, {1, 1})); + + // a few rows of a few columns against many rows, batched (the weighted sum over the depth states of Inkling 2) + for (int64_t m : {1, 3, 8, 33}) { + for (int64_t k : {2, 5, 24, 31}) { + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, m, 2304, k, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, m, 97, k, {7, 2}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_F32, m, 33, k, {2, 3}, {2, 1})); + } + } test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_F32, 32, 509, 2112, {1, 1}, {1, 1})); test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q8_0, GGML_TYPE_F32, 32, 509, 2112, {1, 1}, {1, 1})); @@ -12767,6 +13706,44 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_BF16, 16, 1, 256, {3, 2}, {2, 2})); test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_BF16, 16, 8, 256, {1, 1}, {1, 1})); + // BF16 in src1 (activations): MMVQ, few-row MMQ, MMQ with each layout of the Q8_1 src1 and the FP4 src1, + // cuBLAS for F16 weights, MMVF for BF16 weights and the transposed F32 vector + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_0, GGML_TYPE_BF16, 256, 1, 4096, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q8_0, GGML_TYPE_BF16, 256, 8, 4096, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 256, 8, 4096, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q8_0, GGML_TYPE_BF16, 256, 64, 4096, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 256, 64, 4096, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q2_K, GGML_TYPE_BF16, 256, 64, 4096, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_NVFP4, GGML_TYPE_BF16, 256, 64, 4096, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_MXFP4, GGML_TYPE_BF16, 256, 64, 4096, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_BF16, 256, 1, 4096, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_BF16, GGML_TYPE_BF16, 256, 1, 4096, {1, 1}, {1, 1})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_BF16, 1, 16, 2048, {1, 1}, {1, 1})); + // FP8 weights with more tokens than MMVF takes: src1 quantized to FP8 for cuBLASLt + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F8_E4M3, GGML_TYPE_BF16, 16, 16, 64, {1, 1}, {1, 1})); + // BF16 src1 as a permuted view (rows 4*k values apart, channels k apart): MMVQ, few-row MMQ, MMQ with the Q8_1 and the FP4 src1, + // FP8 on cuBLASLt, MMVF for BF16 and FP8 weights + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 16, 3, 256, {1, 1}, {4, 2}, {0, 2, 1, 3})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 64, 13, 4608, {1, 1}, {4, 2}, {0, 2, 1, 3})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 16, 64, 256, {1, 1}, {4, 2}, {0, 2, 1, 3})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_NVFP4, GGML_TYPE_BF16, 16, 64, 256, {1, 1}, {4, 2}, {0, 2, 1, 3})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F8_E4M3, GGML_TYPE_BF16, 16, 16, 64, {1, 1}, {4, 2}, {0, 2, 1, 3})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_BF16, GGML_TYPE_BF16, 16, 3, 256, {1, 1}, {4, 2}, {0, 2, 1, 3})); + test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F8_E4M3, GGML_TYPE_BF16, 16, 3, 256, {1, 1}, {4, 2}, {0, 2, 1, 3})); + // MUL_MAT_ID: MMVQ, MMQ without and with a broadcast src1 (quantized once per token), MMVF with several tokens + test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 8, 2, true, 256, 1, 1024)); + test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 8, 2, false, 256, 32, 1024)); + test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 8, 2, true, 256, 32, 1024)); + // MUL_MAT_ID few-row MMQ (CUDA, from MMVQ's max. batch size up to 24 tokens) + test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 16, 4, false, 72, 13, 2048)); + test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_NVFP4, GGML_TYPE_BF16, 8, 2, true, 256, 32, 1024)); + test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_MXFP4, GGML_TYPE_BF16, 8, 2, true, 256, 32, 1024)); + test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_F8_E4M3, GGML_TYPE_BF16, 8, 2, false, 256, 4, 1024)); + // float experts (MMF reads only an F32 src1): MMVF for BF16 experts up to 8 tokens, the fallback that sorts src1 by expert for F16 + test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_BF16, GGML_TYPE_BF16, 8, 2, false, 256, 1, 1024)); + test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_BF16, GGML_TYPE_BF16, 8, 2, false, 256, 4, 1024)); + test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_F16, GGML_TYPE_BF16, 8, 2, false, 256, 32, 1024)); + // token-tile boundary coverage. With n_used == n_mats every token routes to every expert, so // each expert receives exactly n rows, with no dependence on the random draw. mul_mm_id is used // from 32 tokens up: n = 32, 33, 47, 48, 49 reach it, leaving a last tile of 32, 1, 15, 16 and @@ -13051,6 +14028,7 @@ static std::vector> make_test_cases_eval() { } } + for (ggml_type type_a : base_types) { for (ggml_type type_b : {GGML_TYPE_F32, GGML_TYPE_F16}) { for (int n : {1, 16}) { @@ -13124,6 +14102,12 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_clamp (type, {1024, 1024, 1, 1})); test_cases.emplace_back(new test_leaky_relu(type, {7, 1, 5, 3})); test_cases.emplace_back(new test_leaky_relu(type, {1024, 1024, 1, 1})); + if (type == GGML_TYPE_F16) { + test_cases.emplace_back(new test_leaky_relu(type, {33, 2, 2, 2})); + test_cases.emplace_back(new test_leaky_relu(type, {65, 2, 2, 2})); + test_cases.emplace_back(new test_leaky_relu(type, {127, 2, 2, 2})); + test_cases.emplace_back(new test_leaky_relu(type, {65536, 2, 1, 1})); + } test_cases.emplace_back(new test_floor (type, {7, 1, 5, 3})); test_cases.emplace_back(new test_floor (type, {1024, 1024, 1, 1})); test_cases.emplace_back(new test_ceil (type, {7, 1, 5, 3})); @@ -13197,6 +14181,7 @@ static std::vector> make_test_cases_eval() { 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}) { for (int64_t ne0 : {16, 1024}) { @@ -13266,9 +14251,9 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_rope(type, { 36, 16, 2457, 1}, 36, rmode, 512, fs, ef, af, ff, 2, fw)); } } - - all = false; } + + all = false; } } } @@ -13319,11 +14304,26 @@ static std::vector> make_test_cases_eval() { } } - // Real-model RoPE: F32 forward, packed Q, 512-token prefill. - test_cases.emplace_back(new test_rope(GGML_TYPE_F32, {256, 8, 512, 1}, 64, GGML_ROPE_TYPE_IMROPE, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // qwen3.5 0.8B - test_cases.emplace_back(new test_rope(GGML_TYPE_F32, {256, 16, 512, 1}, 64, GGML_ROPE_TYPE_IMROPE, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // qwen3.5 4B - test_cases.emplace_back(new test_rope(GGML_TYPE_F32, {256, 8, 512, 1}, 256, GGML_ROPE_TYPE_NEOX, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // gemma4 E2B sliding - test_cases.emplace_back(new test_rope(GGML_TYPE_F32, {512, 8, 512, 1}, 128, GGML_ROPE_TYPE_NEOX, 512, 1.0f, 0.0f, 1.0f, true, 0, true)); // gemma4 E4B global + // Partial n_dims < ne0 (e.g. Qwen3.5 partial RoPE: n_dims = 64, 96 with ne0 = 128) across modes, freq_factors, and strided views. + for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16}) { + for (int n_dims : {64, 96}) { + for (int mode : {GGML_ROPE_TYPE_NORMAL, GGML_ROPE_TYPE_NEOX, GGML_ROPE_TYPE_MROPE, GGML_ROPE_TYPE_IMROPE}) { + for (bool ff : {false, true}) { + for (int v : {0, 1, 2}) { + test_cases.emplace_back(new test_rope(type, {128, 16, 2, 1}, n_dims, mode, 512, 1.0f, 0.0f, 1.0f, ff, v, true)); + } + } + } + } + } + + // Real-model RoPE: F32/F16 forward, packed Q, 512-token prefill. + for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16}) { + test_cases.emplace_back(new test_rope(type, {256, 8, 512, 1}, 64, GGML_ROPE_TYPE_IMROPE, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // qwen3.5 0.8B + test_cases.emplace_back(new test_rope(type, {256, 16, 512, 1}, 64, GGML_ROPE_TYPE_IMROPE, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // qwen3.5 4B + test_cases.emplace_back(new test_rope(type, {256, 8, 512, 1}, 256, GGML_ROPE_TYPE_NEOX, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // gemma4 E2B sliding + test_cases.emplace_back(new test_rope(type, {512, 8, 512, 1}, 128, GGML_ROPE_TYPE_NEOX, 512, 1.0f, 0.0f, 1.0f, true, 0, true)); // gemma4 E4B global + } for (int v : { 0, 1, 2, 3, 16 }) { for (int dim : { 0, 1, 2, 3, }) { @@ -13352,6 +14352,11 @@ 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)); } + // 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)); + test_cases.emplace_back(new test_concat(GGML_TYPE_F16, {4, 2, 1, 70000}, 4, 0, 1)); + 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)); @@ -13368,13 +14373,16 @@ static std::vector> make_test_cases_eval() { 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)); - test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {1, 37, 1, 1}, ne_b_d, 0, 16)); + for (ggml_type type : { GGML_TYPE_F32, GGML_TYPE_F16 }) { + for (int64_t ne_b_d : { 31, 32, 33, 64 }) { + test_cases.emplace_back(new test_concat(type, {3, 10240, 1, 1}, ne_b_d, 0, 16)); + test_cases.emplace_back(new test_concat(type, {1, 37, 1, 1}, ne_b_d, 0, 16)); + } + test_cases.emplace_back(new test_concat(type, {64, 37, 1, 1}, 32, 0, 16)); + // Empty src0 + test_cases.emplace_back(new test_concat(type, {0, 64, 1, 1}, 33, 0, 16)); } - test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {64, 37, 1, 1}, 32, 0, 16)); - // Empty src0 - test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {0, 64, 1, 1}, 33, 0, 16)); + for (ggml_sort_order order : {GGML_SORT_ORDER_ASC, GGML_SORT_ORDER_DESC}) { for (uint32_t i = 4; i <= 1024*1024; i *= 2) { @@ -13458,6 +14466,7 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_topk_qsa(256, 2048, 4, 2, 2000)); test_cases.emplace_back(new test_topk_qsa(64, 256, 2, 1, 200)); // small k: unfused fallback + // exhaustive top_k tests //for (int i = 1; i < 9999; ++i) { // test_cases.emplace_back(new test_top_k(GGML_TYPE_F32, {i, 2, 1, 3}, rand() % i + 1)); @@ -13712,7 +14721,8 @@ static std::vector> make_test_cases_eval() { if (nh == 1 && hsk != 320 && hsk != 576) continue; for (int nr3 : { 1, 3, }) { if (hsk > 64 && nr3 > 1) continue; // skip broadcast for large head sizes - for (int nr2 : { 1, 4, 8, 12, 16, 20, 32 }) { + for (int nr2 : { 1, 2, 3, 4, 8, 12, 16, 20, 32 }) { + if ((nr2 == 2 || nr2 == 3) && hsk != 576) continue; // MLA with a GQA ratio below 4 if (nr2 == 8 && hsk != 192) continue; if (nr2 == 12 && hsk != 128) continue; if (nr2 == 16 && hsk != 192) continue; @@ -14102,6 +15112,20 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 9, 128, 2048, false, 1, 1, false, false, true, false, { 1, 1 })); // on DGX Spark also the expert gate and up matmuls at 8 tokens, instead of the fused MMVQ path test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 8, 128, 2048, true, 16, 4, true)); + // BF16 input to MUL_MAT_ID: fused gate/up + GLU on MMVF (BF16 experts with more than 512 rows) and on MMQ (broadcast input) + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_BF16, GGML_GLU_OP_SWIGLU, 1, 1024, 256, true, 16, 8, false, false, true, false, { 1, 1 }, false, GGML_TYPE_BF16)); + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 17, 5120, 256, true, 16, 8, true, false, true, false, { 4, 2 }, false, GGML_TYPE_BF16)); + // BF16 input: fused gate/up + GLU on MMVQ, MMVF and MMQ (NVFP4 with weight scales), and the NVFP4 weight scale on MMQ + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 1, 32, 256, false, 1, 1, false, false, true, false, { 1, 1 }, false, GGML_TYPE_BF16)); + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_BF16, GGML_GLU_OP_SWIGLU, 1, 32, 256, false, 1, 1, false, false, true, false, { 1, 1 }, false, GGML_TYPE_BF16)); + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 6912, 256, false, 1, 1, false, false, true, true, { 2, 3 }, false, GGML_TYPE_BF16)); + test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 2560, 256, false, 1, 1, false, false, false, true, { 1, 1 }, false, GGML_TYPE_BF16)); + + for (int64_t n_tok : {1, 4, 16}) { + test_cases.emplace_back(new test_moe_router_prec_f32(128, 64, n_tok, 8)); + test_cases.emplace_back(new test_ffn_residual_fusion(GGML_TYPE_Q4_0, 128, 256, n_tok)); + test_cases.emplace_back(new test_ffn_residual_fusion(GGML_TYPE_Q8_0, 128, 256, n_tok)); + } for (auto gate : {GATING_FUNC_SOFTMAX, GATING_FUNC_SIGMOID, GATING_FUNC_SOFTMAX_WEIGHT, GATING_FUNC_SQRT_SOFTPLUS}) { for (bool with_norm : {false, true}) { @@ -14270,6 +15294,8 @@ static std::vector> make_test_cases_eval() { 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)); + test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 64, 1, 1, false, 4)); + test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 64, 64, 1, false, 4)); #if 0 // these tests are disabled to save execution time, sbut they can be handy for debugging @@ -14283,7 +15309,7 @@ static std::vector> make_test_cases_eval() { // lightning_indexer for (int kv : { 256 }) { for (int bs : { 1, 512 }) { - for (int nh : { 4, 32, 64 }) { + for (int nh : { 4, 16, 32, 64 }) { for (auto [ns, nm] : { std::pair{1, 1}, std::pair{4, 4}, std::pair{4, 1} }) { for (ggml_type type_K : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q5_1, GGML_TYPE_Q5_0, GGML_TYPE_Q4_1, GGML_TYPE_Q4_0, GGML_TYPE_IQ4_NL}) { test_cases.emplace_back(new test_lightning_indexer(128, nh, kv, bs, ns, nm, type_K)); @@ -14809,11 +15835,13 @@ static std::vector> make_test_cases_perf() { } } - // Real-model RoPE: F32 forward, packed Q, 512-token prefill. - test_cases.emplace_back(new test_rope(GGML_TYPE_F32, {256, 8, 512, 1}, 64, GGML_ROPE_TYPE_IMROPE, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // qwen3.5 0.8B - test_cases.emplace_back(new test_rope(GGML_TYPE_F32, {256, 16, 512, 1}, 64, GGML_ROPE_TYPE_IMROPE, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // qwen3.5 4B - test_cases.emplace_back(new test_rope(GGML_TYPE_F32, {256, 8, 512, 1}, 256, GGML_ROPE_TYPE_NEOX, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // gemma4 E2B sliding - test_cases.emplace_back(new test_rope(GGML_TYPE_F32, {512, 8, 512, 1}, 128, GGML_ROPE_TYPE_NEOX, 512, 1.0f, 0.0f, 1.0f, true, 0, true)); // gemma4 E4B global + // Real-model RoPE: F32/F16 forward, packed Q, 512-token prefill. + for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16}) { + test_cases.emplace_back(new test_rope(type, {256, 8, 512, 1}, 64, GGML_ROPE_TYPE_IMROPE, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // qwen3.5 0.8B + test_cases.emplace_back(new test_rope(type, {256, 16, 512, 1}, 64, GGML_ROPE_TYPE_IMROPE, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // qwen3.5 4B + test_cases.emplace_back(new test_rope(type, {256, 8, 512, 1}, 256, GGML_ROPE_TYPE_NEOX, 512, 1.0f, 0.0f, 1.0f, false, 0, true)); // gemma4 E2B sliding + test_cases.emplace_back(new test_rope(type, {512, 8, 512, 1}, 128, GGML_ROPE_TYPE_NEOX, 512, 1.0f, 0.0f, 1.0f, true, 0, true)); // gemma4 E4B global + } std::vector> reduce_rows_cases = { { 8192, 1, 1, 1 }, @@ -14925,6 +15953,10 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 1, 1)); // Qwen3.5-like: 32 heads, d=128 test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 64, 1, 1)); // smaller model test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 1, 1, 1, false, true)); // KDA + // Qwen3.8 27B decode and MTP verify: 16 q/k heads, 48 v heads, d=128 + for (int n : { 1, 2, 4 }) { + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, n, 1, 3)); + } // PP: n_seq_tokens=64,256 (prompt processing) test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 64, 1)); // PP-64 test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 256, 1)); // PP-256 @@ -14962,7 +15994,7 @@ static std::vector> make_test_cases_perf() { // lightning_indexer for (int kv : { 256, 4096, 65536 }) { for (int bs : { 1, 512, 2048 }) { - for (int nh : { 4, 32, 64 }) { + for (int nh : { 4, 16, 32, 64 }) { for (int ns : { 1, 4 }) { for (ggml_type type_K : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q5_1, GGML_TYPE_Q5_0, GGML_TYPE_Q4_1, GGML_TYPE_Q4_0, GGML_TYPE_IQ4_NL}) { test_cases.emplace_back(new test_lightning_indexer(128, nh, kv, bs, ns, ns, type_K)); diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp index 20a3cc6a0747..83c11cc2d4ac 100644 --- a/tests/test-chat.cpp +++ b/tests/test-chat.cpp @@ -4255,6 +4255,215 @@ static void test_template_output_peg_parsers(bool detailed_debug) { .expect_content("Hello, world!\nWhat's up?") .run(); } + { + // Raon-1 mini: ChatML turns, an explicit envelope on every assistant turn and Qwen3-Coder style XML tool calls + auto tst = peg_tester("models/templates/KRAFTON-Raon-1-mini-preview.jinja", detailed_debug); + + // reasoning on: the generation prompt opens "\n" + tst.test("I'm\nthinking\n\n\nHello, world!\nWhat's up?") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(true) + .expect(message_assist_thoughts) + .run(); + + tst.test("I'm\nthinking\n\n\nHello, world!\nWhat's up?") + .reasoning_format(COMMON_REASONING_FORMAT_NONE) + .enable_thinking(true) + .expect_content("\nI'm\nthinking\n\n\nHello, world!\nWhat's up?") + .run(); + + // reasoning off: the generation prompt already closes the envelope + tst.test("Hello, world!\nWhat's up?") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(false) + .expect(message_assist) + .run(); + + // typed arguments: integer + tst.test( + "\n" + "\n" + "\n1\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(false) + .tools({ special_function_tool }) + .expect(message_assist_call) + .expect_rules({ "tool-0", "tool-0-arg-0" }) + .run(); + + tst.test( + "I'm\nthinking\n
\n\n" + "\n" + "\n" + "\n1\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(true) + .tools({ special_function_tool }) + .expect(message_assist_call_thoughts) + .run(); + + // typed arguments: string and integer, optional arguments out of order + tst.test( + "\n" + "\n" + "\nhello\n\n" + "\n42\n\n" + "\n100\n\n" + "\nworld\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(false) + .tools({ tool_2req_4opt }) + .expect_tool_calls({ + { "tool_2req_4opt", R"({"req1": "hello", "req2": 42, "opt4": 100, "opt1": "world"})", {} }, + }) + .run(); + + // typed arguments: boolean, object and array values stay JSON + tst.test( + "\n" + "\n" + "\ntrue\n\n" + "\n" + "\n" + "\n" + "\n" + "\n{\"mode\": \"fast\", \"level\": 2}\n\n" + "\n" + "\n" + "\n" + "\n" + "\n[{\"item\": \"Check stuff\", \"selected\": false}]\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(false) + .parallel_tool_calls(true) + .tools({ toggle_tool, config_tool, todo_list }) + .expect_tool_calls({ + { "toggle", R"({"enabled": true})", {} }, + { "set_config", R"({"config": {"mode": "fast", "level": 2}})", {} }, + { "todo_list", R"({"todos": [{"item": "Check stuff", "selected": false}]})", {} }, + }) + .run(); + + // a string argument that looks like a number stays a string + tst.test( + "\n" + "\n" + "\n2024.c\n\n" + "\n1\n\n" + "\n2\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(false) + .tools({ edit_tool }) + .expect_tool_calls({ + { "edit", R"({"filename": "2024.c", "oldString": "1", "newString": "2"})", {} }, + }) + .run(); + + // nullable arguments + tst.test( + "\n" + "\n" + "\nnull\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(false) + .tools({ nullable_string_tool }) + .expect_tool_calls({ + { "set_nullable_str", R"({"name": null})", {} }, + }) + .run(); + + tst.test( + "\n" + "\n" + "\nhello world\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(false) + .tools({ nullable_string_tool }) + .expect_tool_calls({ + { "set_nullable_str", R"({"name": "hello world"})", {} }, + }) + .run(); + + tst.test( + "\n" + "\n" + "\nnull\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(false) + .tools({ nullable_int_tool }) + .expect_tool_calls({ + { "set_nullable_int", R"({"count": null})", {} }, + }) + .run(); + + tst.test( + "\n" + "\n" + "\n42\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(false) + .tools({ nullable_int_tool }) + .expect_tool_calls({ + { "set_nullable_int", R"({"count": 42})", {} }, + }) + .run(); + + // content before the call, then reasoning + parallel calls + tst.test( + "I'm\nthinking\n\n\n" + "Hello, world!\nWhat's up?\n\n" + "\n" + "\n" + "\n1\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(true) + .tools({ special_function_tool }) + .expect(message_assist_call_thoughts_content) + .run(); + + tst.test( + "\n" + "\n" + "\n1\n\n" + "\n" + "\n" + "\n" + "\n" + "\n1\n\n" + "\n2\n\n" + "\n" + "") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .enable_thinking(false) + .parallel_tool_calls(true) + .tools({ special_function_tool, special_function_tool_with_optional_param }) + .expect_tool_calls({ + { "special_function", R"({"arg1": 1})", {} }, + { "special_function_with_opt", R"({"arg1": 1, "arg2": 2})", {} }, + }) + .run(); + } + { auto tst = peg_tester("models/templates/deepseek-ai-DeepSeek-V3.1.jinja", detailed_debug); tst.test( @@ -8188,6 +8397,13 @@ static void test_template_generation_prompt() { check(tmpls, continuation_reasoning(), "<|im_start|>assistant\n\nI'm"); } + { + auto tmpls = read_templates("models/templates/KRAFTON-Raon-1-mini-preview.jinja"); + check(tmpls, basic(), "<|im_start|>assistant\n\n"); + check(tmpls, continuation_content(), "<|im_start|>assistant\n\nI'm thinking\n\n\nHello, "); + check(tmpls, continuation_reasoning(), "<|im_start|>assistant\n\nI'm"); + } + { auto tmpls = read_templates("models/templates/openai-gpt-oss-120b.jinja"); check(tmpls, basic(), "<|start|>assistant"); @@ -8698,6 +8914,179 @@ static void test_deepseek_v4_1_message_fields() { } } +// Raon-1 mini template (models/templates/KRAFTON-Raon-1-mini-preview.jinja) prompt rendering +static void test_raon_prompt() { + LOG_DBG("%s\n", __func__); + + auto tmpls = read_templates("models/templates/KRAFTON-Raon-1-mini-preview.jinja"); + + common_chat_msg developer_msg; + developer_msg.role = "developer"; + developer_msg.content = "You are RAON."; + + common_chat_msg system_msg = developer_msg; + system_msg.role = "system"; + + auto render = [&](const std::vector & messages, bool with_tools, bool enable_thinking = true) { + common_chat_templates_inputs inputs; + inputs.messages = messages; + inputs.enable_thinking = enable_thinking; + if (with_tools) { + inputs.tools = { special_function_tool }; + } + return common_chat_templates_apply(tmpls.get(), inputs); + }; + + // a leading developer message is rendered as the system turn (the template itself rejects "developer") + { + const auto prompt = render({ developer_msg, message_user }, false).prompt.str(); + assert_equals(std::string( + "<|im_start|>system\nYou are RAON.<|im_end|>\n" + "<|im_start|>user\nHey there!<|im_end|>\n" + "<|im_start|>assistant\n\n"), prompt); + assert_equals(render({ system_msg, message_user }, false).prompt.str(), prompt); + } + + // with tools the system text follows the tool block in the same system turn + { + const auto prompt = render({ developer_msg, message_user }, true).prompt.str(); + assert_equals(true, string_starts_with(prompt, "<|im_start|>system\n# Tools\n\n")); + assert_contains(prompt, "\"name\": \"special_function\""); + assert_contains(prompt, "\n\nYou are RAON.<|im_end|>\n<|im_start|>user\nHey there!<|im_end|>\n"); + assert_not_contains(prompt, "developer"); + assert_equals(render({ system_msg, message_user }, true).prompt.str(), prompt); + } + + // reasoning off closes the think envelope in the generation prompt + { + const auto params = render({ message_user }, false, /* enable_thinking = */ false); + assert_equals(std::string("<|im_start|>assistant\n\n\n"), params.generation_prompt); + assert_ends_with(params.prompt.str(), params.generation_prompt); + } + + // assistant history as HF apply_chat_template renders it: kept reasoning and tool calls after the last query, an earlier turn's reasoning kept by default and dropped with truncate_history_thinking=true + { + common_chat_msg calls; + calls.role = "assistant"; + calls.reasoning_content = "Two calls."; + calls.tool_calls.push_back({ "special_function", "{\"arg1\": 1}", "call_1" }); + calls.tool_calls.push_back({ "special_function", "{\"arg1\": 2}", "call_2" }); + common_chat_msg r1; r1.role = "tool"; r1.tool_call_id = "call_1"; r1.content = "one"; + common_chat_msg r2; r2.role = "tool"; r2.tool_call_id = "call_2"; r2.content = "two"; + common_chat_msg user_q; user_q.role = "user"; user_q.content = "Call it twice."; + assert_ends_with(render({ user_q, calls, r1, r2 }, true).prompt.str(), std::string( + "<|im_start|>user\n" + "Call it twice.<|im_end|>\n" + "<|im_start|>assistant\n" + "\n" + "Two calls.\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "1\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "2\n" + "\n" + "\n" + "<|im_end|>\n" + "<|im_start|>user\n" + "\n" + "one\n" + "\n" + "\n" + "two\n" + "<|im_end|>\n" + "<|im_start|>assistant\n" + "\n")); + + common_chat_msg old; old.role = "assistant"; old.content = "Old thought.\n\n\nAnswer."; + common_chat_msg again; again.role = "user"; again.content = "Again."; + // with truncate_history_thinking = true the earlier turn's reasoning is dropped + { + common_chat_templates_inputs inputs; + inputs.messages = { user_q, old, again }; + inputs.chat_template_kwargs["truncate_history_thinking"] = "true"; + assert_equals(std::string( + "<|im_start|>user\n" + "Call it twice.<|im_end|>\n" + "<|im_start|>assistant\n" + "\n" + "\n" + "Answer.<|im_end|>\n" + "<|im_start|>user\n" + "Again.<|im_end|>\n" + "<|im_start|>assistant\n" + "\n"), common_chat_templates_apply(tmpls.get(), inputs).prompt.str()); + } + + // by default (the template defaults truncate_history_thinking to false) the earlier turn keeps the reasoning split out of its content + { + assert_equals(std::string( + "<|im_start|>user\n" + "Call it twice.<|im_end|>\n" + "<|im_start|>assistant\n" + "\n" + "Old thought.\n" + "\n" + "\n" + "Answer.<|im_end|>\n" + "<|im_start|>user\n" + "Again.<|im_end|>\n" + "<|im_start|>assistant\n" + "\n"), render({ user_q, old, again }, false).prompt.str()); + } + } + + // continuing an assistant message without reasoning: the shared Qwen3-Coder handler writes "\n\n\n\n", the template "\n\n"; this pins the handler's behaviour + { + common_chat_templates_inputs inputs; + inputs.messages = { message_user, simple_assist_msg("Hello, ") }; + inputs.add_generation_prompt = false; + inputs.continue_final_message = COMMON_CHAT_CONTINUATION_CONTENT; + assert_ends_with(common_chat_templates_apply(tmpls.get(), inputs).prompt.str(), + std::string("<|im_start|>assistant\n\n\n\n\nHello, ")); + } + + // Keep system instructions in order, including instructions sent as developer messages. + { + common_chat_msg second_system = system_msg; + second_system.content = "Keep it short."; + + const std::string system_turn = "<|im_start|>system\nYou are RAON.<|im_end|>\n"; + const std::string second_system_turn = "<|im_start|>system\nKeep it short.<|im_end|>\n"; + const std::string user_turn = "<|im_start|>user\nHey there!<|im_end|>\n"; + const std::string generation_prompt = "<|im_start|>assistant\n\n"; + + assert_equals(system_turn + second_system_turn + user_turn + generation_prompt, + render({ system_msg, second_system, message_user }, false).prompt.str()); + assert_equals(system_turn + user_turn + second_system_turn + generation_prompt, + render({ system_msg, message_user, second_system }, false).prompt.str()); + assert_equals(user_turn + system_turn + generation_prompt, + render({ message_user, developer_msg }, false).prompt.str()); + + // A system instruction can start a conversation without a user message. + assert_equals(system_turn + generation_prompt, render({ system_msg }, false).prompt.str()); + } + + // A closing tag in the answer is literal, even after an initial reasoning block. + { + const auto literal = simple_assist_msg("The answer quotes ."); + assert_contains(render({ message_user, literal, message_user }, false).prompt.str(), + "<|im_start|>assistant\n\n\nThe answer quotes .<|im_end|>\n"); + + const auto with_reasoning = simple_assist_msg("Reasoning.\n\nThe answer quotes ."); + assert_contains(render({ message_user, with_reasoning, message_user }, false).prompt.str(), + "<|im_start|>assistant\n\nReasoning.\n\n\nThe answer quotes .<|im_end|>\n"); + } +} + static void test_prompt_parts() { LOG_DBG("%s\n", __func__); const std::string tmpl_src = @@ -9132,6 +9521,7 @@ int main(int argc, char ** argv) { test_deepseek_v4_tool_result_ordering(); test_deepseek_v4_1_message_fields(); test_inkling2_media_blocks(); + test_raon_prompt(); test_template_generation_prompt(); test_reasoning_effort_caps(); test_prompt_parts(); diff --git a/tests/test-fusion.cpp b/tests/test-fusion.cpp index c268472ca72e..328c20fc003a 100644 --- a/tests/test-fusion.cpp +++ b/tests/test-fusion.cpp @@ -377,7 +377,8 @@ int main(int argc, char ** argv) { for (const auto & model_path : models) { const std::string arch = get_arch(model_path); - const bool moe = arch.find("moe") != std::string::npos; + const std::string stem = std::filesystem::path(model_path).stem().string(); + const bool moe = stem.size() >= 4 && stem.compare(stem.size() - 4, 4, "-moe") == 0; llama_model_ptr model; llama_model_ptr model_cpu; diff --git a/tests/test-llama-archs.cpp b/tests/test-llama-archs.cpp index 6faa8843decd..3b22dc8921df 100644 --- a/tests/test-llama-archs.cpp +++ b/tests/test-llama-archs.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -176,6 +177,7 @@ static void usage(char ** argv) { LOG(" -o, --out Save generated test models to instead of running backend tests\n"); LOG(" -v Set log verbosity level\n"); LOG(" -b, --backend Run only on the given backend device\n"); + LOG(" --rpc Add RPC servers (comma-separated host:port), must precede -b\n"); LOG(" --kv-shift Check K-shift against a decode at the shifted positions (CPU only)\n"); LOG(" -h, --help Show this help message\n\n"); LOG("Examples:\n"); @@ -300,9 +302,11 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const || arch == LLM_ARCH_BAILINGMOE3 || arch == LLM_ARCH_KIMI_K3 || arch == LLM_ARCH_KIMI_K31 + || arch == LLM_ARCH_RAON1_MINI || arch == LLM_ARCH_MISTRAL4 || arch == LLM_ARCH_MISTRAL_LARGE4 || arch == LLM_ARCH_HY_V4 + || arch == LLM_ARCH_HY_V4_FLASH || arch == LLM_ARCH_XING4_0) { n_embd = 128; n_head = 1; @@ -310,6 +314,9 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const if (arch == LLM_ARCH_MISTRAL_LARGE4) { n_layer = 4; // cover NoPE, shared indexer and KV sharing layers } + if (arch == LLM_ARCH_HY_V4_FLASH) { + n_layer = 4; // dense + MoE across both sparse and sliding attention layers + } } else if (arch == LLM_ARCH_GLM5_NEXT) { // several heads so that -sm tensor can split them and the MLA flash attention has GQA > 1 n_embd = 128; @@ -382,16 +389,19 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const if (arch == LLM_ARCH_PLAMO2 || arch == LLM_ARCH_JAMBA || arch == LLM_ARCH_NEMOTRON_H || arch == LLM_ARCH_NEMOTRON_H_MOE || arch == LLM_ARCH_GRANITE_HYBRID || arch == LLM_ARCH_LFM2 || arch == LLM_ARCH_LFM2MOE || arch == LLM_ARCH_LFM3 || arch == LLM_ARCH_KIMI_LINEAR || arch == LLM_ARCH_BAILINGMOE3 || arch == LLM_ARCH_KIMI_K3 || arch == LLM_ARCH_KIMI_K31 || - arch == LLM_ARCH_GLM5_NEXT + arch == LLM_ARCH_GLM5_NEXT || arch == LLM_ARCH_HY_V4_FLASH || arch == LLM_ARCH_RAON1_MINI ) { GGML_ASSERT(n_layer >= 2); std::vector n_head_per_layer; n_head_per_layer.reserve(n_layer); for (uint32_t il = 0; il < n_layer; il++) { - n_head_per_layer.push_back(il == 1 ? 0 : n_head); + // hy_v4_flash: the odd layers are sliding-window, with twice the heads + n_head_per_layer.push_back(arch == LLM_ARCH_HY_V4_FLASH + ? (il % 2 ? 2*n_head : n_head) + : (il == 1 ? 0 : n_head)); } // GLM5 next KDA heads come from the uniform head count, only head_count_kv is per layer. - if (arch == LLM_ARCH_GLM5_NEXT) { + if (arch == LLM_ARCH_GLM5_NEXT || arch == LLM_ARCH_RAON1_MINI) { ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT, n_head); // the MLA cache holds one latent head for (uint32_t & n : n_head_per_layer) { @@ -400,7 +410,12 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const } else { ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT, n_head_per_layer); } - ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT_KV, n_head_per_layer); + if (arch == LLM_ARCH_HY_V4_FLASH) { + // MLA-as-MQA: one latent KV head on every layer, whatever the query head count + ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT_KV, uint32_t(1)); + } else { + ms.add_kv(LLM_KV_ATTENTION_HEAD_COUNT_KV, n_head_per_layer); + } } else if (arch == LLM_ARCH_METIS16) { // the layer types repeat in every pass std::vector n_head_kv_per_layer; @@ -428,8 +443,10 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const || arch == LLM_ARCH_BAILINGMOE3 || arch == LLM_ARCH_KIMI_K3 || arch == LLM_ARCH_KIMI_K31 + || arch == LLM_ARCH_RAON1_MINI || arch == LLM_ARCH_GLM5_NEXT || arch == LLM_ARCH_HY_V4 + || arch == LLM_ARCH_HY_V4_FLASH || arch == LLM_ARCH_MISTRAL4 || arch == LLM_ARCH_MISTRAL_LARGE4 || arch == LLM_ARCH_XING4_0) { @@ -472,6 +489,7 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const ms.add_kv(LLM_KV_ATTENTION_CLAMP_KQV, 1.0f); ms.add_kv(LLM_KV_ATTENTION_LAYERNORM_EPS, 1e-5f); ms.add_kv(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, 1e-5f); + ms.add_kv(LLM_KV_ATTENTION_LATENT_NORM_RMS_EPS, 1e-6f); ms.add_kv(LLM_KV_ATTENTION_GROUPNORM_EPS, 1e-5f); ms.add_kv(LLM_KV_ATTENTION_GROUPNORM_GROUPS, uint32_t(8)); ms.add_kv(LLM_KV_ATTENTION_Q_LORA_RANK, (arch == LLM_ARCH_DEEPSEEK4 || arch == LLM_ARCH_DEEPSEEK41) ? uint32_t(64) : uint32_t(512)); @@ -496,7 +514,8 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, pattern); } else if (arch == LLM_ARCH_COHERE2MOE || arch == LLM_ARCH_MIMO2 || arch == LLM_ARCH_STEP35 || arch == LLM_ARCH_SPARK2_5 || arch == LLM_ARCH_MUSE_GLIMMER || arch == LLM_ARCH_MUSE_SPARK || arch == LLM_ARCH_GRANITE_SWA || arch == LLM_ARCH_DOTS3NOTE || - arch == LLM_ARCH_KOLIBRI1 || arch == LLM_ARCH_MAPLE || arch == LLM_ARCH_FLINT || arch == LLM_ARCH_BEAM || arch == LLM_ARCH_RICURSIVE || arch == LLM_ARCH_DOMYN_EDGE) { + arch == LLM_ARCH_KOLIBRI1 || arch == LLM_ARCH_MAPLE || arch == LLM_ARCH_FLINT || arch == LLM_ARCH_BEAM || arch == LLM_ARCH_RICURSIVE || arch == LLM_ARCH_DOMYN_EDGE || + arch == LLM_ARCH_HY_V4_FLASH) { std::vector pattern; pattern.reserve(n_layer); for (uint32_t il = 0; il < n_layer; il++) { @@ -532,6 +551,14 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, false); } + if (arch == LLM_ARCH_RAON1_MINI) { + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_SCALE, 1.0f); + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, true); + ms.add_kv(LLM_KV_HYPER_CONNECTION_COUNT, uint32_t(4)); + ms.add_kv(LLM_KV_HYPER_CONNECTION_EPSILON, 1e-5f); + ms.add_kv(LLM_KV_HYPER_CONNECTION_MAGNITUDE, 2.0f); + } + // MSA requires one indexer head per GQA (KV) head, unlike the DSA archs where the // indexer head count is independent of the main attention head count. if (arch == LLM_ARCH_QWEN4EXP || arch == LLM_ARCH_GLM5_NEXT) { @@ -586,6 +613,9 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const // summing to n_rot / 2 (n_rot is 64 in this fixture) if (arch == LLM_ARCH_BAILINGMOE3) { ms.add_kv(LLM_KV_ROPE_DIMENSION_SECTIONS, std::vector({8, 12, 12, 0})); + } else if (arch == LLM_ARCH_HY_V4_FLASH) { + // the published files carry the VL sections, so the text model runs the M-RoPE path + ms.add_kv(LLM_KV_ROPE_DIMENSION_SECTIONS, std::vector({12, 10, 10, 0})); } else { ms.add_kv(LLM_KV_ROPE_DIMENSION_SECTIONS, std::vector({n_embd_head/4, n_embd_head/4, n_embd_head/4, n_embd_head/4})); } @@ -606,6 +636,53 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const ms.add_kv(LLM_KV_ATTENTION_INDEXER_TYPES, indexer_types); } + if (arch == LLM_ARCH_HY_V4_FLASH) { + ms.add_kv(LLM_KV_HYPER_CONNECTION_COUNT, uint32_t(4)); + ms.add_kv(LLM_KV_HYPER_CONNECTION_EPSILON, 1.0e-6f); + ms.add_kv(LLM_KV_HYPER_CONNECTION_MAGNITUDE, 2.0f); + ms.add_kv(LLM_KV_SWIGLU_CLAMP_EXP, 10.0f); + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_SCALE, 1.0f); + ms.add_kv(LLM_KV_EXPERT_WEIGHTS_NORM, true); + ms.add_kv(LLM_KV_ROPE_FREQ_BASE_SWA, 10000.0f); + // the indexer lives on the non-SWA layers, the even ones here + { + std::vector indexer_types; + indexer_types.reserve(n_layer); + for (uint32_t il = 0; il < n_layer; il++) { + indexer_types.push_back(il % 2 ? 0 : 1); + } + ms.add_kv(LLM_KV_ATTENTION_INDEXER_TYPES, indexer_types); + } + ms.add_kv(LLM_KV_ATTENTION_INDEXER_HEAD_COUNT, uint32_t(2)); + ms.add_kv(LLM_KV_ATTENTION_INDEXER_KEY_LENGTH, uint32_t(96)); + + // one Engram module on layer 1, the head offsets are the running sum of the bucket counts + { + // the loader reads the bucket ranges as u64 arrays + const std::vector primes = {7, 11, 13, 17}; + std::vector offsets; + uint64_t base = 0; + for (uint64_t p : primes) { + offsets.push_back(base); + base += p; + } + ms.add_kv(LLM_KV_PLE_LAYERS, std::vector({1})); + ms.add_kv(LLM_KV_PLE_NGRAM_SIZE, uint32_t(3)); + ms.add_kv(LLM_KV_PLE_HEADS_PER_NGRAM, uint32_t(2)); + ms.add_kv(LLM_KV_EMBEDDING_LENGTH_PER_LAYER, uint32_t(32)); + // n_modules * ngram_size multipliers, odd as the reference derives them + ms.add_kv(LLM_KV_PLE_LAYER_MULTIPLIERS, std::vector({3, 5, 7})); + ms.add_kv(LLM_KV_PLE_HEAD_OFFSETS, offsets); + ms.add_kv(LLM_KV_PLE_HEAD_VOCAB_SIZES, primes); + ms.add_kv(LLM_KV_ENGRAM_PAD_TOKEN_ID, uint32_t(1)); + std::vector token_map(n_vocab); + for (uint32_t t = 0; t < n_vocab; t++) { + token_map[t] = (int32_t) t; + } + ms.add_kv(LLM_KV_ENGRAM_TOKEN_MAP, token_map); + } + } + if (arch == LLM_ARCH_MISTRAL_LARGE4) { // layer 3 reads the KV cache of layer 2, both are NoPE ms.add_kv(LLM_KV_ATTENTION_ROPE_PATTERN, std::vector({1, 1, 0, 0})); @@ -756,7 +833,8 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const if (moe) { ms.add_kv(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, n_ff); ms.add_kv(LLM_KV_EXPERT_SHARED_FEED_FORWARD_LENGTH, n_ff / 2); // distinct from n_ff so a saver key-clobber surfaces on reload - ms.add_kv(LLM_KV_EXPERT_LATENT_LENGTH, n_ff); + // a latent width distinct from n_ff_exp catches a transposed routed_down / routed_up + ms.add_kv(LLM_KV_EXPERT_LATENT_LENGTH, arch == LLM_ARCH_HY_V4_FLASH ? uint32_t(64) : n_ff); ms.add_kv(LLM_KV_INTERLEAVE_MOE_LAYER_STEP, uint32_t(2)); // with more experts than a ubatch uses, the copy of the used experts in host memory skips some of them ms.add_kv(LLM_KV_EXPERT_COUNT, uint32_t(host_experts_test(arch) ? 64 : arch == LLM_ARCH_CLOVER_MOE ? 4 : 2)); @@ -1129,6 +1207,7 @@ static bool moe_mandatory(const llm_arch arch) { case LLM_ARCH_HUNYUAN_MOE: case LLM_ARCH_HY_V3: case LLM_ARCH_HY_V4: + case LLM_ARCH_HY_V4_FLASH: case LLM_ARCH_OPENAI_MOE: case LLM_ARCH_LFM2MOE: case LLM_ARCH_SMALLTHINKER: @@ -1143,6 +1222,7 @@ static bool moe_mandatory(const llm_arch arch) { case LLM_ARCH_KIMI_LINEAR: case LLM_ARCH_KIMI_K3: case LLM_ARCH_KIMI_K31: + case LLM_ARCH_RAON1_MINI: case LLM_ARCH_GLM5_NEXT: case LLM_ARCH_STEP35: case LLM_ARCH_MISTRAL4: @@ -1219,7 +1299,7 @@ static bool arch_supported(const llm_arch arch) { // FIXME: these hit scheduler/view-backed-output issues with WebGPU on CI. #ifdef GGML_USE_WEBGPU if (arch == LLM_ARCH_DEEPSEEK32 || arch == LLM_ARCH_GLM_DSA || arch == LLM_ARCH_DOTS3NOTE || arch == LLM_ARCH_QWEN4EXP || - arch == LLM_ARCH_HY_V4) { + arch == LLM_ARCH_HY_V4 || arch == LLM_ARCH_HY_V4_FLASH) { return false; } #endif // GGML_USE_WEBGPU @@ -1904,6 +1984,31 @@ static int test_kv_shift(const std::string & arch_filter, const size_t seed, con return n_failed == 0 ? 0 : 1; } +static bool add_rpc_devices(const std::string & endpoints) { + ggml_backend_reg_t rpc_reg = ggml_backend_reg_by_name("RPC"); + if (rpc_reg == nullptr) { + LOG_ERR("%s: RPC backend not available\n", __func__); + return false; + } + typedef ggml_backend_reg_t (*add_server_t)(const char * endpoint); + auto add_server = (add_server_t) ggml_backend_reg_get_proc_address(rpc_reg, "ggml_backend_rpc_add_server"); + if (add_server == nullptr) { + LOG_ERR("%s: RPC backend has no ggml_backend_rpc_add_server\n", __func__); + return false; + } + std::stringstream ss(endpoints); + std::string endpoint; + while (std::getline(ss, endpoint, ',')) { + ggml_backend_reg_t reg = add_server(endpoint.c_str()); + if (reg == nullptr) { + LOG_ERR("%s: failed to connect to RPC server %s\n", __func__, endpoint.c_str()); + return false; + } + ggml_backend_register(reg); + } + return true; +} + int main(int argc, char ** argv) { // init the logger at max verbosity. filter with a custom callback respecting the user-configure verbosity common_log_set_verbosity_thold(LOG_LEVEL_DEBUG); @@ -1985,6 +2090,16 @@ int main(int argc, char ** argv) { usage(argv); return 1; } + } else if (strcmp(argv[i], "--rpc") == 0) { + if (i + 1 < argc) { + // must precede -b so that the RPC devices can be selected by name + if (!add_rpc_devices(argv[++i])) { + return 1; + } + } else { + usage(argv); + return 1; + } } else if (strcmp(argv[i], "--kv-shift") == 0) { kv_shift = true; } else { diff --git a/tools/mtmd/CMakeLists.txt b/tools/mtmd/CMakeLists.txt index cd9810e6d714..273c5148f418 100644 --- a/tools/mtmd/CMakeLists.txt +++ b/tools/mtmd/CMakeLists.txt @@ -54,6 +54,7 @@ add_library(mtmd models/granite-speech.cpp models/granite4-vision.cpp models/hunyuanvl.cpp + models/hy-v4.cpp models/inkling2v.cpp models/internvl.cpp models/kimivl.cpp diff --git a/tools/mtmd/models/hy-v4.cpp b/tools/mtmd/models/hy-v4.cpp new file mode 100644 index 000000000000..aa8ee8555796 --- /dev/null +++ b/tools/mtmd/models/hy-v4.cpp @@ -0,0 +1,43 @@ +#include "models.h" + +ggml_cgraph * mtmd_graph_hy_v4::build() { + const int merge = hparams.n_merge; + const int pw = n_patches_x; + const int ph = n_patches_y; + + // filled on CPU by mtmd_subcontext::encode(), same as hunyuanvl + ggml_tensor * pos_embd = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, ph * pw); + ggml_set_name(pos_embd, "hunyuanvl_pos_embd"); + ggml_set_input(pos_embd); + + ggml_tensor * inp = build_inp(); + ggml_tensor * cur = build_vit(inp, n_patches, NORM_TYPE_NORMAL, hparams.ffn_op, pos_embd, nullptr); + + cur = build_norm(cur, model.mm_pre_norm_w, nullptr, NORM_TYPE_RMS, eps, -1); + + // [C, W*H] -> [W, H, C] for conv2d + cur = ggml_reshape_3d(ctx0, cur, n_embd, pw, ph); + cur = ggml_permute(ctx0, cur, 2, 0, 1, 3); + cur = ggml_cont(ctx0, cur); + + cur = ggml_conv_2d(ctx0, model.mm_0_w, cur, merge, merge, 0, 0, 1, 1); + cur = ggml_add(ctx0, cur, ggml_reshape_3d(ctx0, model.mm_0_b, 1, 1, model.mm_0_b->ne[0])); + cur = ggml_gelu_erf(ctx0, cur); + cur = ggml_conv_2d(ctx0, model.mm_1_w, cur, 1, 1, 0, 0, 1, 1); + cur = ggml_add(ctx0, cur, ggml_reshape_3d(ctx0, model.mm_1_b, 1, 1, model.mm_1_b->ne[0])); + + const int ow = pw / merge; + const int oh = ph / merge; + const int idim = (int)cur->ne[2]; + + ggml_tensor * nl = ggml_reshape_4d(ctx0, model.image_newline, 1, 1, idim, 1); + nl = ggml_repeat_4d(ctx0, nl, 1, oh, idim, 1); + cur = ggml_concat(ctx0, cur, nl, 0); + + // [OW+1, OH, OC] -> [OC, (OW+1)*OH] + cur = ggml_permute(ctx0, cur, 1, 2, 0, 3); + cur = ggml_cont_2d(ctx0, cur, idim, (ow + 1) * oh); + + ggml_build_forward_expand(gf, cur); + return gf; +} diff --git a/tools/mtmd/models/models.h b/tools/mtmd/models/models.h index c1feef493aab..b47574157090 100644 --- a/tools/mtmd/models/models.h +++ b/tools/mtmd/models/models.h @@ -351,6 +351,11 @@ struct mtmd_graph_hunyuanvl : mtmd_graph { ggml_cgraph * build() override; }; +struct mtmd_graph_hy_v4 : mtmd_graph { + mtmd_graph_hy_v4(mtmd_subcontext * ctx, const mtmd_image_f32 & img) : mtmd_graph(ctx, img) {} + ggml_cgraph * build() override; +}; + struct mtmd_graph_mobilenetv5 : mtmd_graph { mtmd_graph_mobilenetv5(mtmd_subcontext * ctx, const mtmd_image_f32 & img) : mtmd_graph(ctx, img) {} ggml_cgraph * build() override; diff --git a/tools/mtmd/mtmd-graph.cpp b/tools/mtmd/mtmd-graph.cpp index a22f41d372da..576f27b836a0 100644 --- a/tools/mtmd/mtmd-graph.cpp +++ b/tools/mtmd/mtmd-graph.cpp @@ -911,6 +911,10 @@ std::unique_ptr mtmd_get_graph_builder(mtmd_subcontext * ctx, const { builder = std::make_unique(ctx, img); } break; + case PROJECTOR_TYPE_HY_V4_FLASH: + { + builder = std::make_unique(ctx, img); + } break; case PROJECTOR_TYPE_MLP: case PROJECTOR_TYPE_MLP_NORM: case PROJECTOR_TYPE_LDP: diff --git a/tools/mtmd/mtmd-impl.h b/tools/mtmd/mtmd-impl.h index 12bc9728da53..d6b32fae4f8b 100644 --- a/tools/mtmd/mtmd-impl.h +++ b/tools/mtmd/mtmd-impl.h @@ -598,6 +598,7 @@ enum projector_type { PROJECTOR_TYPE_NEMOTRON_V2_VL, PROJECTOR_TYPE_NEMOTRON_OMNI, PROJECTOR_TYPE_HUNYUANVL, + PROJECTOR_TYPE_HY_V4_FLASH, PROJECTOR_TYPE_PARAKEET, PROJECTOR_TYPE_EXAONE4_5, PROJECTOR_TYPE_MINICPMV4_6, @@ -701,6 +702,7 @@ static std::map PROJECTOR_TYPE_NAMES = { { PROJECTOR_TYPE_NEMOTRON_OMNI, "nemotron_omni"}, { PROJECTOR_TYPE_EXAONE4_5, "exaone4_5"}, { PROJECTOR_TYPE_HUNYUANVL, "hunyuanvl"}, + { PROJECTOR_TYPE_HY_V4_FLASH, "hy_v4_flash"}, { PROJECTOR_TYPE_MINICPMV4_6, "minicpmv4_6"}, { PROJECTOR_TYPE_MINICPMV4_7, "minicpmv4_7"}, { PROJECTOR_TYPE_MINICPM_OCR_1_0, "minicpm_ocr_1_0"}, diff --git a/tools/mtmd/mtmd-model.cpp b/tools/mtmd/mtmd-model.cpp index 97dc47598ccc..508dfbe94d81 100644 --- a/tools/mtmd/mtmd-model.cpp +++ b/tools/mtmd/mtmd-model.cpp @@ -1263,6 +1263,23 @@ struct mtmd_model_loader { get_u32(KEY_IMAGE_MAX_PIXELS, hparams.image_max_pixels, false); hparams.set_warmup_n_tokens(32*32); } break; + case PROJECTOR_TYPE_HY_V4_FLASH: + { + hparams.n_merge = 2; + hparams.set_image_resize_algo(RESIZE_ALGO_BICUBIC, true); // HF processor replaces lanczos with bicubic + hparams.image_round_half_even = true; + hparams.image_resize_pad = PAD_NONE; + hparams.ffn_op = FFN_GELU; // tanh gelu (bias_activation_fusion) + log_ffn_op = "gelu"; + get_u32(KEY_SPATIAL_MERGE_SIZE, hparams.n_merge, false); + if (hparams.n_merge == 0) { + throw std::runtime_error(mtmd_format("%s: spatial_merge_size must be > 0\n", __func__)); + } + hparams.set_limit_image_tokens(4, 4096); + get_u32(KEY_IMAGE_MIN_PIXELS, hparams.image_min_pixels, false); + get_u32(KEY_IMAGE_MAX_PIXELS, hparams.image_max_pixels, false); + hparams.set_warmup_n_tokens(46*46); // avoid OOM on warmup + } break; case PROJECTOR_TYPE_LFM2A: case PROJECTOR_TYPE_D1OMNI_A: { @@ -3885,8 +3902,21 @@ struct mtmd_model_loader { model.image_newline = get_tensor(TN_IMAGE_NEWLINE); model.view_seperator = get_tensor(TN_IMAGE_SEPERATOR, false); // the position embedding is resampled on the host as F32 - if (!model.position_embeddings || model.position_embeddings->type != GGML_TYPE_F32) { - throw std::runtime_error(mtmd_format("%s: HunyuanVL requires an F32 %s\n", __func__, mtmd_format(TN_POS_EMBD, prefix).c_str())); + if (!model.position_embeddings || model.position_embeddings->type != GGML_TYPE_F32 || !ggml_is_matrix(model.position_embeddings) || model.position_embeddings->ne[0] != hparams.n_embd) { + throw std::runtime_error(mtmd_format("%s: HunyuanVL requires a 2D F32 %s\n", __func__, mtmd_format(TN_POS_EMBD, prefix).c_str())); + } + } break; + case PROJECTOR_TYPE_HY_V4_FLASH: + { + model.mm_0_w = get_tensor(mtmd_format(TN_LLAVA_PROJ, 0, "weight")); + model.mm_0_b = get_tensor(mtmd_format(TN_LLAVA_PROJ, 0, "bias")); + model.mm_1_w = get_tensor(mtmd_format(TN_LLAVA_PROJ, 2, "weight")); + model.mm_1_b = get_tensor(mtmd_format(TN_LLAVA_PROJ, 2, "bias")); + model.mm_pre_norm_w = get_tensor(mtmd_format(TN_MM_PRE_NORM, "weight")); + model.image_newline = get_tensor(TN_IMAGE_NEWLINE); + if (!model.position_embeddings || model.position_embeddings->type != GGML_TYPE_F32 || !ggml_is_matrix(model.position_embeddings) || model.position_embeddings->ne[0] != hparams.n_embd) { + throw std::runtime_error(mtmd_format("%s: %s requires a 2D F32 %s\n", __func__, + PROJECTOR_TYPE_NAMES[model.proj_type].c_str(), mtmd_format(TN_POS_EMBD, prefix).c_str())); } } break; case PROJECTOR_TYPE_JANUS_PRO: @@ -4690,6 +4720,8 @@ int mtmd_model::n_output_tokens_x(const mtmd_image_f32 * img) const { case PROJECTOR_TYPE_MUSE_GLIMMER: case PROJECTOR_TYPE_LFM3VL: return (img->nx() / params.patch_size) / 2; + case PROJECTOR_TYPE_HY_V4_FLASH: + return (img->nx() / params.patch_size) / params.n_merge + 1; // +1 for newline case PROJECTOR_TYPE_STEP3VL: case PROJECTOR_TYPE_MINICPMV4_6: case PROJECTOR_TYPE_MINICPMV4_7: @@ -4725,6 +4757,8 @@ int mtmd_model::n_output_tokens_y(const mtmd_image_f32 * img) const { case PROJECTOR_TYPE_MUSE_GLIMMER: case PROJECTOR_TYPE_LFM3VL: return (img->ny() / params.patch_size) / 2; + case PROJECTOR_TYPE_HY_V4_FLASH: + return (img->ny() / params.patch_size) / params.n_merge; case PROJECTOR_TYPE_STEP3VL: case PROJECTOR_TYPE_MINICPMV4_6: case PROJECTOR_TYPE_MINICPMV4_7: @@ -4998,6 +5032,13 @@ int mtmd_model::n_output_tokens(const mtmd_image_f32 * img) const { int oh = (img->ny() / patch_size) / merge; n_patches = (ow + 1) * oh + 2; } break; + case PROJECTOR_TYPE_HY_V4_FLASH: + { + int merge = hparams.n_merge; + int ow = (img->nx() / patch_size) / merge; + int oh = (img->ny() / patch_size) / merge; + n_patches = (ow + 1) * oh; + } break; case PROJECTOR_TYPE_DEEPSEEKOCR2: { // 1024 global view -> 256 query tokens + 1 view separator = 257; @@ -5245,6 +5286,8 @@ int mtmd_model::n_mmproj_embd() const { return mm_2_w->ne[1]; case PROJECTOR_TYPE_HUNYUANVL: return mm_model_proj->ne[1]; + case PROJECTOR_TYPE_HY_V4_FLASH: + return mm_1_w->ne[3]; case PROJECTOR_TYPE_COGVLM: return mm_4h_to_h_w->ne[1]; case PROJECTOR_TYPE_DEEPSEEKOCR: diff --git a/tools/mtmd/mtmd-subcontext.cpp b/tools/mtmd/mtmd-subcontext.cpp index 078f154c7939..640950c5c832 100644 --- a/tools/mtmd/mtmd-subcontext.cpp +++ b/tools/mtmd/mtmd-subcontext.cpp @@ -2111,13 +2111,12 @@ bool mtmd_subcontext::encode(mtmd_subctx_encode_params * params) { } } break; case PROJECTOR_TYPE_HUNYUANVL: + case PROJECTOR_TYPE_HY_V4_FLASH: { - // Compute the HunyuanVL 2D position embedding on CPU (with the - // custom sf=(target+0.1)/n_grid bilinear sampling that the - // reference implementation uses) and upload it to the graph - // input declared in mtmd_graph_hunyuanvl::build(). + // resize position embedding on CPU, using bilinear with sf=(target+0.1)/n_grid GGML_ASSERT(model.position_embeddings != nullptr); ggml_tensor * src_t = model.position_embeddings; + GGML_ASSERT(ggml_is_matrix(src_t) && src_t->type == GGML_TYPE_F32); const int64_t n_embd = src_t->ne[0]; const int64_t n_pos = src_t->ne[1]; // = n_grid * n_grid const int n_grid = (int)std::lround(std::sqrt((double)n_pos)); diff --git a/tools/mtmd/mtmd.cpp b/tools/mtmd/mtmd.cpp index fdac762ac98c..e99d25792acc 100644 --- a/tools/mtmd/mtmd.cpp +++ b/tools/mtmd/mtmd.cpp @@ -1392,6 +1392,15 @@ struct mtmd_context { img_end = "<|hy_place▁holder▁no▁101|>"; image_preproc = std::make_unique(models.v.get()); } break; + case PROJECTOR_TYPE_HY_V4_FLASH: + { + if (text_model && pos_type != MTMD_POS_TYPE_MROPE) { + throw std::runtime_error("the hy_v4_flash projector needs a text model with M-RoPE rope sections"); + } + img_beg = "<|hy_image▁start:opensource|>"; + img_end = "<|hy_image▁end:opensource|>"; + image_preproc = std::make_unique(models.v.get()); + } break; case PROJECTOR_TYPE_EXAONE4_5: { // ... (image embeddings) ... diff --git a/tools/quantize/quantize.cpp b/tools/quantize/quantize.cpp index d58695196301..ef9740ce1c73 100644 --- a/tools/quantize/quantize.cpp +++ b/tools/quantize/quantize.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include #include diff --git a/tools/server/README.md b/tools/server/README.md index e854ea2ea877..62cc57551d76 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -2671,6 +2671,12 @@ You can specify default preferences for Llama Chat using `--ui-config **Note:** The old flags `--webui-config` and `--webui-config-file` are deprecated but still work as aliases. You may find available preferences in [settings-keys.ts](../ui/src/lib/constants/settings-keys.ts). diff --git a/tools/server/tests/unit/test_spec_methods.py b/tools/server/tests/unit/test_spec_methods.py index ef6407115506..f5fb719d340e 100644 --- a/tools/server/tests/unit/test_spec_methods.py +++ b/tools/server/tests/unit/test_spec_methods.py @@ -36,7 +36,7 @@ class SpecCase: draft=None, n_max=3, min_accept_rate=0.6040, - min_accept_len=2.7766, + min_accept_len=2.65, ), SpecCase( name="dflash", @@ -45,7 +45,7 @@ class SpecCase: draft="dflash-Qwen3-4B-Q4_K_M.gguf", n_max=7, min_accept_rate=0.1404, - min_accept_len=2.1687, + min_accept_len=2.10, ), SpecCase( name="dspark", @@ -54,7 +54,7 @@ class SpecCase: draft="dspark-Qwen3-4B-Q4_K_M.gguf", n_max=7, min_accept_rate=0.2767, - min_accept_len=3.1246, + min_accept_len=3.05, ), SpecCase( name="eagle3", @@ -63,7 +63,7 @@ class SpecCase: draft="eagle3-Qwen3-4B-Q8_0.gguf", n_max=3, min_accept_rate=0.2006, - min_accept_len=1.5757, + min_accept_len=1.50, ), # Nightly floors retain the earlier three-point rate and 0.2 length margins. SpecCase( @@ -73,7 +73,7 @@ class SpecCase: draft="dflash2-Qwen3.8-27B-Q8_0.gguf", n_max=7, min_accept_rate=0.5180, - min_accept_len=4.5414, + min_accept_len=4.50, ), SpecCase( name="lilicorr", @@ -82,7 +82,7 @@ class SpecCase: draft="lilicorr-NVIDIA-Nemotron-3.5-Bolt-74B-A9B-24GB-NVFP4.gguf", n_max=7, min_accept_rate=0.6399, - min_accept_len=5.4444, + min_accept_len=5.40, ), ] diff --git a/ui/README.md b/ui/README.md index 3d6521b58ac4..6c7acf476e4c 100644 --- a/ui/README.md +++ b/ui/README.md @@ -7,7 +7,8 @@ ui/ ├── lib/ │ ├── 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 +│ ├── harness/ @ggml-org/llama-harness: the agentic loop, headless +│ └── demo/ @ggml-org/llama-demo: scripted demo videos for PRs and docs └── apps/ └── chat/ Llama Chat, the chat app that llama-server serves ``` @@ -20,12 +21,15 @@ ui/ (`@ggml-org/llama-voice/svelte`). Apps in this repo compile its sources too. It is not published to npm yet. - [`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. +- [`lib/demo`](lib/demo/README.md) records scripted demo videos of the apps for PRs and docs, and renders them on the + Llama brand. It is Node TypeScript that an app adds as a local `file:` dependency and imports by name, with the app's own + Playwright; it is private, not published to npm. - [`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`, `lib/voice` or `lib/harness`. +checking and testing `apps/chat` needs no install in `lib/ui`, `lib/voice`, `lib/harness` or `lib/demo`. 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, diff --git a/ui/apps/chat/.env.example b/ui/apps/chat/.env.example index 269e65278648..8941a8a9094c 100644 --- a/ui/apps/chat/.env.example +++ b/ui/apps/chat/.env.example @@ -17,7 +17,16 @@ VITE_PUBLIC_SERVER_ORIGIN='http://localhost:8033' # DEMO_SERVER_ORIGIN='http://localhost:9931' # DEMO_LLAMA_SERVER='../../../build/bin/llama-server' # DEMO_COLOR_SCHEME='light' +# Also start a Storybook for story demos: ui (Llama UI) or chat (Llama Chat) +# DEMO_STORYBOOK='ui' +# DEMO_STORYBOOK_PORT='6007' # Device pixel ratio demos render and record at (1440x900 viewport) # DEMO_SCALE='2' +# 0 records the plain screencast instead of the branded render +# DEMO_POLISH='1' +# Ground of the render: day | night | light | dark | sand (default: day, night for a dark recording) +# DEMO_POLISH_GROUND='day' +# A Llama logo card: start | end | both (default: none) +# DEMO_POLISH_LOGO='end' # Longer side of the GIF preview, in pixels; it shrinks further to stay under 5 MB # DEMO_PREVIEW_WIDTH='800' diff --git a/ui/apps/chat/.storybook/preview.ts b/ui/apps/chat/.storybook/preview.ts index 47c884fd0f99..45fe7809f6a6 100644 --- a/ui/apps/chat/.storybook/preview.ts +++ b/ui/apps/chat/.storybook/preview.ts @@ -51,6 +51,7 @@ const preview: Preview = { [ 'Foundations', ['Safe areas', 'Brand'], + 'Mobile', 'Chat', [ 'ChatScreen', @@ -65,7 +66,7 @@ const preview: Preview = { 'MCP', 'Navigation', 'Settings', - ['DialogSettingsChat', 'Navigation', 'Sections'], + ['DialogSettingsChat', 'SettingsSheet', 'Navigation', 'Sections'], 'Dialogs', 'Forms', 'Actions', diff --git a/ui/apps/chat/AGENTS.md b/ui/apps/chat/AGENTS.md index 0b4884de3167..31a21755ab75 100644 --- a/ui/apps/chat/AGENTS.md +++ b/ui/apps/chat/AGENTS.md @@ -3,7 +3,8 @@ 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. +- **Demos, checks and docs media:** [skills/ui-demo](../../../skills/ui-demo/SKILL.md) records a PR's demo video, turns its flow into an e2e check and captures docs videos and screenshots, for Llama Chat and Llama UI alike. +- **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//`. How the app works on a phone (the sidebar's keys, the sheets and the pages each pushes) is written up in `tests/stories/mobile`, titled `Llama Chat/Mobile/Flows`: update it when a sheet gains or loses a page. 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. - **Releases:** `@ggml-org/llama-chat` and `@ggml-org/llama-ui` are versioned by hand and published by CI when a new version reaches `master` (see [Releases](../../README.md#releases)). Bump a version only when asked to release, never as a side effect of a change; Chat's version and its alias's (`alias/package.json`) always move together. - **Components:** the `SKILL.md` next to a component folder (such as [src/lib/components/app/SKILL.md](src/lib/components/app/SKILL.md)) holds that folder's conventions. diff --git a/ui/apps/chat/DESIGN.md b/ui/apps/chat/DESIGN.md index fc624676d487..cda28f00db3b 100644 --- a/ui/apps/chat/DESIGN.md +++ b/ui/apps/chat/DESIGN.md @@ -1097,6 +1097,16 @@ screens. Status lamps, avatars and the round icon buttons in the chat form are f shade, which makes a field. Unlike the other `matte-glass` surfaces it does not blur: it already sits on glass, and a second backdrop blur re-paints the panel's fill behind it and turns the group visibly lighter, whatever its own fill. +- **Inset lists:** a phone's sheets (settings, add to chat, the model picker) list their + options the native way. `inset-list` is an inset group of rows, `inset-list-row` a row a + finger tall (3rem) that is tappable as a whole, and `inset-list-row-body` its label and value, + whose top border is the divider: it starts at the label, past the row's icon, and the first + row has none. `inset-list-title` sits above a group and `inset-list-caption` below it. Inside + a drawer the groups take `--sheet-group-radius` (1.25rem, the chat form's single-row radius) in place of the card radius, to sit + with the sheet's own 2.5rem corners. A sheet's close or back key is `sheet-key`, a round key + 1rem from the top and from the side, with the title centered on its middle. Build them with Llama UI's + `InsetList`, `InsetListRow`, `InsetListSplitRow`, `SheetHeader` and `SheetPages` + (`@ggml-org/llama-ui/app/sheets`) rather than with the utilities by hand. - **Selected rows:** `selected-row-surface` marks the row a sidebar list is on: a conversation, a project or a top action, on desktop and on a phone. It is a 5% tint of the text colour, under hover's 10%, with the inset group's edge and shade, so the selected row diff --git a/ui/apps/chat/README.md b/ui/apps/chat/README.md index ec4b38b5796b..639587467160 100644 --- a/ui/apps/chat/README.md +++ b/ui/apps/chat/README.md @@ -19,14 +19,15 @@ It works with a llama-server in either mode: **MODEL** (one model) or **ROUTER** Llama Chat is published to npm as [`@ggml-org/llama-chat`](https://www.npmjs.com/package/@ggml-org/llama-chat), with [`llama-chat`](https://www.npmjs.com/package/llama-chat) as its short name. It serves the prebuilt app as static files on localhost, or writes them to a folder for any static file server (see [Self-hosting](#self-hosting)); it brings no server and no models of its own. It needs Node.js 20 or later. ```bash -npx @ggml-org/llama-chat --server http://localhost:8080 # serve it on http://127.0.0.1:3000 for that llama-server +npx @ggml-org/llama-chat # serve it on http://127.0.0.1:3000 for llama-server on :9931 +npx @ggml-org/llama-chat --server http://localhost:8080 # for a llama-server elsewhere npx llama-chat --host 0.0.0.0 --no-open # by its short name, reachable from other devices npx llama-chat build # write the static app to ./llama-chat instead ``` | Flag | Default | What it does | | --------------------------------- | ----------- | ------------------------------------------------------------------------------------------- | -| `--server ` | | The llama-server the app talks to, e.g. `http://localhost:8080`; also for `build` | +| `--server ` | `:9931` | The llama-server the app talks to, e.g. `http://localhost:8080`; also for `build` | | `--port ` | `3000` | Fixed, so the origin, and the chats the browser stores under it, stay the same between runs | | `--host ` | `127.0.0.1` | `0.0.0.0` to open it to the LAN | | `--open` / `--no-open` | open | Opens the default browser once it listens | @@ -46,7 +47,7 @@ The app reaches the llama-server on its own origin by default (llama-server serv { "server": "http://localhost:8080" } ``` -`npx llama-chat build --server ` writes that file, and `npx llama-chat --server ` answers it without one. The app reads it on every start, past its caches, so a host can change it without a new build. That llama-server needs `--cors-origins` for the app's address when it restricts origins. +`npx llama-chat build --server ` writes that file, and `npx llama-chat` answers it without one, with `--server ` or else llama-server's default port on the host the page is opened from. The app reads it on every start, past its caches, so a host can change it without a new build. That llama-server needs `--cors-origins` for the app's address when it restricts origins. ## Features @@ -55,7 +56,7 @@ The app reaches the llama-server on its own origin by default (llama-server serv - **Rendering** - Markdown (GFM), code highlighting, KaTeX math and Mermaid diagrams - **Models** - in ROUTER mode, a selector and a models manager: load and unload, downloads, Discover from the Hugging Face Hub, favorites and hidden models - **Tools** - built-in browser tools, llama-server's tools and MCP servers, each behind a permission prompt -- **Everywhere** - light and dark themes, phone layouts, installable as a PWA, keyboard shortcuts (`Ctrl/Cmd+K` search, `Shift+Ctrl/Cmd+O` new chat, `Ctrl/Cmd+B` sidebar) +- **Everywhere** - light and dark themes, phone layouts, installable as a PWA, keyboard shortcuts (`Ctrl/Cmd+K` search, `Shift+Ctrl/Cmd+O` new chat, `Ctrl/Cmd+B` sidebar, `Esc` stop the reply) ## Development diff --git a/ui/apps/chat/alias/package.json b/ui/apps/chat/alias/package.json index 08662397324d..cf9582d80ea6 100644 --- a/ui/apps/chat/alias/package.json +++ b/ui/apps/chat/alias/package.json @@ -1,6 +1,6 @@ { "name": "llama-chat", - "version": "0.2.0", + "version": "0.3.1", "description": "npx llama-chat: runs Llama Chat, the chat app for llama.cpp. Same as npx @ggml-org/llama-chat.", "keywords": [ "llama.cpp", @@ -28,6 +28,6 @@ "node": ">=20" }, "dependencies": { - "@ggml-org/llama-chat": "0.2.0" + "@ggml-org/llama-chat": "0.3.1" } } diff --git a/ui/apps/chat/cli/server.js b/ui/apps/chat/cli/server.js index 95aa60373fbd..8778ed84c4a6 100644 --- a/ui/apps/chat/cli/server.js +++ b/ui/apps/chat/cli/server.js @@ -25,7 +25,9 @@ export const DEFAULTS = Object.freeze({ // the folder `build` writes to, in the current directory out: 'llama-chat', // fixed, so the origin, and the chats the browser stores under it, stay the same between runs - port: 3000 + port: 3000, + // llama-server's own default port, on the host the app is opened from, when no --server + serverPort: 9931 }); // The same caching llama-server applies to the UI it embeds (tools/server/server-http.cpp): @@ -77,7 +79,8 @@ when it restricts origins. Options: --server the llama-server the app talks to, e.g. http://localhost:8080 - (also for build; default: the address the app is served on) + (default: port ${DEFAULTS.serverPort} of the host the page is opened on; + for build: the address the app is served on) --port port to listen on (default: ${DEFAULTS.port}) --host address to listen on, 0.0.0.0 for the LAN (default: ${DEFAULTS.host}) --open open the browser once it listens (default) @@ -90,6 +93,7 @@ Build options: --force write into a folder that is not empty Examples: + npx @ggml-org/llama-chat npx @ggml-org/llama-chat --server http://localhost:8080 npx @ggml-org/llama-chat --host 0.0.0.0 --port 3000 --no-open npx @ggml-org/llama-chat build --out ./public --server https://llm.example.com`; @@ -258,8 +262,19 @@ function configJson(server) { } /** - * The HTTP server: the files of `dist`, read-only. With `server`, it answers config.json - * itself, so the app talks to that llama-server instead of this address. + * The llama-server on its default port, on the host a request was made to: localhost when + * opened here, the same LAN or Tailscale address when opened from another device. + * @param {http.IncomingMessage} req + */ +function defaultServer(req) { + const { hostname } = new URL(`http://${req.headers.host ?? 'localhost'}`); + + return `http://${hostname}:${DEFAULTS.serverPort}`; +} + +/** + * The HTTP server: the files of `dist`, read-only. It answers config.json itself, so the app + * talks to `server`, or by default to llama-server's default port, instead of this address. * @param {{ distDir?: string, server?: string }} [options] */ export function createChatServer({ distDir = DIST_DIR, server = '' } = {}) { @@ -275,8 +290,8 @@ export function createChatServer({ distDir = DIST_DIR, server = '' } = {}) { return; } - if (server && pathname === CONFIG_PATH) { - const body = configJson(server); + if (pathname === CONFIG_PATH) { + const body = configJson(server || defaultServer(req)); res.writeHead(200, { 'Cache-Control': CACHE_REVALIDATE, @@ -429,7 +444,9 @@ export async function main(argv) { console.log(`Llama Chat ${packageVersion()} on ${url}`); - if (options.server) console.log(`Talking to llama-server on ${options.server}`); + console.log( + `Talking to llama-server on ${options.server || `port ${DEFAULTS.serverPort}, pick another with --server`}` + ); console.log( `If llama-server restricts origins (tools or MCP on), start it with --cors-origins ${url.slice(0, -1)}` diff --git a/ui/apps/chat/demo/README.md b/ui/apps/chat/demo/README.md index e929626870d0..f633d0841769 100644 --- a/ui/apps/chat/demo/README.md +++ b/ui/apps/chat/demo/README.md @@ -1,57 +1,50 @@ -# Demo videos +# Llama Chat demo videos -Scripted Playwright walkthroughs of the UI, exported as mp4 with an animated GIF preview, for pull requests and documentation. The harness lives here; the demo scripts don't: +Llama Chat's fixtures for the demo harness in [`ui/lib/demo`](../../../lib/demo/README.md), which records, renders and publishes the videos. Setup, PR and docs recording, the `demo.*` API and the render are described there; this folder sets the scene for Chat. -- **PR demos** live in the PR description, as a `ts demo` code block. -- **Docs demos** live in the storage target, under `scripts/docs/`. - -``` +```text demo/ -├── cli.ts demo:pr, demo:docs and demo:traces -├── storage.ts storage targets (hf://, file://) -├── helpers.ts `test` with a `demo` fixture: cursor, captions, human-like timing -├── recorder.ts screencast recording and mp4 export -├── fixtures/ fixture MCP servers, seeded settings and demo conversations -└── videos/ output (git-ignored) +├── cli.ts demo:pr, demo:docs and demo:traces +├── helpers.ts `test` with Chat's fixtures and the `demo` fixture +├── playwright.config.ts the servers: fixture MCP servers, llama-server, vite and Storybook +├── fixtures/ fixture MCP servers, seeded settings, demo conversations, a mocked llama-server +└── videos/ output (git-ignored) ``` -## Setup - -### Tools +| Command | Does | +| ------------------------------------ | ----------------------------------------------------------------- | +| `npm run demo:record -- demo/` | records `demo/.demo.ts` (git-ignored) into `demo/videos/` | +| `npm run demo:pr -- ` | records the PR's `ts demo` block and writes its `## Demo` section | +| `npm run demo:docs` | records the docs scripts from `DEMO_STORAGE` | +| `npm run demo:traces` | writes the built-in traces to `demo/traces/`, and pushes them | +| `npm run demo:codegen` | opens Playwright codegen against `:5180` for a first draft | -| Tool | Used for | -| ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Node 22.18+ | runs `demo/cli.ts` directly (TypeScript type stripping) | -| `npx playwright install chromium` | the browser demos record in, with its sandbox on | -| `ffmpeg` | mp4 encoding and the GIF preview | -| `gh`, logged in | reads the PR description and writes the `## Demo` section, so you need edit rights on the PR | -| `hf`, logged in with a write token (`hf auth login`) | uploads to the bucket and the traces dataset | -| `llama-server` | `build/bin/llama-server`, or one already running at `DEMO_SERVER_ORIGIN` (default `:9931`). It runs in router mode, so demos can pick any model in the local cache; scripts that send messages need at least one. | +Settings come from `ui/apps/chat/.env` (see `.env.example`). -`gh` is only needed for `demo:pr`, and `hf` only with the bucket or dataset below. Without them, the video stays in `demo/videos/`. +## Setting the scene -Videos are recorded through Chromium's screencast at `DEMO_SCALE` (2x by default, so 2880x1800) and 60 fps, starting once the page has settled. +Scripts get `test` and `expect` from `helpers.ts` without importing them. Use `test.use({ settings, startPath })` to seed other settings or start on another route, and `chats: ` to add empty conversations to the library. -### Hugging Face bucket (videos, previews, scripts) +### A mocked llama-server -The bucket must be public, since GitHub loads the preview from it: +`test.use({ mockServer: { models: ['org/Model-GGUF:Q4_K_M'], reply: 'A **Markdown** reply' } })` answers llama-server's endpoints in the browser (`fixtures/llama-server.ts`): the model list, props, model loading, tools and a streamed reply. Nothing reaches the server and no model loads, so a demo that sends a message looks the same on every machine. `tests/e2e` checks call `mockLlamaServer(page)` directly, since the e2e build runs without a server. -```bash -hf buckets create /llama-ui-demos -``` +### Storybook stories -Then set it in `ui/apps/chat/.env` (see `.env.example`): +`test.use({ story: 'ui-forms-switch--default' })` records a Storybook story (the id from its `?path=/story/` URL) instead of Llama Chat, from the Storybook that `DEMO_STORYBOOK` adds to the servers: `ui` for Llama UI (`ui/lib/ui`), `chat` for Llama Chat's. It runs on `DEMO_STORYBOOK_PORT` (default `:6007`). A small component reads better at a smaller `viewport` than zoomed in. ```bash -DEMO_STORAGE='hf://buckets//llama-ui-demos' -DEMO_STORAGE_PUBLIC_URL='https://huggingface.co/buckets//llama-ui-demos/resolve' +DEMO_STORYBOOK=ui npm run demo:record -- demo/ ``` -Layout: `videos/pr//.{mp4,gif,demo.ts}`, `videos/docs/.{mp4,gif}` and `scripts/docs/*.demo.ts` (the docs scripts). Without `DEMO_STORAGE_PUBLIC_URL`, videos are uploaded but not linked in the PR. `DEMO_STORAGE='file:///some/dir'` stores them in a local folder instead. +### Conversations -### Hugging Face dataset (conversations, optional) +Demos that need existing chats import them with `test.use({ traces: ['long-chat'] })`, through Settings > Data before the video starts. Traces use the export format (llama.app JSONL), so the Hub shows them as Llama traces: -Only needed for demos that import conversations other than the built-in ones, or to publish the built-in ones with `npm run demo:traces`. It can be private: it is read with your `hf` login. +- `fixtures/traces.ts` generates the built-in ones: `long-chat` (36 tall exchanges) and `agentic-debugging` (long reasoning, shell output and code blocks). +- Any other name is downloaded as `.jsonl` from `DEMO_TRACES_DATASET`, e.g. an exported conversation uploaded there. + +The dataset is only needed for other conversations, or to publish the built-in ones with `npm run demo:traces`. It can be private: it is read with your `hf` login. ```bash hf repos create /llama-ui-demo-traces --repo-type dataset --private @@ -61,73 +54,6 @@ hf repos create /llama-ui-demo-traces --repo-type dataset --private DEMO_TRACES_DATASET='/llama-ui-demo-traces' ``` -### Other storage - -Only Hugging Face buckets and `file://` folders are supported for now. S3, R2 or similar would be one more class in `storage.ts` (`upload` and `downloadDir`) plus the matching `DEMO_STORAGE_PUBLIC_URL`. - -## Recording a pull request - -Add the script to the PR description: - -````md -
-Demo script - -```ts demo -test('demo', async ({ demo, page }) => { - await demo.click(page.getByRole('button', { exact: true, name: 'Settings' })); - await demo.caption('What this shows'); -}); -``` - -
-```` - -Then run: - -```bash -npm run demo:pr -- 31303 -``` - -A PR by someone else runs its code and demo script on your machine, with your `gh` and `hf` logins, so `demo:pr` refuses it until you've read its diff and demo block and pass the head commit you read: `npm run demo:pr -- 31303 --trust `. If the PR gets new commits, it refuses again. - -It checks out the PR head in a temporary worktree, records the script against it, uploads `videos/pr//.{mp4,gif,demo.ts}` and adds or updates a `## Demo` section in the PR description with the preview linking to the video. - -A large PR can show its changes in several shorter videos: each `test()` in the block is recorded as its own video (`-1.mp4`, `-2.mp4`, ...), and the `## Demo` section shows their previews in a table, each headed by its test's title: up to four portrait (phone) videos to a row, or two landscape ones. Helpers and `test.use` at the top of the block are shared by all of them. - -````ts -test('Header and safe areas', async ({ demo, page }) => { - // ... -}); - -test('Sidebar gestures', async ({ demo, page }) => { - // ... -}); -``` GitHub has no API for attachments, so for an inline player drag `demo/videos/pr-.mp4` into the description instead. - -## Recording docs - -```bash -npm run demo:docs -```` - -Records every `scripts/docs/*.demo.ts` from the storage target and uploads `videos/docs/.{mp4,gif}`. - -## Writing a demo - -Scripts get `test` and `expect` from `helpers.ts` without importing them. `demo.click`, `demo.hover` and `demo.type` glide a visible cursor to the target before acting, with timing varied like a person's (seeded per demo, so re-takes match); `demo.scroll` turns the mouse wheel over a target; `demo.zoom` pinches in on a control or a point to show a detail too small to read in the frame, holds, and pinches back out (with the fingertips drawn on a touch device); `demo.caption` shows a caption at the top of the frame. For voice input, `demo.microphone()` gives the page a microphone that hears nothing but `demo.speak(text)`, which reads the text in a synthetic voice (macOS `say`) and shows it as a caption, since the video has no sound. Use `test.use({ settings, startPath })` to seed other settings or start on another route. - -## Conversations - -Demos that need existing chats import them with `test.use({ traces: ['long-chat'] })`, through Settings > Import/Export before the video starts. Traces use the export format (llama.app JSONL), so the Hub shows them as Llama traces: - -- `fixtures/traces.ts` generates the built-in ones: `long-chat` (36 tall exchanges) and `agentic-debugging` (long reasoning, shell output and code blocks). -- Any other name is downloaded as `.jsonl` from `DEMO_TRACES_DATASET`, e.g. an exported conversation uploaded there. - -`npm run demo:traces` writes the built-in traces to `demo/traces/` and pushes them to `DEMO_TRACES_DATASET`. - -## Trying a script locally - -To try a script locally, put it in `demo/` as `.demo.ts`, importing from `./helpers.ts`, and run `npm run demo:record -- demo/`. `npm run demo:codegen` opens Playwright codegen against `:5180` for a first draft. +## Servers -The config starts, or reuses when already running, the fixture MCP servers on `:8765`, `llama-server` on `:9931` (router mode, `--tools all`) and the UI's vite dev server. +The config starts, or reuses when already running, the fixture MCP servers on `:8765`, `llama-server` on `:9931` (`build/bin/llama-server` in router mode with `--tools all`, so demos can pick any model in the local cache), the UI's vite dev server and, with `DEMO_STORYBOOK`, a Storybook. Scripts that send messages to the real server need at least one model; `mockServer` needs none. diff --git a/ui/apps/chat/demo/cli.ts b/ui/apps/chat/demo/cli.ts index 775c361d6319..363e6afd1db6 100644 --- a/ui/apps/chat/demo/cli.ts +++ b/ui/apps/chat/demo/cli.ts @@ -1,5 +1,5 @@ /** - * Records demo videos for pull requests and docs. + * Records Llama Chat's demo videos with the harness in ui/lib/demo: * * node demo/cli.ts pr record the ```ts demo block from a PR description, a video per test * (--trust to record someone else's PR at that head commit) @@ -10,357 +10,13 @@ */ import { DEMO_TRACES, generateTrace } from './fixtures/traces.ts'; -import { type DemoStorage, getDemoStorage, getPublicUrl } from './storage.ts'; +import { runDemoCli } from '@ggml-org/llama-demo/cli'; import { execFileSync } from 'node:child_process'; -import { createHash } from 'node:crypto'; -import { - existsSync, - mkdirSync, - readdirSync, - readFileSync, - rmSync, - statSync, - symlinkSync, - writeFileSync -} from 'node:fs'; -import { createServer } from 'node:net'; -import { tmpdir } from 'node:os'; -import { basename, join, relative, resolve } from 'node:path'; +import { mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; const DEMO_DIR = import.meta.dirname; -const UI_DIR = resolve(DEMO_DIR, '..'); -const RUNS_DIR = join(DEMO_DIR, '.runs'); -const VIDEOS_DIR = join(DEMO_DIR, 'videos'); const TRACES_DIR = join(DEMO_DIR, 'traces'); -const DEMO_BLOCK = /```(?:ts|typescript)[ \t]+demo[ \t]*\r?\n([\s\S]*?)```/; -const HELPERS_IMPORT = /^import\s[^;]*from\s+['"][^'"]*helpers(?:\.ts)?['"];?\s*$/gm; -const SECTION_START = ''; -const SECTION_END = ''; -/** GitHub's image proxy refuses larger images, so a bigger preview shows as a broken image. */ -const PREVIEW_MAX_BYTES = 5 * 1024 * 1024; -const envFile = join(UI_DIR, '.env'); - -if (existsSync(envFile)) process.loadEnvFile(envFile); - -const REPO = process.env.DEMO_GITHUB_REPO ?? 'ggml-org/llama.cpp'; - -function run( - cmd: string, - args: string[], - opts: { cwd?: string; env?: NodeJS.ProcessEnv } = {} -): string { - return execFileSync(cmd, args, { - cwd: opts.cwd ?? UI_DIR, - encoding: 'utf8', - env: opts.env - }).trim(); -} - -/** Writes a demo script into .runs/, importing the harness helpers. */ -function writeDemoScript(name: string, source: string): string { - const file = join(RUNS_DIR, `${name}.demo.ts`); - const helpers = relative(RUNS_DIR, join(DEMO_DIR, 'helpers.ts')); - const body = source.replace(HELPERS_IMPORT, '').trim(); - - mkdirSync(RUNS_DIR, { recursive: true }); - writeFileSync(file, `import { expect, test } from './${helpers}';\n\n${body}\n`); - - return file; -} - -async function freePort(): Promise { - return new Promise((done, fail) => { - const server = createServer(); - - server.once('error', fail); - server.listen(0, () => { - const { port } = server.address() as { port: number }; - - server.close(() => done(port)); - }); - }); -} - -/** A video recorded from one `test()` of a script. */ -interface Video { - mp4: string; - title: string; -} - -/** Records the given scripts; returns a video for each of their tests, in order. */ -async function record(scripts: string[], uiDir = UI_DIR): Promise { - const port = await freePort(); - const manifests = scripts.map((s) => join(VIDEOS_DIR, `${basename(s, '.demo.ts')}.videos.jsonl`)); - - for (const manifest of manifests) rmSync(manifest, { force: true }); - - execFileSync( - 'npx', - [ - 'playwright', - 'test', - '--config=demo/playwright.config.ts', - ...scripts.map((s) => relative(UI_DIR, s)) - ], - { - cwd: UI_DIR, - env: { ...process.env, DEMO_UI_DIR: uiDir, DEMO_UI_PORT: String(port) }, - stdio: 'inherit' - } - ); - - // helpers.ts lists each video it encodes in the script's manifest - return manifests.flatMap((manifest) => - readFileSync(manifest, 'utf8') - .trim() - .split('\n') - .map((line) => JSON.parse(line) as Video) - ); -} - -/** - * Animated GIF preview that GitHub renders inline, its longer side DEMO_PREVIEW_WIDTH (so a - * phone's portrait video is that tall), shrunk until it fits under PREVIEW_MAX_BYTES. - */ -function makePreview(mp4: string): string { - const gif = mp4.replace(/\.mp4$/, '.gif'); - - for (let side = Number(process.env.DEMO_PREVIEW_WIDTH ?? 800); ; side = Math.round(side * 0.8)) { - execFileSync('ffmpeg', [ - '-y', - '-loglevel', - 'error', - '-i', - mp4, - '-vf', - `fps=10,scale='if(gt(iw,ih),${side},-2)':'if(gt(iw,ih),-2,${side})':flags=lanczos,split[a][b];[a]palettegen=stats_mode=diff[p];[b][p]paletteuse=dither=bayer:bayer_scale=5:diff_mode=rectangle`, - '-loop', - '0', - gif - ]); - - if (statSync(gif).size <= PREVIEW_MAX_BYTES || side < 320) return gif; - } -} - -function upload(storage: DemoStorage, files: Record): void { - for (const [key, file] of Object.entries(files)) { - storage.upload(file, key); - console.log(`uploaded ${key}`); - } -} - -/** - * Public URL with a content hash, so a re-recorded file at the same key gets a new - * URL: GitHub's image proxy caches previews by URL. - */ -function versionedUrl(key: string, file: string): null | string { - const url = getPublicUrl(key); - const version = createHash('sha1').update(readFileSync(file)).digest('hex').slice(0, 10); - - return url && `${url}?v=${version}`; -} - -/** Whether a video is taller than wide, like a phone's. */ -function isPortrait(mp4: string): boolean { - const [width, height] = run('ffprobe', [ - '-v', - 'error', - '-select_streams', - 'v:0', - '-show_entries', - 'stream=width,height', - '-of', - 'csv=p=0', - mp4 - ]) - .split(',') - .map(Number); - - return height > width; -} - -/** - * One preview, or a table of them when the script has several tests, each headed by its - * test's title: up to four portrait videos to a row, or two landscape ones, so each stays - * large enough to read. - */ -function demoSection( - links: { gif: string; mp4: string; title: string }[], - sha: string, - columns: number -): string { - const preview = ({ gif, mp4, title }: (typeof links)[number]) => - `[![${title.replace(/[[\]|]/g, '')}](${gif})](${mp4})`; - const cell = (text: string) => text.replace(/\|/g, '\\|'); - const rows = Array.from({ length: Math.ceil(links.length / columns) }, (_, i) => - links.slice(i * columns, (i + 1) * columns) - ); - const pad = (cells: string[]) => [...cells, ...Array(columns - cells.length).fill(' ')]; - const body = - links.length === 1 - ? [preview({ ...links[0], title: 'Demo' })] - : rows.flatMap((row, i) => [ - // a table has one header row, so later rows title their videos in bold - `| ${pad(row.map((l) => (i === 0 ? cell(l.title) : `**${cell(l.title)}**`))).join(' | ')} |`, - ...(i === 0 ? [`|${Array(columns).fill('---').join('|')}|`] : []), - `| ${pad(row.map(preview)).join(' | ')} |` - ]); - const note = - links.length === 1 ? 'the preview for the full video' : 'a preview for its full video'; - - return [ - SECTION_START, - ...body, - '', - `Recorded at ${sha.slice(0, 10)}; click ${note}.`, - SECTION_END - ].join('\n'); -} - -/** Replaces the managed demo section, or adds a `## Demo` section before the details. */ -function withDemoSection(body: string, section: string): string { - const start = body.indexOf(SECTION_START); - const end = body.indexOf(SECTION_END); - - if (start !== -1 && end > start) { - return body.slice(0, start) + section + body.slice(end + SECTION_END.length); - } - - const block = `## Demo\n\n${section}\n\n`; - const anchor = body.search(/^## (Additional information|Requirements)\b/m); - - return anchor === -1 - ? `${body.trimEnd()}\n\n${block}` - : body.slice(0, anchor) + block + body.slice(anchor); -} - -async function recordPr(number: string, trustedSha?: string): Promise { - const pr = JSON.parse( - run('gh', ['pr', 'view', number, '--repo', REPO, '--json', 'author,body,headRefOid']) - ) as { author: { login: string }; body: string; headRefOid: string }; - const source = DEMO_BLOCK.exec(pr.body)?.[1]; - - if (!source) throw new Error(`PR #${number} has no \`\`\`ts demo block in its description`); - - const sha = pr.headRefOid; - - // the PR's code and demo script run on this machine, with the gh and hf logins, - // so someone else's PR only runs at a head commit you've read and passed to --trust - if (pr.author.login !== run('gh', ['api', 'user', '--jq', '.login'])) { - if (!trustedSha) { - throw new Error( - `PR #${number} is by ${pr.author.login}, and recording it runs its code here: ` + - `read its diff and demo block, then run again with --trust ${sha.slice(0, 10)}` - ); - } - - if (trustedSha.length < 7 || !sha.startsWith(trustedSha)) { - throw new Error(`PR #${number} head is ${sha.slice(0, 10)}, not the trusted ${trustedSha}`); - } - } - - const worktree = join(tmpdir(), `llama-ui-demo-pr-${number}`); - - run('git', ['fetch', '--no-tags', `https://github.com/${REPO}.git`, `pull/${number}/head`]); - - if (run('git', ['rev-parse', 'FETCH_HEAD']) !== sha) { - throw new Error(`PR #${number} head moved while fetching, run again`); - } - - rmSync(worktree, { force: true, recursive: true }); - run('git', ['worktree', 'prune']); - run('git', ['worktree', 'add', '--detach', worktree, sha]); - symlinkSync(join(UI_DIR, 'node_modules'), join(worktree, 'ui/apps/chat/node_modules')); - - const name = `pr-${number}`; - const script = writeDemoScript(name, source); - - try { - const videos = (await record([script], join(worktree, 'ui/apps/chat'))).map((video) => ({ - ...video, - gif: makePreview(video.mp4) - })); - const storage = getDemoStorage(); - - for (const { gif, mp4 } of videos) console.log(`\nvideo: ${mp4}\npreview: ${gif}`); - - if (!storage) { - console.log('DEMO_STORAGE is not set: drag the mp4 into the PR description.'); - - return; - } - - const prefix = `videos/pr/${number}/${sha.slice(0, 10)}`; - // a script with several tests gets -1.mp4, -2.mp4 and so on - const keys = videos.map((_, i) => (videos.length === 1 ? prefix : `${prefix}-${i + 1}`)); - - upload(storage, { [`${prefix}.demo.ts`]: script }); - videos.forEach(({ gif, mp4 }, i) => { - upload(storage, { [`${keys[i]}.gif`]: gif, [`${keys[i]}.mp4`]: mp4 }); - }); - - if (!getPublicUrl(prefix)) { - console.log('DEMO_STORAGE_PUBLIC_URL is not set: not linking the video in the PR.'); - - return; - } - - const links = videos.map(({ gif, mp4, title }, i) => ({ - gif: versionedUrl(`${keys[i]}.gif`, gif) ?? '', - mp4: versionedUrl(`${keys[i]}.mp4`, mp4) ?? '', - title - })); - - execFileSync('gh', ['pr', 'edit', number, '--repo', REPO, '--body-file', '-'], { - cwd: UI_DIR, - input: withDemoSection( - pr.body, - demoSection(links, sha, Math.min(links.length, isPortrait(videos[0].mp4) ? 4 : 2)) - ), - stdio: ['pipe', 'inherit', 'inherit'] - }); - console.log(`linked the demo in https://github.com/${REPO}/pull/${number}`); - } finally { - rmSync(script, { force: true }); - run('git', ['worktree', 'remove', '--force', worktree]); - } -} - -async function recordDocs(): Promise { - const storage = getDemoStorage(); - - if (!storage) throw new Error('DEMO_STORAGE is not set: docs demo scripts are read from it'); - - const downloaded = join(RUNS_DIR, 'docs-source'); - - rmSync(downloaded, { force: true, recursive: true }); - - if (!storage.downloadDir('scripts/docs', downloaded)) { - throw new Error('no scripts/docs/*.demo.ts in DEMO_STORAGE'); - } - - const scripts = readdirSync(downloaded) - .filter((f) => f.endsWith('.demo.ts')) - .map((f) => - writeDemoScript(basename(f, '.demo.ts'), readFileSync(join(downloaded, f), 'utf8')) - ); - - try { - const videos = await record(scripts); - - for (const { mp4 } of videos) { - const name = basename(mp4, '.mp4'); - - upload(storage, { - [`videos/docs/${name}.gif`]: makePreview(mp4), - [`videos/docs/${name}.mp4`]: mp4 - }); - } - } finally { - rmSync(RUNS_DIR, { force: true, recursive: true }); - } -} /** Writes the built-in traces to demo/traces/ and uploads them to the traces dataset. */ function writeTraces(): void { @@ -396,16 +52,10 @@ function writeTraces(): void { ); } -const [command, arg, ...flags] = process.argv.slice(2); -const trustIndex = flags.indexOf('--trust'); - -if (command === 'pr' && arg) { - await recordPr(arg, trustIndex === -1 ? undefined : flags[trustIndex + 1]); -} else if (command === 'docs') { - await recordDocs(); -} else if (command === 'traces') { - writeTraces(); -} else { - console.error('usage: node demo/cli.ts pr [--trust ] | docs | traces'); - process.exit(1); -} +await runDemoCli({ + commands: { traces: writeTraces }, + demoDir: DEMO_DIR, + dir: resolve(DEMO_DIR, '..'), + // Chat builds Llama UI from source, and DEMO_STORYBOOK=ui runs its Storybook + linkNodeModules: ['../../lib/ui'] +}); diff --git a/ui/apps/chat/demo/fixtures/llama-server.ts b/ui/apps/chat/demo/fixtures/llama-server.ts new file mode 100644 index 000000000000..6cc985fcea25 --- /dev/null +++ b/ui/apps/chat/demo/fixtures/llama-server.ts @@ -0,0 +1,63 @@ +/** + * A canned llama-server for demos and e2e checks that should not need a real one, or a model: + * routes its endpoints in the browser, so nothing reaches a server and no model loads. + */ + +import type { BrowserContext, Page } from '@playwright/test'; + +export interface MockServerOptions { + /** Model ids the router lists, all loaded. */ + models?: string[]; + /** The assistant's reply to every message, streamed a word per chunk. */ + reply?: string; +} + +function completionStream(reply: string): string { + const words = reply.match(/\S+\s*/g) ?? []; + const chunk = (delta: object, finish: null | string = null) => + `data: ${JSON.stringify({ choices: [{ delta, finish_reason: finish, index: 0 }], object: 'chat.completion.chunk' })}\n\n`; + + return [ + chunk({ role: 'assistant' }), + ...words.map((word) => chunk({ content: word })), + chunk({}, 'stop'), + 'data: [DONE]\n\n' + ].join(''); +} + +/** Call before the page opens; a demo sets `test.use({ mockServer: {...} })` instead. */ +export async function mockLlamaServer( + target: BrowserContext | Page, + { + models = ['ggml-org/gemma-3-4b-it-GGUF:Q4_K_M'], + reply = 'Hello! How can I help?' + }: MockServerOptions = {} +): Promise { + const data = models.map((id) => ({ + id, + object: 'model', + owned_by: 'llamacpp', + status: { value: 'loaded' } + })); + + await target.route(/\/props(\?|$)/, (route) => + route.fulfill({ + json: { build_info: 'mock', model_path: 'none', role: 'router', ui_settings: {} } + }) + ); + await target.route(/\/(v1\/)?models(\?|$)/, (route) => + route.fulfill({ json: { data, object: 'list' } }) + ); + await target.route(/\/models\/(load|unload)$/, (route) => + route.fulfill({ json: { success: true } }) + ); + await target.route(/\/models\/sse$/, (route) => route.abort()); + await target.route(/\/tools(\?|$)/, (route) => route.fulfill({ json: [] })); + await target.route(/\/v1\/streams\/lookup$/, (route) => route.fulfill({ status: 404 })); + await target.route(/\/v1\/chat\/completions$/, (route) => + route.fulfill({ + body: completionStream(reply), + headers: { 'content-type': 'text/event-stream' } + }) + ); +} diff --git a/ui/apps/chat/demo/helpers.ts b/ui/apps/chat/demo/helpers.ts index 6712d5c7b887..28c199558736 100644 --- a/ui/apps/chat/demo/helpers.ts +++ b/ui/apps/chat/demo/helpers.ts @@ -1,115 +1,21 @@ +/** + * Llama Chat's demo fixtures on the harness in ui/lib/demo: settings, conversations and a mocked + * llama-server set the scene, or a Storybook story stands in for the app. + */ + import { demoMcpServerSettings } from './fixtures/demo-config.ts'; +import { mockLlamaServer, type MockServerOptions } from './fixtures/llama-server.ts'; import { generateTrace } from './fixtures/traces.ts'; -import { ScreencastRecorder } from './recorder.ts'; -import { type CDPSession, type Locator, type Page, test as base } from '@playwright/test'; +import { Demo, prepareDemoPage, recordDemo } from '@ggml-org/llama-demo'; +import { type Locator, type Page, test as base, type TestInfo } from '@playwright/test'; import { execFileSync } from 'node:child_process'; -import { - appendFileSync, - mkdirSync, - mkdtempSync, - readFileSync, - rmSync, - writeFileSync -} from 'node:fs'; -import { tmpdir } from 'node:os'; -import { basename, join, resolve } from 'node:path'; +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; const VIDEOS_DIR = resolve(import.meta.dirname, 'videos'); +const BRAND_DIR = resolve(import.meta.dirname, '../node_modules/@ggml-org/llama-brand'); /** How long a demo waits for the app to be ready before it starts recording. */ const APP_READY_TIMEOUT_MS = 90000; -/** How far below the viewport's top a pinch has to start for Chromium to zoom at all. */ -const ZOOM_TOP_INSET_PX = 64; - -/** - * Draws a fake cursor and click ripples, since recorded videos don't include - * the OS pointer, and a fingertip per touch, so a pinch shows as two fingers. - * Runs in the page via addInitScript. - */ -function installCursorOverlay(): void { - const mount = () => { - const style = document.createElement('style'); - - style.textContent = ` - #demo-cursor { position: fixed; top: 0; left: 0; z-index: 2147483647; pointer-events: none; - width: 22px; height: 22px; margin: -3px 0 0 -3px; transition: transform 80ms ease-out; } - #demo-cursor.down { transform: scale(0.85); } - .demo-ripple { position: fixed; z-index: 2147483646; pointer-events: none; width: 36px; height: 36px; - margin: -18px 0 0 -18px; border-radius: 50%; background: rgba(59, 130, 246, 0.35); - animation: demo-ripple 450ms ease-out forwards; } - @keyframes demo-ripple { from { transform: scale(0.3); opacity: 1; } to { transform: scale(1.4); opacity: 0; } } - #demo-caption { position: fixed; left: 50%; top: 72px; z-index: 2147483647; pointer-events: none; - transform: translate(-50%, -8px); opacity: 0; transition: opacity 200ms ease, transform 200ms ease; - max-width: 80%; padding: 10px 18px; border-radius: 10px; background: rgba(17, 17, 17, 0.88); - color: #fff; font: 500 18px/1.4 system-ui, sans-serif; text-align: center; } - #demo-caption.visible { opacity: 1; transform: translate(-50%, 0); } - .demo-finger { position: fixed; z-index: 2147483646; pointer-events: none; width: 40px; height: 40px; - margin: -20px 0 0 -20px; border-radius: 50%; background: rgba(59, 130, 246, 0.3); - border: 2px solid rgba(59, 130, 246, 0.55); transition: opacity 200ms ease; } - `; - document.head.appendChild(style); - - const cursor = document.createElement('div'); - - cursor.id = 'demo-cursor'; - cursor.innerHTML = ``; - document.documentElement.appendChild(cursor); - - const caption = document.createElement('div'); - - caption.id = 'demo-caption'; - document.documentElement.appendChild(caption); - - document.addEventListener( - 'mousemove', - (e) => (cursor.style.translate = `${e.clientX}px ${e.clientY}px`), - true - ); - document.addEventListener( - 'mousedown', - (e) => { - cursor.classList.add('down'); - const ripple = document.createElement('div'); - - ripple.className = 'demo-ripple'; - ripple.style.left = `${e.clientX}px`; - ripple.style.top = `${e.clientY}px`; - document.documentElement.appendChild(ripple); - setTimeout(() => ripple.remove(), 500); - }, - true - ); - document.addEventListener('mouseup', () => cursor.classList.remove('down'), true); - - const fingers: HTMLDivElement[] = []; - const placeFingers = (e: TouchEvent) => { - Array.from(e.touches).forEach((touch, i) => { - const finger = (fingers[i] ??= Object.assign(document.createElement('div'), { - className: 'demo-finger' - })); - - finger.style.left = `${touch.clientX}px`; - finger.style.top = `${touch.clientY}px`; - finger.style.opacity = '1'; - document.documentElement.appendChild(finger); - }); - fingers.slice(e.touches.length).forEach((finger) => (finger.style.opacity = '0')); - }; - - for (const type of ['touchstart', 'touchmove', 'touchend', 'touchcancel']) { - document.addEventListener(type, placeFingers as EventListener, { - capture: true, - passive: true - }); - } - }; - - if (document.readyState === 'loading') { - document.addEventListener('DOMContentLoaded', mount); - } else { - mount(); - } -} /** Seeds UI settings once per demo, so later reloads keep what the demo changed. */ function seedSettings(config: Record): void { @@ -120,337 +26,20 @@ function seedSettings(config: Record): void { } } -/** - * Swaps the page's microphone for one that hears only what `window.demoSpeak` plays into it, - * silence otherwise. Chromium's fake capture device crashes the page, so voice input is - * recorded with this instead. Runs in the page. - */ -function installFakeMicrophone(): void { - const context = new AudioContext(); - const output = context.createMediaStreamDestination(); - - navigator.mediaDevices.getUserMedia = async (constraints) => { - if (!constraints?.audio || constraints.video) { - throw new DOMException('demo: only the microphone is faked', 'NotSupportedError'); - } - - await context.resume(); - - // each opening gets its own tracks, so a recording that stops them leaves the source on - return new MediaStream(output.stream.getAudioTracks().map((track) => track.clone())); - }; - - Object.assign(window, { - demoSpeak: async (wavBase64: string) => { - const bytes = Uint8Array.from(atob(wavBase64), (c) => c.charCodeAt(0)); - const source = context.createBufferSource(); - - source.buffer = await context.decodeAudioData(bytes.buffer); - source.connect(output); - await context.resume(); - await new Promise((done) => { - source.onended = done; - source.start(); - }); - } - }); -} - -/** `text` read by a synthetic voice, as a base64 WAV. Uses macOS `say`. */ -function synthesizeSpeech(text: string, voice: string): string { - const dir = mkdtempSync(join(tmpdir(), 'demo-speech-')); - const file = join(dir, 'speech.wav'); - - try { - execFileSync('say', [ - '-v', - voice, - '-o', - file, - '--file-format=WAVE', - '--data-format=LEI16@24000', - text - ]); - - return readFileSync(file).toString('base64'); - } catch (error) { - throw new Error(`demo: speak() needs macOS \`say\` with the voice ${voice}`, { - cause: error - }); - } finally { - rmSync(dir, { force: true, recursive: true }); - } -} - -/** Seeded randomness, so a demo moves the same way on every recording. */ -function createRandom(seed: string): () => number { - let state = [...seed].reduce((h, c) => Math.imul(h ^ c.charCodeAt(0), 2654435761), 1); - - return () => { - state = (state + 0x6d2b79f5) | 0; - - let t = Math.imul(state ^ (state >>> 15), 1 | state); - - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; -} - -const easeInOut = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2); - -/** - * Drives the page like a person: the cursor glides along a slight arc with - * Fitts-like durations, settles briefly before pressing, and typing and pauses - * vary a little. - */ -export class Demo { - private cdp: CDPSession | undefined; - private readonly page: Page; - private readonly random: () => number; - private x = 0; - private y = 0; - - /** Shows a caption at the top of the frame for `ms`, clear of the chat form. */ - async caption(text: string, ms = 2200): Promise { - await this.showCaption(text); - await this.page.waitForTimeout(ms); - await this.hideCaption(); - } - - async click(target: Locator, ms = 400): Promise { - await this.moveTo(target); - await this.page.waitForTimeout(this.between(80, 160)); - await this.page.mouse.down(); - await this.page.waitForTimeout(this.between(50, 90)); - await this.page.mouse.up(); - await this.pause(ms); - } - - constructor(page: Page, seed: string) { - this.page = page; - this.random = createRandom(seed); - - const viewport = page.viewportSize(); - - this.x = (viewport?.width ?? 0) / 2; - this.y = (viewport?.height ?? 0) / 2; - } - - async hover(target: Locator, ms = 350): Promise { - await this.moveTo(target); - await this.pause(ms); - } - - /** - * Gives the page a microphone that hears only what `speak` says, and allows the page to - * use it. Call it before the microphone is first used. - */ - async microphone(): Promise { - await this.page.context().grantPermissions(['microphone']); - await this.page.evaluate(installFakeMicrophone); - } - - /** Glides the cursor to a point near the center of `target`. */ - async moveTo(target: Locator): Promise { - await target.scrollIntoViewIfNeeded(); - const box = await target.boundingBox(); - - if (!box) throw new Error(`demo: ${target} has no bounding box`); - - const x = box.x + box.width * this.between(0.4, 0.6); - const y = box.y + box.height * this.between(0.4, 0.6); - const dx = x - this.x; - const dy = y - this.y; - const distance = Math.hypot(dx, dy); - const duration = 110 + 55 * Math.log2(distance / 40 + 1); - // bow the path a little to one side, like a wrist turning - const bow = distance * this.between(-0.08, 0.08); - const fromX = this.x; - const fromY = this.y; - const started = Date.now(); - - for (;;) { - const t = Math.min((Date.now() - started) / duration, 1); - const p = easeInOut(t); - const arc = Math.sin(Math.PI * p) * bow; - - this.x = fromX + dx * p - (dy / (distance || 1)) * arc; - this.y = fromY + dy * p + (dx / (distance || 1)) * arc; - await this.page.mouse.move(this.x, this.y); - - if (t === 1) break; - - await this.page.waitForTimeout(8); - } - } - - /** Waits about `ms`, varied by up to 15% so pauses don't feel metronomic. */ - async pause(ms = 800): Promise { - await this.page.waitForTimeout(ms * this.between(0.85, 1.15)); - } - - async press(key: string, ms = 600): Promise { - await this.page.keyboard.press(key); - await this.pause(ms); - } - - /** Scrolls the wheel over `target` by `dy` pixels (negative scrolls up), in small steps like a trackpad. */ - async scroll(target: Locator, dy: number, ms = 500): Promise { - await this.moveTo(target); - - const step = Math.sign(dy) * 40; - - for (let done = 0; Math.abs(done) < Math.abs(dy); done += step) { - await this.page.mouse.wheel(0, step); - await this.page.waitForTimeout(16); - } - - await this.pause(ms); - } - - /** - * Says `text` into the microphone from `microphone` in a synthetic voice (macOS `say`), and - * returns once it is said. The words show as a caption, since the video has no sound. - */ - async speak(text: string, voice = 'Samantha', ms = 400): Promise { - const wav = synthesizeSpeech(text, voice); - - await this.showCaption(`“${text}”`); - await this.page.evaluate( - (base64) => - (window as unknown as { demoSpeak(wav: string): Promise }).demoSpeak(base64), - wav - ); - await this.hideCaption(); - await this.pause(ms); - } - - /** Types quickly with uneven key timing, a little slower after spaces and punctuation. */ - async type(target: Locator, text: string, ms = 500): Promise { - await this.click(target, 200); - - for (const char of text) { - await this.page.keyboard.type(char); - await this.page.waitForTimeout( - this.between(15, 45) + (/[\s.,!?]/.test(char) ? this.between(20, 60) : 0) - ); - } - - await this.pause(ms); - } - - /** - * Pinches in on `target`, a control or a point in the viewport, holds about `ms`, and pinches - * back out to 1x: a two-finger zoom onto a detail too small to read in the frame. On a touch - * device the fingertips show. - */ - async zoom(target: Locator | { x: number; y: number }, scale = 2.5, ms = 1400): Promise { - const point = 'x' in target ? target : await this.center(target); - // a pinch anchored in the viewport's top band does not zoom at all - const at = { x: point.x, y: Math.max(point.y, ZOOM_TOP_INSET_PX) }; - const viewport = this.page.viewportSize() ?? { height: 0, width: 0 }; - const middle = { x: viewport.width / 2, y: viewport.height / 2 }; - - await this.pinch(at, scale, 1400); - - // One near the bottom edge overshoots its ratio, and a pinch there again misses too. A small - // pinch from the middle evens it out, drawing the detail toward the middle, so it stays in view - const reached = await this.pageScale(); - - if (Math.abs(reached / scale - 1) > 0.03) await this.pinch(middle, scale / reached, 1400); - - await this.liftFingers(); - await this.pause(ms); - - // back to exactly 1x, which the next gesture needs, in one quick pinch from the middle of - // the viewport, and another for what is left when one lands short - for (let tries = 0; ; tries++) { - const current = await this.pageScale(); - - if (current <= 1.001) break; - - if (tries === 4) throw new Error(`demo: zoom stuck at ${current.toFixed(3)}x`); - - await this.pinch(middle, 1 / current, 1800); - } - - await this.liftFingers(); - await this.pause(200); - } - - private between(min: number, max: number): number { - return min + (max - min) * this.random(); - } - - private async center(target: Locator): Promise<{ x: number; y: number }> { - const box = await target.boundingBox(); - - if (!box) throw new Error(`demo: ${target} has no bounding box`); - - return { x: box.x + box.width / 2, y: box.y + box.height / 2 }; - } - - private async hideCaption(): Promise { - await this.page.evaluate(() => - document.getElementById('demo-caption')?.classList.remove('visible') - ); - await this.page.waitForTimeout(250); - } - - /** A pinch that reaches the screen's edge can end without its last touchend reaching the page. */ - private async liftFingers(): Promise { - await this.page.evaluate(() => - document - .querySelectorAll('.demo-finger') - .forEach((finger) => (finger.style.opacity = '0')) - ); - } - - private pageScale(): Promise { - return this.page.evaluate(() => window.visualViewport?.scale ?? 1); - } - - /** - * A two-finger pinch by `factor` around `at`, in viewport pixels. While zoomed in, the gesture - * reads its position in page-scale units, so it is divided by the scale the page is at. - */ - private async pinch(at: { x: number; y: number }, factor: number, speed: number): Promise { - const cdp = await this.session(); - const current = await this.pageScale(); - - await cdp.send('Input.synthesizePinchGesture', { - gestureSourceType: 'touch', - relativeSpeed: speed, - scaleFactor: factor, - x: at.x / current, - y: at.y / current - }); - } - - private async session(): Promise { - this.cdp ??= await this.page.context().newCDPSession(this.page); - - return this.cdp; - } - - private async showCaption(text: string): Promise { - await this.page.evaluate((t) => { - const el = document.getElementById('demo-caption'); - - if (!el) return; - - el.textContent = t; - el.classList.add('visible'); - }, text); - } -} - interface DemoOptions { + /** Empty conversations added to the library before the demo starts, e.g. to fill a list. */ + chats: number; + /** Answers llama-server's endpoints in the browser instead (fixtures/llama-server.ts), so no model loads. */ + mockServer: MockServerOptions | null; /** Path the demo starts from. */ startPath: string; /** Extra UI settings merged into the seeded config. */ settings: Record; + /** + * Storybook story id (`?path=/story/`) recorded instead of Llama Chat, from the Storybook + * that DEMO_STORYBOOK starts: `ui` (Llama UI) or `chat` (Llama Chat). + */ + story: string; /** * Conversations imported before the demo starts: built-in traces from * fixtures/traces.ts, or `.jsonl` files from DEMO_TRACES_DATASET. @@ -478,8 +67,8 @@ function loadTrace(name: string, dir: string): string { return readFileSync(join(dir, `${name}.jsonl`), 'utf8'); } -/** Imports conversations through Settings > Import/Export, like a user would. */ -async function importTraces(page: Page, file: string): Promise { +/** Imports conversations through Settings > Data, like a user would. */ +export async function importTraces(page: Page, file: string): Promise { // the expanded sidebar adds the shortcut to the name const settings = page.getByRole('button', { name: /^Settings(\s|$)/ }).first(); const reachable = (target: Locator) => @@ -515,7 +104,12 @@ async function importTraces(page: Page, file: string): Promise { const scope = (await page.getByRole('dialog').count()) > 0 ? page.getByRole('dialog') : page; - await scope.getByText('Import/Export', { exact: true }).filter({ visible: true }).click(); + // the section is Data in the regrouped settings, Import/Export before + await scope + .getByText(/^(Data|Import\/Export)$/) + .filter({ visible: true }) + .first() + .click(); const chooser = page.waitForEvent('filechooser'); @@ -544,83 +138,144 @@ async function importTraces(page: Page, file: string): Promise { }); } -export const test = base.extend({ - demo: async ({ page }, use, testInfo) => { - await use(new Demo(page, `${testInfo.file}:${testInfo.title}`)); - }, - page: async ({ page, settings, startPath, traces }, use, testInfo) => { - await page.addInitScript(installCursorOverlay); - await page.addInitScript(seedSettings, { - mcpServers: JSON.stringify(demoMcpServerSettings()), - ...settings - }); - - if (traces.length > 0) { - const dir = testInfo.outputPath('traces'); - const file = join(dir, 'import.jsonl'); - - mkdirSync(dir, { recursive: true }); - writeFileSync(file, traces.map((name) => loadTrace(name, dir)).join('\n')); - await page.goto('/'); - await page - .getByRole('textbox', { name: 'Type a message...' }) - .waitFor({ timeout: APP_READY_TIMEOUT_MS }); - await importTraces(page, file); +/** The app's IndexedDB database and its conversations store, which a demo seeds. */ +const DEMO_DATABASE = 'LlamaUi'; +const DEMO_CONVERSATIONS_STORE = 'conversations'; +const HOUR_MS = 3_600_000; +/** Names of the seeded conversations, repeated when a demo asks for more. */ +const DEMO_CHAT_NAMES = [ + 'Plan a trip to Lisbon', + 'Explain tail recursion', + 'Draft a polite follow-up', + 'Summarize this changelog', + 'Regex for ISO dates', + 'Ideas for a weekend project', + 'Debug a flaky test', + 'Meal plan for the week' +]; + +/** Adds `count` empty conversations to the library, so a list has enough chats to fold. */ +async function seedChats(page: Page, count: number): Promise { + await page.goto('/'); + await page + .getByRole('textbox', { name: 'Type a message...' }) + .waitFor({ timeout: APP_READY_TIMEOUT_MS }); + await page.evaluate( + async ({ database, hourMs, names, store, total }) => { + const request = indexedDB.open(database); + const db = await new Promise((resolve, reject) => { + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); + const tx = db.transaction(store, 'readwrite'); + + for (let i = 0; i < total; i++) { + tx.objectStore(store).put({ + currNode: null, + id: `demo-chat-${i}`, + lastModified: Date.now() - i * hourMs, + name: names[i % names.length] + }); + } + + await new Promise((resolve) => (tx.oncomplete = resolve)); + db.close(); + }, + { + database: DEMO_DATABASE, + hourMs: HOUR_MS, + names: DEMO_CHAT_NAMES, + store: DEMO_CONVERSATIONS_STORE, + total: count } + ); +} - await page.goto(startPath); +/** Seeds settings, imports the traces, adds the chats and opens `startPath` in Llama Chat. */ +async function openChat( + page: Page, + settings: Record, + startPath: string, + traces: string[], + chats: number, + testInfo: TestInfo +): Promise { + await page.addInitScript(seedSettings, { + mcpServers: JSON.stringify(demoMcpServerSettings()), + ...settings + }); - // a hash route after the import doesn't reload, which the conversations list needs - if (traces.length > 0) await page.reload(); + if (traces.length > 0) { + const dir = testInfo.outputPath('traces'); + const file = join(dir, 'import.jsonl'); - // a fresh checkout's dev server optimizes its dependencies on the first load and reloads the - // page, which can take well past an action's timeout; the recording has not started yet + mkdirSync(dir, { recursive: true }); + writeFileSync(file, traces.map((name) => loadTrace(name, dir)).join('\n')); + await page.goto('/'); await page .getByRole('textbox', { name: 'Type a message...' }) .waitFor({ timeout: APP_READY_TIMEOUT_MS }); + await importTraces(page, file); + } + + if (chats > 0) await seedChats(page, chats); - const viewport = page.viewportSize(); + await page.goto(startPath); - if (viewport) await page.mouse.move(viewport.width / 2, viewport.height / 2); + // a hash route after the import doesn't reload, which the conversations list needs + if (traces.length > 0 || chats > 0) await page.reload(); - // let MCP connections and fonts settle before the recording starts - await page.waitForTimeout(1500); + // a fresh checkout's dev server optimizes its dependencies on the first load and reloads the + // page, which can take well past an action's timeout; the recording has not started yet + await page + .getByRole('textbox', { name: 'Type a message...' }) + .waitFor({ timeout: APP_READY_TIMEOUT_MS }); +} + +export const test = base.extend({ + chats: [0, { option: true }], + demo: async ({ page }, use, testInfo) => { + await use(new Demo(page, `${testInfo.file}:${testInfo.title}`)); + }, + mockServer: [null, { option: true }], - const recorder = new ScreencastRecorder(testInfo.outputPath('frames')); + page: async ( + { chats, colorScheme, mockServer, page, settings, startPath, story, traces }, + use, + testInfo + ) => { + await prepareDemoPage(page, testInfo); - await recorder.start(page); - await use(page); - await recorder.stop(); - await page.close(); + if (story && !process.env.DEMO_STORYBOOK) { + throw new Error('demo: a story demo needs DEMO_STORYBOOK=ui (Llama UI) or chat (Llama Chat)'); + } - if (testInfo.status !== testInfo.expectedStatus) return; + if (story) { + await page.goto( + `http://localhost:${process.env.DEMO_STORYBOOK_PORT}/iframe.html?id=${story}&viewMode=story` + ); + await page.locator('#storybook-root > *').first().waitFor({ timeout: APP_READY_TIMEOUT_MS }); + } else { + if (mockServer) await mockLlamaServer(page, mockServer); - const file = basename(testInfo.file).replace(/\.demo\.ts$/, ''); - const name = testInfo.title === 'demo' ? file : `${file}--${slugify(testInfo.title)}`; - const mp4 = resolve(VIDEOS_DIR, `${name}.mp4`); + await openChat(page, settings, startPath, traces, chats, testInfo); + } - mkdirSync(VIDEOS_DIR, { recursive: true }); - recorder.encode(mp4); - // the CLI reads which videos a script made, in order, with their titles - appendFileSync( - resolve(VIDEOS_DIR, `${file}.videos.jsonl`), - `${JSON.stringify({ mp4, title: testInfo.title })}\n` + await recordDemo( + page, + testInfo, + { brandDir: BRAND_DIR, dark: colorScheme === 'dark', videosDir: VIDEOS_DIR }, + () => use(page) ); - console.log(`demo video: ${mp4}`); }, settings: [{}, { option: true }], startPath: ['/', { option: true }], + story: ['', { option: true }], + traces: [[], { option: true }] }); export { expect } from '@playwright/test'; - -function slugify(text: string): string { - return text - .toLowerCase() - .replace(/[^a-z0-9]+/g, '-') - .replace(/^-|-$/g, ''); -} diff --git a/ui/apps/chat/demo/playwright.config.ts b/ui/apps/chat/demo/playwright.config.ts index bb5aeed08a4e..5168bdfe17db 100644 --- a/ui/apps/chat/demo/playwright.config.ts +++ b/ui/apps/chat/demo/playwright.config.ts @@ -16,6 +16,9 @@ if (existsSync(ENV_FILE)) process.loadEnvFile(ENV_FILE); * DEMO_SERVER_ORIGIN llama-server the UI proxies to (default: http://localhost:9931) * DEMO_LLAMA_SERVER llama-server binary started when none runs there (default: build/bin) * DEMO_COLOR_SCHEME light | dark (default: light) + * DEMO_POLISH 0 for the plain screencast (default: the branded render, see polish.ts) + * DEMO_STORYBOOK ui | chat: also start that Storybook (Llama UI's or Llama Chat's), for story demos + * DEMO_STORYBOOK_PORT port for it (default: 6007) */ // Playwright clears outputDir when a run starts, so concurrent recordings each get @@ -29,6 +32,10 @@ const SERVER_PORT = Number(new URL(SERVER_ORIGIN).port || 80); const LLAMA_SERVER = process.env.DEMO_LLAMA_SERVER ?? resolve(import.meta.dirname, '../../../../build/bin/llama-server'); +const STORYBOOK = process.env.DEMO_STORYBOOK; + +// workers read it to open the stories +process.env.DEMO_STORYBOOK_PORT ??= '6007'; export const VIEWPORT = { height: 900, width: 1440 }; /** Device pixel ratio the demos render and record at. */ @@ -82,7 +89,18 @@ export default defineConfig({ reuseExistingServer: true, timeout: 120000, url: `http://localhost:${UI_PORT}` - } + }, + ...(STORYBOOK + ? [ + { + command: `npx svelte-kit sync && npx storybook dev -p ${process.env.DEMO_STORYBOOK_PORT} --ci --exact-port`, + cwd: STORYBOOK === 'ui' ? resolve(UI_DIR, '../../lib/ui') : UI_DIR, + reuseExistingServer: true, + timeout: 120000, + url: `http://localhost:${process.env.DEMO_STORYBOOK_PORT}/iframe.html` + } + ] + : []) ], workers: 1 }); diff --git a/ui/apps/chat/demo/recorder.ts b/ui/apps/chat/demo/recorder.ts deleted file mode 100644 index 3d1faa9a4765..000000000000 --- a/ui/apps/chat/demo/recorder.ts +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Records a page through Chromium's screencast instead of Playwright's video, - * which encodes VP8 at about 1 Mbit/s at 1x scale. Frames arrive at the page's - * device pixel ratio, each with its timestamp, and are encoded once into an - * H.264 mp4 (what GitHub accepts in PR descriptions). - */ - -import type { CDPSession, Page } from '@playwright/test'; -import { execFileSync } from 'node:child_process'; -import { mkdirSync, rmSync, writeFileSync } from 'node:fs'; -import { writeFile } from 'node:fs/promises'; -import { join } from 'node:path'; - -const FPS = 60; -const JPEG_QUALITY = 92; - -interface Frame { - file: string; - /** Seconds, on the same clock as Date.now(). */ - time: number; -} - -export class ScreencastRecorder { - private readonly dir: string; - private readonly frames: Frame[] = []; - private readonly pending: Promise[] = []; - private session: CDPSession | undefined; - private stoppedAt = 0; - - constructor(dir: string) { - this.dir = dir; - } - - /** Encodes the frames, each held until the next one arrived (the screencast only sends changes). */ - encode(mp4: string): void { - if (this.frames.length === 0) throw new Error('demo: the screencast captured no frames'); - - const list = this.frames.flatMap((frame, i) => { - const end = this.frames[i + 1]?.time ?? this.stoppedAt; - - return [`file '${frame.file}'`, `duration ${Math.max(end - frame.time, 1 / FPS).toFixed(4)}`]; - }); - const listFile = join(this.dir, 'frames.txt'); - - // the concat demuxer ignores the last entry's duration unless the file is repeated - writeFileSync(listFile, [...list, `file '${this.frames.at(-1)!.file}'`, ''].join('\n')); - execFileSync( - 'ffmpeg', - [ - '-y', - '-loglevel', - 'error', - '-f', - 'concat', - '-safe', - '0', - '-i', - listFile, - '-vf', - `fps=${FPS},scale=trunc(iw/2)*2:trunc(ih/2)*2`, - '-c:v', - 'libx264', - '-preset', - 'slow', - '-crf', - '18', - '-pix_fmt', - 'yuv420p', - '-movflags', - '+faststart', - mp4 - ], - { stdio: 'inherit' } - ); - rmSync(this.dir, { force: true, recursive: true }); - } - - async start(page: Page): Promise { - const size = page.viewportSize(); - const scale = await page.evaluate(() => window.devicePixelRatio); - - rmSync(this.dir, { force: true, recursive: true }); - mkdirSync(this.dir, { recursive: true }); - - this.session = await page.context().newCDPSession(page); - this.session.on('Page.screencastFrame', ({ data, metadata, sessionId }) => { - const file = join(this.dir, `${String(this.frames.length).padStart(6, '0')}.jpg`); - - // acknowledged first: Chromium sends the next frame only after the ack - this.session?.send('Page.screencastFrameAck', { sessionId }).catch(() => {}); - this.frames.push({ file, time: metadata.timestamp ?? Date.now() / 1000 }); - this.pending.push(writeFile(file, Buffer.from(data, 'base64'))); - }); - await this.session.send('Page.startScreencast', { - everyNthFrame: 1, - format: 'jpeg', - maxHeight: size ? size.height * scale : undefined, - maxWidth: size ? size.width * scale : undefined, - quality: JPEG_QUALITY - }); - } - - async stop(): Promise { - this.stoppedAt = Date.now() / 1000; - await this.session?.send('Page.stopScreencast').catch(() => {}); - await this.session?.detach().catch(() => {}); - await Promise.all(this.pending); - } -} diff --git a/ui/apps/chat/demo/storage.ts b/ui/apps/chat/demo/storage.ts deleted file mode 100644 index def006d7b8df..000000000000 --- a/ui/apps/chat/demo/storage.ts +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Storage targets for demo scripts and videos, picked by the scheme of the - * DEMO_STORAGE URI: - * - * hf://buckets//[/prefix] Hugging Face bucket, via the `hf` CLI login - * file:///some/dir local or mounted directory - */ - -import { execFileSync } from 'node:child_process'; -import { copyFileSync, cpSync, existsSync, mkdirSync } from 'node:fs'; -import { dirname, join } from 'node:path'; -import { fileURLToPath } from 'node:url'; - -export interface DemoStorage { - /** Copies every file under remote `dir` into local `target`; returns false when it has none. */ - downloadDir(dir: string, target: string): boolean; - /** Copies local `file` to remote `key`. */ - upload(file: string, key: string): void; -} - -function joinKey(base: string, key: string): string { - return `${base.replace(/\/+$/, '')}/${key}`; -} - -// plain fields: the CLI runs under Node's type stripping, which has no parameter properties -class HfStorage implements DemoStorage { - private readonly base: string; - - constructor(base: string) { - this.base = base; - } - - downloadDir(dir: string, target: string): boolean { - mkdirSync(target, { recursive: true }); - - try { - execFileSync('hf', ['buckets', 'sync', joinKey(this.base, dir), target], { - stdio: 'inherit' - }); - } catch { - return false; - } - - return true; - } - - upload(file: string, key: string): void { - execFileSync('hf', ['buckets', 'cp', file, joinKey(this.base, key)], { stdio: 'inherit' }); - } -} - -class FileStorage implements DemoStorage { - private readonly root: string; - - constructor(root: string) { - this.root = root; - } - - downloadDir(dir: string, target: string): boolean { - const source = join(this.root, dir); - - if (!existsSync(source)) return false; - - cpSync(source, target, { recursive: true }); - - return true; - } - - upload(file: string, key: string): void { - const target = join(this.root, key); - - mkdirSync(dirname(target), { recursive: true }); - copyFileSync(file, target); - } -} - -export function getDemoStorage(uri = process.env.DEMO_STORAGE): DemoStorage | null { - if (!uri) return null; - - if (uri.startsWith('hf://')) return new HfStorage(uri); - - if (uri.startsWith('file://')) return new FileStorage(fileURLToPath(uri)); - - throw new Error(`DEMO_STORAGE: unsupported scheme in "${uri}" (use hf:// or file://)`); -} - -/** Public URL of a stored key, when DEMO_STORAGE_PUBLIC_URL is set. */ -export function getPublicUrl(key: string): string | null { - const base = process.env.DEMO_STORAGE_PUBLIC_URL; - - return base ? joinKey(base, key) : null; -} diff --git a/ui/apps/chat/package-lock.json b/ui/apps/chat/package-lock.json index 5009e3ac3dd8..2f400eaa02e1 100644 --- a/ui/apps/chat/package-lock.json +++ b/ui/apps/chat/package-lock.json @@ -1,12 +1,12 @@ { "name": "@ggml-org/llama-chat", - "version": "0.2.0", + "version": "0.3.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@ggml-org/llama-chat", - "version": "0.2.0", + "version": "0.3.1", "license": "MIT", "bin": { "llama-chat": "bin/cli.js" @@ -21,6 +21,7 @@ "@eslint/compat": "2.1.1", "@eslint/js": "10.0.1", "@ggml-org/llama-brand": "0.1.0", + "@ggml-org/llama-demo": "file:../../lib/demo", "@internationalized/date": "3.12.2", "@lezer/highlight": "1.2.5", "@lucide/svelte": "1.46.0", @@ -100,6 +101,20 @@ "node": ">=20" } }, + "../../lib/demo": { + "name": "@ggml-org/llama-demo", + "version": "0.1.0", + "dev": true, + "license": "MIT", + "devDependencies": { + "@playwright/test": "1.56.1", + "@types/node": "24.13.0", + "typescript": "6.0.3" + }, + "engines": { + "node": ">=22.18" + } + }, "node_modules/@adobe/css-tools": { "version": "4.5.0", "resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.5.0.tgz", @@ -1083,6 +1098,10 @@ "dev": true, "license": "CC-BY-NC-4.0 AND MIT AND OFL-1.1" }, + "node_modules/@ggml-org/llama-demo": { + "resolved": "../../lib/demo", + "link": true + }, "node_modules/@hono/node-server": { "version": "2.1.6", "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.6.tgz", diff --git a/ui/apps/chat/package.json b/ui/apps/chat/package.json index 5273e2497b59..b0342802c393 100644 --- a/ui/apps/chat/package.json +++ b/ui/apps/chat/package.json @@ -1,6 +1,6 @@ { "name": "@ggml-org/llama-chat", - "version": "0.2.0", + "version": "0.3.1", "description": "Llama Chat, the chat app for llama.cpp. Run it with npx @ggml-org/llama-chat against any llama-server.", "keywords": [ "llama.cpp", @@ -81,6 +81,8 @@ "@codemirror/view": "6.43.15", "@eslint/compat": "2.1.1", "@eslint/js": "10.0.1", + "@ggml-org/llama-brand": "0.1.0", + "@ggml-org/llama-demo": "file:../../lib/demo", "@internationalized/date": "3.12.2", "@lezer/highlight": "1.2.5", "@lucide/svelte": "1.46.0", @@ -119,7 +121,6 @@ "globals": "16.5.0", "highlight.js": "11.11.1", "http-server": "14.1.1", - "@ggml-org/llama-brand": "0.1.0", "mdsvex": "0.12.7", "mode-watcher": "1.1.0", "pdfjs-dist": "5.4.54", diff --git a/ui/apps/chat/src/app.css b/ui/apps/chat/src/app.css index 03e0e7d27424..6620a32a4d91 100644 --- a/ui/apps/chat/src/app.css +++ b/ui/apps/chat/src/app.css @@ -60,8 +60,9 @@ --chat-form-collapsed-height: 6.375rem; /* the empty chat form card, its text and actions in one row: a new chat centers its top edge */ --chat-form-resting-height: 3.375rem; - /* the chat form's corners while its text and actions share one row */ - --chat-form-single-row-radius: 1.25rem; + /* the chat form's corners while its text and actions share one row: a sheet group's, so the + phone sheets' search, groups and keys round alike */ + --chat-form-single-row-radius: var(--sheet-group-radius); /* the card's translucent fill over the page, made opaque: the phone sheet, and the page and Safari's bars around it */ --chat-form-sheet-fill: color-mix(in oklab, var(--surface-muted) 60%, var(--surface-page)); --max-message-height: max(24rem, min(80dvh, calc(100dvh - var(--chat-form-area-height) - 12rem))); diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemPdf.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemPdf.svelte index 07a08026ca40..3471d13b359a 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemPdf.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemPdf.svelte @@ -5,9 +5,11 @@ import { SyntaxHighlightedCode } from '#lib/components/app/index.ts'; import { ICON_CLASS_DEFAULT, PDF_AS_IMAGES_LEGACY_CONTENT_REGEX } from '#lib/constants/index.ts'; import { AttachmentType, MimeTypeApplication, PdfViewMode } from '#lib/enums/index.ts'; + import { settingsStore } from '#lib/stores/settings/index.svelte.ts'; import type { ChatAttachmentDisplayItem } from '#lib/types/index.ts'; import { convertPDFToImage, convertPDFToText } from '#lib/utils/browser-only.ts'; import { getLanguageFromFilename } from '#lib/utils/index.ts'; + import { clampPdfDpi } from '#lib/utils/pdf-dpi.ts'; interface Props { currentItem: ChatAttachmentDisplayItem | null; @@ -23,7 +25,9 @@ let pdfViewMode = $state(PdfViewMode.PAGES); let pdfImages = $state([]); let pdfImagesLoading = $state(false); - // a failure stays on screen: the effect does not retry while an error is set + // DPI the last fresh render (or failed attempt) used; stored attachment images are shown as-is + let pdfImagesDpi = $state(null); + // a failure stays on screen: the effect does not retry while an error is set at the current DPI let pdfImagesError = $state(null); let pdfText = $state(null); let pdfTextLoading = $state(false); @@ -64,7 +68,7 @@ } async function loadPdfImages() { - if (pdfImages.length > 0 || pdfImagesLoading || !currentItem) return; + if (!currentItem) return; if ( currentItem.attachment?.type === AttachmentType.PDF && @@ -75,9 +79,16 @@ return; } - if (pdfImagesError) return; + const dpi = clampPdfDpi(settingsStore.config.pdfDpi); + + if (pdfImagesLoading) return; + + if (pdfImages.length > 0 && pdfImagesDpi === dpi) return; + + if (pdfImagesError && pdfImagesDpi === dpi) return; pdfImagesLoading = true; + pdfImagesError = null; try { const file = getPdfFile(); @@ -86,10 +97,12 @@ throw new Error('No PDF file available for conversion'); } - pdfImages = await convertPDFToImage(file); + pdfImages = await convertPDFToImage(file, dpi); } catch (error) { pdfImagesError = error instanceof Error ? error.message : 'Failed to load PDF images'; } finally { + // remember the attempt even on failure, so a DPI change is the one retry + pdfImagesDpi = dpi; pdfImagesLoading = false; } } @@ -123,6 +136,9 @@ } $effect(() => { + // reaching the DPI here re-runs the effect when the setting changes + void settingsStore.config.pdfDpi; + if (pdfViewMode === PdfViewMode.PAGES) { loadPdfImages(); } else { 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 82ffb3f6aec0..6fa329d638e0 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 @@ -22,6 +22,7 @@ CLIPBOARD_CONTENT_QUOTE_PREFIX, ICON_CLASS_DEFAULT, INITIAL_FILE_SIZE, + OPEN_OVERLAY_SELECTOR, PROMPT_CONTENT_SEPARATOR, SETTING_CONFIG_DEFAULT, SYSTEM_MESSAGE_PLACEHOLDER, @@ -197,7 +198,7 @@ hasPrompts: () => { const prefs = conversationsStore.preferences; - if (!prefs.isCategoryEnabled(ToolSource.MCP)) return false; + if (!mcpStore.isFeatureEnabled || !prefs.isCategoryEnabled(ToolSource.MCP)) return false; return mcpStore .getServers() @@ -700,16 +701,29 @@ await submit(); } - // Escape drops a recording, wherever the focus is - function handleWindowKeydown(event: KeyboardEvent) { - if (event.key !== KeyboardKey.ESCAPE || !voice.isActive || event.defaultPrevented) return; + // Escape drops a recording, or else stops the reply, wherever the focus is. On the body, so it + // runs before the overlays' document listeners: a tooltip closing on Escape does not take the key + function handleBodyKeydown(event: KeyboardEvent) { + if (event.key !== KeyboardKey.ESCAPE || event.defaultPrevented) return; + + if (document.querySelector(OPEN_OVERLAY_SELECTOR)) return; + + if (voice.isActive) { + event.preventDefault(); + voice.cancel(); + + return; + } + + // the system message editor and a message edit take Escape in their own window listeners + if (!isLoading || systemMode || chatStore.isEditing() || isIMEComposing(event)) return; event.preventDefault(); - voice.cancel(); + onStop?.(); } - + {#snippet systemMessageLeading()} {#if systemMessageAttachment} @@ -897,6 +911,7 @@ isVoiceRefining={voice.isRefining} micWarning={micUnavailableReason ?? micError} onFileUpload={handleFileUpload} + onFilesSelect={handleFileSelect} onMicClick={handleMicClick} {onStop} onSystemPromptClick={() => diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte index fe3bff7bdbc2..8cd81d674168 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte @@ -1,28 +1,42 @@ + + + + +
- {@render trigger({ disabled: chatFormActions.disabled, onclick: () => (drawerOpen = true) })} - - - - {ATTACHMENT_MENU_TEXT.ADD_TO_CHAT} - - - {ATTACHMENT_MENU_TEXT.DESCRIPTION} - - - -
- - - - - {#if chatFormActions.onWorkingDirectoryClick} - - {/if} + {@render trigger({ disabled: chatFormActions.disabled, onclick: open })} - {#if toolsPanel.totalToolCount > 0} - (toolsExpanded = open)} open={toolsExpanded}> - - {#if toolsExpanded} - - {:else} - - {/if} - - - - {ATTACHMENT_MENU_TEXT.TOOLS} - - - -
- {#each toolsPanel.categoryGroups as group (group.key)} - {@render groupRow(group)} - {/each} - - {#each toolsPanel.mcpGroups as group (group.key)} - {@render groupRow(group)} - {/each} -
-
-
+ + + + {ATTACHMENT_MENU_TEXT.DESCRIPTION} + + + {#if page.id === AddSheetPage.ROOT} + {@render rootPage()} + {:else if page.id === AddSheetPage.TOOLS} + {@render toolsPage()} + {:else if currentGroup} + {@render groupPage(currentGroup)} {/if} -
+
+{#snippet rootPage()} + + {#if canUseCamera} + cameraInput?.click()}> + {ATTACHMENT_MENU_TEXT.CAMERA} + + {/if} + + + {ATTACHMENT_MENU_TEXT.ADD_FILES} + + {#if supportedModalities.length > 0} + + {#each supportedModalities as modality (modality.label)} + + {/each} + + {/if} + + + + + attachmentMenu.callbacks[AttachmentAction.SYSTEM_PROMPT_CLICK]()} + > + {ATTACHMENT_MENU_TEXT.SYSTEM_MESSAGE} + + + {#if chatFormActions.onWorkingDirectoryClick} + { + drawerOpen = false; + chatFormActions.onWorkingDirectoryClick?.(); + }} + > + {ATTACHMENT_MENU_TEXT.WORKING_DIRECTORY} + + + {chatFormActions.workingDirectory ?? ATTACHMENT_MENU_TEXT.NONE} + + + {/if} + + + {#if agenticMode.enabled} + push({ id: AddSheetPage.TOOLS })}> + {ATTACHMENT_MENU_TEXT.TOOLS} + + {#if toolsPanel.totalToolCount > 0} + + {enabledToolCount}/{toolsPanel.totalToolCount} + + {/if} + + {/if} + +{/snippet} + +{#snippet toolsPage()} + {#if toolsPanel.totalToolCount === 0} + + {#if toolsStore.loading} + + + + {ATTACHMENT_MENU_TEXT.LOADING_TOOLS} + + {:else if toolsStore.error && !toolsStore.isToolsEndpointUnreachable} + {ATTACHMENT_MENU_TEXT.TOOLS_FAILED} + {:else} + + + + {toolsPanel.noToolsInfoMessage ?? ATTACHMENT_MENU_TEXT.NO_TOOLS} + + {/if} + + {:else} + {#if toolsPanel.categoryGroups.length > 0} + + {#each toolsPanel.categoryGroups as group (group.key)} + {@render groupRow(group)} + {/each} + + {/if} + + {#if toolsPanel.mcpGroups.length > 0} + + {#each toolsPanel.mcpGroups as group (group.key)} + {@render groupRow(group)} + {/each} + + {/if} + {/if} +{/snippet} + +{#snippet groupSwitch(group: ToolGroup, label?: string)} + toolsPanel.toggleGroupByKey(group.key)} + size="lg" + /> +{/snippet} + {#snippet groupRow(group: ToolGroup)} - {@const checkState = toolsPanel.getGroupCheckState(group)} - {@const enabledCount = toolsPanel.getEnabledToolCount(group)} {@const favicon = toolsPanel.getFavicon(group)} - {@const groupDisabled = toolsPanel.isGroupDisabled(group)} + {@const isChecked = toolsPanel.getGroupCheckState(group).checked} - + {#snippet trailing()} + {@render groupSwitch( + group, + isChecked + ? ATTACHMENT_MENU_TEXT.DISABLE_GROUP(group.label) + : ATTACHMENT_MENU_TEXT.ENABLE_GROUP(group.label) + )} + {/snippet} + +{/snippet} + +{#snippet groupPage(group: ToolGroup)} + + + {ATTACHMENT_MENU_TEXT.ALL_TOOLS} + + {@render groupSwitch(group)} + + + + + {#each group.tools as entry (entry.key)} + + + {entry.definition.function.name} + + + toolsPanel.toggleTool(entry)} + size="lg" + /> + + {/each} + {/snippet} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddToolsSubmenu.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddToolsSubmenu.svelte index 11474908693b..d2dff9f82ed8 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddToolsSubmenu.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddToolsSubmenu.svelte @@ -6,7 +6,7 @@ import { Check, ChevronDown, ChevronRight, Info, Loader2, PencilRuler } from '@lucide/svelte'; import { ATTACHMENT_MENU_TEXT, CLI_FLAGS, ICON_CLASS_DEFAULT } from '#lib/constants/index.ts'; import { useToolsPanel } from '#lib/hooks/use-tools-panel.svelte.ts'; - import { mcpStore, toolsStore, uiStore } from '#lib/stores/index.ts'; + import { mcpStore, toolsStore } from '#lib/stores/index.ts'; import type { ToolGroup } from '#lib/types/index.ts'; const toolsPanel = useToolsPanel(); @@ -26,7 +26,7 @@
- Loading tools... + {ATTACHMENT_MENU_TEXT.LOADING_TOOLS}
{:else if toolsStore.isToolsEndpointUnreachable}
@@ -40,8 +40,8 @@ - - {#if uiStore.isMcpShown} + + {#if mcpStore.isFeatureEnabled} @@ -55,7 +55,7 @@
{:else if toolsStore.error}
- Failed to load tools + {ATTACHMENT_MENU_TEXT.TOOLS_FAILED}
{:else if toolsPanel.noToolsInfoMessage}
@@ -65,7 +65,7 @@
{:else}
- No tools available + {ATTACHMENT_MENU_TEXT.NO_TOOLS}
{/if} {:else} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte index c895ef0c34b7..7db0cdf7845e 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte @@ -50,6 +50,7 @@ /** The chat's working directory, which the + menu names. */ workingDirectory?: string | null; onFileUpload?: () => void; + onFilesSelect?: (files: File[]) => void; onMicClick?: () => void; onStop?: () => void; onSystemPromptClick?: () => void; @@ -66,6 +67,7 @@ isSendWaiting = false, isVoiceRefining = false, micWarning = null, + onFilesSelect, onFileUpload, onMicClick, onStop, @@ -132,6 +134,9 @@ get hasVisionModality() { return hasVisionModality; }, + get onFilesSelect() { + return onFilesSelect; + }, get onFileUpload() { return onFileUpload; }, @@ -141,10 +146,13 @@ get onWorkingDirectoryClick() { return onWorkingDirectoryClick; }, - get workingDirectoryLabel() { + get workingDirectory() { return workingDirectory ? abbreviateWorkingDir(workingDirectory, toolsStore.serverHome) - : SET_WORKING_DIRECTORY_LABEL; + : null; + }, + get workingDirectoryLabel() { + return this.workingDirectory ?? SET_WORKING_DIRECTORY_LABEL; } }); diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectory.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectory.svelte index e4b7d81c9649..87518c17a633 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectory.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectory.svelte @@ -82,7 +82,7 @@ const searchUnavailableMessage = $derived( fileSearchKey === null ? 'File search is unavailable on this server - type a full path and press Enter' - : 'File search is disabled - type a full path and press Enter, or enable "Search files" in Settings > Tools' + : 'File search is disabled - type a full path and press Enter, or enable "Search files" in Settings > Agent' ); let searchInputRef: HTMLInputElement | null = $state(null); diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPickerMention.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPickerMention.svelte index ed3c764529c3..64b06a92a5ab 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPickerMention.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPickerMention.svelte @@ -133,7 +133,7 @@ } if (!fileSearchEnabled) { - return 'File search is disabled - enable "Search files" in Settings > Tools to use @-mentions'; + return 'File search is disabled - enable "Search files" in Settings > Agent to use @-mentions'; } return searchError ? `Search failed - ${searchError}` : 'No matching files or folders'; 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 80d0cb5fdc6f..4bc6fa8f51b4 100644 --- a/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte +++ b/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte @@ -10,6 +10,7 @@ X } from '@lucide/svelte'; import { ActionIcon, KeyboardShortcutInfo, ModelOrgAvatar } from '#lib/components/app/index.ts'; + import { ModelsDiscoverDetailsContainer } from '#lib/components/app/models/discover/index.ts'; import { CONVERSATION_SEARCH_CONTENT_DEBOUNCE_MS, CONVERSATION_SEARCH_CONTENT_LIMIT, @@ -22,7 +23,7 @@ ICON_CLASS_SM, ICON_CLASS_XS, SIDEBAR_ACTIONS_ITEMS, - sidebarFooterItems + SIDEBAR_FOOTER_ITEMS } from '#lib/constants/index.ts'; import { KeyboardKey, SidebarAction } from '#lib/enums/index.ts'; import { useDebouncedSearch } from '#lib/hooks/use-debounced-search.svelte.ts'; @@ -32,7 +33,6 @@ 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, @@ -78,6 +78,8 @@ let query = $state(''); let highlighted = $state(0); let inputRef = $state(null); + /** The Hub repo picked from the results, shown in place of them. */ + let selectedModel = $state(null); const needle = $derived(query.trim().toLowerCase()); const limit = $derived( @@ -158,11 +160,10 @@ if (open && isDiscoverEnabled) untrack(() => void modelsDiscoverStore.fetch()); }); - /** A Hub repo as a result; picking it opens Discover on that repo. */ + /** A Hub repo as a result; picking it shows the repo's details under the search. */ function modelEntry(model: HfModelInfo, section: string): SearchEntry { const range = modelsDiscoverStore.cachedSizeRangeFor(model.id); - - return { + const entry: SearchEntry = { icon: DISCOVER_ICON, id: `${section}-${model.id}`, label: model.id, @@ -171,8 +172,16 @@ : `${HuggingFaceService.formatDownloads(model.downloads)} downloads`, // the model's own org, the way the model cards show it org: orgOf(HuggingFaceService.getBaseModels(model)[0]) || orgOf(model.id), - run: () => close(() => uiStore.openModelsDiscover(model.id)) + run: () => (selectedModel = entry) }; + + return entry; + } + + /** Back from a picked repo to the results it was picked from. */ + function clearSelectedModel() { + selectedModel = null; + inputRef?.focus(); } const suggestedEntries = $derived.by((): SearchEntry[] => @@ -249,7 +258,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, ...sidebarFooterItems(agenticMode.enabled)] + [...SIDEBAR_ACTIONS_ITEMS, ...SIDEBAR_FOOTER_ITEMS] .filter( (item) => item.action && @@ -308,6 +317,9 @@ // while an IME is composing, Enter confirms a candidate and the arrows move through them if (isIMEComposing(event)) return; + // a picked repo replaces the results: there is nothing to move through or open + if (selectedModel) return; + if (event.key === KeyboardKey.ARROW_DOWN) { event.preventDefault(); move(1); @@ -324,6 +336,7 @@ if (!nextOpen) { query = ''; highlighted = 0; + selectedModel = null; } open = nextOpen; @@ -350,18 +363,82 @@ {/snippet} +{#snippet row(entry: SearchEntry, index: number | null, isActive: boolean)} + +{/snippet} + {#snippet search()}
0 ? `search-result-${activeIndex}` : undefined} + aria-activedescendant={entries.length > 0 && !selectedModel + ? `search-result-${activeIndex}` + : undefined} aria-controls="search-results" aria-expanded="true" autocomplete="off" class="h-10 min-w-0 flex-1 border-0 bg-transparent px-1 text-title font-normal outline-none placeholder:text-muted-foreground focus:outline-none focus-visible:ring-0" - oninput={() => (highlighted = 0)} + oninput={() => { + highlighted = 0; + selectedModel = null; + }} onkeydown={handleKeydown} placeholder="Search" role="combobox" @@ -378,100 +455,74 @@
-
- {#each sections as section, sectionIndex (section.title)} - {@const offset = sections - .slice(0, sectionIndex) - .reduce((total, previous) => total + previous.entries.length, 0)} - -
-

- {section.title} + {#if selectedModel} + +

+ {@render row({ ...selectedModel, run: clearSelectedModel }, null, true)} +
- {#if section.loading} - - {/if} -

- - {#each section.entries as entry, entryIndex (entry.id)} - {@const index = offset + entryIndex} - {@const isActive = index === activeIndex && !deviceStore.isMobile} - - - - {/each} -
- {:else} -

{emptyMessage}

- {/each} -
+

+ + {#each section.entries as entry, entryIndex (entry.id)} + {@const index = offset + entryIndex} + {@const isActive = index === activeIndex && !deviceStore.isMobile} + + + {@render row(entry, index, isActive)} + {/each} + + {:else} +

{emptyMessage}

+ {/each} + + {/if}
- {@render hint('Close', ['Esc'])} + {#if selectedModel} + {@render hint('Back', ['Esc'])} + {:else} + {@render hint('Close', ['Esc'])} - {@render hint('Navigate', [ArrowUp, ArrowDown])} + {@render hint('Navigate', [ArrowUp, ArrowDown])} - {@render hint('Open', [CornerDownLeft])} + {@render hint('Open', [CornerDownLeft])} + {/if}
{/snippet} { + // Esc steps back from a picked repo before it closes the search + if (!selectedModel) return; + + event.preventDefault(); + clearSelectedModel(); + }} onOpenAutoFocus={(event) => { event.preventDefault(); inputRef?.focus(); diff --git a/ui/apps/chat/src/lib/components/app/dialogs/index.ts b/ui/apps/chat/src/lib/components/app/dialogs/index.ts index 342a6a6f870a..ac2c655f3e9e 100644 --- a/ui/apps/chat/src/lib/components/app/dialogs/index.ts +++ b/ui/apps/chat/src/lib/components/app/dialogs/index.ts @@ -19,10 +19,9 @@ export { default as DialogMcpServerAddNew } from './DialogMcpServerAddNew.svelte'; /** - * **DialogMcpServers** - MCP servers dialog shown from the chat form + * **DialogMcpServers** - MCP servers dialog, opened with `uiStore.openMcpServers` * - * Shows the same MCP server list as the `/mcp-servers` route inside a modal - * dialog. + * Lists the MCP servers, to add, edit, turn on and remove them. */ export { default as DialogMcpServers } from './DialogMcpServers.svelte'; diff --git a/ui/apps/chat/src/lib/components/app/forms/KeyValuePairs.svelte b/ui/apps/chat/src/lib/components/app/forms/KeyValuePairs.svelte index 3a3571ea6dd0..861c08fc62ca 100644 --- a/ui/apps/chat/src/lib/components/app/forms/KeyValuePairs.svelte +++ b/ui/apps/chat/src/lib/components/app/forms/KeyValuePairs.svelte @@ -1,5 +1,6 @@ + +{#snippet modelRow(item: ModelItem)} + {@const inChat = activeId === item.option.id} + {@const dictates = !inChat && voiceStore.isDictationModel(item.option.model)} + {@const isHeld = longPress.isPressing && pressed?.item === item} + {@const isLit = (menuOpen && menuItem === item) || (showFull && highlightedId === item.option.id)} + + + onSelect?.(item.option.id)} + onclickcapture={longPress.handleClickCapture} + oncontextmenu={longPress.handleContextMenu} + onpointercancel={longPress.handlePointerEnd} + onpointerdown={(event) => { + pressed = { item, row: event.currentTarget }; + longPress.handlePointerDown(event); + }} + onpointermove={longPress.handlePointerMove} + onpointerup={longPress.handlePointerEnd} + > + {#snippet leading()} + + {/snippet} + + + + + + + + + {#if inChat} + {@render role(MODELS_SHEET_TEXT.IN_CHAT, Check, 'text-(--action-primary)')} + {:else if dictates} + {@render role(MODELS_SHEET_TEXT.DICTATION, Mic, 'text-destructive')} + {/if} + +{/snippet} + +{#snippet role(label: string, Icon: typeof Check, iconClass: string)} + + {label} + + + +{/snippet} + + +{#snippet unavailableRow(model: string)} + + + + + {MODELS_SHEET_TEXT.NOT_AVAILABLE} + + +{/snippet} + + + + + + + event.preventDefault()} + overlayClass={uiStore.isModelDetailsOpen ? 'z-40' : undefined} + > + + + {MODELS_SHEET_TEXT.DESCRIPTION} + + + {#if unavailableModel} + {@render unavailableRow(unavailableModel)} + {/if} + + {#if showFull} + {#if isEmpty} +

{emptyMessage}

+ {:else} + {#each fullGroups as group (group.key)} + + {#each group.items as item (item.option.id)} + {@render modelRow(item)} + {/each} + + {/each} + {/if} + {:else} + + {#if quickItems.length > 0} + + {#each quickItems as item (item.option.id)} + {@render modelRow(item)} + {/each} + + {:else if isEmpty} +

{emptyMessage}

+ {/if} + + + + {MODELS_SHEET_TEXT.ALL_MODELS} + + + {/if} +
+ + +
+ + {#if hasEffort} +
+ +
+ {/if} + + onSearchChange?.(value)} + onKeyDown={handleSearchKeyDown} + placeholder={MODELS_SHEET_TEXT.SEARCH_PLACEHOLDER} + value={searchTerm} + /> +
+
+
diff --git a/ui/apps/chat/src/lib/components/app/models/ModelsSelector/index.ts b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/index.ts index e234fbac33e0..4366be2898d3 100644 --- a/ui/apps/chat/src/lib/components/app/models/ModelsSelector/index.ts +++ b/ui/apps/chat/src/lib/components/app/models/ModelsSelector/index.ts @@ -3,7 +3,7 @@ export { default as ModelsSelector } from './ModelsSelector.svelte'; export { default as ModelsSelectorDropdown } from './ModelsSelectorDropdown.svelte'; -export { default as ModelsSelectorDrawer } from './ModelsSelectorDrawer.svelte'; +export { default as ModelsSelectorSheet } from './ModelsSelectorSheet.svelte'; export { default as ModelsSelectorList } from './ModelsSelectorList.svelte'; export { default as ModelsSelectorDownloadItem } from './ModelsSelectorDownloadItem.svelte'; export { default as ModelsSelectorOption } from './ModelsSelectorOption.svelte'; diff --git a/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetails.svelte b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetails.svelte index 8cbaac857889..450174a53b98 100644 --- a/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetails.svelte +++ b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetails.svelte @@ -23,9 +23,19 @@ loading?: boolean; /** Error message when loading failed. */ error?: string | null; + /** Leaner pane for a narrow host such as Search: no Hugging Face link, no description. */ + compact?: boolean; } - let { details, error = null, files, loading = false, modelId, readme }: Props = $props(); + let { + compact = false, + details, + error = null, + files, + loading = false, + modelId, + readme + }: Props = $props(); let gguf = $derived(details?.gguf); let baseModels = $derived(HuggingFaceService.getBaseModels(details)); @@ -77,7 +87,7 @@ {#if loading} - + {:else if error}

{error}

@@ -86,6 +96,7 @@
(null); let files = $state([]); @@ -63,4 +65,4 @@ }); - + diff --git a/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsHeader.svelte b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsHeader.svelte index 64bdbd5f62ed..79de8a3faad5 100644 --- a/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsHeader.svelte +++ b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsHeader.svelte @@ -20,10 +20,13 @@ modalities: ModelModalities; hasTools: boolean; hasReasoning: boolean; + /** Leaner pane for a narrow host such as Search: no Hugging Face link, no description. */ + compact?: boolean; } let { baseModels, + compact = false, details, gguf, hasReasoning, @@ -83,23 +86,25 @@
- + + + {/if} - + diff --git a/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsMetadata.svelte b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsMetadata.svelte index c222d4ab0a29..8c425a4fecbd 100644 --- a/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsMetadata.svelte +++ b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsMetadata.svelte @@ -13,9 +13,11 @@ details: HfModelDetailInfo; gguf?: HfModelGguf; licenseTag: string | null; + /** Leaner pane for a narrow host such as Search: no Hugging Face link, no description. */ + compact?: boolean; } - let { details, gguf, licenseTag, modelId }: Props = $props(); + let { compact = false, details, gguf, licenseTag, modelId }: Props = $props(); // Catalog family description when curated, else the HF card description. let description = $derived( @@ -25,7 +27,7 @@ let chatTemplateOpen = $state(false); -{#if description} +{#if description && !compact}

{description}

{/if} diff --git a/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsSkeleton.svelte b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsSkeleton.svelte index 1841495389d4..244023183a10 100644 --- a/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsSkeleton.svelte +++ b/ui/apps/chat/src/lib/components/app/models/discover/ModelsDiscoverDetails/ModelsDiscoverDetailsSkeleton.svelte @@ -1,27 +1,36 @@ - +
-
+
- + - +
- + {#if !compact} + + {/if}
-
+
@@ -29,63 +38,61 @@
- - + + {#if !compact} +
+ + +
+ {/if} - +
- + - + - + - +
- +
{#each [0, 1, 2] as _, index (index)}
-
- +
+ - +
-
- +
+ - + {#if index === 0} + + {/if}
{/each}
- -
- - -
- - - - - -
- - -
+ + + 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 ebbc539f6418..ec77caace11b 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 @@ -1,5 +1,6 @@ - + diff --git a/ui/apps/chat/src/lib/components/app/navigation/index.ts b/ui/apps/chat/src/lib/components/app/navigation/index.ts index a4dc758ad1e9..0f74bc739a70 100644 --- a/ui/apps/chat/src/lib/components/app/navigation/index.ts +++ b/ui/apps/chat/src/lib/components/app/navigation/index.ts @@ -182,7 +182,7 @@ export { default as SidebarNavigationSelectionBar } from './SidebarNavigation/Si export { default as SidebarNavigationConversationList } from './SidebarNavigation/SidebarNavigationConversationList.svelte'; export { default as SidebarNavigationActions } from './SidebarNavigation/SidebarNavigationActions.svelte'; -/** The sidebar's footer: Models, MCP and Settings in a group inset in the sidebar. */ +/** The sidebar's footer: Models and Settings in a group inset in the sidebar. */ export { default as SidebarNavigationFooter } from './SidebarNavigation/SidebarNavigationFooter.svelte'; /** 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 17b00e9742ad..dfe79802b898 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 @@ -1,6 +1,7 @@ +{#snippet groups(list: ReturnType)} + {#each list as group (group.title)} + +
+ +
+
+ {/each} +{/snippet} +
-
+
- {#if currentSection.slug === SETTINGS_SECTION_SLUGS.TOOLS} - - {:else if currentSection.slug === SETTINGS_SECTION_SLUGS.IMPORT_EXPORT} - - {:else if currentSection.slug === SETTINGS_SECTION_SLUGS.VOICE && currentSection.fields} - - {:else if currentSection.fields} -
- - - {#if currentSection.slug === SETTINGS_SECTION_SLUGS.GENERAL} -
+ {#if currentSection.slug === SETTINGS_SECTION_SLUGS.DATA} +
+ + + +
+
+
+ {:else} +
+ {#if currentSection.slug === SETTINGS_SECTION_SLUGS.VOICE} + + {:else} + {#if currentSection.slug === SETTINGS_SECTION_SLUGS.AGENT} + + + + {/if} + + {@render groups(fieldGroups)} + {/if} + + {#if advancedGroups.length > 0} + {@const isOpen = advancedOpen.has(currentSection.slug)} + + toggleAdvanced(currentSection.slug)} + open={isOpen} + > + + {#if isOpen} + + {:else} + + {/if} + + Advanced settings + + + +
+ {@render groups(advancedGroups)} +
+
+
{/if}
{/if} diff --git a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte index 2f66bd4fa835..7a3141534ce5 100644 --- a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte +++ b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatFields.svelte @@ -1,4 +1,5 @@ {#each fields as field (field.key)} @@ -63,23 +40,7 @@
{#if field.type === SettingsFieldType.INPUT} {@const currentValue = String(localConfig[field.key] ?? '')} - {@const serverDefault = currentModelParams[field.key]} - {@const isCustomRealTime = (() => { - if (serverDefault == null) return false; - - if (currentValue === '') return false; - - const numericInput = parseFloat(currentValue); - const normalizedInput = !isNaN(numericInput) - ? Math.round(numericInput * 1000000) / 1000000 - : currentValue; - const normalizedDefault = - typeof serverDefault === 'number' - ? Math.round(serverDefault * 1000000) / 1000000 - : serverDefault; - - return normalizedInput !== normalizedDefault; - })()} + {@const isCustomRealTime = fieldDefaults.isCustom(field)}