mirror of
https://github.com/ggml-org/llama.cpp.git
synced 2026-11-28 05:37:43 -06:00
Compare commits
47
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
40f77d45d3 | ||
|
|
8e23278c7c | ||
|
|
6d8a8886fa | ||
|
|
4c7344447c | ||
|
|
3ab385146c | ||
|
|
d67b7a99d8 | ||
|
|
3b103f75e9 | ||
|
|
4346838ad8 | ||
|
|
0020197457 | ||
|
|
a386950136 | ||
|
|
15fcfc7357 | ||
|
|
7b74cb92d6 | ||
|
|
2a8bf0f593 | ||
|
|
e7ec6361dc | ||
|
|
69812f63c2 | ||
|
|
f351f415d6 | ||
|
|
00d5c142c8 | ||
|
|
ca123ba763 | ||
|
|
f89a243d53 | ||
|
|
ed2153e708 | ||
|
|
e0b9fd7d76 | ||
|
|
a07831a008 | ||
|
|
9fa7a33cbb | ||
|
|
e087c6c4e7 | ||
|
|
492d23cc9e | ||
|
|
e8d7128fea | ||
|
|
2a335259ca | ||
|
|
47d6192fce | ||
|
|
6d54465e9d | ||
|
|
98cc730cc8 | ||
|
|
e630f78729 | ||
|
|
5d7bb89f47 | ||
|
|
0ac39e4705 | ||
|
|
fa9f928f25 | ||
|
|
0e4e925e8f | ||
|
|
6aad4c7efd | ||
|
|
46ba8b7008 | ||
|
|
436d7e81ca | ||
|
|
a866b4ade6 | ||
|
|
4ba835c637 | ||
|
|
689194808a | ||
|
|
fd4b137e38 | ||
|
|
55d482814b | ||
|
|
7365e4793c | ||
|
|
b16f15350a | ||
|
|
b671865c7b | ||
|
|
8c6418001d |
@@ -18,6 +18,8 @@ ARG NODE_VERSION=24
|
||||
FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
|
||||
ARG VITE_PUBLIC_HUGGING_FACE=false
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
|
||||
@@ -25,11 +27,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
|
||||
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
|
||||
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM ${CANN_BASE_IMAGE} AS build
|
||||
|
||||
@@ -8,6 +8,8 @@ ARG NODE_VERSION=24
|
||||
FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
|
||||
ARG VITE_PUBLIC_HUGGING_FACE=false
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
|
||||
@@ -15,11 +17,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
|
||||
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
|
||||
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM docker.io/ubuntu:$UBUNTU_VERSION AS build
|
||||
|
||||
@@ -16,6 +16,8 @@ ARG NODE_VERSION=24
|
||||
FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
|
||||
ARG VITE_PUBLIC_HUGGING_FACE=false
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
|
||||
@@ -23,11 +25,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
|
||||
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
|
||||
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM ${BASE_CUDA_DEV_CONTAINER} AS build
|
||||
|
||||
@@ -10,6 +10,8 @@ ARG NODE_VERSION=24
|
||||
FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
|
||||
ARG VITE_PUBLIC_HUGGING_FACE=false
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
|
||||
@@ -17,11 +19,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
|
||||
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
|
||||
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM docker.io/intel/deep-learning-essentials:$ONEAPI_VERSION AS build
|
||||
|
||||
@@ -14,6 +14,8 @@ ARG NODE_VERSION=24
|
||||
FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
|
||||
ARG VITE_PUBLIC_HUGGING_FACE=false
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
|
||||
@@ -21,11 +23,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
|
||||
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
|
||||
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM ${BASE_MUSA_DEV_CONTAINER} AS build
|
||||
|
||||
@@ -27,6 +27,8 @@ ARG NODE_VERSION=24
|
||||
FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
|
||||
ARG VITE_PUBLIC_HUGGING_FACE=false
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
|
||||
@@ -34,11 +36,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
|
||||
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
|
||||
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
## Build Image
|
||||
|
||||
@@ -16,6 +16,8 @@ ARG NODE_VERSION=24
|
||||
FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
|
||||
ARG VITE_PUBLIC_HUGGING_FACE=false
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
|
||||
@@ -23,11 +25,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
|
||||
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
|
||||
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
### Build image
|
||||
|
||||
@@ -8,6 +8,8 @@ ARG NODE_VERSION=24
|
||||
FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
|
||||
ARG VITE_PUBLIC_HUGGING_FACE=false
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
|
||||
@@ -15,11 +17,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
|
||||
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
|
||||
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM docker.io/ubuntu:$UBUNTU_VERSION AS build
|
||||
|
||||
@@ -8,6 +8,8 @@ ARG NODE_VERSION=24
|
||||
FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
|
||||
ARG VITE_PUBLIC_HUGGING_FACE=false
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
|
||||
@@ -15,11 +17,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
|
||||
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
|
||||
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM docker.io/ubuntu:$UBUNTU_VERSION AS build
|
||||
|
||||
@@ -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
|
||||
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
|
||||
# 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-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]
|
||||
|
||||
@@ -269,6 +269,7 @@ jobs:
|
||||
build-args: |
|
||||
BUILD_DATE=${{ steps.build_date.outputs.date }}
|
||||
APP_VERSION=${{ needs.create_tag.outputs.source_tag }}
|
||||
VITE_PUBLIC_HUGGING_FACE=true
|
||||
APP_REVISION=${{ steps.checkout.outputs.commit }}
|
||||
IMAGE_URL=${{ github.server_url }}/${{ github.repository }}
|
||||
IMAGE_SOURCE=${{ github.server_url }}/${{ github.repository }}
|
||||
@@ -306,6 +307,7 @@ jobs:
|
||||
build-args: |
|
||||
BUILD_DATE=${{ steps.build_date.outputs.date }}
|
||||
APP_VERSION=${{ needs.create_tag.outputs.source_tag }}
|
||||
VITE_PUBLIC_HUGGING_FACE=true
|
||||
APP_REVISION=${{ steps.checkout.outputs.commit }}
|
||||
IMAGE_URL=${{ github.server_url }}/${{ github.repository }}
|
||||
IMAGE_SOURCE=${{ github.server_url }}/${{ github.repository }}
|
||||
@@ -343,6 +345,7 @@ jobs:
|
||||
build-args: |
|
||||
BUILD_DATE=${{ steps.build_date.outputs.date }}
|
||||
APP_VERSION=${{ needs.create_tag.outputs.source_tag }}
|
||||
VITE_PUBLIC_HUGGING_FACE=true
|
||||
APP_REVISION=${{ steps.checkout.outputs.commit }}
|
||||
IMAGE_URL=${{ github.server_url }}/${{ github.repository }}
|
||||
IMAGE_SOURCE=${{ github.server_url }}/${{ github.repository }}
|
||||
|
||||
@@ -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: Clone
|
||||
id: checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- 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 jq
|
||||
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
|
||||
|
||||
# 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: |
|
||||
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 <hip/hip_runtime.h>' '__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' }}
|
||||
|
||||
@@ -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 '<!-- demo:start -->' <<< "$BODY" && grep -qF '<!-- demo:end -->' <<< "$BODY"; } ||
|
||||
|
||||
@@ -33,6 +33,9 @@ jobs:
|
||||
- name: Build application
|
||||
run: npm run build
|
||||
working-directory: ui/apps/chat
|
||||
env:
|
||||
# as in ui-build.yml: the UI under test has the Hugging Face lib
|
||||
VITE_PUBLIC_HUGGING_FACE: "true"
|
||||
|
||||
- name: Upload built UI
|
||||
uses: actions/upload-artifact@v6
|
||||
|
||||
@@ -47,6 +47,8 @@ jobs:
|
||||
- name: Build application
|
||||
env:
|
||||
LLAMA_BUILD_NUMBER: ${{ steps.version.outputs.ui_version }}
|
||||
# the UI that the releases and the prebuilt download are made of has the Hugging Face lib
|
||||
VITE_PUBLIC_HUGGING_FACE: "true"
|
||||
run: npm run build
|
||||
working-directory: ui/apps/chat
|
||||
|
||||
|
||||
@@ -94,6 +94,9 @@ jobs:
|
||||
# This folder's .npmrc sets ignore-scripts, so npm never builds it: this step does.
|
||||
run: LLAMA_BUILD_NUMBER="b$(git rev-list --count HEAD)" npm run build
|
||||
working-directory: ${{ env.APP_DIR }}
|
||||
env:
|
||||
# the same app as the UI llama-server embeds, with the Hugging Face lib
|
||||
VITE_PUBLIC_HUGGING_FACE: "true"
|
||||
|
||||
- name: Test the CLI and the alias version
|
||||
run: npx vitest --project=unit --run tests/unit/cli.test.ts
|
||||
|
||||
@@ -21,6 +21,7 @@ on:
|
||||
'ui/lib/ui/**.*',
|
||||
'ui/lib/voice/**.*',
|
||||
'ui/lib/harness/**.*',
|
||||
'ui/lib/huggingface/**.*',
|
||||
'tools/server/tests/**.*'
|
||||
]
|
||||
pull_request:
|
||||
@@ -32,6 +33,7 @@ on:
|
||||
'ui/lib/ui/**.*',
|
||||
'ui/lib/voice/**.*',
|
||||
'ui/lib/harness/**.*',
|
||||
'ui/lib/huggingface/**.*',
|
||||
'tools/server/tests/**.*'
|
||||
]
|
||||
|
||||
@@ -127,6 +129,9 @@ jobs:
|
||||
if: ${{ always() && steps.setup.conclusion == 'success' }}
|
||||
run: npm run build-storybook
|
||||
working-directory: ui/apps/chat
|
||||
env:
|
||||
# its stories show the Hugging Face lib
|
||||
VITE_PUBLIC_HUGGING_FACE: "true"
|
||||
|
||||
- name: Run UI tests
|
||||
if: ${{ always() && steps.setup.conclusion == 'success' }}
|
||||
|
||||
@@ -49,6 +49,9 @@ jobs:
|
||||
- name: Build Storybook
|
||||
run: npm run build-storybook
|
||||
working-directory: ui/apps/chat
|
||||
env:
|
||||
# its stories show the Hugging Face lib
|
||||
VITE_PUBLIC_HUGGING_FACE: "true"
|
||||
|
||||
- name: Write the Space card
|
||||
run: |
|
||||
|
||||
+100
-1
@@ -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
|
||||
@@ -244,6 +275,71 @@ jobs:
|
||||
fi
|
||||
working-directory: ui/apps/chat
|
||||
|
||||
huggingface-lib-bundle:
|
||||
name: Hugging Face lib in the bundle
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24"
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
working-directory: ui/apps/chat
|
||||
|
||||
- name: Build with and without the Hugging Face lib
|
||||
run: |
|
||||
npm run build
|
||||
VITE_PUBLIC_HUGGING_FACE=true LLAMA_UI_OUT_DIR=dist-with-sharing npm run build
|
||||
working-directory: ui/apps/chat
|
||||
|
||||
# a text of the lib's sign-in: it is in the bundle only when the lib is
|
||||
- name: Check the Hugging Face lib is only in the bundle built with it
|
||||
run: |
|
||||
marker="Hugging Face sent no access token back"
|
||||
if ! grep -rlq "$marker" dist-with-sharing; then
|
||||
echo "The bundle built with the Hugging Face lib does not contain it" && exit 1
|
||||
fi
|
||||
if grep -rlq "$marker" dist; then
|
||||
echo "The default bundle contains the Hugging Face lib" && exit 1
|
||||
fi
|
||||
working-directory: ui/apps/chat
|
||||
|
||||
huggingface-lib-checks:
|
||||
name: Hugging Face lib 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/huggingface
|
||||
|
||||
# its plain TypeScript; the components are checked with the app that compiles them
|
||||
- name: Run type checking
|
||||
run: npm run check
|
||||
working-directory: ui/lib/huggingface
|
||||
|
||||
- name: Run tests
|
||||
run: npm test
|
||||
working-directory: ui/lib/huggingface
|
||||
|
||||
e2e-tests:
|
||||
name: E2E Tests
|
||||
needs: ui-build
|
||||
@@ -286,6 +382,9 @@ jobs:
|
||||
if: ${{ always() && steps.playwright.conclusion == 'success' }}
|
||||
run: npm run build-storybook
|
||||
working-directory: ui/apps/chat
|
||||
env:
|
||||
# its stories show the Hugging Face lib
|
||||
VITE_PUBLIC_HUGGING_FACE: "true"
|
||||
|
||||
- name: Run UI tests
|
||||
if: ${{ always() && steps.playwright.conclusion == 'success' }}
|
||||
|
||||
+88
-13
@@ -333,13 +333,13 @@ class ModelBase:
|
||||
return scale.numel() <= 1 and abs(float(scale.float().sum()) - 1.0) < 1e-6
|
||||
|
||||
def _write_scale_tensor(self, scale_name: str, scale: Tensor):
|
||||
if not self._scale_is_trivial(scale):
|
||||
if not scale_name.endswith(".input_scale") or not self._scale_is_trivial(scale):
|
||||
scale_f32 = scale.float().numpy().flatten()
|
||||
logger.info(f" + {scale_name} (per-tensor scale, shape [{scale_f32.size}])")
|
||||
self.gguf_writer.add_tensor(scale_name, scale_f32)
|
||||
|
||||
def _write_scales_tensor(self, scale_name: str, scales: list[float]):
|
||||
if not np.allclose(scales, 1.0, atol=1e-6):
|
||||
if not scale_name.endswith(".input_scale") or not np.allclose(scales, 1.0, atol=1e-6):
|
||||
scale_vals = np.array(scales, dtype=np.float32)
|
||||
logger.info(f" + {scale_name} (per-expert scale, shape [{len(scales)}])")
|
||||
self.gguf_writer.add_tensor(scale_name, scale_vals)
|
||||
@@ -689,14 +689,34 @@ class ModelBase:
|
||||
new_name = self.tensor_map.get_name(name, try_suffixes=(".weight",))
|
||||
return (new_name,) if new_name is not None else ()
|
||||
|
||||
def _transform_fp8_scale(self, name: str, scale: Tensor) -> tuple[Tensor, ...] | None:
|
||||
# Return scales in mapped weight order, or None to dequantize.
|
||||
# A new weight transform must also provide scale handling.
|
||||
if type(self).modify_tensors is ModelBase.modify_tensors and len(self._map_fp8_weight_names(name)) == 1:
|
||||
return (scale,)
|
||||
return None
|
||||
|
||||
def _prepare_fp8_e4m3_tensors(self):
|
||||
if not self._preserve_fp8:
|
||||
return
|
||||
|
||||
quant_config = self.hparams.get("quantization_config") or {}
|
||||
fp8_configs = [
|
||||
group["weights"] for group in (quant_config.get("config_groups") or {}).values()
|
||||
if isinstance(group, dict) and group.get("weights", {}).get("type") == "float"
|
||||
and group.get("weights", {}).get("num_bits") == 8
|
||||
]
|
||||
unsupported_layout = quant_config.get("weight_block_size") is not None or any(
|
||||
config.get("strategy") not in (None, "tensor", "channel")
|
||||
or config.get("block_structure") is not None or config.get("group_size") is not None
|
||||
for config in fp8_configs
|
||||
)
|
||||
|
||||
scale_tensors: dict[str, list[tuple[int, float]] | np.ndarray] = {}
|
||||
input_scale_tensors: dict[str, list[tuple[int, float]] | np.ndarray] = {}
|
||||
consumed: list[str] = []
|
||||
candidates: dict[str, tuple[str, Tensor, tuple[str, ...], torch.Size]] = {}
|
||||
channel_scales: dict[str, tuple[Tensor, ...]] = {}
|
||||
weight_dtypes: dict[str, torch.dtype] = {}
|
||||
scaled_weights: set[str] = set()
|
||||
expert_pattern = re.compile(r"(\.[^.]*experts)\.(\d+)\.")
|
||||
@@ -729,8 +749,19 @@ class ModelBase:
|
||||
continue
|
||||
|
||||
scale = self.model_tensors[scale_name]()
|
||||
if prod(scale.shape) != 1:
|
||||
continue
|
||||
# Accept per-tensor or per-output-channel scale layouts.
|
||||
scale_size = prod(scale.shape)
|
||||
is_channel_scale = 1 <= scale.ndim <= weight.ndim and scale.shape[0] == weight.shape[0] and all(size == 1 for size in scale.shape[1:])
|
||||
if unsupported_layout or (scale_size != 1 and not is_channel_scale):
|
||||
if quant_config.get("quant_method") in ("modelopt", "modelopt_mixed") and scale_name.endswith("_scale_inv"):
|
||||
continue
|
||||
if self._is_nvfp4_compressed_tensors(quant_config.get("quant_method"), quant_config.get("format"), quant_config.get("config_groups") or {}):
|
||||
continue
|
||||
raise ValueError(
|
||||
f"FP8 weight {weight_name!r} has an unsupported block/group scale "
|
||||
f"(scale shape {list(scale.shape)}, weight shape {list(weight.shape)}); "
|
||||
f"only per-tensor or per-output-channel scales are supported. "
|
||||
f"Re-run with --fp8-as-q8 to dequantize instead.")
|
||||
|
||||
merged_name = expert_pattern.sub(r"\1.", weight_name)
|
||||
new_names = self._map_fp8_weight_names(merged_name)
|
||||
@@ -743,6 +774,12 @@ class ModelBase:
|
||||
if any(new_name.endswith("_norm.weight") or self.tensor_force_quant(weight_name, new_name, bid, weight.ndim) != gguf.GGMLQuantizationType.F8_E4M3 for new_name in new_names):
|
||||
self._fp8_e4m3_preserved.discard(weight_name)
|
||||
continue
|
||||
if scale_size != 1:
|
||||
transformed = self._transform_fp8_scale(weight_name, scale.reshape(-1, 1)) if weight.ndim == 2 else None
|
||||
if transformed is None or len(transformed) != len(new_names):
|
||||
self._fp8_e4m3_preserved.discard(weight_name)
|
||||
continue
|
||||
channel_scales[weight_name] = transformed
|
||||
candidates[weight_name] = (scale_name, scale, new_names, weight.shape)
|
||||
|
||||
expert_groups: dict[str, list[str]] = {}
|
||||
@@ -758,8 +795,13 @@ class ModelBase:
|
||||
continue
|
||||
if dtypes == {torch.float8_e4m3fn} and not any(name in scaled_weights for name in names):
|
||||
continue
|
||||
scale_sizes: dict[str, set[int]] = {}
|
||||
for name in names:
|
||||
if name in candidates:
|
||||
proj = name.rsplit(".", 2)[1]
|
||||
scale_sizes.setdefault(proj, set()).add(prod(candidates[name][1].shape))
|
||||
# The converter merges expert projections together.
|
||||
if not all(name in candidates for name in names):
|
||||
if not all(name in candidates for name in names) or any(len(sizes) > 1 for sizes in scale_sizes.values()):
|
||||
for name in names:
|
||||
candidates.pop(name, None)
|
||||
self._fp8_e4m3_preserved.discard(name)
|
||||
@@ -769,6 +811,7 @@ class ModelBase:
|
||||
|
||||
for weight_name, (scale_name, scale, new_names, shape) in candidates.items():
|
||||
scale = LazyTorchTensor.to_eager(scale).float().flatten()
|
||||
output_scales = tuple(LazyTorchTensor.to_eager(s).float().flatten() for s in channel_scales.get(weight_name, (scale,) * len(new_names)))
|
||||
|
||||
weight_prefix = weight_name.removesuffix(".weight")
|
||||
# Transformers fine-grained FP8 uses activation_scale while ModelOpt uses input_scale.
|
||||
@@ -792,25 +835,25 @@ class ModelBase:
|
||||
expert_match = expert_pattern.search(weight_name)
|
||||
if expert_match:
|
||||
expert_id = int(expert_match.group(2))
|
||||
for new_name in new_names:
|
||||
for new_name, target_scale in zip(new_names, output_scales):
|
||||
target_name = new_name.replace(".weight", ".scale")
|
||||
entries = scale_tensors.setdefault(target_name, [])
|
||||
assert isinstance(entries, list)
|
||||
cast(list[tuple[int, float]], entries).append((expert_id, float(scale[0])))
|
||||
cast(list, entries).append((expert_id, target_scale.numpy().astype(np.float32)))
|
||||
if input_scale is not None:
|
||||
target_name = new_name.replace(".weight", ".input_scale")
|
||||
entries = input_scale_tensors.setdefault(target_name, [])
|
||||
assert isinstance(entries, list)
|
||||
cast(list[tuple[int, float]], entries).append((expert_id, float(input_scale[0])))
|
||||
else:
|
||||
for new_name in new_names:
|
||||
for new_name, target_scale in zip(new_names, output_scales):
|
||||
mapped = self.tensor_map.get_type_and_name(new_name, try_suffixes=(".weight",)) if len(shape) == 3 else None
|
||||
is_packed_expert = mapped is not None and mapped[0] in (
|
||||
gguf.MODEL_TENSOR.FFN_GATE_EXP, gguf.MODEL_TENSOR.FFN_UP_EXP, gguf.MODEL_TENSOR.FFN_DOWN_EXP,
|
||||
)
|
||||
# Packed expert weights need one scale value per expert.
|
||||
n_scales = shape[0] if is_packed_expert else 1
|
||||
scale_tensors[new_name.replace(".weight", ".scale")] = np.repeat(scale.numpy(), n_scales)
|
||||
scale_tensors[new_name.replace(".weight", ".scale")] = np.repeat(target_scale.numpy(), n_scales)
|
||||
if input_scale is not None:
|
||||
input_scale_tensors[new_name.replace(".weight", ".input_scale")] = np.repeat(input_scale.numpy(), n_scales)
|
||||
|
||||
@@ -820,11 +863,15 @@ class ModelBase:
|
||||
for name, values in chain(scale_tensors.items(), input_scale_tensors.items()):
|
||||
if isinstance(values, list):
|
||||
values.sort(key=lambda item: item[0])
|
||||
scale = np.array([item[1] for item in values], dtype=np.float32)
|
||||
arrays = [np.asarray(item[1], dtype=np.float32).reshape(-1) for item in values]
|
||||
if all(a.size == 1 for a in arrays):
|
||||
scale = np.array([a[0] for a in arrays], dtype=np.float32)
|
||||
else:
|
||||
scale = np.stack(arrays, axis=0)
|
||||
else:
|
||||
scale = values.astype(np.float32)
|
||||
if not np.allclose(scale, 1.0, atol=1e-6):
|
||||
logger.info(f" + {name} (FP8 scale, shape [{scale.size}])")
|
||||
if not name.endswith(".input_scale") or not np.allclose(scale, 1.0, atol=1e-6):
|
||||
logger.info(f" + {name} (FP8 scale, shape {list(scale.shape)})")
|
||||
self.gguf_writer.add_tensor(name, scale)
|
||||
|
||||
@classmethod
|
||||
@@ -1359,6 +1406,8 @@ class ModelBase:
|
||||
scale2_name = name.replace(".weight", ".weight_scale_2")
|
||||
input_scale_name = name.replace(".weight", ".input_scale")
|
||||
if scale_name not in self.model_tensors:
|
||||
if self.model_tensors[name]().dtype == torch.uint8:
|
||||
raise ValueError(f"Cannot convert NVFP4 weight {name!r}: source block scale {scale_name!r} is missing")
|
||||
continue
|
||||
weight = self.model_tensors[name]()
|
||||
scale = self.model_tensors[scale_name]()
|
||||
@@ -1369,9 +1418,11 @@ class ModelBase:
|
||||
if weight.ndim != 2 or scale.shape[0] != weight.shape[0] or scale.shape[1] * 8 != weight.shape[1]:
|
||||
raise ValueError(f"NVFP4 weight {name!r} has incompatible shapes: weight {list(weight.shape)}, scale {list(scale.shape)}")
|
||||
|
||||
if scale2_name not in self.model_tensors:
|
||||
raise ValueError(f"Cannot convert NVFP4 weight {name!r}: source weight scale is missing ({scale2_name!r})")
|
||||
weight = LazyTorchTensor.to_eager(weight)
|
||||
scale = LazyTorchTensor.to_eager(scale)
|
||||
scale2 = LazyTorchTensor.to_eager(self.model_tensors.get(scale2_name, lambda: torch.tensor(1.0))())
|
||||
scale2 = LazyTorchTensor.to_eager(self.model_tensors[scale2_name]())
|
||||
input_scale = LazyTorchTensor.to_eager(self.model_tensors.get(input_scale_name, lambda: torch.tensor(1.0))())
|
||||
|
||||
# Mark tensors for removal from model_tensors (already written to gguf)
|
||||
@@ -1450,7 +1501,19 @@ class ModelBase:
|
||||
self._has_ple |= is_ple
|
||||
return is_ple if self.ple_only else not is_ple
|
||||
|
||||
def _has_fp8_source_scale(self, name: str) -> bool:
|
||||
scale_names = (name + "_scale", name + "_scale_inv", name.removesuffix("weight") + "qscale_weight")
|
||||
return any(scale_name in self.model_tensors for scale_name in scale_names)
|
||||
|
||||
def prepare_tensors(self):
|
||||
for name, load in self.model_tensors.items():
|
||||
if not name.endswith(".weight"):
|
||||
continue
|
||||
if load().dtype not in (torch.float8_e4m3fn, torch.float8_e5m2):
|
||||
continue
|
||||
if not self._has_fp8_source_scale(name):
|
||||
raise ValueError(f"Cannot convert FP8 weight {name!r}: source weight scale is missing")
|
||||
|
||||
# detect NVFP4 quantization (ModelOpt and Compressed-tensors formats)
|
||||
quantization_config = self.hparams.get("quantization_config") or {}
|
||||
quant_algo = quantization_config.get("quant_algo")
|
||||
@@ -1666,6 +1729,18 @@ class ModelBase:
|
||||
if any(qkv_buffers):
|
||||
raise ValueError("QKV fusion did not consume all buffered tensors")
|
||||
|
||||
tensor_names = {name for shard in self.gguf_writer.tensors for name in shard}
|
||||
for shard in self.gguf_writer.tensors:
|
||||
for name, tensor in shard.items():
|
||||
# a PLE-only file holds just the table, its scale stays in the backbone
|
||||
if self.ple_only and self._include_ple_tensor(name):
|
||||
continue
|
||||
# Keep in sync with needs_scale in ggml.c.
|
||||
if tensor.dtype in (gguf.GGMLQuantizationType.F8_E4M3, gguf.GGMLQuantizationType.NVFP4):
|
||||
scale_name = name.removesuffix(".weight") + ".scale"
|
||||
if scale_name not in tensor_names:
|
||||
raise ValueError(f"Cannot export {name!r} as {tensor.dtype.name}: required scale tensor {scale_name!r} is missing (implicit unit scales are not supported)")
|
||||
|
||||
def set_type(self):
|
||||
self.gguf_writer.add_type(gguf.GGUFType.MODEL)
|
||||
|
||||
|
||||
+25
-1
@@ -14,7 +14,7 @@ if TYPE_CHECKING:
|
||||
from .base import ModelBase, SentencePieceTokenTypes, TextModel, gguf, jinja_str_or_json, logger
|
||||
|
||||
|
||||
@ModelBase.register("BertModel", "BertForMaskedLM", "CamembertModel", "BertForSequenceClassification")
|
||||
@ModelBase.register("BertModel", "BertForMaskedLM", "CamembertModel")
|
||||
@ModelBase.example("BAAI/bge-small-en-v1.5", "dangvantuan/sentence-camembert-base")
|
||||
class BertModel(TextModel):
|
||||
model_arch = gguf.MODEL_ARCH.BERT
|
||||
@@ -241,6 +241,30 @@ class BertModel(TextModel):
|
||||
special_vocab.add_to_gguf(self.gguf_writer)
|
||||
|
||||
|
||||
@ModelBase.register("BertForSequenceClassification")
|
||||
@ModelBase.example("cross-encoder/ms-marco-MiniLM-L-12-v2")
|
||||
class BertForSequenceClassification(BertModel):
|
||||
model_arch = gguf.MODEL_ARCH.BERT
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
if self.cls_out_labels is None:
|
||||
self.cls_out_labels = self.hparams.get("id2label")
|
||||
|
||||
@classmethod
|
||||
def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
|
||||
name, gen = item
|
||||
|
||||
name = name.replace("pooler.dense", "classifier.dense")
|
||||
|
||||
return super().filter_tensors((name, gen))
|
||||
|
||||
def set_gguf_parameters(self):
|
||||
if "classifier.dense.weight" in self.model_tensors:
|
||||
self.hparams.setdefault("classifier_activation", "tanh")
|
||||
super().set_gguf_parameters()
|
||||
|
||||
|
||||
@ModelBase.register("DistilBertModel", "DistilBertForMaskedLM", "DistilBertForSequenceClassification")
|
||||
@ModelBase.example("distilbert/distilbert-base-uncased")
|
||||
class DistilBertModel(BertModel):
|
||||
|
||||
+67
-11
@@ -65,6 +65,26 @@ def _dequant_expert_chunk(weight: Callable[[], Tensor], scale: Callable[[], Tens
|
||||
return values
|
||||
|
||||
|
||||
def _repack_nvfp4_rows(packed: np.ndarray, scales: np.ndarray, name: str, expert: int) -> np.ndarray:
|
||||
if np.any(scales & 0x80) or np.any(scales == 0x7F):
|
||||
raise ValueError(f"Inkling2: {name}_scale expert {expert}: NVFP4 block scales must be finite and nonnegative")
|
||||
n_rows = packed.shape[0]
|
||||
n_blocks = scales.shape[1]
|
||||
nibbles = np.stack([packed & 0x0F, packed >> 4], axis=-1).reshape(n_rows, n_blocks, 16)
|
||||
qs = (nibbles[:, :, :8] | (nibbles[:, :, 8:] << 4)).astype(np.uint8)
|
||||
n_super = n_blocks // 4
|
||||
blocks = np.concatenate([scales.reshape(n_rows, n_super, 4), qs.reshape(n_rows, n_super, 32)], axis=-1)
|
||||
return blocks.reshape(n_rows, n_super * 36)
|
||||
|
||||
|
||||
def _repack_nvfp4_expert(weight: Callable[[], Tensor], scale: Callable[[], Tensor], name: str, expert: int, w13: bool) -> np.ndarray:
|
||||
packed = LazyTorchTensor.to_eager(weight().view(torch.uint8)[expert]).numpy()
|
||||
scales = LazyTorchTensor.to_eager(scale().view(torch.uint8)[expert]).numpy()
|
||||
if not w13:
|
||||
return _repack_nvfp4_rows(packed, scales, name, expert)
|
||||
return np.concatenate([_repack_nvfp4_rows(packed[half::2], scales[half::2], name, expert) for half in (0, 1)])
|
||||
|
||||
|
||||
def _is_inkling2(dir_model: Path) -> bool:
|
||||
if not (dir_model / "config.json").is_file():
|
||||
return False
|
||||
@@ -84,9 +104,11 @@ def _load_inkling2_hparams(dir_model: Path):
|
||||
class Inkling2Model(TextModel):
|
||||
model_arch = gguf.MODEL_ARCH.INKLING2
|
||||
|
||||
def __init__(self, dir_model: Path, *args, **kwargs):
|
||||
def __init__(self, dir_model: Path, ftype: gguf.LlamaFileType, *args, **kwargs):
|
||||
self._expert_quant: dict[str, dict] = {}
|
||||
self._packed_experts: dict[str, gguf.LazyChunkedTensor] = {}
|
||||
self._native_experts: dict[str, tuple[gguf.LazyChunkedTensor, np.ndarray]] = {}
|
||||
self._preserve_nvfp4 = ftype == gguf.LlamaFileType.GUESSED
|
||||
quant_path = dir_model / "hf_quant_config.json"
|
||||
if quant_path.is_file():
|
||||
with open(quant_path, encoding="utf-8") as f:
|
||||
@@ -99,7 +121,7 @@ class Inkling2Model(TextModel):
|
||||
if name in self._expert_quant:
|
||||
raise ValueError(f"Inkling2: duplicate hf_quant_config.json scheme for {name}")
|
||||
self._expert_quant[name] = group
|
||||
super().__init__(dir_model, *args, **kwargs)
|
||||
super().__init__(dir_model, ftype, *args, **kwargs)
|
||||
logger.warning("Inkling2: converting the text backbone only; vision and MTP tensors are skipped")
|
||||
hp = self.hparams
|
||||
for name, default in (("q_bias", False), ("o_bias", False), ("n_shared_experts", 0), ("use_value_norm_no_gamma", True), ("attn_res_normalize_values", True), ("scoring_func", "sigmoid")):
|
||||
@@ -165,15 +187,38 @@ class Inkling2Model(TextModel):
|
||||
t = gen()
|
||||
if t.dtype != torch.float32 or tuple(t.shape) != expected:
|
||||
raise ValueError(f"Inkling2: {companion}: expected F32 {expected}, got {t.dtype} {tuple(t.shape)}")
|
||||
chunks: list[Callable[[], np.ndarray]] = []
|
||||
for expert in range(experts):
|
||||
for half in range(2 if w13 else 1):
|
||||
for start in range(0, rows // 2 if w13 else rows, _EXPERT_CHUNK_ROWS):
|
||||
stop = min(start + _EXPERT_CHUNK_ROWS, rows // 2 if w13 else rows)
|
||||
# The same packed row slice selects the weight and its scale groups.
|
||||
row_slice = slice(2 * start + half, 2 * stop + half, 2) if w13 else slice(start, stop)
|
||||
chunks.append(partial(_dequant_expert_chunk, weight, scale, amax, denominator, name, expert, row_slice))
|
||||
self._packed_experts[name] = gguf.LazyChunkedTensor(chunks, shape, np.float32)
|
||||
preserve_nvfp4 = nvfp4 and self._preserve_nvfp4
|
||||
if preserve_nvfp4 and cols % 64 != 0:
|
||||
logger.warning("Inkling2: %s: %d columns are not a multiple of 64; dequantizing NVFP4", name, cols)
|
||||
preserve_nvfp4 = False
|
||||
chunks: list[Callable[[], np.ndarray]]
|
||||
if preserve_nvfp4:
|
||||
assert amax is not None and denominator is not None
|
||||
a = LazyTorchTensor.to_eager(amax()).numpy().astype(np.float32)
|
||||
d = LazyTorchTensor.to_eager(denominator()).numpy().astype(np.float32)
|
||||
if not np.isfinite(a).all() or (a < 0).any():
|
||||
raise ValueError(f"Inkling2: {name}_amax: expected finite nonnegative values")
|
||||
if not np.isfinite(d).all() or (d <= 0).any():
|
||||
raise ValueError(f"Inkling2: {name}_outer_scale_denominator: expected finite positive value")
|
||||
with np.errstate(over="ignore", invalid="ignore"):
|
||||
outer_scale = a / d
|
||||
if not np.isfinite(outer_scale).all():
|
||||
raise ValueError(f"Inkling2: {name}: non-finite outer scale")
|
||||
chunks = [partial(_repack_nvfp4_expert, weight, scale, name, expert, w13) for expert in range(experts)]
|
||||
byte_shape = (experts, rows, cols // 64 * 36)
|
||||
self._native_experts[name] = (gguf.LazyChunkedTensor(chunks, byte_shape, np.uint8), outer_scale)
|
||||
else:
|
||||
chunks = []
|
||||
for expert in range(experts):
|
||||
for half in range(2 if w13 else 1):
|
||||
for start in range(0, rows // 2 if w13 else rows, _EXPERT_CHUNK_ROWS):
|
||||
stop = min(start + _EXPERT_CHUNK_ROWS, rows // 2 if w13 else rows)
|
||||
# The same packed row slice selects the weight and its scale groups.
|
||||
row_slice = slice(2 * start + half, 2 * stop + half, 2) if w13 else slice(start, stop)
|
||||
chunks.append(partial(_dequant_expert_chunk, weight, scale, amax, denominator, name, expert, row_slice))
|
||||
self._packed_experts[name] = gguf.LazyChunkedTensor(chunks, shape, np.float32)
|
||||
if not nvfp4 and self._fp8_as_q8:
|
||||
self._fp8_dequantized.add(name)
|
||||
self.model_tensors[name] = lambda shape=shape: torch.empty(shape, dtype=torch.float32, device="meta")
|
||||
for companion in required:
|
||||
del self.model_tensors[companion]
|
||||
@@ -181,6 +226,7 @@ class Inkling2Model(TextModel):
|
||||
t = gen()
|
||||
if not t.dtype.is_floating_point or t.element_size() == 1 or name.endswith(("_weight_scale", "_weight_amax", "_weight_outer_scale_denominator")):
|
||||
raise ValueError(f"Inkling2: unexpected packed tensor or orphan companion {name}")
|
||||
self._is_nvfp4 = bool(self._native_experts)
|
||||
|
||||
@classmethod
|
||||
def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
|
||||
@@ -254,6 +300,16 @@ class Inkling2Model(TextModel):
|
||||
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._native_experts:
|
||||
target = name.replace(".w13_weight", ".gate_up_proj").replace(".w2_weight", ".down_proj")
|
||||
new_name = self.map_tensor_name(target, try_suffixes=()) + ".weight"
|
||||
packed, scale = self._native_experts[name]
|
||||
shape = gguf.quant_shape_from_byte_shape(packed.shape, gguf.GGMLQuantizationType.NVFP4)
|
||||
shape_str = f"{{{', '.join(str(n) for n in reversed(shape))}}}"
|
||||
logger.info(f"{new_name}, NVFP4 --> NVFP4, shape = {shape_str}")
|
||||
self.gguf_writer.add_tensor(new_name, cast("np.ndarray", packed), raw_dtype=gguf.GGMLQuantizationType.NVFP4)
|
||||
self._write_scales_tensor(new_name.removesuffix(".weight") + ".scale", scale.tolist())
|
||||
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])
|
||||
|
||||
@@ -181,6 +181,18 @@ class LlamaModel(TextModel):
|
||||
.swapaxes(1, 2)
|
||||
.reshape(weights.shape))
|
||||
|
||||
def _transform_fp8_scale(self, name: str, scale: Tensor) -> tuple[Tensor, ...] | None:
|
||||
if type(self).modify_tensors is not LlamaModel.modify_tensors:
|
||||
return None
|
||||
if self.undo_permute:
|
||||
n_head = self.find_hparam(["n_heads", "num_attention_heads"])
|
||||
n_kv_head = self.find_hparam(["n_kv_heads", "num_key_value_heads"])
|
||||
if name.endswith("q_proj.weight"):
|
||||
scale = self.permute(scale, n_head, n_head)
|
||||
elif name.endswith("k_proj.weight"):
|
||||
scale = self.permute(scale, n_head, n_kv_head)
|
||||
return (scale,)
|
||||
|
||||
def _repack_nvfp4(self, name: str, weight: Tensor, scale: Tensor, scale2: Tensor, input_scale: Tensor):
|
||||
# Mirror the BF16 Q/K RoPE permutation site in modify_tensors; the NVFP4 path bypasses it.
|
||||
if self.undo_permute:
|
||||
|
||||
+93
-41
@@ -58,6 +58,11 @@ class QwenModel(TextModel):
|
||||
class Qwen2Model(TextModel):
|
||||
model_arch = gguf.MODEL_ARCH.QWEN2
|
||||
|
||||
def _transform_fp8_scale(self, name: str, scale: Tensor) -> tuple[Tensor, ...] | None:
|
||||
if type(self).modify_tensors is Qwen2Model.modify_tensors and len(self._map_fp8_weight_names(name)) == 1:
|
||||
return (scale,)
|
||||
return None
|
||||
|
||||
def set_vocab(self):
|
||||
# HuggingFaceBio/Carbon-14B: Qwen3 with the HybridDNATokenizer (Qwen3 BPE plus DNA 6-mers)
|
||||
if self._is_hybriddna():
|
||||
@@ -92,6 +97,11 @@ class Qwen2MoeModel(TextModel):
|
||||
)
|
||||
return super()._map_fp8_weight_names(name)
|
||||
|
||||
def _transform_fp8_scale(self, name: str, scale: Tensor) -> tuple[Tensor, ...] | None:
|
||||
if type(self).modify_tensors is Qwen2MoeModel.modify_tensors and len(self._map_fp8_weight_names(name)) == 1:
|
||||
return (scale,)
|
||||
return None
|
||||
|
||||
def set_gguf_parameters(self):
|
||||
super().set_gguf_parameters()
|
||||
if (moe_intermediate_size := self.hparams.get("moe_intermediate_size")) is not None:
|
||||
@@ -395,13 +405,50 @@ class Qwen3NextModel(_QwenMtpMixin, Qwen2MoeModel):
|
||||
def _map_fp8_weight_names(self, name: str) -> tuple[str, ...]:
|
||||
if name.endswith(".linear_attn.in_proj_qkvz.weight"):
|
||||
bid = next(int(part) for part in self.map_tensor_name(name).split(".") if part.isdecimal())
|
||||
# Both split projections keep the original per-tensor scales.
|
||||
return (
|
||||
self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_QKV, bid),
|
||||
self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_GATE, bid),
|
||||
)
|
||||
return super()._map_fp8_weight_names(name)
|
||||
|
||||
def _transform_fp8_scale(self, name: str, scale: Tensor) -> tuple[Tensor, ...] | None:
|
||||
if type(self).modify_tensors is not Qwen3NextModel.modify_tensors:
|
||||
return None
|
||||
if name.endswith(".linear_attn.in_proj_qkvz.weight"):
|
||||
return self._split_qkvz(scale)
|
||||
if len(self._map_fp8_weight_names(name)) == 1:
|
||||
return (scale,)
|
||||
return None
|
||||
|
||||
def _split_qkvz(self, data_torch: Tensor) -> tuple[Tensor, Tensor]:
|
||||
# original order: [q, k, v, z] * head_count
|
||||
# corrected order: [q * head_count, k * head_count, v * head_count, z * head_count]
|
||||
head_k_dim = self.hparams["linear_key_head_dim"]
|
||||
head_v_dim = self.hparams["linear_value_head_dim"]
|
||||
num_v_heads = self.hparams["linear_num_value_heads"]
|
||||
num_k_heads = self.hparams["linear_num_key_heads"]
|
||||
hidden_size = data_torch.shape[1]
|
||||
split_arg_list_qkvz = [
|
||||
head_k_dim, # q partition
|
||||
head_k_dim, # k partition
|
||||
(num_v_heads // num_k_heads * head_v_dim), # v partition
|
||||
(num_v_heads // num_k_heads * head_v_dim), # z partition
|
||||
]
|
||||
# view as (n_embd, head_count, [q+k+v+z])
|
||||
data_torch = data_torch.permute(1, 0).contiguous()
|
||||
data_torch = data_torch.view(-1, num_k_heads, sum(split_arg_list_qkvz))
|
||||
# split into q, k, v, z
|
||||
q, k, v, z = torch.split(data_torch, split_arg_list_qkvz, dim=-1)
|
||||
# flatten dim + head_count
|
||||
q = q.contiguous().view(hidden_size, -1)
|
||||
k = k.contiguous().view(hidden_size, -1)
|
||||
v = v.contiguous().view(hidden_size, -1)
|
||||
z = z.contiguous().view(hidden_size, -1)
|
||||
# stack back
|
||||
qkv = torch.cat([q, k, v], dim=-1).permute(1, 0).contiguous()
|
||||
z = z.permute(1, 0).contiguous()
|
||||
return qkv, z
|
||||
|
||||
def set_gguf_parameters(self):
|
||||
super().set_gguf_parameters()
|
||||
self.gguf_writer.add_ssm_conv_kernel(self.hparams["linear_conv_kernel_dim"])
|
||||
@@ -432,32 +479,7 @@ class Qwen3NextModel(_QwenMtpMixin, Qwen2MoeModel):
|
||||
data_torch = data_torch + 1
|
||||
|
||||
if "in_proj_qkvz.weight" in name:
|
||||
# original order: [q, k, v, z] * head_count
|
||||
# corrected order: [q * head_count, k * head_count, v * head_count, z * head_count]
|
||||
head_k_dim = self.hparams["linear_key_head_dim"]
|
||||
head_v_dim = self.hparams["linear_value_head_dim"]
|
||||
num_v_heads = self.hparams["linear_num_value_heads"]
|
||||
num_k_heads = self.hparams["linear_num_key_heads"]
|
||||
hidden_size = self.hparams["hidden_size"]
|
||||
split_arg_list_qkvz = [
|
||||
head_k_dim, # q partition
|
||||
head_k_dim, # k partition
|
||||
(num_v_heads // num_k_heads * head_v_dim), # v partition
|
||||
(num_v_heads // num_k_heads * head_v_dim), # z partition
|
||||
]
|
||||
# view as (n_embd, head_count, [q+k+v+z])
|
||||
data_torch = data_torch.permute(1, 0).contiguous()
|
||||
data_torch = data_torch.view(-1, num_k_heads, sum(split_arg_list_qkvz))
|
||||
# split into q, k, v, z
|
||||
q, k, v, z = torch.split(data_torch, split_arg_list_qkvz, dim=-1)
|
||||
# flatten dim + head_count
|
||||
q = q.contiguous().view(hidden_size, -1)
|
||||
k = k.contiguous().view(hidden_size, -1)
|
||||
v = v.contiguous().view(hidden_size, -1)
|
||||
z = z.contiguous().view(hidden_size, -1)
|
||||
# stack back
|
||||
qkv = torch.cat([q, k, v], dim=-1).permute(1, 0).contiguous()
|
||||
z = z.permute(1, 0).contiguous()
|
||||
qkv, z = self._split_qkvz(data_torch)
|
||||
yield (self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_QKV, bid, ".weight"), qkv)
|
||||
yield (self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_GATE, bid, ".weight"), z)
|
||||
else:
|
||||
@@ -868,6 +890,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 +955,11 @@ class DFlashModel(Qwen3Model):
|
||||
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 +985,10 @@ class DFlashModel(Qwen3Model):
|
||||
|
||||
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 +1015,6 @@ class DFlashModel(Qwen3Model):
|
||||
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 +1032,23 @@ class DFlashModel(Qwen3Model):
|
||||
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 +1111,8 @@ class DFlashModel(Qwen3Model):
|
||||
"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)
|
||||
|
||||
@@ -54,6 +54,12 @@ class Qwen4ExpTextModel(_Qwen35MRopeMixin, _LinearAttentionVReorderBase):
|
||||
self._ple_scale = float(scale[0])
|
||||
super().dequant_model()
|
||||
|
||||
def _has_fp8_source_scale(self, name: str) -> bool:
|
||||
if ".ngram_embedding.shard_" in name:
|
||||
prefix = name.split(".ngram_embedding.shard_")[0]
|
||||
return prefix + ".ngram_embedding.weight_scale" in self.model_tensors or self._ple_scale is not None
|
||||
return super()._has_fp8_source_scale(name)
|
||||
|
||||
@classmethod
|
||||
def filter_tensors(cls, item):
|
||||
name, gen = item
|
||||
|
||||
@@ -110,7 +110,7 @@ Although OpenVINO supports a wide range of [Intel hardware](https://docs.openvin
|
||||
|
||||
**NPU:**
|
||||
- All other quantized tensors are requantized to `Q4_0_128`.
|
||||
- For a `Q6_K` token embedding, `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` selects another layout.
|
||||
- For a `Q6_K` token embedding, `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` selects another layout. When it is set, it also applies to a `Q4_K` or `Q5_K` token embedding.
|
||||
- The validated models use `Q4_K_M` files.
|
||||
|
||||
**Layout names:**
|
||||
@@ -882,7 +882,9 @@ The defaults fit most models. The variables below trade one property for another
|
||||
| Variable | Device | Type | Default | Description |
|
||||
|---|---|---|---|---|
|
||||
| `GGML_OPENVINO_PREFILL_CHUNK_SIZE` | NPU | Integer | `256` | Number of tokens that the NPU processes in one prefill step. A larger value can make long prompts faster, and makes the first load longer. Zero or a negative value means the default. Example: `GGML_OPENVINO_PREFILL_CHUNK_SIZE=512`. |
|
||||
| `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` | NPU | String | `q8_0_c` | How a `Q6_K` `token_embd.weight` is stored for the NPU: `q8_0_c` (8-bit, one scale per row), `f16`, `q4_0_128` (4-bit, one scale per 128 weights) or `q4_0_c` (4-bit, one scale per row). The 4-bit layouts use less memory at some cost in accuracy; `f16` uses more memory. Keep the default unless memory is tight. |
|
||||
| `GGML_OPENVINO_KV_ONLY_PREFILL` | NPU | Boolean | `1` | For models whose last layers reuse the KV cache of an earlier layer (Gemma 3n and Gemma 4 E2B/E4B): compile the prefill with only the KV-cache writes as outputs, which drops those layers and the output layer from it, and compute the output token of a batch with one decode step. Takes effect only without `GGML_OPENVINO_NPU_HFA_PREFILL`, and not for models with recurrent state; with decode KV windows (`GGML_OPENVINO_NPU_BLOB_PREBUILD=1`) the output step runs the decode graph of the window that covers the output token. A batch that needs more than one output token switches to the full prefill. `0` turns it off. |
|
||||
| `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` | NPU | String | `q8_0_c` | How a `Q6_K` `token_embd.weight` is stored for the NPU: `q8_0_c` (8-bit, one scale per row), `f16`, `q4_0_128` (4-bit, one scale per 128 weights) or `q4_0_c` (4-bit, one scale per row). The 4-bit layouts use less memory at some cost in accuracy; `f16` uses more memory. Keep the default unless memory is tight. When set, it also applies to a `Q4_K` or `Q5_K` `token_embd.weight`, which otherwise keeps the 8-bit layout of the other weights; with a tied output layer (Gemma 4 E2B) `q4_0_128` stores it in about half the memory. |
|
||||
| `GGML_OPENVINO_NPU_HOST_GATHER` | NPU | Boolean | `0` | Look up the rows of large embedding tables (64 MiB or more) on the host, from the GGUF data, and pass them to the NPU graph as an input, instead of binding the whole table to the NPU. A table used only for such lookups, such as the per-layer embedding table of Gemma 3n and Gemma 4 E2B/E4B, is then not converted for the NPU at all. Lowers memory and decode time for such models. |
|
||||
| `GGML_OPENVINO_GDN_DECOMPOSE` | all | Boolean | auto | Translate `GATED_DELTA_NET` (Qwen3.5) into MatMul operations instead of the OpenVINO `GatedDeltaNet` op. Unset: on for the Lunar Lake NPU, off elsewhere. `0` turns it off, `1` turns it on for any device. Try `1` for Qwen3.5 on the Panther Lake NPU. |
|
||||
| `GGML_OPENVINO_MANUAL_GQA_ATTN` | CPU, GPU | Boolean | on for GPU | Build grouped-query attention from separate MatMul operations. Unset: on for GPU, off for CPU and NPU. `1` turns it on, `0` turns it off. Try `1` on the CPU for faster decode. |
|
||||
| `GGML_OPENVINO_REQUANT_KQUANT` | CPU, GPU | String | `not set` | Requantize `Q6_K` and `Q5_K` weights to a 4-bit layout instead of `Q8_0_C`: faster decode for lower accuracy. One of `q4_asym64`, `q4_asym64_all` (also `Q4_K`), `q4_sym128`, `q4_sym128_all` (also `Q4_K`) or `native` (no requantization). On GPU with `Q4_K_M` files use `q4_asym64_all`, because `q4_asym64` does not compile there. |
|
||||
@@ -903,10 +905,10 @@ export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache
|
||||
# CPU or GPU, later runs (optional): require the cached model and skip the weight upload and the compilation.
|
||||
export GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1
|
||||
|
||||
# NPU: add the weightless bank.
|
||||
# NPU: valid cached models are imported. Otherwise the run compiles them, writes them without weights plus one
|
||||
# shared weights file, and logs a warning.
|
||||
export GGML_OPENVINO_DEVICE=NPU
|
||||
export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache
|
||||
export GGML_OPENVINO_NPU_WEIGHTLESS_BANK=1
|
||||
./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512
|
||||
|
||||
# NPU, later runs (optional): use less memory. The run fails if a cached model is missing.
|
||||
@@ -919,12 +921,11 @@ export GGML_OPENVINO_SELF_CONTAINED_MMAP=1
|
||||
| Variable | Device | Type | Default | Description |
|
||||
|---|---|---|---|---|
|
||||
| `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY` | CPU, GPU | Boolean | `0` | Require an existing cached model and skip the weight upload and the compilation. Needs mmap model loading (the default on Linux and Windows) and a model that runs fully on OpenVINO. |
|
||||
| `GGML_OPENVINO_NPU_WEIGHTLESS_BANK` | NPU | Boolean | `0` | Requires `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`. Write the prefill and decode models without weights, plus one shared weights file. Later runs read the weights from that file and keep one copy in memory. |
|
||||
| `GGML_OPENVINO_SELF_CONTAINED_MMAP` | NPU | Boolean | `0` | Later runs only. Requires `GGML_OPENVINO_NPU_WEIGHTLESS_BANK=1` and an existing cache. Use the memory-mapped GGUF file as the model buffer, which lowers the host memory peak. Fails if a cached model is missing; run once without it to build the cache. |
|
||||
| `GGML_OPENVINO_SELF_CONTAINED_MMAP` | NPU | Boolean | `0` | Later runs only. Requires `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` with an existing cache. Use the memory-mapped GGUF file as the model buffer, which lowers the host memory peak. Fails if a cached model is missing, for example after a change of the model, `-c` or another setting; run once without it to build the cache. |
|
||||
| `GGML_OPENVINO_CACHE_DIR` | all | String | `not set` | Directory for the cache of the OpenVINO plugin itself. `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` is the recommended cache. |
|
||||
|
||||
- One directory can hold the cached models of different models and settings.
|
||||
- NPU: each prefill length enters the cache in a run without `GGML_OPENVINO_SELF_CONTAINED_MMAP`.
|
||||
- NPU, with the default settings: the first prompt writes the prefill model of every KV window up to `-c`, so later runs with the same `-c` find a cached model for any prompt length.
|
||||
- See [Compiled model cache](../../ggml/src/ggml-openvino/README.md#compiled-model-cache) for the workflow and the restrictions.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -818,6 +818,7 @@ User can use the device management in [docs/multi-gpu.md](https://github.com/ggm
|
||||
| GGML_SYCL_ENABLE_VMM | 0 or 1 (default) | Enable the virtual-memory device pool. |
|
||||
| GGML_SYCL_ENABLE_MKL_FA | 1 (default) or 0 | Enable oneMKL GEMM flash attention for XMX-accelerated prompt processing with quantized KV cache. Automatically activates during prefill (prompt processing) when all conditions are met: (1) flash-attn enabled (`-fa` or `--flash-attn on`), (2) KV cache quantized (`--cache-type-k q8_0 --cache-type-v q8_0` or other `*_0/*_1` types), (3) batch size ≥ 1024 (`--batch-size 1024`), (4) prompt length ≥ 1024 tokens. Set to 0 to force the TILE kernel for A/B testing. Example minimum command: `llama-cli -m model.gguf -fa -ngl 99 --cache-type-k q8_0 --cache-type-v q8_0 --batch-size 1024 -p "your prompt"` |
|
||||
| GGML_SYCL_MKL_FA_DEBUG | 0 (default) or 1 | Enable per-call diagnostic logging for MKL flash attention: GEMM/softmax timings, interleaved-head detection, and buffer memory usage. |
|
||||
| GGML_SYCL_FA_TILE_DEBUG | 0 (default) or 1 | Enable per-call diagnostic logging for the flash-attention TILE kernel dispatcher: head dims (DKQ/DV), GQA ratio, query rows, KV length, and whether the GQA-optimized variant is selected. |
|
||||
| GGML_SYCL_MEMTRACE | 0 (default), 1, 2 | Enable record and output memory allocation diagnostics. Requires `-lv 4`. <br>0 - Disable<br>1 - Basic memory info, including current and peak allocations, as well allocations from other sources, and the device free memory before each model buffer allocation, around 50 lines per model load.<br>2 - More verbose, logging around 900 specific allocations and deallocations. |
|
||||
| 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. |
|
||||
|
||||
@@ -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"
|
||||
];
|
||||
|
||||
|
||||
+25
-1
@@ -607,6 +607,7 @@ extern "C" {
|
||||
GGML_API size_t ggml_element_size(const struct ggml_tensor * tensor);
|
||||
|
||||
GGML_API bool ggml_is_quantized(enum ggml_type type);
|
||||
GGML_API bool ggml_needs_scale(enum ggml_type type);
|
||||
|
||||
// TODO: temporary until model loading of ggml examples is refactored
|
||||
GGML_API enum ggml_type ggml_ftype_to_ggml_type(enum ggml_ftype ftype);
|
||||
@@ -1322,6 +1323,16 @@ extern "C" {
|
||||
struct ggml_tensor * a,
|
||||
struct ggml_tensor * b);
|
||||
|
||||
// scale_weight is F32, either a scalar or one value per output channel.
|
||||
// scale_activations is an optional F32 scalar for activation quantization.
|
||||
// Divide activations by the scale before quantization, then multiply the matmul result by the scale.
|
||||
GGML_API struct ggml_tensor * ggml_mul_mat_ext(
|
||||
struct ggml_context * ctx,
|
||||
struct ggml_tensor * a,
|
||||
struct ggml_tensor * b,
|
||||
struct ggml_tensor * scale_weight,
|
||||
struct ggml_tensor * scale_activations);
|
||||
|
||||
// change the hint of a matrix multiplication
|
||||
GGML_API void ggml_mul_mat_set_hint(
|
||||
struct ggml_tensor * a,
|
||||
@@ -1335,6 +1346,16 @@ extern "C" {
|
||||
struct ggml_tensor * b,
|
||||
struct ggml_tensor * ids);
|
||||
|
||||
// scale_weight: [1], [n_as] or [n_out, n_as], selected by ids
|
||||
// scale_activations: [1] or [n_as], selected by ids
|
||||
GGML_API struct ggml_tensor * ggml_mul_mat_id_ext(
|
||||
struct ggml_context * ctx,
|
||||
struct ggml_tensor * as,
|
||||
struct ggml_tensor * b,
|
||||
struct ggml_tensor * ids,
|
||||
struct ggml_tensor * scale_weight,
|
||||
struct ggml_tensor * scale_activations);
|
||||
|
||||
// A: m columns, n rows,
|
||||
// B: p columns, n rows,
|
||||
// result is m columns, p rows
|
||||
@@ -2813,12 +2834,14 @@ extern "C" {
|
||||
typedef void (*ggml_to_float_t) (const void * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k);
|
||||
typedef void (*ggml_from_float_t)(const float * GGML_RESTRICT x, void * GGML_RESTRICT y, int64_t k);
|
||||
|
||||
// TODO: deprecate struct definition from the public API, replace with functions [TAG_GGML_AVOID_PUBLIC_STRUCTS]
|
||||
struct ggml_type_traits {
|
||||
const char * type_name;
|
||||
int64_t blck_size;
|
||||
int64_t blck_size_interleave; // interleave elements in blocks
|
||||
size_t type_size;
|
||||
bool is_quantized;
|
||||
bool is_quantized; // whether it's a block-quantized data-type
|
||||
//bool needs_scale; // add this flag in the next update [TAG_GGML_VERSION_MAJOR_UPDATE]
|
||||
ggml_to_float_t to_float;
|
||||
ggml_from_float_t from_float_ref;
|
||||
};
|
||||
@@ -2840,6 +2863,7 @@ extern "C" {
|
||||
|
||||
// threadpool params
|
||||
// Use ggml_threadpool_params_default() or ggml_threadpool_params_init() to populate the defaults
|
||||
// TODO: deprecate struct definition from the public API, replace with functions [TAG_GGML_AVOID_PUBLIC_STRUCTS]
|
||||
struct ggml_threadpool_params {
|
||||
bool cpumask[GGML_MAX_N_THREADS]; // mask of cpu cores (all-zeros means use default affinity settings)
|
||||
int n_threads; // number of threads
|
||||
|
||||
@@ -704,11 +704,9 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state(
|
||||
};
|
||||
|
||||
auto handle_view = [&](const std::vector<ggml_backend_meta_split_state> & src_ss) -> ggml_backend_meta_split_state {
|
||||
if (ggml_is_contiguous(tensor) && ggml_is_contiguous(tensor->src[0])) {
|
||||
return handle_reshape(src_ss);
|
||||
}
|
||||
const int axis = src_ss[0].axis;
|
||||
{
|
||||
// Keep the split axis when strides match; reshape is ambiguous across singleton dimensions.
|
||||
bool all_strides_the_same = true;
|
||||
for (int dim = 0; dim < GGML_MAX_DIMS; dim++) {
|
||||
if (tensor->ne[dim] == 1 && tensor->src[0]->ne[dim] == 1) {
|
||||
@@ -723,6 +721,9 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state(
|
||||
return src_ss[0];
|
||||
}
|
||||
}
|
||||
if (ggml_is_contiguous(tensor) && ggml_is_contiguous(tensor->src[0])) {
|
||||
return handle_reshape(src_ss);
|
||||
}
|
||||
if (!ggml_is_permuted(tensor) && !ggml_is_permuted(tensor->src[0]) && axis >= 0 && axis < GGML_MAX_DIMS-1) {
|
||||
for (int dim = 0; dim < GGML_MAX_DIMS-1; dim++) {
|
||||
if (tensor->nb[dim+1] == tensor->src[0]->nb[axis+1]) {
|
||||
|
||||
@@ -398,6 +398,10 @@ static bool ggml_backend_blas_device_supports_op(ggml_backend_dev_t dev, const s
|
||||
const struct ggml_tensor * src0 = op->src[0];
|
||||
const struct ggml_tensor * src1 = op->src[1];
|
||||
|
||||
if (ggml_get_src_scale(op, 0)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (op->op) {
|
||||
case GGML_OP_NONE:
|
||||
case GGML_OP_RESHAPE:
|
||||
|
||||
@@ -2405,6 +2405,10 @@ static enum ggml_status ggml_backend_cann_graph_compute(ggml_backend_t backend,
|
||||
* otherwise false.
|
||||
*/
|
||||
static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
|
||||
if (ggml_get_src_scale(op, 0)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (op->op) {
|
||||
case GGML_OP_UNARY:
|
||||
switch (ggml_get_unary_op(op)) {
|
||||
|
||||
@@ -1306,6 +1306,38 @@ static void ggml_cpu_bf16_to_vec_dot_type(const ggml_bf16_t * x, void * y, int64
|
||||
}
|
||||
}
|
||||
|
||||
// apply the weight scale (src[2]) carried by ggml_mul_mat_ext, broadcast over dst
|
||||
static void ggml_compute_forward_mul_mat_scale(
|
||||
const struct ggml_compute_params * params,
|
||||
struct ggml_tensor * dst) {
|
||||
const struct ggml_tensor * scale = dst->src[2];
|
||||
if (!scale) {
|
||||
return;
|
||||
}
|
||||
|
||||
const int ith = params->ith;
|
||||
const int nth = params->nth;
|
||||
|
||||
const int64_t ne0 = dst->ne[0], ne1 = dst->ne[1], ne2 = dst->ne[2], ne3 = dst->ne[3];
|
||||
const size_t nb1 = dst->nb[1], nb2 = dst->nb[2], nb3 = dst->nb[3];
|
||||
|
||||
ggml_barrier(params->threadpool);
|
||||
|
||||
const char * sd = (const char *) scale->data;
|
||||
const int64_t sne0 = scale->ne[0], sne1 = scale->ne[1], sne2 = scale->ne[2], sne3 = scale->ne[3];
|
||||
const int64_t nr = ne1 * ne2 * ne3;
|
||||
for (int64_t ir = ith; ir < nr; ir += nth) {
|
||||
const int64_t i1 = ir % ne1;
|
||||
const int64_t i2 = (ir / ne1) % ne2;
|
||||
const int64_t i3 = ir / (ne1 * ne2);
|
||||
float * dp = (float *) ((char *) dst->data + i1*nb1 + i2*nb2 + i3*nb3);
|
||||
const size_t so = (i1 % sne1)*scale->nb[1] + (i2 % sne2)*scale->nb[2] + (i3 % sne3)*scale->nb[3];
|
||||
for (int64_t i0 = 0; i0 < ne0; i0++) {
|
||||
dp[i0] *= *(const float *) (sd + (i0 % sne0)*scale->nb[0] + so);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ggml_compute_forward_mul_mat(
|
||||
const struct ggml_compute_params * params,
|
||||
struct ggml_tensor * dst) {
|
||||
@@ -1321,6 +1353,7 @@ void ggml_compute_forward_mul_mat(
|
||||
|
||||
// If tiled is supported, it will execute the full op here and we return
|
||||
if (ggml_compute_forward_mul_mat_tiled(params, dst)) {
|
||||
ggml_compute_forward_mul_mat_scale(params, dst);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1377,6 +1410,7 @@ void ggml_compute_forward_mul_mat(
|
||||
src1->type,
|
||||
dst->type))
|
||||
goto UseGgmlGemm1;
|
||||
ggml_compute_forward_mul_mat_scale(params, dst);
|
||||
return;
|
||||
}
|
||||
UseGgmlGemm1:;
|
||||
@@ -1457,6 +1491,7 @@ UseGgmlGemm1:;
|
||||
vec_dot_type,
|
||||
dst->type))
|
||||
goto UseGgmlGemm2;
|
||||
ggml_compute_forward_mul_mat_scale(params, dst);
|
||||
return;
|
||||
}
|
||||
UseGgmlGemm2:;
|
||||
@@ -1524,6 +1559,8 @@ UseGgmlGemm2:;
|
||||
|
||||
current_chunk = atomic_fetch_add_explicit(¶ms->threadpool->current_chunk, 1, memory_order_relaxed);
|
||||
}
|
||||
|
||||
ggml_compute_forward_mul_mat_scale(params, dst);
|
||||
}
|
||||
|
||||
// ggml_compute_forward_mul_mat_id
|
||||
@@ -1606,6 +1643,53 @@ static void * incr_ptr_aligned(void ** p, size_t size, size_t align) {
|
||||
return ptr;
|
||||
}
|
||||
|
||||
// apply the weight scale (src[3]) carried by ggml_mul_mat_id_ext: per-tensor [1],
|
||||
// per-expert [n_expert] or per-channel-per-expert [n_out, n_expert], indexed via ids
|
||||
static void ggml_compute_forward_mul_mat_id_scale(
|
||||
const struct ggml_compute_params * params,
|
||||
struct ggml_tensor * dst) {
|
||||
const struct ggml_tensor * scale = dst->src[3];
|
||||
if (!scale) {
|
||||
return;
|
||||
}
|
||||
|
||||
const struct ggml_tensor * ids = dst->src[2];
|
||||
|
||||
const int ith = params->ith;
|
||||
const int nth = params->nth;
|
||||
|
||||
const int64_t ne0 = dst->ne[0], ne1 = dst->ne[1], ne2 = dst->ne[2];
|
||||
const int64_t ne02 = dst->src[0]->ne[2];
|
||||
const size_t nb1 = dst->nb[1], nb2 = dst->nb[2];
|
||||
|
||||
ggml_barrier(params->threadpool);
|
||||
|
||||
const char * sd = (const char *) scale->data;
|
||||
const bool per_ch_exp = scale->ne[0] == ne0 && scale->ne[1] == ne02;
|
||||
const bool per_expert = ggml_nelements(scale) == ne02;
|
||||
const int64_t nr = ne1 * ne2;
|
||||
for (int64_t ir = ith; ir < nr; ir += nth) {
|
||||
const int64_t i1 = ir % ne1;
|
||||
const int64_t i2 = ir / ne1;
|
||||
const int32_t expert = *(const int32_t *) ((const char *) ids->data + i1*ids->nb[0] + i2*ids->nb[1]);
|
||||
if (expert < 0) {
|
||||
continue;
|
||||
}
|
||||
float * dp = (float *) ((char *) dst->data + i1*nb1 + i2*nb2);
|
||||
if (per_ch_exp) {
|
||||
const char * sp = sd + expert*scale->nb[1];
|
||||
for (int64_t i0 = 0; i0 < ne0; i0++) {
|
||||
dp[i0] *= *(const float *) (sp + i0*scale->nb[0]);
|
||||
}
|
||||
} else {
|
||||
const float s = *(const float *) (sd + (per_expert ? expert*scale->nb[0] : 0));
|
||||
for (int64_t i0 = 0; i0 < ne0; i0++) {
|
||||
dp[i0] *= s;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void ggml_compute_forward_mul_mat_id(
|
||||
const struct ggml_compute_params * params,
|
||||
struct ggml_tensor * dst) {
|
||||
@@ -1800,6 +1884,8 @@ static void ggml_compute_forward_mul_mat_id(
|
||||
current_chunk = atomic_fetch_add_explicit(current_chunk_ctr, 1, memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
ggml_compute_forward_mul_mat_id_scale(params, dst);
|
||||
}
|
||||
|
||||
/////////////////////////////////
|
||||
@@ -1813,6 +1899,11 @@ static void ggml_compute_forward(struct ggml_compute_params * params, struct ggm
|
||||
|
||||
// extra_buffer op?
|
||||
if (ggml_cpu_extra_compute_forward(params, tensor)) {
|
||||
if (tensor->op == GGML_OP_MUL_MAT) {
|
||||
ggml_compute_forward_mul_mat_scale(params, tensor);
|
||||
} else if (tensor->op == GGML_OP_MUL_MAT_ID) {
|
||||
ggml_compute_forward_mul_mat_id_scale(params, tensor);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -2930,7 +3021,7 @@ struct ggml_cplan ggml_graph_plan(
|
||||
case GGML_OP_ADD:
|
||||
case GGML_OP_ADD_ID:
|
||||
{
|
||||
if (ggml_is_quantized(node->src[0]->type) || node->src[0]->type == GGML_TYPE_F8_E4M3) {
|
||||
if (ggml_is_quantized(node->src[0]->type) || ggml_needs_scale(node->src[0]->type)) {
|
||||
cur = ggml_type_size(GGML_TYPE_F32) * node->src[0]->ne[0] * n_tasks;
|
||||
}
|
||||
} break;
|
||||
@@ -2978,7 +3069,7 @@ struct ggml_cplan ggml_graph_plan(
|
||||
} break;
|
||||
case GGML_OP_OUT_PROD:
|
||||
{
|
||||
if (ggml_is_quantized(node->src[0]->type) || node->src[0]->type == GGML_TYPE_F8_E4M3 ||
|
||||
if (ggml_is_quantized(node->src[0]->type) || ggml_needs_scale(node->src[0]->type) ||
|
||||
node->src[0]->type == GGML_TYPE_F16) {
|
||||
cur = ggml_type_size(GGML_TYPE_F32) * node->src[0]->ne[0] * n_tasks;
|
||||
}
|
||||
|
||||
@@ -441,6 +441,8 @@ static bool ggml_backend_cpu_device_supports_op(ggml_backend_dev_t dev, const st
|
||||
}
|
||||
|
||||
switch (op->op) {
|
||||
case GGML_OP_FLASH_ATTN_EXT:
|
||||
return ggml_validate_flash_attn_ext_indexed_bias(op);
|
||||
case GGML_OP_CPY:
|
||||
case GGML_OP_SET_ROWS:
|
||||
return
|
||||
|
||||
@@ -615,7 +615,7 @@ static void ggml_compute_forward_add_q_f32(
|
||||
GGML_ASSERT(nb1 <= nb2);
|
||||
GGML_ASSERT(nb2 <= nb3);
|
||||
|
||||
GGML_ASSERT(ggml_is_quantized(src0->type) || src0->type == GGML_TYPE_F8_E4M3);
|
||||
GGML_ASSERT(ggml_is_quantized(src0->type) || ggml_needs_scale(src0->type));
|
||||
GGML_ASSERT(src1->type == GGML_TYPE_F32);
|
||||
GGML_ASSERT(ne00 % ggml_blck_size(type) == 0);
|
||||
|
||||
@@ -965,7 +965,7 @@ static void ggml_compute_forward_add1_q_f32(
|
||||
GGML_ASSERT(nb1 <= nb2);
|
||||
GGML_ASSERT(nb2 <= nb3);
|
||||
|
||||
GGML_ASSERT(ggml_is_quantized(src0->type) || src0->type == GGML_TYPE_F8_E4M3);
|
||||
GGML_ASSERT(ggml_is_quantized(src0->type) || ggml_needs_scale(src0->type));
|
||||
GGML_ASSERT(dst->type == src0->type);
|
||||
GGML_ASSERT(src1->type == GGML_TYPE_F32);
|
||||
|
||||
@@ -9722,6 +9722,7 @@ static void ggml_compute_forward_flash_attn_ext_f16(
|
||||
void ggml_compute_forward_flash_attn_ext(
|
||||
const ggml_compute_params * params,
|
||||
ggml_tensor * dst) {
|
||||
GGML_ASSERT(ggml_validate_flash_attn_ext_indexed_bias(dst));
|
||||
switch (ggml_prec_get_acc(dst)) {
|
||||
case GGML_PREC_UNDEFINED:
|
||||
case GGML_PREC_F32:
|
||||
|
||||
@@ -2,26 +2,28 @@
|
||||
|
||||
static __global__ void add_id_kernel(
|
||||
const float * src0, const float * src1, const int32_t * src2, float * dst,
|
||||
int64_t ne0, int64_t ne1,
|
||||
int64_t ne0, int64_t ne1, int64_t ne2,
|
||||
size_t nb01, size_t nb02,
|
||||
size_t nb11,
|
||||
size_t nb21
|
||||
) {
|
||||
|
||||
const int64_t i1 = blockIdx.x;
|
||||
const int64_t i2 = blockIdx.y;
|
||||
|
||||
const int i11 = *(const int32_t *) ((const char *) src2 + i1*sizeof(int32_t) + i2*nb21);
|
||||
// gridDim.y is capped at 65535, blocks stride over larger ne2
|
||||
for (int64_t i2 = blockIdx.y; i2 < ne2; i2 += gridDim.y) {
|
||||
const int i11 = *(const int32_t *) ((const char *) src2 + i1*sizeof(int32_t) + i2*nb21);
|
||||
|
||||
const size_t nb1 = ne0 * sizeof(float);
|
||||
const size_t nb2 = ne1 * nb1;
|
||||
const size_t nb1 = ne0 * sizeof(float);
|
||||
const size_t nb2 = ne1 * nb1;
|
||||
|
||||
float * dst_row = (float *)((char *)dst + i1*nb1 + i2*nb2);
|
||||
const float * src0_row = (const float *)((const char *)src0 + i1*nb01 + i2*nb02);
|
||||
const float * src1_row = (const float *)((const char *)src1 + i11*nb11);
|
||||
float * dst_row = (float *)((char *)dst + i1*nb1 + i2*nb2);
|
||||
const float * src0_row = (const float *)((const char *)src0 + i1*nb01 + i2*nb02);
|
||||
const float * src1_row = (const float *)((const char *)src1 + i11*nb11);
|
||||
|
||||
for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) {
|
||||
dst_row[i0] = src0_row[i0] + src1_row[i0];
|
||||
for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) {
|
||||
dst_row[i0] = src0_row[i0] + src1_row[i0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,10 +49,10 @@ void ggml_cuda_op_add_id(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
|
||||
float * dst_d = (float *)dst->data;
|
||||
|
||||
int threads = std::min((int)ne00, 768); // cols
|
||||
dim3 blocks(ne01, ne02); // n_experts_used, n_tokens
|
||||
dim3 blocks(ne01, std::min(ne02, (int64_t)65535)); // n_experts_used, n_tokens
|
||||
add_id_kernel<<<blocks, threads, 0, ctx.stream()>>>(
|
||||
src0_d, src1_d, src2_d, dst_d,
|
||||
ne0, ne1,
|
||||
ne0, ne1, ne2,
|
||||
nb01, nb02,
|
||||
nb11,
|
||||
nb21
|
||||
|
||||
@@ -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;
|
||||
@@ -1304,6 +1309,7 @@ struct ggml_cuda_device_info {
|
||||
size_t smpb; // max. shared memory per block
|
||||
size_t smpbo; // max. shared memory per block (with opt-in)
|
||||
bool integrated; // Device is integrated as opposed to discrete
|
||||
enum ggml_backend_dev_type type; // GPU or IGPU, from cudaDeviceProp::integrated
|
||||
bool vmm; // virtual memory support
|
||||
size_t vmm_granularity; // granularity of virtual memory
|
||||
size_t total_vram;
|
||||
|
||||
@@ -20,6 +20,28 @@
|
||||
// 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)
|
||||
|
||||
struct fattn_indexed_bias {
|
||||
const float * table;
|
||||
const int32_t * indices;
|
||||
int64_t n_bins;
|
||||
int64_t n_keys;
|
||||
int64_t query_stride;
|
||||
|
||||
__device__ fattn_indexed_bias for_head(int64_t first_query, int head) const {
|
||||
return {table + first_query*query_stride + head*n_bins, indices + first_query*n_keys, n_bins, n_keys, query_stride};
|
||||
}
|
||||
|
||||
__device__ float add(float mask, int query, int key) const {
|
||||
const int bin = indices[query*n_keys + key];
|
||||
return bin >= 0 && bin < n_bins ? mask + table[query*query_stride + bin] : mask;
|
||||
}
|
||||
};
|
||||
|
||||
// ggml-cpu returns zero for the 0/0 of a fully masked query.
|
||||
static __device__ __forceinline__ float fattn_normalize(float value, float rowsum) {
|
||||
return value == 0.0f && rowsum == 0.0f ? 0.0f : value/rowsum;
|
||||
}
|
||||
|
||||
using fattn_kernel_t = void (*)(
|
||||
const float2 * __restrict__ Q,
|
||||
const char * __restrict__ K,
|
||||
@@ -42,7 +64,8 @@ using fattn_kernel_t = void (*)(
|
||||
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 s31, const int64_t s32, const int64_t s33);
|
||||
const int32_t s31, const int64_t s32, const int64_t s33,
|
||||
const fattn_indexed_bias bias);
|
||||
|
||||
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);
|
||||
@@ -1110,7 +1133,7 @@ static __global__ void flash_attn_stream_k_fixup_uniform(
|
||||
}
|
||||
|
||||
// Write back final result:
|
||||
*dst = dst_val / rowsum;
|
||||
*dst = fattn_normalize(dst_val, rowsum);
|
||||
}
|
||||
|
||||
// General fixup kernel for the case where the number of blocks per tile is not uniform across tiles
|
||||
@@ -1221,7 +1244,7 @@ static __global__ void flash_attn_stream_k_fixup_general(
|
||||
}
|
||||
|
||||
// Write back final result:
|
||||
*dst = dst_val / rowsum;
|
||||
*dst = fattn_normalize(dst_val, rowsum);
|
||||
}
|
||||
|
||||
template<int D> // D == head size
|
||||
@@ -1279,7 +1302,7 @@ static __global__ void flash_attn_combine_results(
|
||||
VKQ_denominator += KQ_max_scale * meta[l].y;
|
||||
}
|
||||
|
||||
dst[tid] = VKQ_numerator / VKQ_denominator;
|
||||
dst[tid] = fattn_normalize(VKQ_numerator, VKQ_denominator);
|
||||
}
|
||||
|
||||
template <int DV, int ncols1, int ncols2, typename T_K_stride, typename T_V_stride>
|
||||
@@ -1301,6 +1324,10 @@ void launch_fattn(
|
||||
const ggml_tensor * sinks = dst->src[4];
|
||||
const ggml_tensor * kv_rows = dst->src[5];
|
||||
|
||||
const bool has_bias = ggml_flash_attn_ext_has_indexed_bias(dst);
|
||||
const ggml_tensor * bias_table = has_bias ? dst->src[6] : nullptr;
|
||||
const ggml_tensor * bias_indices = has_bias ? dst->src[7] : nullptr;
|
||||
|
||||
// with kv_rows the kernel iterates over the mask columns and reads K/V rows through kv_rows
|
||||
const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : K->ne[1];
|
||||
GGML_ASSERT(!kv_rows || !use_sparse);
|
||||
@@ -1433,7 +1460,9 @@ void launch_fattn(
|
||||
// Optional optimization where the mask is scanned to determine whether part of the calculation can be skipped.
|
||||
// Only worth the overhead if there is at lease one FATTN_KQ_STRIDE x FATTN_KQ_STRIDE square to be skipped or
|
||||
// multiple sequences of possibly different lengths, or kv_rows lists that end with padding.
|
||||
const bool scan_mask = !use_sparse && mask && mask->ne[2] == 1 && n_kv_cols % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1 || kv_rows);
|
||||
// The scan reads ncols1 mask rows per tile, including the last tile.
|
||||
const bool scan_mask = !has_bias && !use_sparse && mask && mask->ne[2] == 1 && mask->ne[1]/ncols1 >= ntiles_x &&
|
||||
n_kv_cols % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1 || kv_rows);
|
||||
if (scan_mask) {
|
||||
const int64_t s31 = mask->nb[1] / sizeof(half2);
|
||||
const int64_t s33 = mask->nb[3] / sizeof(half2);
|
||||
@@ -1591,7 +1620,12 @@ void launch_fattn(
|
||||
mask ? mask->ne[1] : 0, mask ? mask->ne[2] : 0, mask ? mask->ne[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
|
||||
mask ? int64_t(mask->nb[3] / sizeof(half)) : 0,
|
||||
fattn_indexed_bias{has_bias ? (const float *) bias_table->data : nullptr,
|
||||
has_bias ? (const int32_t *) bias_indices->data : nullptr,
|
||||
has_bias ? bias_table->ne[0] : 0,
|
||||
has_bias ? bias_indices->ne[0] : 0,
|
||||
has_bias ? bias_table->ne[0]*bias_table->ne[1] : 0}
|
||||
);
|
||||
CUDA_CHECK(cudaGetLastError());
|
||||
|
||||
|
||||
@@ -1807,8 +1807,8 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
|
||||
|
||||
if (!needs_fixup && !is_fixup) {
|
||||
const float KQ_rowsum_j = meta_j[1];
|
||||
dstk_val.x /= KQ_rowsum_j;
|
||||
dstk_val.y /= KQ_rowsum_j;
|
||||
dstk_val.x = fattn_normalize(dstk_val.x, KQ_rowsum_j);
|
||||
dstk_val.y = fattn_normalize(dstk_val.y, KQ_rowsum_j);
|
||||
}
|
||||
|
||||
if (is_fixup) {
|
||||
@@ -1865,7 +1865,9 @@ static __global__ void flash_attn_ext_f16(
|
||||
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 s31, const int64_t s32, const int64_t s33) {
|
||||
const int32_t s31, const int64_t s32, const int64_t s33,
|
||||
const fattn_indexed_bias bias) {
|
||||
GGML_UNUSED(bias); // biased ops are never dispatched to the mma kernel
|
||||
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))
|
||||
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
|
||||
|
||||
@@ -375,7 +375,7 @@ static constexpr __device__ int ggml_cuda_fattn_tile_get_nbatch_K(const int DKQ,
|
||||
|
||||
// Function that performs a single iteration in for the KQ matrix multiplication:
|
||||
template <int warp_size, int nwarps, int ncols1, int ncols2, int DKQ, int nbatch_fa, int nbatch_K,
|
||||
bool use_logit_softcap, bool oob_check, typename T_vec_dot, typename T_K>
|
||||
bool use_logit_softcap, bool oob_check, bool indexed_bias, typename T_vec_dot, typename T_K>
|
||||
static __device__ __forceinline__ void flash_attn_tile_iter_KQ(
|
||||
T_vec_dot * const Q_tmp,
|
||||
const T_K * const __restrict__ K_h2,
|
||||
@@ -384,7 +384,8 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ(
|
||||
const int k_VKQ_0,
|
||||
const int k_VKQ_sup,
|
||||
const int k_KQ_0,
|
||||
float * KQ_acc) {
|
||||
float * KQ_acc,
|
||||
const int32_t * const __restrict__ rows) {
|
||||
constexpr int cpy_nb = 16;
|
||||
constexpr int cpy_ne = cpy_nb / 4;
|
||||
|
||||
@@ -393,8 +394,8 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ(
|
||||
constexpr int np = nwarps > ncols ? nwarps/ncols : 1; // number of parallel warps per Q column
|
||||
|
||||
constexpr int stride_tile_K = std::is_same_v<T_vec_dot, half2> ? nbatch_K/2 + cpy_ne : nbatch_K + cpy_ne;
|
||||
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, nbatch_K, stride_tile_K, false, oob_check, false, false, false, T_K, T_vec_dot>
|
||||
(K_h2 + k_KQ_0/2, KV_tmp, nbatch_K/2, stride_K2, k_VKQ_0, k_VKQ_sup, nullptr);
|
||||
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, nbatch_K, stride_tile_K, false, oob_check, false, indexed_bias, false, T_K, T_vec_dot>
|
||||
(K_h2 + k_KQ_0/2, KV_tmp, nbatch_K/2, stride_K2, k_VKQ_0, k_VKQ_sup, rows);
|
||||
__syncthreads();
|
||||
|
||||
#ifdef FAST_FP16_AVAILABLE
|
||||
@@ -451,7 +452,7 @@ 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 <int warp_size, int nwarps, int ncols1, int ncols2, int DKQ, int DV, int nbatch_fa, int nbatch_K,
|
||||
bool use_logit_softcap, bool oob_check, typename T_vec_dot, typename T_KQ, typename T_acc, typename T_K, typename T_V>
|
||||
bool use_logit_softcap, bool oob_check, bool indexed_bias, 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 T_K * const __restrict__ K_h2,
|
||||
@@ -470,7 +471,9 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
|
||||
T_acc * const VKQ,
|
||||
const int k_VKQ_0,
|
||||
const int k_VKQ_max,
|
||||
const int col_Q_0) {
|
||||
const int col_Q_0,
|
||||
const fattn_indexed_bias bias,
|
||||
const int32_t * const __restrict__ rows) {
|
||||
constexpr int cpy_nb = 16;
|
||||
constexpr int cpy_ne = cpy_nb / 4;
|
||||
|
||||
@@ -502,13 +505,13 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
|
||||
constexpr int nbatch_K_last = DKQ % nbatch_K;
|
||||
#pragma unroll
|
||||
for (int k_KQ_0 = 0; k_KQ_0 < DKQ - nbatch_K_last; k_KQ_0 += nbatch_K) {
|
||||
flash_attn_tile_iter_KQ<warp_size, nwarps, ncols1, ncols2, DKQ, nbatch_fa, nbatch_K, use_logit_softcap, oob_check>(
|
||||
Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc);
|
||||
flash_attn_tile_iter_KQ<warp_size, nwarps, ncols1, ncols2, DKQ, nbatch_fa, nbatch_K, use_logit_softcap, oob_check, indexed_bias>(
|
||||
Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc, rows);
|
||||
}
|
||||
if (nbatch_K_last > 0) {
|
||||
constexpr int k_KQ_0 = DKQ - nbatch_K_last;
|
||||
flash_attn_tile_iter_KQ<warp_size, nwarps, ncols1, ncols2, DKQ, nbatch_fa, nbatch_K_last, use_logit_softcap, oob_check>(
|
||||
Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc);
|
||||
flash_attn_tile_iter_KQ<warp_size, nwarps, ncols1, ncols2, DKQ, nbatch_fa, nbatch_K_last, use_logit_softcap, oob_check, indexed_bias>(
|
||||
Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc, rows);
|
||||
}
|
||||
|
||||
// Apply logit softcap + mask, update KQ_max:
|
||||
@@ -531,8 +534,12 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
|
||||
}
|
||||
|
||||
if (!oob_check || i_KQ < k_VKQ_sup) {
|
||||
KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] += (ncols2 > 1 || mask) ?
|
||||
slope*__half2float(mask[j*stride_mask + k_VKQ_0 + i_KQ]) : 0.0f;
|
||||
if (indexed_bias || ncols2 > 1 || mask) {
|
||||
const int k = k_VKQ_0 + i_KQ;
|
||||
__builtin_assume(k >= 0); // avoid sign extension and register spills on RDNA
|
||||
const float m = __half2float(mask[int64_t(j)*stride_mask + k]);
|
||||
KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] += slope*(indexed_bias ? bias.add(m, j, k) : m);
|
||||
}
|
||||
|
||||
KQ_max_new[jc0] = fmaxf(KQ_max_new[jc0], KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] + FATTN_KQ_MAX_OFFSET);
|
||||
}
|
||||
@@ -614,8 +621,8 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
|
||||
constexpr int stride_tile_V = std::is_same_v<T_vec_dot, half2> ? DV/2 : DV;
|
||||
#pragma unroll
|
||||
for (int k0 = 0; k0 < nbatch_fa; k0 += nbatch_V) {
|
||||
flash_attn_load_tile<warp_size, nwarps, nbatch_V, DV, stride_tile_V, false, oob_check, false, false, false, T_V, T_vec_dot>
|
||||
(V_h2, KV_tmp, DV/2, stride_V2, k_VKQ_0 + k0, k_VKQ_sup - k0, nullptr);
|
||||
flash_attn_load_tile<warp_size, nwarps, nbatch_V, DV, stride_tile_V, false, oob_check, false, indexed_bias, false, T_V, T_vec_dot>
|
||||
(V_h2, KV_tmp, DV/2, stride_V2, k_VKQ_0 + k0, k_VKQ_sup - k0, rows);
|
||||
__syncthreads();
|
||||
|
||||
#ifdef FAST_FP16_AVAILABLE
|
||||
@@ -684,7 +691,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
|
||||
}
|
||||
}
|
||||
|
||||
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap, ggml_type type_K, ggml_type type_V> // D == head size
|
||||
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap, bool indexed_bias, ggml_type type_K, ggml_type type_V, bool use_kv_rows> // 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 float2 * Q_ptr,
|
||||
@@ -708,7 +715,8 @@ static __global__ void flash_attn_tile(
|
||||
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 s31, const int64_t s32, const int64_t s33) {
|
||||
const int32_t s31, const int64_t s32, const int64_t s33,
|
||||
const fattn_indexed_bias bias) {
|
||||
#ifdef FLASH_ATTN_AVAILABLE
|
||||
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
|
||||
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
|
||||
@@ -721,7 +729,6 @@ static __global__ void flash_attn_tile(
|
||||
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:
|
||||
|
||||
@@ -760,12 +767,15 @@ 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 int32_t * rows = use_kv_rows ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr;
|
||||
__builtin_assume(!use_kv_rows || rows != nullptr);
|
||||
const fattn_indexed_bias head_bias = indexed_bias ? bias.for_head(int64_t(sequence)*ne01.z, head0) : bias;
|
||||
const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix.
|
||||
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 ? mask + s33*(sequence % ne33) + s32*(head0 % ne32) : nullptr;
|
||||
const half * maskh = indexed_bias || mask ? mask + s33*(sequence % ne33) + s32*(head0 % ne32) : nullptr;
|
||||
|
||||
const int stride_K2 = s11;
|
||||
const int stride_V2 = s21;
|
||||
@@ -864,24 +874,24 @@ static __global__ void flash_attn_tile(
|
||||
int k_VKQ_0 = blockIdx.y*nbatch_fa;
|
||||
while (k_VKQ_0 <= k_VKQ_max - nbatch_fa) {
|
||||
constexpr bool oob_check = false;
|
||||
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check>
|
||||
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check, indexed_bias>
|
||||
(Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp,
|
||||
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0);
|
||||
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, head_bias, rows);
|
||||
k_VKQ_0 += gridDim.y*nbatch_fa;
|
||||
}
|
||||
if (k_VKQ_0 < k_VKQ_max) {
|
||||
constexpr bool oob_check = true;
|
||||
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check>
|
||||
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check, indexed_bias>
|
||||
(Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp,
|
||||
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0);
|
||||
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, head_bias, rows);
|
||||
}
|
||||
} else {
|
||||
// Branch without out-of-bounds checks.
|
||||
for (int k_VKQ_0 = blockIdx.y*nbatch_fa; k_VKQ_0 < k_VKQ_max; k_VKQ_0 += gridDim.y*nbatch_fa) {
|
||||
constexpr bool oob_check = false;
|
||||
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check>
|
||||
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check, indexed_bias>
|
||||
(Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp,
|
||||
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0);
|
||||
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, head_bias, rows);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -998,7 +1008,7 @@ static __global__ void flash_attn_tile(
|
||||
return;
|
||||
}
|
||||
|
||||
const float scale = gridDim.y == 1 ? 1.0f/KQ_sum[jc0] : 1.0f;
|
||||
const float rowsum = gridDim.y == 1 ? KQ_sum[jc0] : 1.0f;
|
||||
|
||||
const int j_dst_unrolled = ((sequence*int(ne01.z) + col_Q_0 + j)*ne02 + head0 + c)*gridDim.y + blockIdx.y;
|
||||
|
||||
@@ -1010,8 +1020,8 @@ static __global__ void flash_attn_tile(
|
||||
#pragma unroll
|
||||
for (int i1 = 0; i1 < cpy_ne_D; ++i1) {
|
||||
tmp[i1] = __half22float2(VKQ[jc0*((DVp/2)/warp_size) + i0/warp_size + i1]);
|
||||
tmp[i1].x *= scale;
|
||||
tmp[i1].y *= scale;
|
||||
tmp[i1].x = fattn_normalize(tmp[i1].x, rowsum);
|
||||
tmp[i1].y = fattn_normalize(tmp[i1].y, rowsum);
|
||||
}
|
||||
if (i0 + warp_size*cpy_ne_D <= DV/2 || i0 + threadIdx.x*cpy_ne_D < DV/2) {
|
||||
ggml_cuda_memcpy_1<sizeof(tmp)>(&dst[j_dst_unrolled*DV + 2*i0 + threadIdx.x*(2*cpy_ne_D)], tmp);
|
||||
@@ -1024,8 +1034,9 @@ static __global__ void flash_attn_tile(
|
||||
if (i0 + warp_size*cpy_ne_D <= DV || i0 + threadIdx.x*cpy_ne_D < DV) {
|
||||
#pragma unroll
|
||||
for (int i1 = 0; i1 < cpy_ne_D/2; ++i1) {
|
||||
VKQ[jc0*((DVp/2)/warp_size) + i0/(2*warp_size) + i1].x *= scale;
|
||||
VKQ[jc0*((DVp/2)/warp_size) + i0/(2*warp_size) + i1].y *= scale;
|
||||
float2 & val = VKQ[jc0*((DVp/2)/warp_size) + i0/(2*warp_size) + i1];
|
||||
val.x = fattn_normalize(val.x, rowsum);
|
||||
val.y = fattn_normalize(val.y, rowsum);
|
||||
}
|
||||
ggml_cuda_memcpy_1<cpy_ne_D*4>(
|
||||
&dst[j_dst_unrolled*DV + i0 + threadIdx.x*cpy_ne_D],
|
||||
@@ -1047,12 +1058,12 @@ static __global__ void flash_attn_tile(
|
||||
s11, s12, s13,
|
||||
s21, s22, s23,
|
||||
ne31, ne32, ne33,
|
||||
s31, s32, s33);
|
||||
s31, s32, s33, bias);
|
||||
NO_DEVICE_CODE;
|
||||
#endif // FLASH_ATTN_AVAILABLE
|
||||
}
|
||||
|
||||
template <int DKQ, int DV, int ncols2, bool use_logit_softcap, ggml_type type_K, ggml_type type_V>
|
||||
template <int DKQ, int DV, int ncols2, bool use_logit_softcap, ggml_type type_K, ggml_type type_V, bool indexed_bias, bool use_kv_rows>
|
||||
static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
|
||||
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
|
||||
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
|
||||
@@ -1066,40 +1077,42 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
|
||||
constexpr size_t nbytes_shared = 0;
|
||||
|
||||
#ifdef GGML_USE_HIP
|
||||
if constexpr (DKQ <= 128) {
|
||||
// Limit indexed bias tile widths to avoid spilling registers on AMD.
|
||||
// TODO: select the tile width in one function.
|
||||
constexpr int max_cols = !indexed_bias ? 64 : DKQ == 64 ? 32 : use_kv_rows ? 16 : 8;
|
||||
if constexpr (DKQ <= 128 && max_cols >= 64) {
|
||||
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<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, indexed_bias, type_K, type_V, use_kv_rows>;
|
||||
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
|
||||
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
|
||||
return;
|
||||
}
|
||||
}
|
||||
#else
|
||||
constexpr int max_cols = DKQ <= 256 ? 32 : 16;
|
||||
#endif // GGML_USE_HIP
|
||||
|
||||
#ifndef GGML_USE_HIP
|
||||
if constexpr (DKQ <= 256)
|
||||
#endif // GGML_USE_HIP
|
||||
{
|
||||
if constexpr (max_cols >= 32) {
|
||||
if (Q->ne[1] > 16/ncols2) {
|
||||
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<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, indexed_bias, type_K, type_V, use_kv_rows>;
|
||||
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
|
||||
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if constexpr (ncols2 <= 16) {
|
||||
if constexpr (ncols2 <= 16 && max_cols >= 16) {
|
||||
if (Q->ne[1] > 8/ncols2) {
|
||||
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<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, indexed_bias, type_K, type_V, use_kv_rows>;
|
||||
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
|
||||
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
|
||||
return;
|
||||
@@ -1111,7 +1124,7 @@ 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<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, indexed_bias, type_K, type_V, use_kv_rows>;
|
||||
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
|
||||
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
|
||||
return;
|
||||
@@ -1123,7 +1136,7 @@ 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<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, indexed_bias, type_K, type_V, use_kv_rows>;
|
||||
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
|
||||
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
|
||||
return;
|
||||
@@ -1134,7 +1147,7 @@ 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<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, indexed_bias, type_K, type_V, use_kv_rows>;
|
||||
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
|
||||
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
|
||||
return;
|
||||
@@ -1163,6 +1176,17 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
|
||||
// a mask with a head dimension is not shared by the Q heads of a K/V head
|
||||
const bool use_gqa_opt = mask && mask->ne[2] == 1 && max_bias == 0.0f && Q->ne[1] <= gqa_limit && K->ne[1] % FATTN_KQ_STRIDE == 0;
|
||||
|
||||
if constexpr (DKQ == 64 || DKQ == 128) {
|
||||
if (ggml_flash_attn_ext_has_indexed_bias(dst)) {
|
||||
if (dst->src[5]) {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 1, use_logit_softcap, type_K, type_V, true, true>(ctx, dst);
|
||||
} else {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 1, use_logit_softcap, type_K, type_V, true, false>(ctx, dst);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if constexpr (DKQ == 320) {
|
||||
// This branch is only used for Mistral Small 4 which has a GQA ratio of 32.
|
||||
// On AMD, simply use that GQA ratio with 32 columns / block since we always have enough SRAM.
|
||||
@@ -1170,12 +1194,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<DKQ, DV, 32, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 32, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
#else
|
||||
if (use_gqa_opt && gqa_ratio % 16 == 0) {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
#endif // GGML_USE_HIP
|
||||
@@ -1184,11 +1208,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<DKQ, DV, 16, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
if (use_gqa_opt && gqa_ratio % 4 == 0) {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -1196,11 +1220,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<DKQ, DV, 16, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
if (use_gqa_opt && gqa_ratio % 8 == 0) {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 8, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 8, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
GGML_ABORT("flash-attn tile (192/128): expected GQA ratio multiple of 8");
|
||||
@@ -1208,22 +1232,22 @@ 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<DKQ, DV, 8, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 8, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
|
||||
if (use_gqa_opt && gqa_ratio % 4 == 0) {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
|
||||
if (use_gqa_opt && gqa_ratio % 2 == 0) {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 2, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 2, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
|
||||
if constexpr (DV <= 256) {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 1, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 1, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ static constexpr __device__ int ggml_cuda_fattn_vec_get_nthreads_device() {
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wpass-failed"
|
||||
#endif // __clang__
|
||||
template<int D, int ncols, ggml_type type_K, ggml_type type_V, bool use_logit_softcap> // D == head size
|
||||
template<int D, int ncols, ggml_type type_K, ggml_type type_V, bool use_logit_softcap, bool indexed_bias, bool use_kv_rows> // D == head size
|
||||
__launch_bounds__(ggml_cuda_fattn_vec_get_nthreads_device(), 1)
|
||||
static __global__ void flash_attn_ext_vec(
|
||||
const float2 * Q_ptr,
|
||||
@@ -40,7 +40,8 @@ static __global__ void flash_attn_ext_vec(
|
||||
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 s31, const int64_t s32, const int64_t s33) {
|
||||
const int32_t s31, const int64_t s32, const int64_t s33,
|
||||
const fattn_indexed_bias bias) {
|
||||
ggml_cuda_pdl_lc();
|
||||
#ifdef FLASH_ATTN_AVAILABLE
|
||||
const float2 * GGML_CUDA_RESTRICT Q = Q_ptr;
|
||||
@@ -51,7 +52,6 @@ static __global__ void flash_attn_ext_vec(
|
||||
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:
|
||||
if (use_logit_softcap && !(D == 128 || D == 256)) {
|
||||
@@ -75,9 +75,9 @@ static __global__ void flash_attn_ext_vec(
|
||||
|
||||
#ifdef GGML_USE_HIP
|
||||
#ifdef RDNA
|
||||
constexpr int nthreads_KQ_q = 2;
|
||||
constexpr int nthreads_KQ_q = indexed_bias && type_K == GGML_TYPE_F8_E4M3 ? 16 : 2;
|
||||
#else
|
||||
constexpr int nthreads_KQ_q = 4;
|
||||
constexpr int nthreads_KQ_q = type_K == GGML_TYPE_F8_E4M3 && D == 256 && ncols == 2 ? 16 : 4;
|
||||
#endif // RDNA
|
||||
constexpr int nthreads_V_q = (D/4 < 32 ? D/4 : 32);
|
||||
#else
|
||||
@@ -107,12 +107,13 @@ static __global__ void flash_attn_ext_vec(
|
||||
|
||||
const int sequence = blockIdx.z / ne02;
|
||||
const int head = blockIdx.z - sequence*ne02;
|
||||
const fattn_indexed_bias head_bias = indexed_bias ? bias.for_head(int64_t(sequence)*ne01.z, head) : bias;
|
||||
const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix.
|
||||
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 ? mask + s33*(sequence % ne33) + s32*(head % ne32) + s31*ic0 : nullptr;
|
||||
const half * maskh = indexed_bias || 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);
|
||||
|
||||
@@ -271,12 +272,15 @@ 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 * s11;
|
||||
V += blockIdx.y*nthreads * s21;
|
||||
const int32_t * rows = use_kv_rows ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr;
|
||||
if constexpr (!use_kv_rows) {
|
||||
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*s11, V += gridDim.y*nthreads*s21, maskh += gridDim.y*nthreads) {
|
||||
K += use_kv_rows ? 0 : gridDim.y*nthreads*s11, V += use_kv_rows ? 0 : 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.
|
||||
@@ -290,21 +294,24 @@ static __global__ void flash_attn_ext_vec(
|
||||
#pragma unroll
|
||||
for (int i_KQ_0 = 0; i_KQ_0 < nthreads_KQ; ++i_KQ_0) {
|
||||
const int i_KQ = threadIdx.y*WARP_SIZE + (nthreads_KQ == WARP_SIZE ? 0 : (threadIdx.x & ~(nthreads_KQ-1))) + i_KQ_0;
|
||||
const char * K_row = use_kv_rows ? K + int64_t(max(rows[k_VKQ_0 + i_KQ], 0))*s11 : K + i_KQ*s11;
|
||||
|
||||
#pragma unroll
|
||||
for (int j = 0; j < ncols; ++j) {
|
||||
float sum = vec_dot_KQ(K + i_KQ*s11, Q_reg[j], Q_i32[j], Q_ds[j]);
|
||||
float sum = vec_dot_KQ(K_row, Q_reg[j], Q_i32[j], Q_ds[j]);
|
||||
sum = warp_reduce_sum<nthreads_KQ>(sum);
|
||||
|
||||
if (use_logit_softcap) {
|
||||
sum = logit_softcap*tanhf(sum);
|
||||
}
|
||||
|
||||
if (mask && (ncols == 1 || ic0 + j < int(ne01.z))) {
|
||||
sum += slope*__half2float(maskh[j*ne11 + i_KQ]);
|
||||
}
|
||||
if constexpr (!indexed_bias) {
|
||||
if (mask && (ncols == 1 || ic0 + j < int(ne01.z))) {
|
||||
sum += slope*__half2float(maskh[j*ne11 + i_KQ]);
|
||||
}
|
||||
|
||||
KQ_max_new[j] = fmaxf(KQ_max_new[j], sum + FATTN_KQ_MAX_OFFSET);
|
||||
KQ_max_new[j] = fmaxf(KQ_max_new[j], sum + FATTN_KQ_MAX_OFFSET);
|
||||
}
|
||||
|
||||
if ((nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ) == uint32_t(i_KQ_0)) {
|
||||
KQ_reg[j] = sum;
|
||||
@@ -314,8 +321,14 @@ static __global__ void flash_attn_ext_vec(
|
||||
|
||||
#pragma unroll
|
||||
for (int j = 0; j < ncols; ++j) {
|
||||
if constexpr (indexed_bias) {
|
||||
const int k = k_VKQ_0 + tid;
|
||||
const float m = head_bias.add(__half2float(maskh[j*ne11 + tid]), ic0 + j, k);
|
||||
KQ_reg[j] += slope*m;
|
||||
KQ_max_new[j] = fmaxf(KQ_max[j], KQ_reg[j] + FATTN_KQ_MAX_OFFSET);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int offset = nthreads_KQ; offset < WARP_SIZE; offset <<= 1) {
|
||||
for (int offset = indexed_bias ? 1 : nthreads_KQ; offset < WARP_SIZE; offset <<= 1) {
|
||||
KQ_max_new[j] = fmaxf(KQ_max_new[j], ggml_cuda_shfl_xor(KQ_max_new[j], offset, WARP_SIZE));
|
||||
}
|
||||
const float KQ_max_scale = expf(KQ_max[j] - KQ_max_new[j]);
|
||||
@@ -345,6 +358,7 @@ static __global__ void flash_attn_ext_vec(
|
||||
#pragma unroll
|
||||
for (int k0 = 0; k0 < WARP_SIZE; k0 += V_cols_per_iter) {
|
||||
const int k = threadIdx.y*WARP_SIZE + k0 + (nthreads_V == WARP_SIZE ? 0 : threadIdx.x / nthreads_V);
|
||||
const char * V_row = V + (use_kv_rows ? int64_t(max(rows[k_VKQ_0 + k], 0))*s21 : k*s21);
|
||||
|
||||
#ifdef V_DOT2_F32_F16_AVAILABLE
|
||||
half2 KQ_k[ncols];
|
||||
@@ -357,14 +371,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*s21, tmp_f,
|
||||
dequantize_V(V_row, 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*s21, tmp,
|
||||
dequantize_V(V_row, tmp,
|
||||
2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread);
|
||||
}
|
||||
#pragma unroll
|
||||
@@ -384,7 +398,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*s21, tmp,
|
||||
dequantize_V(V_row, 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) {
|
||||
@@ -521,7 +535,7 @@ static __global__ void flash_attn_ext_vec(
|
||||
}
|
||||
}
|
||||
if (gridDim.y == 1) {
|
||||
dst_val /= KQ_sum[j_VKQ];
|
||||
dst_val = fattn_normalize(dst_val, KQ_sum[j_VKQ]);
|
||||
}
|
||||
dst[(((sequence*int(ne01.z) + ic0 + j_VKQ)*ne02 + head)*gridDim.y + blockIdx.y)*D + i0 + tid] = dst_val;
|
||||
}
|
||||
@@ -545,7 +559,7 @@ static __global__ void flash_attn_ext_vec(
|
||||
s11, s12, s13,
|
||||
s21, s22, s23,
|
||||
ne31, ne32, ne33,
|
||||
s31, s32, s33);
|
||||
s31, s32, s33, bias);
|
||||
NO_DEVICE_CODE;
|
||||
#endif // FLASH_ATTN_AVAILABLE
|
||||
}
|
||||
@@ -559,7 +573,13 @@ void ggml_cuda_flash_attn_ext_vec_case_impl(ggml_backend_cuda_context & ctx, ggm
|
||||
|
||||
const int nthreads = ggml_cuda_fattn_vec_get_nthreads_host(cc);
|
||||
const int nwarps = nthreads / WARP_SIZE;
|
||||
fattn_kernel_t fattn_kernel = flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap>;
|
||||
fattn_kernel_t fattn_kernel = flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap, false, false>;
|
||||
if constexpr (cols_per_block == 1 && (D == 64 || D == 128) && !use_logit_softcap) {
|
||||
if (ggml_flash_attn_ext_has_indexed_bias(dst)) {
|
||||
fattn_kernel = dst->src[5] ? flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap, true, true>
|
||||
: flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap, true, false>;
|
||||
}
|
||||
}
|
||||
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;
|
||||
|
||||
@@ -599,10 +599,6 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
|
||||
return BEST_FATTN_KERNEL_NONE;
|
||||
#endif// FLASH_ATTN_AVAILABLE
|
||||
|
||||
if (ggml_flash_attn_ext_has_indexed_bias(dst)) {
|
||||
return BEST_FATTN_KERNEL_NONE;
|
||||
}
|
||||
|
||||
const ggml_tensor * KQV = dst;
|
||||
const ggml_tensor * Q = dst->src[0];
|
||||
const ggml_tensor * K = dst->src[1];
|
||||
@@ -610,6 +606,10 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
|
||||
const ggml_tensor * mask = dst->src[3];
|
||||
const ggml_tensor * kv_rows = dst->src[5];
|
||||
|
||||
if (!ggml_validate_flash_attn_ext_indexed_bias(dst)) {
|
||||
return BEST_FATTN_KERNEL_NONE;
|
||||
}
|
||||
|
||||
// with kv_rows the kernel iterates over the mask columns
|
||||
const int64_t n_kv = kv_rows ? kv_rows->ne[0] : K->ne[1];
|
||||
|
||||
@@ -690,6 +690,20 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
|
||||
return BEST_FATTN_KERNEL_NONE;
|
||||
}
|
||||
|
||||
// the tile and vec kernels implement the indexed bias, the mma kernel does not
|
||||
if (ggml_flash_attn_ext_has_indexed_bias(dst)) {
|
||||
float logit_softcap;
|
||||
memcpy(&logit_softcap, (const float *) KQV->op_params + 2, sizeof(float));
|
||||
if (Q->ne[0] != 128 && !(Q->ne[0] == 64 && logit_softcap == 0.0f)) {
|
||||
return BEST_FATTN_KERNEL_NONE;
|
||||
}
|
||||
if (logit_softcap == 0.0f && Q->ne[1] == 1 && n_kv % FATTN_KQ_STRIDE == 0 &&
|
||||
ggml_cuda_get_fattn_vec_case(Q->ne[0], K->type, V->type)) {
|
||||
return BEST_FATTN_KERNEL_VEC;
|
||||
}
|
||||
return BEST_FATTN_KERNEL_TILE;
|
||||
}
|
||||
|
||||
if (mask && mask->ne[2] != 1) {
|
||||
// the kv_rows mask is compacted per sequence, it has no head dimension
|
||||
if (kv_rows) {
|
||||
@@ -703,7 +717,7 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
|
||||
}
|
||||
}
|
||||
|
||||
// only the MMA kernel reads K/V through kv_rows
|
||||
// without a bias only the MMA kernel reads K/V through kv_rows
|
||||
if (kv_rows) {
|
||||
return GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc) && mask && Q->ne[0] != 40 && Q->ne[0] != 72 ?
|
||||
BEST_FATTN_KERNEL_MMA_F16 : BEST_FATTN_KERNEL_NONE;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
#include "common.cuh"
|
||||
#include "ggml-backend-impl.h"
|
||||
|
||||
// whether a mat-vec node can use the fused MMVQ path
|
||||
bool ggml_cuda_should_fuse_mul_mat_vec_q(const ggml_tensor * tensor);
|
||||
|
||||
// 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);
|
||||
+143
-2402
File diff suppressed because it is too large
Load Diff
@@ -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"
|
||||
|
||||
|
||||
@@ -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<int64_t>(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 <bool has_dyn, bool has_res>
|
||||
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<true, true>, params, a);
|
||||
} else {
|
||||
ggml_cuda_kernel_launch(short_conv_f32<true, false>, params, a);
|
||||
}
|
||||
} else {
|
||||
if (a.res) {
|
||||
ggml_cuda_kernel_launch(short_conv_f32<false, true>, params, a);
|
||||
} else {
|
||||
ggml_cuda_kernel_launch(short_conv_f32<false, false>, 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 <int block_size>
|
||||
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<block_size>, 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 <int block_size>
|
||||
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<block_reduce_method::SUM, block_size>(ss, s_ss);
|
||||
dd = block_reduce<block_reduce_method::SUM, block_size>(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<block_size>, 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)));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
@@ -1430,14 +1430,14 @@ namespace ggml_cuda_mma {
|
||||
using floatx4_t = __attribute__((ext_vector_type(4))) float;
|
||||
floatx4_t& acc_frag = reinterpret_cast<floatx4_t&>(D.x[0]);
|
||||
#if defined(CDNA4) || defined(CDNA3) || defined(CDNA2)
|
||||
using bf16x4_t = __attribute__((ext_vector_type(4))) __bf16;
|
||||
using bf16x4_t = __attribute__((ext_vector_type(4))) short;
|
||||
const bf16x4_t& a_frag = reinterpret_cast<const bf16x4_t&>(A.x[0]);
|
||||
const bf16x4_t& b_frag = reinterpret_cast<const bf16x4_t&>(B.x[0]);
|
||||
acc_frag = __builtin_amdgcn_mfma_f32_16x16x16bf16_1k(a_frag, b_frag, acc_frag, 0, 0, 0);
|
||||
#elif defined(CDNA1)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
using bf16x2_t = __attribute__((ext_vector_type(2))) __bf16;
|
||||
using bf16x2_t = __attribute__((ext_vector_type(2))) short;
|
||||
const bf16x2_t& a_frag = reinterpret_cast<const bf16x2_t&>(A.x[i]);
|
||||
const bf16x2_t& b_frag = reinterpret_cast<const bf16x2_t&>(B.x[i]);
|
||||
acc_frag = __builtin_amdgcn_mfma_f32_16x16x8bf16(a_frag, b_frag, acc_frag, 0, 0, 0);
|
||||
|
||||
@@ -169,7 +169,7 @@ void ggml_cuda_mul_mat_q(
|
||||
GGML_ASSERT(!ids || ids->type == GGML_TYPE_I32); // Optional, used for batched GGML_MUL_MAT_ID.
|
||||
|
||||
// Fused gate/up/GLU: src0 is the up weight, dst the GLU output.
|
||||
// Fused scale (no gate): dst is the MUL that applies the weight scale to the MUL_MAT.
|
||||
// Fused scale (no gate): dst is the MUL_MAT whose attached weight scale is applied.
|
||||
const ggml_tensor * gate = fusion ? fusion->gate : nullptr;
|
||||
ggml_cuda_mm_fusion_args_device fusion_device = {};
|
||||
if (fusion) {
|
||||
@@ -236,7 +236,7 @@ void ggml_cuda_mul_mat_q(
|
||||
|
||||
const bool fallback = ggml_cuda_mmq_needs_fallback(ne01);
|
||||
|
||||
// With fusion dst is the GLU output or the scale node, not a MUL_MAT; the src1 precision requested by the fused MUL_MATs is in the fusion args.
|
||||
// With fusion dst can be the GLU output, not a MUL_MAT; the src1 precision requested by the fused MUL_MATs is in the fusion args.
|
||||
const ggml_prec prec_src1 = ggml_cuda_mmq_get_prec_src1(src0->type, fusion ? fusion->prec_src1 : ggml_prec_get_src(dst, 1), cc);
|
||||
|
||||
const bool use_native_fp4 = prec_src1 == GGML_PREC_Q4;
|
||||
@@ -272,7 +272,7 @@ void ggml_cuda_mul_mat_q(
|
||||
ggml_cuda_pool_alloc<char> src1_q8_1(ctx.pool(), nbytes_src1_q8_1);
|
||||
ggml_cuda_pool_alloc<float> src1_scale(ctx.pool());
|
||||
if (src0->type == GGML_TYPE_NVFP4 && use_native_fp4) {
|
||||
src1_scale.alloc(ne13*ne12*ne11);
|
||||
src1_scale.alloc(ne13*ne12*ne11 + J_best-1); // Needs to be padded for unconditional memory access.
|
||||
}
|
||||
|
||||
{
|
||||
@@ -342,7 +342,7 @@ void ggml_cuda_mul_mat_q(
|
||||
ggml_cuda_pool_alloc<char> src1_q8_1(ctx.pool(), nbytes_src1_q8_1);
|
||||
ggml_cuda_pool_alloc<float> src1_scale(ctx.pool());
|
||||
if (src0->type == GGML_TYPE_NVFP4 && use_native_fp4) {
|
||||
src1_scale.alloc(ne12*n_expert_used);
|
||||
src1_scale.alloc(ne12*n_expert_used + J_best-1); // Needs to be padded for unconditional memory access.
|
||||
}
|
||||
|
||||
const int64_t ne11_flat = ne12*n_expert_used;
|
||||
|
||||
@@ -467,7 +467,7 @@ template <ggml_type type, int J, bool fallback, ggml_prec prec_src1> static __de
|
||||
const ggml_glu_op glu_op, const float glu_limit, const float * __restrict__ x_scale, const float * __restrict__ gate_scale) {
|
||||
GGML_UNUSED_VARS(glu_op, glu_limit, gate_scale);
|
||||
|
||||
// NVFP4 weight scale of a fused MUL (per tensor, or of the expert of this tile), 1 without.
|
||||
// NVFP4 weight scale (per tensor, or of the expert of this tile), 1 without.
|
||||
const float scale = type == GGML_TYPE_NVFP4 && x_scale ? *x_scale : 1.0f;
|
||||
|
||||
constexpr int warp_size = ggml_cuda_get_physical_warp_size();
|
||||
@@ -528,7 +528,7 @@ static __device__ __forceinline__ void ggml_cuda_mmq_write_back_mma(
|
||||
|
||||
const bool y_scale_used = type == GGML_TYPE_NVFP4 && y_scale != nullptr;
|
||||
|
||||
// NVFP4: load the weight scales once, 1 without scales. Without fusion x_scale is the scale of a fused MUL.
|
||||
// NVFP4: load the weight scales once, 1 without scales. Without fusion x_scale is the weight scale attached to the MUL_MAT.
|
||||
constexpr bool fused_nvfp4 = has_fusion && type == GGML_TYPE_NVFP4;
|
||||
const float scale_up = type == GGML_TYPE_NVFP4 && x_scale ? *x_scale : 1.0f;
|
||||
const float scale_gate = fused_nvfp4 && gate_scale ? *gate_scale : 1.0f;
|
||||
|
||||
@@ -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 <int block_size, bool has_w, bool has_f>
|
||||
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<block_reduce_method::SUM, block_size>(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 <bool do_multiply = false, bool do_add = false>
|
||||
static void norm_f32_cuda(const float * x,
|
||||
float * dst,
|
||||
@@ -623,6 +671,71 @@ static void l2_norm_f32_cuda(
|
||||
}
|
||||
}
|
||||
|
||||
template <bool has_w, bool has_f>
|
||||
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<WARP_SIZE, 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);
|
||||
} 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<true, true >(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<true, false>(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<false, true >(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<false, false>(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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -868,6 +868,10 @@ static bool et_ggml_is_row_contiguous(const ggml_tensor * t) {
|
||||
static bool ggml_backend_et_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
|
||||
GGML_UNUSED(dev);
|
||||
|
||||
if (ggml_get_src_scale(op, 0)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool supported = false;
|
||||
switch (op->op) {
|
||||
case GGML_OP_CUMSUM:
|
||||
|
||||
@@ -134,7 +134,7 @@ 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 = 3; // 4 = pure W8A8, 3 = hybrid W8A8 + FP16 post-GLU (default), 2 = FP16 HMX -> HVX -> CPU, 1 = HVX -> CPU, 0 = CPU
|
||||
int opt_mm_select = 3; // 3 = W8A8 INT HMX -> FP16 HMX -> HVX -> CPU (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)
|
||||
@@ -3233,6 +3233,10 @@ static bool ggml_backend_hexagon_device_supports_op(ggml_backend_dev_t dev, cons
|
||||
return false;
|
||||
}
|
||||
|
||||
if (ggml_get_src_scale(op, 0)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool supp = false;
|
||||
if (ggml_op_is_empty(op->op) || ggml_is_empty(op)) {
|
||||
supp = true;
|
||||
|
||||
@@ -706,29 +706,6 @@ 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,
|
||||
@@ -748,6 +725,7 @@ static bool htp_kparams_solve_hmx_mm(
|
||||
struct htp_mm_kernel_params * kparams,
|
||||
bool is_glu = false
|
||||
) {
|
||||
GGML_UNUSED(act);
|
||||
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);
|
||||
@@ -776,9 +754,7 @@ static bool htp_kparams_solve_hmx_mm(
|
||||
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));
|
||||
const bool allow_w8a8 = (opt_mm_select >= 3) && (!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;
|
||||
|
||||
@@ -103,7 +103,6 @@ static __attribute__((noinline)) void hmx_fa_w8a8_q_prep_quad_f32(
|
||||
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);
|
||||
|
||||
@@ -114,10 +113,10 @@ static __attribute__((noinline)) void hmx_fa_w8a8_q_prep_quad_f32(
|
||||
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 y0 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0));
|
||||
HVX_Vector y1 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1));
|
||||
HVX_Vector y2 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2));
|
||||
HVX_Vector y3 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3));
|
||||
|
||||
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);
|
||||
@@ -248,7 +247,6 @@ static __attribute__((noinline)) void hmx_fa_w8a8_q_prep_quad_f16(
|
||||
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);
|
||||
|
||||
@@ -261,19 +259,19 @@ static __attribute__((noinline)) void hmx_fa_w8a8_q_prep_quad_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 y0 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf));
|
||||
HVX_Vector y1 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf));
|
||||
HVX_Vector y2 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf));
|
||||
HVX_Vector y3 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf));
|
||||
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 y0 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp0), v_inv0_qf));
|
||||
HVX_Vector y1 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp1), v_inv1_qf));
|
||||
HVX_Vector y2 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp2), v_inv2_qf));
|
||||
HVX_Vector y3 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp3), v_inv3_qf));
|
||||
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);
|
||||
@@ -287,10 +285,10 @@ static __attribute__((noinline)) void hmx_fa_w8a8_q_prep_quad_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 y0 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf));
|
||||
HVX_Vector y1 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf));
|
||||
HVX_Vector y2 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf));
|
||||
HVX_Vector y3 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf));
|
||||
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);
|
||||
@@ -583,7 +581,6 @@ static inline void hmx_fa_w8a8_pack_p_quad_u8_sm(
|
||||
}
|
||||
#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);
|
||||
|
||||
@@ -593,19 +590,19 @@ static inline void hmx_fa_w8a8_pack_p_quad_u8_sm(
|
||||
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 y0 = hvx_vec_i32_from_qf32_rnd(Q6_V_lo_W(vp0));
|
||||
HVX_Vector y1 = hvx_vec_i32_from_qf32_rnd(Q6_V_lo_W(vp1));
|
||||
HVX_Vector y2 = hvx_vec_i32_from_qf32_rnd(Q6_V_lo_W(vp2));
|
||||
HVX_Vector y3 = hvx_vec_i32_from_qf32_rnd(Q6_V_lo_W(vp3));
|
||||
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 y0 = hvx_vec_i32_from_qf32_rnd(Q6_V_hi_W(vp0));
|
||||
HVX_Vector y1 = hvx_vec_i32_from_qf32_rnd(Q6_V_hi_W(vp1));
|
||||
HVX_Vector y2 = hvx_vec_i32_from_qf32_rnd(Q6_V_hi_W(vp2));
|
||||
HVX_Vector y3 = hvx_vec_i32_from_qf32_rnd(Q6_V_hi_W(vp3));
|
||||
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);
|
||||
@@ -664,7 +661,6 @@ static __attribute__((noinline)) void hmx_fa_w8a8_v_prep_tile(
|
||||
|
||||
// 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();
|
||||
|
||||
@@ -673,7 +669,7 @@ static __attribute__((noinline)) void hmx_fa_w8a8_v_prep_tile(
|
||||
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_biased = hvx_vec_i32_from_qf32_rnd(Q6_Vqf32_vmpy_Vqf32Vqf32(v_sc_qf, v_inv127_qf));
|
||||
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);
|
||||
|
||||
|
||||
@@ -26,6 +26,11 @@ static inline HVX_Vector hvx_qf32_mul_sf_scalar(HVX_Vector v_sf, uint32_t scalar
|
||||
#endif
|
||||
}
|
||||
|
||||
static inline HVX_Vector hmx_qf32_to_i32_zp128(HVX_Vector v_qf) {
|
||||
const HVX_Vector v_128p5 = Q6_V_vsplat_R(0x43008000);
|
||||
return Q6_Vw_equals_Vsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(v_qf, v_128p5)));
|
||||
}
|
||||
|
||||
static inline void emit_int_hmx_scales_and_bias(
|
||||
HVX_Vector v_max_sf,
|
||||
float scale_const,
|
||||
@@ -35,9 +40,11 @@ static inline void emit_int_hmx_scales_and_bias(
|
||||
HVX_Vector * restrict bias_out) {
|
||||
|
||||
// |sum_k (a - zp) * w_hat| < 128 * l1_w = (l1_w << 7) <= 32768 * 2^p
|
||||
// Add half-ULP (2^(p-1) for p > 0) so truncating the low p bits rounds to nearest instead of biasing negative.
|
||||
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_rnd = Q6_Vw_vasr_VwR(Q6_Vw_vasl_VwVw(Q6_V_vsplat_R(1), v_p), 1);
|
||||
HVX_Vector v_ib = Q6_Vw_vsub_VwVw(Q6_Vw_vadd_VwVw(Q6_Vw_vasl_VwVw(Q6_V_vsplat_R(32768), v_p), v_rnd), 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));
|
||||
@@ -59,9 +66,11 @@ static inline void emit_int_hmx_scales_and_bias_zp0(
|
||||
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
|
||||
// Add half-ULP (2^(p-1) for p > 0) so truncating the low p bits rounds to nearest instead of biasing negative.
|
||||
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_rnd = Q6_Vw_vasr_VwR(Q6_Vw_vasl_VwVw(Q6_V_vsplat_R(1), v_p), 1);
|
||||
HVX_Vector v_ib = Q6_Vw_vadd_VwVw(Q6_Vw_vasl_VwVw(Q6_V_vsplat_R(32768), v_p), v_rnd);
|
||||
|
||||
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));
|
||||
@@ -97,8 +106,7 @@ static inline void int_hmx_inv127_from_max_f16(
|
||||
}
|
||||
|
||||
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_biased = hvx_vec_i32_from_qf32_rnd(Q6_Vqf32_vmpy_Vqf32Vqf32(v_sc_qf, v_inv127_qf));
|
||||
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)));
|
||||
}
|
||||
|
||||
@@ -625,9 +625,8 @@ static inline void int_hmx_asym_alpha_beta_wb(
|
||||
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));
|
||||
HVX_Vector v_a_bias = hvx_vec_i32_from_qf32_rnd(Q6_Vqf32_vmpy_Vqf32Vqf32(vd_qf, v_scale_q6_qf));
|
||||
HVX_Vector v_b_bias = hvx_vec_i32_from_qf32_rnd(Q6_Vqf32_vmpy_Vqf32Vqf32(vm_qf, v_scale_q6_qf));
|
||||
*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);
|
||||
}
|
||||
@@ -709,7 +708,6 @@ static inline void rescale_iq2_xxs_weight_superblock_impl(
|
||||
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();
|
||||
@@ -757,7 +755,7 @@ static inline void rescale_iq2_xxs_weight_superblock_impl(
|
||||
|
||||
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_m_bias = hvx_vec_i32_from_qf32_rnd(Q6_Vqf32_vmpy_Vqf32Vqf32(v_d_sc_qf, v_ls_qf));
|
||||
HVX_Vector v_alpha_h = Q6_Vh_vshuffe_VhVh(v_m_bias, v_m_bias);
|
||||
|
||||
#pragma clang loop pipeline(disable) unroll(disable)
|
||||
@@ -1053,12 +1051,10 @@ static inline void quantize_f16_quad_step_to_u8_sm(
|
||||
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;
|
||||
|
||||
@@ -1088,19 +1084,19 @@ static inline void quantize_f16_quad_step_to_u8_sm(
|
||||
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 y0 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf));
|
||||
HVX_Vector y1 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf));
|
||||
HVX_Vector y2 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf));
|
||||
HVX_Vector y3 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf));
|
||||
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 y0 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp0), v_inv0_qf));
|
||||
HVX_Vector y1 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp1), v_inv1_qf));
|
||||
HVX_Vector y2 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp2), v_inv2_qf));
|
||||
HVX_Vector y3 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp3), v_inv3_qf));
|
||||
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);
|
||||
@@ -1189,7 +1185,6 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f32_to_u8_sm_
|
||||
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);
|
||||
|
||||
@@ -1200,10 +1195,10 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f32_to_u8_sm_
|
||||
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 y0 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0));
|
||||
HVX_Vector y1 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1));
|
||||
HVX_Vector y2 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2));
|
||||
HVX_Vector y3 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3));
|
||||
|
||||
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);
|
||||
@@ -1288,7 +1283,6 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f32_to_u8_sm(
|
||||
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);
|
||||
|
||||
@@ -1298,10 +1292,10 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f32_to_u8_sm(
|
||||
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 y0 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0));
|
||||
HVX_Vector y1 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1));
|
||||
HVX_Vector y2 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2));
|
||||
HVX_Vector y3 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3));
|
||||
|
||||
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);
|
||||
@@ -1323,10 +1317,10 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f32_to_u8_sm(
|
||||
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 y0 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0));
|
||||
HVX_Vector y1 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1));
|
||||
HVX_Vector y2 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2));
|
||||
HVX_Vector y3 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3));
|
||||
|
||||
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);
|
||||
@@ -1406,7 +1400,6 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f16_to_u8_sm_
|
||||
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);
|
||||
|
||||
@@ -1418,7 +1411,7 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f16_to_u8_sm_
|
||||
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);
|
||||
v_one_f16, v_min_u8, v_max_u8);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1503,7 +1496,6 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f16_to_u8_sm(
|
||||
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);
|
||||
|
||||
@@ -1512,7 +1504,7 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f16_to_u8_sm(
|
||||
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);
|
||||
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_min_u8, v_max_u8);
|
||||
}
|
||||
for (uint32_t c = c_end_full; c < k_end; c += 64) {
|
||||
HVX_Vector vh0 = Q6_V_vzero();
|
||||
@@ -1527,7 +1519,7 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f16_to_u8_sm(
|
||||
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);
|
||||
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_min_u8, v_max_u8);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -218,6 +218,19 @@ static inline HVX_Vector hvx_vec_i16_from_hf_rnd_sat(HVX_Vector vin) {
|
||||
#endif
|
||||
}
|
||||
|
||||
static inline HVX_Vector hvx_vec_i32_from_qf32_rnd(HVX_Vector v_qf) {
|
||||
#if __HVX_ARCH__ >= 79
|
||||
HVX_Vector v_sf = Q6_Vsf_equals_Vqf32(v_qf);
|
||||
const HVX_Vector v_half = Q6_V_vor_VV(Q6_V_vsplat_R(0x3F000000),
|
||||
Q6_V_vand_VV(v_sf, Q6_V_vsplat_R(0x80000000)));
|
||||
return Q6_Vw_equals_Vsf(Q6_Vsf_vadd_VsfVsf(v_sf, v_half));
|
||||
#else
|
||||
const HVX_Vector v_half = Q6_V_vor_VV(Q6_V_vsplat_R(0x3F000000),
|
||||
Q6_V_vand_VV(v_qf, Q6_V_vsplat_R(0x80000000)));
|
||||
return Q6_Vw_equals_Vsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(v_qf, v_half)));
|
||||
#endif
|
||||
}
|
||||
|
||||
#if __HVX_ARCH__ < 79
|
||||
|
||||
static inline HVX_VectorPair hvx_vec_mpy_f32_f16(HVX_Vector x, HVX_Vector y)
|
||||
|
||||
@@ -104,6 +104,16 @@ static inline bool ggml_impl_is_view(const struct ggml_tensor * t) {
|
||||
return t->view_src != NULL;
|
||||
}
|
||||
|
||||
// scale of src[i] set by ggml_mul_mat_ext / ggml_mul_mat_id_ext
|
||||
static inline const struct ggml_tensor * ggml_get_src_scale(const struct ggml_tensor * op, int i) {
|
||||
GGML_ASSERT(i == 0 || i == 1);
|
||||
switch (op->op) {
|
||||
case GGML_OP_MUL_MAT: return op->src[2 + i];
|
||||
case GGML_OP_MUL_MAT_ID: return op->src[3 + i];
|
||||
default: return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
static inline float ggml_compute_softplus_f32(float input) {
|
||||
return (input > 20.0f) ? input : log1pf(expf(input));
|
||||
}
|
||||
@@ -114,6 +124,8 @@ GGML_API void ggml_rope_yarn_corr_dims(
|
||||
|
||||
GGML_API bool ggml_rope_get_truncate(const struct ggml_tensor * a);
|
||||
|
||||
GGML_API bool ggml_validate_flash_attn_ext_indexed_bias(const struct ggml_tensor * a);
|
||||
|
||||
//
|
||||
// logging
|
||||
//
|
||||
|
||||
@@ -97,6 +97,17 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_cpy(ggml_metal_l
|
||||
return res;
|
||||
}
|
||||
|
||||
ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mat_scale(ggml_metal_library_t lib) {
|
||||
const char * name = "kernel_mul_mat_scale";
|
||||
|
||||
ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
|
||||
if (!res.pipeline) {
|
||||
res = ggml_metal_library_compile_pipeline(lib, name, name, nullptr);
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_pool_1d(ggml_metal_library_t lib, const ggml_tensor * op, ggml_op_pool op_pool) {
|
||||
GGML_ASSERT(ggml_is_contiguous(op->src[0]));
|
||||
GGML_ASSERT(op->src[0]->type == GGML_TYPE_F32 && op->src[0]->type == op->type);
|
||||
|
||||
@@ -109,6 +109,7 @@ struct ggml_metal_pipeline_with_params ggml_metal_library_compile_pipeline(ggml_
|
||||
|
||||
struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_base (ggml_metal_library_t lib, enum ggml_op op);
|
||||
struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_cpy (ggml_metal_library_t lib, enum ggml_type tsrc, enum ggml_type tdst);
|
||||
struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mat_scale (ggml_metal_library_t lib);
|
||||
struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_pool_1d (ggml_metal_library_t lib, const struct ggml_tensor * op, enum ggml_op_pool op_pool);
|
||||
struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_pool_2d (ggml_metal_library_t lib, const struct ggml_tensor * op, enum ggml_op_pool op_pool);
|
||||
struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_get_rows (ggml_metal_library_t lib, enum ggml_type tsrc);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "ggml-metal-device.h"
|
||||
|
||||
#include "ggml-backend-impl.h"
|
||||
#include "ggml-impl.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
@@ -792,6 +793,10 @@ static bool ggml_metal_fusion_check_mul_mat_add(
|
||||
const ggml_tensor * mm = nodes[0];
|
||||
const ggml_tensor * add = nodes[1];
|
||||
|
||||
if (ggml_get_src_scale(mm, 0) != nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (ggml_metal_mul_mat_add_operand(mm, add) == nullptr ||
|
||||
!ggml_metal_op_mul_mat_may_use_mma(mm)) {
|
||||
return false;
|
||||
|
||||
@@ -290,6 +290,19 @@ typedef struct {
|
||||
size_t nb21;
|
||||
} ggml_metal_kargs_add_id;
|
||||
|
||||
typedef struct {
|
||||
int64_t ne0;
|
||||
int64_t ne2;
|
||||
uint64_t nb1;
|
||||
uint64_t nb2;
|
||||
uint64_t nb3;
|
||||
uint64_t s_nb0;
|
||||
uint64_t s_nb1;
|
||||
uint64_t ids_nb0;
|
||||
uint64_t ids_nb1;
|
||||
int32_t use_ids;
|
||||
} ggml_metal_kargs_mul_mat_scale;
|
||||
|
||||
typedef struct {
|
||||
int32_t ne00;
|
||||
int32_t ne01;
|
||||
|
||||
@@ -236,8 +236,13 @@ static int ggml_metal_op_encode_impl(ggml_metal_op_t ctx, int idx) {
|
||||
int n_fuse = 1;
|
||||
const ggml_metal_fusion * fusion = ctx->can_fuse(idx, GGML_METAL_FUSION_FULL, &n_fuse);
|
||||
if (fusion) {
|
||||
// fused kernels write to the last node of the group, not necessarily to the first node's dst
|
||||
is_concurrent = ggml_mem_ranges_check(ctx->mem_ranges, ctx->node(idx + n_fuse - 1));
|
||||
// every node of the group contributes sources and destinations, check all of them
|
||||
for (int j = 0; j < n_fuse; ++j) {
|
||||
if (!ggml_mem_ranges_check(ctx->mem_ranges, ctx->node(idx + j))) {
|
||||
is_concurrent = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -383,10 +388,12 @@ static int ggml_metal_op_encode_impl(ggml_metal_op_t ctx, int idx) {
|
||||
case GGML_OP_MUL_MAT:
|
||||
{
|
||||
n_fuse = ggml_metal_op_mul_mat(ctx, idx);
|
||||
ggml_metal_op_mul_mat_scale(ctx, idx);
|
||||
} break;
|
||||
case GGML_OP_MUL_MAT_ID:
|
||||
{
|
||||
n_fuse = ggml_metal_op_mul_mat_id(ctx, idx);
|
||||
ggml_metal_op_mul_mat_scale(ctx, idx);
|
||||
} break;
|
||||
case GGML_OP_GET_ROWS:
|
||||
{
|
||||
@@ -3218,6 +3225,58 @@ int ggml_metal_op_add_id(ggml_metal_op_t ctx, int idx) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
int ggml_metal_op_mul_mat_scale(ggml_metal_op_t ctx, int idx) {
|
||||
ggml_tensor * op = ctx->node(idx);
|
||||
|
||||
const ggml_tensor * scale = ggml_get_src_scale(op, 0);
|
||||
if (scale == nullptr) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
ggml_metal_library_t lib = ctx->lib;
|
||||
ggml_metal_encoder_t enc = ctx->enc;
|
||||
|
||||
GGML_ASSERT(scale->type == GGML_TYPE_F32);
|
||||
GGML_ASSERT(op->type == GGML_TYPE_F32);
|
||||
GGML_ASSERT(ggml_is_contiguous_rows(op));
|
||||
|
||||
const ggml_tensor * src0 = op->src[0];
|
||||
const ggml_tensor * ids = op->op == GGML_OP_MUL_MAT_ID ? op->src[2] : nullptr;
|
||||
|
||||
const bool per_channel_expert = ids && scale->ne[0] == op->ne[0] && scale->ne[1] == src0->ne[2];
|
||||
const bool per_expert = ids && (ggml_nelements(scale) == src0->ne[2] || per_channel_expert);
|
||||
const bool per_channel = per_expert ? per_channel_expert : scale->ne[0] == op->ne[0] && ggml_nelements(scale) > 1;
|
||||
|
||||
ggml_metal_kargs_mul_mat_scale args = {
|
||||
/*.ne0 =*/ op->ne[0],
|
||||
/*.ne2 =*/ op->ne[2],
|
||||
/*.nb1 =*/ op->nb[1],
|
||||
/*.nb2 =*/ op->nb[2],
|
||||
/*.nb3 =*/ op->nb[3],
|
||||
/*.s_nb0 =*/ per_channel ? scale->nb[0] : 0,
|
||||
/*.s_nb1 =*/ per_expert ? (per_channel_expert ? scale->nb[1] : scale->nb[0]) : 0,
|
||||
/*.ids_nb0 =*/ per_expert ? ids->nb[0] : 0,
|
||||
/*.ids_nb1 =*/ per_expert ? ids->nb[1] : 0,
|
||||
/*.use_ids =*/ per_expert,
|
||||
};
|
||||
|
||||
ggml_metal_op_concurrency_reset(ctx);
|
||||
|
||||
auto pipeline = ggml_metal_library_get_pipeline_mul_mat_scale(lib);
|
||||
|
||||
ggml_metal_encoder_set_pipeline(enc, pipeline);
|
||||
ggml_metal_encoder_set_bytes (enc, &args, sizeof(args), 0);
|
||||
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(scale), 1);
|
||||
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(per_expert ? ids : scale), 2);
|
||||
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(op), 3);
|
||||
|
||||
const int nth = std::min<int64_t>(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline), op->ne[0]);
|
||||
|
||||
ggml_metal_encoder_dispatch_threadgroups(enc, op->ne[1], op->ne[2]*op->ne[3], 1, nth, 1, 1);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
bool ggml_metal_op_flash_attn_ext_use_vec(const ggml_tensor * op) {
|
||||
assert(op->op == GGML_OP_FLASH_ATTN_EXT);
|
||||
|
||||
|
||||
@@ -83,6 +83,7 @@ int ggml_metal_op_pool_2d (ggml_metal_op_t ctx, int idx);
|
||||
int ggml_metal_op_fwht (ggml_metal_op_t ctx, int idx);
|
||||
int ggml_metal_op_mul_mat (ggml_metal_op_t ctx, int idx);
|
||||
int ggml_metal_op_mul_mat_id (ggml_metal_op_t ctx, int idx);
|
||||
int ggml_metal_op_mul_mat_scale (ggml_metal_op_t ctx, int idx);
|
||||
int ggml_metal_op_add_id (ggml_metal_op_t ctx, int idx);
|
||||
int ggml_metal_op_flash_attn_ext (ggml_metal_op_t ctx, int idx);
|
||||
int ggml_metal_op_bin (ggml_metal_op_t ctx, int idx);
|
||||
|
||||
@@ -205,6 +205,35 @@ kernel void kernel_add_id(
|
||||
}
|
||||
}
|
||||
|
||||
kernel void kernel_mul_mat_scale(
|
||||
constant ggml_metal_kargs_mul_mat_scale & args,
|
||||
device const char * scale,
|
||||
device const char * ids,
|
||||
device char * dst,
|
||||
uint3 tgpig[[threadgroup_position_in_grid]],
|
||||
ushort3 tpitg[[thread_position_in_threadgroup]],
|
||||
ushort3 ntg[[threads_per_threadgroup]]) {
|
||||
const int i1 = tgpig.x;
|
||||
const int i2 = tgpig.y % args.ne2;
|
||||
const int i3 = tgpig.y / args.ne2;
|
||||
|
||||
device const char * s = scale;
|
||||
|
||||
if (args.use_ids) {
|
||||
const int32_t expert = *((device const int32_t *) (ids + i1*args.ids_nb0 + i2*args.ids_nb1));
|
||||
if (expert < 0) {
|
||||
return;
|
||||
}
|
||||
s += expert*args.s_nb1;
|
||||
}
|
||||
|
||||
device float * dst_row = (device float *) (dst + i1*args.nb1 + i2*args.nb2 + i3*args.nb3);
|
||||
|
||||
for (int i0 = tpitg.x; i0 < args.ne0; i0 += ntg.x) {
|
||||
dst_row[i0] *= *((device const float *) (s + i0*args.s_nb0));
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
kernel void kernel_repeat(
|
||||
constant ggml_metal_kargs_repeat & args,
|
||||
|
||||
@@ -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
|
||||
@@ -1241,6 +1249,7 @@ struct ggml_backend_opencl_context {
|
||||
cl_kernel kernel_mul_mv_id_mxfp4_f32_flat;
|
||||
cl_kernel kernel_mul_mm_f32_f32_l4_lm;
|
||||
cl_kernel kernel_gemv_f32_f32_mc; // multi-column (small-N) f32 GEMV for spec/MTP verify
|
||||
cl_kernel kernel_gemv_f32_f32_mcr = nullptr;
|
||||
cl_kernel kernel_mul_mm_f16_f32_l4_lm;
|
||||
cl_kernel kernel_mul_mm_f16_f32_l4_lm_n8;
|
||||
cl_kernel kernel_mul_mm_q1_0_f32_l4_lm;
|
||||
@@ -1563,6 +1572,7 @@ struct ggml_backend_opencl_context {
|
||||
}
|
||||
#endif
|
||||
for (cl_kernel kernel : {
|
||||
kernel_gemv_f32_f32_mcr,
|
||||
kernel_xielu_f32,
|
||||
kernel_xielu_f16,
|
||||
kernel_mul_mm_f16_f32_kq_p8,
|
||||
@@ -4274,6 +4284,16 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) {
|
||||
|
||||
CL_CHECK((backend_ctx->kernel_mul_mm_f32_f32_l4_lm = clCreateKernel(backend_ctx->program_mul_mm_f32_f32_l4_lm, "kernel_mul_mm_f32_f32_l4_lm", &err), err));
|
||||
CL_CHECK((backend_ctx->kernel_gemv_f32_f32_mc = clCreateKernel(backend_ctx->program_mul_mm_f32_f32_l4_lm, "kernel_gemv_f32_f32_mc", &err), err));
|
||||
|
||||
cl_kernel mcr = clCreateKernel(backend_ctx->program_mul_mm_f32_f32_l4_lm, "kernel_gemv_f32_f32_mcr", &err);
|
||||
if (err == CL_SUCCESS) {
|
||||
if (backend_ctx->get_kernel_workgroup_size(mcr) >= 64) {
|
||||
backend_ctx->kernel_gemv_f32_f32_mcr = mcr;
|
||||
} else {
|
||||
CL_CHECK(clReleaseKernel(mcr));
|
||||
}
|
||||
}
|
||||
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
|
||||
@@ -7808,6 +7828,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 +11244,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<cl_mem> 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(
|
||||
@@ -12512,6 +12746,10 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te
|
||||
return false;
|
||||
}
|
||||
|
||||
if (ggml_get_src_scale(op, 0)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (op->op) {
|
||||
case GGML_OP_NONE:
|
||||
return true;
|
||||
@@ -32854,6 +33092,20 @@ static void ggml_cl_fwht(ggml_backend_t backend, const ggml_tensor * src, ggml_t
|
||||
backend_ctx->enqueue_ndrange_kernel(kernel, 2, global, local, dst);
|
||||
}
|
||||
|
||||
// reduce lanes per row for short K, down to four lanes.
|
||||
static int ggml_cl_mcr_lpr_log2(int ne00) {
|
||||
int lpr_log2 = 6;
|
||||
while (lpr_log2 > 2 && ((ne00 / 4) >> lpr_log2) < 4) {
|
||||
lpr_log2--;
|
||||
}
|
||||
return lpr_log2;
|
||||
}
|
||||
|
||||
static bool ggml_cl_mcr_wide_enough(int ne00, int ne01) {
|
||||
const int rows_per_wg = 64 >> ggml_cl_mcr_lpr_log2(ne00);
|
||||
return CEIL_DIV((size_t) ne01, rows_per_wg) >= 256;
|
||||
}
|
||||
|
||||
static void ggml_cl_mul_mat(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
|
||||
GGML_ASSERT(src0);
|
||||
GGML_ASSERT(src0->extra);
|
||||
@@ -33448,8 +33700,63 @@ static void ggml_cl_mul_mat(ggml_backend_t backend, const ggml_tensor * src0, co
|
||||
// under-occupied WG at ~2.3% tile utilization. Route to a per-output
|
||||
// (m,n) GEMV (64-thread WG, K-split + __local reduce) instead.
|
||||
// 2D contiguous, small N + skinny M only. Default on for X2E, GGML_OPENCL_F32_MC=0/1 forces it.
|
||||
static const char * f32_mc_env = getenv("GGML_OPENCL_F32_MC");
|
||||
const bool f32_mc = f32_mc_env ? atoi(f32_mc_env) != 0 : backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E;
|
||||
static const int f32_mc_env = [] {
|
||||
const char * env = getenv("GGML_OPENCL_F32_MC");
|
||||
return env ? atoi(env) : -1;
|
||||
}();
|
||||
const bool f32_mc = f32_mc_env >= 0 ? f32_mc_env != 0 : backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E;
|
||||
|
||||
static const int f32_mcr_env = [] {
|
||||
const char * env = getenv("GGML_OPENCL_F32_MCR");
|
||||
return env && *env ? atoi(env) : -1;
|
||||
}();
|
||||
const bool f32_mcr = f32_mcr_env >= 0 ? f32_mcr_env != 0 :
|
||||
(backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X);
|
||||
const bool f32_mcr_allowed = f32_mc_env >= 0 ? f32_mc_env != 0 : !adreno_e17_compiler_quirks(backend_ctx);
|
||||
|
||||
if (f32_mcr && f32_mcr_allowed && backend_ctx->kernel_gemv_f32_f32_mcr != nullptr &&
|
||||
ne11 >= 2 && ne11 <= 8 && ne00 > 0 && ne00 <= INT_MAX && ne01 > 0 && ne01 <= 512 &&
|
||||
(size_t) ne01 <= SIZE_MAX / 64 && (ne00 % 4 == 0) &&
|
||||
ne02 == 1 && ne03 == 1 && ne12 == 1 && ne13 == 1 &&
|
||||
dst->ne[2] == 1 && dst->ne[3] == 1 &&
|
||||
ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst) &&
|
||||
offset0 % 16 == 0 && offset1 % 16 == 0 && offsetd % sizeof(float) == 0 &&
|
||||
ggml_cl_mcr_wide_enough((int) ne00, (int) ne01)
|
||||
) {
|
||||
const int K = (int) ne00;
|
||||
const int M = (int) ne01;
|
||||
const int N = (int) ne11;
|
||||
|
||||
const int stride_a = K;
|
||||
const int stride_b = K;
|
||||
const int stride_d = M;
|
||||
|
||||
const int lpr_log2 = ggml_cl_mcr_lpr_log2(K);
|
||||
const int rows_per_wg = 64 >> lpr_log2;
|
||||
|
||||
cl_kernel mcr = backend_ctx->kernel_gemv_f32_f32_mcr;
|
||||
|
||||
CL_CHECK(clSetKernelArg(mcr, 0, sizeof(cl_mem), &extra0->data_device));
|
||||
CL_CHECK(clSetKernelArg(mcr, 1, sizeof(cl_ulong), &offset0));
|
||||
CL_CHECK(clSetKernelArg(mcr, 2, sizeof(cl_mem), &extra1->data_device));
|
||||
CL_CHECK(clSetKernelArg(mcr, 3, sizeof(cl_ulong), &offset1));
|
||||
CL_CHECK(clSetKernelArg(mcr, 4, sizeof(cl_mem), &extrad->data_device));
|
||||
CL_CHECK(clSetKernelArg(mcr, 5, sizeof(cl_ulong), &offsetd));
|
||||
CL_CHECK(clSetKernelArg(mcr, 6, sizeof(int), &K));
|
||||
CL_CHECK(clSetKernelArg(mcr, 7, sizeof(int), &M));
|
||||
CL_CHECK(clSetKernelArg(mcr, 8, sizeof(int), &N));
|
||||
CL_CHECK(clSetKernelArg(mcr, 9, sizeof(int), &stride_a));
|
||||
CL_CHECK(clSetKernelArg(mcr, 10, sizeof(int), &stride_b));
|
||||
CL_CHECK(clSetKernelArg(mcr, 11, sizeof(int), &stride_d));
|
||||
CL_CHECK(clSetKernelArg(mcr, 12, sizeof(int), &lpr_log2));
|
||||
|
||||
size_t global[] = {CEIL_DIV((size_t) M, rows_per_wg) * 64, 1, 1};
|
||||
size_t local[] = {64, 1, 1};
|
||||
|
||||
backend_ctx->enqueue_ndrange_kernel(mcr, 3, global, local, dst);
|
||||
return;
|
||||
}
|
||||
|
||||
if (f32_mc && ne11 >= 2 && ne11 <= 8 && ne01 <= 512 && (ne00 % 4 == 0) &&
|
||||
ne02 == 1 && ne12 == 1 && ne13 == 1 &&
|
||||
ggml_is_contiguous(src0) && ggml_is_contiguous(src1)) {
|
||||
@@ -36917,6 +37224,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");
|
||||
@@ -37221,6 +37546,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");
|
||||
@@ -37500,6 +37843,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");
|
||||
@@ -37699,6 +38060,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");
|
||||
@@ -38183,6 +38562,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");
|
||||
@@ -38522,6 +38919,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");
|
||||
@@ -38742,6 +39157,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");
|
||||
@@ -39042,6 +39475,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;
|
||||
|
||||
@@ -194,3 +194,64 @@ kernel void kernel_gemv_f32_f32_mc(
|
||||
}
|
||||
if (lane == 0) dst[(ulong)n * (uint)stride_d + m] = red[0];
|
||||
}
|
||||
|
||||
// Reuse each weight row across the narrow batch, with one accumulator per column.
|
||||
kernel void kernel_gemv_f32_f32_mcr(
|
||||
global const float * src0, ulong offset0,
|
||||
global const float * src1, ulong offset1,
|
||||
global float * dst, ulong offsetd,
|
||||
int ne00, // K
|
||||
int ne01, // M
|
||||
int ne11, // N, 2..8
|
||||
int stride_a,
|
||||
int stride_b,
|
||||
int stride_d,
|
||||
int lpr_log2 // lanes per row = 1 << lpr_log2
|
||||
) {
|
||||
src0 = (global const float*)((global const char*)src0 + offset0);
|
||||
src1 = (global const float*)((global const char*)src1 + offset1);
|
||||
dst = (global float*)((global char*)dst + offsetd);
|
||||
|
||||
const uint lane = get_local_id(0);
|
||||
const uint lpr = 1u << lpr_log2;
|
||||
const uint l = lane & (lpr - 1);
|
||||
const uint mr = get_group_id(0) * (64u >> lpr_log2) + (lane >> lpr_log2);
|
||||
const bool valid = mr < (uint)ne01;
|
||||
// Keep padded rows in the local-memory barriers.
|
||||
const uint m = valid ? mr : (uint)ne01 - 1;
|
||||
|
||||
global const float4 * wrow = (global const float4*)(src0 + (ulong)m * (uint)stride_a);
|
||||
const uint k4 = (uint)ne00 >> 2;
|
||||
|
||||
float acc[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
|
||||
for (uint k = l; k < k4; k += lpr) {
|
||||
const float4 w = wrow[k];
|
||||
#pragma unroll
|
||||
for (int n = 0; n < 8; n++) {
|
||||
if (n < ne11) {
|
||||
acc[n] += dot(w, ((global const float4*)(src1 + (ulong)n * (uint)stride_b))[k]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
local float red[8 * 64];
|
||||
#pragma unroll
|
||||
for (int n = 0; n < 8; n++) {
|
||||
red[n * 64 + lane] = acc[n];
|
||||
}
|
||||
barrier(CLK_LOCAL_MEM_FENCE);
|
||||
for (uint s = lpr >> 1; s > 0; s >>= 1) {
|
||||
if (l < s) {
|
||||
#pragma unroll
|
||||
for (int n = 0; n < 8; n++) {
|
||||
red[n * 64 + lane] += red[n * 64 + lane + s];
|
||||
}
|
||||
}
|
||||
barrier(CLK_LOCAL_MEM_FENCE);
|
||||
}
|
||||
if (l == 0 && valid) {
|
||||
for (int n = 0; n < ne11; n++) {
|
||||
dst[(ulong)n * (uint)stride_d + m] = red[n * 64 + lane];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
if (NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64|AMD64|aarch64)$")
|
||||
message(FATAL_ERROR "OpenVINO: OpenVINO toolkit supports x86-64 and arm64 but not ${CMAKE_SYSTEM_PROCESSOR}")
|
||||
endif()
|
||||
|
||||
find_package(OpenVINO REQUIRED COMPONENTS Runtime Threading)
|
||||
find_package(OpenCL REQUIRED)
|
||||
|
||||
@@ -24,17 +28,11 @@ if (WIN32)
|
||||
target_link_libraries(ggml-openvino PRIVATE psapi)
|
||||
endif()
|
||||
|
||||
if (GGML_OPENVINO)
|
||||
if (CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64")
|
||||
elseif (CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64" OR CMAKE_SYSTEM_PROCESSOR STREQUAL "amd64" OR CMAKE_SYSTEM_PROCESSOR STREQUAL "AMD64")
|
||||
else()
|
||||
message(FATAL_ERROR "OpenVINO: OpenVINO toolkit supports x86-64 and arm64 but not ${CMAKE_SYSTEM_PROCESSOR}")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Released runtimes retain the ordinary cache translators.
|
||||
include(CheckCXXSourceCompiles)
|
||||
include(CMakePushCheckState)
|
||||
unset(GGML_OPENVINO_HAS_CACHE_UPDATE CACHE)
|
||||
cmake_push_check_state(RESET)
|
||||
set(CMAKE_REQUIRED_LIBRARIES openvino::runtime)
|
||||
set(CMAKE_REQUIRED_INCLUDES "${CMAKE_CURRENT_SOURCE_DIR}/openvino/op")
|
||||
check_cxx_source_compiles("#include <recurrent_cache_update.hpp>
|
||||
@@ -43,8 +41,7 @@ int main() {
|
||||
auto gdn = std::make_shared<ov::op::internal::RecurrentGatedDeltaNetUpdate>(ov::OutputVector{});
|
||||
}"
|
||||
GGML_OPENVINO_HAS_CACHE_UPDATE)
|
||||
unset(CMAKE_REQUIRED_LIBRARIES)
|
||||
unset(CMAKE_REQUIRED_INCLUDES)
|
||||
cmake_pop_check_state()
|
||||
if(GGML_OPENVINO_HAS_CACHE_UPDATE)
|
||||
target_compile_definitions(ggml-openvino PRIVATE GGML_OPENVINO_HAS_CACHE_UPDATE=1)
|
||||
endif()
|
||||
|
||||
@@ -87,3 +87,11 @@ The generic recurrent-cache translation invalidates blobs made with the former s
|
||||
- File identity, size, modification/change timestamps, tensor offsets, graph structure, settings, and OpenVINO version identify cache entries. Linux uses device/inode and Windows uses volume serial/file index. Replacing, copying, or modifying a GGUF invalidates its entries. This avoids reading weight bytes and ties the cache to the local source files. Keep those files unchanged throughout loading and inference.
|
||||
- Use the same target device and compatible OpenVINO/plugin installation. Import support depends on the plugin; the tested CPU plugin cannot import MoE graphs containing `GatherMatmulCompressed`. GPU MoE and CPU dense graph imports were tested.
|
||||
- Blobs contain weights and can approach model size for each compiled graph. Import still reads those blobs and initializes the device.
|
||||
|
||||
# KV-only prefill
|
||||
|
||||
On the static path (NPU, or any device with `GGML_OPENVINO_FORCE_STATIC=1`), models whose tail layers read an earlier layer's KV get a KV-only prefill by default; `GGML_OPENVINO_KV_ONLY_PREFILL=0` turns it off. It compiles the static prefill graph with only the KV-cache writes as outputs (`openvino/pass/keep_cache_results.cpp`). Everything that only feeds the logits is dropped from it: for models whose tail layers read an earlier layer's KV (Gemma 3n/4 E-series) that is every KV-shared layer, plus the LM head. When the batch needs logits, the decode graph is then run once on the output token; it rewrites that token's KV rows and computes the dropped layers against the complete cache. It is used only when attention ops of the graph share a KV cache tensor and the graph has no recurrent state. If a batch needs more than one output token, or the output step fails, the backend logs a warning and uses the full prefill from then on.
|
||||
|
||||
# NPU host gather
|
||||
|
||||
`GGML_OPENVINO_NPU_HOST_GATHER=1` (NPU, opt-in) gathers the rows of large host-resident embedding tables (at least 64 MiB, raw GGUF data) on the host. The static graph gets the gathered rows through an `ggml_host_rows_<node>` input instead of an OpenVINO Gather over the table. NPUW otherwise lifts the table to a function input, and gathering from an input that large costs about as much as streaming the whole table every call (21.6 ms of Gemma 4 E2B decode). A table used only for such lookups (the Gemma 3n/4 per-layer embedding table) is not converted or bound to the NPU at all.
|
||||
|
||||
@@ -11,6 +11,7 @@ The variables for users, and the rules for values, are in [docs/backend/OPENVINO
|
||||
| `GGML_OPENVINO_DEBUG_INPUT` | all | Boolean | `0` | Print the input tensors. |
|
||||
| `GGML_OPENVINO_DEBUG_OUTPUT` | all | Boolean | `0` | Print the output tensors. |
|
||||
| `GGML_OPENVINO_DEBUG_NODE` | all | String | `not set` | Add the named graph nodes as outputs of the compiled model. Separate several names with commas. |
|
||||
| `GGML_OPENVINO_DEBUG_DYNAMIC_DIMS` | all | Boolean | `0` | Print each graph node and its sources with their shapes when a graph is decoded. `*` marks the dynamic (token) dimension. |
|
||||
| `GGML_OPENVINO_PRINT_CGRAPH_TENSOR_ADDRESS` | all | Boolean | `0` | Print the tensor address map once. |
|
||||
| `GGML_OPENVINO_LOG_UNSUPPORTED_OPS` | all | Boolean | `0` | Log each op that the backend does not support, with the tensor details and the reason. |
|
||||
| `GGML_OPENVINO_LOG_SUPPORTS_OP` | all | Integer | `0` | Log what `supports_op` accepts and rejects. `1`: summary at exit. `2`: also each call (the first calls are missing). |
|
||||
@@ -28,6 +29,9 @@ The variables for users, and the rules for values, are in [docs/backend/OPENVINO
|
||||
GGML_OPENVINO_DUMP_CGRAPH=1 GGML_OPENVINO_DUMP_IR=1 \
|
||||
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
|
||||
|
||||
# Shapes of each graph node, with * at the dynamic (token) dimension. Printed to stdout.
|
||||
GGML_OPENVINO_DEBUG_DYNAMIC_DIMS=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 4 -no-cnv -p "Hello" > dims.txt
|
||||
|
||||
# Log unsupported ops. The lines have the WARN level, which the default log verbosity shows (-lv 2 or higher).
|
||||
GGML_OPENVINO_LOG_UNSUPPORTED_OPS=1 ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
|
||||
|
||||
@@ -50,8 +54,8 @@ Each variable turns off an optimization that is on by default, or sets its stren
|
||||
|
||||
| Variable | Device | Type | Default | Description |
|
||||
|---|---|---|---|---|
|
||||
| `GGML_OPENVINO_KV_SLICE` | all | Boolean | `1` | Bind the KV cache, and size the KQ masks, at the attended length instead of the full context. CPU and GPU: a view over the cache. NPU: the prefill graph is compiled at the attended length, rounded up to a power of two, and replaced when that size changes. With `0`, `llama-bench -d` fails on the NPU. |
|
||||
| `GGML_OPENVINO_NPU_BLOB_PREBUILD` | NPU | Boolean | `1` | Decode attends the smallest `1024 * 2^k` rows that cover the next position, with one decode graph for each window. All windows are built, or read from the cache, together with the first prefill and decode pair. `0`: one decode graph attends the whole context. Use the same value in the run that writes the cache and in the runs that read it. |
|
||||
| `GGML_OPENVINO_KV_SLICE` | all | Integer | `1` | Bind the KV cache, and size the KQ masks, at the attended length instead of the full context. `0`: off. `1`: on, KV window base 1024. `N` (a multiple of 256): on, KV window base `N`. CPU and GPU: a view over the cache (any non-zero value just turns it on). Static path (NPU): the prefill graph is compiled at the smallest `N * 2^k` rows (clamped to the context) that cover the attended length; a loaded prefill graph of a larger window also serves a shorter prompt (with `GGML_OPENVINO_NPU_KV_ON_DEMAND=1`, only the exact window); the decode KV windows of `GGML_OPENVINO_NPU_BLOB_PREBUILD` use the same base. With `0`, `llama-bench -d` fails on the NPU. Use the same value in the run that writes the cache and in the runs that read it. |
|
||||
| `GGML_OPENVINO_NPU_BLOB_PREBUILD` | NPU | Boolean | `1` | With `GGML_OPENVINO_KV_SLICE` on, decode attends the smallest `N * 2^k` rows (`N` from `GGML_OPENVINO_KV_SLICE`) that cover the next position, with one decode graph for each window, and the prefill windows are aligned to them. Every decode window is built, or read from the cache, on the first call. With `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`, the first prompt also writes (or reads) the prefill graph of every window; only the prefill graph in use stays loaded, unless `GGML_OPENVINO_SELF_CONTAINED_MMAP=1` or `GGML_OPENVINO_NPU_KV_ON_DEMAND=1` keeps them all loaded. `0`, or `GGML_OPENVINO_KV_SLICE=0`: one decode graph attends the whole context, and prefill graphs are built on first use. Use the same value in the run that writes the cache and in the runs that read it. |
|
||||
| `GGML_OPENVINO_NPU_FAST_MASK` | NPU | Boolean | `1` | Write the prefill attention mask directly into the input tensor, without an intermediate copy. The result is identical. |
|
||||
| `GGML_OPENVINO_NPU_L0_HOST_TENSORS` | NPU | Boolean | `1` | Keep the KV cache and the compute buffers in Level Zero host memory, so the plugin reads them without an extra copy. Falls back to plain host memory if the allocation is not available. |
|
||||
| `GGML_OPENVINO_GDN_Q_SCALE` | NPU | Float | `64` | Factor of the GDN q pre-scaling, which keeps the GDN output above the FP16 flush-to-zero floor of the NPU. `0` or a negative value turns it off. Values below `64` are raised to `64`. |
|
||||
@@ -75,7 +79,6 @@ These options are off by default. They are not validated for general use: some h
|
||||
| Variable | Device | Type | Default | Description |
|
||||
|---|---|---|---|---|
|
||||
| `GGML_OPENVINO_NPU_DECODE_UNFOLD` | NPU | Boolean | `0` | Set `NPUW_UNFOLD_IREQS=YES` on the decode graph only. An explicit `GGML_OPENVINO_NPUW_UNFOLD_IREQS` or `GGML_OPENVINO_NPU_CONFIG` value takes precedence. |
|
||||
| `GGML_OPENVINO_NPU_PARALLEL_COMPILE` | NPU | Boolean | `0` | Compile the prefill and decode graphs in parallel. The load is shorter and the host memory peak during compilation is higher. |
|
||||
| `GGML_OPENVINO_NPU_KV_ON_DEMAND` | NPU | Boolean | `0` | Keep the ggml KV buffer non-resident and bind storage for each layer that grows with the rows in use, so a large `-c` costs memory only for the context that is reached. K is stored head-major and V transposed, as OpenVINO GenAI does. `llama-perplexity` fails with it. |
|
||||
| `GGML_OPENVINO_NPU_REQUANT_POLICY` | NPU | String | `group-128` | Layout of requantized weights: `group-128` (`Q4_0_128`) or `channel-wise` (`Q4_0_C`, lower accuracy). |
|
||||
| `GGML_OPENVINO_GDN_DECOMPOSE_CHUNK` | all | Integer | `16` | Tokens in one chunk when `GGML_OPENVINO_GDN_DECOMPOSE` is on. A power of 2 from 2 to 128; other values use `16`. |
|
||||
@@ -90,16 +93,13 @@ These options are off by default. They are not validated for general use: some h
|
||||
| `GGML_OPENVINO_REDUCE_COMPILE_MEM` | all | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Create fewer weight nodes during compilation, to lower the host memory in use. |
|
||||
| `GGML_OPENVINO_RELEASE_WEIGHTS` | GPU | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Release the host weight buffers when the compiled model holds its own copy. Needs stable graph shapes; do not use it for workloads that compile again. |
|
||||
| `GGML_OPENVINO_SPILL_DIR` | all | String | `not set` | Directory for a disk-backed weight buffer, so its pages can be reclaimed under memory pressure. It must be on real storage, not on tmpfs (`/tmp` on many systems). It is not part of the key of the compiled model cache and is ignored in cache-only mode. |
|
||||
| `GGML_OPENVINO_SELF_CONTAINED_BLOB` | NPU | Boolean | `0` | Requires `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`. Write the prefill and decode graphs as blobs with the weights inside; each blob takes about the size of the model on disk. Decode then attends the whole context. `GGML_OPENVINO_NPU_WEIGHTLESS_BANK` is the recommended cache layout for the NPU. |
|
||||
| `GGML_OPENVINO_NPU_SHARED_BANK` | NPU | Boolean | `0` | With `GGML_OPENVINO_SELF_CONTAINED_BLOB=1`: one weights bank for the prefill and decode blobs. With OpenVINO 2026.4.1 the blobs cannot be read back, so decode is compiled again. |
|
||||
| `GGML_OPENVINO_LAZY_HOST_THRESHOLD_MB` | NPU | Integer | `2048` | With `GGML_OPENVINO_SELF_CONTAINED_MMAP=1`: buffers of at least this size get demand-zero host memory instead of Level Zero host memory. |
|
||||
|
||||
```bash
|
||||
# NPU cache with the weights inside the blobs (experimental). Keep all other NPU settings the same in both runs.
|
||||
# NPU cache: weightless blobs plus one shared weights file. Keep all other NPU settings the same in both runs.
|
||||
export GGML_OPENVINO_DEVICE=NPU
|
||||
export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache
|
||||
export GGML_OPENVINO_SELF_CONTAINED_BLOB=1
|
||||
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 -lv 4 # first run: log shows "model cache WROTE"
|
||||
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 -lv 4 # first run: warns "no usable cached blobs", exports
|
||||
|
||||
export GGML_OPENVINO_SELF_CONTAINED_MMAP=1
|
||||
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 -lv 4 # later runs: log shows "model cache HIT"
|
||||
@@ -141,7 +141,6 @@ export GGML_OPENVINO_REDUCE_COMPILE_MEM=1
|
||||
# NPU: weightless cache, then use the memory-mapped GGUF as the model buffer.
|
||||
export GGML_OPENVINO_DEVICE=NPU
|
||||
export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache
|
||||
export GGML_OPENVINO_NPU_WEIGHTLESS_BANK=1
|
||||
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 # first run writes the cache
|
||||
export GGML_OPENVINO_SELF_CONTAINED_MMAP=1
|
||||
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 # later runs
|
||||
@@ -182,11 +181,15 @@ Other properties that are useful with `GGML_OPENVINO_NPU_CONFIG`. The backend do
|
||||
| `NPUW_UNFOLD_IREQS` | Boolean | `not set` | `NO` | One infer request for each part, also for repeating blocks. |
|
||||
| `LOG_LEVEL` | String | `not set` | `LOG_ERROR` | Log level of the NPU plugin, for example `LOG_INFO`. |
|
||||
|
||||
Set properties with `GGML_OPENVINO_NPU_CONFIG`:
|
||||
|
||||
```bash
|
||||
export GGML_OPENVINO_DEVICE=NPU
|
||||
export GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN,COMPILATION_NUM_THREADS=1,LOG_LEVEL=LOG_INFO"
|
||||
```
|
||||
|
||||
List the properties of the installed NPU plugin:
|
||||
|
||||
```cpp
|
||||
// List the properties of the installed NPU plugin with their current values
|
||||
ov::Core core;
|
||||
@@ -199,6 +202,35 @@ for (const auto & name : core.get_property("NPU", ov::supported_properties)) {
|
||||
- `NPUW_*` options, with type and default: `src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc` in the OpenVINO source.
|
||||
- Graphs without a KV cache compile without NPUW: the backend removes `NPU_USE_NPUW` and the `NPUW_*` keys for them.
|
||||
|
||||
### Example: gemma-4 E2B with the model cache
|
||||
|
||||
`GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` saves the model compiled for the NPU, so only the first start compiles it. Run step 1 once, then start the model as in step 2 every later time.
|
||||
|
||||
#### Step 1: first run, compile and save the model
|
||||
|
||||
```bash
|
||||
# This start takes longer: the backend compiles the model for the NPU and saves it in the cache directory
|
||||
# (with -lv 4 the log shows "no usable cached blobs ... compiling and exporting").
|
||||
# Use the model as usual, then exit with /exit.
|
||||
export GGML_OPENVINO_DEVICE=NPU
|
||||
export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache
|
||||
export GGML_OPENVINO_NPU_HOST_GATHER=1 # optional: faster generation, less memory and disk; the output can differ slightly
|
||||
export GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT=q4_0_128 # optional: slightly less memory; may lower accuracy
|
||||
export GGML_OPENVINO_PREFILL_CHUNK_SIZE=512 # optional: can make long prompts faster; makes the first run longer
|
||||
./build/ReleaseOV/bin/llama-cli -m google_gemma-4-E2B-it-Q4_K_M.gguf -c 4096
|
||||
```
|
||||
|
||||
#### Step 2: later runs, load the model from the cache
|
||||
|
||||
```bash
|
||||
# Use the same exports as in step 1 (repeat them in a new shell) and the same command.
|
||||
# The backend loads the compiled model instead of compiling it, so the model starts much faster
|
||||
# (with -lv 4 the log shows "model cache HIT"). A changed setting or -c value compiles and saves again,
|
||||
# or stops with an error when GGML_OPENVINO_SELF_CONTAINED_MMAP=1 is set.
|
||||
export GGML_OPENVINO_SELF_CONTAINED_MMAP=1 # optional, later runs only: slightly shorter start; fails without the cache of step 1
|
||||
./build/ReleaseOV/bin/llama-cli -m google_gemma-4-E2B-it-Q4_K_M.gguf -c 4096
|
||||
```
|
||||
|
||||
## GPU and CPU plugin properties
|
||||
|
||||
The backend sets no GPU or CPU property, except `CACHE_DIR` and `CACHE_MODE=OPTIMIZE_SIZE` when `GGML_OPENVINO_CACHE_DIR` is set.
|
||||
|
||||
@@ -20,8 +20,12 @@ ExtraQuantType ggml_openvino_get_npu_requant_type() {
|
||||
std::optional<ExtraQuantType> ggml_openvino_npu_token_embd_requant_type(const ggml_tensor * tensor) {
|
||||
// A Q6_K embedding table is stored as q8_0_c by default on the NPU. The int4 layouts only pay off for a tied
|
||||
// embedding, where the table is also the lm_head weight and GET_ROWS gathers the packed rows
|
||||
// before dequantizing them (see gather_compressed_rows).
|
||||
if (tensor->type != GGML_TYPE_Q6_K) {
|
||||
// before dequantizing them (see gather_compressed_rows). Other K-quant tables default to the channel-wise
|
||||
// int8 of ggml_openvino_get_requant_type() and follow this setting only when it is set explicitly
|
||||
// (Gemma 4 E2B: a tied Q4_K table is 384 MiB as int8, 198 MiB as q4_0_128).
|
||||
if (tensor->type != GGML_TYPE_Q6_K &&
|
||||
!((tensor->type == GGML_TYPE_Q4_K || tensor->type == GGML_TYPE_Q5_K) &&
|
||||
ggml_openvino_getenv_str("GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT") != nullptr)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const std::string quant = ggml_openvino_getenv_str("GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT", "q8_0_c");
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
#include <cctype>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
@@ -313,6 +312,17 @@ static std::string get_tensor_graph_input_ov_name(const GgmlOvDecoder * decoder,
|
||||
if (GgmlOvDecoder::is_inp_emb(tensor, op)) {
|
||||
return "embd";
|
||||
}
|
||||
const auto & model_params = decoder->get_model_params();
|
||||
if (tensor == model_params.prune_ids) {
|
||||
return "inp_prune_ids";
|
||||
}
|
||||
if (tensor == model_params.prune_keep) {
|
||||
return "inp_prune_keep";
|
||||
}
|
||||
if (auto it = model_params.pruned_masks.find(tensor); it != model_params.pruned_masks.end()) {
|
||||
// not a graph input: get_kq_mask_input() gathers the rows from the input mask of this name
|
||||
return get_tensor_graph_input_ov_name(decoder, cgraph, it->second, op) + "_pruned";
|
||||
}
|
||||
// gemma-4's KV-shared layers read the mask rows of their output tokens through GET_ROWS, which is not a mask
|
||||
// consumer, so match the masks by identity too
|
||||
if (GgmlOvDecoder::is_inp_mask(tensor, op) || decoder->is_kq_mask(tensor)) {
|
||||
@@ -796,8 +806,14 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
|
||||
} else if (GgmlOvDecoder::is_conv_state_writeback(node)) {
|
||||
op_case = 2;
|
||||
break;
|
||||
} else if (is_conv_states_all_tensor(node->view_src) && node->src[1] != nullptr &&
|
||||
node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src == node->view_src) {
|
||||
} else if (node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW &&
|
||||
node->src[1]->view_src == node->view_src &&
|
||||
(is_conv_states_all_tensor(node->view_src) ||
|
||||
(node->view_src->op == GGML_OP_NONE && ggml_is_contiguous(node->src[1]) &&
|
||||
!is_recurrent_cache(node->view_src) &&
|
||||
strncmp(node->view_src->name, "cache_", strlen("cache_")) != 0))) {
|
||||
// View writeback into a contiguous block of a plain (non-KV, non-recurrent) tensor at
|
||||
// a static offset, e.g. the mamba-style conv state copy into its cache row.
|
||||
op_case = 4;
|
||||
break;
|
||||
} else if (node->src[0]->src[0]->op == GGML_OP_GET_ROWS && node->src[1] != nullptr &&
|
||||
@@ -1075,7 +1091,32 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
|
||||
layer_mask.emplace(layer.value(), mask);
|
||||
max_extent = std::max(max_extent, leaf->ne[1]);
|
||||
if (mask->op == GGML_OP_NONE) {
|
||||
model_params.kq_masks.insert(mask);
|
||||
const ggml_tensor * layer_input_mask = layer_mask[layer.value()];
|
||||
if (layer_input_mask != mask && layer_input_mask->op == GGML_OP_NONE) {
|
||||
// a second input mask on the cache of a layer: the mask rows of gemma-4's KV-shared layers
|
||||
model_params.pruned_masks.emplace(mask, layer_input_mask);
|
||||
} else {
|
||||
model_params.kq_masks.insert(mask);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!model_params.pruned_masks.empty()) {
|
||||
// The first output row index list gathers the rows of the KV-shared layers, a later one the output rows
|
||||
// among them
|
||||
for (int i = 0; i < cgraph->n_nodes; i++) {
|
||||
const ggml_tensor * node = cgraph->nodes[i];
|
||||
if (node->op != GGML_OP_GET_ROWS || !is_output_idx(node->src[1], node)) {
|
||||
continue;
|
||||
}
|
||||
if (model_params.prune_ids == nullptr) {
|
||||
model_params.prune_ids = node->src[1];
|
||||
} else if (node->src[1] != model_params.prune_ids) {
|
||||
model_params.prune_keep = node->src[1];
|
||||
}
|
||||
}
|
||||
if (model_params.prune_ids == nullptr) {
|
||||
throw std::runtime_error("OpenVINO: masks of KV-shared layers without their row index list");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1210,7 +1251,8 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
|
||||
compute_params.seq_active_start = offset / seq_size;
|
||||
|
||||
// a mask that is itself a graph input has the shape of its OV parameter
|
||||
const std::string mask_name = mask->op != GGML_OP_NONE ? std::string() :
|
||||
const std::string mask_name = mask->op != GGML_OP_NONE || model_params.pruned_masks.count(mask) ?
|
||||
std::string() :
|
||||
mask == model_params.swa_mask ? get_tensor_ov_name(cgraph, mask) + "_swa" :
|
||||
get_tensor_ov_name(cgraph, mask);
|
||||
// gemma-4's KV-shared layers come last and take their mask rows from the input masks with GET_ROWS: keep
|
||||
@@ -1229,7 +1271,8 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
|
||||
}
|
||||
}
|
||||
if (is_static) {
|
||||
const bool slice_prefill = ggml_openvino_kv_slice_enabled() && compute_params.input_len > 1;
|
||||
const bool slice_prefill =
|
||||
ggml_openvino_kv_slice_enabled() && compute_params.input_len > 1;
|
||||
if (!slice_prefill) {
|
||||
compute_params.attention_size = model_params.ctx_per_seq;
|
||||
}
|
||||
@@ -1261,10 +1304,8 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
|
||||
compute_params.token_len_per_seq = ggml_nelements(node->src[1]);
|
||||
}
|
||||
|
||||
// When multiple ROPE ops in the graph disagree on op_params (e.g. gemma4's
|
||||
// mixed SWA/non-SWA layers with different n_dims or freq_base), we cannot
|
||||
// share a single precomputed rope_sin/rope_cos. Track divergence so the
|
||||
// translator falls back to per-op make_sin_cos in that case.
|
||||
// Multiple ROPE ops can disagree on op_params (e.g. gemma4's mixed SWA/non-SWA layers with different
|
||||
// n_dims or freq_base). Track divergence for the graph key and for decoder reuse.
|
||||
static_assert(sizeof(model_params.rope_params) == sizeof(int32_t) * 16, "rope_params size");
|
||||
if (!rope_seen) {
|
||||
memcpy(model_params.rope_params, node->op_params, sizeof(int32_t) * 16);
|
||||
@@ -1402,13 +1443,13 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
|
||||
if (is_static && compute_params.output_len == 0) {
|
||||
compute_params.output_len = 1;
|
||||
}
|
||||
// A sliced static prefill attends a power-of-two number of KV rows: every attended size needs its own compiled
|
||||
// prefill model, so a growing sequence compiles one when the attended length doubles, not for each ubatch.
|
||||
// Rounding up adds masked rows, which cost prefill time, so it stops at the next power of two.
|
||||
// A sliced static prefill attends base*2^k KV rows (base from GGML_OPENVINO_KV_SLICE): every attended size needs
|
||||
// its own compiled prefill model, so a growing sequence compiles one when the attended length doubles, not for
|
||||
// each ubatch. Rounding up adds masked rows, which cost prefill time, so it stops at the next window.
|
||||
if (is_static && ggml_openvino_kv_slice_enabled() && compute_params.input_len > 1 &&
|
||||
!model_params.is_cacheless_attn && compute_params.attention_size > 0 && model_params.ctx_per_seq > 0) {
|
||||
compute_params.attention_size =
|
||||
ggml_openvino_static_kv_window(compute_params.attention_size, model_params.ctx_per_seq);
|
||||
compute_params.attention_size = ggml_openvino_static_kv_window(
|
||||
compute_params.attention_size, model_params.ctx_per_seq, ggml_openvino_kv_slice_base());
|
||||
}
|
||||
// The GPU plugin keeps device memory for each KV length it sees, and llama.cpp grows the KV length in steps of
|
||||
// 256. Round it up (ggml_openvino_gpu_kv_window), so that a long context uses a few lengths and not one per step.
|
||||
@@ -1478,8 +1519,8 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op,
|
||||
// Both masks are named "attn_inp_kq_mask", so tell them apart by tensor identity.
|
||||
const bool swa_mask = is_swa_mask(input);
|
||||
int attention_size = swa_mask ? m_model_params.ctx_per_seq_swa * m_model_params.n_seq : m_model_params.ctx;
|
||||
const bool kv_window =
|
||||
m_is_prefill ? ggml_openvino_kv_slice_enabled() : ggml_openvino_npu_decode_bucket() > 0;
|
||||
const bool kv_window = m_is_prefill ? ggml_openvino_kv_slice_enabled() :
|
||||
ggml_openvino_npu_decode_bucket() > 0;
|
||||
if (kv_window) {
|
||||
attention_size = swa_mask ? m_compute_params.attention_size_swa : m_compute_params.attention_size;
|
||||
}
|
||||
@@ -1613,8 +1654,44 @@ bool GgmlOvDecoder::is_s_copy_leaf(const ggml_tensor * tensor) const {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool GgmlOvDecoder::is_host_gather_rows(const ggml_tensor * node) {
|
||||
if (!ggml_openvino_npu_host_gather_enabled() || node == nullptr || node->op != GGML_OP_GET_ROWS) {
|
||||
return false;
|
||||
}
|
||||
const ggml_tensor * table = node->src[0];
|
||||
const ggml_tensor * ids = node->src[1];
|
||||
// The table must hold raw ggml rows in host memory. OpenVINO buffers store weights in the extracted layout, except
|
||||
// with the NPU weightless cache, where they keep (or, with SELF_CONTAINED_MMAP, wrap) the raw GGUF bytes.
|
||||
constexpr size_t min_table_bytes = 64ull * 1024 * 1024;
|
||||
if (table == nullptr || ids == nullptr || table->view_src != nullptr || table->buffer == nullptr) {
|
||||
return false;
|
||||
}
|
||||
const bool raw_cache = ggml_openvino_npu_weightless_cache_enabled();
|
||||
const bool raw_rows = ggml_backend_buffer_is_openvino(table->buffer) ? raw_cache :
|
||||
ggml_backend_buffer_is_host(table->buffer);
|
||||
return table->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS && raw_rows &&
|
||||
ggml_get_type_traits(table->type)->to_float != nullptr &&
|
||||
ggml_nbytes(table) >= min_table_bytes && ids->type == GGML_TYPE_I32 && ids->op == GGML_OP_NONE &&
|
||||
ggml_nelements(ids) == ids->ne[0] && node->ne[1] == ids->ne[0];
|
||||
}
|
||||
|
||||
void GgmlOvDecoder::add_extra_inputs() {
|
||||
m_model_extra_inputs.clear();
|
||||
m_host_gather_rows.clear();
|
||||
if (m_is_static) {
|
||||
for (const auto & info : m_node_info_list) {
|
||||
if (is_host_gather_rows(info.node)) {
|
||||
const std::string name = std::string(host_rows_prefix) + info.node_name;
|
||||
m_host_gather_rows[name] = info.node;
|
||||
m_model_extra_inputs[name] = {ov::element::f32,
|
||||
ov::Shape{1, 1, (size_t) get_static_n_tokens(), (size_t) info.node->ne[0]},
|
||||
0,
|
||||
true,
|
||||
{},
|
||||
-1};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extra inputs:
|
||||
// 1. `attention_size`, used in FLASH_ATTN where the shape of the matmul's are 256 aligned,
|
||||
@@ -1679,7 +1756,6 @@ void GgmlOvDecoder::add_extra_inputs() {
|
||||
m_model_extra_inputs["ggml_hfa_mask"] = {
|
||||
ov::element::f16, ov::Shape{1, 1, chunk_size, past_capacity + chunk_size}, 0, true, {}, -1};
|
||||
}
|
||||
// create_1d_input("token_len", m_compute_params.token_len_per_seq * m_compute_params.n_seq_active);
|
||||
|
||||
// n_seq_active and attention_size(_swa) are dimensions of the KQ masks. Read them from the mask shape inside the
|
||||
// model: the GPU plugin then gets the Q Reshape and KV Slice shapes from shape inference instead of waiting for
|
||||
@@ -1885,6 +1961,9 @@ void GgmlOvDecoder::compute_model_inputs() {
|
||||
if (m_model_inputs.find(src_name) != m_model_inputs.end()) {
|
||||
continue;
|
||||
}
|
||||
if (is_pruned_mask(src)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
m_inputs[src_name] = src;
|
||||
|
||||
@@ -2087,22 +2166,6 @@ bool GgmlOvDecoder::is_kvcache_token_rows(const ggml_tensor * cache) const {
|
||||
return true;
|
||||
}
|
||||
|
||||
const ggml_tensor * GgmlOvDecoder::get_tensor_from_name(const std::string & name) const {
|
||||
for (int i = 0; i < m_cgraph->n_nodes; i++) {
|
||||
const auto * node = m_cgraph->nodes[i];
|
||||
for (int j = 0; j < GGML_MAX_SRC; j++) {
|
||||
const auto * src = node->src[j];
|
||||
if (src == nullptr) {
|
||||
break;
|
||||
}
|
||||
if (get_tensor_ov_name(m_cgraph, src) == name) {
|
||||
return src;
|
||||
}
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::string GgmlOvDecoder::get_hfa_history_input_name() const {
|
||||
for (const auto & [name, tensor] : m_inputs) {
|
||||
const auto * op = get_tensor_used_op(tensor);
|
||||
@@ -2143,6 +2206,10 @@ std::map<std::string, std::shared_ptr<ov::Node>> GgmlOvDecoder::create_weight_no
|
||||
continue;
|
||||
}
|
||||
|
||||
// A table whose rows are gathered on the host needs no OV weight for that use.
|
||||
if (i == 0 && is_host_gather_rows(node)) {
|
||||
continue;
|
||||
}
|
||||
// A view over a weight is served by the base tensor's Constant.
|
||||
ggml_tensor * base = src->view_src ? src->view_src : src;
|
||||
std::string src_name = get_tensor_ov_name(cgraph, base);
|
||||
@@ -2242,9 +2309,9 @@ std::shared_ptr<ov::Node> GgmlOvDecoder::create_weight_node(ggml_tensor * tensor
|
||||
// pointer to avoid re-extracting on every recompile. Opt-in via
|
||||
// GGML_OPENVINO_REDUCE_COMPILE_MEM or GGML_OPENVINO_MEMORY_OPTIMIZE. Skip
|
||||
// for `naive` (test/naive path) since use_bias changes the produced node.
|
||||
// Self-contained decode-window models are built after the pair; reusing the node keeps e.g. the
|
||||
// Cached decode-window models are built after the pair; reusing the node keeps e.g. the
|
||||
// token_embd vocab on the pair's NPUW bank uid instead of embedding and importing a second copy.
|
||||
const bool keep_for_windows = ggml_openvino_npu_raw_weight_cache_enabled() && ggml_openvino_npu_decode_bucket() > 0;
|
||||
const bool keep_for_windows = ggml_openvino_npu_weightless_cache_enabled() && ggml_openvino_npu_decode_bucket() > 0;
|
||||
const bool cacheable_nonov = (ggml_openvino_reduce_compile_mem_enabled() || keep_for_windows) && !is_ov_buffer &&
|
||||
!naive && tensor->data != nullptr;
|
||||
if (cacheable_nonov) {
|
||||
@@ -2273,10 +2340,10 @@ std::shared_ptr<ov::Node> GgmlOvDecoder::create_weight_node(ggml_tensor * tensor
|
||||
if (ggml_is_quantized(tensor->type)) {
|
||||
auto use_bias = naive;
|
||||
if (is_ov_buffer) {
|
||||
const bool preserve_raw = ggml_openvino_npu_raw_weight_cache_enabled();
|
||||
const bool preserve_raw = ggml_openvino_npu_weightless_cache_enabled();
|
||||
if (preserve_raw) {
|
||||
// A later context must fingerprint the same raw GGUF bytes before importing its
|
||||
// self-contained blob, so keep the model buffer immutable in this mode.
|
||||
// cached blob, so keep the model buffer immutable in this mode.
|
||||
ov_weight = process_weight_tensor(tensor, tensor->data, nullptr, use_bias);
|
||||
} else {
|
||||
// The regular path stores extracted weights in the model buffer. Copy raw data
|
||||
@@ -2689,7 +2756,10 @@ std::vector<std::string> GgmlOvDecoder::get_output_names(int node_idx) const {
|
||||
// the written state block plus the full updated cache (see translate_cpy op_case 13)
|
||||
return {m_node_info_list[node_idx].node_name, get_tensor_ov_name(m_cgraph, node->view_src)};
|
||||
}
|
||||
if (node->op == GGML_OP_GATED_DELTA_NET && (!m_model_params.has_rs_rollback || node->op_params[0] > 1)) {
|
||||
// Naive (op test) graphs have no runtime slot inputs for the native state writeback, so they keep the packed
|
||||
// [attention | state] output, which the consumers slice through the generic view path.
|
||||
if (!m_naive && node->op == GGML_OP_GATED_DELTA_NET &&
|
||||
(!m_model_params.has_rs_rollback || node->op_params[0] > 1)) {
|
||||
std::string attn_name;
|
||||
std::string state_name;
|
||||
for (int i = node_idx + 1; i < m_cgraph->n_nodes; i++) {
|
||||
@@ -2824,43 +2894,29 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
|
||||
if (src == nullptr) {
|
||||
continue;
|
||||
}
|
||||
struct ggml_tensor * root_src = nullptr;
|
||||
// if (src->org_src) {
|
||||
// root_src = src->org_src;
|
||||
// }
|
||||
if (root_src) {
|
||||
if (is_inp_tok(root_src, node) || is_inp_pos(root_src, node) || is_get_rows_input_idx(root_src, node)) {
|
||||
m_node_dynamic_dims[root_src] = 0;
|
||||
m_node_dynamic_dims[src] = m_node_dynamic_dims[root_src];
|
||||
continue;
|
||||
}
|
||||
self(self, root_src);
|
||||
m_node_dynamic_dims[src] = m_node_dynamic_dims[root_src];
|
||||
} else {
|
||||
if (is_inp_tok(src, node) || is_inp_pos(src, node) || is_get_rows_input_idx(src, node)) {
|
||||
m_node_dynamic_dims[src] = 0;
|
||||
continue;
|
||||
}
|
||||
if (is_inp_scale_rows(src, node) || is_inp_embd_leaf(src, node)) {
|
||||
m_node_dynamic_dims[src] = 1;
|
||||
continue;
|
||||
}
|
||||
if (!m_is_static && is_activation_input(src, node)) {
|
||||
m_node_dynamic_dims[src] = 1;
|
||||
continue;
|
||||
}
|
||||
// a view of a model weight (BERT's token type row) has no token dim
|
||||
if (node->op == GGML_OP_VIEW && src->op == GGML_OP_NONE && !is_stateful() && !m_model_is_splitted &&
|
||||
!(src->buffer != nullptr && src->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS)) {
|
||||
m_node_dynamic_dims[src] = 1;
|
||||
continue;
|
||||
}
|
||||
if (is_inp_embd_2d(src, node)) {
|
||||
m_node_dynamic_dims[src] = 1;
|
||||
continue;
|
||||
}
|
||||
self(self, src);
|
||||
if (is_inp_tok(src, node) || is_inp_pos(src, node) || is_get_rows_input_idx(src, node)) {
|
||||
m_node_dynamic_dims[src] = 0;
|
||||
continue;
|
||||
}
|
||||
if (is_inp_scale_rows(src, node) || is_inp_embd_leaf(src, node)) {
|
||||
m_node_dynamic_dims[src] = 1;
|
||||
continue;
|
||||
}
|
||||
if (!m_is_static && is_activation_input(src, node)) {
|
||||
m_node_dynamic_dims[src] = 1;
|
||||
continue;
|
||||
}
|
||||
// a view of a model weight (BERT's token type row) has no token dim
|
||||
if (node->op == GGML_OP_VIEW && src->op == GGML_OP_NONE && !is_stateful() && !m_model_is_splitted &&
|
||||
!(src->buffer != nullptr && src->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS)) {
|
||||
m_node_dynamic_dims[src] = 1;
|
||||
continue;
|
||||
}
|
||||
if (is_inp_embd_2d(src, node)) {
|
||||
m_node_dynamic_dims[src] = 1;
|
||||
continue;
|
||||
}
|
||||
self(self, src);
|
||||
}
|
||||
switch (node->op) {
|
||||
case GGML_OP_NONE:
|
||||
@@ -2885,9 +2941,6 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
|
||||
}
|
||||
}
|
||||
}
|
||||
// OPENVINO_ASSERT(dynamic_dim_value == node->ne[m_node_dynamic_dims[node]],
|
||||
// "Dynamic dim value mismatch for node: " + std::string(node->name) +
|
||||
// " and its src[1]: " + std::string(node->src[1]->name));
|
||||
}
|
||||
break;
|
||||
case GGML_OP_MUL:
|
||||
@@ -2904,7 +2957,6 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
|
||||
m_node_dynamic_dims[node] = -1;
|
||||
if (m_node_dynamic_dims[node->src[0]] != -1) {
|
||||
auto dynamic_dim_idx = m_node_dynamic_dims[node->src[0]];
|
||||
// auto dynamic_dim_value = node->src[0]->ne[dynamic_dim_idx];
|
||||
// src dim i moves to dim op_params[i]
|
||||
if (dynamic_dim_idx >= 0 && dynamic_dim_idx < GGML_MAX_DIMS) {
|
||||
m_node_dynamic_dims[node] = node->op_params[dynamic_dim_idx];
|
||||
@@ -3229,8 +3281,8 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
|
||||
visit_node(visit_node, node);
|
||||
}
|
||||
|
||||
// print the nodes in m_cgraph name & shape with the dynamic dim (the dynamic dim is the dimension with -1 in m_node_dynamic_dims) for debugging
|
||||
if (0) {
|
||||
// GGML_OPENVINO_DEBUG_DYNAMIC_DIMS: print each node and its sources with their shapes, '*' marking the dynamic dim
|
||||
if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_DYNAMIC_DIMS")) {
|
||||
for (int i = 0; i < m_cgraph->n_nodes; i++) {
|
||||
ggml_tensor * node = m_cgraph->nodes[i];
|
||||
int dynamic_dim = m_node_dynamic_dims[node];
|
||||
|
||||
@@ -47,6 +47,15 @@ struct ModelParams {
|
||||
// The attention masks that are graph inputs, by identity: gemma-4's KV-shared layers also read them through
|
||||
// GET_ROWS, which must resolve to the same OV parameter as the attention ops
|
||||
std::set<const ggml_tensor *> kq_masks;
|
||||
// gemma-4's KV-shared layers attend for the output rows only (prune_shared in src/models/gemma4.cpp): llama.cpp
|
||||
// copies their mask rows from the input masks on the host into separate inputs (out_mask, out_mask_swa), and
|
||||
// gathers their activations, positions and per-layer embeddings with an index list (inp_prune_ids). The static
|
||||
// models bind the input masks per prefill chunk, so these masks are not graph inputs: each maps to the input
|
||||
// mask it copies, and the OV model gathers its rows from that mask with inp_prune_ids instead.
|
||||
std::map<const ggml_tensor *, const ggml_tensor *> pruned_masks;
|
||||
const ggml_tensor * prune_ids = nullptr;
|
||||
// the output rows among the gathered rows (inp_prune_keep)
|
||||
const ggml_tensor * prune_keep = nullptr;
|
||||
|
||||
std::vector<std::string> kv_names;
|
||||
size_t kv_buffer_ctx_id = 0;
|
||||
@@ -86,7 +95,6 @@ struct ComputeParams {
|
||||
int swa_window = -1;
|
||||
int input_len = -1;
|
||||
int token_len_per_seq = -1;
|
||||
int past_kv_len = -1;
|
||||
int output_len = 1;
|
||||
|
||||
int cache_rs_reset_idx = -1;
|
||||
@@ -288,16 +296,38 @@ public:
|
||||
|
||||
virtual std::set<std::string> get_model_output_names() const override { return m_model_output_names; }
|
||||
|
||||
virtual std::set<std::string> get_cache_output_names() const override {
|
||||
std::set<std::string> names;
|
||||
for (const auto & name : m_model_output_names) {
|
||||
const ggml_tensor * tensor = m_model_outputs.at(name);
|
||||
if (is_kvcache(tensor, nullptr) || is_recurrent_cache(tensor)) {
|
||||
names.insert(name);
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
virtual bool is_kv_only_outputs() const override { return m_kv_only_outputs; }
|
||||
|
||||
// Convert the model with only the cache writes as outputs (GGML_OPENVINO_KV_ONLY_PREFILL); the conversion pipeline
|
||||
// then drops everything that only feeds the other outputs, see pass::KeepCacheResults.
|
||||
void set_kv_only_outputs(bool kv_only) { m_kv_only_outputs = kv_only; }
|
||||
|
||||
// GET_ROWS of a large host-resident weight table by graph-input ids (GGML_OPENVINO_NPU_HOST_GATHER): its rows
|
||||
// are gathered on the host and fed through the "ggml_host_rows_<node>" input instead of an OV Gather.
|
||||
static bool is_host_gather_rows(const ggml_tensor * node);
|
||||
static constexpr const char * host_rows_prefix = "ggml_host_rows_";
|
||||
const ggml_tensor * get_host_gather_rows(const std::string & input_name) const {
|
||||
auto it = m_host_gather_rows.find(input_name);
|
||||
return it == m_host_gather_rows.end() ? nullptr : it->second;
|
||||
}
|
||||
|
||||
const std::map<std::string, ggml_tensor *> & get_model_outputs() const { return m_model_outputs; }
|
||||
|
||||
virtual int get_ctx_size() const { return m_model_params.ctx; }
|
||||
|
||||
virtual int get_ctx_per_seq() const { return m_model_params.ctx_per_seq; }
|
||||
|
||||
virtual int get_ctx_per_seq_swa() const { return m_model_params.ctx_per_seq_swa; }
|
||||
|
||||
virtual int get_n_seq() const { return m_model_params.n_seq; }
|
||||
|
||||
virtual int is_swa_layer(int layer) const override {
|
||||
return std::find(m_model_params.swa_layers.begin(), m_model_params.swa_layers.end(), layer) !=
|
||||
m_model_params.swa_layers.end();
|
||||
@@ -318,14 +348,10 @@ public:
|
||||
return m_model_params.n_heads_kv;
|
||||
}
|
||||
|
||||
int get_past_kv_len() const { return m_compute_params.past_kv_len; }
|
||||
|
||||
int get_input_len() const { return m_compute_params.input_len; }
|
||||
|
||||
virtual int32_t * get_rope_params() const override { return const_cast<int32_t *>(m_model_params.rope_params); }
|
||||
|
||||
virtual bool has_mixed_rope_params() const override { return m_model_params.mixed_rope_params; }
|
||||
|
||||
virtual int get_ssm_state_size() const override { return m_model_params.state_size; }
|
||||
|
||||
virtual std::map<std::string, std::string> get_kv_param_res_names() const override;
|
||||
@@ -417,8 +443,6 @@ public:
|
||||
return v;
|
||||
}
|
||||
|
||||
const ggml_tensor * get_tensor_from_name(const std::string & name) const;
|
||||
|
||||
std::string get_hfa_history_input_name() const;
|
||||
|
||||
void clear_model_weights() { m_model_weights.clear(); }
|
||||
@@ -608,10 +632,6 @@ public:
|
||||
|
||||
bool is_direct_gdn_view(const ggml_tensor * node) const;
|
||||
|
||||
static bool is_cache(const ggml_tensor * tensor, const ggml_tensor * op) {
|
||||
return is_recurrent_cache(tensor) || is_kvcache(tensor, op);
|
||||
}
|
||||
|
||||
static bool is_kvcache(const ggml_tensor * tensor, const ggml_tensor * op) {
|
||||
if (tensor == nullptr || is_recurrent_cache(tensor)) {
|
||||
return false;
|
||||
@@ -697,6 +717,8 @@ public:
|
||||
|
||||
bool is_kq_mask(const ggml_tensor * tensor) const { return m_model_params.kq_masks.count(tensor) != 0; }
|
||||
|
||||
bool is_pruned_mask(const ggml_tensor * tensor) const { return m_model_params.pruned_masks.count(tensor) != 0; }
|
||||
|
||||
// A graph-input index list of GET_ROWS: out_ids, or the inp->s_copy leaf when build_rs gathers
|
||||
// every recurrent state at once.
|
||||
static bool is_get_rows_input_idx(const ggml_tensor * tensor, const ggml_tensor * op) {
|
||||
@@ -722,33 +744,6 @@ public:
|
||||
op->src[0]->buffer->usage == GGML_BACKEND_BUFFER_USAGE_ANY;
|
||||
}
|
||||
|
||||
std::string get_graph_input_ov_name(const ggml_tensor * tensor, const ggml_tensor * op) const {
|
||||
if (is_inp_pos(tensor, op)) {
|
||||
return "inp_pos";
|
||||
}
|
||||
if (is_inp_emb(tensor, op)) {
|
||||
return "embd";
|
||||
}
|
||||
if (is_inp_mask(tensor, op)) {
|
||||
// Give the two attention masks distinct OV parameter names.
|
||||
//
|
||||
// An interleaved-SWA model builds one full-attention mask and one sliding-window mask,
|
||||
// but build_attn_inp_kq_mask() names them identically, so keying a parameter off
|
||||
// tensor->name alone makes the second mask OVERWRITE the first in m_model_inputs: both
|
||||
// attention types then read a single parameter, and the windowed layers silently run
|
||||
// against an unbanded mask. Disambiguate using the SWA layer set computed in
|
||||
// compute_llm_params(), which classifies by mask tensor identity rather than by name.
|
||||
//
|
||||
// When no SWA layer was found there is only one mask in play, so the plain name is
|
||||
// correct and no _swa parameter is created.
|
||||
if (m_model_params.swa_layers.empty()) {
|
||||
return "self_kq_mask";
|
||||
}
|
||||
return is_swa_mask(tensor) ? "self_kq_mask_swa" : "self_kq_mask";
|
||||
}
|
||||
return tensor->name;
|
||||
}
|
||||
|
||||
private:
|
||||
void set_input_output();
|
||||
int compute_op_case(const ggml_tensor * node) const;
|
||||
@@ -776,6 +771,8 @@ private:
|
||||
std::set<std::string> m_model_output_names;
|
||||
// The output set the compiled model was built from, for has_same_graph_io().
|
||||
std::set<std::string> m_built_output_names;
|
||||
bool m_kv_only_outputs = false;
|
||||
std::map<std::string, const ggml_tensor *> m_host_gather_rows;
|
||||
std::vector<NodeInfo> m_node_info_list;
|
||||
std::map<ggml_tensor *, int> m_node_dynamic_dims;
|
||||
std::set<const ggml_tensor *> m_kvcache_4d;
|
||||
|
||||
@@ -162,6 +162,7 @@ constexpr env_var env_vars[] = {
|
||||
{"GGML_OPENVINO_DUMP_IR", env_type::BOOL},
|
||||
{"GGML_OPENVINO_DEBUG_INPUT", env_type::BOOL},
|
||||
{"GGML_OPENVINO_DEBUG_OUTPUT", env_type::BOOL},
|
||||
{"GGML_OPENVINO_DEBUG_DYNAMIC_DIMS", env_type::BOOL},
|
||||
// Force the static (NPU-shape) compute path on any device, e.g. GGML_OPENVINO_DEVICE=CPU,
|
||||
// to test the static-shape translation without NPUW/real NPU hardware in the loop.
|
||||
{"GGML_OPENVINO_FORCE_STATIC", env_type::BOOL},
|
||||
@@ -191,14 +192,12 @@ constexpr env_var env_vars[] = {
|
||||
{"GGML_OPENVINO_GDN_NATIVE_STATE", env_type::BOOL},
|
||||
{"GGML_OPENVINO_GDN_DECOMPOSE", env_type::BOOL},
|
||||
{"GGML_OPENVINO_NPU_L0_HOST_TENSORS", env_type::BOOL},
|
||||
{"GGML_OPENVINO_KV_SLICE", env_type::BOOL},
|
||||
{"GGML_OPENVINO_KV_SLICE", env_type::INT},
|
||||
{"GGML_OPENVINO_NPU_HFA_PREFILL", env_type::BOOL},
|
||||
{"GGML_OPENVINO_NPU_DECODE_UNFOLD", env_type::BOOL},
|
||||
{"GGML_OPENVINO_NPU_PARALLEL_COMPILE", env_type::BOOL},
|
||||
{"GGML_OPENVINO_SELF_CONTAINED_BLOB", env_type::BOOL},
|
||||
{"GGML_OPENVINO_SELF_CONTAINED_MMAP", env_type::BOOL},
|
||||
{"GGML_OPENVINO_NPU_SHARED_BANK", env_type::BOOL},
|
||||
{"GGML_OPENVINO_NPU_WEIGHTLESS_BANK", env_type::BOOL},
|
||||
{"GGML_OPENVINO_KV_ONLY_PREFILL", env_type::BOOL},
|
||||
{"GGML_OPENVINO_NPU_HOST_GATHER", env_type::BOOL},
|
||||
// Build the precise (but O(n_nodes)) graph cache key. Needed by op tests.
|
||||
{"GGML_OPENVINO_FULL_GRAPH_KEY", env_type::BOOL},
|
||||
};
|
||||
@@ -260,6 +259,12 @@ std::string checked_env_value(const env_var & var, const char * value) {
|
||||
if (!parse_env_int(value, number)) {
|
||||
GGML_ABORT("ggml-openvino: %s=%s is not valid, use a whole number", var.name, value);
|
||||
}
|
||||
if (std::strcmp(var.name, "GGML_OPENVINO_KV_SLICE") == 0 && number != 0 && number != 1 &&
|
||||
(number < 0 || number % 256 != 0)) {
|
||||
GGML_ABORT("ggml-openvino: %s=%s is not valid, use 0 (off), 1 (on) or a KV window size that is a multiple "
|
||||
"of 256",
|
||||
var.name, value);
|
||||
}
|
||||
return std::to_string(number);
|
||||
case env_type::FLOAT: {
|
||||
char * end = nullptr;
|
||||
@@ -548,10 +553,7 @@ std::string ggml_openvino_config_overrides_in_use() {
|
||||
|
||||
bool ggml_openvino_manual_gqa_enabled() {
|
||||
// set: a positive value enables it, 0 disables it; unset: on GPU only
|
||||
if (ggml_openvino_getenv_str("GGML_OPENVINO_MANUAL_GQA_ATTN") != nullptr) {
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0;
|
||||
}
|
||||
return ggml_openvino_is_gpu();
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN", ggml_openvino_is_gpu() ? 1 : 0) > 0;
|
||||
}
|
||||
|
||||
bool ggml_openvino_gdn_prescale_enabled() {
|
||||
@@ -580,10 +582,7 @@ bool ggml_openvino_npu_is_4000() {
|
||||
}
|
||||
|
||||
bool ggml_openvino_gdn_decompose_enabled() {
|
||||
if (ggml_openvino_getenv_str("GGML_OPENVINO_GDN_DECOMPOSE") != nullptr) {
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_GDN_DECOMPOSE") > 0;
|
||||
}
|
||||
return ggml_openvino_npu_is_4000();
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_GDN_DECOMPOSE", ggml_openvino_npu_is_4000() ? 1 : 0) > 0;
|
||||
}
|
||||
|
||||
int ggml_openvino_gdn_decompose_chunk() {
|
||||
@@ -607,19 +606,14 @@ float ggml_openvino_gdn_q_scale() {
|
||||
}
|
||||
|
||||
bool ggml_openvino_reduce_compile_mem_enabled() {
|
||||
const char * reduce_compile_mem = ggml_openvino_getenv_str("GGML_OPENVINO_REDUCE_COMPILE_MEM");
|
||||
if (reduce_compile_mem != nullptr) {
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_REDUCE_COMPILE_MEM") != 0;
|
||||
}
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE") != 0;
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_REDUCE_COMPILE_MEM",
|
||||
ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE")) != 0;
|
||||
}
|
||||
|
||||
bool ggml_openvino_release_weights_enabled() {
|
||||
const char * release_weights = ggml_openvino_getenv_str("GGML_OPENVINO_RELEASE_WEIGHTS");
|
||||
if (release_weights != nullptr) {
|
||||
return ggml_openvino_is_gpu() && ggml_openvino_getenv_int("GGML_OPENVINO_RELEASE_WEIGHTS") != 0;
|
||||
}
|
||||
return ggml_openvino_is_gpu() && ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE") != 0;
|
||||
return ggml_openvino_is_gpu() &&
|
||||
ggml_openvino_getenv_int("GGML_OPENVINO_RELEASE_WEIGHTS",
|
||||
ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE")) != 0;
|
||||
}
|
||||
|
||||
// Check if running on NPU
|
||||
@@ -635,8 +629,13 @@ bool ggml_openvino_is_gpu() {
|
||||
return has_prefix(ggml_openvino_get_device_name(), "GPU");
|
||||
}
|
||||
|
||||
int ggml_openvino_kv_slice_base() {
|
||||
const int value = ggml_openvino_getenv_int("GGML_OPENVINO_KV_SLICE", 1);
|
||||
return value <= 0 ? 0 : value == 1 ? 1024 : value;
|
||||
}
|
||||
|
||||
bool ggml_openvino_kv_slice_enabled() {
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_KV_SLICE", 1) != 0;
|
||||
return ggml_openvino_kv_slice_base() > 0;
|
||||
}
|
||||
|
||||
bool ggml_openvino_npu_fast_mask_enabled() {
|
||||
@@ -655,26 +654,15 @@ bool ggml_openvino_npu_decode_unfold_enabled() {
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_DECODE_UNFOLD") != 0;
|
||||
}
|
||||
|
||||
bool ggml_openvino_npu_parallel_compile_enabled() {
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_PARALLEL_COMPILE") != 0;
|
||||
}
|
||||
|
||||
int ggml_openvino_npu_decode_bucket() {
|
||||
if (!ggml_openvino_is_npu()) {
|
||||
return 0;
|
||||
}
|
||||
// A self-contained blob embeds its weights bank, and NPUW cannot load a blob into a bank that already holds
|
||||
// weights, so a decode model per KV window cannot be imported next to the decode model of the pair.
|
||||
if (ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR") &&
|
||||
ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_BLOB") != 0 &&
|
||||
!ggml_openvino_npu_weightless_bank_enabled()) {
|
||||
return 0;
|
||||
}
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_BLOB_PREBUILD", 1) != 0 ? 1024 : 0;
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_BLOB_PREBUILD", 1) != 0 ? ggml_openvino_kv_slice_base() : 0;
|
||||
}
|
||||
|
||||
int ggml_openvino_static_kv_window(int rows, int ctx) {
|
||||
int window = 1;
|
||||
int ggml_openvino_static_kv_window(int rows, int ctx, int base) {
|
||||
int window = std::max(base, 1);
|
||||
while (window < rows && window < ctx) {
|
||||
window *= 2;
|
||||
}
|
||||
@@ -683,7 +671,7 @@ int ggml_openvino_static_kv_window(int rows, int ctx) {
|
||||
|
||||
int ggml_openvino_gpu_kv_window(int rows, int ctx, int n_tokens) {
|
||||
if (n_tokens > 16) {
|
||||
return ggml_openvino_static_kv_window(rows, ctx);
|
||||
return ggml_openvino_static_kv_window(rows, ctx, 1);
|
||||
}
|
||||
// a multiple of 256 and of 2^k / 4, where 2^k <= rows < 2^(k+1)
|
||||
int step = 256;
|
||||
@@ -702,13 +690,22 @@ bool ggml_openvino_npu_kv_head_major_enabled() {
|
||||
ggml_openvino_kv_slice_enabled();
|
||||
}
|
||||
|
||||
bool ggml_openvino_npu_raw_weight_cache_enabled() {
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_BLOB") != 0 ||
|
||||
ggml_openvino_npu_weightless_bank_enabled();
|
||||
bool ggml_openvino_npu_host_gather_enabled() {
|
||||
return ggml_openvino_is_npu() && ggml_openvino_getenv_int("GGML_OPENVINO_NPU_HOST_GATHER") != 0;
|
||||
}
|
||||
|
||||
bool ggml_openvino_npu_weightless_bank_enabled() {
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_WEIGHTLESS_BANK") != 0;
|
||||
bool ggml_openvino_kv_only_prefill_enabled() {
|
||||
// On by default; it only takes effect for graphs with KV-shared layers.
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_KV_ONLY_PREFILL", 1) != 0;
|
||||
}
|
||||
|
||||
bool ggml_openvino_npu_weightless_cache_enabled() {
|
||||
return ggml_openvino_is_npu() && ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR") != nullptr;
|
||||
}
|
||||
|
||||
bool ggml_openvino_self_contained_mmap_enabled() {
|
||||
return ggml_openvino_npu_weightless_cache_enabled() &&
|
||||
ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_MMAP") != 0;
|
||||
}
|
||||
|
||||
namespace {
|
||||
@@ -768,8 +765,8 @@ bool kv_grow_locked(kv_storage_entry & e, size_t rows, size_t heads) {
|
||||
if (rows <= e.cap_rows) {
|
||||
return false;
|
||||
}
|
||||
const int bucket = ggml_openvino_npu_decode_bucket();
|
||||
size_t cap = bucket > 0 ? static_cast<size_t>(bucket) : 1024;
|
||||
const int base = ggml_openvino_kv_slice_base();
|
||||
size_t cap = base > 0 ? static_cast<size_t>(base) : 1024;
|
||||
while (cap < rows) {
|
||||
cap *= 2;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
#define CL_TARGET_OPENCL_VERSION 300
|
||||
#include <CL/cl.h>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <openvino/core/node.hpp>
|
||||
@@ -140,10 +139,14 @@ bool ggml_openvino_is_static();
|
||||
// KV-cache slicing: bind the KV cache, and size the KQ masks, at the attended length instead of the full context.
|
||||
// One mechanism, two modes:
|
||||
// dynamic graphs (CPU/GPU): the KV input is a view over the cache; the graph is not recompiled.
|
||||
// static graphs (NPU, or any device with GGML_OPENVINO_FORCE_STATIC): the prefill graph is compiled at the aligned
|
||||
// attended length and recompiled when it changes; decode keeps the full context.
|
||||
// On by default for all devices; GGML_OPENVINO_KV_SLICE=0 turns it off.
|
||||
// static graphs (NPU, or any device with GGML_OPENVINO_FORCE_STATIC): the prefill graph is compiled at a KV window of
|
||||
// base*2^k rows (clamped to ctx) covering the attended length and recompiled when it changes; decode keeps the
|
||||
// full context unless NPU decode KV windows are on (see ggml_openvino_npu_decode_bucket).
|
||||
// GGML_OPENVINO_KV_SLICE: unset or 1 = on with window base 1024, N (a multiple of 256) = on with window base N,
|
||||
// 0 = off. CPU/GPU dynamic graphs only use it as on/off.
|
||||
bool ggml_openvino_kv_slice_enabled();
|
||||
// Static KV window base of GGML_OPENVINO_KV_SLICE, 0 = off.
|
||||
int ggml_openvino_kv_slice_base();
|
||||
|
||||
// On by default: back NPU buffers with Level Zero host memory; GGML_OPENVINO_NPU_L0_HOST_TENSORS=0 turns it off.
|
||||
bool ggml_openvino_npu_l0_host_tensors_enabled();
|
||||
@@ -155,17 +158,28 @@ bool ggml_openvino_npu_fast_mask_enabled();
|
||||
// env-var name lives in one place; see docs/backend/OPENVINO.md for semantics.
|
||||
bool ggml_openvino_npu_hfa_prefill_enabled();
|
||||
bool ggml_openvino_npu_decode_unfold_enabled();
|
||||
bool ggml_openvino_npu_parallel_compile_enabled();
|
||||
// Static path (NPU, or any device with GGML_OPENVINO_FORCE_STATIC): prefill only the KV-writing part of the model
|
||||
// and compute the logits with one decode step. Pays off for models whose tail layers share earlier layers' KV
|
||||
// (Gemma 3n/4 E-series), where it skips those layers for prompt tokens. On by default (it only applies to graphs
|
||||
// with KV-shared attention, at most one output token per batch, and no HFA prefill);
|
||||
// GGML_OPENVINO_KV_ONLY_PREFILL=0 turns it off.
|
||||
bool ggml_openvino_kv_only_prefill_enabled();
|
||||
// Gather the rows of large embedding tables on the host and feed them to the static graph as an input, instead of
|
||||
// binding the whole table to the NPU (NPUW lifts it to a function input, and gathering from an input that large
|
||||
// costs about as much as streaming the table).
|
||||
bool ggml_openvino_npu_host_gather_enabled();
|
||||
|
||||
// GGML_OPENVINO_NPU_BLOB_PREBUILD (default 1): static NPU graphs attend a KV window of 1024*2^k rows (clamped to ctx)
|
||||
// instead of the whole ctx, with one decode model per window, all built/imported with the prefill/decode pair;
|
||||
// with head-major KV the prefill models of every window are also exported and preloaded.
|
||||
// Returns the window base (1024), 0 = off (GGML_OPENVINO_NPU_BLOB_PREBUILD=0).
|
||||
// GGML_OPENVINO_NPU_BLOB_PREBUILD (default 1), with GGML_OPENVINO_KV_SLICE on: static NPU decode also attends a KV
|
||||
// window of base*2^k rows (clamped to ctx, base from GGML_OPENVINO_KV_SLICE) instead of the whole ctx, with one
|
||||
// decode model per window, all built/imported with the prefill/decode pair.
|
||||
// The prefill windows are aligned to the decode windows, and with the weightless bank the prefill models of every
|
||||
// window are exported too (and preloaded with head-major KV).
|
||||
// Returns the window base, 0 = off (GGML_OPENVINO_NPU_BLOB_PREBUILD=0 or GGML_OPENVINO_KV_SLICE=0: decode attends
|
||||
// the full ctx).
|
||||
int ggml_openvino_npu_decode_bucket();
|
||||
|
||||
// Rows a static prefill attends with GGML_OPENVINO_KV_SLICE: the attended length rounded up to a power of two,
|
||||
// clamped to ctx.
|
||||
int ggml_openvino_static_kv_window(int rows, int ctx);
|
||||
// Smallest base*2^k covering rows, clamped to ctx.
|
||||
int ggml_openvino_static_kv_window(int rows, int ctx, int base);
|
||||
|
||||
// Rows the dynamic GPU graph attends for a batch of n_tokens tokens per sequence, clamped to ctx. The GPU plugin keeps
|
||||
// memory for each attended length, so a long context should use a few lengths:
|
||||
@@ -176,18 +190,19 @@ int ggml_openvino_static_kv_window(int rows, int ctx);
|
||||
int ggml_openvino_gpu_kv_window(int rows, int ctx, int n_tokens);
|
||||
|
||||
// On-demand NPU KV cache (GGML_OPENVINO_NPU_KV_ON_DEMAND): the ggml KV buffer stays non-resident and the
|
||||
// NPU binds per-tensor L0 storage that grows (base*2^k rows, base = decode bucket or 1024) with the rows in use.
|
||||
// NPU binds per-tensor L0 storage that grows (base*2^k rows, base = KV_SLICE window base or 1024) with the rows in use.
|
||||
bool ggml_openvino_npu_kv_on_demand_enabled();
|
||||
// On-demand KV with BLOB_PREBUILD and KV_SLICE: K storage is [heads][rows][head_size] and V storage is
|
||||
// [heads][head_size][rows] (head-major with heads * head_size channels); every static graph binds the whole storage
|
||||
// as [1, heads, rows, head_size] / [1, heads, head_size, rows], and attention uses V^T.
|
||||
bool ggml_openvino_npu_kv_head_major_enabled();
|
||||
|
||||
// NPU blob cache modes that keep the raw GGUF weights and skip requantization on a warm hit:
|
||||
// GGML_OPENVINO_SELF_CONTAINED_BLOB (weights embedded in each blob) or
|
||||
// GGML_OPENVINO_NPU_WEIGHTLESS_BANK (weightless blobs plus one shared weights file).
|
||||
bool ggml_openvino_npu_raw_weight_cache_enabled();
|
||||
bool ggml_openvino_npu_weightless_bank_enabled();
|
||||
// NPU with GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR: graphs with a KV cache are cached as weightless blobs plus one
|
||||
// shared weights file. Valid blobs are imported; otherwise the models are compiled and exported. The raw GGUF
|
||||
// weights are kept, and requantization is skipped on a warm hit.
|
||||
bool ggml_openvino_npu_weightless_cache_enabled();
|
||||
// GGML_OPENVINO_SELF_CONTAINED_MMAP=1 with the NPU weightless cache
|
||||
bool ggml_openvino_self_contained_mmap_enabled();
|
||||
void ggml_openvino_kv_storage_register(void * data, size_t row_bytes, size_t rows);
|
||||
void ggml_openvino_kv_storage_unregister(const void * base, size_t size);
|
||||
// Storage address backing ggml address `ptr` with at least `bytes` valid (grown if needed);
|
||||
|
||||
@@ -31,9 +31,6 @@
|
||||
#include <openvino/runtime/intel_npu/level_zero/level_zero.hpp>
|
||||
#include <openvino/runtime/properties.hpp>
|
||||
#include <openvino/runtime/tensor.hpp>
|
||||
#include <algorithm>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
#include <vector>
|
||||
@@ -98,8 +95,6 @@ struct ggml_backend_openvino_buffer_context {
|
||||
std::map<const void *, uint64_t> weight_fingerprints;
|
||||
std::vector<ggml_openvino_source_mapping> source_mappings;
|
||||
|
||||
// Used for re-allocation on device for kvcache
|
||||
void * data_prev = nullptr;
|
||||
// data is in the weight buffer registry
|
||||
bool weight_registered = false;
|
||||
|
||||
@@ -149,10 +144,7 @@ struct ggml_backend_openvino_buffer_context {
|
||||
// commits/zeroes it eagerly (fully resident). For such large buffers, reserve
|
||||
// demand-zero pages instead (no L0, no memset) so they stay non-resident. KV and small
|
||||
// I/O buffers keep the L0 host tensor for zero-copy import (decode throughput).
|
||||
const bool strict_mmap = device_name == "NPU" &&
|
||||
ggml_openvino_npu_raw_weight_cache_enabled() &&
|
||||
ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_MMAP") &&
|
||||
ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR");
|
||||
const bool strict_mmap = device_name == "NPU" && ggml_openvino_self_contained_mmap_enabled();
|
||||
// 2 GiB keeps a large-context KV cache (~1 GiB at ctx 8K) on L0 while the bigger prefill
|
||||
// compute buffer still goes lazy.
|
||||
const size_t lazy_host_threshold =
|
||||
@@ -391,12 +383,6 @@ static bool is_stateful_enabled() {
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_STATEFUL_EXECUTION") != 0;
|
||||
}
|
||||
|
||||
static bool is_self_contained_mmap_enabled() {
|
||||
return ggml_openvino_is_npu() && ggml_openvino_npu_raw_weight_cache_enabled() &&
|
||||
ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_MMAP") &&
|
||||
ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR");
|
||||
}
|
||||
|
||||
// Stores extra as the tensor's extra, deleting the one it replaces
|
||||
static void ggml_openvino_set_extra(ggml_backend_openvino_buffer_context * ctx,
|
||||
ggml_tensor * tensor,
|
||||
@@ -431,7 +417,6 @@ static bool ggml_openvino_swap_buffer_context(ggml_backend_buffer_t buffer,
|
||||
}
|
||||
|
||||
static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
|
||||
// GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
|
||||
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
|
||||
|
||||
// Put kvcache on device memory for GPU (NPU memory is too small even for kvcache). Same for the speculative
|
||||
@@ -505,7 +490,6 @@ static void ggml_backend_openvino_buffer_memset_tensor(ggml_backend_buffer_t buf
|
||||
uint8_t value,
|
||||
size_t offset,
|
||||
size_t size) {
|
||||
// GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
|
||||
GGML_ASSERT(tensor != nullptr && tensor->data != nullptr);
|
||||
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
|
||||
|
||||
@@ -617,7 +601,6 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
|
||||
const void * data,
|
||||
size_t offset,
|
||||
size_t size) {
|
||||
// GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
|
||||
GGML_ASSERT(tensor != nullptr && tensor->data != nullptr);
|
||||
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
|
||||
|
||||
@@ -642,10 +625,9 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
|
||||
bool is_supported_weight_shape = is_2d || (tensor->ne[3] == 1 && ggml_is_quantized(tensor->type));
|
||||
|
||||
if (is_weight_buffer && is_full_tensor_set && is_supported_weight_shape) {
|
||||
if (ggml_openvino_is_npu() && ggml_openvino_npu_raw_weight_cache_enabled() &&
|
||||
ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR")) {
|
||||
if (ggml_openvino_npu_weightless_cache_enabled()) {
|
||||
// Keep raw bytes for cache fingerprint validation and compile fallback; the imported
|
||||
// self-contained blob supplies the runtime weights, so eager requant is unnecessary.
|
||||
// blob supplies the runtime weights, so eager requant is unnecessary.
|
||||
memcpy(tensor->data, data, size);
|
||||
return;
|
||||
}
|
||||
@@ -653,32 +635,15 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
|
||||
auto result = process_weight_tensor(tensor, data, tensor->data);
|
||||
result.weight_node->set_friendly_name(tensor->name);
|
||||
|
||||
// const auto & layout = result.layout;
|
||||
ggml_openvino_extra_base * extra;
|
||||
|
||||
// Quantized path with extracted weight/scale/zp tensors
|
||||
if (result.is_quantized()) {
|
||||
extra = new ggml_openvino_quantized_weight_extra(std::move(result.weights), std::move(result.scales),
|
||||
std::move(result.zp), result.weight_node);
|
||||
|
||||
// if (layout.is_requant) {
|
||||
// GGML_LOG_DEBUG("%s: requantized %s to %s (u%d, block_size=%ld)\n", __func__, tensor->name,
|
||||
// extra_quant_type_name(layout.requant_type.value()), layout.is_u4 ? 4 : 8,
|
||||
// layout.weights_per_block);
|
||||
// } else {
|
||||
// int64_t n_blocks = ggml_nelements(tensor) / layout.weights_per_block;
|
||||
// GGML_LOG_DEBUG("%s: extracted quantized weight node for %s (u%d, %zu weights, %ld blocks)\n",
|
||||
// __func__, tensor->name, layout.is_u4 ? 4 : 8, layout.weights_size, n_blocks);
|
||||
// }
|
||||
} else {
|
||||
// F16/F32/BF16 weight or F16-requant
|
||||
extra = new ggml_openvino_weight_extra(std::move(result.weights), result.weight_node);
|
||||
|
||||
// if (layout.total_size > 0) {
|
||||
// GGML_LOG_DEBUG("%s: requantized %s to F16\n", __func__, tensor->name);
|
||||
// } else {
|
||||
// GGML_LOG_DEBUG("%s: created shared-memory weight node for %s\n", __func__, tensor->name);
|
||||
// }
|
||||
}
|
||||
|
||||
ggml_openvino_set_extra(ctx, tensor, extra);
|
||||
@@ -804,7 +769,6 @@ static void ggml_backend_openvino_buffer_get_tensor(ggml_backend_buffer_t buffer
|
||||
void * data,
|
||||
size_t offset,
|
||||
size_t size) {
|
||||
// GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
|
||||
GGML_ASSERT(tensor != nullptr && tensor->data != nullptr);
|
||||
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
|
||||
|
||||
@@ -843,7 +807,6 @@ static void ggml_backend_openvino_buffer_get_tensor(ggml_backend_buffer_t buffer
|
||||
static bool ggml_backend_openvino_buffer_cpy_tensor(ggml_backend_buffer_t buffer,
|
||||
const ggml_tensor * src,
|
||||
ggml_tensor * dst) {
|
||||
// GGML_LOG_DEBUG("%s: src tensor name=%s, dst tensor name=%s\n", __func__, src->name, dst->name);
|
||||
GGML_ASSERT(src != nullptr && dst != nullptr);
|
||||
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
|
||||
|
||||
@@ -978,7 +941,7 @@ static size_t ggml_backend_openvino_buffer_type_get_alloc_size(ggml_backend_buff
|
||||
const ggml_tensor * tensor) {
|
||||
GGML_UNUSED(buft);
|
||||
|
||||
if (is_self_contained_mmap_enabled()) {
|
||||
if (ggml_openvino_self_contained_mmap_enabled()) {
|
||||
return ggml_nbytes(tensor);
|
||||
}
|
||||
|
||||
@@ -1178,7 +1141,6 @@ static void ggml_backend_openvino_free(ggml_backend_t backend) {
|
||||
// reuses it instead of recompiling against zeroed weights.
|
||||
if (!ggml_openvino_weight_buffers_released()) {
|
||||
cache->graphs.clear();
|
||||
ov_clear_imported_blobs();
|
||||
std::lock_guard<std::mutex> fingerprints_lock(g_fallback_fingerprints_mutex);
|
||||
g_fallback_fingerprints.clear();
|
||||
}
|
||||
@@ -1455,7 +1417,7 @@ static void ggml_backend_openvino_device_get_props(ggml_backend_dev_t dev, ggml_
|
||||
props->caps = {
|
||||
/* .async = */ false,
|
||||
/* .host_buffer = */ false,
|
||||
/* .buffer_from_host_ptr = */ is_self_contained_mmap_enabled(),
|
||||
/* .buffer_from_host_ptr = */ ggml_openvino_self_contained_mmap_enabled(),
|
||||
/* .events = */ false,
|
||||
/* .mmap_support = */ true,
|
||||
/* .fast_async_host_input = */ false,
|
||||
@@ -1685,6 +1647,13 @@ static bool cpy_output_view_is_supported(const ggml_tensor * op) {
|
||||
GgmlOvDecoder::is_gdn_snapshot_writeback(op) || GgmlOvDecoder::is_ssm_state_writeback(op);
|
||||
}
|
||||
|
||||
// SET_ROWS writes whole rows of a contiguous destination. Other destination views (e.g. a permuted view of a
|
||||
// state tensor) are supported only for the recognized cache writes.
|
||||
static bool set_rows_output_view_is_supported(const ggml_tensor * op) {
|
||||
return op->view_src == nullptr || ggml_nbytes(op) == 0 || ggml_is_contiguous(op) ||
|
||||
GgmlOvDecoder::is_column_set_rows(op) || GgmlOvDecoder::is_conv_state_snapshot_writeback(op);
|
||||
}
|
||||
|
||||
static bool mul_mat_id_requires_large_tmp(const ggml_tensor * op) {
|
||||
const ggml_tensor * as = op->src[0];
|
||||
const ggml_tensor * ids = op->src[2];
|
||||
@@ -1795,6 +1764,9 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
|
||||
if (op->op == GGML_OP_SET_ROWS && op->src[0]->type == GGML_TYPE_BF16) {
|
||||
return {false, "SET_ROWS with BF16 src0 is not supported"};
|
||||
}
|
||||
if (op->op == GGML_OP_SET_ROWS && !set_rows_output_view_is_supported(op)) {
|
||||
return {false, "SET_ROWS with non-contiguous output view is not supported"};
|
||||
}
|
||||
if (op->ne[0] == 256 && (op->src[0]->type == GGML_TYPE_Q4_K || op->src[0]->type == GGML_TYPE_Q5_K ||
|
||||
op->src[0]->type == GGML_TYPE_Q4_1 || op->src[0]->type == GGML_TYPE_Q5_1)) {
|
||||
// These are all f16-arithmetic dequant rounding errors that intermittently exceed the
|
||||
@@ -2335,10 +2307,6 @@ static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(gg
|
||||
if (!supported) {
|
||||
return {false, "op " + std::string(ggml_op_name(op->op)) + " has no op translator"};
|
||||
}
|
||||
static std::set<ggml_op> ops_not_support_view_input{};
|
||||
if (ops_not_support_view_input.find(op->op) != ops_not_support_view_input.end() && has_view_op_input(op)) {
|
||||
return {false, "op " + std::string(ggml_op_name(op->op)) + " with VIEW input is not supported"};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2441,6 +2409,10 @@ struct supports_op_tally {
|
||||
} // namespace
|
||||
|
||||
static bool ggml_backend_openvino_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
|
||||
if (ggml_get_src_scale(op, 0)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
auto res = ggml_backend_openvino_device_supports_op_impl(dev, op);
|
||||
const bool supported = res.is_supported;
|
||||
if (!supported) {
|
||||
|
||||
@@ -8,29 +8,6 @@
|
||||
|
||||
static constexpr size_t GGML_QUANTIZATION_GROUP_SIZE = 32;
|
||||
|
||||
inline const char * extra_quant_type_name(ExtraQuantType t) {
|
||||
switch (t) {
|
||||
case ExtraQuantType::F16:
|
||||
return "F16";
|
||||
case ExtraQuantType::Q4_0_C:
|
||||
return "Q4_0_C";
|
||||
case ExtraQuantType::Q4_0_128:
|
||||
return "Q4_0_128";
|
||||
case ExtraQuantType::Q8_0_C:
|
||||
return "Q8_0_C";
|
||||
case ExtraQuantType::Q8_0_32:
|
||||
return "Q8_0_32";
|
||||
case ExtraQuantType::Q8_1_C:
|
||||
return "Q8_1_C";
|
||||
case ExtraQuantType::Q4_0_64:
|
||||
return "Q4_0_64";
|
||||
case ExtraQuantType::Q4_1_64:
|
||||
return "Q4_1_64";
|
||||
default:
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
// Result from process_weight_tensor containing the weight node and tensors.
|
||||
// For quantized weights, also contains the extracted layout and scale/zp tensors.
|
||||
struct OvWeight {
|
||||
|
||||
@@ -7,20 +7,21 @@
|
||||
#include "ggml-openvino-extra.h"
|
||||
#include "openvino/rt_info/weightless_caching_attributes.hpp"
|
||||
|
||||
#include <cerrno>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <limits>
|
||||
#include <sstream>
|
||||
#include <openvino/core/model.hpp>
|
||||
#include <openvino/core/version.hpp>
|
||||
#include <openvino/op/constant.hpp>
|
||||
#include <string>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <system_error>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
@@ -113,50 +114,12 @@ std::string hex64(uint64_t v) {
|
||||
return std::string(buf);
|
||||
}
|
||||
|
||||
// Portable mkdir for a single path component. Returns true if the directory
|
||||
// exists after the call (created now or already present).
|
||||
bool make_dir(const std::string & path) {
|
||||
#if defined(_WIN32)
|
||||
int rc = _mkdir(path.c_str());
|
||||
#else
|
||||
int rc = ::mkdir(path.c_str(), 0755);
|
||||
#endif
|
||||
if (rc == 0 || errno == EEXIST) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Create `path` and any missing parents (like `mkdir -p`). Best-effort:
|
||||
// returns true only if the full directory exists afterwards.
|
||||
bool make_dirs(const std::string & path) {
|
||||
if (path.empty()) {
|
||||
return false;
|
||||
}
|
||||
std::string acc;
|
||||
for (size_t i = 0; i < path.size(); ++i) {
|
||||
const char c = path[i];
|
||||
acc.push_back(c);
|
||||
const bool sep = (c == '/'
|
||||
#if defined(_WIN32)
|
||||
|| c == '\\'
|
||||
#endif
|
||||
);
|
||||
// Create each intermediate component (skip a leading "/" root).
|
||||
if (sep && acc.size() > 1) {
|
||||
std::string component = acc.substr(0, acc.size() - 1);
|
||||
#if defined(_WIN32)
|
||||
// A drive root such as "D:" cannot be mkdir'ed (EACCES, not EEXIST).
|
||||
if (component.size() == 2 && component[1] == ':') {
|
||||
continue;
|
||||
}
|
||||
#endif
|
||||
if (!make_dir(component)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return make_dir(path);
|
||||
// Create `path` and any missing parents (like `mkdir -p`). True if the directory exists afterwards.
|
||||
bool make_dirs(const std::string & path, std::error_code & ec) {
|
||||
const auto fs_path = std::filesystem::u8path(path);
|
||||
std::filesystem::create_directories(fs_path, ec);
|
||||
std::error_code ec_dir;
|
||||
return std::filesystem::is_directory(fs_path, ec_dir);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -179,10 +142,8 @@ static const char * cache_settings[] = {
|
||||
"GGML_OPENVINO_EXACT_ZERO_POINT",
|
||||
"GGML_OPENVINO_STATEFUL_EXECUTION",
|
||||
"GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT",
|
||||
"GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS",
|
||||
"GGML_OPENVINO_REDUCE_COMPILE_MEM",
|
||||
"GGML_OPENVINO_MEMORY_OPTIMIZE",
|
||||
"GGML_OPENVINO_PROFILING",
|
||||
"GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK",
|
||||
"GGML_OPENVINO_KV_SCATTER_ELEMENTS",
|
||||
"GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN",
|
||||
@@ -337,9 +298,10 @@ std::string ggml_openvino_model_cache_dir() {
|
||||
// Create the cache directory (and parents) on first use so callers don't
|
||||
// have to pre-create it; a missing dir would otherwise silently disable the
|
||||
// cache (manifest/blob writes fail with no directory to write into).
|
||||
if (!make_dirs(path)) {
|
||||
GGML_LOG_WARN("ggml-openvino: could not create model cache dir '%s' (errno=%d); caching disabled\n",
|
||||
path.c_str(), errno);
|
||||
std::error_code ec;
|
||||
if (!make_dirs(path, ec)) {
|
||||
GGML_LOG_WARN("ggml-openvino: could not create model cache dir '%s' (%s); caching disabled\n", path.c_str(),
|
||||
ec.message().c_str());
|
||||
return std::string();
|
||||
}
|
||||
return path;
|
||||
@@ -370,13 +332,16 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph,
|
||||
// Version 7 reads ROPE frequency factors named other than rope_freqs.weight as a Constant, not a Parameter.
|
||||
// Version 8 drops result_norm from the outputs when it has a consumer, and hashes the output flags.
|
||||
// Version 9 hashes GGML_OPENVINO_ROPE_F32_ANGLE, which became opt-in.
|
||||
h = fnv1a_u64(h, 9);
|
||||
// Version 10 hashes only whether GGML_OPENVINO_PROFILING is 2 or more (it then compiles with enable_profiling),
|
||||
// and no longer GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS, which only changes the output bindings.
|
||||
h = fnv1a_u64(h, 10);
|
||||
h = fnv1a(h, graph_signature.data(), graph_signature.size());
|
||||
for (const char * name : cache_settings) {
|
||||
const char * value = ggml_openvino_getenv_str(name, "");
|
||||
h = fnv1a(h, value, strlen(value) + 1);
|
||||
}
|
||||
h = fnv1a_u64(h, ggml_openvino_gdn_decompose_enabled() ? ggml_openvino_gdn_decompose_chunk() : 0);
|
||||
h = fnv1a_u64(h, ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING") >= 2 ? 1 : 0);
|
||||
if (const char * debug_nodes = ggml_openvino_getenv_str("GGML_OPENVINO_DEBUG_NODE")) {
|
||||
h = fnv1a(h, "GGML_OPENVINO_DEBUG_NODE", sizeof("GGML_OPENVINO_DEBUG_NODE"));
|
||||
h = fnv1a(h, debug_nodes, strlen(debug_nodes) + 1);
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
// Compiled blobs include weights. Cache-only execution skips weight uploads and graph compilation.
|
||||
// On NPU, GGML_OPENVINO_SELF_CONTAINED_BLOB=1 exports embedded-weight prefill/decode
|
||||
// blobs. A warm hit skips weight requantization, graph conversion, and compilation,
|
||||
// at the cost of roughly model-size storage per blob and separate NPUW weight banks.
|
||||
// After both blobs exist, GGML_OPENVINO_SELF_CONTAINED_MMAP=1 additionally wraps the
|
||||
// GGUF mmap instead of allocating the private OpenVINO model buffer. This mode is
|
||||
// import-only and fails clearly if either required blob is missing or invalid.
|
||||
// GGML_OPENVINO_NPU_WEIGHTLESS_BANK=1 is the same raw-weight flow, but exports weightless
|
||||
// prefill/decode blobs plus ONE <weights_fp>-<weights_fp>.weights.bin shared by every prefill/decode pair
|
||||
// of the model (pairs differ only in KV window). Warm import reads the weights from that file
|
||||
// (ov::weights_path) and NPUW deduplicates all models into one bank
|
||||
// (no OpenVINO patch needed), so the weights are stored once on disk and resident once.
|
||||
// On NPU, GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR imports the cached prefill/decode blobs when they are
|
||||
// valid; otherwise it compiles them and exports weightless blobs plus ONE
|
||||
// <weights_fp>-<weights_fp>.weights.bin shared by every prefill/decode pair of the model (pairs differ
|
||||
// only in KV window), with a warning. Import reads the weights from that file (ov::weights_path) and NPUW
|
||||
// deduplicates all models into one bank, so the weights are stored once on disk and resident once.
|
||||
// GGML_OPENVINO_SELF_CONTAINED_MMAP=1 additionally wraps the GGUF mmap instead of allocating the private
|
||||
// OpenVINO model buffer. This mode is import-only and fails clearly if a required blob is missing.
|
||||
|
||||
#include "ggml.h"
|
||||
|
||||
@@ -84,7 +80,7 @@ bool ggml_openvino_model_cache_verify_manifest(const std::string & path,
|
||||
std::vector<std::string> & inputs,
|
||||
std::vector<std::string> & outputs);
|
||||
|
||||
// GGML_OPENVINO_NPU_WEIGHTLESS_BANK: a weights file shared by weightless blobs. Every weightless-tagged
|
||||
// NPU cache: a weights file shared by weightless blobs. Every weightless-tagged
|
||||
// Constant is one region keyed by its data pointer (NPUW maps a Constant to its file offset by pointer).
|
||||
struct ggml_openvino_weights_layout {
|
||||
std::string path;
|
||||
|
||||
@@ -111,11 +111,14 @@ public:
|
||||
virtual const std::map<std::string, ModelExtraInputInfo> & get_model_extra_inputs() const = 0;
|
||||
virtual const std::map<std::string, std::shared_ptr<ov::Node>> & get_model_weights() const = 0;
|
||||
virtual std::set<std::string> get_model_output_names() const = 0;
|
||||
// KV-only prefill (GGML_OPENVINO_KV_ONLY_PREFILL): the model keeps only the cache outputs, see
|
||||
// pass::KeepCacheResults.
|
||||
virtual bool is_kv_only_outputs() const { return false; }
|
||||
// The outputs that write a KV or recurrent cache.
|
||||
virtual std::set<std::string> get_cache_output_names() const { return {}; }
|
||||
|
||||
virtual int32_t * get_rope_params() const = 0;
|
||||
|
||||
virtual bool has_mixed_rope_params() const = 0;
|
||||
|
||||
virtual int get_ssm_state_size() const = 0;
|
||||
|
||||
virtual std::map<std::string, std::string> get_kv_param_res_names() const = 0;
|
||||
|
||||
@@ -16,21 +16,15 @@ typedef std::map<std::string, Output<Node>> TensorMap;
|
||||
|
||||
class NodeContext : public frontend::NodeContext {
|
||||
public:
|
||||
NodeContext(const std::shared_ptr<GgmlDecoder> & decoder,
|
||||
std::shared_ptr<TensorMap> & tensor_map,
|
||||
int node_idx,
|
||||
TranslateSession * translate_session = nullptr) :
|
||||
NodeContext(const std::shared_ptr<GgmlDecoder> & decoder, std::shared_ptr<TensorMap> & tensor_map, int node_idx) :
|
||||
ov::frontend::NodeContext(decoder->get_op_type(node_idx)),
|
||||
m_decoder(decoder),
|
||||
m_tensor_map(tensor_map),
|
||||
m_node_idx(node_idx),
|
||||
m_translate_session(translate_session) {
|
||||
m_node_idx(node_idx) {
|
||||
m_input_names = decoder->get_input_names(m_node_idx);
|
||||
m_output_names = decoder->get_output_names(m_node_idx);
|
||||
}
|
||||
|
||||
TranslateSession * get_translate_session() const { return m_translate_session; }
|
||||
|
||||
const std::vector<std::string> & get_input_names() const { return m_input_names; }
|
||||
|
||||
const std::vector<std::string> & get_output_names() const { return m_output_names; }
|
||||
@@ -172,7 +166,6 @@ private:
|
||||
std::shared_ptr<GgmlDecoder> m_decoder;
|
||||
std::shared_ptr<TensorMap> & m_tensor_map;
|
||||
int m_node_idx;
|
||||
TranslateSession * m_translate_session;
|
||||
std::vector<std::string> m_input_names;
|
||||
std::vector<std::string> m_output_names;
|
||||
};
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
#include "../node_context.h"
|
||||
#include "../op_table.h"
|
||||
#include "../utils.h"
|
||||
#include "ggml.h"
|
||||
#include "ggml-openvino/ggml-openvino-extra.h"
|
||||
#include "ggml.h"
|
||||
|
||||
#include <climits>
|
||||
#include <cstdint>
|
||||
#include <openvino/frontend/exception.hpp>
|
||||
#include <openvino/op/add.hpp>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
#include "../node_context.h"
|
||||
#include "../op_table.h"
|
||||
#include "../utils.h"
|
||||
|
||||
#include <climits>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <memory>
|
||||
#include <numeric>
|
||||
#include <openvino/frontend/exception.hpp>
|
||||
@@ -126,9 +126,13 @@ OutputVector translate_cpy(const NodeContext & context) {
|
||||
auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
|
||||
auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {3});
|
||||
|
||||
auto head_part = std::make_shared<ov::op::v8::Slice>(base, zero, begin, one, axis);
|
||||
auto tail_part = std::make_shared<ov::op::v8::Slice>(base, end, int_max, one, axis);
|
||||
auto res = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{head_part, src, tail_part}, 3);
|
||||
// The view offset is relative to the whole base buffer, so splice on the flattened base.
|
||||
auto flat_base = std::make_shared<ov::op::v1::Reshape>(base, flat_shape, false);
|
||||
auto head_part = std::make_shared<ov::op::v8::Slice>(flat_base, zero, begin, one, axis);
|
||||
auto tail_part = std::make_shared<ov::op::v8::Slice>(flat_base, end, int_max, one, axis);
|
||||
auto spliced = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{head_part, src, tail_part}, 3);
|
||||
auto res = std::make_shared<ov::op::v1::Reshape>(
|
||||
spliced, std::make_shared<ov::op::v3::ShapeOf>(base, ov::element::i64), false);
|
||||
return rename_outputs_with_suffix({res}, context.get_name());
|
||||
}
|
||||
|
||||
@@ -221,6 +225,8 @@ OutputVector translate_cpy(const NodeContext & context) {
|
||||
"CPY conv state cache update requires static source feature view");
|
||||
|
||||
const int64_t full_feature_size = base_shape[3].get_length();
|
||||
FRONT_END_OP_CONVERSION_CHECK(full_feature_size > 0,
|
||||
"CPY conv state cache update requires a non-empty base cache feature size");
|
||||
const int64_t update_feature_size = input_shape[2].get_length() * input_shape[3].get_length();
|
||||
const auto output_stride = context.get_output_stride();
|
||||
const size_t elem_size = output_stride.empty() ? context.get_output_type().size() : output_stride.back();
|
||||
|
||||
@@ -139,7 +139,6 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
|
||||
|
||||
float * params = reinterpret_cast<float *>(context.get_output_op_params());
|
||||
float scale = params[0];
|
||||
// float max_bias = params[1];
|
||||
const float logit_softcap = params[2];
|
||||
|
||||
auto q = std::make_shared<ov::op::v0::Convert>(q_f32, ov::element::f16);
|
||||
@@ -168,9 +167,6 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
|
||||
false);
|
||||
}
|
||||
|
||||
//auto tile_kv = [&](int64_t num_heads, int64_t num_heads_kv, int64_t head_size, ov::Output<Node> kv) {
|
||||
// int64_t factor = num_heads / num_heads_kv;
|
||||
// if (factor > 1 && num_heads_kv > 1) {
|
||||
auto q_shape = context.get_input_shape(0).to_shape();
|
||||
auto k_shape = context.get_input_shape(1).to_shape();
|
||||
auto v_shape = context.get_input_shape(2).to_shape();
|
||||
@@ -279,9 +275,6 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
|
||||
new_kv_shape = ov::op::v0::Constant::create(
|
||||
ov::element::i64, {4},
|
||||
transposed ? std::vector<int64_t>{0, n_heads, hs, -1} : std::vector<int64_t>{0, n_heads, -1, hs});
|
||||
// ov::element::i64, {5}, {(int64_t) 1, (int64_t) 1, factor, (int64_t) 1, (int64_t) 1});
|
||||
//new_kv_shape =
|
||||
// ov::op::v0::Constant::create(ov::element::i64, {4}, {(int64_t) 0, num_heads, (int64_t) -1, head_size});
|
||||
|
||||
kv = std::make_shared<ov::op::v3::Broadcast>(kv_unsqueezed, kv_broadcast_shape,
|
||||
ov::op::BroadcastType::BIDIRECTIONAL);
|
||||
@@ -294,9 +287,9 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
|
||||
const bool v_transposed = ggml_openvino_npu_kv_head_major_enabled() && context.is_static() &&
|
||||
context.get_input_names()[2].find("cache_v_l") != std::string::npos;
|
||||
|
||||
// the HFA prefill path has no sinks
|
||||
const bool use_hfa_gate =
|
||||
ggml_openvino_npu_hfa_prefill_enabled() && context.is_static() && context.is_prefill() && has_mask && !has_sink;
|
||||
// the HFA prefill path has no sinks, and attends the rows of a whole chunk (not those of gemma-4's KV-shared layers)
|
||||
const bool use_hfa_gate = ggml_openvino_npu_hfa_prefill_enabled() && context.is_static() && context.is_prefill() &&
|
||||
has_mask && !has_sink && !is_pruned_mask_name(context.get_input_names()[3]);
|
||||
if (use_hfa_gate) {
|
||||
const int layer = extract_layer(context.get_input_names()[1]);
|
||||
auto past_k = context.get_input("ggml_hfa_past_cache_k_l" + std::to_string(layer));
|
||||
@@ -350,10 +343,6 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
|
||||
return rename_outputs_with_suffix({res}, context.get_name());
|
||||
}
|
||||
|
||||
//auto q_shape = context.get_input_shape(0).to_shape();
|
||||
//auto k_shape = context.get_input_shape(1).to_shape();
|
||||
//k = tile_kv(q_shape[1], k_shape[1], q_shape[3], k);
|
||||
//v = tile_kv(q_shape[1], k_shape[1], q_shape[3], v);
|
||||
k = tile_kv(num_heads, num_heads_kv, head_size, k);
|
||||
v = tile_kv(num_heads, num_heads_kv, head_size, v, v_transposed);
|
||||
|
||||
|
||||
@@ -514,10 +514,6 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
|
||||
g = std::make_shared<ov::op::v1::Multiply>(g, mask);
|
||||
}
|
||||
|
||||
// std::cout << "GatedDeltaNet input shapes: q=" << q.get_partial_shape() << ", k=" << k.get_partial_shape()
|
||||
// << ", v=" << v.get_partial_shape() << ", g=" << g.get_partial_shape()
|
||||
// << ", beta=" << beta.get_partial_shape() << ", state=" << state.get_partial_shape() << std::endl;
|
||||
|
||||
#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
|
||||
if (cache_inputs) {
|
||||
OutputVector args{q, k, v, (*cache_inputs)[0], g, beta};
|
||||
|
||||
@@ -24,6 +24,13 @@ namespace op {
|
||||
OutputVector translate_get_rows(const NodeContext & context) {
|
||||
num_inputs_check(context, 2, 2);
|
||||
|
||||
// Rows gathered on the host (GGML_OPENVINO_NPU_HOST_GATHER) arrive as a [1, 1, n_tokens, row] input.
|
||||
const std::string host_rows = "ggml_host_rows_" + context.get_name();
|
||||
if (context.has_input(host_rows)) {
|
||||
// Not renamed: the output is the Parameter itself, whose name binds the input at runtime.
|
||||
return {context.get_input(host_rows)};
|
||||
}
|
||||
|
||||
Output<Node> res;
|
||||
Output<Node> data;
|
||||
int64_t row_offset = 0;
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
#include "../op_table.h"
|
||||
#include "../utils.h"
|
||||
|
||||
#include <climits>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <openvino/core/node.hpp>
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
#include "../utils.h"
|
||||
#include "ggml-openvino/ggml-openvino-extra.h"
|
||||
|
||||
#include <climits>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <openvino/core/node.hpp>
|
||||
@@ -113,10 +112,6 @@ OutputVector translate_permute(const NodeContext & context) {
|
||||
auto new_shape =
|
||||
std::make_shared<ov::op::v0::Concat>(ov::OutputVector{n_seq_active, neg_one, n_heads, head_size}, 0);
|
||||
|
||||
// // Alternative
|
||||
// auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});
|
||||
// auto new_shape = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{n_seq_active, neg_one, zero, zero}, 0);
|
||||
|
||||
auto reshaped = std::make_shared<ov::op::v1::Reshape>(src, new_shape, true);
|
||||
res = std::make_shared<ov::op::v1::Transpose>(reshaped, perm);
|
||||
} else if ((op_case == 3 || op_case == 4) && is_kvcache_4d_shape(src.get_partial_shape())) {
|
||||
|
||||
@@ -49,34 +49,29 @@ OutputVector translate_rope(const NodeContext & context) {
|
||||
|
||||
Output<Node> cos_theta_node;
|
||||
Output<Node> sin_theta_node;
|
||||
if (context.has_input("rope_cos")) {
|
||||
cos_theta_node = context.get_input("rope_cos");
|
||||
sin_theta_node = context.get_input("rope_sin");
|
||||
std::string cache_key = "rope_sin_cos";
|
||||
for (int i = 0; i < 15; i++) {
|
||||
cache_key += "_" + std::to_string(op_params[i]);
|
||||
}
|
||||
if (context.get_input_size() == 3) {
|
||||
cache_key += "_ff_" + context.get_input_names()[2];
|
||||
}
|
||||
// Not every ROPE takes inp_pos: gemma-4 rotates its KV-shared layers at the positions of the output rows only
|
||||
cache_key += "_pos_" + context.get_input_names()[1];
|
||||
if (context.has_input(cache_key + "_cos")) {
|
||||
cos_theta_node = context.get_input(cache_key + "_cos");
|
||||
sin_theta_node = context.get_input(cache_key + "_sin");
|
||||
} else {
|
||||
std::string cache_key = "rope_sin_cos";
|
||||
for (int i = 0; i < 15; i++) {
|
||||
cache_key += "_" + std::to_string(op_params[i]);
|
||||
}
|
||||
auto inp_pos = context.get_input(1).get_node_shared_ptr();
|
||||
std::shared_ptr<ov::Node> rope_freqs_weight;
|
||||
if (context.get_input_size() == 3) {
|
||||
cache_key += "_ff_" + context.get_input_names()[2];
|
||||
}
|
||||
// Not every ROPE takes inp_pos: gemma-4 rotates its KV-shared layers at the positions of the output rows only
|
||||
cache_key += "_pos_" + context.get_input_names()[1];
|
||||
if (context.has_input(cache_key + "_cos")) {
|
||||
cos_theta_node = context.get_input(cache_key + "_cos");
|
||||
sin_theta_node = context.get_input(cache_key + "_sin");
|
||||
} else {
|
||||
auto inp_pos = context.get_input(1).get_node_shared_ptr();
|
||||
std::shared_ptr<ov::Node> rope_freqs_weight;
|
||||
if (context.get_input_size() == 3) {
|
||||
rope_freqs_weight = context.get_input(2).get_node_shared_ptr();
|
||||
}
|
||||
auto sin_cos = make_sin_cos(op_params, inp_pos, rope_freqs_weight, mode, false, head_dim);
|
||||
sin_theta_node = sin_cos.first;
|
||||
cos_theta_node = sin_cos.second;
|
||||
context.put_shared(cache_key + "_cos", cos_theta_node);
|
||||
context.put_shared(cache_key + "_sin", sin_theta_node);
|
||||
rope_freqs_weight = context.get_input(2).get_node_shared_ptr();
|
||||
}
|
||||
auto sin_cos = make_sin_cos(op_params, inp_pos, rope_freqs_weight, mode, false, head_dim);
|
||||
sin_theta_node = sin_cos.first;
|
||||
cos_theta_node = sin_cos.second;
|
||||
context.put_shared(cache_key + "_cos", cos_theta_node);
|
||||
context.put_shared(cache_key + "_sin", sin_theta_node);
|
||||
}
|
||||
|
||||
auto output_type = context.get_output_type();
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
#include "../utils.h"
|
||||
#include "ggml-openvino/ggml-openvino-extra.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <numeric>
|
||||
|
||||
@@ -5,9 +5,7 @@
|
||||
#include <openvino/op/constant.hpp>
|
||||
#include <openvino/op/group_conv.hpp>
|
||||
#include <openvino/op/reshape.hpp>
|
||||
#include <openvino/op/squeeze.hpp>
|
||||
#include <openvino/op/transpose.hpp>
|
||||
#include <openvino/op/unsqueeze.hpp>
|
||||
|
||||
namespace ov {
|
||||
namespace frontend {
|
||||
@@ -23,34 +21,32 @@ OutputVector translate_ssm_conv(const NodeContext & context) {
|
||||
auto sx_shape = context.get_input_shape(0).to_shape(); // [1, n_s, d_inner, ncs]
|
||||
auto c_shape = context.get_input_shape(1).to_shape(); // [1, 1, d_inner, d_conv]
|
||||
|
||||
// int64_t n_s = sx_shape[1];
|
||||
int64_t d_inner = sx_shape[2];
|
||||
// int64_t ncs = sx_shape[3]; // d_conv - 1 + n_t
|
||||
int64_t d_conv = c_shape[3];
|
||||
// int64_t n_t = ncs - d_conv + 1;
|
||||
int64_t d_conv = c_shape[3];
|
||||
|
||||
// Reshape sx from [1, n_s, d_inner, ncs] to [n_s, d_inner, ncs] for 1D GroupConvolution
|
||||
auto sx_reshaped =
|
||||
std::make_shared<ov::op::v0::Squeeze>(sx, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
|
||||
// The depthwise conv is expressed as a 2D GroupConvolution with a unit H dim: the GPU plugin
|
||||
// (OV 2026.4, ACCURACY mode) fails to compile the 1D form ("Weights/ifm mismatch") when its
|
||||
// input comes from RMSNorm -> Transpose -> Concat.
|
||||
// Transpose sx from [1, n_s, d_inner, ncs] to [n_s, d_inner, 1, ncs]
|
||||
auto sx_perm = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 2, 0, 3});
|
||||
auto sx_reshaped = std::make_shared<ov::op::v1::Transpose>(sx, sx_perm);
|
||||
|
||||
// Reshape c from [1, 1, d_inner, d_conv] to [d_inner, 1, 1, d_conv]
|
||||
// GroupConvolution filter: [groups, out_channels/groups, in_channels/groups, kernel_size]
|
||||
auto c_new_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{d_inner, 1, 1, d_conv});
|
||||
// Reshape c from [1, 1, d_inner, d_conv] to [d_inner, 1, 1, 1, d_conv]
|
||||
// GroupConvolution filter: [groups, out_channels/groups, in_channels/groups, kH, kW]
|
||||
auto c_new_shape =
|
||||
ov::op::v0::Constant::create(ov::element::i64, {5}, std::vector<int64_t>{d_inner, 1, 1, 1, d_conv});
|
||||
auto c_reshaped = std::make_shared<ov::op::v1::Reshape>(c, c_new_shape, false);
|
||||
|
||||
// Depthwise 1D convolution: groups=d_inner, stride=1, no padding, no dilation
|
||||
// Input: [n_s, d_inner, ncs], Filter: [d_inner, 1, 1, d_conv]
|
||||
// Output: [n_s, d_inner, n_t]
|
||||
auto conv = std::make_shared<ov::op::v1::GroupConvolution>(
|
||||
sx_reshaped, c_reshaped, ov::Strides{1}, ov::CoordinateDiff{0}, ov::CoordinateDiff{0}, ov::Strides{1});
|
||||
// Depthwise convolution: groups=d_inner, stride=1, no padding, no dilation
|
||||
// Input: [n_s, d_inner, 1, ncs], Filter: [d_inner, 1, 1, 1, d_conv]
|
||||
// Output: [n_s, d_inner, 1, n_t]
|
||||
auto conv = std::make_shared<ov::op::v1::GroupConvolution>(sx_reshaped, c_reshaped, ov::Strides{1, 1},
|
||||
ov::CoordinateDiff{0, 0}, ov::CoordinateDiff{0, 0},
|
||||
ov::Strides{1, 1});
|
||||
|
||||
// Transpose from [n_s, d_inner, n_t] to [n_s, n_t, d_inner]
|
||||
auto perm = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{0, 2, 1});
|
||||
auto transposed = std::make_shared<ov::op::v1::Transpose>(conv, perm);
|
||||
|
||||
// Reshape to output shape [1, n_s, n_t, d_inner]
|
||||
auto res =
|
||||
std::make_shared<ov::op::v0::Unsqueeze>(transposed, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
|
||||
// Transpose from [n_s, d_inner, 1, n_t] to output shape [1, n_s, n_t, d_inner]
|
||||
auto perm = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{2, 0, 3, 1});
|
||||
auto res = std::make_shared<ov::op::v1::Transpose>(conv, perm);
|
||||
|
||||
return rename_outputs_with_suffix({res}, context.get_name());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
#include "keep_cache_results.h"
|
||||
|
||||
#include <openvino/core/model.hpp>
|
||||
#include <openvino/op/parameter.hpp>
|
||||
#include <openvino/op/result.hpp>
|
||||
|
||||
#include <unordered_set>
|
||||
|
||||
namespace ov {
|
||||
namespace frontend {
|
||||
namespace ggml {
|
||||
namespace pass {
|
||||
|
||||
bool KeepCacheResults::run_on_model(const std::shared_ptr<ov::Model> & model) {
|
||||
bool changed = false;
|
||||
// Copies: remove_result()/remove_parameter() modify the vectors these accessors return.
|
||||
const ov::ResultVector results = model->get_results();
|
||||
for (const auto & result : results) {
|
||||
if (m_cache_outputs.count(result->get_friendly_name()) == 0) {
|
||||
model->remove_result(result);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (!changed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Removed Results leave their producers unreachable, but those nodes still hold their inputs, so a Parameter
|
||||
// is unused when none of its consumers is still part of the model.
|
||||
std::unordered_set<const ov::Node *> live;
|
||||
for (const auto & op : model->get_ordered_ops()) {
|
||||
live.insert(op.get());
|
||||
}
|
||||
const ov::ParameterVector params = model->get_parameters();
|
||||
for (const auto & param : params) {
|
||||
bool used = false;
|
||||
for (const auto & input : param->output(0).get_target_inputs()) {
|
||||
if (live.count(input.get_node()) != 0) {
|
||||
used = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!used) {
|
||||
model->remove_parameter(param);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace pass
|
||||
} // namespace ggml
|
||||
} // namespace frontend
|
||||
} // namespace ov
|
||||
@@ -0,0 +1,30 @@
|
||||
#include "openvino/pass/pass.hpp"
|
||||
|
||||
#include <set>
|
||||
#include <string>
|
||||
|
||||
namespace ov {
|
||||
namespace frontend {
|
||||
namespace ggml {
|
||||
namespace pass {
|
||||
|
||||
// Keeps only the Results named in |cache_outputs| (the KV / recurrent cache writes) and drops every other Result,
|
||||
// so that everything that only feeds them -- for models whose tail layers read an earlier layer's KV (Gemma 3n/4
|
||||
// E-series) the KV-shared layers and the LM head -- leaves the model. Parameters that nothing reads afterwards are
|
||||
// removed too. Used for KV-only prefill on the static path (GGML_OPENVINO_KV_ONLY_PREFILL); the outputs of the
|
||||
// batch then come from one step of the decode model.
|
||||
class KeepCacheResults : public ov::pass::ModelPass {
|
||||
public:
|
||||
OPENVINO_MODEL_PASS_RTTI("ov::frontend::ggml::pass::KeepCacheResults")
|
||||
explicit KeepCacheResults(std::set<std::string> cache_outputs) : m_cache_outputs(std::move(cache_outputs)) {}
|
||||
|
||||
bool run_on_model(const std::shared_ptr<ov::Model> & model) override;
|
||||
|
||||
private:
|
||||
std::set<std::string> m_cache_outputs;
|
||||
};
|
||||
|
||||
} // namespace pass
|
||||
} // namespace ggml
|
||||
} // namespace frontend
|
||||
} // namespace ov
|
||||
@@ -1,6 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
#include "mark_decompression_convert_constant_folding.h"
|
||||
#include "openvino/core/visibility.hpp"
|
||||
#include "openvino/pass/matcher_pass.hpp"
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "ggml-openvino/openvino/decoder.h"
|
||||
#include "ggml-openvino/openvino/pass/fuse_argsort_topk.h"
|
||||
#include "ggml-openvino/openvino/pass/fuse_to_conv.h"
|
||||
#include "ggml-openvino/openvino/pass/keep_cache_results.h"
|
||||
#include "ggml-openvino/openvino/pass/kv_state_seq_axis.h"
|
||||
#include "ggml-openvino/openvino/pass/mark_decompression_convert_constant_folding.h"
|
||||
#include "ggml-openvino/openvino/pass/mark_dequantization_subgraph.h"
|
||||
@@ -21,11 +22,18 @@ GraphTraits analyze_graph(const GgmlDecoder & decoder) {
|
||||
traits.device = ggml_openvino_is_npu() ? Device::NPU : ggml_openvino_is_gpu() ? Device::GPU : Device::CPU;
|
||||
traits.is_static = decoder.is_static();
|
||||
traits.is_stateful = decoder.is_stateful();
|
||||
traits.kv_only_outputs = decoder.is_kv_only_outputs();
|
||||
if (traits.kv_only_outputs) {
|
||||
traits.cache_output_names = decoder.get_cache_output_names();
|
||||
}
|
||||
return traits;
|
||||
}
|
||||
|
||||
void register_common_passes(ov::pass::Manager & manager, const GraphTraits & traits) {
|
||||
(void) traits;
|
||||
// First, so the other passes do not work on the layers it removes.
|
||||
if (traits.kv_only_outputs) {
|
||||
manager.register_pass<pass::KeepCacheResults>(traits.cache_output_names);
|
||||
}
|
||||
manager.register_pass<ov::pass::MarkCompressedFloatConstants>();
|
||||
// Marks the Convert/Subtract/Multiply nodes of our GatherMatmul dequantization chain
|
||||
// (make_int4_weights/make_int8_weights, for_gather_matmul=true) with disable_constant_folding,
|
||||
|
||||
@@ -16,6 +16,9 @@
|
||||
#include <openvino/pass/make_stateful.hpp>
|
||||
#include <openvino/pass/manager.hpp>
|
||||
|
||||
#include <set>
|
||||
#include <string>
|
||||
|
||||
namespace ov {
|
||||
namespace frontend {
|
||||
namespace ggml {
|
||||
@@ -31,6 +34,8 @@ struct GraphTraits {
|
||||
Device device = Device::CPU;
|
||||
bool is_static = false; // static shapes (NPU, or GGML_OPENVINO_FORCE_STATIC)
|
||||
bool is_stateful = false; // KV cache kept inside the model (GGML_OPENVINO_STATEFUL_EXECUTION)
|
||||
bool kv_only_outputs = false; // static KV-only prefill: keep only the cache outputs (GGML_OPENVINO_KV_ONLY_PREFILL)
|
||||
std::set<std::string> cache_output_names;
|
||||
};
|
||||
|
||||
GraphTraits analyze_graph(const GgmlDecoder & decoder);
|
||||
|
||||
@@ -3,10 +3,8 @@
|
||||
|
||||
# include "../ggml-openvino-extra.h"
|
||||
# include "ggml-impl.h"
|
||||
# include "op/recurrent_cache_update.hpp"
|
||||
# include "op_table.h"
|
||||
# ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
|
||||
# include "op/recurrent_cache_update.hpp"
|
||||
# endif
|
||||
# include "utils.h"
|
||||
|
||||
# include <openvino/op/concat.hpp>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user