mirror of
https://github.com/ggml-org/llama.cpp.git
synced 2026-11-28 05:37:43 -06:00
Compare commits
187
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 | ||
|
|
09c1410642 | ||
|
|
28148b5f06 | ||
|
|
51ab45e3c5 | ||
|
|
caea914e9d | ||
|
|
e38ea719bd | ||
|
|
074f1f3f73 | ||
|
|
1715275226 | ||
|
|
2a59da5bf2 | ||
|
|
07ba74babd | ||
|
|
267dda8180 | ||
|
|
e0f884d405 | ||
|
|
f8b7ed5250 | ||
|
|
55b2238be8 | ||
|
|
a8ad690ca9 | ||
|
|
aee03fbe80 | ||
|
|
9c003a97ab | ||
|
|
7135e2fd69 | ||
|
|
5917b39ff7 | ||
|
|
8d35ba4f7b | ||
|
|
acb269e511 | ||
|
|
d9dae03443 | ||
|
|
eb56575095 | ||
|
|
5a09582d80 | ||
|
|
2d5b3ddde3 | ||
|
|
94a1e4b722 | ||
|
|
c943331339 | ||
|
|
244640b7f2 | ||
|
|
679d8677b2 | ||
|
|
beb9d49339 | ||
|
|
532d67426b | ||
|
|
5e4fda8ed0 | ||
|
|
a28feb4589 | ||
|
|
3125043613 | ||
|
|
98f870c220 | ||
|
|
2e2f5a0373 | ||
|
|
41c7a1b49d | ||
|
|
77026f6e61 | ||
|
|
c8eda101c1 | ||
|
|
996de35a9c | ||
|
|
ab16df399f | ||
|
|
0cac1220e3 | ||
|
|
1ed4e77f4d | ||
|
|
48ac736960 | ||
|
|
5220a2d404 | ||
|
|
0fc7e1716f | ||
|
|
6d5f648721 | ||
|
|
52f6e0247a | ||
|
|
de30697285 | ||
|
|
62d6c8cb3a | ||
|
|
5bd90fa0e4 | ||
|
|
522d6fdd44 | ||
|
|
61d456a232 | ||
|
|
ea72294814 | ||
|
|
36d818e161 | ||
|
|
81ff0cab06 | ||
|
|
cddaa915a4 | ||
|
|
e8906e6b0c | ||
|
|
abca692003 | ||
|
|
e6443bd7eb | ||
|
|
79c69f4b06 | ||
|
|
33aeb17f85 | ||
|
|
22b99122e1 | ||
|
|
dfdfca22bc | ||
|
|
a1cee51c9d | ||
|
|
bb692efaa4 | ||
|
|
dbaf582af4 | ||
|
|
0ce7f213b0 | ||
|
|
96eb41bc48 | ||
|
|
23f0c0182f | ||
|
|
f20c5907c0 | ||
|
|
8bf2eae708 | ||
|
|
5fddd0b998 | ||
|
|
66a3b01b0a | ||
|
|
d3c257a493 | ||
|
|
3090e45a86 | ||
|
|
ba8521a44e | ||
|
|
72cda4a222 | ||
|
|
922cff91e9 | ||
|
|
2e779d5e70 | ||
|
|
396ed2ccea | ||
|
|
97bbf98fdf | ||
|
|
40fe9164f4 | ||
|
|
26f5048d5c | ||
|
|
9578bd3fe4 | ||
|
|
e683365a74 | ||
|
|
4c92c5bfb7 | ||
|
|
2a487782f2 | ||
|
|
6fb428332e | ||
|
|
6ac648d7a9 | ||
|
|
94165b288d | ||
|
|
a8ed778914 | ||
|
|
6970118ef1 | ||
|
|
ae6a7ad2c5 | ||
|
|
5fe4906859 | ||
|
|
82dd970474 | ||
|
|
a6ac41c757 | ||
|
|
3fccd98e9d | ||
|
|
4af4bb6d8a | ||
|
|
b12f22d2f2 | ||
|
|
d141011c25 | ||
|
|
12d47ba2f4 | ||
|
|
af5c58347f | ||
|
|
c74c71a6f7 | ||
|
|
38b9cad71d | ||
|
|
d35dc4d9e6 | ||
|
|
c212d25ad3 | ||
|
|
fd24ee26ad | ||
|
|
8355b88625 | ||
|
|
51831d47d0 | ||
|
|
ab789a246c | ||
|
|
239242322d | ||
|
|
30ec35ae2e | ||
|
|
87f816e87f | ||
|
|
1d3aad2fd8 | ||
|
|
325914defd | ||
|
|
1094646c1f | ||
|
|
27d0a1fc73 | ||
|
|
b6d5ce4bc9 | ||
|
|
1f3ea67fbf | ||
|
|
a0677c341b | ||
|
|
2359d27a36 | ||
|
|
51fc2f90e2 | ||
|
|
03813c56e4 | ||
|
|
46f4da2174 | ||
|
|
4663f9ca8a | ||
|
|
969d733317 | ||
|
|
a8f8294c45 | ||
|
|
7d9b931df9 | ||
|
|
212c547fe9 | ||
|
|
f5e6915c28 | ||
|
|
dd53f70d08 | ||
|
|
1f8baae28d | ||
|
|
44d50873b5 | ||
|
|
7778de0c3f | ||
|
|
f4f6f2e7db | ||
|
|
253671d882 | ||
|
|
94f3af3d09 | ||
|
|
f505c30b92 | ||
|
|
5bacb7c868 | ||
|
|
d2bceda3de |
@@ -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,10 +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 and Llama Voice 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,10 +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 and Llama Voice 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,10 +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 and Llama Voice 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,10 +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 and Llama Voice 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,10 +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 and Llama Voice 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
|
||||
|
||||
+3
-15
@@ -13,7 +13,6 @@
|
||||
blas,
|
||||
cudaPackages,
|
||||
autoAddDriverRunpath,
|
||||
darwin,
|
||||
rocmPackages,
|
||||
vulkan-headers,
|
||||
vulkan-loader,
|
||||
@@ -104,19 +103,9 @@ let
|
||||
ln -s /usr/bin/xcrun $out/bin
|
||||
'';
|
||||
|
||||
# apple_sdk is supposed to choose sane defaults, no need to handle isAarch64
|
||||
# separately
|
||||
darwinBuildInputs =
|
||||
with darwin.apple_sdk.frameworks;
|
||||
[
|
||||
Accelerate
|
||||
CoreVideo
|
||||
CoreGraphics
|
||||
]
|
||||
++ optionals useMetalKit [ MetalKit ];
|
||||
|
||||
cudaBuildInputs = with cudaPackages; [
|
||||
cuda_cudart
|
||||
cuda_nvml_dev
|
||||
cccl # <nv/target>
|
||||
libcublas
|
||||
];
|
||||
@@ -182,7 +171,7 @@ effectiveStdenv.mkDerivation (finalAttrs: {
|
||||
webui = stdenvNoCC.mkDerivation {
|
||||
pname = "webui";
|
||||
version = llamaVersion;
|
||||
# the app compiles Llama UI from its source in ../../lib/ui, so the source is ui/ as a whole
|
||||
# the app compiles Llama UI and the harness from their sources in ../../lib, so the source is ui/ as a whole
|
||||
src = lib.cleanSource ../../ui;
|
||||
sourceRoot = "source/apps/chat";
|
||||
|
||||
@@ -243,8 +232,7 @@ effectiveStdenv.mkDerivation (finalAttrs: {
|
||||
++ optionals syclAot [ oclocAot ];
|
||||
|
||||
buildInputs =
|
||||
optionals effectiveStdenv.hostPlatform.isDarwin darwinBuildInputs
|
||||
++ optionals useCuda cudaBuildInputs
|
||||
optionals useCuda cudaBuildInputs
|
||||
++ optionals useMpi [ mpi ]
|
||||
++ optionals useRocm rocmBuildInputs
|
||||
++ optionals useBlas [ blas ]
|
||||
|
||||
@@ -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,10 +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 and Llama Voice 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,10 +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 and Llama Voice 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,10 +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 and Llama Voice 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,10 +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 and Llama Voice 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
|
||||
|
||||
@@ -32,7 +32,8 @@ concurrency:
|
||||
|
||||
jobs:
|
||||
ubuntu-26-virtgpu:
|
||||
runs-on: ${{ 'ubuntu-26.04-arm' || 'ubuntu-26.04' }}
|
||||
runs-on: [self-hosted, Linux, gb10]
|
||||
container: "ubuntu:26.04"
|
||||
|
||||
steps:
|
||||
- name: Clone
|
||||
@@ -42,8 +43,23 @@ jobs:
|
||||
- name: Dependencies
|
||||
id: depends
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y build-essential libdrm-dev pkg-config libssl-dev
|
||||
apt update
|
||||
apt install -y build-essential jq cmake python3 python3-venv python3-pip libdrm-dev pkg-config libssl-dev
|
||||
|
||||
- name: ccache
|
||||
uses: ggml-org/ccache-action@v1.2.24
|
||||
with:
|
||||
restore: false
|
||||
save: false
|
||||
|
||||
- name: ccache-buckets-restore
|
||||
uses: ./.github/actions/ccache-buckets
|
||||
env:
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN_CI }}
|
||||
with:
|
||||
key: virtgpu-ubuntu-26.04-gb10
|
||||
folder: llama.cpp
|
||||
hf_bucket: ggml-org/cache
|
||||
|
||||
- name: Build
|
||||
id: cmake_build
|
||||
@@ -52,3 +68,15 @@ jobs:
|
||||
-DGGML_VIRTGPU=ON \
|
||||
-DGGML_VIRTGPU_BACKEND=ON
|
||||
cmake --build build --config Release -j $(nproc)
|
||||
|
||||
- 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: virtgpu-ubuntu-26.04-gb10
|
||||
folder: llama.cpp
|
||||
evict-old-files: 1d
|
||||
hf_bucket: ggml-org/cache
|
||||
save: true
|
||||
|
||||
@@ -41,8 +41,9 @@ env:
|
||||
LLAMA_ARG_LOG_TIMESTAMPS: 1
|
||||
|
||||
jobs:
|
||||
ubuntu-arm64:
|
||||
runs-on: ubuntu-26.04-arm
|
||||
ubuntu:
|
||||
runs-on: [self-hosted, Linux, gb10]
|
||||
container: "ubuntu:26.04"
|
||||
|
||||
steps:
|
||||
- name: Clone
|
||||
@@ -52,14 +53,13 @@ jobs:
|
||||
- name: Dependencies
|
||||
id: depends
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y build-essential glslc libvulkan-dev spirv-headers libssl-dev ninja-build
|
||||
apt update
|
||||
apt install -y build-essential jq cmake python3 python3-venv python3-pip glslc libvulkan-dev spirv-headers libssl-dev ninja-build
|
||||
|
||||
- name: ccache
|
||||
uses: ggml-org/ccache-action@v1.2.24
|
||||
with:
|
||||
restore: false
|
||||
variant: ccache
|
||||
save: false
|
||||
|
||||
- name: ccache-buckets-restore
|
||||
@@ -67,7 +67,7 @@ jobs:
|
||||
env:
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN_CI }}
|
||||
with:
|
||||
key: vulkan-ubuntu-26.04-arm
|
||||
key: vulkan-ubuntu-26.04-gb10
|
||||
folder: llama.cpp
|
||||
hf_bucket: ggml-org/cache
|
||||
|
||||
@@ -82,7 +82,7 @@ jobs:
|
||||
- name: Build
|
||||
id: cmake_build
|
||||
run: |
|
||||
time cmake --build build -j $(nproc)
|
||||
cmake --build build -j $(nproc)
|
||||
|
||||
- name: ccache-buckets-save
|
||||
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
|
||||
@@ -90,7 +90,7 @@ jobs:
|
||||
env:
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
|
||||
with:
|
||||
key: vulkan-ubuntu-26.04-arm
|
||||
key: vulkan-ubuntu-26.04-gb10
|
||||
folder: llama.cpp
|
||||
evict-old-files: 1d
|
||||
hf_bucket: ggml-org/cache
|
||||
@@ -167,7 +167,8 @@ jobs:
|
||||
export GGML_VK_VISIBLE_DEVICES=0
|
||||
export GGML_VK_DISABLE_F16=1
|
||||
export GGML_VK_DISABLE_COOPMAT=1
|
||||
ctest -L main --verbose --timeout 900
|
||||
# TODO: too slow on llvmpipe
|
||||
ctest -L main -E "test-llama-context" --verbose --timeout 900
|
||||
|
||||
windows:
|
||||
name: windows / ${{ matrix.arch }}
|
||||
|
||||
@@ -49,18 +49,18 @@ env:
|
||||
|
||||
jobs:
|
||||
ubuntu-webgpu:
|
||||
runs-on: ubuntu-26.04-arm
|
||||
runs-on: [self-hosted, Linux, gb10]
|
||||
container: "ubuntu:26.04"
|
||||
|
||||
steps:
|
||||
- name: Clone
|
||||
id: checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: ccache
|
||||
uses: ggml-org/ccache-action@v1.2.24
|
||||
with:
|
||||
restore: false
|
||||
save: false
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
apt update
|
||||
apt install -y build-essential cmake ninja-build git curl python3 python-is-python3
|
||||
|
||||
- name: Install wasi-sdk
|
||||
uses: bytecodealliance/setup-wasi-sdk-action@77d09f3df1e8da344d8403cf8631af8977938b4c # v1.0.0
|
||||
@@ -92,15 +92,6 @@ jobs:
|
||||
INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_LIST_DIR}/dawn-headers/include/webgpu_upstream;${_wasi_webgpu}")
|
||||
EOF
|
||||
|
||||
- name: ccache-buckets-restore
|
||||
uses: ./.github/actions/ccache-buckets
|
||||
env:
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN_CI }}
|
||||
with:
|
||||
key: webgpu-ubuntu-26.04-arm-wasi
|
||||
folder: llama.cpp
|
||||
hf_bucket: ggml-org/cache
|
||||
|
||||
# llama-common does not build for WASI, so the executables are linked by hand
|
||||
- name: Build
|
||||
id: cmake_build
|
||||
@@ -120,7 +111,7 @@ jobs:
|
||||
-DDawn_DIR=$PWD/wasi-webgpu \
|
||||
-DLLAMA_BUILD_COMMON=OFF
|
||||
|
||||
time cmake --build build-wasi --config Release --target llama -j $(nproc)
|
||||
cmake --build build-wasi --config Release --target llama -j $(nproc)
|
||||
|
||||
LIBS="build-wasi/ggml/src/libggml.a build-wasi/ggml/src/ggml-webgpu/libggml-webgpu.a build-wasi/ggml/src/libggml-cpu.a build-wasi/ggml/src/libggml-base.a"
|
||||
LDFLAGS="-lunwind -ldl -Wl,-z,stack-size=8388608"
|
||||
@@ -128,15 +119,3 @@ jobs:
|
||||
|
||||
$CXX examples/simple/simple.cpp build-wasi/src/libllama.a $LIBS $LDFLAGS -o build-wasi/llama-simple.wasm
|
||||
$CXX tests/test-backend-ops.cpp $LIBS $LDFLAGS -o build-wasi/test-backend-ops.wasm
|
||||
|
||||
- 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: webgpu-ubuntu-26.04-arm-wasi
|
||||
folder: llama.cpp
|
||||
evict-old-files: 1d
|
||||
hf_bucket: ggml-org/cache
|
||||
save: true
|
||||
|
||||
@@ -50,18 +50,18 @@ env:
|
||||
|
||||
jobs:
|
||||
ubuntu-webgpu:
|
||||
runs-on: ubuntu-26.04-arm
|
||||
runs-on: [self-hosted, Linux, gb10]
|
||||
container: "ubuntu:26.04"
|
||||
|
||||
steps:
|
||||
- name: Clone
|
||||
id: checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: ccache
|
||||
uses: ggml-org/ccache-action@v1.2.24
|
||||
with:
|
||||
restore: false
|
||||
save: false
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
apt update
|
||||
apt install -y build-essential cmake ninja-build git curl unzip python3
|
||||
|
||||
- name: Install Emscripten
|
||||
run: |
|
||||
@@ -79,16 +79,8 @@ jobs:
|
||||
"https://github.com/google/dawn/releases/download/${DAWN_TAG}/${EMDAWN_PKG}"
|
||||
unzip emdawn.zip
|
||||
|
||||
- name: ccache-buckets-restore
|
||||
uses: ./.github/actions/ccache-buckets
|
||||
env:
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN_CI }}
|
||||
with:
|
||||
key: webgpu-ubuntu-26.04-arm-wasm
|
||||
folder: llama.cpp
|
||||
hf_bucket: ggml-org/cache
|
||||
|
||||
- name: Build WASM WebGPU
|
||||
shell: bash
|
||||
run: |
|
||||
source emsdk/emsdk_env.sh
|
||||
emcmake cmake -B build-wasm \
|
||||
@@ -99,16 +91,4 @@ jobs:
|
||||
-DLLAMA_OPENSSL=OFF \
|
||||
-DEMDAWNWEBGPU_DIR=emdawnwebgpu_pkg
|
||||
|
||||
time cmake --build build-wasm --config Release --target test-backend-ops -j $(nproc)
|
||||
|
||||
- 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: webgpu-ubuntu-26.04-arm-wasm
|
||||
folder: llama.cpp
|
||||
evict-old-files: 1d
|
||||
hf_bucket: ggml-org/cache
|
||||
save: true
|
||||
cmake --build build-wasm --config Release --target test-backend-ops -j $(nproc)
|
||||
|
||||
@@ -49,7 +49,8 @@ env:
|
||||
|
||||
jobs:
|
||||
gpu-cuda:
|
||||
runs-on: "hf-jobs-t4-medium:cuda13"
|
||||
runs-on: [self-hosted, Linux, gb10]
|
||||
container: "nvidia/cuda:13.5.0-devel-ubuntu26.04"
|
||||
|
||||
steps:
|
||||
- name: Clone
|
||||
@@ -58,8 +59,8 @@ jobs:
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
sudo apt update
|
||||
sudo apt install -y cmake libssl-dev time unzip wget python3 python3-venv python3-pip
|
||||
apt update
|
||||
apt install -y build-essential jq cmake git git-lfs libssl-dev time unzip wget python3 python3-venv python3-pip
|
||||
|
||||
- name: ccache
|
||||
uses: ggml-org/ccache-action@v1.2.24
|
||||
@@ -70,7 +71,7 @@ jobs:
|
||||
- name: ccache-buckets-restore
|
||||
uses: ./.github/actions/ccache-buckets
|
||||
with:
|
||||
key: self-hosted-gpu-cuda
|
||||
key: self-hosted-gpu-cuda-gb10
|
||||
folder: llama.cpp
|
||||
hf_bucket: ggml-org/cache
|
||||
|
||||
@@ -78,7 +79,7 @@ jobs:
|
||||
id: ggml-ci
|
||||
run: |
|
||||
nvidia-smi
|
||||
GG_BUILD_CUDA=1 CUDACXX=/usr/local/cuda/bin/nvcc bash ./ci/run.sh ~/results/llama.cpp ~/mnt/llama.cpp
|
||||
GG_BUILD_CUDA=1 CUDACXX=/usr/local/cuda/bin/nvcc 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' }}
|
||||
@@ -86,7 +87,7 @@ jobs:
|
||||
env:
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
|
||||
with:
|
||||
key: self-hosted-gpu-cuda
|
||||
key: self-hosted-gpu-cuda-gb10
|
||||
folder: llama.cpp
|
||||
evict-old-files: 1d
|
||||
hf_bucket: ggml-org/cache
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -120,9 +120,6 @@ jobs:
|
||||
mv build-matrix.json.tmp build-matrix.json
|
||||
fi
|
||||
|
||||
jq 'map(select(.tag != "musa"))' build-matrix.json > build-matrix.json.tmp
|
||||
mv build-matrix.json.tmp build-matrix.json
|
||||
|
||||
BUILD_MATRIX="$(jq -c . build-matrix.json)"
|
||||
MERGE_MATRIX="$(jq -c '
|
||||
reduce .[] as $entry ({}; .[$entry.tag] |= (
|
||||
@@ -272,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 }}
|
||||
@@ -309,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 }}
|
||||
@@ -346,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"; } ||
|
||||
|
||||
@@ -1129,7 +1129,7 @@ jobs:
|
||||
target: 'ggml-vulkan'
|
||||
- backend: 'opencl-adreno'
|
||||
arch: 'arm64'
|
||||
defines: '-G "Ninja Multi-Config" -D CMAKE_TOOLCHAIN_FILE=cmake/arm64-windows-llvm.cmake -DCMAKE_PREFIX_PATH="$env:RUNNER_TEMP/opencl-arm64-release" -DGGML_OPENCL=ON -DGGML_OPENCL_USE_ADRENO_KERNELS=ON'
|
||||
defines: '-G "Ninja Multi-Config" -D CMAKE_TOOLCHAIN_FILE=cmake/arm64-windows-llvm.cmake -DCMAKE_PREFIX_PATH="$env:RUNNER_TEMP/opencl-arm64-release" -DGGML_OPENCL=ON -DGGML_OPENCL_USE_ADRENO_KERNELS=ON -DGGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=OFF'
|
||||
target: 'ggml-opencl'
|
||||
|
||||
steps:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -20,6 +20,8 @@ on:
|
||||
'ui/apps/chat/**.*',
|
||||
'ui/lib/ui/**.*',
|
||||
'ui/lib/voice/**.*',
|
||||
'ui/lib/harness/**.*',
|
||||
'ui/lib/huggingface/**.*',
|
||||
'tools/server/tests/**.*'
|
||||
]
|
||||
pull_request:
|
||||
@@ -30,6 +32,8 @@ on:
|
||||
'ui/apps/chat/**.*',
|
||||
'ui/lib/ui/**.*',
|
||||
'ui/lib/voice/**.*',
|
||||
'ui/lib/harness/**.*',
|
||||
'ui/lib/huggingface/**.*',
|
||||
'tools/server/tests/**.*'
|
||||
]
|
||||
|
||||
@@ -125,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: |
|
||||
|
||||
+163
-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
|
||||
|
||||
@@ -181,6 +189,157 @@ jobs:
|
||||
run: npm run prepack
|
||||
working-directory: ui/lib/voice
|
||||
|
||||
harness-checks:
|
||||
name: Harness checks
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24"
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
working-directory: ui/lib/harness
|
||||
|
||||
- name: Run type checking
|
||||
run: npm run check
|
||||
working-directory: ui/lib/harness
|
||||
|
||||
- name: Run tests
|
||||
run: npm test
|
||||
working-directory: ui/lib/harness
|
||||
|
||||
- name: Build the package
|
||||
run: npm run prepack
|
||||
working-directory: ui/lib/harness
|
||||
|
||||
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
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24"
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
working-directory: ui/apps/chat
|
||||
|
||||
- name: Build without the agentic loop
|
||||
run: npm run build
|
||||
working-directory: ui/apps/chat
|
||||
env:
|
||||
VITE_PUBLIC_AGENTIC: "false"
|
||||
|
||||
- name: Check the harness loop is not in the bundle
|
||||
run: |
|
||||
if grep -rlq "Tool execution was interrupted by a new user message" dist; then
|
||||
echo "The chat-only bundle contains Llama Harness's loop" && exit 1
|
||||
fi
|
||||
working-directory: ui/apps/chat
|
||||
|
||||
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
|
||||
@@ -223,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' }}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# date: Mon Nov 16 10:05:56 EET 2026
|
||||
# date: Wed Nov 25 16:07:40 EET 2026
|
||||
# this file is auto-generated by scripts/gen-authors.sh
|
||||
|
||||
Нияз Гарифзянов <112617865+garrnizon@users.noreply.github.com>
|
||||
@@ -90,6 +90,7 @@ Aidan <99101158+gSUz92nc@users.noreply.github.com>
|
||||
AidanBeltonS <87009434+AidanBeltonS@users.noreply.github.com>
|
||||
AidanBeltonS <aidan.belton@codeplay.com>
|
||||
aiqubits <aiqubits@hotmail.com>
|
||||
Aircg <64237451+cgair@users.noreply.github.com>
|
||||
Aisuko <urakiny@gmail.com>
|
||||
Akarshan Biswas <akarshan.biswas@gmail.com>
|
||||
Akarshan Biswas <akarshan@menlo.ai>
|
||||
@@ -256,6 +257,7 @@ Asghar Ghorbani <a-ghorbani@users.noreply.github.com>
|
||||
Ashish <1856117+ashishdatta@users.noreply.github.com>
|
||||
Ashok Gelal <401055+ashokgelal@users.noreply.github.com>
|
||||
Ashraful Islam <ashraful.meche@gmail.com>
|
||||
Ashutosh Singh <ashutosh.singh@intel.com>
|
||||
AT <manyoso@users.noreply.github.com>
|
||||
at8u <129688334+at8u@users.noreply.github.com>
|
||||
Atharva Dubey <atharva.dubey@codeplay.com>
|
||||
@@ -267,6 +269,7 @@ Austin <77757836+teleprint-me@users.noreply.github.com>
|
||||
AustinMroz <austinmroz@utexas.edu>
|
||||
AUTOMATIC1111 <16777216c@gmail.com>
|
||||
automaticcat <daogiatuank54@gmail.com>
|
||||
AWA <15575202581@163.com>
|
||||
awatuna <23447591+awatuna@users.noreply.github.com>
|
||||
Awss <gitj.18@alt.awss1i.com>
|
||||
b4b4o <zwbao@foxmail.com>
|
||||
@@ -277,6 +280,7 @@ Bailey Chittle <39804642+bachittle@users.noreply.github.com>
|
||||
Bálint Bokros <bbalint96@gmail.com>
|
||||
bandoti <141645996+bandoti@users.noreply.github.com>
|
||||
Bar Haim <barvhaim@gmail.com>
|
||||
Baran Bati <66915560+Batibaran@users.noreply.github.com>
|
||||
BarfingLemurs <128182951+BarfingLemurs@users.noreply.github.com>
|
||||
Bart Louwers <bart.louwers@gmail.com>
|
||||
Bartosz Taudul <wolf@nereid.pl>
|
||||
@@ -315,11 +319,13 @@ Bill Sideris <bill88t@feline.gr>
|
||||
Billel Mokeddem <billel.mokeddem.ml@gmail.com>
|
||||
Bingan <70050083+binganao@users.noreply.github.com>
|
||||
Bipin Yadav <83943505+bipinyadav3175@users.noreply.github.com>
|
||||
Birk Skyum <74932975+birkskyum@users.noreply.github.com>
|
||||
bitalov <60072763+bitalov@users.noreply.github.com>
|
||||
Bizhao Shi <37729561+shibizhao@users.noreply.github.com>
|
||||
Bjarke Viksøe <164612031+bviksoe@users.noreply.github.com>
|
||||
Björn Ganster <mail@bjoern-ganster.de>
|
||||
BlackFoil <127078112+BlackFoil@users.noreply.github.com>
|
||||
BlivionIaG <kev29lt@gmail.com>
|
||||
BlueMöhre <bluemoehre@gmx.de>
|
||||
bmwl <brian.marshall@tolko.com>
|
||||
Bo Zheng <368586905@qq.com>
|
||||
@@ -390,7 +396,11 @@ Chen Yuan <constantchen525@gmail.com>
|
||||
Cheng Shao <terrorjack@type.dance>
|
||||
Chenguang Li <757486878@qq.com>
|
||||
Chenguang Li <87689256+noemotiovon@users.noreply.github.com>
|
||||
Chenyang Li <cl4288@cumc.columbia.edu>
|
||||
cherry77-cloud <1615405@qq.com>
|
||||
chessMan <71754779+mohitmishra786@users.noreply.github.com>
|
||||
chiheb ben cheikh <100644963+ChihebBENCHEIKH1@users.noreply.github.com>
|
||||
Chinmay Shrivastava <cshrivastava2000@gmail.com>
|
||||
chinmaykamjith001 <chinmaykamjith@gmail.com>
|
||||
Chipmunk <101038159+CHIPMUNK-T0T@users.noreply.github.com>
|
||||
chiranko <96988916+chiranko@users.noreply.github.com>
|
||||
@@ -477,6 +487,7 @@ Daniel Varga <vargad88@gmail.com>
|
||||
Daniele <57776841+daniandtheweb@users.noreply.github.com>
|
||||
Daniele <daniele.dilotorres@gmail.com>
|
||||
Daniele Pinna <72076821+pestopoppa@users.noreply.github.com>
|
||||
Daniil Sterkhov <ngoroth@gmail.com>
|
||||
Danny Milosavljevic <dannym@friendly-machines.com>
|
||||
DannyDaemonic <DannyDaemonic@gmail.com>
|
||||
Dante <144588016+KafKafrnZ@users.noreply.github.com>
|
||||
@@ -581,6 +592,8 @@ Echo Nolan <echo@echonolan.net>
|
||||
Ed Addario <29247825+EAddario@users.noreply.github.com>
|
||||
Ed Lee <edilee@mozilla.com>
|
||||
Ed Lepedus <ed.lepedus@googlemail.com>
|
||||
Eddie Zhou <e.zhou@chocolat.chaud.io>
|
||||
Eddie Zhou <eddiezhou1996@gmail.com>
|
||||
Eddie-Wang <wangjinheng1120@163.com>
|
||||
eddiechen <Echen1246@gmail.com>
|
||||
Eden <aa9736195201@gmail.com>
|
||||
@@ -596,6 +609,7 @@ Emil Askerov <56842174+EmilAskerov@users.noreply.github.com>
|
||||
Emmanuel Ferdman <emmanuelferdman@gmail.com>
|
||||
Empressia <sphere.soffie@gmail.com>
|
||||
Emreerdog <34742675+Emreerdog@users.noreply.github.com>
|
||||
En Yao <68765784+JeremyCEY@users.noreply.github.com>
|
||||
Engininja2 <139037756+Engininja2@users.noreply.github.com>
|
||||
Equim <sayaka@ekyu.moe>
|
||||
Eric A Stalee <87948564+Eric-A-Stalee@users.noreply.github.com>
|
||||
@@ -706,6 +720,7 @@ Gavin Zhao <gavinzhaojw@protonmail.com>
|
||||
Genkagaku.GPT <hlhr202@163.com>
|
||||
Geo Maciolek <geoffmaciolek@gmail.com>
|
||||
George <35490284+noctrex@users.noreply.github.com>
|
||||
George Burton <8233643+gecBurton@users.noreply.github.com>
|
||||
Georgi Gerganov <ggerganov@gmail.com>
|
||||
Geramy Loveless <gloveless@jqluv.com>
|
||||
Gerard Guillemas Martos <gguillemas@users.noreply.github.com>
|
||||
@@ -714,11 +729,13 @@ Gerben van V <gerbenvv@gmail.com>
|
||||
Gezahegne <gezahegne.yirefu@gmail.com>
|
||||
ghleg <aoleg@users.noreply.github.com>
|
||||
Gian-Carlo Pascutto <gcp@sjeng.org>
|
||||
gianni-cor <gianfranco.cordella@tether.io>
|
||||
gianni-cor <gianfrancocordella@gmail.com>
|
||||
GiantPrince <90118823+GiantPrince@users.noreply.github.com>
|
||||
GideonSerf <gdserf.gs@gmail.com>
|
||||
Gilad S <giladgd@users.noreply.github.com>
|
||||
Gilad S. <7817232+giladgd@users.noreply.github.com>
|
||||
Giorgio Sarno <giorgio.srn@gmail.com>
|
||||
Giovanni Rivera <rivera.giovanni271@gmail.com>
|
||||
github-actions[bot] <github-actions[bot]@users.noreply.github.com>
|
||||
GittyBurstein <g0534163997@gmail.com>
|
||||
@@ -799,6 +816,7 @@ hey-gm <heitorgm@outlook.com>
|
||||
HighDoping <highdoping@gmail.com>
|
||||
HimariO <dsfhe49854@gmail.com>
|
||||
hipudding <huafengchun@gmail.com>
|
||||
Hiroyuki Ikegami <ikegam@mixallow.net>
|
||||
Hitesh Chopra <34310832+hiteshchopra11@users.noreply.github.com>
|
||||
hksdpc255 <43977088+hksdpc255@users.noreply.github.com>
|
||||
hmirin <hmirin@users.noreply.github.com>
|
||||
@@ -866,6 +884,7 @@ Ilia Ilmer <iliailmer@users.noreply.github.com>
|
||||
Ilya <ilya77105@gmail.com>
|
||||
Ilya Kurdyukov <59548320+ilyakurdyukov@users.noreply.github.com>
|
||||
Imad Saddik <79410781+ImadSaddik@users.noreply.github.com>
|
||||
Imdadullah Mohammed <7274724+imdadvs@users.noreply.github.com>
|
||||
iMil <imil@NetBSD.org>
|
||||
Incarnas <119618389+bit-incarnas@users.noreply.github.com>
|
||||
InflexCZE <martin.pavlicek11@gmail.com>
|
||||
@@ -904,6 +923,7 @@ Jaeden Amero <jaeden@patater.com>
|
||||
Jaemin Son <woalsdnd@gmail.com>
|
||||
Jafar Uruç <jafar.uruc@gmail.com>
|
||||
Jag Chadha <jagtesh@gmail.com>
|
||||
Jai Patel <61297975+jpatel2005@users.noreply.github.com>
|
||||
jaime-m-p <167997752+jaime-m-p@users.noreply.github.com>
|
||||
Jake Karnes <jake.karnes@gmail.com>
|
||||
Jakkala Mahesh <155058658+MaheshJakkala@users.noreply.github.com>
|
||||
@@ -912,6 +932,7 @@ JamePeng <jame_peng@sina.com>
|
||||
James A Capozzoli <157492257+jac-jim@users.noreply.github.com>
|
||||
James Francis <6763899+JamesFranc@users.noreply.github.com>
|
||||
James O'Leary <65884233+jpohhhh@users.noreply.github.com>
|
||||
James Prevett <jp@jamespre.dev>
|
||||
James Reynolds <magnusviri@users.noreply.github.com>
|
||||
jameswu2014 <545426914@qq.com>
|
||||
JamieBordoni <jamie.bordoni@protonmail.com>
|
||||
@@ -932,6 +953,7 @@ Jason Ni <jason.ni.py@gmail.com>
|
||||
Jason Stillerman <jason.t.stillerman@gmail.com>
|
||||
jason_w <jason.wang@126.com>
|
||||
Jassieluo <130133492+Jassieluo@users.noreply.github.com>
|
||||
Javier Argomedo <79397619+diabluz@users.noreply.github.com>
|
||||
Jay <BusyJay@users.noreply.github.com>
|
||||
Jay Zenith <162098309+JayZenith@users.noreply.github.com>
|
||||
Jayant Lohia <rajiblohia@gmail.com>
|
||||
@@ -1070,6 +1092,7 @@ Kaben Nanlohy <kaben.nanlohy@gmail.com>
|
||||
Kabir Potdar <kabirpotdar7@gmail.com>
|
||||
Kabir08 <62639358+Kabir08@users.noreply.github.com>
|
||||
Kai Pastor <dg0yt@darc.de>
|
||||
KaiFelixBennett <83428264+KaiFelixBennett@users.noreply.github.com>
|
||||
kaizau <kaizau@users.noreply.github.com>
|
||||
Kakaru <97896816+KakaruHayate@users.noreply.github.com>
|
||||
kallewoof <kalle.alm@gmail.com>
|
||||
@@ -1080,6 +1103,7 @@ Kamil Tomšík <info@tomsik.cz>
|
||||
kang <tpdns9032100@gmail.com>
|
||||
Kangjia Gao <145212963+kkkzbh@users.noreply.github.com>
|
||||
Kante Yin <kerthcet@gmail.com>
|
||||
karan <67942227+dheepakkaran@users.noreply.github.com>
|
||||
karavayev <192749314+karavayev@users.noreply.github.com>
|
||||
Karol Kontny <82021046+kkontny@users.noreply.github.com>
|
||||
Karsten Weiss <knweiss@gmail.com>
|
||||
@@ -1097,6 +1121,7 @@ Katara <sohaib.harraoui@ostorlab.dev>
|
||||
Katostrofik <georgiopapairo@gmail.com>
|
||||
katsu560 <118887472+katsu560@users.noreply.github.com>
|
||||
Kawrakow <48489457+ikawrakow@users.noreply.github.com>
|
||||
Kazutoshi, Akao <73567414+kazutoshi-ak@users.noreply.github.com>
|
||||
kbenkhaled <khalilbenkhaled01@gmail.com>
|
||||
kchro3 <62481661+kchro3@users.noreply.github.com>
|
||||
kdkd <2569413+kdkd@users.noreply.github.com>
|
||||
@@ -1129,6 +1154,7 @@ KnightYao <KnightYao@users.noreply.github.com>
|
||||
KokerZhou <111279477+KokerZhou@users.noreply.github.com>
|
||||
Kolen Cheung <ickc@users.noreply.github.com>
|
||||
Kong Jiale <2049447146@qq.com>
|
||||
Kong Jiale <jialekong2004@mails.ccnu.edu.cn>
|
||||
kononnable <kononnable@gmail.com>
|
||||
Konrad Moren <kmoren@nvidia.com>
|
||||
konradmb <konradmb@o2.pl>
|
||||
@@ -1182,6 +1208,7 @@ Leng Yue <lengyue@lengyue.me>
|
||||
Lennart Austenfeld <53152202+l-austenfeld@users.noreply.github.com>
|
||||
leo-pony <nengjunma@outlook.com>
|
||||
Leon <118652405+LeON-Nie-code@users.noreply.github.com>
|
||||
Leon <3077740163@qq.com>
|
||||
Leon Knauer <git@leonknauer.com>
|
||||
Leonard Mosescu <tlemo@users.noreply.github.com>
|
||||
leonardHONG <2695316095@qq.com>
|
||||
@@ -1217,6 +1244,7 @@ lon <114724657+longregen@users.noreply.github.com>
|
||||
loonerin <132926317+loonerin@users.noreply.github.com>
|
||||
Lorenzo Bona <lorenzobona@tuta.com>
|
||||
losewayy <1134285612@qq.com>
|
||||
losewayy <losemywayy@gmail.com>
|
||||
LostRuins <39025047+LostRuins@users.noreply.github.com>
|
||||
LostRuins Concedo <39025047+LostRuins@users.noreply.github.com>
|
||||
lovedheart <6277001+lovedheart@users.noreply.github.com>
|
||||
@@ -1256,6 +1284,7 @@ Mahdiou Diallo <104755555+mahdiou@users.noreply.github.com>
|
||||
Mahekk Shaikh <118063190+Mahekk357@users.noreply.github.com>
|
||||
Mahesh Madhav <67384846+heshpdx@users.noreply.github.com>
|
||||
mahorozte <41834471+mahorozte@users.noreply.github.com>
|
||||
mahounairo <24420747+mahounairo@users.noreply.github.com>
|
||||
makomk <makosoft@googlemail.com>
|
||||
manayang <jackmanayang@gmail.com>
|
||||
manikbhandari <mbbhandarimanik2@gmail.com>
|
||||
@@ -1272,6 +1301,7 @@ Marcos Del Sol Vives <marcos@orca.pet>
|
||||
marcoStocchi <marcostocchi77@gmail.com>
|
||||
Marcus <marcusds@users.noreply.github.com>
|
||||
Marcus Dunn <51931484+MarcusDunn@users.noreply.github.com>
|
||||
Marcus Tillmanns <maddimax@gmail.com>
|
||||
Marek Hradil jr. <marek.hradil@outlook.com>
|
||||
Marian Cepok <marian.cepok@gmail.com>
|
||||
Mario <191101255+wariuccio@users.noreply.github.com>
|
||||
@@ -1339,6 +1369,7 @@ Matvey Soloviev <blackhole89@gmail.com>
|
||||
Max Krasnyansky <max.krasnyansky@gmail.com>
|
||||
Max Krasnyansky <maxk@qti.qualcomm.com>
|
||||
Max Krasnyansky <quic_maxk@quicinc.com>
|
||||
Max S. <rin@wantan.me>
|
||||
Maxim Evtush <154841002+maximevtush@users.noreply.github.com>
|
||||
Maxime <672982+maximegmd@users.noreply.github.com>
|
||||
Maximilian Werk <maximilian.werk@gmx.de>
|
||||
@@ -1347,6 +1378,7 @@ mdrokz <mohammadmunshi@gmail.com>
|
||||
Me42019 <jeremyh88.jh@gmail.com>
|
||||
meatposes <computerdork@verizon.net>
|
||||
MeeMin <74113151+Meet91721@users.noreply.github.com>
|
||||
Meet Amin <meetamin378@gmail.com>
|
||||
megemini <megemini@outlook.com>
|
||||
Mendy Berger <12537668+MendyBerger@users.noreply.github.com>
|
||||
Meng Zhang <meng@tabbyml.com>
|
||||
@@ -1358,6 +1390,7 @@ Merrick Christensen <merrick.christensen@gmail.com>
|
||||
mgroeber9110 <45620825+mgroeber9110@users.noreply.github.com>
|
||||
MiaoMing Chen <miaomingc@stumail.nwu.edu.cn>
|
||||
Miaoqian Lin <linmq006@gmail.com>
|
||||
Michael <michael.overhorst@gmail.com>
|
||||
Michael Coppola <m18coppola@gmail.com>
|
||||
Michael de Gans <michael.john.degans@gmail.com>
|
||||
Michaël de Vries <vriesdemichael@gmail.com>
|
||||
@@ -1456,6 +1489,7 @@ niansa/tuxifan <anton-sa@web.de>
|
||||
niansa/tuxifan <tuxifan@posteo.de>
|
||||
Nicholai Tukanov <nicholaitukanov@gmail.com>
|
||||
Nicholas Sparks <157740354+nisparks@users.noreply.github.com>
|
||||
nicholas-mainardi-domyn <nicholas.mainardi@domyn.com>
|
||||
Nick <0x0b4ac@gmail.com>
|
||||
Nick Farrell <nick.farrell@aiven.io>
|
||||
nick huang <nickhuang99@hotmail.com>
|
||||
@@ -1531,6 +1565,7 @@ PAB <pierreantoine.bannier@gmail.com>
|
||||
Pablo Duboue <pablo.duboue@gmail.com>
|
||||
Pádraic Slattery <pgoslatara@gmail.com>
|
||||
parabelboi <parabelboi@gmail.com>
|
||||
parthod0x <260393540+parthod0x@users.noreply.github.com>
|
||||
Pascal <admin@serveurperso.com>
|
||||
Pascal Patry <ppatry@mtacitlabs.com>
|
||||
pascal-lc <49066376+pascal-lc@users.noreply.github.com>
|
||||
@@ -1553,6 +1588,7 @@ Paweł Wodnicki <151604+32bitmicro@users.noreply.github.com>
|
||||
pculliton <phillipculliton@gmail.com>
|
||||
Pedro Cuenca <pedro@huggingface.co>
|
||||
peidaqi <peidaqi@gmail.com>
|
||||
Pelayo Garcia Bárcena <40317024+PelaGB17@users.noreply.github.com>
|
||||
Penglin Cai <1402538448@qq.com>
|
||||
pengxin99 <pengxin.yuan@intel.com>
|
||||
Pepijn de Vos <me@pepijndevos.nl>
|
||||
@@ -1583,6 +1619,7 @@ Piotr Kubaj <pkubaj@anongoth.pl>
|
||||
Piotr Wilkin (ilintar) <piotr.wilkin@syndatis.com>
|
||||
pl752 <pl752@mail.ru>
|
||||
Plamen Minev <pacominev@gmail.com>
|
||||
Plasmatix Ultra <stevenrichardbarnett@gmail.com>
|
||||
Ploo <239304139+xinitrcn1@users.noreply.github.com>
|
||||
pmaybank <113125070+pmaybank@users.noreply.github.com>
|
||||
pmysl <piotr.myslinski@outlook.com>
|
||||
@@ -1646,6 +1683,7 @@ Rahul Vivek Nair <68507071+RahulVivekNair@users.noreply.github.com>
|
||||
Rail Chabdarov <rchabdar@amd.com>
|
||||
rainred <107027757+gryffindor-rr@users.noreply.github.com>
|
||||
Raj Hammeer Singh Hada <hammeerraj@gmail.com>
|
||||
Rajarshi Datta <138959719+rajarshidattapy@users.noreply.github.com>
|
||||
Rajendra Matcha <matcraje@qti.qualcomm.com>
|
||||
Ralph Soika <ralph.soika@imixs.com>
|
||||
Raman Shinde <raman.shinde15@gmail.com>
|
||||
@@ -1678,6 +1716,7 @@ Ren Xuancheng <jklj077@users.noreply.github.com>
|
||||
Renat <rntk@users.noreply.github.com>
|
||||
Rene Leonhardt <65483435+reneleonhardt@users.noreply.github.com>
|
||||
Renzis <93137239+Renzishi@users.noreply.github.com>
|
||||
Revertron <105154+Revertron@users.noreply.github.com>
|
||||
Reza Kakhki <rezakakhki.de@gmail.com>
|
||||
Reza Rahemtola <49811529+RezaRahemtola@users.noreply.github.com>
|
||||
RhinoDevel <RhinoDevel@users.noreply.github.com>
|
||||
@@ -1746,6 +1785,7 @@ Ruben Ortlam <picard12@live.de>
|
||||
Ruben Ortlam <rortlam@redhat.com>
|
||||
Ruchira Hasaranga <ruchira66@gmail.com>
|
||||
Rudi Servo <rudiservo@gmail.com>
|
||||
Rudransh Shekhar <kanhaiffco2007@gmail.com>
|
||||
Ruikai Peng <retr0@retr0.blog>
|
||||
Ruixiang Wang <wangruixiang07@outlook.com>
|
||||
Ruixin Huang <18860020911@163.com>
|
||||
@@ -1759,6 +1799,7 @@ Ryan Goulden <percontation@gmail.com>
|
||||
Ryan Landay <rlanday@gmail.com>
|
||||
Ryan Mangeno <160974989+ryan-mangeno@users.noreply.github.com>
|
||||
Ryder Wishart <ryderwishart@gmail.com>
|
||||
Ryn Wang <94994001+rynwang@users.noreply.github.com>
|
||||
Ryuei <louixs@users.noreply.github.com>
|
||||
s-goto-11 <206795233+s-goto-11@users.noreply.github.com>
|
||||
s0mecode <213953308+s0mecode@users.noreply.github.com>
|
||||
@@ -1773,6 +1814,7 @@ Safi Ullah <safiullah.3915@gmail.com>
|
||||
safranowith <bsh155762@gmail.com>
|
||||
Said Taghadouini <84044788+staghado@users.noreply.github.com>
|
||||
SaidSultani <62264302+SaidSultani@users.noreply.github.com>
|
||||
saiph <cecwxf@126.com>
|
||||
Sait Furkan Teke <35101659+stfurkan@users.noreply.github.com>
|
||||
SakuraUmi <yukinon244@gmail.com>
|
||||
Salvador E. Tropea <stropea@inti.gob.ar>
|
||||
@@ -1813,6 +1855,7 @@ Seb C <47074056+Sebby37@users.noreply.github.com>
|
||||
Sebastián A <sebastian.aedo29@gmail.com>
|
||||
Sebastian Dröge <sebastian@centricular.com>
|
||||
Sebastian Dröge <slomo@coaxion.net>
|
||||
Sebastian Kuzminsky <seb@highlab.com>
|
||||
SebastianApel <13675545+SebastianApel@users.noreply.github.com>
|
||||
SecondSeed <38520721+SecondSeed@users.noreply.github.com>
|
||||
semidark <me@semidark.net>
|
||||
@@ -1873,6 +1916,7 @@ Shreya Jain <shreya94jain@gmail.com>
|
||||
Shreya Jain <shreyajn@qti.qualcomm.com>
|
||||
Shrivas Shankar <86219405+shrivasshankar@users.noreply.github.com>
|
||||
SHUAI YANG <shuaiyang047@163.com>
|
||||
Shubham Roy <roy388925@gmail.com>
|
||||
Shuichi Tsutsumi <shuichi0526@gmail.com>
|
||||
shun095 <8069181+shun095@users.noreply.github.com>
|
||||
Shunta Saito <shunta.saito@gmail.com>
|
||||
@@ -1883,6 +1927,7 @@ Siavash Norouzi <35790025+siavashnorouzi@users.noreply.github.com>
|
||||
Sid Mohan <61345237+sidmohan0@users.noreply.github.com>
|
||||
Sid Shaytay <2595088+SidShaytay@users.noreply.github.com>
|
||||
SIDDARTHA REDDY <75976672+SIDDARTHAREDDY8@users.noreply.github.com>
|
||||
Sidhartha Reddy Potu <73529763+sid-rp@users.noreply.github.com>
|
||||
Sigbjørn Skjæret <1629204+CISC@users.noreply.github.com>
|
||||
Sigbjørn Skjæret <ggerganov@gmail.com>
|
||||
Sigbjørn Skjæret <sigbjorn.skjaeret@huggingface.co>
|
||||
@@ -1926,6 +1971,7 @@ Son H. Nguyen <33925625+nhs000@users.noreply.github.com>
|
||||
Song Li <songtli@outlook.com>
|
||||
Sophon <strongtz@yeah.net>
|
||||
Sou-ly <79574807+Sou-ly@users.noreply.github.com>
|
||||
Souleyman <79574807+Sou-ly@users.noreply.github.com>
|
||||
Sourab Mangrulkar <13534540+pacman100@users.noreply.github.com>
|
||||
Spencer Sutton <spencersutton@users.noreply.github.com>
|
||||
sprayandwipe <spray.and.wipe@gmail.com>
|
||||
@@ -1935,6 +1981,7 @@ Srihari-mcw <96763064+Srihari-mcw@users.noreply.github.com>
|
||||
Srijan Keshri <212402043+arcusbuilds@users.noreply.github.com>
|
||||
Srinivas Billa <nivibilla@gmail.com>
|
||||
srkizer <github.soreepeong.prqovzj1d@srkizer.net>
|
||||
SS1618 <45392178+SS1618@users.noreply.github.com>
|
||||
ssweens <1149151+ssweens@users.noreply.github.com>
|
||||
standby24x7 <standby24x7@gmail.com>
|
||||
staviq <staviq@gmail.com>
|
||||
@@ -1969,6 +2016,8 @@ swittk <switt1995@gmail.com>
|
||||
sxq <18856096915@163.com>
|
||||
SXX <song_xiaoxi@126.com>
|
||||
SXX <sxx1136965276@gmail.com>
|
||||
sys2008 <165458212+sys2008@users.noreply.github.com>
|
||||
t-kusanagi <46693526+t-kusanagi@users.noreply.github.com>
|
||||
Tai Duc Nguyen <taiducnguyen.drexel@gmail.com>
|
||||
Taikono-Himazin <kazu@po.harenet.ne.jp>
|
||||
Taimur Ahmad <taimur.ahmad@10xengineers.ai>
|
||||
@@ -1998,6 +2047,7 @@ Tei Home <taiteitonghome@proton.me>
|
||||
Tekin Ertekin <tekin.ertekin@gmail.com>
|
||||
Tekin Ertekin <tekinertekin@gmail.com>
|
||||
tempstudio <49735574+tempstudio@users.noreply.github.com>
|
||||
Teng Mei <73174080+meitmt@users.noreply.github.com>
|
||||
teo <TeoZosa@users.noreply.github.com>
|
||||
Terrence Zhao <32208165+Terrencezzj@users.noreply.github.com>
|
||||
texasich <101962694+texasich@users.noreply.github.com>
|
||||
@@ -2107,8 +2157,10 @@ Valentyn Bezshapkin <61702053+valentynbez@users.noreply.github.com>
|
||||
Valeriy Dubov <dvv101111@gmail.com>
|
||||
Vali Malinoiu <0x4139@gmail.com>
|
||||
valiray <133289098+valiray@users.noreply.github.com>
|
||||
varun <varun10221@gmail.com>
|
||||
vb <vaibhavs10@gmail.com>
|
||||
Vedran Miletić <vedran@miletic.net>
|
||||
velonica0 <47554626+velonica0@users.noreply.github.com>
|
||||
Vexxie <rainandriamusic@gmail.com>
|
||||
Victor <194116445+dodekapod@users.noreply.github.com>
|
||||
Victor Nogueira <felladrin@gmail.com>
|
||||
@@ -2137,6 +2189,7 @@ Vladimir Sotnikov <bubert9@gmail.com>
|
||||
Vladimir Vuksanovic <109677816+vvuksanovic@users.noreply.github.com>
|
||||
Vladimir Zorin <vladimir@deviant.guru>
|
||||
Vladislav <vladplotnikov34@gmail.com>
|
||||
Vladislav Merkulov <150796351+merkulovlad@users.noreply.github.com>
|
||||
Vladislav Sayapin <70110788+v-sayapin@users.noreply.github.com>
|
||||
vmobilis <75476228+vmobilis@users.noreply.github.com>
|
||||
vodkaslime <646329483@qq.com>
|
||||
@@ -2166,6 +2219,7 @@ wencan <wencan@live.cn>
|
||||
wendadawen <130649302+wendadawen@users.noreply.github.com>
|
||||
WenqiangJia2026 <wenqijia@amd.com>
|
||||
Wentai Zhang <rchardx@gmail.com>
|
||||
Wenyu Chen <wenyuc21@gmail.com>
|
||||
wes <huangwei858@126.com>
|
||||
whoreson <139810751+whoreson@users.noreply.github.com>
|
||||
Wilken Gottwalt <12194808+wgottwalt@users.noreply.github.com>
|
||||
@@ -2211,6 +2265,7 @@ Xie Yanbo <xieyanbo@gmail.com>
|
||||
Xingchen Song(宋星辰) <xingchensong1996@163.com>
|
||||
Xinpeng Dou <15529241576@163.com>
|
||||
Xinpeng Dou <81913537+Dou-Git@users.noreply.github.com>
|
||||
xjf888800 <59639069+xjf888800@users.noreply.github.com>
|
||||
xloem <0xloem@gmail.com>
|
||||
xris99 <79798089+xris99@users.noreply.github.com>
|
||||
Xuan Son Nguyen <son@huggingface.co>
|
||||
@@ -2218,6 +2273,7 @@ Xuan Son Nguyen <thichthat@gmail.com>
|
||||
Xuan-Son Nguyen <son@huggingface.co>
|
||||
Xuan-Son Nguyen <thichthat@gmail.com>
|
||||
Xue Zhenliang <riteme@users.noreply.github.com>
|
||||
Xuejun Zhai <xuejun.zhai@intel.com>
|
||||
XZiar <15145384+XZiar@users.noreply.github.com>
|
||||
y198 <90976397+y198nt@users.noreply.github.com>
|
||||
yael-works <106673277+yael-works@users.noreply.github.com>
|
||||
@@ -2255,6 +2311,7 @@ Yishuo Wang <MeouSker77@outlook.com>
|
||||
Yiwei Shao <44545837+njsyw1997@users.noreply.github.com>
|
||||
ymcki <84055651+ymcki@users.noreply.github.com>
|
||||
ynankani <ynankani@nvidia.com>
|
||||
yoch <yoch.melka@gmail.com>
|
||||
yomi <3527628634@qq.com>
|
||||
Yonghye Kwon <developer.0hye@gmail.com>
|
||||
Yongmin Yoo 유용민 <yymin1022@gmail.com>
|
||||
@@ -2299,6 +2356,7 @@ zhangrunda <zhangrunda1234@outlook.com>
|
||||
zhangtao2-1 <478679312@qq.com>
|
||||
ZHAOKAI WANG <sanxianwei@163.com>
|
||||
Zhaolun Yin <129580161+ZhaolunYin@users.noreply.github.com>
|
||||
ZhaolunYin <129580161+ZhaolunYin@users.noreply.github.com>
|
||||
zhaoyshine <30611065+zhaoyshine@users.noreply.github.com>
|
||||
Zheng.Deng <32841220+dengzheng-cloud@users.noreply.github.com>
|
||||
zhentaoyu <zhentao.yu@intel.com>
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ include(CheckIncludeFileCXX)
|
||||
|
||||
### llama.cpp version
|
||||
set(LLAMA_VERSION_MAJOR 1)
|
||||
set(LLAMA_VERSION_MINOR 0)
|
||||
set(LLAMA_VERSION_MINOR 1)
|
||||
set(LLAMA_VERSION_PATCH 0)
|
||||
set(LLAMA_VERSION_BASE "${LLAMA_VERSION_MAJOR}.${LLAMA_VERSION_MINOR}.${LLAMA_VERSION_PATCH}")
|
||||
|
||||
|
||||
@@ -171,7 +171,7 @@ if (LLAMA_LLGUIDANCE)
|
||||
CONFIGURE_COMMAND ""
|
||||
BUILD_COMMAND cargo build --release --package llguidance
|
||||
INSTALL_COMMAND ""
|
||||
BUILD_BYPRODUCTS ${LLGUIDANCE_PATH}/${LLGUIDANCE_LIB_NAME} ${LLGUIDANCE_PATH}/llguidance.h
|
||||
BUILD_BYPRODUCTS ${LLGUIDANCE_PATH}/${LLGUIDANCE_LIB_NAME} ${LLGUIDANCE_SRC}/parser/llguidance.h
|
||||
UPDATE_COMMAND ""
|
||||
)
|
||||
target_compile_definitions(${TARGET} PUBLIC LLAMA_USE_LLGUIDANCE)
|
||||
@@ -180,7 +180,7 @@ if (LLAMA_LLGUIDANCE)
|
||||
set_target_properties(llguidance PROPERTIES IMPORTED_LOCATION ${LLGUIDANCE_PATH}/${LLGUIDANCE_LIB_NAME})
|
||||
add_dependencies(llguidance llguidance_ext)
|
||||
|
||||
target_include_directories(${TARGET} PRIVATE ${LLGUIDANCE_PATH})
|
||||
target_include_directories(${TARGET} PRIVATE ${LLGUIDANCE_SRC}/parser)
|
||||
target_link_libraries(${TARGET} PRIVATE llguidance)
|
||||
if (WIN32)
|
||||
target_link_libraries(${TARGET} PRIVATE ws2_32 userenv ntdll bcrypt)
|
||||
|
||||
@@ -3494,6 +3494,14 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
|
||||
// note: do not modify cors_origins here, as the options are not evaluated in order (user may explicitly set --cors-origins before --agent)
|
||||
}
|
||||
).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_AGENT"));
|
||||
add_opt(common_arg(
|
||||
{"--ui-agent"},
|
||||
"enable agent mode in Llama Chat with nothing enabled on the server: the tools that run in the browser and MCP servers the browser reaches itself, no server tools and no MCP proxy (default: disabled)\n"
|
||||
"note: not needed with --agent, --tools or --ui-mcp-proxy, they enable agent mode in Llama Chat too",
|
||||
[](common_params & params) {
|
||||
params.ui_agent = true;
|
||||
}
|
||||
).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_UI_AGENT"));
|
||||
add_opt(common_arg(
|
||||
{"--ui", "--webui"},
|
||||
{"--no-ui", "--no-webui"},
|
||||
|
||||
@@ -225,13 +225,13 @@ common_peg_parser analyze_tools::build_tool_parser_json_native(parser_build_cont
|
||||
auto single_tool_parser = p.standard_json_tools(
|
||||
format.per_call_start, format.per_call_end, inputs.tools, inputs.parallel_tool_calls,
|
||||
inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED, name_field, args_field, format.tools_array_wrapped,
|
||||
format.fun_name_is_key, format.id_field, format.gen_id_field, format.parameter_order, format.openai_wrapper_trigger);
|
||||
format.fun_name_is_key, format.id_field, format.gen_id_field, format.parameter_order, format.openai_wrapper_trigger, inputs.tool_choice);
|
||||
tools_parser = p.trigger_rule("tool-calls", p.one_or_more(single_tool_parser + p.space()));
|
||||
} else {
|
||||
tools_parser = p.standard_json_tools(
|
||||
format.section_start, format.section_end, inputs.tools, inputs.parallel_tool_calls,
|
||||
inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED, name_field, args_field, format.tools_array_wrapped,
|
||||
format.fun_name_is_key, format.id_field, format.gen_id_field, format.parameter_order, format.openai_wrapper_trigger);
|
||||
format.fun_name_is_key, format.id_field, format.gen_id_field, format.parameter_order, format.openai_wrapper_trigger, inputs.tool_choice);
|
||||
}
|
||||
|
||||
// Handle content wrappers if present
|
||||
@@ -304,7 +304,7 @@ common_peg_parser analyze_tools::build_tool_parser_tag_json(parser_build_context
|
||||
|
||||
common_peg_parser tool_choice = p.choice();
|
||||
|
||||
foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) {
|
||||
common_chat_foreach_tool(inputs.tools, inputs.tool_choice, [&](size_t tool_index, const json & tool) {
|
||||
const auto & func = tool.at("function");
|
||||
std::string name = func.at("name");
|
||||
const auto schema = common_chat_tool_parameters(func);
|
||||
@@ -379,7 +379,7 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
|
||||
|
||||
common_peg_parser tool_choice = p.choice();
|
||||
|
||||
foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) {
|
||||
common_chat_foreach_tool(inputs.tools, inputs.tool_choice, [&](size_t tool_index, const json & tool) {
|
||||
const auto & func = tool.at("function");
|
||||
std::string name = func.at("name");
|
||||
|
||||
|
||||
+24
-32
@@ -650,19 +650,16 @@ static std::pair<std::string, std::string> parse_key_spec(const std::string & ke
|
||||
|
||||
// Mode 1: function_is_key — parse {"function_name": {...}}
|
||||
common_peg_parser common_chat_peg_builder::build_json_tools_function_is_key(
|
||||
const ordered_json & tools,
|
||||
const std::string & args_key,
|
||||
const std::string & effective_args_key,
|
||||
const std::string & call_id_key,
|
||||
const std::string & gen_call_id_key) {
|
||||
const ordered_json & tools,
|
||||
const common_chat_tool_choice & tool_choice,
|
||||
const std::string & args_key,
|
||||
const std::string & effective_args_key,
|
||||
const std::string & call_id_key,
|
||||
const std::string & gen_call_id_key) {
|
||||
|
||||
auto tool_choices = choice();
|
||||
|
||||
for (size_t i = 0; i < tools.size(); i++) {
|
||||
const auto & tool_def = tools[i];
|
||||
if (!tool_def.contains("function")) {
|
||||
continue;
|
||||
}
|
||||
common_chat_foreach_tool(tools, tool_choice, [&](size_t i, const ordered_json & tool_def) {
|
||||
const auto & function = tool_def.at("function");
|
||||
std::string name = function.at("name");
|
||||
ordered_json params = common_chat_tool_parameters(function);
|
||||
@@ -723,18 +720,19 @@ common_peg_parser common_chat_peg_builder::build_json_tools_function_is_key(
|
||||
);
|
||||
|
||||
tool_choices |= rule("tool-" + std::to_string(i), tool_parser);
|
||||
}
|
||||
});
|
||||
|
||||
return tool_choices;
|
||||
}
|
||||
|
||||
// Mode 2: Nested keys (dot notation like "function.name")
|
||||
common_peg_parser common_chat_peg_builder::build_json_tools_nested_keys(
|
||||
const ordered_json & tools,
|
||||
const std::string & effective_name_key,
|
||||
const std::string & effective_args_key,
|
||||
const std::string & call_id_key,
|
||||
const std::string & gen_call_id_key) {
|
||||
const ordered_json & tools,
|
||||
const common_chat_tool_choice & tool_choice,
|
||||
const std::string & effective_name_key,
|
||||
const std::string & effective_args_key,
|
||||
const std::string & call_id_key,
|
||||
const std::string & gen_call_id_key) {
|
||||
|
||||
auto tool_choices = choice();
|
||||
|
||||
@@ -745,11 +743,7 @@ common_peg_parser common_chat_peg_builder::build_json_tools_nested_keys(
|
||||
std::string nested_name_field = !name_spec.first.empty() ? name_spec.second : effective_name_key;
|
||||
std::string nested_args_field = !args_spec.first.empty() ? args_spec.second : effective_args_key;
|
||||
|
||||
for (size_t i = 0; i < tools.size(); i++) {
|
||||
const auto & tool_def = tools[i];
|
||||
if (!tool_def.contains("function")) {
|
||||
continue;
|
||||
}
|
||||
common_chat_foreach_tool(tools, tool_choice, [&](size_t i, const ordered_json & tool_def) {
|
||||
const auto & function = tool_def.at("function");
|
||||
std::string name = function.at("name");
|
||||
ordered_json params = common_chat_tool_parameters(function);
|
||||
@@ -796,7 +790,7 @@ common_peg_parser common_chat_peg_builder::build_json_tools_nested_keys(
|
||||
tool_parser_body = tool_parser_body + nested_field + space() + tool_close(literal("}"));
|
||||
|
||||
tool_choices |= rule("tool-" + std::to_string(i), tool(tool_parser_body));
|
||||
}
|
||||
});
|
||||
|
||||
return tool_choices;
|
||||
}
|
||||
@@ -804,6 +798,7 @@ common_peg_parser common_chat_peg_builder::build_json_tools_nested_keys(
|
||||
// Mode 3: Flat keys with optional ID fields and parameter ordering
|
||||
common_peg_parser common_chat_peg_builder::build_json_tools_flat_keys(
|
||||
const ordered_json & tools,
|
||||
const common_chat_tool_choice & tool_choice,
|
||||
const std::string & effective_name_key,
|
||||
const std::string & effective_args_key,
|
||||
const std::string & call_id_key,
|
||||
@@ -815,11 +810,7 @@ common_peg_parser common_chat_peg_builder::build_json_tools_flat_keys(
|
||||
auto name_key_parser = literal("\"" + effective_name_key + "\"");
|
||||
auto args_key_parser = literal("\"" + effective_args_key + "\"");
|
||||
|
||||
for (size_t i = 0; i < tools.size(); i++) {
|
||||
const auto & tool_def = tools[i];
|
||||
if (!tool_def.contains("function")) {
|
||||
continue;
|
||||
}
|
||||
common_chat_foreach_tool(tools, tool_choice, [&](size_t i, const ordered_json & tool_def) {
|
||||
const auto & function = tool_def.at("function");
|
||||
std::string name = function.at("name");
|
||||
ordered_json params = common_chat_tool_parameters(function);
|
||||
@@ -888,7 +879,7 @@ common_peg_parser common_chat_peg_builder::build_json_tools_flat_keys(
|
||||
ordered_body = ordered_body + space() + tool_close(literal("}"));
|
||||
|
||||
tool_choices |= rule("tool-" + std::to_string(i), tool(ordered_body));
|
||||
}
|
||||
});
|
||||
|
||||
return tool_choices;
|
||||
}
|
||||
@@ -942,7 +933,8 @@ common_peg_parser common_chat_peg_builder::standard_json_tools(
|
||||
const std::string & call_id_key,
|
||||
const std::string & gen_call_id_key,
|
||||
const std::vector<std::string> & parameters_order,
|
||||
bool accept_openai_wrapper) {
|
||||
bool accept_openai_wrapper,
|
||||
const common_chat_tool_choice & tool_choice) {
|
||||
if (!tools.is_array() || tools.empty()) {
|
||||
return eps();
|
||||
}
|
||||
@@ -953,14 +945,14 @@ common_peg_parser common_chat_peg_builder::standard_json_tools(
|
||||
// Dispatch to the appropriate builder based on the JSON layout mode
|
||||
common_peg_parser tool_choices = eps();
|
||||
if (function_is_key) {
|
||||
tool_choices = build_json_tools_function_is_key(tools, args_key, effective_args_key, call_id_key, gen_call_id_key);
|
||||
tool_choices = build_json_tools_function_is_key(tools, tool_choice, args_key, effective_args_key, call_id_key, gen_call_id_key);
|
||||
} else {
|
||||
auto name_spec = parse_key_spec(effective_name_key);
|
||||
auto args_spec = parse_key_spec(effective_args_key);
|
||||
if (!name_spec.first.empty() || !args_spec.first.empty()) {
|
||||
tool_choices = build_json_tools_nested_keys(tools, effective_name_key, effective_args_key, call_id_key, gen_call_id_key);
|
||||
tool_choices = build_json_tools_nested_keys(tools, tool_choice, effective_name_key, effective_args_key, call_id_key, gen_call_id_key);
|
||||
} else {
|
||||
tool_choices = build_json_tools_flat_keys(tools, effective_name_key, effective_args_key, call_id_key, gen_call_id_key, parameters_order, accept_openai_wrapper);
|
||||
tool_choices = build_json_tools_flat_keys(tools, tool_choice, effective_name_key, effective_args_key, call_id_key, gen_call_id_key, parameters_order, accept_openai_wrapper);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+14
-10
@@ -143,7 +143,7 @@ class common_chat_peg_builder : public common_peg_parser_builder {
|
||||
// parameters_order: order in which JSON fields should be parsed
|
||||
common_peg_parser standard_json_tools(const std::string & section_start,
|
||||
const std::string & section_end,
|
||||
const common_json & tools,
|
||||
const common_json & tools,
|
||||
bool parallel_tool_calls,
|
||||
bool force_tool_calls,
|
||||
const std::string & name_key = "",
|
||||
@@ -153,7 +153,8 @@ class common_chat_peg_builder : public common_peg_parser_builder {
|
||||
const std::string & call_id_key = "",
|
||||
const std::string & gen_call_id_key = "",
|
||||
const std::vector<std::string> & parameters_order = {},
|
||||
bool accept_openai_wrapper = false);
|
||||
bool accept_openai_wrapper = false,
|
||||
const common_chat_tool_choice & tool_choice = {});
|
||||
|
||||
// Legacy-compatible helper for building XML/tagged style tool calls
|
||||
// Used by tests and manual parsers
|
||||
@@ -176,18 +177,21 @@ class common_chat_peg_builder : public common_peg_parser_builder {
|
||||
|
||||
// Implementation helpers for standard_json_tools — one per JSON tool call layout mode
|
||||
common_peg_parser build_json_tools_function_is_key(const common_json & tools,
|
||||
const std::string & args_key,
|
||||
const std::string & effective_args_key,
|
||||
const std::string & call_id_key,
|
||||
const std::string & gen_call_id_key);
|
||||
const common_chat_tool_choice & tool_choice,
|
||||
const std::string & args_key,
|
||||
const std::string & effective_args_key,
|
||||
const std::string & call_id_key,
|
||||
const std::string & gen_call_id_key);
|
||||
|
||||
common_peg_parser build_json_tools_nested_keys(const common_json & tools,
|
||||
const std::string & effective_name_key,
|
||||
const std::string & effective_args_key,
|
||||
const std::string & call_id_key,
|
||||
const std::string & gen_call_id_key);
|
||||
const common_chat_tool_choice & tool_choice,
|
||||
const std::string & effective_name_key,
|
||||
const std::string & effective_args_key,
|
||||
const std::string & call_id_key,
|
||||
const std::string & gen_call_id_key);
|
||||
|
||||
common_peg_parser build_json_tools_flat_keys(const common_json & tools,
|
||||
const common_chat_tool_choice & tool_choice,
|
||||
const std::string & effective_name_key,
|
||||
const std::string & effective_args_key,
|
||||
const std::string & call_id_key,
|
||||
|
||||
+54
-3
@@ -322,7 +322,21 @@ struct common_chat_templates {
|
||||
std::shared_ptr<common_tts_dicts> tts_dicts; // dictionaries of the model for tts_dict(), by name
|
||||
};
|
||||
|
||||
common_chat_tool_choice common_chat_tool_choice_parse_oaicompat(const std::string & tool_choice) {
|
||||
bool common_chat_tool_choice::allows(const std::string & name) const {
|
||||
return !is_none() && (allowed.empty() || std::find(allowed.begin(), allowed.end(), name) != allowed.end());
|
||||
}
|
||||
|
||||
void common_chat_foreach_tool(const common_json & tools, const common_chat_tool_choice & tool_choice,
|
||||
const std::function<void(size_t, const common_json &)> & fn) {
|
||||
for (size_t i = 0; i < tools.size(); i++) {
|
||||
const auto & tool = tools[i];
|
||||
if (tool_choice.allows(tool.at("function").at("name").get<std::string>())) {
|
||||
fn(i, tool);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
common_chat_tool_choice common_chat_tool_choice_parse_oaicompat(const common_json & tool_choice, const std::vector<common_chat_tool> & tools) {
|
||||
if (tool_choice == "auto") {
|
||||
return COMMON_CHAT_TOOL_CHOICE_AUTO;
|
||||
}
|
||||
@@ -332,7 +346,44 @@ common_chat_tool_choice common_chat_tool_choice_parse_oaicompat(const std::strin
|
||||
if (tool_choice == "required") {
|
||||
return COMMON_CHAT_TOOL_CHOICE_REQUIRED;
|
||||
}
|
||||
throw std::invalid_argument("Invalid tool_choice: " + tool_choice);
|
||||
common_chat_tool_choice choice;
|
||||
const auto type = tool_choice.value("type", json());
|
||||
if (type == "function") {
|
||||
choice.mode = COMMON_CHAT_TOOL_CHOICE_REQUIRED;
|
||||
choice.allowed.push_back(tool_choice.at("function").at("name").get<std::string>());
|
||||
} else if (type == "allowed_tools") {
|
||||
const auto & allowed = tool_choice.at("allowed_tools");
|
||||
const auto & mode = allowed.at("mode");
|
||||
const auto & allowed_tools = allowed.at("tools");
|
||||
if ((mode != "auto" && mode != "required") || !allowed_tools.is_array()) {
|
||||
throw std::invalid_argument("allowed_tools requires mode auto or required and a tools array");
|
||||
}
|
||||
choice.mode = mode == "required" ? COMMON_CHAT_TOOL_CHOICE_REQUIRED : COMMON_CHAT_TOOL_CHOICE_AUTO;
|
||||
for (const auto & tool : allowed_tools) {
|
||||
if (tool.value("type", json()) != "function") {
|
||||
throw std::invalid_argument("allowed_tools entries must have type function");
|
||||
}
|
||||
choice.allowed.push_back(tool.at("function").at("name").get<std::string>());
|
||||
}
|
||||
if (choice.allowed.empty()) {
|
||||
if (choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) {
|
||||
throw std::invalid_argument("Required allowed_tools must contain at least one function");
|
||||
}
|
||||
choice.mode = COMMON_CHAT_TOOL_CHOICE_NONE;
|
||||
}
|
||||
} else {
|
||||
throw std::invalid_argument("Invalid tool_choice: " + tool_choice.dump());
|
||||
}
|
||||
|
||||
for (const auto & name : choice.allowed) {
|
||||
const auto n_matching = std::count_if(tools.begin(), tools.end(), [&](const common_chat_tool & tool) {
|
||||
return tool.name == name;
|
||||
});
|
||||
if (name.empty() || n_matching != 1) {
|
||||
throw std::invalid_argument("tool_choice function name must match exactly one supplied tool: " + name);
|
||||
}
|
||||
}
|
||||
return choice;
|
||||
}
|
||||
|
||||
bool common_chat_templates_support_enable_thinking(const common_chat_templates * chat_templates) {
|
||||
@@ -1406,7 +1457,7 @@ static common_chat_params_init_fn common_chat_template_detect_params_init(const
|
||||
}
|
||||
|
||||
// LFM2.5 format detection: template uses plain "List of tools: [...]" with no special tokens
|
||||
if (src.find("List of tools: [") != std::string::npos &&
|
||||
if (src.find("List of tools: ") != std::string::npos &&
|
||||
src.find("<|tool_list_start|>") == std::string::npos) {
|
||||
LOG_DBG("Using specialized template: LFM2.5\n");
|
||||
return common_chat_params_init_lfm2_5;
|
||||
|
||||
+25
-2
@@ -232,12 +232,35 @@ struct common_chat_tool {
|
||||
bool defer_loading = false;
|
||||
};
|
||||
|
||||
enum common_chat_tool_choice {
|
||||
enum common_chat_tool_choice_mode {
|
||||
COMMON_CHAT_TOOL_CHOICE_AUTO,
|
||||
COMMON_CHAT_TOOL_CHOICE_REQUIRED,
|
||||
COMMON_CHAT_TOOL_CHOICE_NONE,
|
||||
};
|
||||
|
||||
struct common_chat_tool_choice {
|
||||
common_chat_tool_choice_mode mode = COMMON_CHAT_TOOL_CHOICE_AUTO;
|
||||
|
||||
// Names of the tools the model may call, every tool when empty.
|
||||
std::vector<std::string> allowed;
|
||||
|
||||
common_chat_tool_choice() = default;
|
||||
common_chat_tool_choice(common_chat_tool_choice_mode mode) : mode(mode) {}
|
||||
|
||||
bool operator==(common_chat_tool_choice_mode other) const { return mode == other; }
|
||||
bool operator!=(common_chat_tool_choice_mode other) const { return mode != other; }
|
||||
|
||||
bool allows(const std::string & name) const;
|
||||
|
||||
bool is_auto() const { return mode == COMMON_CHAT_TOOL_CHOICE_AUTO; }
|
||||
bool is_required() const { return mode == COMMON_CHAT_TOOL_CHOICE_REQUIRED; }
|
||||
bool is_none() const { return mode == COMMON_CHAT_TOOL_CHOICE_NONE; }
|
||||
};
|
||||
|
||||
// Keep the original tool indices when restricting the parser's tool set.
|
||||
void common_chat_foreach_tool(const common_json & tools, const common_chat_tool_choice & tool_choice,
|
||||
const std::function<void(size_t, const common_json &)> & fn);
|
||||
|
||||
enum common_chat_format {
|
||||
COMMON_CHAT_FORMAT_CONTENT_ONLY,
|
||||
|
||||
@@ -458,7 +481,7 @@ class common_chat_session {
|
||||
const char * common_reasoning_format_name(common_reasoning_format format);
|
||||
common_reasoning_format common_reasoning_format_from_name(const std::string & format);
|
||||
|
||||
common_chat_tool_choice common_chat_tool_choice_parse_oaicompat(const std::string & tool_choice);
|
||||
common_chat_tool_choice common_chat_tool_choice_parse_oaicompat(const common_json & tool_choice, const std::vector<common_chat_tool> & tools);
|
||||
|
||||
bool common_chat_templates_support_enable_thinking(const common_chat_templates * chat_templates);
|
||||
|
||||
|
||||
@@ -701,6 +701,7 @@ struct common_params {
|
||||
|
||||
// UI configs
|
||||
bool ui = true;
|
||||
bool ui_agent = false; // agent mode in Llama Chat, no server tools and no MCP proxy
|
||||
bool ui_mcp_proxy = false;
|
||||
bool ui_mcp_proxy_allow_private_urls = false; // allow the MCP CORS proxy to reach local or private addresses
|
||||
std::string ui_config_json;
|
||||
|
||||
@@ -117,14 +117,32 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) {
|
||||
imatrix.chunk_size = chunk_size_key != -1 ? gguf_get_val_u32(ctx_gguf, chunk_size_key) : 0;
|
||||
imatrix.n_layer_nextn = nextn_key != -1 ? gguf_get_val_u32(ctx_gguf, nextn_key) : 0;
|
||||
|
||||
const int64_t schema_idx = gguf_find_key(ctx_gguf, LLM_KV_IMATRIX_STATS_SCHEMA);
|
||||
if (schema_idx != -1 && gguf_get_kv_type(ctx_gguf, schema_idx) == GGUF_TYPE_ARRAY &&
|
||||
gguf_get_arr_type(ctx_gguf, schema_idx) == GGUF_TYPE_STRING) {
|
||||
const int64_t n_schema = gguf_get_arr_n(ctx_gguf, schema_idx);
|
||||
imatrix.stats_schema.resize(n_schema);
|
||||
for (int64_t i = 0; i < n_schema; ++i) { imatrix.stats_schema[i] = gguf_get_arr_str(ctx_gguf, schema_idx, i); }
|
||||
} else {
|
||||
if (schema_idx != -1) {
|
||||
LOG_WRN("%s: %s in %s is not an array of strings, using the default order\n", __func__, LLM_KV_IMATRIX_STATS_SCHEMA, fname.c_str());
|
||||
}
|
||||
|
||||
imatrix.stats_schema = {
|
||||
"sum_sq", "mean", "elements", "std_deviation", "skewness", "kurtosis", "gain", "h_norm", "l2_dist", "cossim", "pearson", "covariance",
|
||||
};
|
||||
}
|
||||
|
||||
const std::string in_sum_suffix{ ".in_sum" };
|
||||
const std::string in_sum2_suffix{ ".in_sum2" };
|
||||
const std::string counts_suffix{ ".counts" };
|
||||
const std::string stats_suffix{ ".stats" };
|
||||
|
||||
struct sum_tensors {
|
||||
struct ggml_tensor * in_sum = nullptr;
|
||||
struct ggml_tensor * in_sum2 = nullptr;
|
||||
struct ggml_tensor * counts = nullptr;
|
||||
struct ggml_tensor * stats = nullptr;
|
||||
};
|
||||
|
||||
std::map<std::string, sum_tensors> sums_counts_for;
|
||||
@@ -138,6 +156,8 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) {
|
||||
sums_counts_for[std::move(name)].in_sum2 = cur;
|
||||
} else if (string_remove_suffix(name, counts_suffix)) {
|
||||
sums_counts_for[std::move(name)].counts = cur;
|
||||
} else if (string_remove_suffix(name, stats_suffix)) {
|
||||
sums_counts_for[std::move(name)].stats = cur;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,6 +166,7 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) {
|
||||
const struct ggml_tensor * in_sum = sc.second.in_sum;
|
||||
const struct ggml_tensor * in_sum2 = sc.second.in_sum2;
|
||||
const struct ggml_tensor * counts = sc.second.counts;
|
||||
const struct ggml_tensor * stats = sc.second.stats;
|
||||
|
||||
if (!in_sum2 || !counts || (in_sum != nullptr && ggml_nelements(in_sum) != ggml_nelements(in_sum2))) {
|
||||
LOG_ERR("%s: mismatched sums and counts for %s\n", __func__, name.c_str());
|
||||
@@ -182,6 +203,12 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) {
|
||||
e.activations[j] = ((const float *) in_sum->data)[j];
|
||||
}
|
||||
}
|
||||
|
||||
if (stats && stats->type == GGML_TYPE_F32) {
|
||||
const int64_t n_stats = ggml_nelements(stats);
|
||||
e.stats.resize(n_stats);
|
||||
for (int64_t j = 0; j < n_stats; ++j) { e.stats[j] = ((const float *) stats->data)[j]; }
|
||||
}
|
||||
}
|
||||
|
||||
gguf_free(ctx_gguf);
|
||||
|
||||
@@ -15,11 +15,13 @@ struct common_imatrix_entry {
|
||||
std::vector<float> sums;
|
||||
std::vector<float> activations;
|
||||
std::vector<int64_t> counts;
|
||||
std::vector<float> stats;
|
||||
};
|
||||
|
||||
struct common_imatrix {
|
||||
std::map<std::string, common_imatrix_entry> entries;
|
||||
std::vector<std::string> datasets;
|
||||
std::vector<std::string> stats_schema;
|
||||
int32_t chunk_count = 0;
|
||||
int32_t chunk_size = 0;
|
||||
int32_t n_layer_nextn = 0;
|
||||
|
||||
@@ -244,6 +244,12 @@ class common_chat_schema_builder {
|
||||
}
|
||||
|
||||
common_chat_schema_ptr build_node_impl(const common_json & schema, const std::string & path) {
|
||||
if (schema.is_boolean()) {
|
||||
if (schema.get<bool>()) {
|
||||
return std::make_unique<common_chat_schema_any>(); // true matches any value, like {}
|
||||
}
|
||||
fail(path, "false schema is not supported"); // false matches nothing, the grammar cannot express it
|
||||
}
|
||||
if (!schema.is_object()) {
|
||||
fail(path, "schema must be an object");
|
||||
}
|
||||
|
||||
+36
-38
@@ -100,18 +100,18 @@ common_chat_params common_chat_params_init_inkling(const common_chat_template &
|
||||
auto use_tools = has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE;
|
||||
auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE;
|
||||
|
||||
data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
|
||||
auto header = p.literal(HEADER);
|
||||
auto end = p.literal(END);
|
||||
data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) {
|
||||
auto header = p.token(HEADER);
|
||||
auto end = p.token(END);
|
||||
|
||||
auto think = p.literal(THINK);
|
||||
auto thinking = p.rule("thinking", extract_reasoning ? think + p.reasoning(p.until(END)) + end :
|
||||
p.atomic(p.content(think)) + p.content(p.until(END) + end));
|
||||
auto text = p.rule("text", p.literal(TEXT) + p.content(p.until(END)) + end);
|
||||
auto think = p.token(THINK);
|
||||
auto thinking = p.rule("thinking", extract_reasoning ? think + p.reasoning(p.until(end)) + end :
|
||||
p.atomic(p.content(think)) + p.content(p.until(end) + end));
|
||||
auto text = p.rule("text", p.token(TEXT) + p.content(p.until(end)) + end);
|
||||
|
||||
if (has_response_format) {
|
||||
auto response_format = p.rule("response-format", p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema)));
|
||||
return p.zero_or_more(header + thinking) + header + p.literal(TEXT) + response_format + end;
|
||||
return p.zero_or_more(header + thinking) + header + p.token(TEXT) + response_format + end;
|
||||
}
|
||||
|
||||
auto blocks = p.zero_or_more(header + (thinking | text));
|
||||
@@ -120,45 +120,43 @@ common_chat_params common_chat_params_init_inkling(const common_chat_template &
|
||||
return blocks;
|
||||
}
|
||||
|
||||
auto tool_choice = p.choice();
|
||||
foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) {
|
||||
const auto & function = tool.at("function");
|
||||
std::string name = function.at("name");
|
||||
|
||||
auto open = p.tool_name(p.literal(name)) + p.literal(TOOL_JSON) + p.literal("{\"name\":" + json(name).dump() + ",\"args\":");
|
||||
auto args = p.tool_args(p.json());
|
||||
|
||||
tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(p.tool_open(open) + args + p.tool_close(p.literal("}")) + end));
|
||||
});
|
||||
|
||||
// tool calls are the last blocks of the turn
|
||||
auto calls = inputs.parallel_tool_calls ? tool_choice + p.zero_or_more(header + tool_choice) : tool_choice;
|
||||
auto tool_calls = header + p.trigger_rule("tool-calls", calls);
|
||||
// the call takes the name in the JSON
|
||||
auto tool_json = p.token(TOOL_JSON);
|
||||
auto tool_body = [&](const common_peg_parser & json_name) {
|
||||
return p.tool_open(p.literal("{")) << p.json_member("name", p.literal("\"") + p.tool_name(json_name) + p.literal("\"")) << p.literal(",")
|
||||
<< p.json_member("args", p.tool_args(p.json())) << p.tool_close(p.literal("}")) + end;
|
||||
};
|
||||
|
||||
if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) {
|
||||
return blocks + tool_calls;
|
||||
auto tool_choice = p.choice();
|
||||
foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) {
|
||||
const auto & function = tool.at("function");
|
||||
std::string name = function.at("name");
|
||||
std::string quoted = json(name).dump();
|
||||
|
||||
// The research model does not generate a tool name before the tool call token
|
||||
auto json_name = p.literal(quoted.substr(1, quoted.size() - 2));
|
||||
tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(p.optional(p.literal(name)) + tool_json + tool_body(json_name)));
|
||||
});
|
||||
|
||||
auto calls = inputs.parallel_tool_calls ? tool_choice + p.zero_or_more(header + tool_choice) : tool_choice;
|
||||
return blocks + header + calls;
|
||||
}
|
||||
|
||||
return blocks + p.optional(tool_calls);
|
||||
auto name = p.until(tool_json);
|
||||
auto body = tool_body(p.string_content('"'));
|
||||
auto next = p.rule("tool-call", header + p.tool(name + tool_json + body));
|
||||
auto more = inputs.parallel_tool_calls ? p.zero_or_more(next) : p.eps();
|
||||
auto calls = header + name + p.trigger_rule("tool-calls", tool_json, body + more);
|
||||
|
||||
return blocks + p.optional(calls);
|
||||
});
|
||||
|
||||
if (has_response_format || use_tools) {
|
||||
data.grammar_lazy = !has_response_format && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
|
||||
data.grammar_lazy = false;
|
||||
data.grammar = build_grammar([&](const common_grammar_builder & builder) {
|
||||
data.parser.build_grammar(builder, data.grammar_lazy);
|
||||
data.parser.build_grammar(builder, !has_response_format && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO);
|
||||
});
|
||||
|
||||
if (data.grammar_lazy) {
|
||||
// a header followed by text and not by a content token is a tool call, the grammar starts at the name
|
||||
data.grammar_triggers = {
|
||||
{ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "<\\|message_model\\|>([^<])" },
|
||||
};
|
||||
// Inkling 1: the first header is in the generation prompt, and a lazy grammar does not get the prompt.
|
||||
// an output that starts with no content token is a tool call. not for a continuation, it starts with text
|
||||
if (!inputs.has_continuation()) {
|
||||
data.grammar_triggers.push_back({ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL, "[^<]+" });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
|
||||
+139
-7
@@ -1140,8 +1140,8 @@ protected:
|
||||
llama_set_causal_attn(ctx_dft, causal_attn); // DFlash needs non-causal attention unless the model says otherwise
|
||||
}
|
||||
|
||||
// only LiliCorr uses this, to keep the context features for its scorer; the other heads only need the KV cache
|
||||
// called after the host copy injection of a chunk, while h_nextn still holds the context features of batch_inject
|
||||
// LiliCorr and the Inkling2 DSpark keep context features from h_nextn; the other heads only need the KV cache
|
||||
// called after the injection of a chunk, while h_nextn still holds the context features of batch_inject
|
||||
virtual void store_context_features(llama_seq_id /*seq_id*/, int32_t /*n_chunk*/) {}
|
||||
|
||||
public:
|
||||
@@ -1245,6 +1245,7 @@ public:
|
||||
__func__, rc, (int) n_chunk, (int) offset);
|
||||
return false;
|
||||
}
|
||||
store_context_features(seq_id, n_chunk);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1374,6 +1375,19 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im
|
||||
// bonus anchor (SpecForge exports) when false: slot 0 is a bonus token, not a prediction slot
|
||||
bool sample_from_anchor = true;
|
||||
|
||||
// the Markov head reads the context state of the last committed token (Inkling2 f_rnn)
|
||||
// it comes back from the injection as h_nextn, kept for the last ctx_rows positions of each sequence
|
||||
bool has_markov_context = false;
|
||||
size_t ctx_rows = 0;
|
||||
std::vector<float> ctx_embd;
|
||||
std::vector<llama_pos> ctx_pos;
|
||||
|
||||
// per-token state of the block tokens, n_embd_dec wide: the context state on the anchor row, [uniform | 1/temp] on the draft rows, see llama_batch_ext_select_n_embd_state
|
||||
// with probabilistic drafting the graph draws each block token from it and returns [token, k, ids, probs] in h_nextn
|
||||
std::vector<float> block_state;
|
||||
std::vector<std::mt19937> draw_rng;
|
||||
std::vector<int64_t> draw_seed; // the seed each generator was last seeded with (-1: reseed)
|
||||
|
||||
common_speculative_impl_draft_dspark(const common_params_speculative & params, uint32_t n_seq)
|
||||
: common_speculative_impl_draft_dflash(params, n_seq, COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK)
|
||||
{
|
||||
@@ -1384,6 +1398,18 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im
|
||||
if (llama_model_meta_val_str(model_dft, "dflash.sample_from_anchor", buf, sizeof(buf)) >= 0) {
|
||||
sample_from_anchor = std::strcmp(buf, "true") == 0;
|
||||
}
|
||||
if (llama_model_meta_val_str(model_dft, "dflash.has_markov_context", buf, sizeof(buf)) >= 0) {
|
||||
has_markov_context = std::strcmp(buf, "true") == 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (has_markov_context) {
|
||||
ctx_rows = (size_t) block_size + 1;
|
||||
ctx_embd.resize((size_t) n_seq * ctx_rows * (size_t) n_embd_dec);
|
||||
ctx_pos.assign((size_t) n_seq * ctx_rows, -1);
|
||||
block_state.reserve((size_t) n_seq * block_size * n_embd_dec);
|
||||
draw_rng.resize(n_seq);
|
||||
draw_seed.assign(n_seq, -1);
|
||||
}
|
||||
|
||||
if (this->params.p_min > 0.0f) {
|
||||
@@ -1396,17 +1422,59 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im
|
||||
}
|
||||
}
|
||||
|
||||
LOG_INF("%s: - sample_from_anchor=%s\n", __func__, sample_from_anchor ? "true" : "false");
|
||||
LOG_INF("%s: - sample_from_anchor=%s, has_markov_context=%s\n", __func__,
|
||||
sample_from_anchor ? "true" : "false", has_markov_context ? "true" : "false");
|
||||
|
||||
// anchor-first DSpark yields a full block_size draft tokens
|
||||
// the context state is read back from h_nextn at every injected row
|
||||
init({
|
||||
/* .n_draft_max = */ sample_from_anchor ? block_size : block_size - 1,
|
||||
/* .backend_sampling = */ true,
|
||||
/* .dev_features = */ true,
|
||||
/* .nextn_masked = */ true,
|
||||
/* .nextn_masked = */ !has_markov_context,
|
||||
});
|
||||
}
|
||||
|
||||
protected:
|
||||
void store_context_features(llama_seq_id seq_id, int32_t n_chunk) override {
|
||||
if (!has_markov_context) {
|
||||
return;
|
||||
}
|
||||
const float * state = llama_get_embeddings_nextn(params.ctx_dft);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
const llama_pos pos_min = std::max(0, batch_inject.tokens.back().pos[0] - block_size);
|
||||
for (int32_t i = 0; i < n_chunk; ++i) {
|
||||
const llama_pos pos = batch_inject.tokens[i].pos[0];
|
||||
if (pos < pos_min) {
|
||||
continue;
|
||||
}
|
||||
const size_t slot = (size_t) seq_id * ctx_rows + (size_t) pos % ctx_rows;
|
||||
std::memcpy(ctx_embd.data() + slot * (size_t) n_embd_dec, state + (size_t) i * n_embd_dec, (size_t) n_embd_dec * sizeof(float));
|
||||
ctx_pos[slot] = pos;
|
||||
}
|
||||
}
|
||||
|
||||
// context state of the token before the block, nullptr if it was not injected
|
||||
const float * get_context_state(llama_seq_id seq_id, llama_pos pos) const {
|
||||
if (pos < 0) {
|
||||
return nullptr;
|
||||
}
|
||||
const size_t slot = (size_t) seq_id * ctx_rows + (size_t) pos % ctx_rows;
|
||||
return ctx_pos[slot] == pos ? ctx_embd.data() + slot * (size_t) n_embd_dec : nullptr;
|
||||
}
|
||||
|
||||
public:
|
||||
void begin(llama_seq_id seq_id, const llama_tokens & prompt) override {
|
||||
// the markov context draws: reseed per request rather than per round, or two identical requests differ
|
||||
if (has_markov_context && seq_id >= 0 && seq_id < (llama_seq_id) n_seq) {
|
||||
draw_seed[seq_id] = -1;
|
||||
}
|
||||
|
||||
common_speculative_impl_draft_dflash::begin(seq_id, prompt);
|
||||
}
|
||||
|
||||
void draft(common_speculative_draft_params_vec & dparams) override {
|
||||
auto & ctx_dft = params.ctx_dft;
|
||||
|
||||
@@ -1416,6 +1484,9 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im
|
||||
// record where each block starts and its size
|
||||
std::vector<int32_t> i_block_beg(n_seq, -1);
|
||||
std::vector<int32_t> n_block (n_seq, 0);
|
||||
std::vector<bool> sampled (n_seq, false);
|
||||
|
||||
block_state.clear();
|
||||
|
||||
for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) {
|
||||
auto & dp = dparams[seq_id];
|
||||
@@ -1423,16 +1494,53 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im
|
||||
continue;
|
||||
}
|
||||
|
||||
// the Markov head reads the context state of the token before the block, no draft without it
|
||||
const float * state = has_markov_context ? get_context_state(seq_id, dp.pos0 - 1) : nullptr;
|
||||
if (has_markov_context && !state) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// the graph draws the block at the target's temperature, the verifier then does rejection sampling with q
|
||||
sampled[seq_id] = has_markov_context && params.probabilistic && dp.result_q && dp.temp > 0.0f;
|
||||
if (sampled[seq_id] && draw_seed[seq_id] != dp.seed) {
|
||||
draw_seed[seq_id] = dp.seed;
|
||||
// the default seed means random; mixed so it differs from the target's, as in spec_retune
|
||||
draw_rng[seq_id].seed(dp.seed == LLAMA_DEFAULT_SEED ? std::random_device{}() : dp.seed ^ 0x85ebca6bu);
|
||||
}
|
||||
|
||||
common_sampler_reset(smpls[seq_id].get());
|
||||
|
||||
const int32_t n = (int32_t) dp.pos0;
|
||||
|
||||
const int32_t n_draft = params.n_max;
|
||||
const int32_t n_block_tokens = n_draft + (sample_from_anchor ? 0 : 1);
|
||||
|
||||
// all blocks share one decode: a block that does not fit in the draft context fails every sequence's draft
|
||||
if ((uint64_t) dp.pos0 + n_block_tokens > llama_n_ctx_seq(ctx_dft)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
i_block_beg[seq_id] = batch.size();
|
||||
n_block [seq_id] = n_block_tokens;
|
||||
for (int32_t i = 0; i < n_block_tokens; ++i) {
|
||||
batch.add(i == 0 ? dp.id_last : mask_token_id, n + i, seq_id, true);
|
||||
const int32_t idx = batch.add(i == 0 ? dp.id_last : mask_token_id, n + i, seq_id, true);
|
||||
if (state) {
|
||||
// reserved up front, so the views of the earlier tokens stay valid
|
||||
GGML_ASSERT(block_state.size() + n_embd_dec <= block_state.capacity());
|
||||
float * row = block_state.data() + block_state.size();
|
||||
if (i == 0) {
|
||||
block_state.insert(block_state.end(), state, state + n_embd_dec);
|
||||
} else {
|
||||
block_state.resize(block_state.size() + n_embd_dec, 0.0f);
|
||||
if (sampled[seq_id]) {
|
||||
// u in [0, 1): a draw in double can round up to 1 in float
|
||||
const float u = (float) std::uniform_real_distribution<double>(0.0, 1.0)(draw_rng[seq_id]);
|
||||
row[0] = std::min(u, std::nextafter(1.0f, 0.0f));
|
||||
row[1] = 1.0f / dp.temp;
|
||||
}
|
||||
}
|
||||
batch.set_embd_state(idx, { row, 1, (size_t) n_embd_dec });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1460,10 +1568,34 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im
|
||||
|
||||
auto & result = *dp.result;
|
||||
|
||||
// DSpark: read from the first draft slot, truncate below the confidence threshold
|
||||
const float * conf = params.p_min > 0.0f ? llama_get_embeddings_nextn(ctx_dft) : nullptr;
|
||||
// bonus-anchor drafts read the mask positions only, like DFlash
|
||||
const int32_t i_draft_beg = sample_from_anchor ? 0 : 1;
|
||||
|
||||
if (sampled[seq_id]) {
|
||||
// the tokens the graph drew, and the distribution q each one was drawn from
|
||||
const float * draws = llama_get_embeddings_nextn(ctx_dft);
|
||||
GGML_ASSERT(draws && "DSpark draws missing from h_nextn");
|
||||
for (int32_t i = i_draft_beg; i < n_block_tokens; ++i) {
|
||||
const float * row = draws + (size_t) (beg + i) * n_embd_dec;
|
||||
const int32_t n_cand = (int32_t) row[1];
|
||||
|
||||
auto & q = dp.result_q->emplace_back();
|
||||
q.reserve(n_cand);
|
||||
for (int32_t k = 0; k < n_cand; ++k) {
|
||||
const float p = row[2 + n_cand + k];
|
||||
q.push_back({ (llama_token) row[2 + k], std::log(p), p });
|
||||
}
|
||||
result.push_back((llama_token) row[0]);
|
||||
}
|
||||
if (result.size() < (size_t) params.n_min) {
|
||||
result.clear();
|
||||
dp.result_q->clear();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// DSpark: read from the first draft slot, truncate below the confidence threshold
|
||||
const float * conf = params.p_min > 0.0f ? llama_get_embeddings_nextn(ctx_dft) : nullptr;
|
||||
for (int32_t i = i_draft_beg; i < n_block_tokens; ++i) {
|
||||
const int32_t idx = beg + i;
|
||||
|
||||
|
||||
@@ -146,6 +146,7 @@ TEXT_MODEL_MAP: dict[str, str] = {
|
||||
"HrmTextForCausalLM": "hrm_text",
|
||||
"HYV3ForCausalLM": "hunyuan",
|
||||
"HYV4ForCausalLM": "hy_v4",
|
||||
"HYV4FlashForCausalLM": "hy_v4_flash",
|
||||
"IQuestCoderForCausalLM": "llama",
|
||||
"Inkling2ForCausalLM": "inkling2",
|
||||
"Inkling2LoopForCausalLM": "inkling2",
|
||||
@@ -307,6 +308,7 @@ TEXT_MODEL_MAP: dict[str, str] = {
|
||||
"RWForCausalLM": "falcon",
|
||||
"RWKV6Qwen2ForCausalLM": "rwkv",
|
||||
"RWKV7ForCausalLM": "rwkv",
|
||||
"Raon1MiniForCausalLM": "raon1_mini",
|
||||
"RobertaForSequenceClassification": "bert",
|
||||
"RobertaModel": "bert",
|
||||
"RuGPT3XLForCausalLM": "gpt2",
|
||||
@@ -390,6 +392,8 @@ MMPROJ_MODEL_MAP: dict[str, str] = {
|
||||
"GraniteSpeechPlusForConditionalGeneration": "granite",
|
||||
"HiggsAudio3Model": "higgs_audio",
|
||||
"HunYuanVLForConditionalGeneration": "hunyuan",
|
||||
"HYV4FlashForCausalLM": "hy_v4_flash",
|
||||
"HYV4FlashForConditionalGeneration": "hy_v4_flash",
|
||||
"Idefics3ForConditionalGeneration": "smolvlm",
|
||||
"Inkling2ForConditionalGeneration": "inkling2",
|
||||
"Inkling2LoopForConditionalGeneration": "inkling2",
|
||||
|
||||
+91
-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)
|
||||
|
||||
@@ -2473,6 +2548,9 @@ class TextModel(ModelBase):
|
||||
if chkhsh == "32d85c31273f8019248f2559fed492d929ea28b17e51d81d3bb36fff23ca72b3":
|
||||
# ref: https://huggingface.co/domyn/Domyn-Edge-Teacher-IF
|
||||
res = "domyn-edge"
|
||||
if chkhsh == "ffdae2f611dc6903980be2fbb108467cb97376d7d03cd332bb7e2602f87fa1f1":
|
||||
# ref: https://huggingface.co/KRAFTON/Raon-1-mini-preview
|
||||
res = "raon"
|
||||
|
||||
if res is None:
|
||||
logger.warning("\n")
|
||||
|
||||
+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):
|
||||
|
||||
@@ -0,0 +1,650 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Callable, Iterable, cast
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from .base import LazyTorchTensor, MmprojModel, ModelBase, gguf, logger
|
||||
from .deepseek41 import _StreamedBytes
|
||||
from .hy_v4 import HYV4Model
|
||||
|
||||
# the reference derives the hash multipliers from the Engram seed, the 1-based layer id and the compressed vocab size
|
||||
ENGRAM_SEED_STRIDE = 10007
|
||||
|
||||
|
||||
@ModelBase.register("HYV4FlashForCausalLM", "HYV4FlashForConditionalGeneration")
|
||||
@ModelBase.example("tencent/Hy4-Flash")
|
||||
class HYV4FlashModel(HYV4Model):
|
||||
"""hy_v4 with sparse and sliding-window MLA layers, sandwich norms, latent routed experts, Engram and a k-pool indexer.
|
||||
|
||||
The MTP draft block is exported as one extra sparse layer. The vision tower and the dfly draft layers are not converted.
|
||||
"""
|
||||
|
||||
model_arch = gguf.MODEL_ARCH.HY_V4_FLASH
|
||||
|
||||
# the draft block is exported under block ids past the trunk, which skip_mtp would drop
|
||||
skip_mtp = False
|
||||
|
||||
# dropped subsystems, see the class docstring
|
||||
DROP_PREFIXES = ("vit.", "model.dfly_layers.")
|
||||
DROP_SUBSTRINGS = ()
|
||||
|
||||
# the released config renamed sparse_attention, both name the same layer type
|
||||
SPARSE_TYPES = ("sparse_attention", "deepseek_sparse_attention")
|
||||
|
||||
# the released checkpoints ship the token map as a tensor instead of engram_vocab_map.npz
|
||||
ENGRAM_LOOKUP_TABLE = "lookup_table"
|
||||
|
||||
# compressed_indexer tail -> the tensor the graph reads it as
|
||||
INDEXER_MAP = {
|
||||
"token_key_projection.weight": gguf.MODEL_TENSOR.INDEXER_ATTN_K,
|
||||
"token_key_norm.weight": gguf.MODEL_TENSOR.INDEXER_K_NORM,
|
||||
"key_value_projection.weight": gguf.MODEL_TENSOR.INDEXER_KPOOL_VALUE,
|
||||
"key_gate_projection.weight": gguf.MODEL_TENSOR.INDEXER_KPOOL_GATE,
|
||||
"intra_group_ape": gguf.MODEL_TENSOR.INDEXER_KPOOL_APE,
|
||||
"key_norm.weight": gguf.MODEL_TENSOR.INDEXER_COMPRESSOR_NORM,
|
||||
"query_projection.weight": gguf.MODEL_TENSOR.INDEXER_ATTN_Q_B,
|
||||
"head_weight_projection.weight": gguf.MODEL_TENSOR.INDEXER_PROJ,
|
||||
}
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
# the draft block is an extra block, the loader subtracts the nextn count from block_count
|
||||
if not getattr(self, "no_mtp", False):
|
||||
self.block_count += self._n_nextn()
|
||||
self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count)
|
||||
# Engram weights arrive one at a time but are written fused, so they wait here
|
||||
self._engram_buf: dict[int, dict[str, torch.Tensor]] = {}
|
||||
self._engram_tables: dict[int, torch.Tensor] = {}
|
||||
self._engram_done: set[str] = set()
|
||||
|
||||
@classmethod
|
||||
def filter_tensors(cls, item):
|
||||
name = item[0]
|
||||
if name.startswith(cls.DROP_PREFIXES) or any(s in name for s in cls.DROP_SUBSTRINGS):
|
||||
return None
|
||||
if name.startswith("model.mtp_layers."):
|
||||
# hy_v4 drops the draft block; this model exports it, so skip that filter
|
||||
return super(HYV4Model, cls).filter_tensors(item)
|
||||
return super().filter_tensors(item)
|
||||
|
||||
def _layer_types(self) -> list[str]:
|
||||
cached = getattr(self, "_layer_types_cache", None)
|
||||
if cached is not None:
|
||||
return cached
|
||||
layer_types = self.hparams.get("layer_types")
|
||||
n_layer = self.hparams["num_hidden_layers"]
|
||||
if not layer_types or len(layer_types) < n_layer:
|
||||
raise ValueError("HY_V4_FLASH needs a layer_types entry per layer")
|
||||
unknown = set(layer_types[:n_layer]) - set(self.SPARSE_TYPES) - {"sliding_attention"}
|
||||
if unknown:
|
||||
raise ValueError(f"HY_V4_FLASH unknown layer_types values: {sorted(unknown)}")
|
||||
# the released config renamed the sparse layers, normalize so the rest reads one name
|
||||
self._layer_types_cache = ["sparse_attention" if t in self.SPARSE_TYPES else t for t in layer_types[:n_layer]]
|
||||
return self._layer_types_cache
|
||||
|
||||
# Engram: one n-gram hash module per Engram layer, all buckets in one table as in deepseek41
|
||||
|
||||
def _engram_enabled(self) -> bool:
|
||||
# engram_enable is optional, a False turns Engram off
|
||||
return bool(self.hparams.get("engram_enable", True)) and bool(self.hparams.get("engram_layer_ids"))
|
||||
|
||||
def _engram_ids(self) -> list[int]:
|
||||
"""engram_layer_ids, 1-based and sorted."""
|
||||
ids = sorted(int(i) for i in self.hparams["engram_layer_ids"])
|
||||
n_layer = self.hparams["num_hidden_layers"]
|
||||
for i in ids:
|
||||
# 1-based: the tensors live at model.layers.{i-1}.engram_layer.*
|
||||
if not 1 <= i <= n_layer:
|
||||
raise ValueError(f"HY_V4_FLASH engram_layer_ids has {i}, outside 1..{n_layer}")
|
||||
return ids
|
||||
|
||||
def _engram_primes(self) -> dict[int, list[int]]:
|
||||
"""Per 1-based layer id, the flattened [ngram][head] bucket counts."""
|
||||
raw = self.hparams.get("engram_layer_head_vocab_sizes") or {}
|
||||
n_gram = self.hparams["engram_max_ngram_size"]
|
||||
n_head = self.hparams["engram_n_head_per_ngram"]
|
||||
out = {}
|
||||
for i in self._engram_ids():
|
||||
# the keys are strings in the config
|
||||
groups = raw.get(str(i)) or raw.get(i)
|
||||
if groups is None:
|
||||
raise ValueError(f"HY_V4_FLASH engram_layer_head_vocab_sizes has no entry for layer {i}")
|
||||
if len(groups) != n_gram - 1 or any(len(g) != n_head for g in groups):
|
||||
raise ValueError(
|
||||
f"HY_V4_FLASH engram layer {i}: expected {n_gram - 1} groups of {n_head} bucket "
|
||||
f"counts, got {[len(g) for g in groups]}")
|
||||
out[i] = [int(p) for g in groups for p in g]
|
||||
return out
|
||||
|
||||
def _engram_lookup_names(self) -> list[str]:
|
||||
"""The lookup_table tensor of every Engram layer, empty when the checkpoint carries the npz instead."""
|
||||
names = [f"model.layers.{i - 1}.engram_layer.{self.ENGRAM_LOOKUP_TABLE}" for i in self._engram_ids()]
|
||||
present = [n for n in names if n in self.model_tensors]
|
||||
if present and len(present) != len(names):
|
||||
raise ValueError(f"HY_V4_FLASH engram is missing the lookup table of {sorted(set(names) - set(present))}")
|
||||
return present
|
||||
|
||||
def _engram_vocab_map(self) -> tuple[list[int], int]:
|
||||
"""The token -> compressed id map, extended by identity as the reference does, and the compressed vocab size."""
|
||||
names = self._engram_lookup_names()
|
||||
if names:
|
||||
table = LazyTorchTensor.to_eager(self.model_tensors[names[0]]()).numpy().astype(np.int64)
|
||||
for other in names[1:]:
|
||||
if not np.array_equal(LazyTorchTensor.to_eager(self.model_tensors[other]()).numpy().astype(np.int64), table):
|
||||
raise ValueError(f"HY_V4_FLASH engram lookup table of {other} differs from {names[0]}")
|
||||
# the map is onto a dense id range from 0, so its largest id gives the compressed vocab size
|
||||
compressed = int(table.max()) + 1
|
||||
if int(table.min()) != 0 or len(np.unique(table)) != compressed:
|
||||
raise ValueError("HY_V4_FLASH engram lookup table is not a dense id range from 0, supply engram_vocab_map.npz")
|
||||
else:
|
||||
path = Path(self.dir_model) / "engram_vocab_map.npz"
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(f"HY_V4_FLASH engram needs a lookup_table tensor or {path}")
|
||||
with np.load(path) as z:
|
||||
table = z["lookup_table"].astype(np.int64)
|
||||
meta = json.loads(bytes(z["metadata"]).decode("utf-8").rstrip("\x00"))
|
||||
|
||||
compressed = int(meta["compressed_vocab_size"])
|
||||
if int(table.max()) + 1 > compressed:
|
||||
raise ValueError("HY_V4_FLASH engram lookup table exceeds its compressed vocab size")
|
||||
if int(meta["engram_seed"]) != int(self.hparams.get("engram_seed", 0)):
|
||||
raise ValueError("HY_V4_FLASH engram seed disagrees between the config and the vocab map")
|
||||
|
||||
n_vocab = self.hparams["vocab_size"]
|
||||
token_map = list(map(int, table))
|
||||
token_map += list(range(len(token_map), n_vocab))
|
||||
return token_map, compressed
|
||||
|
||||
def _engram_multipliers(self, layer_id: int, compressed: int) -> list[int]:
|
||||
seed = int(self.hparams.get("engram_seed", 0))
|
||||
n_gram = self.hparams["engram_max_ngram_size"]
|
||||
bound = max(1, (np.iinfo(np.int64).max // compressed) // 2)
|
||||
rng = np.random.default_rng(seed + ENGRAM_SEED_STRIDE * layer_id)
|
||||
return [int(m) for m in rng.integers(0, bound, size=n_gram) * 2 + 1]
|
||||
|
||||
def _engram_set_gguf_parameters(self):
|
||||
hparams = self.hparams
|
||||
ids = self._engram_ids()
|
||||
primes = self._engram_primes()
|
||||
token_map, compressed = self._engram_vocab_map()
|
||||
|
||||
n_gram = hparams["engram_max_ngram_size"]
|
||||
n_head = hparams["engram_n_head_per_ngram"]
|
||||
head_dim, rem = divmod(hparams["engram_n_embed_per_ngram"], n_head)
|
||||
if rem:
|
||||
raise ValueError("HY_V4_FLASH engram_n_embed_per_ngram is not a multiple of the head count")
|
||||
|
||||
# rebase each module's buckets into the shared table, row ids are int32
|
||||
offsets: list[int] = []
|
||||
multipliers: list[int] = []
|
||||
base = 0
|
||||
for i in ids:
|
||||
for p in primes[i]:
|
||||
offsets.append(base)
|
||||
base += p
|
||||
multipliers += self._engram_multipliers(i, compressed)
|
||||
if base > np.iinfo(np.int32).max:
|
||||
raise ValueError(f"HY_V4_FLASH engram table needs {base} rows, past the int32 row id limit")
|
||||
|
||||
w = self.gguf_writer
|
||||
w.add_ple_layers([i - 1 for i in ids])
|
||||
w.add_ple_ngram_size(n_gram)
|
||||
w.add_ple_heads_per_ngram(n_head)
|
||||
w.add_embedding_length_per_layer_input(head_dim)
|
||||
w.add_ple_layer_multipliers(multipliers)
|
||||
w.add_ple_head_offsets(offsets)
|
||||
w.add_ple_head_vocab_sizes([p for i in ids for p in primes[i]])
|
||||
w.add_engram_pad_token_id(hparams["engram_pad_id"])
|
||||
w.add_engram_token_map(token_map)
|
||||
|
||||
logger.info(
|
||||
"HY_V4_FLASH engram: %d module(s) at 0-based layers %s, %d-gram x %d heads x %d dims, "
|
||||
"%d table rows, compressed vocab %d",
|
||||
len(ids), [i - 1 for i in ids], n_gram, n_head, head_dim, base, compressed)
|
||||
|
||||
def _n_nextn(self) -> int:
|
||||
return int(self.hparams.get("num_nextn_predict_layers", 0) or 0)
|
||||
|
||||
def _layer_type_of(self, bid: int) -> str:
|
||||
"""Layer type of any block, draft blocks included. Only sparse draft blocks are supported."""
|
||||
n_layer = self.hparams["num_hidden_layers"]
|
||||
if bid < n_layer:
|
||||
return self._layer_types()[bid]
|
||||
|
||||
types = self.hparams.get("mtp_layer_types") or []
|
||||
if not types:
|
||||
return "sparse_attention"
|
||||
|
||||
t = types[min(bid - n_layer, len(types) - 1)]
|
||||
if t != "sparse_attention":
|
||||
raise ValueError(
|
||||
f"HY_V4_FLASH: mtp_layer_types gives {t!r} for draft block {bid}, "
|
||||
"but only 'sparse_attention' draft blocks are supported")
|
||||
return t
|
||||
|
||||
def _write_rope_sections(self, sparse_rope: dict, window_rope: dict):
|
||||
"""Write the M-RoPE sections of the VL checkpoints. Text-only files keep the loader default."""
|
||||
sections = sparse_rope.get("mrope_section")
|
||||
if sections is None:
|
||||
return
|
||||
if window_rope.get("mrope_section") != sections:
|
||||
raise ValueError(
|
||||
f"HY_V4_FLASH needs one mrope_section for both layer types, but "
|
||||
f"{window_rope.get('mrope_section')} != {sections}")
|
||||
if not sparse_rope.get("mrope_interleaved", False):
|
||||
raise NotImplementedError("HY_V4_FLASH expects mrope_interleaved = true")
|
||||
|
||||
rope_dim = self.hparams["qk_rope_head_dim"]
|
||||
if len(sections) != 3 or 2 * sum(sections) != rope_dim:
|
||||
raise ValueError(f"HY_V4_FLASH mrope_section {sections} must sum to qk_rope_head_dim / 2")
|
||||
|
||||
self.gguf_writer.add_rope_dimension_sections(list(sections) + [0])
|
||||
|
||||
def _rope_for(self, layer_type: str) -> dict:
|
||||
params = self.hparams.get("rope_parameters")
|
||||
names = self.SPARSE_TYPES if layer_type == "sparse_attention" else (layer_type,)
|
||||
found = [params[n] for n in names if isinstance(params, dict) and n in params]
|
||||
if not found:
|
||||
raise ValueError(f"HY_V4_FLASH needs rope_parameters[{layer_type!r}]")
|
||||
if any(f != found[0] for f in found[1:]):
|
||||
raise ValueError(f"HY_V4_FLASH has conflicting rope_parameters for {names}")
|
||||
return found[0]
|
||||
|
||||
def set_gguf_parameters(self):
|
||||
hparams = self.hparams
|
||||
layer_types = self._layer_types()
|
||||
is_swa = [t == "sliding_attention" for t in layer_types]
|
||||
|
||||
if not any(is_swa) or all(is_swa):
|
||||
raise ValueError("HY_V4_FLASH expects a mix of sparse and sliding attention layers")
|
||||
|
||||
# the graph always applies the sandwich post-norms
|
||||
if not hparams.get("sandwich_norm", False):
|
||||
raise ValueError("HY_V4_FLASH expects sandwich_norm, the graph always applies the post-norms")
|
||||
if hparams.get("dsa_skip_attn_post_norm", False):
|
||||
raise ValueError(
|
||||
"HY_V4_FLASH: dsa_skip_attn_post_norm is not supported - the graph applies "
|
||||
"attn_post_norm on the sparse layers too")
|
||||
|
||||
# the non-sliding rope entry is keyed "sparse_attention", not "full_attention" as the base expects
|
||||
sparse_rope = self._rope_for("sparse_attention")
|
||||
window_rope = self._rope_for("sliding_attention")
|
||||
|
||||
# hide the key from hy_v4, which warns that it drops the draft block
|
||||
n_nextn = self.hparams.pop("num_nextn_predict_layers", None)
|
||||
try:
|
||||
super().set_gguf_parameters()
|
||||
finally:
|
||||
if n_nextn is not None:
|
||||
self.hparams["num_nextn_predict_layers"] = n_nextn
|
||||
|
||||
self.gguf_writer.add_rope_freq_base(sparse_rope["rope_theta"])
|
||||
|
||||
# the graph reorders the rope rows itself, so the sections only say how to split them
|
||||
self._write_rope_sections(sparse_rope, window_rope)
|
||||
|
||||
# per-layer head count: the window layers carry swa_num_attention_heads
|
||||
n_head = hparams["num_attention_heads"]
|
||||
n_head_swa = hparams["swa_num_attention_heads"]
|
||||
self.gguf_writer.remove_key(
|
||||
gguf.Keys.Attention.HEAD_COUNT.format(arch=self.gguf_writer.arch))
|
||||
# the arrays cover n_layer_all, the draft block is a sparse layer
|
||||
is_swa_all = is_swa + [False] * (0 if getattr(self, "no_mtp", False) else self._n_nextn())
|
||||
self.gguf_writer.add_head_count(
|
||||
[n_head_swa if swa else n_head for swa in is_swa_all])
|
||||
|
||||
# the base already derives rope.freq_base_swa from rope_parameters["sliding_attention"]
|
||||
self.gguf_writer.add_sliding_window(hparams["sliding_window"])
|
||||
self.gguf_writer.add_sliding_window_pattern(is_swa_all)
|
||||
|
||||
# routed experts run here, the router and the shared expert stay at hidden_size
|
||||
latent = hparams.get("routed_expert_hidden_size")
|
||||
if latent:
|
||||
self.gguf_writer.add_expert_latent_length(latent)
|
||||
|
||||
if self._n_nextn() and not getattr(self, "no_mtp", False):
|
||||
self.gguf_writer.add_nextn_predict_layers(self._n_nextn())
|
||||
|
||||
if self._indexer_enabled():
|
||||
# the pool size is compress_ratio, and the current group is always kept
|
||||
ratio = hparams["compressed_indexer_compress_ratio"]
|
||||
self.gguf_writer.add_indexer_kpool(ratio)
|
||||
self.gguf_writer.add_indexer_kpool_select_tail(True)
|
||||
|
||||
# same check as the reference
|
||||
group_topk = hparams.get("compressed_indexer_group_topk")
|
||||
candidate = hparams.get("compressed_indexer_candidate_topk")
|
||||
if group_topk and candidate and group_topk * ratio != candidate:
|
||||
raise ValueError(
|
||||
f"HY_V4_FLASH indexer: candidate_topk {candidate} != "
|
||||
f"group_topk {group_topk} x compress_ratio {ratio}")
|
||||
if hparams["index_topk"] % ratio:
|
||||
raise ValueError(
|
||||
f"HY_V4_FLASH indexer: index_topk {hparams['index_topk']} is not a multiple "
|
||||
f"of compress_ratio {ratio}")
|
||||
is_full = self.indexer_is_full() or []
|
||||
logger.info(
|
||||
"HY_V4_FLASH indexer: %d pooled groups of %d, keeping the best %d plus the current group (index_topk %d)",
|
||||
sum(is_full), ratio, hparams["index_topk"] // ratio, hparams["index_topk"])
|
||||
|
||||
if self._engram_enabled():
|
||||
self._engram_set_gguf_parameters()
|
||||
|
||||
self._check_mla_geometry()
|
||||
|
||||
logger.info(
|
||||
"HY_V4_FLASH: %d sparse (%d heads, rope_theta %g) + %d sliding "
|
||||
"(%d heads, rope_theta %g, window %d) layers",
|
||||
is_swa.count(False), n_head, sparse_rope["rope_theta"],
|
||||
is_swa.count(True), n_head_swa, window_rope["rope_theta"],
|
||||
hparams["sliding_window"],
|
||||
)
|
||||
if hparams.get("engram_layer_ids") and not self._engram_enabled():
|
||||
logger.warning(
|
||||
"HY_V4_FLASH: engram_enable is off, dropping %d Engram layer(s)",
|
||||
len(hparams["engram_layer_ids"]))
|
||||
if hparams.get("use_compressed_indexer") and not self._indexer_enabled():
|
||||
logger.warning(
|
||||
"HY_V4_FLASH: dropping the compressed indexer - the sparse layers will "
|
||||
"attend their whole context instead of the top %s tokens",
|
||||
hparams.get("index_topk"),
|
||||
)
|
||||
|
||||
def _check_mla_geometry(self):
|
||||
"""Both layer types must share one MLA geometry, only the head count may differ."""
|
||||
hparams = self.hparams
|
||||
for sparse_key, window_key in (
|
||||
("qk_nope_head_dim", "swa_qk_nope_head_dim"),
|
||||
("qk_rope_head_dim", "swa_qk_rope_head_dim"),
|
||||
("v_head_dim", "swa_v_head_dim"),
|
||||
("qk_head_dim", "swa_qk_head_dim"),
|
||||
("kv_lora_rank", "swa_kv_lora_rank"),
|
||||
):
|
||||
if window_key not in hparams:
|
||||
continue
|
||||
if hparams[window_key] != hparams[sparse_key]:
|
||||
raise NotImplementedError(
|
||||
f"HY_V4_FLASH needs one MLA geometry for both layer types, but "
|
||||
f"{window_key}={hparams[window_key]} != {sparse_key}={hparams[sparse_key]}"
|
||||
)
|
||||
|
||||
def _indexer_enabled(self) -> bool:
|
||||
return bool(self.hparams.get("use_dsa")) and bool(self.hparams.get("use_compressed_indexer"))
|
||||
|
||||
def indexer_is_full(self) -> list[bool] | None:
|
||||
"""Which layers own a k-pool indexer: the sparse ones. The config indexer_types marks every layer."""
|
||||
if not self._indexer_enabled():
|
||||
return None
|
||||
n_all = self.hparams["num_hidden_layers"] + self._n_nextn()
|
||||
return [self._layer_type_of(i) == "sparse_attention" for i in range(n_all)]
|
||||
|
||||
def prepare_tensors(self):
|
||||
"""Check the compressed_indexer tensors instead of hy_v4's self_attn.indexer ones."""
|
||||
self.hparams["num_key_value_heads"] = self.hparams["num_attention_heads"]
|
||||
|
||||
is_full = self.indexer_is_full()
|
||||
if is_full is not None:
|
||||
want = set(self.INDEXER_MAP)
|
||||
n_layer = self.hparams["num_hidden_layers"]
|
||||
present: dict[int, set[str]] = {}
|
||||
for name in self.model_tensors:
|
||||
head, sep, tail = name.partition(".self_attn.compressed_indexer.")
|
||||
if not sep:
|
||||
continue
|
||||
# the draft block carries its own indexer, under a different prefix
|
||||
if head.startswith("model.layers."):
|
||||
present.setdefault(int(head.split(".")[2]), set()).add(tail)
|
||||
elif head.startswith("model.mtp_layers."):
|
||||
present.setdefault(n_layer + int(head.split(".")[2]), set()).add(tail)
|
||||
for il, expect in enumerate(is_full):
|
||||
seen = present.get(il, set())
|
||||
if expect and seen != want:
|
||||
raise ValueError(
|
||||
f"HY_V4_FLASH layer {il} owns an indexer but is missing "
|
||||
f"{sorted(want - seen)}" + (f" and carries unexpected {sorted(seen - want)}"
|
||||
if seen - want else ""))
|
||||
if not expect and seen:
|
||||
raise ValueError(
|
||||
f"HY_V4_FLASH layer {il} owns no indexer but carries {sorted(seen)}")
|
||||
|
||||
# straight to the grandparent: hy_v4's own validation does not apply here
|
||||
super(HYV4Model, self).prepare_tensors()
|
||||
|
||||
if self._engram_enabled():
|
||||
T = gguf.MODEL_TENSOR
|
||||
want = {self.format_tensor_name(T.PER_LAYER_TOKEN_EMBD)}
|
||||
for i in self._engram_ids():
|
||||
for t in (T.ENGRAM_KV, T.ENGRAM_KV_B, T.ENGRAM_GATE, T.ENGRAM_LOOKUP_NORM, T.ENGRAM_HC_SCALE, T.ENGRAM_PRE_GAMMA):
|
||||
want.add(self.format_tensor_name(t, i - 1))
|
||||
if want - self._engram_done:
|
||||
raise ValueError(f"HY_V4_FLASH: incomplete Engram tensors {sorted(want - self._engram_done)}")
|
||||
|
||||
def tensor_force_quant(self, name: str, new_name: str, bid: int | None, n_dims: int):
|
||||
# ggml_add / ggml_mul operands, kept f32 as deepseek41 does for engram_gate
|
||||
if new_name.endswith((".engram_gate.weight", ".engram_kv_b.weight", ".engram_hc_scale.weight")):
|
||||
return gguf.GGMLQuantizationType.F32
|
||||
# the pooled-key position bias is a ggml_add operand too
|
||||
if new_name.endswith(".indexer_compressor_ape.weight"):
|
||||
return gguf.GGMLQuantizationType.F32
|
||||
# the base rule misses the router of the renumbered draft block
|
||||
if new_name.endswith((".ffn_gate_inp.weight", ".ffn_gate_inp_shexp.weight")):
|
||||
return gguf.GGMLQuantizationType.F32
|
||||
return super().tensor_force_quant(name, new_name, bid, n_dims)
|
||||
|
||||
def _engram_modify(self, data_torch: torch.Tensor, name: str,
|
||||
bid: int | None) -> Iterable[tuple[str, torch.Tensor]]:
|
||||
"""Fuse a layer's Engram weights as deepseek41 does, once all parts of a group arrived."""
|
||||
if bid is None:
|
||||
raise ValueError(f"HY_V4_FLASH: engram tensor without a layer id: {name}")
|
||||
|
||||
hc = self.hparams["hc_mult"]
|
||||
n_head = self.hparams["engram_n_head_per_ngram"] * (self.hparams["engram_max_ngram_size"] - 1)
|
||||
|
||||
tail = name.split(".engram_layer.", 1)[1]
|
||||
if tail == self.ENGRAM_LOOKUP_TABLE:
|
||||
# the token map, read through _engram_vocab_map() and written as GGUF metadata
|
||||
return
|
||||
|
||||
buf = self._engram_buf.setdefault(bid, {})
|
||||
buf[tail] = data_torch
|
||||
|
||||
tn = self.format_tensor_name
|
||||
T = gguf.MODEL_TENSOR
|
||||
|
||||
def ready(*names) -> bool:
|
||||
return all(n in buf for n in names)
|
||||
|
||||
def take(*names):
|
||||
return [buf.pop(n) for n in names]
|
||||
|
||||
# hc key projections then the value projection, the order the graph views assume
|
||||
kv_parts = [f"key_projs.{c}.weight" for c in range(hc)] + ["value_proj.weight"]
|
||||
if ready(*kv_parts):
|
||||
yield tn(T.ENGRAM_KV, bid), torch.cat(take(*kv_parts), dim=0)
|
||||
|
||||
kvb_parts = [f"key_projs.{c}.bias" for c in range(hc)] + ["value_proj.bias"]
|
||||
if ready(*kvb_parts):
|
||||
yield tn(T.ENGRAM_KV_B, bid), torch.stack(take(*kvb_parts), dim=0)
|
||||
|
||||
# engram_gate folds the key and query norms, as deepseek41 does
|
||||
gate_parts = [f"norm_key.{c}.weight" for c in range(hc)] + [f"norm_query.{c}.weight" for c in range(hc)]
|
||||
if ready(*gate_parts):
|
||||
parts = take(*gate_parts)
|
||||
yield tn(T.ENGRAM_GATE, bid), torch.stack(
|
||||
[parts[c] * parts[hc + c] for c in range(hc)], dim=0)
|
||||
|
||||
norm_parts = [f"lookup_per_head_norms.{c}.weight" for c in range(n_head)]
|
||||
if ready(*norm_parts):
|
||||
yield tn(T.ENGRAM_LOOKUP_NORM, bid), torch.stack(take(*norm_parts), dim=0)
|
||||
|
||||
scale_parts = [f"unified_per_hc_scales.{c}" for c in range(hc)]
|
||||
if ready(*scale_parts):
|
||||
yield tn(T.ENGRAM_HC_SCALE, bid), torch.stack(take(*scale_parts), dim=0)
|
||||
|
||||
if ready("unified_pre_gamma"):
|
||||
yield tn(T.ENGRAM_PRE_GAMMA, bid), take("unified_pre_gamma")[0]
|
||||
|
||||
# the tables of all modules are concatenated in layer order
|
||||
if ready("multi_head_embedding.embedding.weight"):
|
||||
self._engram_tables[bid] = take("multi_head_embedding.embedding.weight")[0]
|
||||
want = [i - 1 for i in self._engram_ids()]
|
||||
if all(i in self._engram_tables for i in want):
|
||||
self._write_engram_tables([self._engram_tables.pop(i) for i in want])
|
||||
|
||||
def _write_engram_tables(self, tables: list[torch.Tensor]) -> None:
|
||||
# the concatenated tables are ~127 GB in BF16, so they are streamed one table at a time as deepseek41 does
|
||||
f32 = self.ftype == gguf.LlamaFileType.ALL_F32
|
||||
dim = tables[0].shape[1]
|
||||
if any(t.shape[1] != dim for t in tables):
|
||||
raise ValueError("HY_V4_FLASH engram tables differ in width")
|
||||
n_rows = sum(t.shape[0] for t in tables)
|
||||
|
||||
def chunks() -> Iterable[np.ndarray]:
|
||||
while tables:
|
||||
table = LazyTorchTensor.to_eager(tables.pop(0))
|
||||
for r0 in range(0, table.shape[0], 1 << 18):
|
||||
# a copy, so that no chunk still held by the writer keeps the whole table alive
|
||||
rows = (table[r0:r0 + (1 << 18)].float() if f32 else table[r0:r0 + (1 << 18)].bfloat16()).clone()
|
||||
yield rows.view(torch.uint8).numpy()
|
||||
del table, rows
|
||||
|
||||
qt = gguf.GGMLQuantizationType.F32 if f32 else gguf.GGMLQuantizationType.BF16
|
||||
data = cast(np.ndarray, _StreamedBytes((n_rows, dim * (4 if f32 else 2)), chunks))
|
||||
name = self.format_tensor_name(gguf.MODEL_TENSOR.PER_LAYER_TOKEN_EMBD)
|
||||
self.gguf_writer.add_tensor(name, data, raw_dtype=qt)
|
||||
self._engram_done.add(name)
|
||||
|
||||
NEXTN_MAP = {
|
||||
"eh_proj.weight": gguf.MODEL_TENSOR.NEXTN_EH_PROJ,
|
||||
"enorm.weight": gguf.MODEL_TENSOR.NEXTN_ENORM,
|
||||
"hnorm.weight": gguf.MODEL_TENSOR.NEXTN_HNORM,
|
||||
"final_layernorm.weight": gguf.MODEL_TENSOR.NEXTN_SHARED_HEAD_NORM,
|
||||
}
|
||||
|
||||
def modify_tensors(self, data_torch: torch.Tensor, name: str, bid: int | None) -> Iterable[tuple[str, torch.Tensor]]:
|
||||
if name.startswith("model.mtp_layers."):
|
||||
if not self._n_nextn() or getattr(self, "no_mtp", False):
|
||||
return
|
||||
parts = name.split(".", 3)
|
||||
nbid = self.hparams["num_hidden_layers"] + int(parts[2])
|
||||
tail = parts[3]
|
||||
key = self.NEXTN_MAP.get(tail)
|
||||
if key is not None:
|
||||
yield self.format_tensor_name(key, nbid), data_torch
|
||||
return
|
||||
# the rest of the block is an ordinary sparse layer, so re-enter under its block index
|
||||
yield from self.modify_tensors(data_torch, f"model.layers.{nbid}.{tail}", nbid)
|
||||
return
|
||||
|
||||
if ".compressed_indexer." in name:
|
||||
# dropped when the indexer is off, the sparse layers then attend their whole context
|
||||
if not self._indexer_enabled():
|
||||
return
|
||||
tail = name.split(".compressed_indexer.", 1)[1]
|
||||
key = self.INDEXER_MAP.get(tail)
|
||||
if key is None:
|
||||
raise ValueError(f"HY_V4_FLASH: unmapped compressed_indexer tensor {name}")
|
||||
# intra_group_ape [kpool, head_dim] is already ne (head_dim, kpool)
|
||||
yield self.format_tensor_name(key, bid), data_torch
|
||||
return
|
||||
|
||||
if ".engram_layer." in name:
|
||||
if not self._engram_enabled():
|
||||
return
|
||||
for new_name, t in self._engram_modify(data_torch, name, bid):
|
||||
self._engram_done.add(new_name)
|
||||
yield new_name, t
|
||||
return
|
||||
|
||||
# split kv_b_proj with the head count of this layer, the base uses a global one
|
||||
if name.endswith("kv_b_proj.weight") and bid is not None:
|
||||
hparams = self.hparams
|
||||
n_head = (hparams["swa_num_attention_heads"]
|
||||
if self._layer_type_of(bid) == "sliding_attention"
|
||||
else hparams["num_attention_heads"])
|
||||
v_head_dim = hparams["v_head_dim"]
|
||||
qk_nope_head_dim = hparams["qk_nope_head_dim"]
|
||||
|
||||
expected = n_head * (v_head_dim + qk_nope_head_dim)
|
||||
if data_torch.shape[0] != expected:
|
||||
raise ValueError(
|
||||
f"HY_V4_FLASH layer {bid}: {name} has {data_torch.shape[0]} rows, "
|
||||
f"expected {expected} = {n_head} heads x ({qk_nope_head_dim} + {v_head_dim})"
|
||||
)
|
||||
|
||||
kv_b = data_torch.view(n_head, qk_nope_head_dim + v_head_dim, data_torch.shape[-1])
|
||||
k_b, v_b = torch.split(kv_b, [qk_nope_head_dim, v_head_dim], dim=1)
|
||||
k_b = k_b.transpose(1, 2)
|
||||
|
||||
tn = self.format_tensor_name
|
||||
yield from ModelBase.modify_tensors(self, k_b, tn(gguf.MODEL_TENSOR.ATTN_K_B, bid), bid)
|
||||
yield from ModelBase.modify_tensors(self, v_b, tn(gguf.MODEL_TENSOR.ATTN_V_B, bid), bid)
|
||||
return
|
||||
|
||||
yield from super().modify_tensors(data_torch, name, bid)
|
||||
|
||||
|
||||
@ModelBase.register("HYV4FlashForCausalLM", "HYV4FlashForConditionalGeneration")
|
||||
class HYV4FlashVisionModel(MmprojModel):
|
||||
"""Vision tower of HY_V4_FLASH: a SigLIP-shaped encoder with a rmsnorm_mlp_adapter projector.
|
||||
|
||||
Positions come from a learned grid, resampled to the patch grid. The projector merges 2x2 patches with a strided conv2d, runs a 1x1 conv2d and appends a newline embedding to every row.
|
||||
"""
|
||||
|
||||
projector_type = gguf.VisionProjectorType.HY_V4_FLASH
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
assert self.hparams_vision is not None
|
||||
# there is no image_size, the position-embedding grid is max_image_size / patch_size
|
||||
self.hparams_vision["image_size"] = self.hparams_vision.get("max_image_size", 2048)
|
||||
|
||||
def set_gguf_parameters(self):
|
||||
super().set_gguf_parameters()
|
||||
assert self.hparams_vision is not None
|
||||
vcfg = self.hparams_vision
|
||||
projector_type = vcfg.get("projector_type")
|
||||
if projector_type != "rmsnorm_mlp_adapter":
|
||||
raise ValueError(f"unsupported projector_type {projector_type!r}")
|
||||
# the graph implements the plain variant only
|
||||
unsupported = {
|
||||
"use_2d_rope": bool(vcfg.get("use_2d_rope", False)),
|
||||
"cat_extra_token": bool(vcfg.get("cat_extra_token", False)),
|
||||
"use_image_newline_token": not vcfg.get("use_image_newline_token", True),
|
||||
"perceive_post_norm": bool(vcfg.get("perceive_post_norm", False)),
|
||||
"hidden_act": vcfg.get("hidden_act", "gelu") != "gelu",
|
||||
"interpolate_mode": vcfg.get("interpolate_mode", "bilinear") != "bilinear",
|
||||
}
|
||||
for key, bad in unsupported.items():
|
||||
if bad:
|
||||
raise NotImplementedError(f"HY_V4_FLASH vision config {key}={vcfg.get(key)!r} is not supported")
|
||||
self.gguf_writer.add_clip_projector_type(self.projector_type)
|
||||
self.gguf_writer.add_vision_use_gelu(True)
|
||||
# rms_norm_eps is also the LayerNorm eps of the encoder blocks
|
||||
self.gguf_writer.add_vision_attention_layernorm_eps(vcfg.get("rms_norm_eps", 1e-5))
|
||||
self.gguf_writer.add_vision_spatial_merge_size(vcfg.get("spatial_merge_size", 2))
|
||||
self.gguf_writer.add_vision_min_pixels(int(self.preprocessor_config["min_pixels"]))
|
||||
self.gguf_writer.add_vision_max_pixels(int(self.preprocessor_config["max_pixels"]))
|
||||
|
||||
@classmethod
|
||||
def filter_tensors(cls, item: tuple[str, Callable[[], torch.Tensor]]) -> tuple[str, Callable[[], torch.Tensor]] | None:
|
||||
if not item[0].startswith("vit."):
|
||||
return None
|
||||
|
||||
return super().filter_tensors(item)
|
||||
|
||||
def modify_tensors(self, data_torch: torch.Tensor, name: str, bid: int | None) -> Iterable[tuple[str, torch.Tensor]]:
|
||||
# row 0 of the position embedding is an unused CLS slot, the reference resamples rows 1:
|
||||
if "position_embedding" in name:
|
||||
data_torch = data_torch[1:]
|
||||
yield from super().modify_tensors(data_torch, name, bid)
|
||||
|
||||
def tensor_force_quant(self, name, new_name, bid, n_dims):
|
||||
# conv weights in F32 or F16, BF16 IM2COL is not supported on Metal
|
||||
if ("mm.0." in new_name or "mm.2." in new_name) and new_name.endswith(".weight"):
|
||||
return gguf.GGMLQuantizationType.F16 if self.ftype == gguf.LlamaFileType.MOSTLY_F16 else gguf.GGMLQuantizationType.F32
|
||||
return super().tensor_force_quant(name, new_name, bid, n_dims)
|
||||
+240
-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:
|
||||
@@ -248,6 +294,22 @@ class Inkling2Model(TextModel):
|
||||
return super().tensor_force_quant(name, new_name, bid, n_dims)
|
||||
|
||||
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
|
||||
# PEFT names the wrapped projections (self_attn.k_proj.linear.weight) and the attention
|
||||
# output gate (self_attn.o_proj.gate_proj.weight); neither is in the tensor map.
|
||||
name = name.replace(".linear.", ".")
|
||||
if name.endswith(".o_proj.gate_proj.weight"):
|
||||
yield self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_GATE, bid), data_torch
|
||||
return
|
||||
if name in self._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])
|
||||
@@ -329,6 +391,173 @@ class Inkling2LoopModel(Inkling2Model):
|
||||
yield self.format_tensor_name(gguf.MODEL_TENSOR.LOOP_MSG_QUERY, start + i, ".weight"), query
|
||||
|
||||
|
||||
def _fold_markov_chunk(unembed: Callable[[], Tensor], weight: Tensor | None, bias: Tensor | None, rows: slice) -> np.ndarray:
|
||||
head = LazyTorchTensor.to_eager(unembed()[rows]).double()
|
||||
out = head @ weight if weight is not None else head @ bias
|
||||
return out.float().numpy()
|
||||
|
||||
|
||||
class Inkling2DSparkModel(Inkling2Model):
|
||||
"""Inkling2 DSpark draft (mtp.safetensors) as a DFLASH GGUF, export with --dspark"""
|
||||
model_arch = gguf.MODEL_ARCH.DFLASH
|
||||
|
||||
_TARGET = {
|
||||
"model.llm.unembed.weight": "target.unembed",
|
||||
"model.language_model.unembed.weight": "target.unembed",
|
||||
"lm_head.weight": "target.unembed",
|
||||
"model.llm.embed_norm.weight": "target.embed_norm",
|
||||
"model.language_model.embed_norm.weight": "target.embed_norm",
|
||||
"model.language_model.embed_tokens.embed_norm.weight": "target.embed_norm",
|
||||
}
|
||||
|
||||
_LAYER = {
|
||||
"self_attn.k_proj_ctx.weight": gguf.MODEL_TENSOR.DFLASH_ATTN_K_CTX,
|
||||
"self_attn.v_proj_ctx.weight": gguf.MODEL_TENSOR.DFLASH_ATTN_V_CTX,
|
||||
"self_attn.k_norm_ctx.weight": gguf.MODEL_TENSOR.DFLASH_ATTN_K_CTX_NORM,
|
||||
"dflare_norm.weight": gguf.MODEL_TENSOR.DFLASH_CTX_NORM,
|
||||
}
|
||||
|
||||
_ROOT = {
|
||||
"target.embed_norm": gguf.MODEL_TENSOR.TOKEN_EMBD_NORM,
|
||||
"mtp.norm.weight": gguf.MODEL_TENSOR.OUTPUT_NORM,
|
||||
"mtp.markov_head.markov_w1.weight": gguf.MODEL_TENSOR.DSPARK_MARKOV_W1,
|
||||
"mtp.markov_head.rnn_proj.weight": gguf.MODEL_TENSOR.DSPARK_JOINT_PROJ,
|
||||
"mtp.markov_head.rnn_proj.bias": gguf.MODEL_TENSOR.DSPARK_JOINT_PROJ,
|
||||
"mtp.markov_head.dflare_norm.weight": gguf.MODEL_TENSOR.DSPARK_MARKOV_CTX_NORM,
|
||||
}
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self._folded: dict[str, gguf.LazyChunkedTensor] = {}
|
||||
super().__init__(*args, **kwargs)
|
||||
hp = self.hparams
|
||||
mtp = hp.get("mtp_config")
|
||||
if not mtp:
|
||||
raise ValueError("Inkling2 DSpark export needs the mtp_config")
|
||||
if mtp.get("markov_head_type") != "rnn_hidden" or mtp.get("q_bias") or mtp.get("o_bias") or mtp["hidden_size"] != hp["hidden_size"]:
|
||||
raise ValueError(f"Inkling2 DSpark: unsupported mtp_config {mtp}")
|
||||
# ids count loop passes, the last id is the final norm output
|
||||
n_visits = self.block_count
|
||||
if (loop := hp.get("loop_config")) is not None:
|
||||
n_visits += (loop["num_passes"] - 1) * (loop["core_end"] - loop["core_start"])
|
||||
targets = mtp["target_layer_ids"]
|
||||
if len(targets) < 2 or targets != sorted(set(targets)) or targets[-1] != n_visits:
|
||||
raise ValueError(f"Inkling2 DSpark: target_layer_ids {targets} must be sorted and end at {n_visits}")
|
||||
self.mtp = mtp
|
||||
self.block_count = mtp["num_hidden_layers"]
|
||||
self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count)
|
||||
|
||||
def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]:
|
||||
if remote_hf_model_id is not None:
|
||||
raise NotImplementedError("Inkling2 DSpark export needs a local checkpoint")
|
||||
# mtp.safetensors is not in the weight map, unembed and embed_norm come from the target
|
||||
tensors = self.index_local_tensors("mtp")
|
||||
tensors.update(self.index_local_tensors("model"))
|
||||
return tensors
|
||||
|
||||
@classmethod
|
||||
def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
|
||||
name, gen = item
|
||||
if name in cls._TARGET:
|
||||
return cls._TARGET[name], gen
|
||||
if name.startswith(("model.", "lm_head.")):
|
||||
return None
|
||||
if name.startswith("layers."):
|
||||
return f"model.{name}", gen
|
||||
return f"mtp.{name}", gen
|
||||
|
||||
def dequant_model(self):
|
||||
super().dequant_model()
|
||||
if "target.unembed" not in self.model_tensors:
|
||||
raise ValueError("Inkling2 DSpark: missing the target unembed")
|
||||
unembed = self.model_tensors.pop("target.unembed")
|
||||
weight = LazyTorchTensor.to_eager(self.model_tensors.pop("mtp.markov_head.hidden_out.weight")()).double()
|
||||
bias = LazyTorchTensor.to_eager(self.model_tensors.pop("mtp.markov_head.hidden_out.bias")()).double()
|
||||
n_vocab, n_embd = unembed().shape
|
||||
if weight.shape[0] != n_embd or bias.shape != (n_embd,):
|
||||
raise ValueError(f"Inkling2 DSpark: hidden_out {tuple(weight.shape)} does not match unembed {(n_vocab, n_embd)}")
|
||||
# markov_w2 = unembed @ hidden_out, fp64 like vLLM, one row chunk at a time
|
||||
# padded tokens are never sampled, so keep only the tokenizer rows
|
||||
n_vocab = self.hparams["unpadded_vocab_size"]
|
||||
row_chunks = [slice(i, min(i + 4096, n_vocab)) for i in range(0, n_vocab, 4096)]
|
||||
for name, w, b, shape in (
|
||||
("mtp.markov_head.fold.weight", weight, None, (n_vocab, weight.shape[1])),
|
||||
("mtp.markov_head.fold.bias", None, bias, (n_vocab,)),
|
||||
):
|
||||
self._folded[name] = gguf.LazyChunkedTensor([partial(_fold_markov_chunk, unembed, w, b, r) for r in row_chunks], shape, np.float32)
|
||||
self.model_tensors[name] = lambda shape=shape: torch.empty(shape, dtype=torch.float32, device="meta")
|
||||
|
||||
def prepare_metadata(self, vocab_only: bool):
|
||||
from_dir = self.fname_out.is_dir()
|
||||
super().prepare_metadata(vocab_only=vocab_only)
|
||||
if from_dir:
|
||||
self.fname_out = self.fname_out.parent / f"dspark-{self.fname_out.name}"
|
||||
|
||||
def set_vocab(self):
|
||||
super().set_vocab()
|
||||
# block uses mask_embd, mask token id is not used
|
||||
self.gguf_writer.add_mask_token_id(0)
|
||||
|
||||
def set_gguf_parameters(self):
|
||||
hp, mtp = self.hparams, self.mtp
|
||||
n = self.block_count
|
||||
w = self.gguf_writer
|
||||
w.add_block_count(n)
|
||||
w.add_context_length(mtp["max_position_embeddings"])
|
||||
w.add_embedding_length(mtp["hidden_size"])
|
||||
w.add_feed_forward_length(mtp["intermediate_size"])
|
||||
w.add_head_count(mtp["num_attention_heads"])
|
||||
w.add_head_count_kv(mtp["num_key_value_heads"])
|
||||
w.add_key_length(mtp["head_dim"])
|
||||
w.add_value_length(mtp["head_dim"])
|
||||
w.add_rope_dimension_count(mtp["head_dim"])
|
||||
w.add_rope_freq_base(float(mtp["rope_theta"]))
|
||||
w.add_layer_norm_rms_eps(mtp["rms_norm_eps"])
|
||||
# the block sees W positions before the anchor, llama.cpp SWA sees n_swa - 1
|
||||
w.add_sliding_window(mtp["sliding_window_size"] + 1)
|
||||
w.add_sliding_window_pattern([i in mtp["local_layer_ids"] for i in range(n)])
|
||||
w.add_final_logit_softcapping(hp["final_logit_softcapping"])
|
||||
w.add_block_size(mtp["block_size"])
|
||||
w.add_target_layers(mtp["target_layer_ids"])
|
||||
# slot 0 is the anchor, it does not predict a token
|
||||
w.add_sample_from_anchor(False)
|
||||
w.add_has_confidence_head(False)
|
||||
w.add_has_markov_context(mtp["markov_head_type"] == "rnn_hidden")
|
||||
w.add_file_type(self.ftype)
|
||||
|
||||
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
|
||||
if name in self._folded:
|
||||
suffix = ".bias" if name.endswith(".bias") else ".weight"
|
||||
yield self.format_tensor_name(gguf.MODEL_TENSOR.DSPARK_MARKOV_W2, None, suffix), cast("Tensor", self._folded[name])
|
||||
return
|
||||
if name == "mtp.markov_head.markov_w1.weight":
|
||||
data_torch = data_torch[:self.hparams["unpadded_vocab_size"]]
|
||||
if name in self._ROOT:
|
||||
suffix = ".bias" if name.endswith(".bias") else ".weight"
|
||||
yield self.format_tensor_name(self._ROOT[name], None, suffix), data_torch
|
||||
return
|
||||
if name == "mtp.fuse_weight":
|
||||
if tuple(data_torch.shape) != (self.block_count + 1, len(self.mtp["target_layer_ids"])):
|
||||
raise ValueError(f"Inkling2 DSpark: unexpected fuse_weight shape {tuple(data_torch.shape)}")
|
||||
# one row per draft layer, the last row is for the markov head
|
||||
alpha = torch.softmax(data_torch.float(), dim=-1)
|
||||
for i in range(self.block_count):
|
||||
yield self.format_tensor_name(gguf.MODEL_TENSOR.DFLASH_CTX_MIX, i), alpha[i]
|
||||
yield self.format_tensor_name(gguf.MODEL_TENSOR.DSPARK_MARKOV_CTX_MIX), alpha[-1]
|
||||
return
|
||||
if name == "mtp.mask_embed":
|
||||
# copy the one mask embedding to each mask slot
|
||||
yield self.format_tensor_name(gguf.MODEL_TENSOR.DSPARK_MASK_EMBD), data_torch.unsqueeze(0).expand(self.mtp["block_size"] - 1, -1).contiguous()
|
||||
return
|
||||
if name.startswith("mtp."):
|
||||
raise ValueError(f"Inkling2 DSpark: unexpected tensor {name!r}")
|
||||
assert bid is not None
|
||||
key = name.removeprefix(f"model.layers.{bid}.")
|
||||
if key in self._LAYER:
|
||||
yield self.format_tensor_name(self._LAYER[key], bid), data_torch
|
||||
return
|
||||
yield from TextModel.modify_tensors(self, data_torch, name, bid)
|
||||
|
||||
|
||||
@ModelBase.register("Inkling2ForConditionalGeneration", "Inkling2LoopForConditionalGeneration")
|
||||
class Inkling2VisionModel(MmprojModel):
|
||||
def get_vision_config(self):
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -209,7 +209,7 @@ class Qwen3OmniMmprojModel(Qwen3VLVisionModel, Qwen25AudioModel):
|
||||
if not self.has_vision_encoder:
|
||||
raise ValueError(f"Model does not have vision encoder, but found tensor {name}")
|
||||
# need to transform vision tensor naming, so that modify_tensors() logic can be used correctly
|
||||
name = name.replace("thinker.visual.", "model.visual.")
|
||||
name = name.replace("thinker.visual.", "visual.")
|
||||
if ".merger_list." in name:
|
||||
name = name.replace(".merger_list.", ".deepstack_merger_list.")
|
||||
name = name.replace(".ln_q", ".norm")
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, Iterable
|
||||
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
from .base import ModelBase, TextModel, gguf
|
||||
|
||||
|
||||
_REQUIRED = object()
|
||||
|
||||
|
||||
def _renamed_key(config: dict[str, Any], new: str, old: str, default: Any = _REQUIRED) -> Any:
|
||||
# the HF config accepts the older spellings (kda_layers, mhc_*): null counts as absent, a conflicting pair is an error
|
||||
values = [config[key] for key in (new, old) if config.get(key) is not None]
|
||||
if len(values) == 2 and values[0] != values[1]:
|
||||
raise ValueError(f"Raon-1 mini config has conflicting {new}={values[0]!r} and {old}={values[1]!r}")
|
||||
if values:
|
||||
return values[0]
|
||||
if default is _REQUIRED:
|
||||
raise KeyError(f"Raon-1 mini config needs {new} (or the older spelling {old})")
|
||||
return default
|
||||
|
||||
|
||||
def _rda_config(hp: dict[str, Any]) -> dict[str, Any]:
|
||||
# rda_config is the current spelling; older exports use linear_attn_config with short_conv_kernel_size / use_full_rank_gate / full_attn_layers / kda_layers
|
||||
if hp.get("rda_config") is not None and hp.get("linear_attn_config") is not None:
|
||||
raise ValueError("Raon-1 mini config has both rda_config and the older linear_attn_config")
|
||||
config = hp["rda_config"] if hp.get("rda_config") is not None else hp["linear_attn_config"]
|
||||
result = {
|
||||
"num_heads": config["num_heads"],
|
||||
"head_dim": config["head_dim"],
|
||||
"conv_kernel_size": _renamed_key(config, "conv_kernel_size", "short_conv_kernel_size"),
|
||||
"full_rank_gate": _renamed_key(config, "full_rank_gate", "use_full_rank_gate"),
|
||||
"mla_layers": _renamed_key(config, "mla_layers", "full_attn_layers"),
|
||||
"rda_layers": _renamed_key(config, "rda_layers", "kda_layers"),
|
||||
}
|
||||
# absent and null differ here (see set_gguf_parameters), so the key is copied only when present
|
||||
if "gate_lower_bound" in config:
|
||||
result["gate_lower_bound"] = config["gate_lower_bound"]
|
||||
return result
|
||||
|
||||
|
||||
@ModelBase.register("Raon1MiniForCausalLM")
|
||||
@ModelBase.example("KRAFTON/Raon-1-mini-preview")
|
||||
class Raon1MiniModel(TextModel):
|
||||
model_arch = gguf.MODEL_ARCH.RAON1_MINI
|
||||
|
||||
# mHC sites: HF module name -> tensor prefix; each site has 10 parameters, packed into fn / base / scale
|
||||
_MHC_SITES = (("self_attn_raon_mhc", "HC_ATTN"), ("mlp_raon_mhc", "HC_FFN"))
|
||||
_MHC_PARTS = ("phi_pre", "phi_post", "res.phi_z", "b_pre", "b_post", "res.b_z",
|
||||
"alpha_pre", "alpha_post", "res.alpha_z", "res.eta")
|
||||
# Keep these tensors at F16 for direct conversion to Q8_0, TQ1_0 or TQ2_0.
|
||||
_KEEP_UNQUANTIZED = ("hc_attn_fn", "hc_ffn_fn", "ssm_f_a", "ssm_f_b", "ssm_beta", "ssm_rda")
|
||||
_KEEP_UNQUANTIZED_Q8_0 = ("attn_kv_a_mqa", "attn_k_b", "attn_v_b")
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self._experts: dict[tuple[int, str], dict[int, Tensor]] = {}
|
||||
self._mhc: dict[tuple[int, str], dict[str, Tensor]] = {}
|
||||
self._rda_layers = set(_rda_config(self.hparams)["rda_layers"])
|
||||
|
||||
def filter_tensors(self, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
|
||||
filtered = super().filter_tensors(item)
|
||||
if filtered is None:
|
||||
return None
|
||||
|
||||
name, _ = filtered
|
||||
if name.startswith("model.layers."):
|
||||
layer = name.split(".", 3)[2]
|
||||
# MTP layers follow the main model layers.
|
||||
if layer.isdecimal() and int(layer) >= self.hparams["num_hidden_layers"]:
|
||||
return None
|
||||
|
||||
return filtered
|
||||
|
||||
def set_gguf_parameters(self):
|
||||
hp = self.hparams
|
||||
rda_config = _rda_config(hp)
|
||||
n_layer = hp["num_hidden_layers"]
|
||||
# 1-based layer ids, as in the HF config (is_rda_layer: layer_idx + 1 in rda_layers)
|
||||
rda = self._rda_layers
|
||||
mla = set(rda_config["mla_layers"])
|
||||
if rda & mla or rda | mla != set(range(1, n_layer + 1)):
|
||||
raise ValueError("Raon-1 mini attention layer lists must partition all layers")
|
||||
# the hybrid memory needs both layer kinds
|
||||
if not rda or not mla:
|
||||
raise ValueError("Raon-1 mini needs at least one RDA (rda_layers) and one MLA (mla_layers) layer")
|
||||
if hp.get("tie_word_embeddings"):
|
||||
raise ValueError("Raon-1 mini with tie_word_embeddings is not supported (the released model has a separate lm_head)")
|
||||
if (not hp["mla_use_nope"] or not hp["mla_use_output_gate"]
|
||||
or not rda_config["full_rank_gate"] or hp["hidden_act"] != "situ"
|
||||
or hp["moe_router_activation_func"] != "sigmoid"
|
||||
or hp.get("use_grouped_topk") or hp.get("routed_expert_hidden_size")
|
||||
or hp.get("attn_res_block_size") or hp["moe_layer_freq"] != 1):
|
||||
raise ValueError("Unsupported Raon-1 mini architecture variant")
|
||||
if rda_config["num_heads"] != hp["num_attention_heads"]:
|
||||
raise ValueError("Raon-1 mini RDA and MLA head counts must match")
|
||||
|
||||
super().set_gguf_parameters()
|
||||
self.gguf_writer.add_vocab_size(hp["vocab_size"])
|
||||
self.gguf_writer.add_head_count_kv([0 if i + 1 in rda else 1 for i in range(n_layer)])
|
||||
self.gguf_writer.add_ssm_conv_kernel(rda_config["conv_kernel_size"])
|
||||
# the .get() defaults below are the HF config defaults
|
||||
self.gguf_writer.add_ssm_time_step_rank(_renamed_key(hp, "rda_decay_rank", "kda_decay_rank", 128))
|
||||
self.gguf_writer.add_kda_head_dim(rda_config["head_dim"])
|
||||
# HF uses -5.0 when the key is absent; an explicit null selects the unbounded gate
|
||||
if (bound := rda_config.get("gate_lower_bound", -5.0)) is not None:
|
||||
self.gguf_writer.add_kda_gate_lower_bound(bound)
|
||||
self.gguf_writer.add_q_lora_rank(hp["q_lora_rank"])
|
||||
self.gguf_writer.add_kv_lora_rank(hp["kv_lora_rank"])
|
||||
self.gguf_writer.add_rope_dimension_count(hp["qk_rope_head_dim"])
|
||||
self.gguf_writer.add_key_length(hp["kv_lora_rank"] + hp["qk_rope_head_dim"])
|
||||
self.gguf_writer.add_value_length(hp["kv_lora_rank"])
|
||||
self.gguf_writer.add_key_length_mla(hp["qk_nope_head_dim"] + hp["qk_rope_head_dim"])
|
||||
self.gguf_writer.add_value_length_mla(hp["v_head_dim"])
|
||||
self.gguf_writer.add_latent_norm_rms_eps(hp.get("mla_latent_norm_eps", 1e-6))
|
||||
self.gguf_writer.add_expert_feed_forward_length(hp["moe_intermediate_size"])
|
||||
self.gguf_writer.add_expert_shared_count(hp["num_shared_experts"])
|
||||
self.gguf_writer.add_leading_dense_block_count(hp["first_k_dense_replace"])
|
||||
self.gguf_writer.add_expert_weights_scale(hp["routed_scaling_factor"])
|
||||
self.gguf_writer.add_expert_weights_norm(hp["moe_renormalize"])
|
||||
self.gguf_writer.add_activation_situ_beta(hp["activation_situ_beta"])
|
||||
self.gguf_writer.add_activation_situ_linear_beta(hp["activation_situ_linear_beta"])
|
||||
self.gguf_writer.add_hyper_connection_count(_renamed_key(hp, "raon_mhc_streams", "mhc_streams", 4))
|
||||
self.gguf_writer.add_hyper_connection_epsilon(_renamed_key(hp, "raon_mhc_selector_eps", "mhc_selector_eps", 1e-5))
|
||||
self.gguf_writer.add_hyper_connection_magnitude(_renamed_key(hp, "raon_mhc_post_factor", "mhc_post_factor", 2.0))
|
||||
|
||||
def prepare_tensors(self):
|
||||
super().prepare_tensors()
|
||||
if self._experts or self._mhc:
|
||||
raise ValueError(f"Incomplete Raon-1 mini tensor groups: experts={list(self._experts)}, mHC={list(self._mhc)}")
|
||||
|
||||
def tensor_force_quant(self, name, new_name, bid, n_dims):
|
||||
if ".hc_" in new_name and not new_name.endswith("_fn.weight"):
|
||||
return gguf.GGMLQuantizationType.F32
|
||||
quantized = (gguf.LlamaFileType.MOSTLY_Q8_0, gguf.LlamaFileType.MOSTLY_TQ1_0, gguf.LlamaFileType.MOSTLY_TQ2_0)
|
||||
if self.ftype in quantized and new_name.startswith("blk."):
|
||||
keep = self._KEEP_UNQUANTIZED
|
||||
if self.ftype == gguf.LlamaFileType.MOSTLY_Q8_0:
|
||||
keep += self._KEEP_UNQUANTIZED_Q8_0
|
||||
if new_name.split(".")[2] in keep:
|
||||
return gguf.GGMLQuantizationType.F16
|
||||
return super().tensor_force_quant(name, new_name, bid, n_dims)
|
||||
|
||||
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
|
||||
for site, prefix in self._MHC_SITES:
|
||||
marker = f".{site}."
|
||||
if marker not in name:
|
||||
continue
|
||||
assert bid is not None
|
||||
parts = self._mhc.setdefault((bid, site), {})
|
||||
suffix = name.split(marker, 1)[1]
|
||||
if suffix in parts:
|
||||
raise ValueError(f"Duplicate tensor {name}")
|
||||
parts[suffix] = data_torch
|
||||
if len(parts) < len(self._MHC_PARTS):
|
||||
return
|
||||
fn = torch.cat([parts[k] for k in ("phi_pre", "phi_post", "res.phi_z")])
|
||||
base = torch.cat([parts[k].float() for k in ("b_pre", "b_post", "res.b_z")])
|
||||
scale = torch.stack([parts[k].float().reshape(()) for k in ("alpha_pre", "alpha_post", "res.alpha_z", "res.eta")])
|
||||
for kind, tensor in (("FN", fn), ("BASE", base), ("SCALE", scale)):
|
||||
yield from super().modify_tensors(tensor, self.format_tensor_name(getattr(gguf.MODEL_TENSOR, f"{prefix}_{kind}"), bid), bid)
|
||||
del self._mhc[(bid, site)]
|
||||
return
|
||||
|
||||
# moe.experts.{e}.{gate,down,up}_proj; older exports: block_sparse_moe.experts.{e}.{w1,w2,w3}
|
||||
if ".moe.experts." in name or ".block_sparse_moe.experts." in name:
|
||||
assert bid is not None
|
||||
tail = name.split(".experts.", 1)[1].split(".")
|
||||
eid, wid = int(tail[0]), tail[1]
|
||||
group = self._experts.setdefault((bid, wid), {})
|
||||
if eid in group or not 0 <= eid < self.hparams["num_experts"]:
|
||||
raise ValueError(f"Invalid expert tensor {name}")
|
||||
group[eid] = data_torch
|
||||
if len(group) == self.hparams["num_experts"]:
|
||||
tid = {"gate_proj": gguf.MODEL_TENSOR.FFN_GATE_EXP, "down_proj": gguf.MODEL_TENSOR.FFN_DOWN_EXP,
|
||||
"up_proj": gguf.MODEL_TENSOR.FFN_UP_EXP, "w1": gguf.MODEL_TENSOR.FFN_GATE_EXP,
|
||||
"w2": gguf.MODEL_TENSOR.FFN_DOWN_EXP, "w3": gguf.MODEL_TENSOR.FFN_UP_EXP}[wid]
|
||||
yield from super().modify_tensors(torch.stack([group[i] for i in range(len(group))]), self.format_tensor_name(tid, bid), bid)
|
||||
del self._experts[(bid, wid)]
|
||||
return
|
||||
|
||||
if name.endswith("kv_b_proj.weight"):
|
||||
n_head = self.hparams["num_attention_heads"]
|
||||
qk_nope_head_dim, v_head_dim = self.hparams["qk_nope_head_dim"], self.hparams["v_head_dim"]
|
||||
kv_b = data_torch.reshape(n_head, qk_nope_head_dim + v_head_dim, self.hparams["kv_lora_rank"])
|
||||
k_b, v_b = torch.split(kv_b, [qk_nope_head_dim, v_head_dim], dim=1)
|
||||
yield from super().modify_tensors(k_b.transpose(1, 2).contiguous(), name.replace("kv_b_proj", "k_b_proj"), bid)
|
||||
yield from super().modify_tensors(v_b.contiguous(), name.replace("kv_b_proj", "v_b_proj"), bid)
|
||||
return
|
||||
if name.endswith(".self_attn.g_proj.weight"):
|
||||
assert bid is not None
|
||||
rda = bid + 1 in self._rda_layers
|
||||
tid = gguf.MODEL_TENSOR.SSM_G if rda else gguf.MODEL_TENSOR.ATTN_GATE
|
||||
yield self.format_tensor_name(tid, bid), data_torch
|
||||
return
|
||||
if name.endswith((".q_conv1d.weight", ".k_conv1d.weight", ".v_conv1d.weight")):
|
||||
data_torch = data_torch.reshape(1, -1, 1, data_torch.shape[-1])
|
||||
if name.endswith(".A_log"):
|
||||
data_torch = -torch.exp(data_torch.float())
|
||||
# dt_bias -> the name SSM_DT's mapping expects, as for qwen3next
|
||||
if name.endswith(".dt_bias"):
|
||||
name = name.removesuffix(".dt_bias") + ".dt_proj.bias"
|
||||
yield from super().modify_tensors(data_torch, name, bid)
|
||||
@@ -136,7 +136,7 @@ def parse_args() -> argparse.Namespace:
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dspark", action="store_true",
|
||||
help="Export only the DeepSeek-V4 or Mistral Large 4 DSpark draft tensors as a separate GGUF.",
|
||||
help="Export only the DeepSeek-V4, Mistral Large 4 or Inkling 2 DSpark draft tensors as a separate GGUF.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--mistral-format", action="store_true",
|
||||
@@ -289,8 +289,11 @@ def main() -> None:
|
||||
sys.exit(1)
|
||||
from conversion.mistral4 import MistralLarge4DSparkModel
|
||||
model_class = MistralLarge4DSparkModel
|
||||
elif model_architecture in ("Inkling2ForConditionalGeneration", "Inkling2ForCausalLM", "Inkling2LoopForConditionalGeneration", "Inkling2LoopForCausalLM"):
|
||||
from conversion.inkling2 import Inkling2DSparkModel
|
||||
model_class = Inkling2DSparkModel
|
||||
elif model_architecture not in ("DeepseekV4ForCausalLM", "DeepseekV41ForCausalLM"):
|
||||
logger.error("--dspark is only supported for DeepseekV4ForCausalLM, DeepseekV41ForCausalLM and Mistral Large 4")
|
||||
logger.error("--dspark is only supported for DeepseekV4ForCausalLM, DeepseekV41ForCausalLM, Mistral Large 4 and Inkling 2")
|
||||
sys.exit(1)
|
||||
elif model_architecture == "DeepseekV41ForCausalLM":
|
||||
from conversion.deepseek41 import DeepseekV41DSparkModel
|
||||
|
||||
@@ -169,6 +169,7 @@ models = [
|
||||
{"name": "k2-horizon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/IFM/K2-Horizon-36B", },
|
||||
{"name": "inkling2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/thinkingmachines/Inkling-2-Small", },
|
||||
{"name": "domyn-edge", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/domyn/Domyn-Edge-Teacher-IF", },
|
||||
{"name": "raon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/KRAFTON/Raon-1-mini-preview", },
|
||||
]
|
||||
|
||||
# some models are known to be broken upstream, so we will skip them as exceptions
|
||||
|
||||
+16
-8
@@ -83,22 +83,29 @@ Since common quantizations are supported now, it is recommanded to download GGUF
|
||||
A prebuilt binary kernel library has been introduced for Adreno GPUs.
|
||||
It currently targets X2 GPUs (X2-90, X2-85 and X2-45) found in Snapdragon X2 SoC.
|
||||
The library currently contains kernels for MUL_MAT_ID with Q4_0, Q4_1, Q4_K, MXFP4.
|
||||
The library must be manually downloaded from https://softwarecenter.qualcomm.com/catalog/item/Adreno_Kernel_Library_GGML.
|
||||
The library is published at https://softwarecenter.qualcomm.com/catalog/item/Adreno_Kernel_Library_GGML.
|
||||
Its use is subject to the license in the `license.txt` file shipped with it.
|
||||
|
||||
To allow using the kernel library, add `-DGGML_OPENCL_USE_ADRENO_BIN_KERNELS=ON` when configuring with CMake.
|
||||
Then, extract `adreno-opencl-kernels.dll` from the zip file downloaded from the above URL and put it alongside the executables.
|
||||
The library is enabled by default (`GGML_OPENCL_USE_ADRENO_BIN_KERNELS=ON`).
|
||||
On Windows on ARM64, CMake downloads the library version pinned in `ggml/src/ggml-opencl/CMakeLists.txt` during configuration (`GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=ON`).
|
||||
The download is verified against a SHA256 hash, and the build copies `adreno-opencl-kernels.dll` and `LICENSE-adreno-opencl-kernels.txt` alongside the executables.
|
||||
If the download fails, configuration continues with a warning.
|
||||
To skip the download, add `-DGGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=OFF`, then extract `adreno-opencl-kernels.dll` from the zip file downloaded from the above URL and put it alongside the executables yourself.
|
||||
If kernels compatible with the current GPU are found in the library, they will be loaded and used.
|
||||
If the library is missing, the builtin kernels are used.
|
||||
Add `-DGGML_OPENCL_USE_ADRENO_BIN_KERNELS=OFF` to disable the library entirely.
|
||||
|
||||
|
||||
## CMake Options
|
||||
|
||||
The OpenCL backend has the following CMake options that control the behavior of the backend.
|
||||
|
||||
| CMake options | Default value | Description |
|
||||
|:------------------------------------:|:--------------:|:------------------------------------------|
|
||||
| `GGML_OPENCL_EMBED_KERNELS` | `ON` | Embed OpenCL kernels into the executable. |
|
||||
| `GGML_OPENCL_USE_ADRENO_KERNELS` | `ON` | Use kernels optimized for Adreno. |
|
||||
| `GGML_OPENCL_USE_ADRENO_BIN_KERNELS` | `OFF` | Allow using binary kernel lib for Adreno. |
|
||||
| CMake options | Default value | Description |
|
||||
|:--------------------------------------:|:--------------:|:--------------------------------------------------------|
|
||||
| `GGML_OPENCL_EMBED_KERNELS` | `ON` | Embed OpenCL kernels into the executable. |
|
||||
| `GGML_OPENCL_USE_ADRENO_KERNELS` | `ON` | Use kernels optimized for Adreno. |
|
||||
| `GGML_OPENCL_USE_ADRENO_BIN_KERNELS` | `ON` | Allow using binary kernel lib for Adreno. |
|
||||
| `GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH` | `ON` | Download the binary kernel lib for Adreno (Windows ARM64). |
|
||||
|
||||
## Decomposed Flash Attention
|
||||
|
||||
@@ -311,6 +318,7 @@ ninja
|
||||
|
||||
## Known Issues
|
||||
|
||||
- Adreno E17 compiler workarounds are disabled by default. If you encounter Flash Attention compilation failures or incorrect MoE results, set `GGML_OPENCL_ADRENO_E17_QUIRKS=1` before starting llama.cpp.
|
||||
- Flash attention does not always improve performance.
|
||||
- Currently OpenCL backend works on A6xx GPUs with recent drivers and compilers (usually found in IoT platforms).
|
||||
However, it does not work on A6xx GPUs found in phones with old drivers and compilers.
|
||||
|
||||
@@ -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>
|
||||
@@ -995,6 +996,16 @@ build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.
|
||||
|
||||
**GPU-specific**
|
||||
|
||||
- Muse-Glimmer-30B with a DFlash draft needs a 64 GB system (peak about 45 GB of RAM):
|
||||
|
||||
```bash
|
||||
export GGML_OPENVINO_DEVICE=GPU
|
||||
export GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill # local disk, not tmpfs
|
||||
export GGML_OPENVINO_ROPE_F32_ANGLE=1 # long prompts
|
||||
mkdir -p $GGML_OPENVINO_SPILL_DIR
|
||||
./build/ReleaseOV/bin/llama-server -m Muse-Glimmer-30B-Q4_K_M.gguf -md <dflash-draft>.gguf \
|
||||
--spec-type draft-dflash --spec-draft-n-max 4
|
||||
```
|
||||
- Multiple GPUs (`GGML_OPENVINO_DEVICE=GPU.0,GPU.1` with `-sm layer`):
|
||||
- `-sm tensor` is not supported.
|
||||
- Copies between GPUs go through host memory. There is no asynchronous copy and no peer-to-peer copy.
|
||||
|
||||
@@ -44,7 +44,7 @@ The following releases are verified and recommended:
|
||||
|
||||
### Ubuntu 24.04
|
||||
|
||||
The release packages for Ubuntu 24.04 x64 (FP32/FP16) only include the binary files of the llama.cpp SYCL backend. They require the target machine to have pre-installed Intel GPU drivers and oneAPI packages that are the same version as the build package. To get the version and installation info, refer to [.github/workflows/release.yml#L713](../../.github/workflows/release.yml#L713): ubuntu-24-sycl -> Download & Install oneAPI.
|
||||
The release packages for Ubuntu 24.04 x64 (FP32/FP16) only include the binary files of the llama.cpp SYCL backend. They require the target machine to have pre-installed Intel GPU drivers and oneAPI packages that are the same version as the build package. To get the version and installation info, refer to [.github/workflows/release.yml#1447](../../.github/workflows/release.yml#L1447): `ubuntu-24-sycl` -> `Download & Install oneAPI`.
|
||||
|
||||
It is recommended to use them with [Intel Docker](https://hub.docker.com/r/intel/deep-learning-essentials).
|
||||
|
||||
@@ -818,10 +818,12 @@ 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. |
|
||||
| GGML_SYCL_ENABLE_FUSION | 0 or 1 (default) | Enable fused-kernel dispatch in graph compute. Unsupported types and layouts fall back to the standalone op kernels. See `ggml_sycl_can_fuse()`. |
|
||||
| GGML_SYCL_FUSE_CONV_WINDOW | 0 or 1 (default) | Fuse four-tap recurrent convolution windows, rollback cache updates and SiLU into one kernel. Other shapes use the existing kernels. |
|
||||
| GGML_SYCL_ENABLE_ESIMD | 0 or 1 (default)| Enable ESIMD kernels when available. |
|
||||
| GGML_SYCL_ENABLE_XMX_ESIMD | 0 or 1 (default) | Use the XMX (DPAS) multi-column mat-vec kernels for reordered Q2_K to Q6_K and Q8_0 weights on Xe2 GPUs. Speeds up speculative decoding and short prompt batches. |
|
||||
| GGML_SYCL_XMX_MAX_COLS | non-negative integer, 80 (default) | Most activation columns (batch size) the `GGML_SYCL_ENABLE_XMX_ESIMD` kernels take; wider batches use the other mat-mul kernels. A larger value keeps XMX for bigger batches (as repeated launches), `0` never uses it. |
|
||||
|
||||
@@ -304,6 +304,22 @@ Unlike host-level tensor-splitting, row-splitting is executed entirely inside th
|
||||
You can also combine row-splitting with layer-splitting across multiple grouped devices (e.g. `--devices 'HTP0[0-1],HTP1[2-3]'`
|
||||
on 4 physical NPUs, or `--devices 'HTP0[0-1:0],HTP1[0-1:1]'` on 2 physical NPUs using virtual sessions 0 and 1).
|
||||
|
||||
## Numerical Precision and End-to-End Accuracy
|
||||
|
||||
By default, the Hexagon backend is tuned for higher NPU throughput and lower memory bandwidth while preserving strong
|
||||
end-to-end accuracy across typical models. Specifically, batched matrix multiplications default to `W8A8` integer HMX
|
||||
(`--hex-mm-select 3`), which dynamically quantizes activations into 8-bit (`uint8` x `int8`) blocks with a 2048-element
|
||||
`K`-group scale (using HVX when `M <= 4`),
|
||||
and internal `FP32` activation tensors within each HTP subgraph are automatically lowered in-place to `FP16`
|
||||
(`--hex-oplower 1`). If a particular model or workload exhibits accuracy degradation (for example due to large activation
|
||||
outliers or `FP16` residual overflow), try stepping down to higher-precision configurations in the following order:
|
||||
|
||||
1. `--hex-mm-select 4 --hex-oplower 1`: pure `W8A8` INT HMX everywhere + internal `FP16` lowering (maximum prefill speed)
|
||||
2. `--hex-mm-select 3 --hex-oplower 1` (default): hybrid `W8A8` INT HMX (FP16 HMX on post-GLU / `GGML_PREC_F32` projections) + internal `FP16` lowering
|
||||
3. `--hex-mm-select 3 --hex-oplower 0`: hybrid `W8A8` INT HMX + `FP32` intermediate activations
|
||||
4. `--hex-mm-select 2 --hex-oplower 1`: `FP16` HMX everywhere + internal `FP16` lowering
|
||||
5. `--hex-mm-select 2 --hex-oplower 0`: `FP16` HMX everywhere + `FP32` intermediate activations
|
||||
|
||||
## Environment variables
|
||||
|
||||
- `GGML_HEXAGON_DEVICES` (default: not set, defaults to HTP0 session)
|
||||
@@ -398,3 +414,27 @@ on 4 physical NPUs, or `--devices 'HTP0[0-1:0],HTP1[0-1:1]'` on 2 physical NPUs
|
||||
# Disable ADD and SUB on Hexagon (fall back to CPU or GPU)
|
||||
./scripts/snapdragon/run.py --target adb --hex-opfilter "ADD|SUB" -- llama-cli ...
|
||||
```
|
||||
|
||||
- `GGML_HEXAGON_OPLOWER=N`
|
||||
Controls internal FP32-to-FP16 activation tensor lowering inside HTP opbatches (configurable via `--hex-oplower` in `run.py`):
|
||||
|
||||
- `0`: Disabled - keep internal activations in FP32
|
||||
- `1`: Enabled (default) - lower internal `FP32` activation tensors across the opbatch to `FP16` while respecting `GGML_PREC_F32` hints
|
||||
|
||||
- `GGML_HEXAGON_MM_SELECT=N`
|
||||
Selects the matrix multiplication engine on HTP (configurable via `--hex-mm-select` in `run.py`):
|
||||
|
||||
- `0`: Disabled (falls back to CPU or GPU)
|
||||
- `1`: HVX vector kernels only
|
||||
- `2`: FP16 HMX matrix engine (`M > 4`) with HVX decode (`M <= 4`)
|
||||
- `3`: Hybrid INT HMX `W8A8` (`uint8` activations x `int8` weights) with FP16 HMX fallback on post-GLU / `GGML_PREC_F32` projections and HVX decode (`M <= 4`) (default; automatically defaults to 2 on multi-session v73 hardware unless overridden)
|
||||
- `4`: Pure INT HMX `W8A8` everywhere (`M > 4`) with HVX decode (`M <= 4`)
|
||||
|
||||
- `GGML_HEXAGON_OPPOLL=N`
|
||||
Controls host polling while waiting for HTP opbatch completion (configurable via `--hex-oppoll` in `run.py`):
|
||||
|
||||
- `0`: Blocking wait (lowest host CPU usage)
|
||||
- `1`: Full polling (keeps the host CPU awake for minimum wakeup latency; best for peak benchmarking and profiling)
|
||||
- `> 1`: Hybrid polling budget in milliseconds - polls for up to `N` ms per opbatch before falling back to a blocking wait (default: `50` when supported by the FastRPC driver, `0` otherwise)
|
||||
|
||||
The default (`50`) is tuned for general performance and thermal/power balance (covers decode batches while letting the CPU sleep during longer prefills). For benchmarking, consider more aggressive settings like `10`-`20` or `1` for full polling.
|
||||
|
||||
@@ -30,6 +30,10 @@ The Hexagon NPU backend takes advantage of Snapdragon unified memory where all D
|
||||
The NPU has dedicated tightly-coupled memory called VTCM (Vector Tightly-Coupled Memory). VTCM is used for intermediate data (such as
|
||||
dynamically quantized activations) and streaming buffers (chunks of weight and activation tensors fetched via DMA).
|
||||
|
||||
Both DDR and VTCM reserve trailing guard space so HVX kernels can issue full-width vector loads (`vmem` / `vmemu`) on tail elements without boundary branches:
|
||||
- Shared DDR buffers pad allocations to 4 KB and append a 4 KB guard page.
|
||||
- Usable VTCM (`htp_vtcm_usable_size`) reserves `HTP_VTCM_GUARD_SIZE` (128 bytes) at the end of the physical VTCM page.
|
||||
|
||||
## Large model handling
|
||||
|
||||
Hexagon NPU sessions have a 32-bit virtual address space window of around 3.5GB.
|
||||
@@ -72,34 +76,29 @@ For a weight matrix of logical shape `[ne0, ne1]` (where `ne0 = K`, `ne1 = N`):
|
||||
|
||||
### Block-32 Quantized Formats
|
||||
|
||||
Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`):
|
||||
Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`).
|
||||
Quants are stored in 4-K-grouped (`vrmpy`) byte order across 128-byte HVX vectors:
|
||||
columns `k = 0..31` are split into 8 groups `g = k / 4` of 4 consecutive columns (`j = k % 4`), stored at `4 * row + j` within each vector.
|
||||
|
||||
- **Q4_0** (576 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q4_0`):
|
||||
- **Quants** (bytes 0..511, 512 bytes):
|
||||
- **Quants** (bytes 0..511, 512 bytes, 4 HVX vectors `p = 0..3`):
|
||||
Contains 32 rows x 32 columns of 4-bit quants.
|
||||
Divided into 16 column pairs `cp = 0..15` covering columns `2*cp` and `2*cp + 1`.
|
||||
For each column pair `cp`, 32 bytes are stored consecutively for rows `row = 0..31`:
|
||||
`tile[cp * 32 + row]` holds `(quant[row][2*cp + 1] << 4) | quant[row][2*cp]`.
|
||||
Low nibble holds the even column; high nibble holds the odd column.
|
||||
Vector `p` packs column group `2*p` in the low nibble and group `2*p + 1` in the high nibble:
|
||||
`tile[p * 128 + row * 4 + j]` holds `(quant[row][8*p + 4 + j] << 4) | quant[row][8*p + j]` for `row = 0..31`, `j = 0..3`.
|
||||
- **Scales** (bytes 512..575, 64 bytes):
|
||||
32 FP16 values (`ggml_half`), storing scale `d` for each row `row = 0..31`.
|
||||
|
||||
- **Q8_0** (1088 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q8_0`):
|
||||
- **Quants** (bytes 0..1023, 1024 bytes):
|
||||
- **Quants** (bytes 0..1023, 1024 bytes, 8 HVX vectors `p = 0..7`):
|
||||
Contains 32 rows x 32 columns of signed 8-bit quants (`int8_t`).
|
||||
Divided into 16 column pairs `cp = 0..15` covering columns `col0 = 2*cp` and `col1 = 2*cp + 1`.
|
||||
For each column pair `cp`, 64 bytes store interleaved column elements for each row `row = 0..31`:
|
||||
`tile[cp * 64 + 2 * row + 0] = quant[row][col0]`
|
||||
`tile[cp * 64 + 2 * row + 1] = quant[row][col1]`
|
||||
Vector `p` holds column group `p` (`k = 4*p .. 4*p + 3`):
|
||||
`tile[p * 128 + row * 4 + j] = quant[row][4*p + j]` for `row = 0..31`, `j = 0..3`.
|
||||
- **Scales** (bytes 1024..1087, 64 bytes):
|
||||
32 FP16 values (`ggml_half`), storing scale `d` for each row `row = 0..31`.
|
||||
|
||||
- **IQ4_NL** (576 bytes per tile, `HTP_TENSOR_TILE_SIZE_IQ4_NL`):
|
||||
- **Quants** (bytes 0..511, 512 bytes):
|
||||
Same nibble transposition and storage layout as `Q4_0`.
|
||||
Contains 32 rows x 32 columns of non-linear 4-bit indices (values 0..15).
|
||||
Divided into 16 column pairs `cp = 0..15`:
|
||||
`tile[cp * 32 + row]` holds `(quant[row][2*cp + 1] << 4) | quant[row][2*cp]`.
|
||||
Same 4-K-grouped nibble layout as `Q4_0`, storing 4-bit non-linear indices (values 0..15).
|
||||
- **Scales** (bytes 512..575, 64 bytes):
|
||||
32 FP16 values (`ggml_half`), storing scale `d` for each row `row = 0..31`.
|
||||
- **Dequantization**:
|
||||
@@ -107,10 +106,7 @@ Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`):
|
||||
|
||||
- **MXFP4** (544 bytes per tile, `HTP_TENSOR_TILE_SIZE_MXFP4`):
|
||||
- **Quants** (bytes 0..511, 512 bytes):
|
||||
Same nibble transposition and storage layout as `Q4_0`.
|
||||
Contains 32 rows x 32 columns of 4-bit OCP Microscaling FP4 (E2M1) values.
|
||||
Divided into 16 column pairs `cp = 0..15`:
|
||||
`tile[cp * 32 + row]` holds `(quant[row][2*cp + 1] << 4) | quant[row][2*cp]`.
|
||||
Same 4-K-grouped nibble layout as `Q4_0`, storing 4-bit OCP Microscaling FP4 (E2M1) values.
|
||||
- **Scales** (bytes 512..543, 32 bytes):
|
||||
32 unsigned 8-bit values (`uint8_t`), storing one 8-bit biased exponent (E8M0, bias 127) scale `e` per row `row = 0..31`.
|
||||
- **Dequantization**:
|
||||
@@ -119,26 +115,25 @@ Block-32 formats use a tile size of 32 rows x 32 columns (`K_cols = 32`):
|
||||
|
||||
- **NVFP4** (576 bytes per tile, `HTP_TENSOR_TILE_SIZE_NVFP4`, lossless tiling with same size as `block_nvfp4`):
|
||||
- A 64-element block spans 2 consecutive k-tiles; k-tile `h` holds sub-blocks `2h` and `2h+1`.
|
||||
- **Quants** (bytes 0..511): same nibble transposition as `Q4_0`, holding E2M1 values in element order
|
||||
(within a 16-element sub-block, `qs` byte `j` holds elements `j` and `j+8`).
|
||||
- **Quants** (bytes 0..511, 4 HVX vectors): 4-K-grouped nibble layout per 16-element sub-block `u = 0..1` (`tile[(2*u + 0)*128 + row*4 + j]` holds low nibbles of `qs_sub[j]` and `qs_sub[4+j]`; `tile[(2*u + 1)*128 + row*4 + j]` holds high nibbles).
|
||||
- **Scales** (bytes 512..575): UE4M3 bytes, `tile[512 + 32*u + row]` for sub-block `u = 0..1` of the k-tile.
|
||||
- The per-tensor F32 scale is not part of the tile.
|
||||
|
||||
- **Q4_1** (640 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q4_1`):
|
||||
- **Quants** (bytes 0..511, 512 bytes):
|
||||
Same 4-bit nibble transposition and storage layout as `Q4_0`.
|
||||
Same 4-K-grouped nibble layout as `Q4_0`.
|
||||
- **Scales** (bytes 512..639, 128 bytes):
|
||||
32 pairs of FP16 values (`ggml_half`): `scale[2 * row + 0] = d` (scale) and `scale[2 * row + 1] = m` (min) for each row `row = 0..31`.
|
||||
|
||||
- **Q5_0** (704 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q5_0`):
|
||||
- **Quants** (bytes 0..511): same 4-bit nibble transposition and storage layout as `Q4_0`, holding the low 4 bits.
|
||||
- **5th-bit plane** (bytes 512..639): byte `32*c + row` (`c = 0..3`) holds a flag for `k = 2*(4i + c)` at bit `2i` and for `k = 2*(4i + c) + 1` at bit `2i + 1`, for `i = 0..3`. The flag is set when the 5th bit of the quant is clear.
|
||||
- **Quants** (bytes 0..511): same 4-K-grouped nibble layout as `Q4_0`, holding the low 4 bits.
|
||||
- **5th-bit plane** (bytes 512..639, 1 HVX vector): 4-K-grouped; `plane[row * 4 + j]` (`j = 0..3`) holds a flag at bit `g` (`0..7`) for `k = 4*g + j`. The flag is set when the 5th bit of the quant is clear.
|
||||
- **Scales** (bytes 640..703, 64 bytes): 32 FP16 values, storing scale `d` for each row `row = 0..31`.
|
||||
- **Dequantization**: `0xF0` is OR-ed into the nibble where the flag is set, giving the signed value `q - 16` (-16..15), scaled by `d`.
|
||||
|
||||
- **Q5_1** (768 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q5_1`, same layout as the Q5_K tile):
|
||||
- **Quants** (bytes 0..511) and **scales** (bytes 512..639): same as `Q4_1`, holding the low 4 bits and `(d, m)` pairs.
|
||||
- **5th-bit plane** (bytes 640..767): same as `Q5_K`; a bit is set when the 5th bit of the quant is set.
|
||||
- **5th-bit plane** (bytes 640..767, 1 HVX vector): 4-K-grouped; `plane[row * 4 + j]` (`j = 0..3`) holds bit `g` (`0..7`) for `k = 4*g + j`, set when the 5th bit of the quant is set.
|
||||
- Uses the `Q5_K` HVX/HMX kernels (Q8_1 activations with block sums).
|
||||
|
||||
### Q1_0 Format (1-Bit Quantization)
|
||||
@@ -209,12 +204,12 @@ Byte ordering: `Q2_K`, `Q3_K`, and `Q6_K` use `vrmpy` byte order within each 128
|
||||
- `bytes 384..511` (vec 3): FP16 scales `d * (scales[] - 32)`: `fp16[0..31]` for k 0..15, `fp16[32..63]` for k 16..31.
|
||||
|
||||
- **Q4_K** (640 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q4_K`, same layout as Q4_1 tile; each 256-k super-block splits into 8 tiles of 32 k):
|
||||
- `bytes 0..511` (vec 0..3): 4-bit quants; byte `32*cp + r` holds `k = 2*cp` (low nibble) and `2*cp + 1` (high nibble).
|
||||
- `bytes 0..511` (vec 0..3): 4-bit quants in 4-K-grouped order; `tile[p * 128 + row * 4 + j]` holds `k = 8*p + j` (low nibble) and `k = 8*p + 4 + j` (high nibble).
|
||||
- `bytes 512..639` (vec 4): 32x2 FP16 per row: `(d * sc, -dmin * m)`.
|
||||
|
||||
- **Q5_K** (768 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q5_K`):
|
||||
- `bytes 0..639` (vec 0..4): Q4_K tile (low 4 bits + FP16 scale/min pairs).
|
||||
- `bytes 640..767` (vec 5): 5th-bit plane; byte `l` holds the 8 high bits for lane `l` across vec `i = 0..3` (`bit 2i = lo, 2i+1 = hi`).
|
||||
- `bytes 640..767` (vec 5): 5th-bit plane in 4-K-grouped order; `plane[row * 4 + j]` holds bit `g` (`0..7`) for `k = 4*g + j`.
|
||||
|
||||
- **Q6_K** (896 bytes per tile, `HTP_TENSOR_TILE_SIZE_Q6_K`):
|
||||
- `bytes 0..511` (vec 0..3): low 4 bits; vec `i` holds group `2i` (low nibble) and `2i+1` (high nibble).
|
||||
@@ -227,8 +222,9 @@ Writing high-performance operators for Hexagon requires following specific guide
|
||||
|
||||
### DDR -> DMA -> VTCM Execution Pipeline
|
||||
|
||||
- Strongly prefer the `DDR -> DMA -> VTCM -> compute (HVX/HMX) -> VTCM -> DMA -> DDR` data flow.
|
||||
- Direct HVX reads/writes from/to DDR are less efficient and should only be used as a fallback.
|
||||
- All operators must use the `DDR -> DMA -> VTCM -> compute (HVX/HMX) -> VTCM -> DMA -> DDR` data flow.
|
||||
- **No direct reads or writes to `tensor->data`**: Do not dereference `tensor->data` pointers directly (scalar or HVX). All tensor transfers must go through DMA, because bypass DMA writes are not L1D/L2 coherent and tensors may reside in 40-bit extended address space.
|
||||
- **Rare exception (small index/position tensors)**: For small metadata tensors that require scalar indexing (such as `ids`, `pos`, or row indices), use [`htp_tensor_read()`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h) to copy into a 128-byte aligned local DDR buffer (`ddr_spad_base` or stack). It handles extended addresses, arbitrary strides, and `dccleaninva` + `syncht` cache maintenance in one place.
|
||||
- Use `dma_addr_t` only for DMA base and final addresses. Form a final address by adding a 32-bit byte offset to a
|
||||
`dma_addr_t` tensor base address. This permits a 64-bit mapped base address on newer platforms while retaining 32-bit
|
||||
relative addressing.
|
||||
@@ -244,8 +240,12 @@ Writing high-performance operators for Hexagon requires following specific guide
|
||||
properly. Flushing is only used in rare exceptions where a batch of operations is pushed without individual pops.
|
||||
- Use the DMA queue interface from [`dma-queue.h`](../../../ggml/src/ggml-hexagon/htp/dma-queue.h)
|
||||
(`dma_queue_push()`, `dma_queue_pop()`, and `dma_queue_flush()`).
|
||||
See [`cumsum-ops.c`](../../../ggml/src/ggml-hexagon/htp/cumsum-ops.c) and
|
||||
[`act-ops.c`](../../../ggml/src/ggml-hexagon/htp/act-ops.c) for reference implementations.
|
||||
- For new simple ops, prefer the generic double-buffered pipeline drivers in
|
||||
[`dma-pipeline.h`](../../../ggml/src/ggml-hexagon/htp/dma-pipeline.h) (`dma_pipe_io_run`, `dma_pipe_in_run`,
|
||||
`dma_pipe_out_run`), which use dummy pushes, `dma_queue_pop().src`/`.dst` slot recycling, and `dma_queue_flush()`
|
||||
at the end of the op. See [`cumsum-ops.c`](../../../ggml/src/ggml-hexagon/htp/cumsum-ops.c),
|
||||
[`diag-ops.c`](../../../ggml/src/ggml-hexagon/htp/diag-ops.c), and
|
||||
[`pad-ops.c`](../../../ggml/src/ggml-hexagon/htp/pad-ops.c) for reference implementations.
|
||||
|
||||
### Avoid Scalar Reads and Writes to VTCM
|
||||
|
||||
@@ -256,22 +256,22 @@ Writing high-performance operators for Hexagon requires following specific guide
|
||||
- Hexagon cores do not have hardware division instructions.
|
||||
- For recurring divisions across iterations or threads, use `fastdiv` from
|
||||
[`hex-fastdiv.h`](../../../ggml/src/ggml-hexagon/htp/hex-fastdiv.h) with precomputed divisors (such as
|
||||
`octx->ctx->mdev.count_div` or `octx->n_threads_div`).
|
||||
`octx->ctx->mdev.count_div` or `octx->n_hvx_div`).
|
||||
- Do not call `init_fastdiv_values()` for single-use divisions; use standard compiler division (`/`) instead.
|
||||
|
||||
### Host-Side Precomputation via `kernel_params`
|
||||
|
||||
- Precompute tensor shapes, strides, scale conversions, tiling layouts, and validation checks on the host CPU during graph
|
||||
preparation in [`ggml-hexagon.cpp`](../../../ggml/src/ggml-hexagon/ggml-hexagon.cpp).
|
||||
preparation in [`htp-kparams.cpp`](../../../ggml/src/ggml-hexagon/htp-kparams.cpp).
|
||||
- Pack precomputed parameters into the operator's fixed `kernel_params` structure in `htp_op_node` (such as
|
||||
`htp_mm_kernel_params`, `htp_unary_kernel_params`, `htp_fa_kernel_params`, `htp_get_rows_kernel_params`).
|
||||
- The NPU executes directly using `octx->kernel_params` without redundant runtime metadata extraction or validation.
|
||||
- **Strict Host-Kernel Alignment**:
|
||||
- Verify that parameters calculated by the host CPU are strictly honored by the NPU kernel.
|
||||
- Ensure the kernel does not ignore host-computed fields (for example, falling back to `octx->n_threads` instead of
|
||||
using `kparams->n_threads`, or ignoring precomputed `tasks_per_thread` and chunk counts).
|
||||
- Ensure the kernel does not ignore host-computed fields (for example, falling back to `octx->n_hvx` instead of
|
||||
using `kparams->n_hvx`, or ignoring precomputed `tasks_per_hvx` and chunk counts).
|
||||
- Both human developers and coding agents must audit both sides of the interface: ensure fields populated in `kernel_params`
|
||||
in [`ggml-hexagon.cpp`](../../../ggml/src/ggml-hexagon/ggml-hexagon.cpp) are actively and consistently utilized by the
|
||||
in [`htp-kparams.cpp`](../../../ggml/src/ggml-hexagon/htp-kparams.cpp) are actively and consistently utilized by the
|
||||
corresponding operator entry point and worker threads in `htp/*-ops.c`.
|
||||
|
||||
### Tracing Instrumentation
|
||||
@@ -292,7 +292,7 @@ Writing high-performance operators for Hexagon requires following specific guide
|
||||
- Distribute parallel work across NPU worker threads using the thread pool work queue:
|
||||
|
||||
```c
|
||||
work_queue_run(ctx->work_queue, worker_func, &op_ctx, n_threads);
|
||||
work_queue_run(ctx->hvx_queue, worker_func, &op_ctx, n_hvx);
|
||||
```
|
||||
|
||||
- Keep worker functions independent and re-entrant. Worker threads should only operate on their designated chunk of rows or elements.
|
||||
@@ -307,6 +307,12 @@ Writing high-performance operators for Hexagon requires following specific guide
|
||||
- **Distinction**: `octx->src[N]` pointers *can* be NULL by design and must be checked when optional.
|
||||
Examples include attention masks, optional bias or weights in fused kernels, and frequency factors.
|
||||
|
||||
### Prefer Early Dispatch and Specialized Micro-Kernels
|
||||
|
||||
- Avoid peppering micro-kernels, row or tile compute loops, or DMA worker loops with runtime checks for operand types, optional inputs, broadcast modes, or layout variants.
|
||||
- Resolve execution variants early during operator setup (`op_*` / `execute_op_*`) via function pointers or dispatch tables so each micro-kernel and inner loop handles a single clean path that the compiler can unroll and software-pipeline without extra branch or register pressure.
|
||||
- Prefer clean standalone specialized functions; use macros only to avoid genuine code duplication across type or mode instantiations.
|
||||
|
||||
### `supports_op` Independence from Buffer and Repack State
|
||||
|
||||
- `supports_op` (and op-specific checkers such as `supported_mul_mat()`, `supported_get_rows()`) runs during GGML graph scheduling **before** buffers are allocated and before tensor data is populated.
|
||||
@@ -319,6 +325,10 @@ Writing high-performance operators for Hexagon requires following specific guide
|
||||
- Repacking (converting weights to tiled layout) is an internal optimization applied during `set_tensor()` or rt-repack. Non-weight tensors or test harness tensors with the same type remain in flat layout.
|
||||
- Therefore, any supported type (such as BF16, F16, quantized types) must be supported both when repacked into tiles and when stored flat in memory.
|
||||
|
||||
### FP16 and Mixed-Precision Operator Support
|
||||
|
||||
- New and updated Hexagon compute operators must support `F16` (and mixed `F16`/`F32` where applicable for graph lowering) across activation inputs and outputs, even when `ggml-cpu` only implements `F32`.
|
||||
|
||||
### Multiline Macro Formatting
|
||||
|
||||
- Keep trailing backslashes in multiline `#define` macros cleanly aligned to a consistent column.
|
||||
@@ -361,56 +371,37 @@ python3 scripts/snapdragon/ggml-hexagon-inspect.py --addr2line 0x51a30 0x5ba54
|
||||
Multi-device (mdev) mode enables row-level tensor parallel execution across multiple physical NPU cores or virtual NPU
|
||||
sessions.
|
||||
|
||||
### 128-Byte Cache Line Alignment
|
||||
### Non-Overlapping Output Ranges
|
||||
|
||||
- Shared tensor buffers reside in DDR (RPCMEM) with a 128-byte cache line granularity
|
||||
(`HEX_L2_LINE_SIZE` = 128 bytes, `HTP_TENSOR_MDEV_LINE_SIZE`).
|
||||
- **Rule**: Multi-device work partitions that write directly to DDR through HVX/L2 must align destination write regions to
|
||||
128-byte cache line boundaries so distinct devices never share or overwrite the same cache line.
|
||||
- DMA writes to DDR are not subject to this cache-line ownership rule. They may use smaller non-overlapping destination
|
||||
ranges when the operator only writes through DMA.
|
||||
- Because all DDR writes go through bypass DMA, multi-device partitions are **not** subject to 128-byte cache-line
|
||||
alignment rules.
|
||||
- Devices only need non-overlapping destination output ranges and any kernel-specific tile or vector granularity
|
||||
(for example, 32 rows for tiled matmul or 128-byte vector chunks for flat 1D element-wise ops).
|
||||
|
||||
### Partitioning Helpers in `htp-tensor.h`
|
||||
### Partitioning Helper in `htp-tensor.h`
|
||||
|
||||
Common partitioning logic is factored into reusable inline helpers in
|
||||
[`htp-tensor.h`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h):
|
||||
Common partitioning logic is factored into [`htp_tensor_mdev_partition`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h)
|
||||
in [`htp-tensor.h`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h):
|
||||
|
||||
1. [`htp_tensor_mdev_rows_per_chunk`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L104):
|
||||
Determines the minimum number of rows per chunk so that the chunk byte size is a multiple of 128 bytes:
|
||||
|
||||
```
|
||||
rows_per_chunk = 128 / hex_gcd_u32(row_size, 128)
|
||||
```
|
||||
|
||||
If the active row and outer strides are already multiples of 128 bytes, `rows_per_chunk = 1`.
|
||||
Returns `false` if the tensor cannot be safely row-partitioned (such as unaligned base pointer, permuted layout,
|
||||
or non-128-byte aligned outer strides).
|
||||
|
||||
2. [`htp_tensor_mdev_partition`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L131):
|
||||
Calculates the per-device work range `struct htp_tensor_mdev_range { uint32_t start; uint32_t count; }` given
|
||||
`total_units`, `units_per_chunk`, `mdev_idx`, `mdev_count`, and the precomputed `mdev_count_div`.
|
||||
Handles chunk distribution across devices, assigns remainder units to the last device, and automatically triggers
|
||||
single-device fallback when partitioning is unsafe.
|
||||
- Calculates the per-device work range `struct htp_tensor_mdev_range { uint32_t start; uint32_t count; }` given
|
||||
`total_units`, `units_per_chunk`, `mdev_idx`, `mdev_count`, and the precomputed `mdev_count_div`.
|
||||
- Handles chunk distribution across devices, assigns remainder units to the last device, and automatically falls back
|
||||
to Device 0 when `units_per_chunk == 0` or `total_units / units_per_chunk < mdev_count`.
|
||||
|
||||
### Row-Partitioned Operators
|
||||
|
||||
For row-wise operators that write directly to DDR
|
||||
(such as activations in [`act-ops.c`](../../../ggml/src/ggml-hexagon/htp/act-ops.c),
|
||||
binary ops in [`binary-ops.c`](../../../ggml/src/ggml-hexagon/htp/binary-ops.c),
|
||||
For row-wise operators (such as binary ops in [`binary-ops.c`](../../../ggml/src/ggml-hexagon/htp/binary-ops.c)
|
||||
and unary ops in [`unary-ops.c`](../../../ggml/src/ggml-hexagon/htp/unary-ops.c)):
|
||||
|
||||
```c
|
||||
const uint32_t total_rows = ne01 * ne02 * ne03;
|
||||
const size_t dst_row_size = dst->ne[0] * elem_size;
|
||||
const uint32_t total_rows = ne01 * ne02 * ne03;
|
||||
|
||||
uint32_t row_start = 0;
|
||||
uint32_t nrows = total_rows;
|
||||
|
||||
if (octx->ctx->mdev.count > 1) {
|
||||
uint32_t rows_per_chunk = 0;
|
||||
htp_tensor_mdev_rows_per_chunk(dst, elem_size, (uint32_t) dst_row_size, &rows_per_chunk);
|
||||
const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition(
|
||||
total_rows, rows_per_chunk, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
|
||||
total_rows, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div);
|
||||
row_start = range.start;
|
||||
nrows = range.count;
|
||||
}
|
||||
@@ -422,24 +413,16 @@ if (nrows == 0) {
|
||||
|
||||
### Element-Partitioned Operators
|
||||
|
||||
For flat element-wise operations that write directly to DDR:
|
||||
- Partition total linear elements N = ne0 * ne1 * ne2 * ne3 in 128-byte cache line chunks (`elems_per_line = (elem_size == 4) ? 32 : 64`).
|
||||
- Requires strict 1D contiguity:
|
||||
[`htp_tensor_is_contiguous(dst, elem_size)`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L65)
|
||||
and 128-byte aligned destination pointer
|
||||
[`htp_tensor_mdev_data_aligned(dst)`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L84).
|
||||
- If contiguous and aligned, pass `elems_per_line` to
|
||||
[`htp_tensor_mdev_partition`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h#L131);
|
||||
otherwise pass 0 to trigger Device 0 fallback.
|
||||
For flat 1D element-wise operations:
|
||||
- Partition total linear elements `N = ne0 * ne1 * ne2 * ne3` in HVX vector-sized chunks (`elems_per_line = 128 / elem_size`).
|
||||
- Requires 1D contiguity via [`htp_tensor_is_contiguous`](../../../ggml/src/ggml-hexagon/htp/htp-tensor.h); otherwise pass
|
||||
`0` to trigger Device 0 fallback.
|
||||
|
||||
### Single-Device Fallback (Device 0)
|
||||
|
||||
- Fallback to Device 0 (`mdev.idx == 0`) when partitioning would cause cache line tearing or there are too few aligned chunks.
|
||||
- Triggers:
|
||||
1. Destination tensor cannot be safely partitioned (`rows_per_chunk == 0` or non-contiguous/unaligned buffer).
|
||||
2. Total aligned chunks < `mdev_count`.
|
||||
- Fallback to Device 0 (`mdev.idx == 0`) happens when `units_per_chunk == 0` or `total_chunks < mdev_count`.
|
||||
- Device 0 processes the entire tensor `[0, total_units)`.
|
||||
- Devices 1 ... N-1 receive `count = 0` and return `HTP_STATUS_OK` immediately.
|
||||
- Devices `1 ... N-1` receive `count = 0` and return `HTP_STATUS_OK` immediately.
|
||||
|
||||
### Flatten Outer Dimensions Globally
|
||||
|
||||
@@ -494,10 +477,7 @@ Multi-device execution synchronizes worker sessions through atomic fence slots a
|
||||
(htp_mdev_group_barrier) (htp_mdev_group_barrier)
|
||||
| |
|
||||
Kernel Execution Kernel Execution
|
||||
(Output Slice 0) (Output Slice 1)
|
||||
| |
|
||||
Tensor Cache Flush Tensor Cache Flush
|
||||
(htp_dcache_flush_dirty_tensors) (htp_dcache_flush_dirty_tensors)
|
||||
(Output Slice 0, via bypass DMA) (Output Slice 1, via bypass DMA)
|
||||
| |
|
||||
Post-Op/Batch Barrier ---------------------- Post-Op/Batch Barrier
|
||||
(htp_mdev_group_barrier) (htp_mdev_group_barrier)
|
||||
@@ -532,11 +512,8 @@ Multi-device execution synchronizes worker sessions through atomic fence slots a
|
||||
misaligned barrier arrivals across iterations.
|
||||
- If any peer reports an error status (`peer_status > HTP_STATUS_OK`), the barrier propagates the error and unblocks immediately.
|
||||
|
||||
### Tensor Cache Flush and Pipeline Completion
|
||||
### Pipeline Completion
|
||||
|
||||
- In the kernel, ensure all pushed DMA operations have been popped in strict FIFO order to drain the queue.
|
||||
- Use [`htp_dcache_flush_dirty_tensors()`](../../../ggml/src/ggml-hexagon/htp/htp-dcache.h) to flush specific dirty tensors back to DDR:
|
||||
- [`htp_dcache_flush_dirty_tensors()`](../../../ggml/src/ggml-hexagon/htp/htp-dcache.h) flushes modified tensor address ranges, or the
|
||||
full D-cache when their total size exceeds the flush threshold, ensuring peer devices and the host CPU observe consistent
|
||||
data in DDR.
|
||||
- Never signal completion before all DMA transfers are drained and dirty tensor flushes have completed.
|
||||
- In the kernel, ensure all pushed DMA operations have been popped in strict FIFO order (or flushed via `dma_queue_flush()`) to drain the queue.
|
||||
- Because all DDR writes use bypass DMA, no per-tensor output cache flush is needed.
|
||||
- Never signal completion before all DMA transfers are drained.
|
||||
|
||||
@@ -50,6 +50,37 @@ export RISCV_ROOT_PATH_IME1={your RISC-V compiler path}
|
||||
${QEMU_ROOT_PATH}/bin/qemu-riscv64 -L ${RISCV_ROOT_PATH_IME1}/sysroot -cpu max,vlen=256,elen=64,vext_spec=v1.0 ${PWD}/build/bin/llama-cli -m ${PWD}/models/Qwen2.5-0.5B-Instruct-Q4_0.gguf -t 1
|
||||
~~~
|
||||
|
||||
## Run On Device
|
||||
On a SpacemiT board the backend reads `marchid` from `/proc/cpuinfo` and selects cores with the variables below. `SPACEMIT_CORE_ARCH` is read only when `/proc/cpuinfo` has no SpacemiT core, which is the QEMU case above. A `0x` prefix on the arch id is optional.
|
||||
|
||||
| Variable | Default | Value |
|
||||
| --- | --- | --- |
|
||||
| `SPACEMIT_PERFER_CORE_ARCH` | cores with arch id high bits `0xA` (`arch >> 12 == 0xA`) | `503c` X60, `5064` X100, `50c8` X200, `a03c` A60, `a064` A100, `a0c8` A200 |
|
||||
| `SPACEMIT_PERFER_CORE_ID` | every core selected above | comma-separated `processor` ids from `/proc/cpuinfo` |
|
||||
| `SPACEMIT_CORE_ARCH` | parse `/proc/cpuinfo` | same hex arch id as `SPACEMIT_PERFER_CORE_ARCH` |
|
||||
| `SPACEMIT_MEM_BACKEND` | `HPAGE` | `NONE`, `POSIX`, `HPAGE`, `HPAGE1GB` |
|
||||
| `SPACEMIT_DISABLE_TCM` | use TCM when the device provides it | any value other than `0` disables TCM |
|
||||
|
||||
X100 (`5064`) and A60 (`a03c`) enable IME1. A100 (`a064`) enables IME2. X60, X200 and A200 do not enable IME1 or IME2.
|
||||
|
||||
To make any child processes get sent to the A100 cores, you need to write the PID of the current process to `/proc/set_ai_thread`. In many shell programs, such as bash or zsh, this can be done with `echo $$ > /proc/set_ai_thread`.
|
||||
~~~
|
||||
echo $$ > /proc/set_ai_thread
|
||||
~~~
|
||||
|
||||
Set them in the environment of the process you start. For example, to run on A100 cores 8-15:
|
||||
~~~
|
||||
echo $$ > /proc/set_ai_thread
|
||||
export SPACEMIT_PERFER_CORE_ARCH=a064
|
||||
export SPACEMIT_PERFER_CORE_ID=8,9,10,11,12,13,14,15
|
||||
|
||||
${PWD}/build/bin/llama-cli -m ${PWD}/models/Qwen2.5-0.5B-Instruct-Q4_0.gguf -t 8
|
||||
~~~
|
||||
|
||||
The same variables can be written in front of the command: `SPACEMIT_PERFER_CORE_ARCH=a064 SPACEMIT_PERFER_CORE_ID=8,9,10,11,12,13,14,15 ${PWD}/build/bin/llama-cli ...`. They are read when the process starts.
|
||||
|
||||
Each id in `SPACEMIT_PERFER_CORE_ID` must be in range and must have the arch given by `SPACEMIT_PERFER_CORE_ARCH`, otherwise the process aborts. An unknown `SPACEMIT_MEM_BACKEND` aborts with the four names above.
|
||||
|
||||
## Quantization Support For Matrix
|
||||
|
||||
| Quantization Type | X60 | A100 |
|
||||
|
||||
+10
-8
@@ -27,7 +27,7 @@ Legend:
|
||||
| COL2IM_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | 🟡 | ❌ | ❌ |
|
||||
| CONCAT | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ❌ | ❌ |
|
||||
| CONT | ❌ | 🟡 | ✅ | ✅ | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | ❌ | ❌ |
|
||||
| CONV_1D_DW | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ |
|
||||
| CONV_1D_DW | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ |
|
||||
| CONV_2D | ❌ | ❌ | 🟡 | ✅ | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ❌ | ❌ |
|
||||
| CONV_2D_DW | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ❌ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| CONV_3D | ❌ | ❌ | ✅ | ✅ | ❌ | 🟡 | ✅ | 🟡 | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
@@ -77,9 +77,9 @@ Legend:
|
||||
| MUL_MAT_ID | ❌ | 🟡 | ✅ | ✅ | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | 🟡 | 🟡 | ❌ |
|
||||
| MUL_MAT_ID_W4A4 | ❌ | ❌ | ✅ | ❌ | ❌ | 🟡 | ❌ | 🟡 | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_ID_W4A8 | ❌ | ❌ | ✅ | ❌ | ❌ | 🟡 | ❌ | 🟡 | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_PREC_SRC1_BF16 | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_PREC_SRC1_BF16_SRC0 | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_PREC_SRC1_F32 | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_PREC_SRC1_BF16 | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_PREC_SRC1_BF16_SRC0 | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_PREC_SRC1_F32 | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_W4A4 | ❌ | ❌ | ✅ | ❌ | ❌ | 🟡 | ❌ | 🟡 | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_W4A8 | ❌ | ❌ | ✅ | ❌ | ❌ | 🟡 | ❌ | 🟡 | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| NEG | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
@@ -89,7 +89,7 @@ Legend:
|
||||
| OUT_PROD | 🟡 | 🟡 | 🟡 | 🟡 | ❌ | ❌ | ❌ | ❌ | ❌ | 🟡 | 🟡 | ❌ | ❌ | ❌ |
|
||||
| PAD | ❌ | 🟡 | ✅ | 🟡 | ❌ | ✅ | 🟡 | ✅ | 🟡 | 🟡 | ✅ | ✅ | ❌ | ❌ |
|
||||
| PAD_REFLECT_1D | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ❌ | ✅ | ❌ | ❌ |
|
||||
| POOL_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| POOL_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| POOL_2D | ❌ | 🟡 | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| REGLU | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| RELU | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
@@ -97,7 +97,7 @@ Legend:
|
||||
| REPEAT_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| RMS_NORM | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| RMS_NORM_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| ROLL | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| ROLL | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| ROPE | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | ✅ | 🟡 | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| ROPE_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| ROUND | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
@@ -108,9 +108,11 @@ Legend:
|
||||
| SET_ROWS | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | ❌ | ❌ |
|
||||
| SGN | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SIGMOID | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SIGMOID_BACK | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| SILU | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SILU_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ |
|
||||
| SIN | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SLEEP | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| SOFTPLUS | ❌ | ❌ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SOFT_MAX | ❌ | 🟡 | ✅ | ✅ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SOFT_MAX_BACK | ❌ | ❌ | 🟡 | 🟡 | ❌ | ❌ | ❌ | ❌ | ❌ | 🟡 | ✅ | ❌ | ❌ | ❌ |
|
||||
@@ -129,8 +131,8 @@ Legend:
|
||||
| TANH | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| TIMESTEP_EMBEDDING | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| TOP_K | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | 🟡 | ✅ | ❌ | ❌ |
|
||||
| TOP_K_MASK | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ |
|
||||
| TOP_K_MASK | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ |
|
||||
| TRI | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| TRUNC | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ✅ | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| UPSCALE | ❌ | 🟡 | ✅ | ✅ | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| XIELU | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| XIELU | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
|
||||
+12673
-9001
File diff suppressed because it is too large
Load Diff
+4
-4
@@ -16812,11 +16812,11 @@
|
||||
"OpenCL","CUMSUM","type=f32,ne=[242004,1,1,1]","support","1","yes","OpenCL"
|
||||
"OpenCL","CUMSUM","type=f32,ne=[375960,1,1,1]","support","1","yes","OpenCL"
|
||||
"OpenCL","CUMSUM","type=f32,ne=[20481,4,1,1]","support","1","yes","OpenCL"
|
||||
"OpenCL","XIELU","type=f32,ne=[10,5,4,3]","support","0","no","OpenCL"
|
||||
"OpenCL","XIELU","type=f16,ne=[10,5,4,3]","support","0","no","OpenCL"
|
||||
"OpenCL","XIELU","type=f32,ne=[10,5,4,3]","support","1","yes","OpenCL"
|
||||
"OpenCL","XIELU","type=f16,ne=[10,5,4,3]","support","1","yes","OpenCL"
|
||||
"OpenCL","XIELU","type=bf16,ne=[10,5,4,3]","support","0","no","OpenCL"
|
||||
"OpenCL","XIELU","type=f32,ne=[512,16,1,1]","support","0","no","OpenCL"
|
||||
"OpenCL","XIELU","type=f16,ne=[512,16,1,1]","support","0","no","OpenCL"
|
||||
"OpenCL","XIELU","type=f32,ne=[512,16,1,1]","support","1","yes","OpenCL"
|
||||
"OpenCL","XIELU","type=f16,ne=[512,16,1,1]","support","1","yes","OpenCL"
|
||||
"OpenCL","XIELU","type=bf16,ne=[512,16,1,1]","support","0","no","OpenCL"
|
||||
"OpenCL","TRI","type=f32,ne=[10,10,4,3],tri_type=3","support","1","yes","OpenCL"
|
||||
"OpenCL","TRI","type=f32,ne=[10,10,4,3],tri_type=2","support","1","yes","OpenCL"
|
||||
|
||||
|
Can't render this file because it is too large.
|
+247
-49
@@ -1283,54 +1283,246 @@
|
||||
"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=0,p1=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=1,p1=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=1,p1=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=0","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=10,s0=10,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,1024,1,1],k0=10,s0=10,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,3,2,1],k0=128,s0=128,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,1024,1,1],k0=128,s0=128,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[256,3,2,1],k0=256,s0=256,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[256,1024,1,1],k0=256,s0=256,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[1000,3,2,1],k0=1000,s0=1000,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[1000,1024,1,1],k0=1000,s0=1000,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[2048,3,2,1],k0=2048,s0=2048,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[2048,1024,1,1],k0=2048,s0=2048,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[4099,3,2,1],k0=4099,s0=4099,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[4099,1024,1,1],k0=4099,s0=4099,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=1","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=2","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=3","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=10,s0=10,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,1024,1,1],k0=10,s0=10,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,3,2,1],k0=128,s0=128,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,1024,1,1],k0=128,s0=128,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[256,3,2,1],k0=256,s0=256,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[256,1024,1,1],k0=256,s0=256,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[1000,3,2,1],k0=1000,s0=1000,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[1000,1024,1,1],k0=1000,s0=1000,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[2048,3,2,1],k0=2048,s0=2048,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[2048,1024,1,1],k0=2048,s0=2048,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[4099,3,2,1],k0=4099,s0=4099,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[4099,1024,1,1],k0=4099,s0=4099,p0=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","IM2COL","type_input=f32,type_kernel=f32,dst_type=f32,ne_input=[3000,128,1,1],ne_kernel=[3,128,1280,1],s0=1,s1=0,p0=1,p1=0,d0=1,d1=0,is_2D=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","IM2COL","type_input=f32,type_kernel=f16,dst_type=f32,ne_input=[3000,128,1,1],ne_kernel=[3,128,1280,1],s0=1,s1=0,p0=1,p1=0,d0=1,d1=0,is_2D=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","IM2COL","type_input=f32,type_kernel=f16,dst_type=f16,ne_input=[3000,128,1,1],ne_kernel=[3,128,1280,1],s0=1,s1=0,p0=1,p1=0,d0=1,d1=0,is_2D=0","support","1","yes","WebGPU"
|
||||
@@ -12345,7 +12537,13 @@
|
||||
"WebGPU: WebGPU","PAD_REFLECT_1D","type=f32,ne_a=[257,7,1,1],pad_0=0,pad_1=256,view=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","PAD_REFLECT_1D","type=f32,ne_a=[2,16777217,1,1],pad_0=1,pad_1=1,view=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","PAD_REFLECT_1D","type=f32,ne_a=[3000,384,4,1],pad_0=10,pad_1=9,view=0","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=3,shift1=-2,shift3=1,shift4=-1","support","0","no","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=3,shift1=-2,shift3=1,shift4=-1,permute=0,ne_a=[10,5,4,3]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=3,shift1=-2,shift3=1,shift4=-1,permute=1,ne_a=[10,5,4,3]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=0,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[1,1,1,1]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=256,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[257,1,1,1]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=-16,shift1=6,shift3=-2,shift4=1,permute=0,ne_a=[17,7,3,2]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=4,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[42,512,1,1]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ROLL","shift0=4,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[380,512,1,1]","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ARANGE","type=f32,start=0.000000,stop=10.000000,step=1.000000","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ARANGE","type=f32,start=3.000000,stop=3.500000,step=1.000000","support","1","yes","WebGPU"
|
||||
"WebGPU: WebGPU","ARANGE","type=f32,start=-10.000000,stop=10.000000,step=0.300000","support","1","yes","WebGPU"
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -132,6 +132,20 @@ llama-server -m Qwen3-4B.gguf -md Qwen3-4B-DSpark.gguf \
|
||||
acceptance (from the draft's confidence head) falls below `P` (default 0 = disabled).
|
||||
Values above 0 require a draft with a confidence head.
|
||||
|
||||
Inkling 2 ships its DSpark drafter as `mtp.safetensors` in the model directory. Export it from a local
|
||||
checkpoint with `--dspark`; the converter also reads the target's lm head and embedding norm from there:
|
||||
|
||||
```bash
|
||||
python convert_hf_to_gguf.py /path/to/Inkling-2-Mini --dspark --outtype bf16 --outfile Inkling-2-Mini-DSpark.gguf
|
||||
|
||||
llama-server -m Inkling-2-Mini.gguf -md Inkling-2-Mini-DSpark.gguf \
|
||||
--spec-type draft-dspark --spec-draft-n-max 3 -fa on --jinja
|
||||
```
|
||||
|
||||
The Inkling 2 drafter supports `--spec-draft-sampling probabilistic`:
|
||||
at a positive request temperature, each drawn token conditions the next one, and the target verifies the draft by
|
||||
rejection sampling.
|
||||
|
||||
Currently only drafts with a Qwen3 backbone are supported; support for other backbones
|
||||
(e.g. Gemma4) is planned.
|
||||
|
||||
|
||||
@@ -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"
|
||||
];
|
||||
|
||||
|
||||
+4
-2
@@ -4,8 +4,8 @@ project("ggml" C CXX ASM)
|
||||
|
||||
### GGML Version
|
||||
set(GGML_VERSION_MAJOR 1)
|
||||
set(GGML_VERSION_MINOR 0)
|
||||
set(GGML_VERSION_PATCH 0)
|
||||
set(GGML_VERSION_MINOR 1)
|
||||
set(GGML_VERSION_PATCH 1)
|
||||
set(GGML_VERSION_BASE "${GGML_VERSION_MAJOR}.${GGML_VERSION_MINOR}.${GGML_VERSION_PATCH}")
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/")
|
||||
@@ -269,6 +269,8 @@ option(GGML_OPENCL "ggml: use OpenCL"
|
||||
option(GGML_OPENCL_PROFILING "ggml: use OpenCL profiling (increases overhead)" OFF)
|
||||
option(GGML_OPENCL_EMBED_KERNELS "ggml: embed kernels" ON)
|
||||
option(GGML_OPENCL_USE_ADRENO_KERNELS "ggml: use optimized kernels for Adreno" ON)
|
||||
option(GGML_OPENCL_USE_ADRENO_BIN_KERNELS "ggml: load the Adreno binary kernel library" ON)
|
||||
option(GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH "ggml: fetch the Adreno binary kernel library" ON)
|
||||
set (GGML_OPENCL_TARGET_VERSION "300" CACHE STRING
|
||||
"ggml: OpenCL API version to target")
|
||||
|
||||
|
||||
@@ -56,8 +56,8 @@ function(ggml_get_system_arch)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
# Determines which FlashAttention vector kernel template instances to compile, returns them in OUT_SRCS.
|
||||
function(ggml_cuda_fattn_vec_instances DIR OUT_SRCS)
|
||||
# Determines which FlashAttention kernel template instances to compile, returns them in OUT_SRCS.
|
||||
function(ggml_cuda_fattn_instances DIR OUT_SRCS)
|
||||
set(FA_TYPES q4_0 q4_1 q5_0 q5_1 q8_0 bf16 f16 f8_e4m3)
|
||||
|
||||
string(TOLOWER "${GGML_CUDA_FA_QUANTS}" FA_QUANTS)
|
||||
@@ -122,6 +122,12 @@ function(ggml_cuda_fattn_vec_instances DIR OUT_SRCS)
|
||||
message(FATAL_ERROR "FlashAttention template instance \"${SRC}\" does not exist")
|
||||
endif()
|
||||
list(APPEND SRCS "${SRC}")
|
||||
|
||||
file(GLOB TILE_SRCS "${DIR}/template-instances/fattn-tile-instance-${COMBINATION}-*.cu")
|
||||
list(APPEND SRCS ${TILE_SRCS})
|
||||
|
||||
file(GLOB MMA_SRCS "${DIR}/template-instances/fattn-mma-f16-instance-${COMBINATION}-*.cu")
|
||||
list(APPEND SRCS ${MMA_SRCS})
|
||||
endforeach()
|
||||
|
||||
set(${OUT_SRCS} ${SRCS} PARENT_SCOPE)
|
||||
|
||||
@@ -161,6 +161,8 @@ extern "C" {
|
||||
bool events;
|
||||
// mmap is supported for loading
|
||||
bool mmap_support;
|
||||
// set_tensor_async from host memory can be ordered with the graph computation and can therefore be faster than a blocking write
|
||||
bool fast_async_host_input;
|
||||
};
|
||||
|
||||
// all the device properties
|
||||
|
||||
+64
-7
@@ -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
|
||||
@@ -2292,6 +2313,15 @@ extern "C" {
|
||||
struct ggml_tensor * a,
|
||||
struct ggml_tensor * sinks);
|
||||
|
||||
GGML_API bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a);
|
||||
|
||||
// Add table[indices[key, query], head, query] to the mask, in F32.
|
||||
// Queries from all streams are flattened in stream order. Indices must be in [0, table->ne[0]).
|
||||
GGML_API void ggml_flash_attn_ext_add_indexed_bias(
|
||||
struct ggml_tensor * a,
|
||||
struct ggml_tensor * table,
|
||||
struct ggml_tensor * indices);
|
||||
|
||||
// TODO: needs to be adapted to ggml_flash_attn_ext
|
||||
GGML_API struct ggml_tensor * ggml_flash_attn_back(
|
||||
struct ggml_context * ctx,
|
||||
@@ -2426,11 +2456,17 @@ extern "C" {
|
||||
// beta : [1, H_v, n_tokens, n_seqs]
|
||||
// state : [S_v, S_v, H_v, n_seqs] -- initial recurrent state s0
|
||||
//
|
||||
// the output packs the attention scores [S_v, H_v, n_tokens, n_seqs] followed by K state
|
||||
// snapshots, most-recent first (slot 0 = final state, slot s = state s tokens back). K == 1
|
||||
// keeps only the final state; when n_tokens < K only slots 0..n_tokens-1 are written.
|
||||
// when n_tokens > K only slot 0 is guaranteed; backends may leave slots 1..K-1 unwritten.
|
||||
GGML_API struct ggml_tensor * ggml_gated_delta_net(
|
||||
// the output packs the attention scores [S_v, H_v, n_tokens, n_seqs] followed by the final state [S_v, S_v, H_v, n_seqs]
|
||||
//
|
||||
// replay (optional, set all of pend_k, pend_v, pend_gb and n_rep, or none): first runs the pending tokens of the
|
||||
// previous ubatch, so that a rollback only drops pending tokens instead of restoring a snapshot
|
||||
// pend_k : [S_k, H_k, n_pend, n_seqs]
|
||||
// pend_v : [S_v, H_v, n_pend, n_seqs]
|
||||
// pend_gb : [g0, H_v, 2*n_pend, n_seqs], the gates of the n_pend tokens, then their betas (in element 0)
|
||||
// n_rep : I32 [n_seqs], number of pending tokens to replay (<= n_pend)
|
||||
// the state output is the state after the replay if keep is true, else the final state.
|
||||
// op param 1 is n_pend (0 without replay): backends that do not implement the replay reject the op when it is set
|
||||
GGML_API struct ggml_tensor * ggml_gated_delta_net_ext(
|
||||
struct ggml_context * ctx,
|
||||
struct ggml_tensor * q,
|
||||
struct ggml_tensor * k,
|
||||
@@ -2438,7 +2474,25 @@ extern "C" {
|
||||
struct ggml_tensor * g,
|
||||
struct ggml_tensor * beta,
|
||||
struct ggml_tensor * state,
|
||||
int64_t K);
|
||||
struct ggml_tensor * pend_k,
|
||||
struct ggml_tensor * pend_v,
|
||||
struct ggml_tensor * pend_gb,
|
||||
struct ggml_tensor * n_rep,
|
||||
bool keep);
|
||||
|
||||
// the output packs the attention scores followed by K state snapshots, most-recent first (slot 0 = final state,
|
||||
// slot s = state s tokens back). when n_tokens < K only slots 0..n_tokens-1 are written. when n_tokens > K only
|
||||
// slot 0 is guaranteed; backends may leave slots 1..K-1 unwritten.
|
||||
GGML_DEPRECATED(GGML_API struct ggml_tensor * ggml_gated_delta_net(
|
||||
struct ggml_context * ctx,
|
||||
struct ggml_tensor * q,
|
||||
struct ggml_tensor * k,
|
||||
struct ggml_tensor * v,
|
||||
struct ggml_tensor * g,
|
||||
struct ggml_tensor * beta,
|
||||
struct ggml_tensor * state,
|
||||
int64_t K),
|
||||
"use ggml_gated_delta_net_ext instead");
|
||||
|
||||
// DSA lightning indexer
|
||||
//
|
||||
@@ -2780,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;
|
||||
};
|
||||
@@ -2807,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
|
||||
|
||||
@@ -621,7 +621,7 @@ endforeach()
|
||||
|
||||
target_link_libraries(ggml-base PRIVATE Threads::Threads)
|
||||
|
||||
if (DEFINED MATH_LIBRARY)
|
||||
if (MATH_LIBRARY)
|
||||
target_link_libraries(ggml-base PRIVATE ${MATH_LIBRARY})
|
||||
elseif (NOT WIN32 AND NOT DEFINED ENV{ONEAPI_ROOT})
|
||||
target_link_libraries(ggml-base PRIVATE m)
|
||||
|
||||
@@ -57,8 +57,9 @@ extern "C" {
|
||||
void * (*get_base) (ggml_backend_buffer_t buffer);
|
||||
// (optional) initialize a tensor in the buffer (eg. add tensor extras)
|
||||
enum ggml_status (*init_tensor)(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor);
|
||||
// tensor data access
|
||||
// (optional) fill tensor data with a value, ggml_backend_tensor_memset falls back to set_tensor
|
||||
void (*memset_tensor)(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, uint8_t value, size_t offset, size_t size);
|
||||
// tensor data access
|
||||
void (*set_tensor) (ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size);
|
||||
void (*get_tensor) (ggml_backend_buffer_t buffer, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size);
|
||||
// (optional) 2d data copies
|
||||
@@ -124,6 +125,15 @@ extern "C" {
|
||||
// keep `tensor` allocated at least until `until` (a node of the same graph) has been computed
|
||||
// can be called multiple times for the same tensor: the longest lifetime applies
|
||||
void (*add_alloc_dep)(void * user_data, struct ggml_tensor * tensor, struct ggml_tensor * until);
|
||||
|
||||
// reserve `nbytes` of memory in the compute buffer of the backend, e.g. for data that several nodes share
|
||||
// the memory is reserved from before `first` is computed until `last` has been computed: outside of that range the
|
||||
// allocator can give it to other tensors, so its contents do not carry over between evaluations of the graph
|
||||
// `first` and `last` are nodes of the same graph, and `last` must not come before `first` in the optimized graph
|
||||
// returns a 1-d GGML_TYPE_I8 tensor that is not a node of the graph, its data is set when the graph is allocated
|
||||
// the backend can keep references to the tensor itself until the scheduler splits the next graph
|
||||
struct ggml_tensor * (*add_scratch)(void * user_data, size_t nbytes, struct ggml_tensor * first, struct ggml_tensor * last);
|
||||
|
||||
void * user_data;
|
||||
};
|
||||
|
||||
|
||||
@@ -133,6 +133,7 @@ static void ggml_backend_meta_device_get_props(ggml_backend_dev_t dev, ggml_back
|
||||
/* .buffer_from_host_ptr = */ false, // Not implemented.
|
||||
/* .events = */ false, // Not implemented.
|
||||
/* .mmap_support = */ true,
|
||||
/* .fast_async_host_input = */ false,
|
||||
};
|
||||
for (ggml_backend_dev_t simple_dev : meta_dev_ctx->simple_devs) {
|
||||
ggml_backend_dev_props tmp_props;
|
||||
@@ -152,6 +153,10 @@ static ggml_backend_buffer_type_t ggml_backend_meta_device_get_buffer_type(ggml_
|
||||
static ggml_backend_buffer_type_t ggml_backend_meta_device_get_host_buffer_type(ggml_backend_dev_t dev);
|
||||
|
||||
static bool ggml_backend_meta_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
|
||||
if (ggml_flash_attn_ext_has_indexed_bias(op)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
GGML_ASSERT(ggml_backend_dev_is_meta(dev));
|
||||
const ggml_backend_meta_device_context * meta_dev_ctx = (const ggml_backend_meta_device_context *) dev->context;
|
||||
return std::all_of(meta_dev_ctx->simple_devs.begin(), meta_dev_ctx->simple_devs.end(),
|
||||
@@ -699,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) {
|
||||
@@ -718,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]) {
|
||||
@@ -871,11 +877,22 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state(
|
||||
};
|
||||
|
||||
auto handle_gated_delta_net = [&](const std::vector<ggml_backend_meta_split_state> & src_ss) -> ggml_backend_meta_split_state {
|
||||
// replay (src 6..9): the pending k, v and gates/betas are split by heads like k, v and g, n_rep is per seq
|
||||
const bool replay = tensor->src[6] != nullptr;
|
||||
if (src_ss[0].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[1].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED &&
|
||||
src_ss[2].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[3].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED &&
|
||||
src_ss[4].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[5].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED) {
|
||||
for (int i = 6; replay && i < 10; i++) {
|
||||
GGML_ASSERT(src_ss[i].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED);
|
||||
}
|
||||
return src_ss[0];
|
||||
}
|
||||
if (replay) {
|
||||
GGML_ASSERT(src_ss[6].axis == GGML_BACKEND_SPLIT_AXIS_1);
|
||||
GGML_ASSERT(src_ss[7].axis == GGML_BACKEND_SPLIT_AXIS_1);
|
||||
GGML_ASSERT(src_ss[8].axis == GGML_BACKEND_SPLIT_AXIS_1);
|
||||
GGML_ASSERT(src_ss[9].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED);
|
||||
}
|
||||
GGML_ASSERT(src_ss[0].axis == GGML_BACKEND_SPLIT_AXIS_1);
|
||||
GGML_ASSERT(src_ss[1].axis == GGML_BACKEND_SPLIT_AXIS_1);
|
||||
GGML_ASSERT(src_ss[2].axis == GGML_BACKEND_SPLIT_AXIS_1);
|
||||
|
||||
+91
-12
@@ -21,6 +21,7 @@
|
||||
#include <string.h>
|
||||
#include <algorithm>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
#ifdef __APPLE__
|
||||
@@ -761,7 +762,17 @@ void ggml_backend_tensor_memset(struct ggml_tensor * tensor, uint8_t value, size
|
||||
GGML_ASSERT(buf != NULL && "tensor buffer not set");
|
||||
GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
|
||||
GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor write out of bounds");
|
||||
GGML_ASSERT(buf->iface.memset_tensor != NULL && "memset not implemented by backend buffer");
|
||||
|
||||
if (buf->iface.memset_tensor == NULL) {
|
||||
GGML_ASSERT(buf->iface.set_tensor != NULL && "memset not implemented by backend buffer");
|
||||
|
||||
// fallback: write the value in chunks with set_tensor
|
||||
const std::vector<uint8_t> chunk(std::min(size, (size_t) 1024*1024), value);
|
||||
for (size_t chunk_offset = 0; chunk_offset < size; chunk_offset += chunk.size()) {
|
||||
ggml_backend_tensor_set(tensor, chunk.data(), offset + chunk_offset, std::min(size - chunk_offset, chunk.size()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
buf->iface.memset_tensor(buf, tensor, value, offset, size);
|
||||
}
|
||||
@@ -1251,6 +1262,9 @@ struct ggml_backend_sched {
|
||||
// inputs of the next split read from the backend of the current split before it computes, see ggml_backend_sched_prefetch_inputs
|
||||
ggml_backend_event_t prefetch_events[GGML_SCHED_MAX_BACKENDS]; // created on first use, NULL if the backend has no events
|
||||
bool prefetch_tried [GGML_SCHED_MAX_BACKENDS];
|
||||
|
||||
// backends that take host inputs with set_tensor_async, see ggml_backend_dev_caps
|
||||
bool fast_async_host_input[GGML_SCHED_MAX_BACKENDS];
|
||||
struct ggml_tensor * prefetched[GGML_SCHED_MAX_SPLIT_INPUTS];
|
||||
int n_prefetched;
|
||||
int prefetch_split; // the split that reads the prefetched inputs
|
||||
@@ -1880,20 +1894,38 @@ void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgra
|
||||
sched->prev_leaf_backend_ids = tmp;
|
||||
}
|
||||
|
||||
// optimize the split graphs and collect the allocation dependencies added by the backends
|
||||
// optimize the split graphs and collect the allocation dependencies and scratch tensors added by the backends
|
||||
// this needs to happen before we make graph_copy, so they are in sync
|
||||
// TODO: this may create many small allocations in the scheduler, restructure to use a flat array
|
||||
std::unordered_map<ggml_tensor *, std::vector<ggml_tensor *>> alloc_deps;
|
||||
struct optimize_state {
|
||||
ggml_context * ctx;
|
||||
// node -> tensors kept allocated until the node has been computed
|
||||
std::unordered_map<ggml_tensor *, std::vector<ggml_tensor *>> alloc_deps;
|
||||
// node -> scratch tensors allocated before the node is computed
|
||||
std::unordered_map<ggml_tensor *, std::vector<ggml_tensor *>> scratch;
|
||||
} opt_state;
|
||||
opt_state.ctx = sched->ctx;
|
||||
|
||||
struct ggml_backend_graph_optimize_params opt_params = {
|
||||
/* .add_alloc_dep = */ [](void * user_data, ggml_tensor * tensor, ggml_tensor * until) {
|
||||
auto & deps = *(std::unordered_map<ggml_tensor *, std::vector<ggml_tensor *>> *) user_data;
|
||||
std::vector<ggml_tensor *> & keep = deps[until];
|
||||
auto & state = *(optimize_state *) user_data;
|
||||
std::vector<ggml_tensor *> & keep = state.alloc_deps[until];
|
||||
if (std::find(keep.begin(), keep.end(), tensor) == keep.end()) {
|
||||
keep.push_back(tensor);
|
||||
}
|
||||
},
|
||||
/* .user_data = */ &alloc_deps,
|
||||
/* .add_scratch = */ [](void * user_data, size_t nbytes, ggml_tensor * first, ggml_tensor * last) {
|
||||
auto & state = *(optimize_state *) user_data;
|
||||
GGML_ASSERT(nbytes > 0);
|
||||
ggml_tensor * t = ggml_new_tensor_1d(state.ctx, GGML_TYPE_I8, (int64_t) nbytes);
|
||||
std::vector<ggml_tensor *> & first_scratch = state.scratch[first];
|
||||
ggml_format_name(t, "scratch-%zu (%s)", first_scratch.size(), first->name);
|
||||
first_scratch.push_back(t);
|
||||
// the scratch tensor has no other users, the dep at `last` is what frees it
|
||||
state.alloc_deps[last].push_back(t);
|
||||
return t;
|
||||
},
|
||||
/* .user_data = */ &opt_state,
|
||||
};
|
||||
|
||||
for (int i = 0; i < sched->n_splits; i++) {
|
||||
@@ -1903,17 +1935,27 @@ void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgra
|
||||
ggml_backend_graph_optimize(sched->backends[split->backend_id], &split->graph, &opt_params);
|
||||
}
|
||||
|
||||
const auto & alloc_deps = opt_state.alloc_deps;
|
||||
|
||||
// each dep is added to graph_copy as a GGML_OP_NONE node with the kept tensors as srcs
|
||||
int n_dep_nodes = 0;
|
||||
for (const auto & it : alloc_deps) {
|
||||
n_dep_nodes += (it.second.size() + GGML_MAX_SRC - 1) / GGML_MAX_SRC;
|
||||
}
|
||||
|
||||
// each scratch tensor is added to graph_copy as a GGML_OP_NONE node right before its first user
|
||||
// scratch tensors not yet added to graph_copy
|
||||
std::unordered_set<ggml_tensor *> scratch_pending;
|
||||
for (const auto & it : opt_state.scratch) {
|
||||
scratch_pending.insert(it.second.begin(), it.second.end());
|
||||
}
|
||||
const int n_scratch_nodes = (int) scratch_pending.size();
|
||||
|
||||
int total_inputs = sched->n_graph_inputs;
|
||||
for (int i = 0; i < sched->n_splits; i++) {
|
||||
total_inputs += sched->splits[i].n_inputs;
|
||||
}
|
||||
int graph_size = std::max(graph->n_nodes, graph->n_leafs) + total_inputs * 2 * sched->n_copies + n_dep_nodes;
|
||||
int graph_size = std::max(graph->n_nodes, graph->n_leafs) + total_inputs * 2 * sched->n_copies + n_dep_nodes + n_scratch_nodes;
|
||||
|
||||
// remember the actual graph_size for performing reallocation checks later
|
||||
sched->prev_graph_size = sched->graph_size;
|
||||
@@ -1956,6 +1998,19 @@ void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgra
|
||||
}
|
||||
|
||||
for (int j = split->i_start; j < split->i_end; j++) {
|
||||
// add the scratch tensors first so that they are allocated before this node is computed
|
||||
if (!scratch_pending.empty()) {
|
||||
auto it = opt_state.scratch.find(graph->nodes[j]);
|
||||
if (it != opt_state.scratch.end()) {
|
||||
for (ggml_tensor * t : it->second) {
|
||||
assert(graph_copy->size > graph_copy->n_nodes);
|
||||
sched->node_backend_ids[graph_copy->n_nodes] = split->backend_id;
|
||||
graph_copy->nodes[graph_copy->n_nodes++] = t;
|
||||
scratch_pending.erase(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert(graph_copy->size > graph_copy->n_nodes);
|
||||
sched->node_backend_ids[graph_copy->n_nodes] = tensor_backend_id(graph->nodes[j]);
|
||||
graph_copy->nodes[graph_copy->n_nodes++] = graph->nodes[j];
|
||||
@@ -1971,6 +2026,8 @@ void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgra
|
||||
for (size_t k = 0; k < keep.size(); k += GGML_MAX_SRC) {
|
||||
struct ggml_tensor * dep = ggml_view_tensor(sched->ctx, keep[k]);
|
||||
for (size_t s = 0; s < GGML_MAX_SRC && k + s < keep.size(); s++) {
|
||||
// a scratch tensor freed before it was allocated: its `last` comes before its `first`
|
||||
GGML_ASSERT(scratch_pending.count(keep[k + s]) == 0 && "add_scratch: last is before first");
|
||||
dep->src[s] = keep[k + s];
|
||||
}
|
||||
assert(graph_copy->size > graph_copy->n_nodes);
|
||||
@@ -1984,6 +2041,8 @@ void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgra
|
||||
|
||||
// a mismatch means a backend added a dep with an `until` tensor that is not a node of the optimized graph
|
||||
GGML_ASSERT(n_dep_nodes_added == n_dep_nodes);
|
||||
// a scratch tensor left over means a backend passed a `first` tensor that is not a node of the optimized graph
|
||||
GGML_ASSERT(scratch_pending.empty() && "add_scratch: first is not a node of the graph");
|
||||
|
||||
if (sched->n_copies > 1) {
|
||||
// add input copies as leafs so that they are allocated first
|
||||
@@ -2097,7 +2156,8 @@ static bool ggml_backend_sched_is_host_weight(const struct ggml_tensor * t) {
|
||||
ggml_backend_buffer_is_host(t->buffer);
|
||||
}
|
||||
|
||||
static void ggml_backend_sched_copy_input(ggml_backend_sched_t sched, struct ggml_backend_sched_split * split, struct ggml_tensor * input) {
|
||||
// returns true if the copy is reading asynchronously from host memory, to safely write to the memory a synchronization on the split backend is then needed
|
||||
static bool ggml_backend_sched_copy_input(ggml_backend_sched_t sched, struct ggml_backend_sched_split * split, struct ggml_tensor * input) {
|
||||
const int split_backend_id = split->backend_id;
|
||||
ggml_backend_t split_backend = sched->backends[split_backend_id];
|
||||
ggml_backend_t input_backend = ggml_backend_sched_get_tensor_backend(sched, input);
|
||||
@@ -2108,11 +2168,20 @@ static void ggml_backend_sched_copy_input(ggml_backend_sched_t sched, struct ggm
|
||||
for (int i = 0; i < sched->n_prefetched; i++) {
|
||||
if (sched->prefetched[i] == input) {
|
||||
ggml_backend_event_synchronize(sched->prefetch_events[sched->prefetch_backend_id]);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// without pipeline parallelism the input copy has a single slot, so it can be written in order on the split backend
|
||||
ggml_backend_buffer_t input_buf = input->view_src ? input->view_src->buffer : input->buffer;
|
||||
if (sched->fast_async_host_input[split_backend_id] && sched->events[split_backend_id][sched->cur_copy] == NULL &&
|
||||
ggml_backend_dev_type(ggml_backend_get_device(input_backend)) == GGML_BACKEND_DEVICE_TYPE_CPU &&
|
||||
ggml_backend_buffer_is_host(input_buf) && !ggml_backend_sched_is_host_weight(input) && ggml_nbytes(input) > 0) {
|
||||
ggml_backend_tensor_set_async(split_backend, input_cpy, input->data, 0, ggml_nbytes(input));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (input->flags & GGML_TENSOR_FLAG_INPUT) {
|
||||
// inputs from the user must be copied immediately to prevent the user overwriting the data before the copy is done
|
||||
if (sched->events[split_backend_id][sched->cur_copy] != NULL) {
|
||||
@@ -2121,7 +2190,7 @@ static void ggml_backend_sched_copy_input(ggml_backend_sched_t sched, struct ggm
|
||||
ggml_backend_synchronize(split_backend);
|
||||
}
|
||||
ggml_backend_tensor_copy(input, input_cpy);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
// wait for the split backend to finish using the input before overwriting it
|
||||
@@ -2133,7 +2202,7 @@ static void ggml_backend_sched_copy_input(ggml_backend_sched_t sched, struct ggm
|
||||
|
||||
if (sched->callback_copy != NULL && ggml_backend_sched_is_host_weight(input) &&
|
||||
sched->callback_copy(split_backend, input, input_cpy, &split->graph, sched->callback_copy_user_data)) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
// try async copy, but if not possible, we can still use a sync copy without synchronizing the dst backend, since we handle the synchronization here with multiple copies and events
|
||||
@@ -2147,6 +2216,7 @@ static void ggml_backend_sched_copy_input(ggml_backend_sched_t sched, struct ggm
|
||||
}
|
||||
ggml_backend_tensor_copy(input, input_cpy);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// the inputs of the next split that are computed on the backend of this split before it, and copied to host memory,
|
||||
@@ -2233,12 +2303,17 @@ static enum ggml_status ggml_backend_sched_compute_splits(ggml_backend_sched_t s
|
||||
|
||||
// copy the input tensors to the split backend
|
||||
// the weights in host memory are copied last, so that the copy callback can read the other inputs of the split
|
||||
bool host_read_pending = false;
|
||||
for (int input_id = 0; input_id < split->n_inputs; input_id++) {
|
||||
struct ggml_tensor * input = split->inputs[input_id];
|
||||
if (!ggml_backend_sched_is_host_weight(input) && sched->hv_tensor_requires_copy[hash_id(input)]) {
|
||||
ggml_backend_sched_copy_input(sched, split, input);
|
||||
host_read_pending |= ggml_backend_sched_copy_input(sched, split, input);
|
||||
}
|
||||
}
|
||||
// the host data of async copies can be overwritten by later splits or by the user after this function returns
|
||||
if (host_read_pending) {
|
||||
ggml_backend_synchronize(split_backend);
|
||||
}
|
||||
// after the copies above, which may read host memory reused by the copies of the next split
|
||||
// before the weights, whose copy callback may queue large uploads
|
||||
ggml_backend_sched_prefetch_inputs(sched, split_id);
|
||||
@@ -2357,6 +2432,10 @@ ggml_backend_sched_t ggml_backend_sched_new(
|
||||
sched->bufts[b] = bufts ? bufts[b] : ggml_backend_get_default_buffer_type(backends[b]);
|
||||
GGML_ASSERT(ggml_backend_supports_buft(backends[b], sched->bufts[b]));
|
||||
|
||||
struct ggml_backend_dev_props props;
|
||||
ggml_backend_dev_get_props(ggml_backend_get_device(backends[b]), &props);
|
||||
sched->fast_async_host_input[b] = props.caps.fast_async_host_input && backends[b]->iface.set_tensor_async != NULL && !ggml_backend_is_meta(backends[b]);
|
||||
|
||||
if (sched->n_copies > 1) {
|
||||
for (int c = 0; c < sched->n_copies; c++) {
|
||||
sched->events[b][c] = ggml_backend_event_new(backends[b]->device);
|
||||
|
||||
@@ -370,6 +370,7 @@ static void ggml_backend_blas_device_get_props(ggml_backend_dev_t dev, struct gg
|
||||
/* .buffer_from_host_ptr = */ true,
|
||||
/* .events = */ false,
|
||||
/* .mmap_support = */ true,
|
||||
/* .fast_async_host_input = */ false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -397,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)) {
|
||||
@@ -2449,10 +2453,12 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten
|
||||
switch (op->src[0]->type) {
|
||||
#ifndef ASCEND_310P
|
||||
case GGML_TYPE_BF16:
|
||||
return true;
|
||||
#endif
|
||||
case GGML_TYPE_F16:
|
||||
case GGML_TYPE_F32:
|
||||
return true;
|
||||
// src1 goes to aclnn as is: a BF16 src1 with F16/F32 weights is not verified
|
||||
return op->src[1]->type != GGML_TYPE_BF16;
|
||||
case GGML_TYPE_Q8_0:
|
||||
case GGML_TYPE_Q4_0:
|
||||
#ifdef ASCEND_310P
|
||||
@@ -2470,7 +2476,8 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten
|
||||
switch (op->src[0]->type) {
|
||||
case GGML_TYPE_F16:
|
||||
case GGML_TYPE_F32:
|
||||
return true;
|
||||
// src1 goes to aclnn as is: a BF16 src1 with F16/F32 weights is not verified
|
||||
return op->src[1]->type != GGML_TYPE_BF16;
|
||||
case GGML_TYPE_Q8_0:
|
||||
case GGML_TYPE_Q4_0:
|
||||
#ifdef ASCEND_310P
|
||||
@@ -2679,8 +2686,8 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten
|
||||
return true;
|
||||
case GGML_OP_FLASH_ATTN_EXT:
|
||||
{
|
||||
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
|
||||
if (op->src[5] != nullptr) {
|
||||
// K/V row lists and indexed bias are not supported
|
||||
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) {
|
||||
return false;
|
||||
}
|
||||
#ifdef ASCEND_310P
|
||||
@@ -2847,6 +2854,7 @@ static void ggml_backend_cann_device_get_props(ggml_backend_dev_t dev, ggml_back
|
||||
/* .buffer_from_host_ptr = */ false,
|
||||
/* .events = */ true,
|
||||
/* .mmap_support = */ true,
|
||||
/* .fast_async_host_input = */ false,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -35,8 +35,10 @@
|
||||
|
||||
// precomputed tables for expanding 8bits to 8 bytes:
|
||||
static const uint64_t table_b2b_0[1 << 8] = { B8(00, 10) }; // ( b) << 4
|
||||
#if !defined(__ARM_FEATURE_SVE)
|
||||
static const uint64_t table_b2b_1[1 << 8] = { B8(10, 00) }; // (!b) << 4
|
||||
#endif
|
||||
#endif
|
||||
|
||||
void quantize_row_q8_0(const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int64_t k) {
|
||||
assert(QK8_0 == 32);
|
||||
@@ -920,6 +922,27 @@ void ggml_vec_dot_nvfp4_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const vo
|
||||
*s = sumf;
|
||||
}
|
||||
|
||||
#if defined(__ARM_FEATURE_SVE)
|
||||
static inline svbool_t load_as_svbool(const uint8_t * p, uint64_t vector_length) {
|
||||
#if defined(__GNUC__) || defined(__clang__)
|
||||
if (vector_length < 512) {
|
||||
svbool_t r;
|
||||
__asm__("ldr %0, %1"
|
||||
: "=Upa"(r)
|
||||
: "Q"(*(const struct { char bytes[32]; } *) p));
|
||||
return r;
|
||||
}
|
||||
#endif
|
||||
const svbool_t active = vector_length >= 512 ? svptrue_pat_b8(SV_VL32) : svptrue_b8();
|
||||
const uint64_t load_bytes = vector_length >= 512 ? 4 : svcntd();
|
||||
const svbool_t load = svwhilelt_b8_u64(0, load_bytes);
|
||||
const svuint8_t raw = svld1_u8(load, p);
|
||||
const svuint8_t sel = svlsr_n_u8_x(active, svindex_u8(0, 1), 3);
|
||||
const svuint8_t msk = svdupq_n_u8(1, 2, 4, 8, 16, 32, 64, 128, 1, 2, 4, 8, 16, 32, 64, 128);
|
||||
return svcmpne_n_u8(active, svand_u8_x(active, svtbl_u8(raw, sel), msk), 0);
|
||||
}
|
||||
#endif
|
||||
|
||||
void ggml_vec_dot_q5_0_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const void * GGML_RESTRICT vx, size_t bx, const void * GGML_RESTRICT vy, size_t by, int nrc) {
|
||||
const int qk = QK8_0;
|
||||
const int nb = n / qk;
|
||||
@@ -938,7 +961,106 @@ void ggml_vec_dot_q5_0_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const voi
|
||||
const block_q5_0 * GGML_RESTRICT x = vx;
|
||||
const block_q8_0 * GGML_RESTRICT y = vy;
|
||||
|
||||
#if defined(__ARM_NEON)
|
||||
#if defined(__ARM_FEATURE_SVE)
|
||||
svfloat32_t sumv0 = svdup_n_f32(0.0f);
|
||||
svfloat32_t sumv1 = svdup_n_f32(0.0f);
|
||||
|
||||
const int vector_length = ggml_cpu_get_sve_cnt()*8;
|
||||
|
||||
switch (vector_length) {
|
||||
case 128:
|
||||
{
|
||||
const svbool_t p16 = svptrue_pat_b8(SV_VL16);
|
||||
const svbool_t p4 = svptrue_pat_b32(SV_VL4);
|
||||
|
||||
for (; ib + 1 < nb; ib += 2) {
|
||||
const block_q5_0 * GGML_RESTRICT x0 = &x[ib];
|
||||
const block_q5_0 * GGML_RESTRICT x1 = &x[ib + 1];
|
||||
const block_q8_0 * GGML_RESTRICT y0 = &y[ib];
|
||||
const block_q8_0 * GGML_RESTRICT y1 = &y[ib + 1];
|
||||
|
||||
const svbool_t qhl0p = load_as_svbool(x0->qh, vector_length);
|
||||
const svbool_t qhh0p = load_as_svbool(((const uint8_t *) x0->qh + 2), vector_length);
|
||||
const svbool_t qhl1p = load_as_svbool(x1->qh, vector_length);
|
||||
const svbool_t qhh1p = load_as_svbool(((const uint8_t *) x1->qh + 2), vector_length);
|
||||
|
||||
const svint8_t qhl0 = svdup_n_s8_z(svnot_b_z(p16, qhl0p), 0x10);
|
||||
const svint8_t qhh0 = svdup_n_s8_z(svnot_b_z(p16, qhh0p), 0x10);
|
||||
const svint8_t qhl1 = svdup_n_s8_z(svnot_b_z(p16, qhl1p), 0x10);
|
||||
const svint8_t qhh1 = svdup_n_s8_z(svnot_b_z(p16, qhh1p), 0x10);
|
||||
|
||||
const svuint8_t qx0r = svld1rq_u8(p16, x0->qs);
|
||||
const svuint8_t qx1r = svld1rq_u8(p16, x1->qs);
|
||||
|
||||
const svint8_t qx0l = svreinterpret_s8_u8(svand_n_u8_x(p16, qx0r, 0x0F));
|
||||
const svint8_t qx0h = svreinterpret_s8_u8(svlsr_n_u8_x(p16, qx0r, 0x04));
|
||||
const svint8_t qx1l = svreinterpret_s8_u8(svand_n_u8_x(p16, qx1r, 0x0F));
|
||||
const svint8_t qx1h = svreinterpret_s8_u8(svlsr_n_u8_x(p16, qx1r, 0x04));
|
||||
|
||||
const svint8_t qx0lf = svsub_s8_x(p16, qx0l, qhl0);
|
||||
const svint8_t qx0hf = svsub_s8_x(p16, qx0h, qhh0);
|
||||
const svint8_t qx1lf = svsub_s8_x(p16, qx1l, qhl1);
|
||||
const svint8_t qx1hf = svsub_s8_x(p16, qx1h, qhh1);
|
||||
|
||||
const svint8_t qy0l = svld1_s8(p16, y0->qs);
|
||||
const svint8_t qy0h = svld1_s8(p16, y0->qs + 16);
|
||||
const svint8_t qy1l = svld1_s8(p16, y1->qs);
|
||||
const svint8_t qy1h = svld1_s8(p16, y1->qs + 16);
|
||||
|
||||
sumv0 = svmla_n_f32_x(p4, sumv0, svcvt_f32_s32_x(p4, svadd_s32_x(p4,
|
||||
svdot_s32(svdup_n_s32(0), qx0lf, qy0l),
|
||||
svdot_s32(svdup_n_s32(0), qx0hf, qy0h))), GGML_CPU_FP16_TO_FP32(x0->d)*GGML_CPU_FP16_TO_FP32(y0->d));
|
||||
sumv1 = svmla_n_f32_x(p4, sumv1, svcvt_f32_s32_x(p4, svadd_s32_x(p4,
|
||||
svdot_s32(svdup_n_s32(0), qx1lf, qy1l),
|
||||
svdot_s32(svdup_n_s32(0), qx1hf, qy1h))), GGML_CPU_FP16_TO_FP32(x1->d)*GGML_CPU_FP16_TO_FP32(y1->d));
|
||||
}
|
||||
|
||||
sumf = svaddv_f32(p4, svadd_f32_x(p4, sumv0, sumv1));
|
||||
} break;
|
||||
case 256:
|
||||
case 512:
|
||||
{
|
||||
const svbool_t p32 = svptrue_pat_b8(SV_VL32);
|
||||
const svbool_t p16h = svptrue_pat_b8(SV_VL16);
|
||||
const svbool_t p16l = svnot_b_z(p32, p16h);
|
||||
const svbool_t p8 = svptrue_pat_b32(SV_VL8);
|
||||
|
||||
for (; ib + 1 < nb; ib += 2) {
|
||||
const block_q5_0 * GGML_RESTRICT x0 = &x[ib];
|
||||
const block_q5_0 * GGML_RESTRICT x1 = &x[ib + 1];
|
||||
const block_q8_0 * GGML_RESTRICT y0 = &y[ib];
|
||||
const block_q8_0 * GGML_RESTRICT y1 = &y[ib + 1];
|
||||
|
||||
svbool_t qhbits0p = load_as_svbool(x0->qh, vector_length);
|
||||
svbool_t qhbits1p = load_as_svbool(x1->qh, vector_length);
|
||||
const svint8_t qhbits0 = svdup_n_s8_z(svnot_b_z(p32, qhbits0p), 0x10);
|
||||
const svint8_t qhbits1 = svdup_n_s8_z(svnot_b_z(p32, qhbits1p), 0x10);
|
||||
|
||||
const svuint8_t qx0r = svld1rq_u8(p32, x0->qs);
|
||||
const svuint8_t qx1r = svld1rq_u8(p32, x1->qs);
|
||||
|
||||
const svint8_t qx0 = svreinterpret_s8_u8(svlsr_n_u8_m(p16l, svand_n_u8_m(p16h, qx0r, 0x0F), 0x04));
|
||||
const svint8_t qx1 = svreinterpret_s8_u8(svlsr_n_u8_m(p16l, svand_n_u8_m(p16h, qx1r, 0x0F), 0x04));
|
||||
|
||||
const svint8_t qx0f = svsub_s8_x(p32, qx0, qhbits0);
|
||||
const svint8_t qx1f = svsub_s8_x(p32, qx1, qhbits1);
|
||||
|
||||
const svint8_t qy0 = svld1_s8(p32, y0->qs);
|
||||
const svint8_t qy1 = svld1_s8(p32, y1->qs);
|
||||
|
||||
sumv0 = svmla_n_f32_x(p8, sumv0, svcvt_f32_s32_x(p8,
|
||||
svdot_s32(svdup_n_s32(0), qx0f, qy0)), GGML_CPU_FP16_TO_FP32(x0->d)*GGML_CPU_FP16_TO_FP32(y0->d));
|
||||
sumv1 = svmla_n_f32_x(p8, sumv1, svcvt_f32_s32_x(p8,
|
||||
svdot_s32(svdup_n_s32(0), qx1f, qy1)), GGML_CPU_FP16_TO_FP32(x1->d)*GGML_CPU_FP16_TO_FP32(y1->d));
|
||||
}
|
||||
|
||||
sumf = svaddv_f32(p8, svadd_f32_x(p8, sumv0, sumv1));
|
||||
} break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
#elif defined(__ARM_NEON)
|
||||
float32x4_t sumv0 = vdupq_n_f32(0.0f);
|
||||
float32x4_t sumv1 = vdupq_n_f32(0.0f);
|
||||
|
||||
@@ -1050,7 +1172,115 @@ void ggml_vec_dot_q5_1_q8_1(int n, float * GGML_RESTRICT s, size_t bs, const voi
|
||||
const block_q5_1 * GGML_RESTRICT x = vx;
|
||||
const block_q8_1 * GGML_RESTRICT y = vy;
|
||||
|
||||
#if defined(__ARM_NEON)
|
||||
#if defined(__ARM_FEATURE_SVE)
|
||||
svfloat32_t sumv0 = svdup_n_f32(0.0f);
|
||||
svfloat32_t sumv1 = svdup_n_f32(0.0f);
|
||||
|
||||
float summs0 = 0.0f;
|
||||
float summs1 = 0.0f;
|
||||
|
||||
const int vector_length = ggml_cpu_get_sve_cnt()*8;
|
||||
|
||||
switch (vector_length) {
|
||||
case 128:
|
||||
{
|
||||
const svbool_t p16 = svptrue_pat_b8(SV_VL16);
|
||||
const svbool_t p4 = svptrue_pat_b32(SV_VL4);
|
||||
|
||||
for (; ib + 1 < nb; ib += 2) {
|
||||
const block_q5_1 * GGML_RESTRICT x0 = &x[ib];
|
||||
const block_q5_1 * GGML_RESTRICT x1 = &x[ib + 1];
|
||||
const block_q8_1 * GGML_RESTRICT y0 = &y[ib];
|
||||
const block_q8_1 * GGML_RESTRICT y1 = &y[ib + 1];
|
||||
|
||||
summs0 += GGML_CPU_FP16_TO_FP32(x0->m) * GGML_CPU_FP16_TO_FP32(y0->s);
|
||||
summs1 += GGML_CPU_FP16_TO_FP32(x1->m) * GGML_CPU_FP16_TO_FP32(y1->s);
|
||||
|
||||
const svbool_t qhl0p = load_as_svbool(x0->qh, vector_length);
|
||||
const svbool_t qhh0p = load_as_svbool(((const uint8_t *) x0->qh + 2), vector_length);
|
||||
const svbool_t qhl1p = load_as_svbool(x1->qh, vector_length);
|
||||
const svbool_t qhh1p = load_as_svbool(((const uint8_t *) x1->qh + 2), vector_length);
|
||||
|
||||
const svint8_t qhl0 = svdup_n_s8_z(qhl0p, 0x10);
|
||||
const svint8_t qhh0 = svdup_n_s8_z(qhh0p, 0x10);
|
||||
const svint8_t qhl1 = svdup_n_s8_z(qhl1p, 0x10);
|
||||
const svint8_t qhh1 = svdup_n_s8_z(qhh1p, 0x10);
|
||||
|
||||
const svuint8_t qx0r = svld1rq_u8(p16, x0->qs);
|
||||
const svuint8_t qx1r = svld1rq_u8(p16, x1->qs);
|
||||
|
||||
const svint8_t qx0l = svreinterpret_s8_u8(svand_n_u8_x(p16, qx0r, 0x0F));
|
||||
const svint8_t qx0h = svreinterpret_s8_u8(svlsr_n_u8_x(p16, qx0r, 0x04));
|
||||
const svint8_t qx1l = svreinterpret_s8_u8(svand_n_u8_x(p16, qx1r, 0x0F));
|
||||
const svint8_t qx1h = svreinterpret_s8_u8(svlsr_n_u8_x(p16, qx1r, 0x04));
|
||||
|
||||
const svint8_t qx0lf = svreinterpret_s8_u8(svorr_u8_x(p16, svreinterpret_u8_s8(qx0l), svreinterpret_u8_s8(qhl0)));
|
||||
const svint8_t qx0hf = svreinterpret_s8_u8(svorr_u8_x(p16, svreinterpret_u8_s8(qx0h), svreinterpret_u8_s8(qhh0)));
|
||||
const svint8_t qx1lf = svreinterpret_s8_u8(svorr_u8_x(p16, svreinterpret_u8_s8(qx1l), svreinterpret_u8_s8(qhl1)));
|
||||
const svint8_t qx1hf = svreinterpret_s8_u8(svorr_u8_x(p16, svreinterpret_u8_s8(qx1h), svreinterpret_u8_s8(qhh1)));
|
||||
|
||||
const svint8_t qy0l = svld1_s8(p16, y0->qs);
|
||||
const svint8_t qy0h = svld1_s8(p16, y0->qs + 16);
|
||||
const svint8_t qy1l = svld1_s8(p16, y1->qs);
|
||||
const svint8_t qy1h = svld1_s8(p16, y1->qs + 16);
|
||||
|
||||
sumv0 = svmla_n_f32_x(p4, sumv0, svcvt_f32_s32_x(p4, svadd_s32_x(p4,
|
||||
svdot_s32(svdup_n_s32(0), qx0lf, qy0l),
|
||||
svdot_s32(svdup_n_s32(0), qx0hf, qy0h))), GGML_CPU_FP16_TO_FP32(x0->d)*GGML_CPU_FP16_TO_FP32(y0->d));
|
||||
sumv1 = svmla_n_f32_x(p4, sumv1, svcvt_f32_s32_x(p4, svadd_s32_x(p4,
|
||||
svdot_s32(svdup_n_s32(0), qx1lf, qy1l),
|
||||
svdot_s32(svdup_n_s32(0), qx1hf, qy1h))), GGML_CPU_FP16_TO_FP32(x1->d)*GGML_CPU_FP16_TO_FP32(y1->d));
|
||||
}
|
||||
|
||||
sumf = svaddv_f32(p4, svadd_f32_x(p4, sumv0, sumv1)) + summs0 + summs1;
|
||||
} break;
|
||||
case 256:
|
||||
case 512:
|
||||
{
|
||||
const svbool_t p32 = svptrue_pat_b8(SV_VL32);
|
||||
const svbool_t p16h = svptrue_pat_b8(SV_VL16);
|
||||
const svbool_t p16l = svnot_b_z(p32, p16h);
|
||||
const svbool_t p8 = svptrue_pat_b32(SV_VL8);
|
||||
|
||||
for (; ib + 1 < nb; ib += 2) {
|
||||
const block_q5_1 * GGML_RESTRICT x0 = &x[ib];
|
||||
const block_q5_1 * GGML_RESTRICT x1 = &x[ib + 1];
|
||||
const block_q8_1 * GGML_RESTRICT y0 = &y[ib];
|
||||
const block_q8_1 * GGML_RESTRICT y1 = &y[ib + 1];
|
||||
|
||||
summs0 += GGML_CPU_FP16_TO_FP32(x0->m) * GGML_CPU_FP16_TO_FP32(y0->s);
|
||||
summs1 += GGML_CPU_FP16_TO_FP32(x1->m) * GGML_CPU_FP16_TO_FP32(y1->s);
|
||||
|
||||
const svbool_t qhbits0p = load_as_svbool(x0->qh, vector_length);
|
||||
const svbool_t qhbits1p = load_as_svbool(x1->qh, vector_length);
|
||||
const svint8_t qhbits0 = svdup_n_s8_z(qhbits0p, 0x10);
|
||||
const svint8_t qhbits1 = svdup_n_s8_z(qhbits1p, 0x10);
|
||||
|
||||
const svuint8_t qx0r = svld1rq_u8(p32, x0->qs);
|
||||
const svuint8_t qx1r = svld1rq_u8(p32, x1->qs);
|
||||
|
||||
const svint8_t qx0 = svreinterpret_s8_u8(svlsr_n_u8_m(p16l, svand_n_u8_m(p16h, qx0r, 0x0F), 0x04));
|
||||
const svint8_t qx1 = svreinterpret_s8_u8(svlsr_n_u8_m(p16l, svand_n_u8_m(p16h, qx1r, 0x0F), 0x04));
|
||||
|
||||
const svint8_t qx0f = svreinterpret_s8_u8(svorr_u8_x(p32, svreinterpret_u8_s8(qx0), svreinterpret_u8_s8(qhbits0)));
|
||||
const svint8_t qx1f = svreinterpret_s8_u8(svorr_u8_x(p32, svreinterpret_u8_s8(qx1), svreinterpret_u8_s8(qhbits1)));
|
||||
|
||||
const svint8_t qy0 = svld1_s8(p32, y0->qs);
|
||||
const svint8_t qy1 = svld1_s8(p32, y1->qs);
|
||||
|
||||
sumv0 = svmla_n_f32_x(p8, sumv0, svcvt_f32_s32_x(p8,
|
||||
svdot_s32(svdup_n_s32(0), qx0f, qy0)), GGML_CPU_FP16_TO_FP32(x0->d)*GGML_CPU_FP16_TO_FP32(y0->d));
|
||||
sumv1 = svmla_n_f32_x(p8, sumv1, svcvt_f32_s32_x(p8,
|
||||
svdot_s32(svdup_n_s32(0), qx1f, qy1)), GGML_CPU_FP16_TO_FP32(x1->d)*GGML_CPU_FP16_TO_FP32(y1->d));
|
||||
}
|
||||
|
||||
sumf = svaddv_f32(p8, svadd_f32_x(p8, sumv0, sumv1)) + summs0 + summs1;
|
||||
} break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
#elif defined(__ARM_NEON)
|
||||
float32x4_t sumv0 = vdupq_n_f32(0.0f);
|
||||
float32x4_t sumv1 = vdupq_n_f32(0.0f);
|
||||
|
||||
@@ -4319,4 +4549,3 @@ void ggml_vec_dot_iq4_xs_q8_K(int n, float * GGML_RESTRICT s, size_t bs, const v
|
||||
ggml_vec_dot_iq4_xs_q8_K_generic(n, s, bs, vx, bx, vy, by, nrc);
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
@@ -66,6 +66,70 @@ static inline int8x16_t ggml_q1_0_unpack_pair(uint8_t bits0, uint8_t bits1) {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(__aarch64__) && defined(__ARM_NEON) && !defined(__ARM_FEATURE_DOTPROD)
|
||||
// Split repacked q4_0 bytes into sign-extended low and high nibbles
|
||||
static inline void ggml_q4_0x4_unpack(int8x16_t b, int8x16_t * lo, int8x16_t * hi) {
|
||||
*lo = vshrq_n_s8(vshlq_n_s8(b, 4), 4);
|
||||
*hi = vshrq_n_s8(b, 4);
|
||||
}
|
||||
|
||||
// w holds 8 bytes of 2 columns, a holds the same 8 bytes twice: acc[c] += column c * a
|
||||
static inline void ggml_mla_2x8_s16(int16x8_t * acc, int8x16_t w, int8x16_t a) {
|
||||
acc[0] = vmlal_s8(acc[0], vget_low_s8(w), vget_low_s8(a));
|
||||
acc[1] = vmlal_high_s8(acc[1], w, a);
|
||||
}
|
||||
|
||||
// w holds 8 bytes of 2 columns, a holds 8 bytes of 2 rows: r0[c] += column c * row 0, r1[c] += column c * row 1
|
||||
static inline void ggml_mla_2x2x8_s16(int16x8_t * r0, int16x8_t * r1, int8x16_t w, int8x16_t a) {
|
||||
const int8x16_t as = vextq_s8(a, a, 8);
|
||||
|
||||
r0[0] = vmlal_s8(r0[0], vget_low_s8(w), vget_low_s8(a));
|
||||
r1[1] = vmlal_high_s8(r1[1], w, a);
|
||||
r1[0] = vmlal_s8(r1[0], vget_low_s8(w), vget_low_s8(as));
|
||||
r0[1] = vmlal_high_s8(r0[1], w, as);
|
||||
}
|
||||
|
||||
// Same as ggml_mla_2x8_s16 for two chunks, widened to int32
|
||||
static inline void ggml_dot2_2x8_s32(int32x4_t * acc, int8x16_t w0, int8x16_t a0, int8x16_t w1, int8x16_t a1) {
|
||||
int16x8_t p0 = vmull_s8(vget_low_s8(w0), vget_low_s8(a0));
|
||||
int16x8_t p1 = vmull_high_s8(w0, a0);
|
||||
|
||||
p0 = vmlal_s8(p0, vget_low_s8(w1), vget_low_s8(a1));
|
||||
p1 = vmlal_high_s8(p1, w1, a1);
|
||||
|
||||
acc[0] = vpadalq_s16(acc[0], p0);
|
||||
acc[1] = vpadalq_s16(acc[1], p1);
|
||||
}
|
||||
|
||||
// Same as ggml_mla_2x2x8_s16 for two chunks, widened to int32
|
||||
static inline void ggml_dot2_2x2x8_s32(int32x4_t * r0,
|
||||
int32x4_t * r1,
|
||||
int8x16_t w0,
|
||||
int8x16_t a0,
|
||||
int8x16_t w1,
|
||||
int8x16_t a1) {
|
||||
const int8x16_t as0 = vextq_s8(a0, a0, 8);
|
||||
const int8x16_t as1 = vextq_s8(a1, a1, 8);
|
||||
const int8x8_t w0l = vget_low_s8(w0);
|
||||
const int8x8_t w1l = vget_low_s8(w1);
|
||||
|
||||
r0[0] = vpadalq_s16(r0[0], vmlal_s8(vmull_s8(w0l, vget_low_s8(a0)), w1l, vget_low_s8(a1)));
|
||||
r1[1] = vpadalq_s16(r1[1], vmlal_high_s8(vmull_high_s8(w0, a0), w1, a1));
|
||||
r1[0] = vpadalq_s16(r1[0], vmlal_s8(vmull_s8(w0l, vget_low_s8(as0)), w1l, vget_low_s8(as1)));
|
||||
r0[1] = vpadalq_s16(r0[1], vmlal_high_s8(vmull_high_s8(w0, as0), w1, as1));
|
||||
}
|
||||
|
||||
// Sum each of 4 int16 accumulators into one int32 lane, the lanes must be below 16384
|
||||
static inline int32x4_t ggml_hsum_4x_s16(const int16x8_t * acc) {
|
||||
return vpaddq_s32(vpaddlq_s16(vpaddq_s16(acc[0], acc[1])), vpaddlq_s16(vpaddq_s16(acc[2], acc[3])));
|
||||
}
|
||||
|
||||
// Sum each of 4 int32 accumulators into one int32 lane
|
||||
static inline int32x4_t ggml_hsum_4x_s32(const int32x4_t * acc) {
|
||||
return vpaddq_s32(vpaddq_s32(acc[0], acc[1]), vpaddq_s32(acc[2], acc[3]));
|
||||
}
|
||||
#endif
|
||||
|
||||
void ggml_quantize_mat_q8_0_4x4(const float * GGML_RESTRICT x, void * GGML_RESTRICT vy, int64_t k) {
|
||||
assert(QK8_0 == 32);
|
||||
assert(k % QK8_0 == 0);
|
||||
@@ -351,6 +415,46 @@ void ggml_gemv_q4_0_4x8_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const vo
|
||||
}
|
||||
return;
|
||||
#endif // #if ! ((defined(_MSC_VER)) && ! defined(__clang__)) && defined(__aarch64__) && defined(__ARM_NEON) && defined(__ARM_FEATURE_DOTPROD)
|
||||
|
||||
#if ! ((defined(_MSC_VER)) && ! defined(__clang__)) && defined(__aarch64__) && defined(__ARM_NEON) && ! defined(__ARM_FEATURE_DOTPROD)
|
||||
// No dotprod: sum products in int16 lanes. Sign-extended nibbles allow 8 products per lane (8 * 8 * 127 < 32767), nibbles << 4 only 2.
|
||||
// A 16-byte load holds 8 bytes of 2 columns, each column has its own accumulator with 4 products per lane.
|
||||
const block_q4_0x4 * b_ptr = (const block_q4_0x4 *) vx;
|
||||
|
||||
for (int c = 0; c < nc; c += ncols_interleaved) {
|
||||
const block_q8_0 * a_ptr = (const block_q8_0 *) vy;
|
||||
float32x4_t acc = vdupq_n_f32(0);
|
||||
for (int b = 0; b < nb; b++) {
|
||||
int16x8_t sum[4] = { vdupq_n_s16(0), vdupq_n_s16(0), vdupq_n_s16(0), vdupq_n_s16(0) };
|
||||
|
||||
for (int k = 0; k < 2; k++) {
|
||||
const int8x8_t al8 = vld1_s8(a_ptr->qs + 8 * k);
|
||||
const int8x8_t ah8 = vld1_s8(a_ptr->qs + qk/2 + 8 * k);
|
||||
const int8x16_t al = vcombine_s8(al8, al8);
|
||||
const int8x16_t ah = vcombine_s8(ah8, ah8);
|
||||
int8x16_t wl, wh;
|
||||
|
||||
ggml_q4_0x4_unpack(vld1q_s8(b_ptr->qs + 32 * k), &wl, &wh);
|
||||
ggml_mla_2x8_s16(&sum[0], wl, al);
|
||||
ggml_mla_2x8_s16(&sum[0], wh, ah);
|
||||
|
||||
ggml_q4_0x4_unpack(vld1q_s8(b_ptr->qs + 32 * k + 16), &wl, &wh);
|
||||
ggml_mla_2x8_s16(&sum[2], wl, al);
|
||||
ggml_mla_2x8_s16(&sum[2], wh, ah);
|
||||
}
|
||||
|
||||
const float32x4_t bd = vcvt_f32_f16(vld1_f16((const __fp16 *) b_ptr->d));
|
||||
|
||||
acc = vfmaq_f32(acc, vcvtq_f32_s32(ggml_hsum_4x_s16(sum)),
|
||||
vmulq_n_f32(bd, GGML_CPU_FP16_TO_FP32(a_ptr->d)));
|
||||
a_ptr++;
|
||||
b_ptr++;
|
||||
}
|
||||
vst1q_f32(s, acc);
|
||||
s += ncols_interleaved;
|
||||
}
|
||||
return;
|
||||
#endif // #if ! ((defined(_MSC_VER)) && ! defined(__clang__)) && defined(__aarch64__) && defined(__ARM_NEON) && ! defined(__ARM_FEATURE_DOTPROD)
|
||||
ggml_gemv_q4_0_4x8_q8_0_generic(n, s, bs, vx, vy, nr, nc);
|
||||
}
|
||||
|
||||
@@ -1957,6 +2061,43 @@ void ggml_gemv_q8_0_4x8_q8_0(int n,
|
||||
return;
|
||||
|
||||
#endif // defined(__aarch64__) && defined(__ARM_NEON) && defined(__ARM_FEATURE_DOTPROD)
|
||||
|
||||
#if defined(__aarch64__) && defined(__ARM_NEON) && !defined(__ARM_FEATURE_DOTPROD)
|
||||
// No dotprod: two products fit an int16 lane (2 * 128 * 127 < 32767), then widen to int32.
|
||||
// A 16-byte load holds 8 bytes of 2 columns, each column has its own int32 accumulator.
|
||||
const block_q8_0x4 * b_ptr = (const block_q8_0x4 *) vx;
|
||||
|
||||
for (int c = 0; c < nc; c += ncols_interleaved) {
|
||||
const block_q8_0 * a_ptr = (const block_q8_0 *) vy;
|
||||
float32x4_t acc = vdupq_n_f32(0);
|
||||
for (int b = 0; b < nb; b++) {
|
||||
int32x4_t sum[4] = { vdupq_n_s32(0), vdupq_n_s32(0), vdupq_n_s32(0), vdupq_n_s32(0) };
|
||||
|
||||
for (int k = 0; k < 4; k += 2) {
|
||||
const int8x8_t a08 = vld1_s8(a_ptr->qs + 8 * k);
|
||||
const int8x8_t a18 = vld1_s8(a_ptr->qs + 8 * (k + 1));
|
||||
const int8x16_t a0 = vcombine_s8(a08, a08);
|
||||
const int8x16_t a1 = vcombine_s8(a18, a18);
|
||||
|
||||
const int8_t * w0 = b_ptr->qs + 32 * k;
|
||||
const int8_t * w1 = b_ptr->qs + 32 * (k + 1);
|
||||
|
||||
ggml_dot2_2x8_s32(&sum[0], vld1q_s8(w0), a0, vld1q_s8(w1), a1);
|
||||
ggml_dot2_2x8_s32(&sum[2], vld1q_s8(w0 + 16), a0, vld1q_s8(w1 + 16), a1);
|
||||
}
|
||||
|
||||
const float32x4_t bd = vcvt_f32_f16(vld1_f16((const __fp16 *) b_ptr->d));
|
||||
|
||||
acc =
|
||||
vfmaq_f32(acc, vcvtq_f32_s32(ggml_hsum_4x_s32(sum)), vmulq_n_f32(bd, GGML_CPU_FP16_TO_FP32(a_ptr->d)));
|
||||
a_ptr++;
|
||||
b_ptr++;
|
||||
}
|
||||
vst1q_f32(s, acc);
|
||||
s += ncols_interleaved;
|
||||
}
|
||||
return;
|
||||
#endif // defined(__aarch64__) && defined(__ARM_NEON) && !defined(__ARM_FEATURE_DOTPROD)
|
||||
ggml_gemv_q8_0_4x8_q8_0_generic(n, s, bs, vx, vy, nr, nc);
|
||||
}
|
||||
|
||||
@@ -2985,6 +3126,64 @@ void ggml_gemm_q4_0_4x8_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const vo
|
||||
);
|
||||
return;
|
||||
#endif // #if ! ((defined(_MSC_VER)) && ! defined(__clang__)) && defined(__aarch64__) && defined(__ARM_NEON) && defined(__ARM_FEATURE_MATMUL_INT8)
|
||||
|
||||
#if ! ((defined(_MSC_VER)) && ! defined(__clang__)) && defined(__aarch64__) && defined(__ARM_NEON) && ! defined(__ARM_FEATURE_DOTPROD)
|
||||
// No dotprod: see ggml_gemv_q4_0_4x8_q8_0, one int16 accumulator per (row, column). The high nibbles go with the activations at qs + 64.
|
||||
for (int y = 0; y < nr / 4; y++) {
|
||||
const block_q8_0x4 * a_ptr = (const block_q8_0x4 *) vy + (y * nb);
|
||||
for (int x = 0; x < nc / ncols_interleaved; x++) {
|
||||
const block_q4_0x4 * b_ptr = (const block_q4_0x4 *) vx + (x * nb);
|
||||
|
||||
float32x4_t sumf[4];
|
||||
for (int m = 0; m < 4; m++) {
|
||||
sumf[m] = vdupq_n_f32(0);
|
||||
}
|
||||
|
||||
for (int l = 0; l < nb; l++) {
|
||||
int16x8_t sum[4][4];
|
||||
for (int m = 0; m < 4; m++) {
|
||||
for (int j = 0; j < 4; j++) {
|
||||
sum[m][j] = vdupq_n_s16(0);
|
||||
}
|
||||
}
|
||||
|
||||
for (int k = 0; k < 2; k++) {
|
||||
int8x16_t w01l, w01h, w23l, w23h;
|
||||
ggml_q4_0x4_unpack(vld1q_s8(b_ptr[l].qs + 32 * k), &w01l, &w01h);
|
||||
ggml_q4_0x4_unpack(vld1q_s8(b_ptr[l].qs + 32 * k + 16), &w23l, &w23h);
|
||||
|
||||
const int8x16_t a01l = vld1q_s8(a_ptr[l].qs + 32 * k);
|
||||
const int8x16_t a23l = vld1q_s8(a_ptr[l].qs + 32 * k + 16);
|
||||
const int8x16_t a01h = vld1q_s8(a_ptr[l].qs + 64 + 32 * k);
|
||||
const int8x16_t a23h = vld1q_s8(a_ptr[l].qs + 64 + 32 * k + 16);
|
||||
|
||||
ggml_mla_2x2x8_s16(&sum[0][0], &sum[1][0], w01l, a01l);
|
||||
ggml_mla_2x2x8_s16(&sum[0][2], &sum[1][2], w23l, a01l);
|
||||
ggml_mla_2x2x8_s16(&sum[2][0], &sum[3][0], w01l, a23l);
|
||||
ggml_mla_2x2x8_s16(&sum[2][2], &sum[3][2], w23l, a23l);
|
||||
|
||||
ggml_mla_2x2x8_s16(&sum[0][0], &sum[1][0], w01h, a01h);
|
||||
ggml_mla_2x2x8_s16(&sum[0][2], &sum[1][2], w23h, a01h);
|
||||
ggml_mla_2x2x8_s16(&sum[2][0], &sum[3][0], w01h, a23h);
|
||||
ggml_mla_2x2x8_s16(&sum[2][2], &sum[3][2], w23h, a23h);
|
||||
}
|
||||
|
||||
const float32x4_t b_d = vcvt_f32_f16(vld1_f16((const __fp16 *) b_ptr[l].d));
|
||||
const float32x4_t a_d = vcvt_f32_f16(vld1_f16((const __fp16 *) a_ptr[l].d));
|
||||
|
||||
sumf[0] = vfmaq_f32(sumf[0], vcvtq_f32_s32(ggml_hsum_4x_s16(sum[0])), vmulq_laneq_f32(b_d, a_d, 0));
|
||||
sumf[1] = vfmaq_f32(sumf[1], vcvtq_f32_s32(ggml_hsum_4x_s16(sum[1])), vmulq_laneq_f32(b_d, a_d, 1));
|
||||
sumf[2] = vfmaq_f32(sumf[2], vcvtq_f32_s32(ggml_hsum_4x_s16(sum[2])), vmulq_laneq_f32(b_d, a_d, 2));
|
||||
sumf[3] = vfmaq_f32(sumf[3], vcvtq_f32_s32(ggml_hsum_4x_s16(sum[3])), vmulq_laneq_f32(b_d, a_d, 3));
|
||||
}
|
||||
|
||||
for (int m = 0; m < 4; m++) {
|
||||
vst1q_f32(s + (y * 4 + m) * bs + x * ncols_interleaved, sumf[m]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
#endif // #if ! ((defined(_MSC_VER)) && ! defined(__clang__)) && defined(__aarch64__) && defined(__ARM_NEON) && ! defined(__ARM_FEATURE_DOTPROD)
|
||||
ggml_gemm_q4_0_4x8_q8_0_generic(n, s, bs, vx, vy, nr, nc);
|
||||
}
|
||||
|
||||
@@ -5602,6 +5801,59 @@ void ggml_gemm_q8_0_4x8_q8_0(int n,
|
||||
}
|
||||
return;
|
||||
#endif // defined(__aarch64__) && defined(__ARM_NEON) && defined(__ARM_FEATURE_MATMUL_INT8)
|
||||
|
||||
#if defined(__aarch64__) && defined(__ARM_NEON) && !defined(__ARM_FEATURE_DOTPROD)
|
||||
// No dotprod: see ggml_gemv_q8_0_4x8_q8_0, one int32 accumulator per (row, column)
|
||||
for (int y = 0; y < nr / 4; y++) {
|
||||
const block_q8_0x4 * a_ptr = (const block_q8_0x4 *) vy + (y * nb);
|
||||
for (int x = 0; x < nc / ncols_interleaved; x++) {
|
||||
const block_q8_0x4 * b_ptr = (const block_q8_0x4 *) vx + (x * nb);
|
||||
|
||||
float32x4_t sumf[4];
|
||||
for (int m = 0; m < 4; m++) {
|
||||
sumf[m] = vdupq_n_f32(0);
|
||||
}
|
||||
|
||||
for (int l = 0; l < nb; l++) {
|
||||
int32x4_t sum[4][4];
|
||||
for (int m = 0; m < 4; m++) {
|
||||
for (int j = 0; j < 4; j++) {
|
||||
sum[m][j] = vdupq_n_s32(0);
|
||||
}
|
||||
}
|
||||
|
||||
for (int k = 0; k < 4; k += 2) {
|
||||
const int8x16_t w01_0 = vld1q_s8(b_ptr[l].qs + 32 * k);
|
||||
const int8x16_t w23_0 = vld1q_s8(b_ptr[l].qs + 32 * k + 16);
|
||||
const int8x16_t w01_1 = vld1q_s8(b_ptr[l].qs + 32 * (k + 1));
|
||||
const int8x16_t w23_1 = vld1q_s8(b_ptr[l].qs + 32 * (k + 1) + 16);
|
||||
const int8x16_t a01_0 = vld1q_s8(a_ptr[l].qs + 32 * k);
|
||||
const int8x16_t a23_0 = vld1q_s8(a_ptr[l].qs + 32 * k + 16);
|
||||
const int8x16_t a01_1 = vld1q_s8(a_ptr[l].qs + 32 * (k + 1));
|
||||
const int8x16_t a23_1 = vld1q_s8(a_ptr[l].qs + 32 * (k + 1) + 16);
|
||||
|
||||
ggml_dot2_2x2x8_s32(&sum[0][0], &sum[1][0], w01_0, a01_0, w01_1, a01_1);
|
||||
ggml_dot2_2x2x8_s32(&sum[0][2], &sum[1][2], w23_0, a01_0, w23_1, a01_1);
|
||||
ggml_dot2_2x2x8_s32(&sum[2][0], &sum[3][0], w01_0, a23_0, w01_1, a23_1);
|
||||
ggml_dot2_2x2x8_s32(&sum[2][2], &sum[3][2], w23_0, a23_0, w23_1, a23_1);
|
||||
}
|
||||
|
||||
const float32x4_t a_d = vcvt_f32_f16(vld1_f16((const float16_t *) a_ptr[l].d));
|
||||
const float32x4_t b_d = vcvt_f32_f16(vld1_f16((const float16_t *) b_ptr[l].d));
|
||||
|
||||
sumf[0] = vfmaq_f32(sumf[0], vcvtq_f32_s32(ggml_hsum_4x_s32(sum[0])), vmulq_laneq_f32(b_d, a_d, 0));
|
||||
sumf[1] = vfmaq_f32(sumf[1], vcvtq_f32_s32(ggml_hsum_4x_s32(sum[1])), vmulq_laneq_f32(b_d, a_d, 1));
|
||||
sumf[2] = vfmaq_f32(sumf[2], vcvtq_f32_s32(ggml_hsum_4x_s32(sum[2])), vmulq_laneq_f32(b_d, a_d, 2));
|
||||
sumf[3] = vfmaq_f32(sumf[3], vcvtq_f32_s32(ggml_hsum_4x_s32(sum[3])), vmulq_laneq_f32(b_d, a_d, 3));
|
||||
}
|
||||
|
||||
for (int m = 0; m < 4; m++) {
|
||||
vst1q_f32(s + (y * 4 + m) * bs + x * ncols_interleaved, sumf[m]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
#endif // defined(__aarch64__) && defined(__ARM_NEON) && !defined(__ARM_FEATURE_DOTPROD)
|
||||
ggml_gemm_q8_0_4x8_q8_0_generic(n, s, bs, vx, vy, nr, nc);
|
||||
}
|
||||
|
||||
|
||||
+128
-15
@@ -1287,6 +1287,57 @@ static void ggml_compute_forward_mul_mat_one_chunk(
|
||||
}
|
||||
}
|
||||
|
||||
// converts n BF16 values (whole blocks of vec_dot_type) to vec_dot_type: widened directly to F32, otherwise via F32 in chunks
|
||||
static void ggml_cpu_bf16_to_vec_dot_type(const ggml_bf16_t * x, void * y, int64_t n, enum ggml_type vec_dot_type) {
|
||||
if (vec_dot_type == GGML_TYPE_F32) {
|
||||
ggml_cpu_bf16_to_fp32(x, (float *) y, n);
|
||||
return;
|
||||
}
|
||||
|
||||
ggml_from_float_t const from_float = type_traits_cpu[vec_dot_type].from_float;
|
||||
const int64_t bs = ggml_blck_size(vec_dot_type);
|
||||
|
||||
float tmp[1024];
|
||||
const int64_t chunk = (1024/bs)*bs;
|
||||
for (int64_t i = 0; i < n; i += chunk) {
|
||||
const int64_t nc = MIN(chunk, n - i);
|
||||
ggml_cpu_bf16_to_fp32(x + i, tmp, nc);
|
||||
from_float(tmp, (char *) y + (i/bs)*ggml_type_size(vec_dot_type), nc);
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
@@ -1302,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;
|
||||
}
|
||||
|
||||
@@ -1358,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:;
|
||||
@@ -1372,11 +1425,9 @@ UseGgmlGemm1:;
|
||||
const size_t nbw3 = nbw2*ne12;
|
||||
|
||||
assert(params->wsize >= ne13*nbw3);
|
||||
// src1 is either packed from F32 into vec_dot_type, or widened from F16 or BF16 into the F32 work buffer
|
||||
const bool widen = src1->type != GGML_TYPE_F32;
|
||||
|
||||
GGML_ASSERT(!widen || vec_dot_type == GGML_TYPE_F32);
|
||||
GGML_ASSERT(!widen || src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_BF16);
|
||||
// src1 is either packed from F32 or BF16 into vec_dot_type, or widened from F16 or BF16 into the F32 work buffer
|
||||
GGML_ASSERT(src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16 ||
|
||||
(src1->type == GGML_TYPE_F16 && vec_dot_type == GGML_TYPE_F32));
|
||||
|
||||
#if 0
|
||||
for (int64_t i13 = 0; i13 < ne13; ++i13) {
|
||||
@@ -1404,7 +1455,7 @@ UseGgmlGemm1:;
|
||||
if (src1->type == GGML_TYPE_F16) {
|
||||
ggml_cpu_fp16_to_fp32((const ggml_fp16_t *) src1_row, (float *) wdata_row, ne10_block_size);
|
||||
} else if (src1->type == GGML_TYPE_BF16) {
|
||||
ggml_cpu_bf16_to_fp32((const ggml_bf16_t *) src1_row, (float *) wdata_row, ne10_block_size);
|
||||
ggml_cpu_bf16_to_vec_dot_type((const ggml_bf16_t *) src1_row, wdata_row, ne10_block_size, vec_dot_type);
|
||||
} else {
|
||||
from_float((const float *) src1_row, wdata_row, ne10_block_size);
|
||||
}
|
||||
@@ -1440,6 +1491,7 @@ UseGgmlGemm1:;
|
||||
vec_dot_type,
|
||||
dst->type))
|
||||
goto UseGgmlGemm2;
|
||||
ggml_compute_forward_mul_mat_scale(params, dst);
|
||||
return;
|
||||
}
|
||||
UseGgmlGemm2:;
|
||||
@@ -1507,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
|
||||
@@ -1589,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) {
|
||||
@@ -1656,7 +1757,7 @@ static void ggml_compute_forward_mul_mat_id(
|
||||
const size_t nbw3 = nbw2*ne12;
|
||||
|
||||
assert(params->wsize >= ne13*nbw3);
|
||||
GGML_ASSERT(src1->type == GGML_TYPE_F32);
|
||||
GGML_ASSERT(src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16);
|
||||
|
||||
#if 0
|
||||
for (int64_t i13 = 0; i13 < ne13; ++i13) {
|
||||
@@ -1675,9 +1776,13 @@ static void ggml_compute_forward_mul_mat_id(
|
||||
size_t bs = ggml_blck_size(vec_dot_type);
|
||||
int64_t ne10_block_start = (ith * ne10/bs) / nth;
|
||||
int64_t ne10_block_end = ((ith + 1) * ne10/bs) / nth;
|
||||
from_float((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + ne10_block_start*bs*nb10),
|
||||
(void *) (wdata + i13*nbw3 + i12*nbw2 + i11*nbw1 + ne10_block_start*nbw0),
|
||||
(ne10_block_end - ne10_block_start) * bs);
|
||||
const void * src1_row = (const char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + ne10_block_start*bs*nb10;
|
||||
void * wdata_row = wdata + i13*nbw3 + i12*nbw2 + i11*nbw1 + ne10_block_start*nbw0;
|
||||
if (src1->type == GGML_TYPE_BF16) {
|
||||
ggml_cpu_bf16_to_vec_dot_type((const ggml_bf16_t *) src1_row, wdata_row, (ne10_block_end - ne10_block_start) * bs, vec_dot_type);
|
||||
} else {
|
||||
from_float((const float *) src1_row, wdata_row, (ne10_block_end - ne10_block_start) * bs);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1779,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);
|
||||
}
|
||||
|
||||
/////////////////////////////////
|
||||
@@ -1792,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;
|
||||
}
|
||||
|
||||
@@ -2909,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;
|
||||
@@ -2957,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;
|
||||
}
|
||||
@@ -3068,9 +3180,10 @@ struct ggml_cplan ggml_graph_plan(
|
||||
} break;
|
||||
case GGML_OP_GATED_DELTA_NET:
|
||||
{
|
||||
const int64_t S_v = node->src[2]->ne[0];
|
||||
const int64_t K = ggml_get_op_params_i32(node, 0);
|
||||
const int64_t per_thread = S_v + (K > 1 ? S_v * S_v : 0);
|
||||
const int64_t S_v = node->src[2]->ne[0];
|
||||
const int64_t K = ggml_get_op_params_i32(node, 0);
|
||||
const bool keep = node->src[6] && ggml_get_op_params_i32(node, 2) != 0;
|
||||
const int64_t per_thread = S_v + (K > 1 || keep ? S_v * S_v : 0);
|
||||
cur = per_thread * sizeof(float) * n_tasks;
|
||||
} break;
|
||||
case GGML_OP_COUNT:
|
||||
|
||||
@@ -398,6 +398,7 @@ static void ggml_backend_cpu_device_get_props(ggml_backend_dev_t dev, struct ggm
|
||||
/* .buffer_from_host_ptr = */ true,
|
||||
/* .events = */ false,
|
||||
/* .mmap_support = */ true,
|
||||
/* .fast_async_host_input = */ false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -440,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
|
||||
@@ -452,14 +455,19 @@ static bool ggml_backend_cpu_device_supports_op(ggml_backend_dev_t dev, const st
|
||||
op->type != GGML_TYPE_IQ1_M; // missing type_traits.from_float
|
||||
case GGML_OP_MUL_MAT:
|
||||
if (ggml_get_op_params_i32(op, 1) == GGML_HINT_SRC0_IS_HADAMARD &&
|
||||
src0->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32) {
|
||||
return src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16;
|
||||
src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) {
|
||||
// the hinted matmul is an FWHT of src1 for every src0 type, which reads F32 or F16 only;
|
||||
// with use_ref it takes the general path instead, so src1 has to pass the check below too
|
||||
return false;
|
||||
}
|
||||
// F16 or BF16 in src1 is widened into the F32 work buffer
|
||||
return src1->type == GGML_TYPE_F32 ||
|
||||
// F16 in src1 is widened into the F32 work buffer, BF16 is widened or converted to vec_dot_type
|
||||
return src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16 ||
|
||||
src1->type == ggml_get_type_traits_cpu(src0->type)->vec_dot_type ||
|
||||
((src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_BF16) &&
|
||||
ggml_get_type_traits_cpu(src0->type)->vec_dot_type == GGML_TYPE_F32);
|
||||
(src1->type == GGML_TYPE_F16 && ggml_get_type_traits_cpu(src0->type)->vec_dot_type == GGML_TYPE_F32);
|
||||
case GGML_OP_MUL_MAT_ID:
|
||||
// src1 is converted to vec_dot_type from F32 or BF16 only
|
||||
return src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16 ||
|
||||
src1->type == ggml_get_type_traits_cpu(src0->type)->vec_dot_type;
|
||||
case GGML_OP_SOFT_MAX_BACK: {
|
||||
if (op->src[0]->type != GGML_TYPE_F32 || op->src[1]->type != GGML_TYPE_F32) {
|
||||
return false;
|
||||
@@ -688,6 +696,9 @@ static void * ggml_backend_cpu_get_proc_address(ggml_backend_reg_t reg, const ch
|
||||
if (strcmp(name, "ggml_threadpool_free") == 0) {
|
||||
return (void *)ggml_threadpool_free;
|
||||
}
|
||||
if (strcmp(name, "ggml_threadpool_pause") == 0) {
|
||||
return (void *)ggml_threadpool_pause;
|
||||
}
|
||||
if (strcmp(name, "ggml_backend_cpu_set_threadpool") == 0) {
|
||||
return (void *)ggml_backend_cpu_set_threadpool;
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ if (NOT TARGET kleidiai)
|
||||
endif()
|
||||
|
||||
if (MSVC)
|
||||
target_compile_options(kleidiai PRIVATE $<$<COMPILE_LANGUAGE:C,CXX>:/WX->)
|
||||
target_compile_options(kleidiai PRIVATE "$<$<COMPILE_LANGUAGE:C,CXX>:/WX-;/w>")
|
||||
else()
|
||||
target_compile_options(kleidiai PRIVATE $<$<COMPILE_LANGUAGE:C,CXX>:-Wno-error>)
|
||||
target_compile_options(kleidiai PRIVATE "$<$<COMPILE_LANGUAGE:C,CXX>:-Wno-error;-w>")
|
||||
endif()
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -8981,6 +8981,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
|
||||
const ggml_tensor * mask = dst->src[3];
|
||||
const ggml_tensor * sinks = dst->src[4];
|
||||
const ggml_tensor * kv_rows = dst->src[5];
|
||||
const ggml_tensor * bias_table = dst->src[6];
|
||||
const ggml_tensor * bias_indices = dst->src[7];
|
||||
|
||||
GGML_TENSOR_LOCALS(int64_t, neq, q, ne)
|
||||
GGML_TENSOR_LOCALS(size_t, nbq, q, nb)
|
||||
@@ -9022,6 +9024,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
|
||||
const int64_t rv2 = neq2/nev2;
|
||||
const int64_t rv3 = neq3/nev3;
|
||||
|
||||
const int64_t n_bins = bias_table ? bias_table->ne[0] : 0;
|
||||
|
||||
// parallelize by q rows using ggml_vec_dot_f32
|
||||
|
||||
float scale = 1.0f;
|
||||
@@ -9085,12 +9089,21 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
|
||||
|
||||
const int32_t * rows = kv_rows ? (const int32_t *) ((const char *) kv_rows->data + iq3*kv_rows->nb[1]) : nullptr;
|
||||
|
||||
// bias rows of this query and head, queries of all streams are flattened
|
||||
const float * bias = bias_table ? (const float *) ((const char *) bias_table->data + (iq3*neq1 + iq1)*bias_table->nb[2] + iq2*bias_table->nb[1]) : nullptr;
|
||||
const int32_t * bins = bias_indices ? (const int32_t *) ((const char *) bias_indices->data + (iq3*neq1 + iq1)*bias_indices->nb[1]) : nullptr;
|
||||
|
||||
// online softmax / attention
|
||||
// loop over n_kv and n_head_kv
|
||||
// ref: https://arxiv.org/pdf/2112.05682.pdf
|
||||
|
||||
for (int64_t ic = ic_start; ic < ic_end; ++ic) {
|
||||
const float mv = mp ? slope*GGML_CPU_FP16_TO_FP32(mp[ic]) : 0.0f;
|
||||
float mv = mp ? GGML_CPU_FP16_TO_FP32(mp[ic]) : 0.0f;
|
||||
if (bias) {
|
||||
GGML_ASSERT(bins[ic] >= 0 && bins[ic] < n_bins);
|
||||
mv += bias[bins[ic]];
|
||||
}
|
||||
mv *= slope;
|
||||
if (mv == -INFINITY) {
|
||||
continue;
|
||||
}
|
||||
@@ -9268,6 +9281,10 @@ static void ggml_compute_forward_flash_attn_ext_tiled(
|
||||
const ggml_tensor * kv_rows = dst->src[5];
|
||||
const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : nek1;
|
||||
|
||||
const ggml_tensor * bias_table = dst->src[6];
|
||||
const ggml_tensor * bias_indices = dst->src[7];
|
||||
const int64_t n_bins = bias_table ? bias_table->ne[0] : 0;
|
||||
|
||||
int ir = ir0;
|
||||
while (ir < ir1) {
|
||||
// q indices for the start of this tile
|
||||
@@ -9346,8 +9363,15 @@ static void ggml_compute_forward_flash_attn_ext_tiled(
|
||||
bool can_skip = true;
|
||||
for (int tq = 0; tq < tile_rows; tq++) {
|
||||
const ggml_fp16_t * mp_row = (const ggml_fp16_t *)((const char *) mask->data + (iq1 + tq)*mask->nb[1] + (iq2%mask->ne[2])*mask->nb[2] + (iq3%mask->ne[3])*mask->nb[3]);
|
||||
const float * bias = bias_table ? (const float *) ((const char *) bias_table->data + (iq3*neq1 + iq1 + tq)*bias_table->nb[2] + iq2*bias_table->nb[1]) : nullptr;
|
||||
const int32_t * bins = bias_indices ? (const int32_t *) ((const char *) bias_indices->data + (iq3*neq1 + iq1 + tq)*bias_indices->nb[1]) : nullptr;
|
||||
for (int tk = 0; tk < kv_tile; tk++) {
|
||||
mask32[tq * KV_TILE_SZ + tk] = slope * GGML_CPU_FP16_TO_FP32(mp_row[ic + tk]);
|
||||
float m = GGML_CPU_FP16_TO_FP32(mp_row[ic + tk]);
|
||||
if (bias) {
|
||||
GGML_ASSERT(bins[ic + tk] >= 0 && bins[ic + tk] < n_bins);
|
||||
m += bias[bins[ic + tk]];
|
||||
}
|
||||
mask32[tq * KV_TILE_SZ + tk] = slope * m;
|
||||
if (mask32[tq * KV_TILE_SZ + tk] != -INFINITY) {
|
||||
can_skip = false;
|
||||
}
|
||||
@@ -9698,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:
|
||||
@@ -11289,11 +11314,19 @@ static void ggml_compute_forward_gated_delta_net_one_chunk(
|
||||
// per-seq stride in floats (seq s starts at state + s * seq_stride)
|
||||
const int64_t state_seq_stride = src_state->nb[3] / sizeof(float);
|
||||
|
||||
const int64_t per_thread = S_v + (K > 1 ? S_v * S_v : 0);
|
||||
// replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
|
||||
const ggml_tensor * src_pk = dst->src[6];
|
||||
const ggml_tensor * src_pv = dst->src[7];
|
||||
const ggml_tensor * src_pgb = dst->src[8];
|
||||
const ggml_tensor * src_n_rep = dst->src[9];
|
||||
const int64_t n_pend = src_pk ? ggml_get_op_params_i32(dst, 1) : 0;
|
||||
const bool keep = src_pk && ggml_get_op_params_i32(dst, 2) != 0;
|
||||
|
||||
const int64_t per_thread = S_v + (K > 1 || keep ? S_v * S_v : 0);
|
||||
const int ith = params->ith;
|
||||
|
||||
float * delta = (float *)params->wdata + ith * per_thread + CACHE_LINE_SIZE_F32;
|
||||
float * state_work = K > 1 ? (delta + S_v) : nullptr;
|
||||
float * state_work = K > 1 || keep ? (delta + S_v) : nullptr;
|
||||
|
||||
// output layout: [attn_scores | new_states]
|
||||
// attn_scores: S_v * H * n_tokens * n_seqs floats
|
||||
@@ -11327,7 +11360,7 @@ static void ggml_compute_forward_gated_delta_net_one_chunk(
|
||||
|
||||
// For K=1, write directly to the single output slot to avoid an extra memcpy at the end.
|
||||
// For K>1, work in scratch and copy out per-token when the slot is in range.
|
||||
float * s_out = (K > 1)
|
||||
float * s_out = (K > 1 || keep)
|
||||
? state_work
|
||||
: state_out_base + (iv3 * H + iv1) * S_v * S_v;
|
||||
|
||||
@@ -11336,6 +11369,48 @@ static void ggml_compute_forward_gated_delta_net_one_chunk(
|
||||
const float * s_in = state_in_base + iv3 * state_seq_stride + iv1 * S_v * S_v;
|
||||
memcpy(s_out, s_in, S_v * S_v * sizeof(float));
|
||||
|
||||
if (src_pk) {
|
||||
const int64_t n_r = ((const int32_t *) src_n_rep->data)[iv3];
|
||||
GGML_ASSERT(n_r >= 0 && n_r <= n_pend);
|
||||
|
||||
const char * pk = (const char *) src_pk->data + iv3*src_pk->nb[3] + ik1*src_pk->nb[1];
|
||||
const char * pv = (const char *) src_pv->data + iv3*src_pv->nb[3] + iv1*src_pv->nb[1];
|
||||
const char * pgb = (const char *) src_pgb->data + iv3*src_pgb->nb[3] + iv1*src_pgb->nb[1];
|
||||
|
||||
for (int64_t t = 0; t < n_r; t++) {
|
||||
const float * k_d = (const float *) (pk + t*src_pk->nb[2]);
|
||||
const float * v_d = (const float *) (pv + t*src_pv->nb[2]);
|
||||
const float * g_d = (const float *) (pgb + t*src_pgb->nb[2]);
|
||||
const float beta_val = *(const float *) (pgb + (n_pend + t)*src_pgb->nb[2]);
|
||||
|
||||
if (kda) {
|
||||
for (int64_t i = 0; i < S_v; ++i) {
|
||||
delta[i] = expf(g_d[i]);
|
||||
}
|
||||
for (int64_t j = 0; j < S_v; ++j) {
|
||||
ggml_vec_mul_f32(S_v, &s_out[j * S_v], &s_out[j * S_v], delta);
|
||||
}
|
||||
} else {
|
||||
ggml_vec_scale_f32(S_v * S_v, s_out, expf(g_d[0]));
|
||||
}
|
||||
|
||||
for (int64_t j = 0; j < S_v; ++j) {
|
||||
float sum = 0.0f;
|
||||
ggml_vec_dot_f32(S_v, &sum, 0, &s_out[j * S_v], 0, k_d, 0, 1);
|
||||
delta[j] = (v_d[j] - sum) * beta_val;
|
||||
}
|
||||
|
||||
for (int64_t j = 0; j < S_v; ++j) {
|
||||
ggml_vec_mad_f32(S_v, &s_out[j * S_v], k_d, delta[j]);
|
||||
}
|
||||
}
|
||||
|
||||
// the committed state, the new tokens go on in the scratch
|
||||
if (keep) {
|
||||
memcpy(state_out_base + (iv3 * H + iv1) * S_v * S_v, s_out, S_v * S_v * sizeof(float));
|
||||
}
|
||||
}
|
||||
|
||||
// attn output pointer for first token of this (head, seq)
|
||||
float * attn_data = attn_out_base + (iv3 * n_tokens * H + iv1) * S_v;
|
||||
|
||||
|
||||
@@ -4992,6 +4992,15 @@ static const ggml::cpu::tensor_traits * ggml_repack_get_optimal_repack_type(cons
|
||||
return &q4_0_4x4_q8_0;
|
||||
}
|
||||
}
|
||||
#if defined(__aarch64__) && !defined(__APPLE__)
|
||||
// no dotprod (e.g. Cortex-A53): AArch64 only, on 32-bit ARM the 4x8 kernels run scalar code
|
||||
// not on Apple: repacked weights cannot go to BLAS (Accelerate), which is faster there for large batches
|
||||
if (ggml_cpu_has_neon() && !ggml_cpu_has_dotprod()) {
|
||||
if (cur->ne[1] % 4 == 0) {
|
||||
return &q4_0_4x8_q8_0;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
if (ggml_cpu_has_vxe()) {
|
||||
if (cur->ne[1] % 4 == 0) {
|
||||
return &q4_0_4x4_q8_0;
|
||||
@@ -5118,6 +5127,15 @@ static const ggml::cpu::tensor_traits * ggml_repack_get_optimal_repack_type(cons
|
||||
return &q8_0_4x4_q8_0;
|
||||
}
|
||||
}
|
||||
#if defined(__aarch64__) && !defined(__APPLE__)
|
||||
// no dotprod (e.g. Cortex-A53): AArch64 only, on 32-bit ARM the 4x8 kernels run scalar code
|
||||
// not on Apple: repacked weights cannot go to BLAS (Accelerate), which is faster there for large batches
|
||||
if (ggml_cpu_has_neon() && !ggml_cpu_has_dotprod()) {
|
||||
if (cur->ne[1] % 4 == 0) {
|
||||
return &q8_0_4x8_q8_0;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
if (ggml_cpu_has_riscv_v()) {
|
||||
#if defined __riscv_zvfh
|
||||
switch (__riscv_vlenb() * 8) {
|
||||
|
||||
@@ -1047,8 +1047,8 @@ class tensor_traits_common : public tensor_traits_base {
|
||||
return true;
|
||||
}
|
||||
case GGML_OP_FLASH_ATTN_EXT:
|
||||
// K/V row lists are handled by the generic CPU path
|
||||
if (op->src[5] != nullptr) {
|
||||
// K/V row lists and the indexed bias are handled by the generic CPU path
|
||||
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) {
|
||||
return false;
|
||||
}
|
||||
forward_flash_attn_ext_f16(params, op);
|
||||
@@ -1156,7 +1156,8 @@ class tensor_traits_common : public tensor_traits_base {
|
||||
}
|
||||
return true;
|
||||
case GGML_OP_GATED_DELTA_NET:
|
||||
if (params->use_ref) {
|
||||
// the generic kernel does the replay of pending tokens (op param 1)
|
||||
if (params->use_ref || ggml_get_op_params_i32(op, 1) != 0) {
|
||||
return false;
|
||||
}
|
||||
switch (op->src[0]->type) {
|
||||
|
||||
@@ -1199,13 +1199,15 @@ void forward_flash_attn_ext_f16_one_chunk_vlen1024_vf16(const ggml_compute_param
|
||||
(iq3 % mask->ne[3]) * mask->nb[3]) :
|
||||
NULL;
|
||||
|
||||
const bool mp_equal_2 = iq1_1 == iq1 && (iq2 % mask->ne[2]) == (iq2_1 % mask->ne[2]) &&
|
||||
(iq3 % mask->ne[3]) == (iq3_1 % mask->ne[3]);
|
||||
// the multi-row kernels share one mask row and one ALiBi slope across the grouped q rows
|
||||
const bool mp_equal_2 =
|
||||
max_bias == 0.0f && iq1_1 == iq1 &&
|
||||
(!mask || ((iq2 % mask->ne[2]) == (iq2_1 % mask->ne[2]) && (iq3 % mask->ne[3]) == (iq3_1 % mask->ne[3])));
|
||||
|
||||
const bool mp_equal_4 = mp_equal_2 && iq1_2 == iq1 && (iq2 % mask->ne[2]) == (iq2_2 % mask->ne[2]) &&
|
||||
(iq3 % mask->ne[3]) == (iq3_2 % mask->ne[3]) && iq1_3 == iq1 &&
|
||||
(iq2 % mask->ne[2]) == (iq2_3 % mask->ne[2]) &&
|
||||
(iq3 % mask->ne[3]) == (iq3_3 % mask->ne[3]);
|
||||
const bool mp_equal_4 =
|
||||
mp_equal_2 && iq1_2 == iq1 && iq1_3 == iq1 &&
|
||||
(!mask || ((iq2 % mask->ne[2]) == (iq2_2 % mask->ne[2]) && (iq3 % mask->ne[3]) == (iq3_2 % mask->ne[3]) &&
|
||||
(iq2 % mask->ne[2]) == (iq2_3 % mask->ne[2]) && (iq3 % mask->ne[3]) == (iq3_3 % mask->ne[3])));
|
||||
|
||||
// k indices
|
||||
const int ik3 = iq3 / rk3;
|
||||
@@ -1514,7 +1516,11 @@ void forward_flash_attn_ext_f16_tiled_vlen1024_vf16(const ggml_compute_params *
|
||||
}
|
||||
}
|
||||
|
||||
// Set padded KQ entries to -inf so softmax gives them zero weight
|
||||
if (logit_softcap != 0.0f) {
|
||||
rvv_softcap_tanh_inplace_f32(KQ, KV_TILE_SZ, tile_rows, KV_TILE_SZ, logit_softcap);
|
||||
}
|
||||
|
||||
// Set padded KQ entries to -inf so softmax gives them zero weight (after softcap, which would make them finite)
|
||||
if (kv_tile < KV_TILE_SZ) {
|
||||
for (int tq = 0; tq < tile_rows; tq++) {
|
||||
for (int tk = kv_tile; tk < KV_TILE_SZ; tk++) {
|
||||
@@ -1523,10 +1529,6 @@ void forward_flash_attn_ext_f16_tiled_vlen1024_vf16(const ggml_compute_params *
|
||||
}
|
||||
}
|
||||
|
||||
if (logit_softcap != 0.0f) {
|
||||
rvv_softcap_tanh_inplace_f32(KQ, KV_TILE_SZ, tile_rows, KV_TILE_SZ, logit_softcap);
|
||||
}
|
||||
|
||||
if (mask) {
|
||||
rvv_add_inplace_f32(KQ, KV_TILE_SZ, mask32, KV_TILE_SZ, tile_rows, KV_TILE_SZ);
|
||||
}
|
||||
|
||||
@@ -627,7 +627,7 @@ static bool ggml_tiled_supported(const struct ggml_tensor * src0,
|
||||
case GGML_TYPE_IQ3_S:
|
||||
case GGML_TYPE_IQ1_S:
|
||||
case GGML_TYPE_IQ1_M:
|
||||
return true;
|
||||
break;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -116,16 +116,12 @@ if (CUDAToolkit_FOUND)
|
||||
list(APPEND GGML_HEADERS_CUDA "../../include/ggml-cuda.h")
|
||||
|
||||
file(GLOB GGML_SOURCES_CUDA "*.cu")
|
||||
file(GLOB SRCS "template-instances/fattn-tile*.cu")
|
||||
list(APPEND GGML_SOURCES_CUDA ${SRCS})
|
||||
file(GLOB SRCS "template-instances/fattn-mma*.cu")
|
||||
list(APPEND GGML_SOURCES_CUDA ${SRCS})
|
||||
file(GLOB SRCS "template-instances/mmq*.cu")
|
||||
list(APPEND GGML_SOURCES_CUDA ${SRCS})
|
||||
file(GLOB SRCS "template-instances/mmf*.cu")
|
||||
list(APPEND GGML_SOURCES_CUDA ${SRCS})
|
||||
|
||||
ggml_cuda_fattn_vec_instances(${CMAKE_CURRENT_SOURCE_DIR} SRCS)
|
||||
ggml_cuda_fattn_instances(${CMAKE_CURRENT_SOURCE_DIR} SRCS)
|
||||
list(APPEND GGML_SOURCES_CUDA ${SRCS})
|
||||
|
||||
ggml_add_backend_library(ggml-cuda
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -256,6 +256,18 @@ static void launch_bin_bcast_pack(const ggml_tensor * src0, const ggml_tensor *
|
||||
size_t s02 = nb02 / sizeof(src0_t);
|
||||
size_t s03 = nb03 / sizeof(src0_t);
|
||||
|
||||
// the index of a dim of size 1 is always 0, so its stride is never applied,
|
||||
// but after collapsing contiguous dims it can be the whole tensor size and exceed 32 bits
|
||||
if (cne0[1] == 1) { s01 = 0; }
|
||||
if (cne0[2] == 1) { s02 = 0; }
|
||||
if (cne0[3] == 1) { s03 = 0; }
|
||||
if (cne1[1] == 1) { s11 = 0; }
|
||||
if (cne1[2] == 1) { s12 = 0; }
|
||||
if (cne1[3] == 1) { s13 = 0; }
|
||||
if (ne1 == 1) { s1 = 0; }
|
||||
if (ne2 == 1) { s2 = 0; }
|
||||
if (ne3 == 1) { s3 = 0; }
|
||||
|
||||
GGML_ASSERT(ne0 <= std::numeric_limits<uint32_t>::max());
|
||||
GGML_ASSERT(ne1 <= std::numeric_limits<uint32_t>::max());
|
||||
GGML_ASSERT(ne2 <= std::numeric_limits<uint32_t>::max());
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -104,38 +104,41 @@ static __global__ void __launch_bounds__(CUDA_CONCAT_BLOCK_SIZE)
|
||||
uint64_t nb13,
|
||||
int64_t ne0,
|
||||
int64_t /*ne1*/,
|
||||
int64_t /*ne2*/,
|
||||
int64_t /*ne3*/,
|
||||
int64_t ne2,
|
||||
int64_t ne3,
|
||||
uint64_t nb0,
|
||||
uint64_t nb1,
|
||||
uint64_t nb2,
|
||||
uint64_t nb3) {
|
||||
static_assert(dim >= 0 && dim <= 3, "dim must be in [0, 3]");
|
||||
|
||||
const int64_t i3 = blockIdx.z;
|
||||
const int64_t i2 = blockIdx.y;
|
||||
const int64_t i1 = blockIdx.x;
|
||||
|
||||
const T * x;
|
||||
|
||||
for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) {
|
||||
if (i0 < ne00 && i1 < ne01 && i2 < ne02 && i3 < ne03) {
|
||||
x = (const T *)(src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
|
||||
} else {
|
||||
if constexpr (dim == 0) {
|
||||
x = (const T *)(src1 + i3*nb13 + i2*nb12 + i1*nb11 + (i0 - ne00)*nb10);
|
||||
} else if constexpr (dim == 1) {
|
||||
x = (const T *)(src1 + i3*nb13 + i2*nb12 + (i1 - ne01)*nb11 + i0*nb10);
|
||||
} else if constexpr (dim == 2) {
|
||||
x = (const T *)(src1 + i3*nb13 + (i2 - ne02)*nb12 + i1*nb11 + i0*nb10);
|
||||
} else if constexpr (dim == 3) {
|
||||
x = (const T *)(src1 + (i3 - ne03)*nb13 + i2*nb12 + i1*nb11 + i0*nb10);
|
||||
// gridDim.y and gridDim.z are capped at 65535, loop over the rest of ne2 and ne3
|
||||
for (int64_t i3 = blockIdx.z; i3 < ne3; i3 += gridDim.z) {
|
||||
for (int64_t i2 = blockIdx.y; i2 < ne2; i2 += gridDim.y) {
|
||||
for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) {
|
||||
if (i0 < ne00 && i1 < ne01 && i2 < ne02 && i3 < ne03) {
|
||||
x = (const T *)(src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00);
|
||||
} else {
|
||||
if constexpr (dim == 0) {
|
||||
x = (const T *)(src1 + i3*nb13 + i2*nb12 + i1*nb11 + (i0 - ne00)*nb10);
|
||||
} else if constexpr (dim == 1) {
|
||||
x = (const T *)(src1 + i3*nb13 + i2*nb12 + (i1 - ne01)*nb11 + i0*nb10);
|
||||
} else if constexpr (dim == 2) {
|
||||
x = (const T *)(src1 + i3*nb13 + (i2 - ne02)*nb12 + i1*nb11 + i0*nb10);
|
||||
} else if constexpr (dim == 3) {
|
||||
x = (const T *)(src1 + (i3 - ne03)*nb13 + i2*nb12 + i1*nb11 + i0*nb10);
|
||||
}
|
||||
}
|
||||
|
||||
T * y = (T *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
|
||||
|
||||
*y = *x;
|
||||
}
|
||||
}
|
||||
|
||||
T * y = (T *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0);
|
||||
|
||||
*y = *x;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,7 +166,7 @@ static void concat_cuda(const ggml_tensor * src0, const ggml_tensor * src1, ggml
|
||||
} else {
|
||||
GGML_ASSERT(!ggml_is_quantized(src0->type));
|
||||
|
||||
dim3 grid_dim(dst->ne[1], dst->ne[2], dst->ne[3]);
|
||||
dim3 grid_dim(dst->ne[1], std::min<int64_t>(dst->ne[2], 65535), std::min<int64_t>(dst->ne[3], 65535));
|
||||
auto launch_kernel = [&](auto dim) {
|
||||
concat_non_cont<T, dim><<<grid_dim, CUDA_CONCAT_BLOCK_SIZE, 0, stream>>>(
|
||||
(const char *) src0->data, (const char *) src1->data, (char *) dst->data,
|
||||
|
||||
@@ -385,7 +385,7 @@ static __global__ void dequantize_block_nvfp4(
|
||||
const void * __restrict__ vx,
|
||||
dst_t * __restrict__ yy,
|
||||
const int64_t ne) {
|
||||
const int64_t i = blockIdx.x;
|
||||
const int64_t i = (int64_t) blockIdx.x*blockDim.y + threadIdx.y;
|
||||
const int tid = threadIdx.x;
|
||||
|
||||
const int64_t base = i * QK_NVFP4;
|
||||
@@ -417,7 +417,7 @@ static void dequantize_row_nvfp4_cuda(
|
||||
cudaStream_t stream) {
|
||||
GGML_ASSERT(k % QK_NVFP4 == 0);
|
||||
const int nb = k / QK_NVFP4;
|
||||
dequantize_block_nvfp4<<<nb, 32, 0, stream>>>(vx, y, k);
|
||||
dequantize_block_nvfp4<<<(nb + 7)/8, dim3(32, 8), 0, stream>>>(vx, y, k);
|
||||
}
|
||||
template <typename src_t, typename dst_t>
|
||||
static __global__ void convert_unary(
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
// Simplified API for asynchronous data loading.
|
||||
|
||||
#include "common.cuh"
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
#include "common.cuh"
|
||||
#include "convert.cuh"
|
||||
#include "cp-async.cuh"
|
||||
#include "mma.cuh"
|
||||
#include "vecdotq.cuh"
|
||||
|
||||
#include <cstdint>
|
||||
@@ -18,16 +20,38 @@
|
||||
// The macro on the following line shifts it by a factor of 2**3=8, as was needed to fix https://github.com/ggml-org/llama.cpp/issues/18606 .
|
||||
#define FATTN_KQ_MAX_OFFSET (3.0f*0.6931f)
|
||||
|
||||
typedef void (* fattn_kernel_t)(
|
||||
const char * __restrict__ Q,
|
||||
const char * __restrict__ K,
|
||||
const char * __restrict__ V,
|
||||
const char * __restrict__ mask,
|
||||
const char * __restrict__ sinks,
|
||||
const int * __restrict__ KV_max,
|
||||
const int * __restrict__ KV_rows,
|
||||
float * __restrict__ dst,
|
||||
float2 * __restrict__ dst_meta,
|
||||
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,
|
||||
const char * __restrict__ V,
|
||||
const half * __restrict__ mask,
|
||||
const float * __restrict__ sinks,
|
||||
const int * __restrict__ KV_max,
|
||||
const int * __restrict__ KV_rows,
|
||||
float * __restrict__ dst,
|
||||
float2 * __restrict__ dst_meta,
|
||||
const float scale,
|
||||
const float max_bias,
|
||||
const float m0,
|
||||
@@ -35,16 +59,22 @@ typedef void (* fattn_kernel_t)(
|
||||
const uint32_t n_head_log2,
|
||||
const float logit_softcap,
|
||||
const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03,
|
||||
const int32_t nb01, const int32_t nb02, const int32_t nb03,
|
||||
const int32_t s01, const int32_t s02, const int32_t s03,
|
||||
const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13,
|
||||
const int32_t nb11, const int32_t nb12, const int64_t nb13,
|
||||
const int32_t nb21, const int32_t nb22, const int64_t nb23,
|
||||
const int32_t s11, const int32_t s12, const int64_t s13,
|
||||
const int32_t s21, const int32_t s22, const int64_t s23,
|
||||
const int32_t ne31, const int32_t ne32, const int32_t ne33,
|
||||
const int32_t nb31, const int64_t nb32, const int64_t nb33);
|
||||
const int32_t s31, const int64_t s32, const int64_t s33,
|
||||
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);
|
||||
|
||||
template <typename T_src, typename T_dst>
|
||||
using fattn_load_tile_t = void (*)(
|
||||
const T_src * __restrict__ KV, T_dst * __restrict__ tile_KV, const int D2, const int stride_KV,
|
||||
const int k_VKQ_0, const int i_sup, const int32_t * __restrict__ indices);
|
||||
|
||||
struct ggml_cuda_flash_attn_ext_f16_extra_data {
|
||||
uintptr_t K;
|
||||
uintptr_t V;
|
||||
@@ -669,6 +699,253 @@ static __device__ __forceinline__ void dequantize_V_q8_0(const void * __restrict
|
||||
}
|
||||
}
|
||||
|
||||
template <int warp_size, int nwarps, int I, int J, int stride_tile,
|
||||
bool use_cp_async, bool oob_check, bool use_sparse, bool KV_indirection, bool use_swizzle,
|
||||
typename T_src, typename T_dst>
|
||||
struct flash_attn_load_tile_impl;
|
||||
|
||||
template <int warp_size, int nwarps, int I, int J, int stride_tile, bool oob_check, bool use_sparse, bool KV_indirection, bool use_swizzle>
|
||||
struct flash_attn_load_tile_impl<warp_size, nwarps, I, J, stride_tile, true, oob_check, use_sparse, KV_indirection, use_swizzle, half2, half2> {
|
||||
static __device__ __forceinline__ void load(
|
||||
const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int D2, const int stride_KV,
|
||||
const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) {
|
||||
constexpr int cpy_nb = 16;
|
||||
constexpr int cpy_ne = cpy_nb / 4;
|
||||
|
||||
static_assert(warp_size == 32, "bad warp_size");
|
||||
static_assert(!oob_check || use_sparse, "OOB check not compatible with cp_async");
|
||||
static_assert(!use_sparse || KV_indirection, "use_sparse requires KV_indirection");
|
||||
static_assert(J % 8 == 0, "bad J");
|
||||
static_assert((J/2) % cpy_ne == 0, "bad J");
|
||||
GGML_UNUSED(indices);
|
||||
|
||||
// K/V data is loaded with decreasing granularity for D for better memory bandwidth.
|
||||
const int chunks_per_row = D2 / cpy_ne;
|
||||
|
||||
auto load_step = [&] __device__ (const int n) {
|
||||
const int stride_k = warp_size >> n;
|
||||
if (stride_k == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const int k0_start = stride_k == warp_size ? 0 : chunks_per_row - chunks_per_row % (2*stride_k);
|
||||
const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k);
|
||||
const int stride_i = warp_size / stride_k;
|
||||
|
||||
if (k0_start == k0_stop) {
|
||||
return;
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) {
|
||||
const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k);
|
||||
|
||||
if (i0 + nwarps*stride_i > I && i >= I) {
|
||||
break;
|
||||
}
|
||||
|
||||
constexpr int preload = 64;
|
||||
const unsigned int tile_KV_32 = ggml_cuda_cvta_generic_to_shared(tile_KV);
|
||||
|
||||
int64_t i_KV;
|
||||
if constexpr (use_sparse) {
|
||||
// padded slots gather row 0, the -inf mask removes their contribution
|
||||
const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : 0;
|
||||
i_KV = index >= 0 ? index : 0;
|
||||
} else if constexpr (KV_indirection) {
|
||||
// K/V rows given per mask column, negative rows are padding
|
||||
i_KV = indices ? max(indices[k_VKQ_0 + i], 0) : k_VKQ_0 + i;
|
||||
} else {
|
||||
i_KV = k_VKQ_0 + i;
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) {
|
||||
const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k);
|
||||
uint32_t offset = i*stride_tile*sizeof(half2) + k*cpy_nb;
|
||||
if constexpr (use_swizzle) {
|
||||
offset = ggml_cuda_mma::swizzle<stride_tile*sizeof(half2), char>(offset, i);
|
||||
}
|
||||
|
||||
cp_async_cg_16<preload>(tile_KV_32 + offset, KV + i_KV*stride_KV + k*cpy_ne);
|
||||
}
|
||||
}
|
||||
};
|
||||
ggml_cuda_unroll<7>{}(load_step);
|
||||
}
|
||||
};
|
||||
|
||||
template <int warp_size, int nwarps, int I, int J, int stride_tile, bool oob_check, bool use_sparse, bool KV_indirection, bool use_swizzle>
|
||||
struct flash_attn_load_tile_impl<warp_size, nwarps, I, J, stride_tile, false, oob_check, use_sparse, KV_indirection, use_swizzle, half2, half2> {
|
||||
static __device__ __forceinline__ void load(
|
||||
const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int D2, const int stride_KV,
|
||||
const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) {
|
||||
constexpr int cpy_nb = 16;
|
||||
constexpr int cpy_ne = cpy_nb / 4;
|
||||
|
||||
static_assert(!use_sparse || KV_indirection, "use_sparse requires KV_indirection");
|
||||
static_assert(J % 8 == 0, "bad J");
|
||||
static_assert((J/2) % cpy_ne == 0, "bad J");
|
||||
GGML_UNUSED(indices);
|
||||
|
||||
// K/V data is loaded with decreasing granularity for D for better memory bandwidth.
|
||||
const int chunks_per_row = D2 / cpy_ne;
|
||||
|
||||
auto load_step = [&] __device__ (const int n) {
|
||||
const int stride_k = warp_size >> n;
|
||||
if (stride_k == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const int k0_start = stride_k == warp_size ? 0 : chunks_per_row - chunks_per_row % (2*stride_k);
|
||||
const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k);
|
||||
const int stride_i = warp_size / stride_k;
|
||||
|
||||
if (k0_start == k0_stop) {
|
||||
return;
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) {
|
||||
const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k);
|
||||
|
||||
if (i0 + nwarps*stride_i > I && i >= I) {
|
||||
break;
|
||||
}
|
||||
|
||||
const __align__(16) half2 zero[cpy_ne] = {{0.0f, 0.0f}};
|
||||
#pragma unroll
|
||||
for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) {
|
||||
const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k);
|
||||
|
||||
const half2 * src;
|
||||
if constexpr (use_sparse) {
|
||||
const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1;
|
||||
src = index >= 0 ? KV + int64_t(index)*stride_KV + k*cpy_ne : zero;
|
||||
} else if (!oob_check || i < i_sup) {
|
||||
if constexpr (KV_indirection) {
|
||||
const int64_t i_KV = indices ? max(indices[k_VKQ_0 + i], 0) : k_VKQ_0 + i;
|
||||
src = KV + i_KV*stride_KV + k*cpy_ne;
|
||||
} else {
|
||||
src = KV + int64_t(k_VKQ_0 + i)*stride_KV + k*cpy_ne;
|
||||
}
|
||||
} else {
|
||||
src = zero;
|
||||
}
|
||||
|
||||
half2 * dst;
|
||||
if constexpr (use_swizzle) {
|
||||
dst = ggml_cuda_mma::swizzle<stride_tile>(tile_KV, i*stride_tile + k*cpy_ne, i);
|
||||
} else {
|
||||
dst = tile_KV + i*stride_tile + k*cpy_ne;
|
||||
}
|
||||
|
||||
ggml_cuda_memcpy_1<cpy_nb>(dst, src);
|
||||
}
|
||||
}
|
||||
};
|
||||
ggml_cuda_unroll<7>{}(load_step);
|
||||
}
|
||||
};
|
||||
|
||||
template <int warp_size, int nwarps, int I, int J, int stride_tile, bool oob_check, bool use_sparse, bool KV_indirection>
|
||||
struct flash_attn_load_tile_impl<warp_size, nwarps, I, J, stride_tile, false, oob_check, use_sparse, KV_indirection, false, half2, float> {
|
||||
static __device__ __forceinline__ void load(
|
||||
const half2 * const __restrict__ KV, float * const __restrict__ tile_KV, const int D2, const int stride_KV,
|
||||
const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) {
|
||||
constexpr int cpy_nb = 16;
|
||||
constexpr int cpy_ne = cpy_nb / 4;
|
||||
constexpr int h2_per_chunk = cpy_ne / 2;
|
||||
|
||||
static_assert(!use_sparse || KV_indirection, "use_sparse requires KV_indirection");
|
||||
static_assert(J % 8 == 0, "bad J");
|
||||
static_assert(J % cpy_ne == 0, "bad J");
|
||||
GGML_UNUSED(indices);
|
||||
|
||||
// K/V data is loaded with decreasing granularity for D for better memory bandwidth.
|
||||
const int chunks_per_row = D2 / h2_per_chunk;
|
||||
const half2 * const __restrict__ KV_0 = use_sparse || (KV_indirection && indices) ? KV : KV + int64_t(k_VKQ_0)*stride_KV;
|
||||
|
||||
auto load_step = [&] __device__ (const int n) {
|
||||
const int stride_k = warp_size >> n;
|
||||
if (stride_k == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const int k0_start = stride_k == warp_size ? 0 : chunks_per_row - chunks_per_row % (2*stride_k);
|
||||
const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k);
|
||||
const int stride_i = warp_size / stride_k;
|
||||
|
||||
if (k0_start == k0_stop) {
|
||||
return;
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) {
|
||||
const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k);
|
||||
|
||||
if (i0 + nwarps*stride_i > I && i >= I) {
|
||||
break;
|
||||
}
|
||||
|
||||
const __align__(16) half2 zero[h2_per_chunk] = {{0.0f, 0.0f}};
|
||||
#pragma unroll
|
||||
for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) {
|
||||
const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k);
|
||||
|
||||
const half2 * src;
|
||||
if constexpr (use_sparse) {
|
||||
const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1;
|
||||
src = index >= 0 ? KV + int64_t(index)*stride_KV + k*h2_per_chunk : zero;
|
||||
} else if (!oob_check || i < i_sup) {
|
||||
if constexpr (KV_indirection) {
|
||||
if (indices) {
|
||||
const int64_t i_KV = max(indices[k_VKQ_0 + i], 0);
|
||||
src = KV_0 + i_KV*stride_KV + k*h2_per_chunk;
|
||||
} else {
|
||||
src = KV_0 + i*stride_KV + k*h2_per_chunk;
|
||||
}
|
||||
} else {
|
||||
src = KV_0 + i*stride_KV + k*h2_per_chunk;
|
||||
}
|
||||
} else {
|
||||
src = zero;
|
||||
}
|
||||
|
||||
__align__(16) half2 tmp_h2[h2_per_chunk];
|
||||
ggml_cuda_memcpy_1<sizeof(tmp_h2)>(tmp_h2, src);
|
||||
|
||||
__align__(16) float2 tmp_f2[h2_per_chunk];
|
||||
#pragma unroll
|
||||
for (int l = 0; l < h2_per_chunk; ++l) {
|
||||
tmp_f2[l] = __half22float2(tmp_h2[l]);
|
||||
}
|
||||
ggml_cuda_memcpy_1<sizeof(tmp_f2)>(tile_KV + i*stride_tile + k*cpy_ne, tmp_f2);
|
||||
}
|
||||
}
|
||||
};
|
||||
ggml_cuda_unroll<7>{}(load_step);
|
||||
}
|
||||
};
|
||||
|
||||
template <int warp_size, int nwarps, int I, int J, int stride_tile, bool use_cp_async, bool oob_check, bool use_sparse, bool KV_indirection, bool use_swizzle, typename T_src, typename T_dst>
|
||||
static __device__ __forceinline__ void flash_attn_load_tile(
|
||||
const T_src * const __restrict__ KV, T_dst * const __restrict__ tile_KV, const int D2, const int stride_KV,
|
||||
const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) {
|
||||
flash_attn_load_tile_impl<warp_size, nwarps, I, J, stride_tile, use_cp_async, oob_check, use_sparse, KV_indirection, use_swizzle, T_src, T_dst>::load(
|
||||
KV, tile_KV, D2, stride_KV, k_VKQ_0, i_sup, indices);
|
||||
}
|
||||
|
||||
// Helper function to get a C++ type for calculating pointer offsets from a ggml type:
|
||||
template <ggml_type type>
|
||||
static __host__ __device__ auto ggml_cuda_fattn_kv_dtype() {
|
||||
if constexpr (type == GGML_TYPE_F16) {
|
||||
return half2{};
|
||||
} else {
|
||||
static_assert(type == -1, "bad type");
|
||||
}
|
||||
}
|
||||
|
||||
template <ggml_type type_K, int D, int nthreads>
|
||||
constexpr __device__ vec_dot_KQ_t get_vec_dot_KQ() {
|
||||
if constexpr (type_K == GGML_TYPE_F16) {
|
||||
@@ -856,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
|
||||
@@ -967,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
|
||||
@@ -1025,12 +1302,13 @@ 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>
|
||||
template <int DV, int ncols1, int ncols2, typename T_K_stride, typename T_V_stride>
|
||||
void launch_fattn(
|
||||
ggml_backend_cuda_context & ctx, ggml_tensor * dst, fattn_kernel_t fattn_kernel, const int nwarps, const size_t nbytes_shared,
|
||||
ggml_backend_cuda_context & ctx, ggml_tensor * dst, fattn_kernel_t fattn_kernel,
|
||||
const int nwarps, const size_t nbytes_shared,
|
||||
const int nbatch_fa, const bool need_f16_K, const bool need_f16_V, const bool stream_k, const bool use_sparse,
|
||||
const int warp_size = WARP_SIZE, const bool async_kv_preload = false
|
||||
) {
|
||||
@@ -1046,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);
|
||||
@@ -1148,6 +1430,14 @@ void launch_fattn(
|
||||
}
|
||||
}
|
||||
|
||||
GGML_ASSERT(nb11 % sizeof(T_K_stride) == 0);
|
||||
GGML_ASSERT(nb12 % sizeof(T_K_stride) == 0);
|
||||
GGML_ASSERT(nb13 % sizeof(T_K_stride) == 0);
|
||||
|
||||
GGML_ASSERT(nb21 % sizeof(T_V_stride) == 0);
|
||||
GGML_ASSERT(nb22 % sizeof(T_V_stride) == 0);
|
||||
GGML_ASSERT(nb23 % sizeof(T_V_stride) == 0);
|
||||
|
||||
const int ntiles_x = ((Q->ne[1] + ncols1 - 1) / ncols1);
|
||||
const int gqa_ratio = Q->ne[2] / K->ne[2];
|
||||
const int ntiles_z_gqa = ((gqa_ratio + ncols2 - 1) / ncols2);
|
||||
@@ -1170,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);
|
||||
@@ -1311,20 +1603,29 @@ void launch_fattn(
|
||||
|
||||
ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(blocks_num, block_dim, nbytes_shared, main_stream);
|
||||
ggml_cuda_kernel_launch(fattn_kernel, launch_params,
|
||||
(const char *) Q->data,
|
||||
K_data,
|
||||
V_data,
|
||||
mask ? ((const char *) mask->data) : nullptr,
|
||||
sinks ? ((const char *) sinks->data) : nullptr,
|
||||
(const float2 *) Q->data,
|
||||
(const char *) K_data,
|
||||
(const char *) V_data,
|
||||
mask ? ((const half *) mask->data) : nullptr,
|
||||
sinks ? ((const float *) sinks->data) : nullptr,
|
||||
KV_max.ptr,
|
||||
kv_rows ? (const int *) kv_rows->data : nullptr,
|
||||
!stream_k && parallel_blocks > 1 ? dst_tmp.ptr : (float *) KQV->data, dst_tmp_meta.ptr,
|
||||
scale, max_bias, m0, m1, n_head_log2, logit_softcap,
|
||||
Q->ne[0], ne01, Q->ne[2], Q->ne[3], Q->nb[1], Q->nb[2], Q->nb[3],
|
||||
K->ne[0], n_kv, K->ne[2], K->ne[3], nb11, nb12, nb13,
|
||||
nb21, nb22, nb23,
|
||||
Q->ne[0], ne01, Q->ne[2], Q->ne[3],
|
||||
int32_t(Q->nb[1] / sizeof(float2)), int32_t(Q->nb[2] / sizeof(float2)), int32_t(Q->nb[3] / sizeof(float2)),
|
||||
K->ne[0], n_kv, K->ne[2], K->ne[3],
|
||||
int32_t(nb11 / sizeof(T_K_stride)), int32_t(nb12 / sizeof(T_K_stride)), int64_t(nb13 / sizeof(T_K_stride)),
|
||||
int32_t(nb21 / sizeof(T_V_stride)), int32_t(nb22 / sizeof(T_V_stride)), int64_t(nb23 / sizeof(T_V_stride)),
|
||||
mask ? mask->ne[1] : 0, mask ? mask->ne[2] : 0, mask ? mask->ne[3] : 0,
|
||||
mask ? mask->nb[1] : 0, mask ? mask->nb[2] : 0, mask ? mask->nb[3] : 0
|
||||
mask ? int32_t(mask->nb[1] / sizeof(half)) : 0,
|
||||
mask ? int64_t(mask->nb[2] / sizeof(half)) : 0,
|
||||
mask ? int64_t(mask->nb[3] / sizeof(half)) : 0,
|
||||
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());
|
||||
|
||||
|
||||
@@ -413,116 +413,6 @@ static constexpr __device__ int ggml_cuda_fattn_mma_get_nstages(
|
||||
|
||||
// ------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
template<int stride_tile, int nwarps, int nbatch_fa, bool use_cp_async, bool oob_check, bool use_sparse>
|
||||
static __device__ __forceinline__ void flash_attn_ext_f16_load_tile(
|
||||
const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int D2, const int stride_KV,
|
||||
const int k_VKQ_0, const int i_sup, const int32_t * const __restrict__ indices) {
|
||||
constexpr int warp_size = ggml_cuda_get_physical_warp_size();
|
||||
// K/V data is loaded with decreasing granularity for D for better memory bandwidth.
|
||||
// The minimum granularity is 16 bytes.
|
||||
constexpr int chunk_size = 16;
|
||||
constexpr int h2_per_chunk = chunk_size / sizeof(half2);
|
||||
const int chunks_per_row = D2 / h2_per_chunk;
|
||||
if constexpr (use_cp_async) {
|
||||
static_assert(warp_size == 32, "bad warp_size");
|
||||
static_assert(!oob_check || use_sparse, "OOB check not compatible with cp_async");
|
||||
constexpr int preload = 64;
|
||||
|
||||
const unsigned int tile_KV_32 = ggml_cuda_cvta_generic_to_shared(tile_KV);
|
||||
|
||||
auto load = [&] __device__ (auto n) {
|
||||
const int stride_k = warp_size >> n;
|
||||
const int k0_start = stride_k == warp_size ? 0 : chunks_per_row - chunks_per_row % (2*stride_k);
|
||||
const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k);
|
||||
const int stride_i = warp_size / stride_k;
|
||||
|
||||
if (k0_start == k0_stop) {
|
||||
return;
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int i0 = 0; i0 < nbatch_fa; i0 += nwarps*stride_i) {
|
||||
const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k);
|
||||
|
||||
if (i0 + nwarps*stride_i > nbatch_fa && i >= nbatch_fa) {
|
||||
break;
|
||||
}
|
||||
|
||||
int64_t i_KV;
|
||||
if constexpr (use_sparse) {
|
||||
// padded slots gather row 0, the -inf mask removes their contribution
|
||||
const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : 0;
|
||||
i_KV = index >= 0 ? index : 0;
|
||||
} else if (indices) {
|
||||
// K/V rows given per mask column, negative rows are padding
|
||||
i_KV = max(indices[k_VKQ_0 + i], 0);
|
||||
} else {
|
||||
i_KV = k_VKQ_0 + i;
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) {
|
||||
const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k);
|
||||
|
||||
cp_async_cg_16<preload>(tile_KV_32 + swizzle<stride_tile*sizeof(half2), char>(i*stride_tile*sizeof(half2) + k*chunk_size, i), KV + i_KV*stride_KV + k*h2_per_chunk);
|
||||
}
|
||||
}
|
||||
};
|
||||
// 1: max 32*16=512 bytes, 256 half
|
||||
// 2: max 16*16=256 bytes, 128 half
|
||||
// 3: max 8*16=128 bytes, 64 half
|
||||
// 4: max 4*16= 64 bytes, 32 half
|
||||
// 5: max 2*16= 32 bytes, 16 half
|
||||
// 6: max 1*16= 16 bytes, 8 half
|
||||
ggml_cuda_unroll<6>{}(load);
|
||||
} else {
|
||||
const half2 zero[4] = {{0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}};
|
||||
auto load = [&] __device__ (const int n) {
|
||||
const int stride_k = 32 >> n;
|
||||
const int k0_start = stride_k == 32 ? 0 : chunks_per_row - chunks_per_row % (2*stride_k);
|
||||
const int k0_stop = chunks_per_row - chunks_per_row % (1*stride_k);
|
||||
const int stride_i = warp_size / stride_k;
|
||||
|
||||
if (k0_start == k0_stop) {
|
||||
return;
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int i0 = 0; i0 < nbatch_fa; i0 += nwarps*stride_i) {
|
||||
const int i = i0 + threadIdx.y*stride_i + (stride_k == warp_size ? 0 : threadIdx.x / stride_k);
|
||||
|
||||
if (i0 + nwarps*stride_i > nbatch_fa && i >= nbatch_fa) {
|
||||
break;
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int k0 = k0_start; k0 < k0_stop; k0 += stride_k) {
|
||||
const int k = k0 + (stride_k == warp_size ? threadIdx.x : threadIdx.x % stride_k);
|
||||
|
||||
const half2 * src;
|
||||
if constexpr (use_sparse) {
|
||||
const int32_t index = i < i_sup ? indices[k_VKQ_0 + i] : -1;
|
||||
src = index >= 0 ? KV + int64_t(index)*stride_KV + k*h2_per_chunk : zero;
|
||||
} else if (!oob_check || i < i_sup) {
|
||||
const int64_t i_KV = indices ? max(indices[k_VKQ_0 + i], 0) : k_VKQ_0 + i;
|
||||
src = KV + i_KV*stride_KV + k*h2_per_chunk;
|
||||
} else {
|
||||
src = zero;
|
||||
}
|
||||
ggml_cuda_memcpy_1<16>(swizzle<stride_tile>(tile_KV, i*stride_tile + k*h2_per_chunk, i), src);
|
||||
}
|
||||
}
|
||||
};
|
||||
// 1: max 32*16=512 bytes, 256 half
|
||||
// 2: max 16*16=256 bytes, 128 half
|
||||
// 3: max 8*16=128 bytes, 64 half
|
||||
// 4: max 4*16= 64 bytes, 32 half
|
||||
// 5: max 2*16= 32 bytes, 16 half
|
||||
// 6: max 1*16= 16 bytes, 8 half
|
||||
ggml_cuda_unroll<6>{}(load);
|
||||
}
|
||||
}
|
||||
|
||||
template<int ncols1, int nwarps, int nbatch_fa, bool use_cp_async, bool oob_check, bool use_sparse>
|
||||
static __device__ __forceinline__ void flash_attn_ext_f16_load_mask(
|
||||
const half * const __restrict__ mask_h, half * const __restrict__ tile_mask,
|
||||
@@ -612,11 +502,12 @@ static __device__ __forceinline__ void flash_attn_ext_f16_load_mask(
|
||||
|
||||
template<int DKQ, int DV, int ncols1, int ncols2, int nwarps,
|
||||
bool use_logit_softcap, bool V_is_K_view, bool use_sparse, bool needs_fixup, bool is_fixup, bool last_iter, bool oob_check,
|
||||
typename T_A_KQ, typename T_B_KQ, typename T_C_KQ, typename T_A_VKQ, typename T_B_VKQ, typename T_C_VKQ>
|
||||
typename T_A_KQ, typename T_B_KQ, typename T_C_KQ, typename T_A_VKQ, typename T_B_VKQ, typename T_C_VKQ,
|
||||
typename T_K, typename T_V>
|
||||
static __device__ __forceinline__ void flash_attn_ext_f16_iter(
|
||||
const float2 * const __restrict__ Q_f2,
|
||||
const half2 * const __restrict__ K_h2,
|
||||
const half2 * const __restrict__ V_h2,
|
||||
const T_K * const __restrict__ K_h2,
|
||||
const T_V * const __restrict__ V_h2,
|
||||
const half * const __restrict__ mask_h,
|
||||
const int32_t * const __restrict__ indices,
|
||||
float2 * const __restrict__ dstk,
|
||||
@@ -653,6 +544,13 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
|
||||
constexpr bool Q_in_reg = ggml_cuda_fattn_mma_get_Q_in_reg (DKQ, DV, ncols);
|
||||
constexpr int nstages = ggml_cuda_fattn_mma_get_nstages (DKQ, DV, ncols1, ncols2, use_sparse);
|
||||
|
||||
// FIXME this is causing performance regressions on AMD/V100.
|
||||
#ifdef TURING_MMA_AVAILABLE
|
||||
constexpr bool KV_indirection = true;
|
||||
#else
|
||||
constexpr bool KV_indirection = use_sparse;
|
||||
#endif // TURING_MMA_AVAILABLE
|
||||
|
||||
constexpr int DKQp = GGML_PAD(DKQ, 16);
|
||||
constexpr int DVp = GGML_PAD(DV, 16);
|
||||
|
||||
@@ -676,7 +574,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
|
||||
constexpr bool use_cp_async = true;
|
||||
cp_async_wait_all();
|
||||
__syncthreads();
|
||||
flash_attn_ext_f16_load_tile<stride_tile_V, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
|
||||
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, 2*nbatch_V2, stride_tile_V, use_cp_async, oob_check, use_sparse, KV_indirection, swz, T_V, half2>
|
||||
(V_h2, tile_V, min(nbatch_V2, DV/2), stride_V, k_VKQ_0, k_VKQ_sup, indices);
|
||||
} else {
|
||||
// the sparse mask values are gathered per element, always load them synchronously
|
||||
@@ -696,7 +594,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
|
||||
if constexpr (nstages <= 1) {
|
||||
const int k0_diff = min(k0_stop, DKQ/2) - k0_start; // Only load the real head size from global memory.
|
||||
constexpr bool use_cp_async = nstages == 1;
|
||||
flash_attn_ext_f16_load_tile<stride_tile_K, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
|
||||
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, 2*nbatch_K2, stride_tile_K, use_cp_async, oob_check, use_sparse, KV_indirection, swz, T_K, half2>
|
||||
(K_h2 + k0_start, tile_K, k0_diff, stride_K, k_VKQ_0, k_VKQ_sup, indices);
|
||||
if (use_cp_async) {
|
||||
cp_async_wait_all();
|
||||
@@ -1033,7 +931,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
|
||||
flash_attn_ext_f16_load_mask<ncols1, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
|
||||
(mask_h, tile_mask, stride_mask, kb0_next*nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr);
|
||||
}
|
||||
flash_attn_ext_f16_load_tile<stride_tile_K, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
|
||||
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, 2*nbatch_K2, stride_tile_K, use_cp_async, oob_check, use_sparse, KV_indirection, swz, T_K, half2>
|
||||
(K_h2, tile_K, min(nbatch_K2, DKQ/2), stride_K, kb0_next*nbatch_fa, k_VKQ_sup, indices);
|
||||
}
|
||||
}
|
||||
@@ -1049,7 +947,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter(
|
||||
const int i0_diff = min(i0_stop, DV) - i0_start; // Only load the real head size from global memory.
|
||||
if (!V_is_K_view || i0_stop > 2*nbatch_K2) {
|
||||
constexpr bool use_cp_async = nstages == 1;
|
||||
flash_attn_ext_f16_load_tile<stride_tile_V, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
|
||||
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, 2*nbatch_V2, stride_tile_V, use_cp_async, oob_check, use_sparse, KV_indirection, swz, T_V, half2>
|
||||
(V_h2 + i0_start/2, tile_V, i0_diff/2, stride_V, k_VKQ_0, k_VKQ_sup, indices);
|
||||
if (use_cp_async) {
|
||||
cp_async_wait_all();
|
||||
@@ -1261,11 +1159,11 @@ template<int DKQ, int ncols> struct mma_tile_sizes {
|
||||
};
|
||||
#endif // defined(TURING_MMA_AVAILABLE)
|
||||
|
||||
template<int DKQ, int DV, int ncols1, int ncols2, int nwarps, bool use_logit_softcap, bool V_is_K_view, bool use_sparse, bool needs_fixup, bool is_fixup>
|
||||
template<int DKQ, int DV, int ncols1, int ncols2, int nwarps, bool use_logit_softcap, bool V_is_K_view, bool use_sparse, bool needs_fixup, bool is_fixup, typename T_K, typename T_V>
|
||||
static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
|
||||
const float2 * const __restrict__ Q_f2,
|
||||
const half2 * const __restrict__ K_h2,
|
||||
const half2 * const __restrict__ V_h2,
|
||||
const T_K * const __restrict__ K_h2,
|
||||
const T_V * const __restrict__ V_h2,
|
||||
const half * const __restrict__ mask_h,
|
||||
const int32_t * const __restrict__ indices,
|
||||
const float * const __restrict__ sinks_f,
|
||||
@@ -1310,6 +1208,13 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
|
||||
constexpr bool Q_in_reg = ggml_cuda_fattn_mma_get_Q_in_reg (DKQ, DV, ncols);
|
||||
constexpr int nstages = ggml_cuda_fattn_mma_get_nstages (DKQ, DV, ncols1, ncols2, use_sparse);
|
||||
|
||||
// FIXME this is causing performance regressions on AMD/V100.
|
||||
#ifdef TURING_MMA_AVAILABLE
|
||||
constexpr bool KV_indirection = true;
|
||||
#else
|
||||
constexpr bool KV_indirection = use_sparse;
|
||||
#endif // TURING_MMA_AVAILABLE
|
||||
|
||||
constexpr int DKQp = GGML_PAD(DKQ, 16);
|
||||
constexpr int DVp = GGML_PAD(DV, 16);
|
||||
|
||||
@@ -1459,7 +1364,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
|
||||
flash_attn_ext_f16_load_mask<ncols1, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
|
||||
(mask_h, tile_mask, stride_mask, kb0*nbatch_fa, k_VKQ_sup, jt*ncols1, ne01, nullptr);
|
||||
}
|
||||
flash_attn_ext_f16_load_tile<stride_tile_K, nwarps, nbatch_fa, use_cp_async, oob_check, use_sparse>
|
||||
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, 2*nbatch_K2, stride_tile_K, use_cp_async, oob_check, use_sparse, KV_indirection, swz, T_K, half2>
|
||||
(K_h2, tile_K, min(nbatch_K2, DKQ/2), stride_K, kb0*nbatch_fa, k_VKQ_sup, indices);
|
||||
}
|
||||
|
||||
@@ -1472,7 +1377,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
|
||||
constexpr int k_VKQ_sup = nbatch_fa;
|
||||
flash_attn_ext_f16_iter
|
||||
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
|
||||
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
|
||||
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
|
||||
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
|
||||
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
|
||||
KQ_max, KQ_rowsum, jt, kb0, kb0_next, k_VKQ_sup);
|
||||
@@ -1482,7 +1387,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
|
||||
constexpr int k_VKQ_sup = nbatch_fa;
|
||||
flash_attn_ext_f16_iter
|
||||
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
|
||||
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
|
||||
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
|
||||
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
|
||||
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
|
||||
KQ_max, KQ_rowsum, jt, kb0, kb0, k_VKQ_sup);
|
||||
@@ -1493,7 +1398,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
|
||||
constexpr int k_VKQ_sup = nbatch_fa;
|
||||
flash_attn_ext_f16_iter
|
||||
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
|
||||
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
|
||||
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
|
||||
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
|
||||
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
|
||||
KQ_max, KQ_rowsum, jt, kb0, kb0 + 1, k_VKQ_sup);
|
||||
@@ -1502,7 +1407,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
|
||||
const int k_VKQ_sup = ne11 - kb0*nbatch_fa;
|
||||
flash_attn_ext_f16_iter
|
||||
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
|
||||
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
|
||||
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
|
||||
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
|
||||
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
|
||||
KQ_max, KQ_rowsum, jt, kb0, kb0, k_VKQ_sup);
|
||||
@@ -1513,7 +1418,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
|
||||
constexpr int k_VKQ_sup = nbatch_fa;
|
||||
flash_attn_ext_f16_iter
|
||||
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
|
||||
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
|
||||
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
|
||||
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
|
||||
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
|
||||
KQ_max, KQ_rowsum, jt, kb0, kb0 + 1, k_VKQ_sup);
|
||||
@@ -1522,7 +1427,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
|
||||
constexpr int k_VKQ_sup = nbatch_fa;
|
||||
flash_attn_ext_f16_iter
|
||||
<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, last_iter, oob_check,
|
||||
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ>
|
||||
T_A_KQ, T_B_KQ, T_C_KQ, T_A_VKQ, T_B_VKQ, T_C_VKQ, T_K, T_V>
|
||||
(Q_f2, K_h2, V_h2, mask_h, indices, dstk, dstk_fixup, scale, slope, logit_softcap,
|
||||
ne01, ne02, stride_K, stride_V, stride_mask, tile_Q, tile_K, tile_V, tile_mask, Q_B, VKQ_C,
|
||||
KQ_max, KQ_rowsum, jt, kb0, kb0, k_VKQ_sup);
|
||||
@@ -1902,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) {
|
||||
@@ -1936,18 +1841,18 @@ static constexpr __host__ __device__ bool ggml_cuda_flash_attn_ext_mma_f16_may_u
|
||||
(DKQ == 256 && DV == 256 && ncols1 == 8 && ncols2 == 8);
|
||||
}
|
||||
|
||||
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap, bool V_is_K_view, bool use_sparse>
|
||||
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap, bool V_is_K_view, bool use_sparse, ggml_type type_K, ggml_type type_V>
|
||||
__launch_bounds__(ggml_cuda_fattn_mma_get_nthreads(DKQ, DV, ncols1*ncols2), ggml_cuda_fattn_mma_get_occupancy(DKQ, DV, ncols1*ncols2))
|
||||
static __global__ void flash_attn_ext_f16(
|
||||
const char * Q_ptr,
|
||||
const char * K_ptr,
|
||||
const char * V_ptr,
|
||||
const char * mask_ptr,
|
||||
const char * sinks_ptr,
|
||||
const int * KV_max_ptr,
|
||||
const int * KV_rows_ptr,
|
||||
float * dst_ptr,
|
||||
float2 * dst_meta_ptr,
|
||||
const float2 * Q_ptr,
|
||||
const char * K_ptr,
|
||||
const char * V_ptr,
|
||||
const half * mask_ptr,
|
||||
const float * sinks_ptr,
|
||||
const int * KV_max_ptr,
|
||||
const int * KV_rows_ptr,
|
||||
float * dst_ptr,
|
||||
float2 * dst_meta_ptr,
|
||||
const float scale,
|
||||
const float max_bias,
|
||||
const float m0,
|
||||
@@ -1955,19 +1860,24 @@ static __global__ void flash_attn_ext_f16(
|
||||
const uint32_t n_head_log2,
|
||||
const float logit_softcap,
|
||||
const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03,
|
||||
const int32_t nb01, const int32_t nb02, const int32_t nb03,
|
||||
const int32_t s01, const int32_t s02, const int32_t s03,
|
||||
const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13,
|
||||
const int32_t nb11, const int32_t nb12, const int64_t nb13,
|
||||
const int32_t nb21, const int32_t nb22, const int64_t nb23,
|
||||
const int32_t s11, const int32_t s12, const int64_t s13,
|
||||
const int32_t s21, const int32_t s22, const int64_t s23,
|
||||
const int32_t ne31, const int32_t ne32, const int32_t ne33,
|
||||
const int32_t nb31, const int64_t nb32, const int64_t nb33) {
|
||||
const int32_t s31, const int64_t s32, const int64_t s33,
|
||||
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))
|
||||
const char * GGML_CUDA_RESTRICT Q = Q_ptr;
|
||||
const char * GGML_CUDA_RESTRICT K = K_ptr;
|
||||
const char * GGML_CUDA_RESTRICT V = V_ptr;
|
||||
const char * GGML_CUDA_RESTRICT mask = mask_ptr;
|
||||
const char * GGML_CUDA_RESTRICT sinks = sinks_ptr;
|
||||
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
|
||||
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
|
||||
|
||||
const float2 * GGML_CUDA_RESTRICT Q = Q_ptr;
|
||||
const T_K * GGML_CUDA_RESTRICT K = (const T_K *) K_ptr;
|
||||
const T_V * GGML_CUDA_RESTRICT V = (const T_V *) V_ptr;
|
||||
const half * GGML_CUDA_RESTRICT mask = mask_ptr;
|
||||
const float * GGML_CUDA_RESTRICT sinks = sinks_ptr;
|
||||
// sparse: one index list per (sequence, query tile), the live count of each list follows the lists
|
||||
const int * GGML_CUDA_RESTRICT sparse_indices = use_sparse ? KV_max_ptr : nullptr;
|
||||
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
|
||||
@@ -2024,12 +1934,7 @@ static __global__ void flash_attn_ext_f16(
|
||||
|
||||
const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix.
|
||||
|
||||
const int stride_Q1 = nb01 / sizeof(float2);
|
||||
const int stride_Q2 = nb02 / sizeof(float2);
|
||||
const int stride_K = nb11 / sizeof(half2);
|
||||
const int stride_mask = nb31 / sizeof(half);
|
||||
|
||||
const int stride_V = V_is_K_view ? stride_K : nb21 / sizeof(half2);
|
||||
const int stride_V = V_is_K_view ? s11 : s21;
|
||||
|
||||
const int iter_k = (ne11 + (nbatch_fa - 1)) / nbatch_fa;
|
||||
const int iter_j = (ne01.z + (ncols1 - 1)) / ncols1;
|
||||
@@ -2072,14 +1977,14 @@ static __global__ void flash_attn_ext_f16(
|
||||
|
||||
const int zt_Q = z_KV*gqa_ratio + zt_gqa*ncols2; // Global Q head start index.
|
||||
|
||||
const float2 * Q_f2 = (const float2 *) (Q + nb03*sequence + nb02*zt_Q);
|
||||
const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*z_KV);
|
||||
const float2 * Q_f2 = Q + s03*sequence + s02*zt_Q;
|
||||
const T_K * K_h2 = K + s13*sequence + s12*z_KV;
|
||||
const half * mask_h = ncols2 == 1 && !mask ? nullptr :
|
||||
(const half *) (mask + nb33*(sequence % ne33) + nb32*(zt_Q % ne32));
|
||||
mask + s33*(sequence % ne33) + s32*(zt_Q % ne32);
|
||||
float2 * dstk = ((float2 *) dst) + (sequence*ne01.z*ne02 + zt_Q) * (DV/2);
|
||||
|
||||
const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*sequence + nb22*z_KV);
|
||||
const float * sinks_f = sinks ? (const float *) sinks + zt_Q : nullptr;
|
||||
const T_V * V_h2 = V_is_K_view ? (const T_V *) K_h2 : V + s23*sequence + s22*z_KV;
|
||||
const float * sinks_f = sinks ? sinks + zt_Q : nullptr;
|
||||
const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 :
|
||||
KV_rows_ptr ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr;
|
||||
|
||||
@@ -2096,14 +2001,14 @@ static __global__ void flash_attn_ext_f16(
|
||||
constexpr bool is_fixup = false; // All but (potentially) the last iterations write their data to dst rather than the fixup buffer.
|
||||
if (kb0_start == 0) {
|
||||
constexpr bool needs_fixup = false; // CUDA block is working on an entire tile.
|
||||
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup>
|
||||
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, T_K, T_V>
|
||||
(Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap,
|
||||
ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
|
||||
ne01, ne02, gqa_ratio, ne11, s01, s02, s11, stride_V, s31, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
|
||||
} else {
|
||||
constexpr bool needs_fixup = true; // CUDA block is missing the beginning of a tile.
|
||||
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup>
|
||||
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, T_K, T_V>
|
||||
(Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap,
|
||||
ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
|
||||
ne01, ne02, gqa_ratio, ne11, s01, s02, s11, stride_V, s31, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
|
||||
}
|
||||
|
||||
kbc += iter_k;
|
||||
@@ -2126,14 +2031,14 @@ static __global__ void flash_attn_ext_f16(
|
||||
|
||||
const int zt_Q = z_KV*gqa_ratio + zt_gqa*ncols2; // Global Q head start index.
|
||||
|
||||
const float2 * Q_f2 = (const float2 *) (Q + nb03*sequence + nb02*zt_Q);
|
||||
const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*z_KV);
|
||||
const float2 * Q_f2 = Q + s03*sequence + s02*zt_Q;
|
||||
const T_K * K_h2 = K + s13*sequence + s12*z_KV;
|
||||
const half * mask_h = ncols2 == 1 && !mask ? nullptr :
|
||||
(const half *) (mask + nb33*(sequence % ne33) + nb32*(zt_Q % ne32));
|
||||
mask + s33*(sequence % ne33) + s32*(zt_Q % ne32);
|
||||
float2 * dstk = ((float2 *) dst) + (sequence*ne01.z*ne02 + zt_Q) * (DV/2);
|
||||
|
||||
const half2 * V_h2 = V_is_K_view ? K_h2 : (const half2 *) (V + nb23*sequence + nb22*z_KV);
|
||||
const float * sinks_f = sinks ? (const float *) sinks + zt_Q : nullptr;
|
||||
const T_V * V_h2 = V_is_K_view ? (const T_V *) K_h2 : V + s23*sequence + s22*z_KV;
|
||||
const float * sinks_f = sinks ? sinks + zt_Q : nullptr;
|
||||
const int32_t * indices = use_sparse ? sparse_indices + (int64_t(sequence % ne33)*iter_j + jt)*ne11 :
|
||||
KV_rows_ptr ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr;
|
||||
|
||||
@@ -2149,27 +2054,30 @@ static __global__ void flash_attn_ext_f16(
|
||||
|
||||
constexpr bool is_fixup = true; // Last index writes its data to fixup buffer to avoid data races with other blocks.
|
||||
constexpr bool needs_fixup = false;
|
||||
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup>
|
||||
flash_attn_ext_f16_process_tile<DKQ, DV, ncols1, ncols2, nwarps, use_logit_softcap, V_is_K_view, use_sparse, needs_fixup, is_fixup, T_K, T_V>
|
||||
(Q_f2, K_h2, V_h2, mask_h, indices, sinks_f, dstk, dst_meta, scale, slope, logit_softcap,
|
||||
ne01, ne02, gqa_ratio, ne11, stride_Q1, stride_Q2, stride_K, stride_V, stride_mask, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
|
||||
ne01, ne02, gqa_ratio, ne11, s01, s02, s11, stride_V, s31, jt, zt_gqa, kb0_rot, kb0_rot + kb0_stop - kb0_start, kb0_max);
|
||||
#else
|
||||
GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale,
|
||||
max_bias, m0, m1, n_head_log2, logit_softcap,
|
||||
ne00, ne01, ne02, ne03,
|
||||
nb01, nb02, nb03,
|
||||
s01, s02, s03,
|
||||
ne10, ne11, ne12, ne13,
|
||||
nb11, nb12, nb13,
|
||||
nb21, nb22, nb23,
|
||||
s11, s12, s13,
|
||||
s21, s22, s23,
|
||||
ne31, ne32, ne33,
|
||||
nb31, nb32, nb33);
|
||||
s31, s32, s33);
|
||||
NO_DEVICE_CODE;
|
||||
#endif // defined(FLASH_ATTN_AVAILABLE) && (defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE))
|
||||
}
|
||||
|
||||
bool ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(const int cc, const ggml_tensor * dst, const int ncols1, const int ncols2);
|
||||
|
||||
template <int DKQ, int DV, int ncols1, int ncols2>
|
||||
template <int DKQ, int DV, int ncols1, int ncols2, ggml_type type_K = GGML_TYPE_F16, ggml_type type_V = GGML_TYPE_F16>
|
||||
void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
|
||||
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
|
||||
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
|
||||
|
||||
const ggml_tensor * KQV = dst;
|
||||
const int id = ggml_cuda_get_device();
|
||||
const int cc = ggml_cuda_info().devices[id].cc;
|
||||
@@ -2223,7 +2131,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml
|
||||
if constexpr (ggml_cuda_flash_attn_ext_mma_f16_may_use_sparse(DKQ, DV, ncols1, ncols2)) {
|
||||
if (ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, ncols1, ncols2)) {
|
||||
constexpr bool use_sparse_kernel = true;
|
||||
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel>;
|
||||
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel, type_K, type_V>;
|
||||
use_sparse = true;
|
||||
|
||||
static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false};
|
||||
@@ -2233,7 +2141,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml
|
||||
}
|
||||
} else {
|
||||
constexpr bool use_sparse_kernel = false;
|
||||
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel>;
|
||||
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel, type_K, type_V>;
|
||||
|
||||
static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false};
|
||||
if (!shared_memory_limit_raised[id]) {
|
||||
@@ -2245,7 +2153,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml
|
||||
#endif // !defined(GGML_USE_MUSA)
|
||||
{
|
||||
constexpr bool use_sparse_kernel = false;
|
||||
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel>;
|
||||
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel, type_K, type_V>;
|
||||
|
||||
static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false};
|
||||
if (!shared_memory_limit_raised[id]) {
|
||||
@@ -2256,7 +2164,7 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml
|
||||
} else {
|
||||
constexpr bool use_logit_softcap = true;
|
||||
constexpr bool use_sparse_kernel = false;
|
||||
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel>;
|
||||
fattn_kernel = flash_attn_ext_f16<DKQ, DV, ncols1, ncols2, use_logit_softcap, V_is_K_view, use_sparse_kernel, type_K, type_V>;
|
||||
|
||||
static bool shared_memory_limit_raised[GGML_CUDA_MAX_DEVICES] = {false};
|
||||
if (!shared_memory_limit_raised[id]) {
|
||||
@@ -2266,83 +2174,83 @@ void ggml_cuda_flash_attn_ext_mma_f16_case(ggml_backend_cuda_context & ctx, ggml
|
||||
}
|
||||
|
||||
const bool async_kv_preload = nstages == 2 && !use_sparse;
|
||||
launch_fattn<DV, ncols1, ncols2>
|
||||
launch_fattn<DV, ncols1, ncols2, T_K, T_V>
|
||||
(ctx, dst, fattn_kernel, nwarps, nbytes_shared_total, nbatch_fa, true, true, true, use_sparse, warp_size_host, async_kv_preload);
|
||||
}
|
||||
|
||||
|
||||
#define DECL_FATTN_MMA_F16_CASE(DKQ, DV, ncols1, ncols2) \
|
||||
template void ggml_cuda_flash_attn_ext_mma_f16_case \
|
||||
<DKQ, DV, ncols1, ncols2>(ggml_backend_cuda_context & ctx, ggml_tensor * dst) \
|
||||
#define DECL_FATTN_MMA_F16_CASE(DKQ, DV, ncols1, ncols2, type_K, type_V) \
|
||||
template void ggml_cuda_flash_attn_ext_mma_f16_case \
|
||||
<DKQ, DV, ncols1, ncols2, type_K, type_V>(ggml_backend_cuda_context & ctx, ggml_tensor * dst) \
|
||||
|
||||
#define DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(DKQ, DV, ncols) \
|
||||
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 1, 1); \
|
||||
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 2, 2); \
|
||||
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 4, 4); \
|
||||
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 8, 8); \
|
||||
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/16, 16); \
|
||||
#define DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(DKQ, DV, ncols, type_K, type_V) \
|
||||
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 1, 1, type_K, type_V); \
|
||||
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 2, 2, type_K, type_V); \
|
||||
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 4, 4, type_K, type_V); \
|
||||
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/ 8, 8, type_K, type_V); \
|
||||
extern DECL_FATTN_MMA_F16_CASE(DKQ, DV, (ncols)/16, 16, type_K, type_V); \
|
||||
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 8)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 8)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 8)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 8)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 8)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 8)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 8)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 8)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 8, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 8, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 8, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 8, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 8, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 8, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 8, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 8, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 16, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 16, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 16, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 16, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 16, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 16, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 16, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 16, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 32)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 32)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 32)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 32)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 32)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 32)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 32)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 32)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 32, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 32, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 32, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 32, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 32, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 32, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 32, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 32, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 64)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 64)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 64)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 64)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 64)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 64)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 64)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 64)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 40, 40, 64, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 64, 64, 64, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 72, 72, 64, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 80, 80, 64, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2( 96, 96, 64, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(112, 112, 64, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(128, 128, 64, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
DECL_FATTN_MMA_F16_CASE_ALL_NCOLS2(256, 256, 64, GGML_TYPE_F16, GGML_TYPE_F16)
|
||||
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 2);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 2);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 16, 2);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 32, 2);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 2, 4);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 4);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 4);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 16, 4);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 1, 8);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 2, 8);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 8);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 8);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 2, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 2, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 16, 2, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 32, 2, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 2, 4, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 1, 8, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 2, 8, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 4, 8, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(512, 512, 8, 8, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
|
||||
// The number of viable configurations for Deepseek is very limited:
|
||||
extern DECL_FATTN_MMA_F16_CASE(576, 512, 1, 16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(576, 512, 2, 16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(576, 512, 4, 16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(576, 512, 1, 16, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(576, 512, 2, 16, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(576, 512, 4, 16, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
|
||||
// Mistral Small 4 (DKQ=320, DV=256), GQA=32-only build:
|
||||
extern DECL_FATTN_MMA_F16_CASE(320, 256, 1, 32);
|
||||
extern DECL_FATTN_MMA_F16_CASE(320, 256, 2, 32);
|
||||
extern DECL_FATTN_MMA_F16_CASE(320, 256, 1, 32, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(320, 256, 2, 32, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
|
||||
// For GLM 4.7 Flash
|
||||
extern DECL_FATTN_MMA_F16_CASE(576, 512, 4, 4);
|
||||
extern DECL_FATTN_MMA_F16_CASE(576, 512, 8, 4);
|
||||
extern DECL_FATTN_MMA_F16_CASE(576, 512, 16, 4);
|
||||
extern DECL_FATTN_MMA_F16_CASE(576, 512, 1, 32);
|
||||
extern DECL_FATTN_MMA_F16_CASE(576, 512, 2, 32);
|
||||
extern DECL_FATTN_MMA_F16_CASE(576, 512, 4, 4, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(576, 512, 8, 4, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(576, 512, 16, 4, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(576, 512, 1, 32, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_MMA_F16_CASE(576, 512, 2, 32, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
|
||||
@@ -1,59 +1,75 @@
|
||||
#include "common.cuh"
|
||||
#include "fattn-tile.cuh"
|
||||
|
||||
void ggml_cuda_flash_attn_ext_tile(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
|
||||
template <ggml_type type_K, ggml_type type_V>
|
||||
static void ggml_cuda_flash_attn_ext_tile_switch_head_size(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
|
||||
const ggml_tensor * K = dst->src[1];
|
||||
const ggml_tensor * V = dst->src[2];
|
||||
switch (K->ne[0]) {
|
||||
case 40: {
|
||||
GGML_ASSERT(V->ne[0] == K->ne[0]);
|
||||
ggml_cuda_flash_attn_ext_tile_case< 40, 40>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_tile_case< 40, 40, type_K, type_V>(ctx, dst);
|
||||
} break;
|
||||
case 64: {
|
||||
GGML_ASSERT(V->ne[0] == K->ne[0]);
|
||||
ggml_cuda_flash_attn_ext_tile_case< 64, 64>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_tile_case< 64, 64, type_K, type_V>(ctx, dst);
|
||||
} break;
|
||||
case 72: {
|
||||
GGML_ASSERT(V->ne[0] == K->ne[0]);
|
||||
ggml_cuda_flash_attn_ext_tile_case< 72, 72>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_tile_case< 72, 72, type_K, type_V>(ctx, dst);
|
||||
} break;
|
||||
case 80: {
|
||||
GGML_ASSERT(V->ne[0] == K->ne[0]);
|
||||
ggml_cuda_flash_attn_ext_tile_case< 80, 80>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_tile_case< 80, 80, type_K, type_V>(ctx, dst);
|
||||
} break;
|
||||
case 96: {
|
||||
GGML_ASSERT(V->ne[0] == K->ne[0]);
|
||||
ggml_cuda_flash_attn_ext_tile_case< 96, 96>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_tile_case< 96, 96, type_K, type_V>(ctx, dst);
|
||||
} break;
|
||||
case 112: {
|
||||
GGML_ASSERT(V->ne[0] == K->ne[0]);
|
||||
ggml_cuda_flash_attn_ext_tile_case<112, 112>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_tile_case<112, 112, type_K, type_V>(ctx, dst);
|
||||
} break;
|
||||
case 128: {
|
||||
GGML_ASSERT(V->ne[0] == K->ne[0]);
|
||||
ggml_cuda_flash_attn_ext_tile_case<128, 128>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_tile_case<128, 128, type_K, type_V>(ctx, dst);
|
||||
} break;
|
||||
case 192: {
|
||||
GGML_ASSERT(V->ne[0] == 128);
|
||||
ggml_cuda_flash_attn_ext_tile_case<192, 128>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_tile_case<192, 128, type_K, type_V>(ctx, dst);
|
||||
} break;
|
||||
case 256: {
|
||||
GGML_ASSERT(V->ne[0] == K->ne[0]);
|
||||
ggml_cuda_flash_attn_ext_tile_case<256, 256>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_tile_case<256, 256, type_K, type_V>(ctx, dst);
|
||||
} break;
|
||||
case 320: {
|
||||
GGML_ASSERT(V->ne[0] == 256);
|
||||
ggml_cuda_flash_attn_ext_tile_case<320, 256>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_tile_case<320, 256, type_K, type_V>(ctx, dst);
|
||||
} break;
|
||||
case 512: {
|
||||
GGML_ASSERT(V->ne[0] == K->ne[0]);
|
||||
ggml_cuda_flash_attn_ext_tile_case<512, 512>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_tile_case<512, 512, type_K, type_V>(ctx, dst);
|
||||
} break;
|
||||
case 576: {
|
||||
GGML_ASSERT(V->ne[0] == 512);
|
||||
ggml_cuda_flash_attn_ext_tile_case<576, 512>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_tile_case<576, 512, type_K, type_V>(ctx, dst);
|
||||
} break;
|
||||
default:
|
||||
GGML_ABORT("Unsupported head size");
|
||||
}
|
||||
}
|
||||
|
||||
void ggml_cuda_flash_attn_ext_tile(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
|
||||
const ggml_tensor * K = dst->src[1];
|
||||
const ggml_tensor * V = dst->src[2];
|
||||
|
||||
if constexpr (GGML_CUDA_FA_F16_F16) {
|
||||
if (K->type == GGML_TYPE_F16 && V->type == GGML_TYPE_F16) {
|
||||
ggml_cuda_flash_attn_ext_tile_switch_head_size<GGML_TYPE_F16, GGML_TYPE_F16>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: convert K and V to F16.
|
||||
ggml_cuda_flash_attn_ext_tile_switch_head_size<GGML_TYPE_F16, GGML_TYPE_F16>(ctx, dst);
|
||||
}
|
||||
|
||||
+159
-227
@@ -373,133 +373,29 @@ static constexpr __device__ int ggml_cuda_fattn_tile_get_nbatch_K(const int DKQ,
|
||||
return (ggml_cuda_fattn_tile_get_config(DKQ, DV, ncols) >> 23) & ((1 << 9) - 1);
|
||||
}
|
||||
|
||||
// TODO: deduplicate with mma-f16
|
||||
template<int warp_size, int nwarps, int I, int J, int J_padding, bool oob_check>
|
||||
static __device__ __forceinline__ void flash_attn_tile_load_tile(
|
||||
const half2 * const __restrict__ KV, half2 * const __restrict__ tile_KV, const int stride_KV, const int i_sup) {
|
||||
constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
|
||||
constexpr int cpy_ne = cpy_nb / 4;
|
||||
|
||||
auto load = [&] __device__ (const int n) {
|
||||
const int stride_j = warp_size >> n;
|
||||
|
||||
if (stride_j == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const int j0_start = stride_j == warp_size ? 0 : ((J/2)/cpy_ne) - ((J/2)/cpy_ne) % (2*stride_j);
|
||||
const int j0_stop = ((J/2)/cpy_ne) - ((J/2)/cpy_ne) % (1*stride_j);
|
||||
const int stride_i = warp_size / stride_j;
|
||||
|
||||
if (j0_start == j0_stop) {
|
||||
return;
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) {
|
||||
const int i = i0 + threadIdx.y*stride_i + (stride_j == warp_size ? 0 : threadIdx.x / stride_j);
|
||||
|
||||
if (i0 + nwarps*stride_i <= I || i < I) {
|
||||
#pragma unroll
|
||||
for (int j0 = j0_start; j0 < j0_stop; j0 += stride_j) {
|
||||
const int j = j0*cpy_ne + (stride_j == warp_size ? threadIdx.x : threadIdx.x % stride_j)*cpy_ne;
|
||||
|
||||
const __align__(16) half2 zero[cpy_ne] = {{0.0f, 0.0f}};
|
||||
ggml_cuda_memcpy_1<cpy_nb>(
|
||||
tile_KV + i*(J/2 + J_padding) + j,
|
||||
!oob_check || i < i_sup ? KV + i*stride_KV + j : zero);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
// 1: max 64*16=512 bytes, 512 half
|
||||
// 2: max 32*16=512 bytes, 256 half
|
||||
// 3: max 16*16=256 bytes, 128 half
|
||||
// 4: max 8*16=128 bytes, 64 half
|
||||
// 5: max 4*16= 64 bytes, 32 half
|
||||
// 6: max 2*16= 32 bytes, 16 half
|
||||
// 7: max 1*16= 16 bytes, 8 half
|
||||
static_assert(J % 8 == 0, "bad J");
|
||||
static_assert((J/2) % cpy_ne == 0, "bad J");
|
||||
ggml_cuda_unroll<7>{}(load);
|
||||
}
|
||||
|
||||
template<int warp_size, int nwarps, int I, int J, int J_padding, bool oob_check>
|
||||
static __device__ __forceinline__ void flash_attn_tile_load_tile(
|
||||
const half2 * const __restrict__ KV, float * const __restrict__ tile_KV, const int stride_KV, const int i_sup) {
|
||||
constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
|
||||
constexpr int cpy_ne = cpy_nb / 4;
|
||||
|
||||
auto load = [&] __device__ (const int n) {
|
||||
const int stride_j = warp_size >> n;
|
||||
|
||||
if (stride_j == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const int j0_start = stride_j == warp_size ? 0 : (J/cpy_ne) - (J/cpy_ne) % (2*stride_j);
|
||||
const int j0_stop = (J/cpy_ne) - (J/cpy_ne) % (1*stride_j);
|
||||
const int stride_i = warp_size / stride_j;
|
||||
|
||||
if (j0_start == j0_stop) {
|
||||
return;
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int i0 = 0; i0 < I; i0 += nwarps*stride_i) {
|
||||
const int i = i0 + threadIdx.y*stride_i + (stride_j == warp_size ? 0 : threadIdx.x / stride_j);
|
||||
|
||||
if (i0 + nwarps*stride_i <= I || i < I) {
|
||||
#pragma unroll
|
||||
for (int j0 = j0_start; j0 < j0_stop; j0 += stride_j) {
|
||||
const int j = j0*(cpy_ne/2) + (stride_j == warp_size ? threadIdx.x : threadIdx.x % stride_j)*(cpy_ne/2);
|
||||
|
||||
const half2 zero[cpy_ne/2] = {{0.0f, 0.0f}};
|
||||
__align__(16) half2 tmp_h2[cpy_ne/2];
|
||||
ggml_cuda_memcpy_1<sizeof(tmp_h2)>(
|
||||
tmp_h2, !oob_check || i < i_sup ? KV + i*stride_KV + j : zero);
|
||||
|
||||
__align__(16) float2 tmp_f2[cpy_ne/2];
|
||||
#pragma unroll
|
||||
for (int l = 0; l < cpy_ne/2; ++l) {
|
||||
tmp_f2[l] = __half22float2(tmp_h2[l]);
|
||||
}
|
||||
ggml_cuda_memcpy_1<sizeof(tmp_f2)>(tile_KV + i*(J + J_padding) + 2*j, tmp_f2);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
// 1: max 32*16=512 bytes, 128 float
|
||||
// 2: max 16*16=256 bytes, 64 float
|
||||
// 3: max 8*16=128 bytes, 32 float
|
||||
// 4: max 4*16= 64 bytes, 16 float
|
||||
// 5: max 2*16= 32 bytes, 8 float
|
||||
static_assert(J % 8 == 0, "bad J");
|
||||
static_assert(J % cpy_ne == 0, "bad J");
|
||||
ggml_cuda_unroll<5>{}(load);
|
||||
}
|
||||
|
||||
// Function that performs a single iteration in for the KQ matrix multiplication:
|
||||
template <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>
|
||||
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 half2 * const __restrict__ K_h2,
|
||||
const T_K * const __restrict__ K_h2,
|
||||
T_vec_dot * const KV_tmp,
|
||||
const int stride_K2,
|
||||
const int k_VKQ_0,
|
||||
const int k_VKQ_sup,
|
||||
const int k_KQ_0,
|
||||
float * KQ_acc) {
|
||||
constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
|
||||
float * KQ_acc,
|
||||
const int32_t * const __restrict__ rows) {
|
||||
constexpr int cpy_nb = 16;
|
||||
constexpr int cpy_ne = cpy_nb / 4;
|
||||
|
||||
constexpr int ncols = ncols1*ncols2;
|
||||
constexpr int cpw = ncols > nwarps ? ncols/nwarps : 1; // Q columns per warp
|
||||
constexpr int np = nwarps > ncols ? nwarps/ncols : 1; // number of parallel warps per Q column
|
||||
|
||||
flash_attn_tile_load_tile<warp_size, nwarps, nbatch_fa, nbatch_K, cpy_ne, oob_check>
|
||||
(K_h2 + int64_t(k_VKQ_0)*stride_K2 + k_KQ_0/2, KV_tmp, stride_K2, k_VKQ_sup);
|
||||
constexpr int stride_tile_K = std::is_same_v<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, 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
|
||||
@@ -556,11 +452,11 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ(
|
||||
|
||||
// Function that performs a single iteration of the main loop over up to nbatch_fa tokens.
|
||||
template <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>
|
||||
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 half2 * const __restrict__ K_h2,
|
||||
const half2 * const __restrict__ V_h2,
|
||||
const T_K * const __restrict__ K_h2,
|
||||
const T_V * const __restrict__ V_h2,
|
||||
const half * const __restrict__ mask,
|
||||
const uint3 ne01,
|
||||
const float logit_softcap,
|
||||
@@ -575,8 +471,10 @@ 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) {
|
||||
constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
|
||||
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;
|
||||
|
||||
constexpr int ncols = ncols1*ncols2;
|
||||
@@ -607,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:
|
||||
@@ -636,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);
|
||||
}
|
||||
@@ -716,10 +618,11 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
|
||||
constexpr int nbatch_V = (DV % nbatch_K == 0 ? nbatch_K : nbatch_K*2/3) * nbatch_fa / DV; // Number of V columns that fit in SRAM for K.
|
||||
static_assert(nbatch_fa % nbatch_V == 0, "bad nbatch_V");
|
||||
static_assert(nbatch_V % np == 0, "bad nbatch_V");
|
||||
constexpr int stride_tile_V = std::is_same_v<T_vec_dot, half2> ? DV/2 : DV;
|
||||
#pragma unroll
|
||||
for (int k0 = 0; k0 < nbatch_fa; k0 += nbatch_V) {
|
||||
flash_attn_tile_load_tile<warp_size, nwarps, nbatch_V, DV, 0, oob_check>
|
||||
(V_h2 + int64_t(k_VKQ_0 + k0)*stride_V2, KV_tmp, stride_V2, k_VKQ_sup - k0);
|
||||
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
|
||||
@@ -788,18 +691,18 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
|
||||
}
|
||||
}
|
||||
|
||||
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap> // 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 char * Q_ptr,
|
||||
const char * K_ptr,
|
||||
const char * V_ptr,
|
||||
const char * mask_ptr,
|
||||
const char * sinks_ptr,
|
||||
const int * KV_max_ptr,
|
||||
const int * KV_rows_ptr,
|
||||
float * dst_ptr,
|
||||
float2 * dst_meta_ptr,
|
||||
const float2 * Q_ptr,
|
||||
const char * K_ptr,
|
||||
const char * V_ptr,
|
||||
const half * mask_ptr,
|
||||
const float * sinks_ptr,
|
||||
const int * KV_max_ptr,
|
||||
const int * KV_rows_ptr,
|
||||
float * dst_ptr,
|
||||
float2 * dst_meta_ptr,
|
||||
const float scale,
|
||||
const float max_bias,
|
||||
const float m0,
|
||||
@@ -807,22 +710,25 @@ static __global__ void flash_attn_tile(
|
||||
const uint32_t n_head_log2,
|
||||
const float logit_softcap,
|
||||
const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03,
|
||||
const int32_t nb01, const int32_t nb02, const int32_t nb03,
|
||||
const int32_t s01, const int32_t s02, const int32_t s03,
|
||||
const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13,
|
||||
const int32_t nb11, const int32_t nb12, const int64_t nb13,
|
||||
const int32_t nb21, const int32_t nb22, const int64_t nb23,
|
||||
const int32_t s11, const int32_t s12, const int64_t s13,
|
||||
const int32_t s21, const int32_t s22, const int64_t s23,
|
||||
const int32_t ne31, const int32_t ne32, const int32_t ne33,
|
||||
const int32_t nb31, const int64_t nb32, const int64_t nb33) {
|
||||
const int32_t s31, const int64_t s32, const int64_t s33,
|
||||
const fattn_indexed_bias bias) {
|
||||
#ifdef FLASH_ATTN_AVAILABLE
|
||||
const char * GGML_CUDA_RESTRICT Q = Q_ptr;
|
||||
const char * GGML_CUDA_RESTRICT K = K_ptr;
|
||||
const char * GGML_CUDA_RESTRICT V = V_ptr;
|
||||
const char * GGML_CUDA_RESTRICT mask = mask_ptr;
|
||||
const char * GGML_CUDA_RESTRICT sinks = sinks_ptr;
|
||||
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
|
||||
float * GGML_CUDA_RESTRICT dst = dst_ptr;
|
||||
float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr;
|
||||
GGML_UNUSED(KV_rows_ptr);
|
||||
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
|
||||
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
|
||||
|
||||
const float2 * GGML_CUDA_RESTRICT Q = Q_ptr;
|
||||
const T_K * GGML_CUDA_RESTRICT K = (const T_K *) K_ptr;
|
||||
const T_V * GGML_CUDA_RESTRICT V = (const T_V *) V_ptr;
|
||||
const half * GGML_CUDA_RESTRICT mask = mask_ptr;
|
||||
const float * GGML_CUDA_RESTRICT sinks = sinks_ptr;
|
||||
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
|
||||
float * GGML_CUDA_RESTRICT dst = dst_ptr;
|
||||
float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr;
|
||||
|
||||
// Skip unused kernel variants for faster compilation:
|
||||
|
||||
@@ -830,15 +736,22 @@ static __global__ void flash_attn_tile(
|
||||
GGML_UNUSED_VARS(Q, K, V, mask, sinks, KV_max, dst, dst_meta, scale,
|
||||
max_bias, m0, m1, n_head_log2, logit_softcap,
|
||||
ne00, ne01, ne02, ne03,
|
||||
nb01, nb02, nb03,
|
||||
s01, s02, s03,
|
||||
ne10, ne11, ne12, ne13,
|
||||
nb11, nb12, nb13,
|
||||
nb21, nb22, nb23,
|
||||
s11, s12, s13,
|
||||
s21, s22, s23,
|
||||
ne31, ne32, ne33,
|
||||
nb31, nb32, nb33);
|
||||
s31, s32, s33);
|
||||
NO_DEVICE_CODE;
|
||||
return;
|
||||
}
|
||||
#ifdef AMD_MFMA_AVAILABLE
|
||||
if (ncols1 == 64 && ncols2 == 1) {
|
||||
// The tile kernel is suffering from register spills for ncols1 == 64 && ncols2 == 1.
|
||||
NO_DEVICE_CODE;
|
||||
return;
|
||||
}
|
||||
#endif // AMD_MFMA_AVAILABLE
|
||||
|
||||
static_assert(ggml_cuda_fattn_tile_get_config(DKQ, DV, ncols1*ncols2) != 0, "kernel config not defined");
|
||||
|
||||
@@ -854,20 +767,23 @@ 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 float * Q_f = (const float *) (Q + nb03*sequence + nb02* head0);
|
||||
const half2 * K_h2 = (const half2 *) (K + nb13*sequence + nb12*(head0 / gqa_ratio));
|
||||
const half2 * V_h2 = (const half2 *) (V + nb23*sequence + nb22*(head0 / gqa_ratio)); // K and V have same shape
|
||||
const float2 * Q_f2 = Q + s03*sequence + s02* head0;
|
||||
const T_K * K_h2 = K + s13*sequence + s12*(head0 / gqa_ratio);
|
||||
const T_V * V_h2 = V + s23*sequence + s22*(head0 / gqa_ratio); // K and V have same shape
|
||||
|
||||
const half * maskh = mask ? (const half *) (mask + nb33*(sequence % ne33) + nb32*(head0 % ne32)) : nullptr;
|
||||
const half * maskh = indexed_bias || mask ? mask + s33*(sequence % ne33) + s32*(head0 % ne32) : nullptr;
|
||||
|
||||
const int stride_K2 = nb11 / sizeof(half2);
|
||||
const int stride_V2 = nb21 / sizeof(half2);
|
||||
const int stride_mask = nb31 / sizeof(half);
|
||||
const int stride_K2 = s11;
|
||||
const int stride_V2 = s21;
|
||||
const int stride_mask = s31;
|
||||
|
||||
const float slope = ncols2 == 1 ? get_alibi_slope(max_bias, head0, n_head_log2, m0, m1) : 1.0f;
|
||||
|
||||
constexpr int cpy_nb = ggml_cuda_get_max_cpy_bytes();
|
||||
constexpr int cpy_nb = 16;
|
||||
constexpr int cpy_ne = cpy_nb / 4;
|
||||
|
||||
constexpr int cpw = ncols > nwarps ? ncols/nwarps : 1; // Q columns per warp.
|
||||
@@ -919,8 +835,7 @@ static __global__ void flash_attn_tile(
|
||||
if (i0 + np*warp_size*cpy_ne_D <= DKQ || i0 + (threadIdx.y % np)*(warp_size*cpy_ne_D) + threadIdx.x*cpy_ne_D < DKQ) {
|
||||
__align__(16) float tmp_f[cpy_ne_D] = {0.0f};
|
||||
ggml_cuda_memcpy_1<sizeof(tmp_f)>
|
||||
(tmp_f, &Q_f[c*(nb02/sizeof(float)) + fastmodulo(col_Q_0 + j, ne01)*(nb01/sizeof(float))
|
||||
+ i0 + (threadIdx.y % np)*(warp_size*cpy_ne_D) + threadIdx.x*cpy_ne_D]);
|
||||
(tmp_f, Q_f2 + c*s02 + fastmodulo(col_Q_0 + j, ne01)*s01 + i0/2 + (threadIdx.y % np)*(warp_size*(cpy_ne_D/2)) + threadIdx.x*(cpy_ne_D/2));
|
||||
|
||||
#pragma unroll
|
||||
for (int i1 = 0; i1 < cpy_ne_D; ++i1) {
|
||||
@@ -959,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1056,7 +971,7 @@ static __global__ void flash_attn_tile(
|
||||
#pragma unroll
|
||||
for (int jc0 = 0; jc0 < cpw; ++jc0) {
|
||||
const int jc = jc0 + (threadIdx.y/np)*cpw;
|
||||
const float sink = ((const float *) sinks)[head0 + jc % ncols2];
|
||||
const float sink = sinks[head0 + jc % ncols2];
|
||||
|
||||
float KQ_max_new_j = fmaxf(KQ_max[jc0], sink);
|
||||
const float KQ_max_scale = expf(KQ_max[jc0] - KQ_max_new_j);
|
||||
@@ -1093,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;
|
||||
|
||||
@@ -1105,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);
|
||||
@@ -1119,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],
|
||||
@@ -1137,18 +1053,21 @@ static __global__ void flash_attn_tile(
|
||||
GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale,
|
||||
max_bias, m0, m1, n_head_log2, logit_softcap,
|
||||
ne00, ne01, ne02, ne03,
|
||||
nb01, nb02, nb03,
|
||||
s01, s02, s03,
|
||||
ne10, ne11, ne12, ne13,
|
||||
nb11, nb12, nb13,
|
||||
nb21, nb22, nb23,
|
||||
s11, s12, s13,
|
||||
s21, s22, s23,
|
||||
ne31, ne32, ne33,
|
||||
nb31, nb32, nb33);
|
||||
s31, s32, s33, bias);
|
||||
NO_DEVICE_CODE;
|
||||
#endif // FLASH_ATTN_AVAILABLE
|
||||
}
|
||||
|
||||
template <int DKQ, int DV, int ncols2, bool use_logit_softcap>
|
||||
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>());
|
||||
|
||||
const ggml_tensor * Q = dst->src[0];
|
||||
|
||||
const int id = ggml_cuda_get_device();
|
||||
@@ -1158,41 +1077,43 @@ 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) {
|
||||
if (Q->ne[1] > 32/ncols2) {
|
||||
// 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>;
|
||||
launch_fattn<DV, cols_per_block/ncols2, ncols2>
|
||||
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>;
|
||||
launch_fattn<DV, cols_per_block/ncols2, ncols2>
|
||||
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>;
|
||||
launch_fattn<DV, cols_per_block/ncols2, ncols2>
|
||||
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;
|
||||
}
|
||||
@@ -1203,8 +1124,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
|
||||
constexpr int cols_per_block = 8;
|
||||
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
|
||||
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
|
||||
launch_fattn<DV, cols_per_block/ncols2, ncols2>
|
||||
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;
|
||||
}
|
||||
@@ -1215,8 +1136,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
|
||||
constexpr int cols_per_block = 4;
|
||||
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
|
||||
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
|
||||
launch_fattn<DV, cols_per_block/ncols2, ncols2>
|
||||
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;
|
||||
}
|
||||
@@ -1226,8 +1147,8 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
|
||||
constexpr int cols_per_block = 2;
|
||||
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
|
||||
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap>;
|
||||
launch_fattn<DV, cols_per_block/ncols2, ncols2>
|
||||
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;
|
||||
}
|
||||
@@ -1235,7 +1156,7 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
|
||||
GGML_ABORT("fatal error");
|
||||
}
|
||||
|
||||
template <int DKQ, int DV, bool use_logit_softcap>
|
||||
template <int DKQ, int DV, bool use_logit_softcap, ggml_type type_K, ggml_type type_V>
|
||||
static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
|
||||
const ggml_tensor * KQV = dst;
|
||||
const ggml_tensor * Q = dst->src[0];
|
||||
@@ -1255,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.
|
||||
@@ -1262,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>(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>(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
|
||||
@@ -1276,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>(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>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -1288,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>(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>(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");
|
||||
@@ -1300,29 +1232,29 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
|
||||
|
||||
if constexpr (DKQ <= 512 && DKQ != 320 && DKQ != 192) {
|
||||
if (use_gqa_opt && gqa_ratio % 8 == 0) {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 8, use_logit_softcap>(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>(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>(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>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 1, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
}
|
||||
GGML_ABORT("fatal error");
|
||||
}
|
||||
|
||||
template <int DKQ, int DV>
|
||||
template <int DKQ, int DV, ggml_type type_K, ggml_type type_V>
|
||||
void ggml_cuda_flash_attn_ext_tile_case(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
|
||||
const ggml_tensor * KQV = dst;
|
||||
|
||||
@@ -1331,28 +1263,28 @@ void ggml_cuda_flash_attn_ext_tile_case(ggml_backend_cuda_context & ctx, ggml_te
|
||||
|
||||
if (logit_softcap == 0.0f) {
|
||||
constexpr bool use_logit_softcap = false;
|
||||
launch_fattn_tile_switch_ncols2<DKQ, DV, use_logit_softcap>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols2<DKQ, DV, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
} else {
|
||||
constexpr bool use_logit_softcap = true;
|
||||
launch_fattn_tile_switch_ncols2<DKQ, DV, use_logit_softcap>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols2<DKQ, DV, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
}
|
||||
}
|
||||
|
||||
void ggml_cuda_flash_attn_ext_tile(ggml_backend_cuda_context & ctx, ggml_tensor * dst);
|
||||
|
||||
#define DECL_FATTN_TILE_CASE(DKQ, DV) \
|
||||
template void ggml_cuda_flash_attn_ext_tile_case \
|
||||
<DKQ, DV>(ggml_backend_cuda_context & ctx, ggml_tensor * dst) \
|
||||
#define DECL_FATTN_TILE_CASE(DKQ, DV, type_K, type_V) \
|
||||
template void ggml_cuda_flash_attn_ext_tile_case \
|
||||
<DKQ, DV, type_K, type_V>(ggml_backend_cuda_context & ctx, ggml_tensor * dst) \
|
||||
|
||||
extern DECL_FATTN_TILE_CASE( 40, 40);
|
||||
extern DECL_FATTN_TILE_CASE( 64, 64);
|
||||
extern DECL_FATTN_TILE_CASE( 72, 72);
|
||||
extern DECL_FATTN_TILE_CASE( 80, 80);
|
||||
extern DECL_FATTN_TILE_CASE( 96, 96);
|
||||
extern DECL_FATTN_TILE_CASE(112, 112);
|
||||
extern DECL_FATTN_TILE_CASE(128, 128);
|
||||
extern DECL_FATTN_TILE_CASE(192, 128);
|
||||
extern DECL_FATTN_TILE_CASE(256, 256);
|
||||
extern DECL_FATTN_TILE_CASE(320, 256);
|
||||
extern DECL_FATTN_TILE_CASE(512, 512);
|
||||
extern DECL_FATTN_TILE_CASE(576, 512);
|
||||
extern DECL_FATTN_TILE_CASE( 40, 40, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_TILE_CASE( 64, 64, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_TILE_CASE( 72, 72, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_TILE_CASE( 80, 80, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_TILE_CASE( 96, 96, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_TILE_CASE(112, 112, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_TILE_CASE(128, 128, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_TILE_CASE(192, 128, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_TILE_CASE(256, 256, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_TILE_CASE(320, 256, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_TILE_CASE(512, 512, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
extern DECL_FATTN_TILE_CASE(576, 512, GGML_TYPE_F16, GGML_TYPE_F16);
|
||||
|
||||
@@ -16,18 +16,18 @@ 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 char * Q_ptr,
|
||||
const char * K_ptr,
|
||||
const char * V_ptr,
|
||||
const char * mask_ptr,
|
||||
const char * sinks_ptr,
|
||||
const int * KV_max_ptr,
|
||||
const int * KV_rows_ptr,
|
||||
float * dst_ptr,
|
||||
float2 * dst_meta_ptr,
|
||||
const float2 * Q_ptr,
|
||||
const char * K_ptr,
|
||||
const char * V_ptr,
|
||||
const half * mask_ptr,
|
||||
const float * sinks_ptr,
|
||||
const int * KV_max_ptr,
|
||||
const int * KV_rows_ptr,
|
||||
float * dst_ptr,
|
||||
float2 * dst_meta_ptr,
|
||||
const float scale,
|
||||
const float max_bias,
|
||||
const float m0,
|
||||
@@ -35,35 +35,35 @@ static __global__ void flash_attn_ext_vec(
|
||||
const uint32_t n_head_log2,
|
||||
const float logit_softcap,
|
||||
const int32_t ne00, const uint3 ne01, const int32_t ne02, const int32_t ne03,
|
||||
const int32_t nb01, const int32_t nb02, const int32_t nb03,
|
||||
const int32_t s01, const int32_t s02, const int32_t s03,
|
||||
const int32_t ne10, const int32_t ne11, const int32_t ne12, const int32_t ne13,
|
||||
const int32_t nb11, const int32_t nb12, const int64_t nb13,
|
||||
const int32_t nb21, const int32_t nb22, const int64_t nb23,
|
||||
const int32_t s11, const int32_t s12, const int64_t s13,
|
||||
const int32_t s21, const int32_t s22, const int64_t s23,
|
||||
const int32_t ne31, const int32_t ne32, const int32_t ne33,
|
||||
const int32_t nb31, const int64_t nb32, const int64_t nb33) {
|
||||
const int32_t s31, const int64_t s32, const int64_t s33,
|
||||
const fattn_indexed_bias bias) {
|
||||
ggml_cuda_pdl_lc();
|
||||
#ifdef FLASH_ATTN_AVAILABLE
|
||||
const char * GGML_CUDA_RESTRICT Q = Q_ptr;
|
||||
const char * GGML_CUDA_RESTRICT K = K_ptr;
|
||||
const char * GGML_CUDA_RESTRICT V = V_ptr;
|
||||
const char * GGML_CUDA_RESTRICT mask = mask_ptr;
|
||||
const char * GGML_CUDA_RESTRICT sinks = sinks_ptr;
|
||||
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
|
||||
float * GGML_CUDA_RESTRICT dst = dst_ptr;
|
||||
float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr;
|
||||
GGML_UNUSED(KV_rows_ptr);
|
||||
const float2 * GGML_CUDA_RESTRICT Q = Q_ptr;
|
||||
const char * GGML_CUDA_RESTRICT K = K_ptr;
|
||||
const char * GGML_CUDA_RESTRICT V = V_ptr;
|
||||
const half * GGML_CUDA_RESTRICT mask = mask_ptr;
|
||||
const float * GGML_CUDA_RESTRICT sinks = sinks_ptr;
|
||||
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
|
||||
float * GGML_CUDA_RESTRICT dst = dst_ptr;
|
||||
float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr;
|
||||
|
||||
// Skip unused kernel variants for faster compilation:
|
||||
if (use_logit_softcap && !(D == 128 || D == 256)) {
|
||||
GGML_UNUSED_VARS(Q, K, V, mask, sinks, KV_max, dst, dst_meta, scale,
|
||||
max_bias, m0, m1, n_head_log2, logit_softcap,
|
||||
ne00, ne01, ne02, ne03,
|
||||
nb01, nb02, nb03,
|
||||
s01, s02, s03,
|
||||
ne10, ne11, ne12, ne13,
|
||||
nb11, nb12, nb13,
|
||||
nb21, nb22, nb23,
|
||||
s11, s12, s13,
|
||||
s21, s22, s23,
|
||||
ne31, ne32, ne33,
|
||||
nb31, nb32, nb33);
|
||||
s31, s32, s33);
|
||||
NO_DEVICE_CODE;
|
||||
return;
|
||||
}
|
||||
@@ -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 += nb03*sequence + nb02* head + nb01*ic0;
|
||||
K += nb13*sequence + nb12*(head / gqa_ratio);
|
||||
V += nb23*sequence + nb22*(head / gqa_ratio);
|
||||
Q += s03*sequence + s02* head + s01*ic0;
|
||||
K += s13*sequence + s12*(head / gqa_ratio);
|
||||
V += s23*sequence + s22*(head / gqa_ratio);
|
||||
|
||||
const half * maskh = mask ? (const half *) (mask + nb33*(sequence % ne33) + nb32*(head % ne32) + nb31*ic0) : nullptr;
|
||||
const half * maskh = 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);
|
||||
|
||||
@@ -176,7 +177,7 @@ static __global__ void flash_attn_ext_vec(
|
||||
tmp_q_ds[threadIdx.x] = make_float2(0.0f, 0.0f);
|
||||
}
|
||||
} else {
|
||||
const float * Q_f = (const float *) (Q + j*nb01);
|
||||
const float * Q_f = (const float *) (Q + j*s01);
|
||||
constexpr int nthreads_quantize = D/sizeof(int) < WARP_SIZE ? D/sizeof(int) : WARP_SIZE;
|
||||
#pragma unroll
|
||||
for (int i0 = 0; i0 < int(D/sizeof(int)); i0 += nthreads_quantize) {
|
||||
@@ -206,7 +207,7 @@ static __global__ void flash_attn_ext_vec(
|
||||
} else if constexpr (type_K == GGML_TYPE_F8_E4M3) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < ncols; ++j) {
|
||||
const float * Q_j = (const float *) (Q + j*nb01);
|
||||
const float * Q_j = (const float *) (Q + j*s01);
|
||||
#pragma unroll
|
||||
for (int i0 = 0; i0 < D; i0 += nthreads_KQ*4) {
|
||||
const int i = i0 + (threadIdx.x % nthreads_KQ)*4;
|
||||
@@ -229,7 +230,7 @@ static __global__ void flash_attn_ext_vec(
|
||||
const half2 scale_h2 = make_half2(scale, scale);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < ncols; ++j) {
|
||||
const float2 * Q_j = (const float2 *) (Q + j*nb01);
|
||||
const float2 * Q_j = Q + j*s01;
|
||||
#pragma unroll
|
||||
for (int i0 = 0; i0 < D/2; i0 += nthreads_KQ*cpy_ne) {
|
||||
const int i = i0 + (nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ)*cpy_ne;
|
||||
@@ -252,7 +253,7 @@ static __global__ void flash_attn_ext_vec(
|
||||
#else
|
||||
#pragma unroll
|
||||
for (int j = 0; j < ncols; ++j) {
|
||||
const float2 * Q_j = (const float2 *) (Q + j*nb01);
|
||||
const float2 * Q_j = Q + j*s01;
|
||||
#pragma unroll
|
||||
for (int i0 = 0; i0 < D/2; i0 += nthreads_KQ*cpy_ne) {
|
||||
const int i = i0 + (nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ)*cpy_ne;
|
||||
@@ -271,12 +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 * nb11;
|
||||
V += blockIdx.y*nthreads * nb21;
|
||||
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*nb11, V += gridDim.y*nthreads*nb21, 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*nb11, 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*nb21, 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*nb21, 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*nb21, 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) {
|
||||
@@ -402,7 +416,7 @@ static __global__ void flash_attn_ext_vec(
|
||||
}
|
||||
|
||||
if (sinks && blockIdx.y == 0) {
|
||||
const float sink = ((const float *) sinks)[head];
|
||||
const float sink = sinks[head];
|
||||
|
||||
#pragma unroll
|
||||
for (int j0 = 0; j0 < ncols; j0 += nwarps) {
|
||||
@@ -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;
|
||||
}
|
||||
@@ -540,12 +554,12 @@ static __global__ void flash_attn_ext_vec(
|
||||
GGML_UNUSED_VARS(Q_ptr, K_ptr, V_ptr, mask_ptr, sinks_ptr, KV_max_ptr, KV_rows_ptr, dst_ptr, dst_meta_ptr, scale,
|
||||
max_bias, m0, m1, n_head_log2, logit_softcap,
|
||||
ne00, ne01, ne02, ne03,
|
||||
nb01, nb02, nb03,
|
||||
s01, s02, s03,
|
||||
ne10, ne11, ne12, ne13,
|
||||
nb11, nb12, nb13,
|
||||
nb21, nb22, nb23,
|
||||
s11, s12, s13,
|
||||
s21, s22, s23,
|
||||
ne31, ne32, ne33,
|
||||
nb31, nb32, nb33);
|
||||
s31, s32, s33, bias);
|
||||
NO_DEVICE_CODE;
|
||||
#endif // FLASH_ATTN_AVAILABLE
|
||||
}
|
||||
@@ -559,11 +573,17 @@ 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;
|
||||
launch_fattn<D, cols_per_block, 1>(ctx, dst, fattn_kernel, nwarps, nbytes_shared, D, need_f16_K, need_f16_V, false, false);
|
||||
launch_fattn<D, cols_per_block, 1, char, char>(ctx, dst, fattn_kernel, nwarps, nbytes_shared, D, need_f16_K, need_f16_V, false, false);
|
||||
}
|
||||
|
||||
template <int D, ggml_type type_K, ggml_type type_V>
|
||||
|
||||
+91
-53
@@ -159,7 +159,7 @@ bool ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(const int cc, const ggml_
|
||||
#endif // !defined(GGML_USE_MUSA)
|
||||
}
|
||||
|
||||
template <int DKQ, int DV, int ncols2>
|
||||
template <int DKQ, int DV, int ncols2, ggml_type type_K, ggml_type type_V>
|
||||
static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
|
||||
const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc;
|
||||
const ggml_tensor * Q = dst->src[0];
|
||||
@@ -169,7 +169,7 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ggml_backend_cuda_con
|
||||
// a sparse variant at the full tile width gathers the union of its queries once, prefer it for large batches
|
||||
constexpr bool has_wide_sparse = ggml_cuda_flash_attn_ext_mma_f16_may_use_sparse(DKQ, DV, 64/ncols2, ncols2);
|
||||
if (!(has_wide_sparse && Q->ne[1] > 32/ncols2) && ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, 1, ncols2)) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 1, ncols2>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 1, ncols2, type_K, type_V>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -177,38 +177,39 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1(ggml_backend_cuda_con
|
||||
|
||||
if constexpr (ncols2 <= 8) {
|
||||
if (turing_mma_available(cc) && Q->ne[1] <= 8/ncols2) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 8/ncols2, ncols2>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 8/ncols2, ncols2, type_K, type_V>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if constexpr (ncols2 <= 16) {
|
||||
if (Q->ne[1] <= 16/ncols2) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 16/ncols2, ncols2>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 16/ncols2, ncols2, type_K, type_V>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (Q->ne[1] <= 32/ncols2 || (GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) == GGML_CUDA_CC_TURING) ||
|
||||
(GGML_CUDA_CC_IS_AMD(cc) && DKQ > 256)) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 32/ncols2, ncols2>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 32/ncols2, ncols2, type_K, type_V>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
|
||||
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 64/ncols2, ncols2>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_case<DKQ, DV, 64/ncols2, ncols2, type_K, type_V>(ctx, dst);
|
||||
}
|
||||
|
||||
template <int DKQ, int DV>
|
||||
template <int DKQ, int DV, ggml_type type_K, ggml_type type_V>
|
||||
static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
|
||||
const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc;
|
||||
const ggml_tensor * KQV = dst;
|
||||
const ggml_tensor * Q = dst->src[0];
|
||||
const ggml_tensor * K = dst->src[1];
|
||||
const ggml_tensor * V = dst->src[2];
|
||||
const ggml_tensor * mask = dst->src[3];
|
||||
const ggml_tensor * KQV = dst;
|
||||
const ggml_tensor * Q = dst->src[0];
|
||||
const ggml_tensor * K = dst->src[1];
|
||||
const ggml_tensor * V = dst->src[2];
|
||||
const ggml_tensor * mask = dst->src[3];
|
||||
const ggml_tensor * kv_rows = dst->src[5];
|
||||
|
||||
// with kv_rows the kernel iterates over the mask columns
|
||||
const int64_t n_kv = dst->src[5] ? dst->src[5]->ne[0] : K->ne[1];
|
||||
const int64_t n_kv = kv_rows ? kv_rows->ne[0] : K->ne[1];
|
||||
|
||||
float max_bias = 0.0f;
|
||||
memcpy(&max_bias, (const float *) KQV->op_params + 1, sizeof(float));
|
||||
@@ -235,22 +236,22 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_con
|
||||
// On Volta the GQA optimizations aren't as impactful vs. minimizing wasted compute:
|
||||
if (cc == GGML_CUDA_CC_VOLTA) {
|
||||
if (use_gqa_opt && gqa_ratio % 8 == 0) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8, type_K, type_V>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
|
||||
if (use_gqa_opt && gqa_ratio % 4 == 0) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4, type_K, type_V>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
|
||||
if constexpr (DKQ <= 256) {
|
||||
if (use_gqa_opt && gqa_ratio % 2 == 0) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2, type_K, type_V>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1, type_K, type_V>(ctx, dst);
|
||||
return;
|
||||
} else {
|
||||
GGML_ABORT("fatal error");
|
||||
@@ -260,44 +261,45 @@ static void ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2(ggml_backend_cuda_con
|
||||
// On RDNA it is preferable to minimize wasted compute vs. duplicate I/O for the mask.
|
||||
if (amd_wmma_available(cc)) {
|
||||
if (use_gqa_opt && gqa_ratio % 8 == 0) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8, type_K, type_V>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
|
||||
if (use_gqa_opt && gqa_ratio % 4 == 0) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4, type_K, type_V>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
|
||||
if (use_gqa_opt && gqa_ratio % 2 == 0) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2, type_K, type_V>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (use_gqa_opt && gqa_ratio > 4) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 8, type_K, type_V>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
|
||||
if (use_gqa_opt && gqa_ratio > 2) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 4, type_K, type_V>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
|
||||
if (use_gqa_opt && gqa_ratio > 1) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 2, type_K, type_V>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
|
||||
if constexpr (DKQ <= 256) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<DKQ, DV, 1, type_K, type_V>(ctx, dst);
|
||||
} else {
|
||||
GGML_ABORT("fatal error");
|
||||
}
|
||||
}
|
||||
|
||||
static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
|
||||
template <ggml_type type_K, ggml_type type_V>
|
||||
static void ggml_cuda_flash_attn_ext_mma_f16_switch_head_size(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
|
||||
const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc;
|
||||
const ggml_tensor * KQV = dst;
|
||||
const ggml_tensor * Q = dst->src[0];
|
||||
@@ -308,31 +310,31 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg
|
||||
switch (Q->ne[0]) {
|
||||
case 40:
|
||||
GGML_ASSERT(V->ne[0] == 40);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 40, 40>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 40, 40, type_K, type_V>(ctx, dst);
|
||||
break;
|
||||
case 64:
|
||||
GGML_ASSERT(V->ne[0] == 64);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 64, 64>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 64, 64, type_K, type_V>(ctx, dst);
|
||||
break;
|
||||
case 72:
|
||||
GGML_ASSERT(V->ne[0] == 72);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 72, 72>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 72, 72, type_K, type_V>(ctx, dst);
|
||||
break;
|
||||
case 80:
|
||||
GGML_ASSERT(V->ne[0] == 80);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 80, 80>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 80, 80, type_K, type_V>(ctx, dst);
|
||||
break;
|
||||
case 96:
|
||||
GGML_ASSERT(V->ne[0] == 96);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 96, 96>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2< 96, 96, type_K, type_V>(ctx, dst);
|
||||
break;
|
||||
case 112:
|
||||
GGML_ASSERT(V->ne[0] == 112);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<112, 112>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<112, 112, type_K, type_V>(ctx, dst);
|
||||
break;
|
||||
case 128:
|
||||
GGML_ASSERT(V->ne[0] == 128);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<128, 128>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<128, 128, type_K, type_V>(ctx, dst);
|
||||
break;
|
||||
case 192: {
|
||||
// MiMo-V2.5 / V2.5-Pro / V2-Flash: gqa_ratio is 8 (SWA) or 16 (full attn)
|
||||
@@ -344,15 +346,15 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg
|
||||
GGML_ASSERT(Q->ne[2] % K->ne[2] == 0);
|
||||
const int gqa_ratio = Q->ne[2] / K->ne[2];
|
||||
if (gqa_ratio % 16 == 0) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 16>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 16, type_K, type_V>(ctx, dst);
|
||||
} else {
|
||||
GGML_ASSERT(gqa_ratio % 8 == 0);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 8>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<192, 128, 8, type_K, type_V>(ctx, dst);
|
||||
}
|
||||
} break;
|
||||
case 256:
|
||||
GGML_ASSERT(V->ne[0] == 256);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<256, 256>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<256, 256, type_K, type_V>(ctx, dst);
|
||||
break;
|
||||
case 320:
|
||||
// For Mistral Small 4, go straight to the ncols1 switch (ncols2=32-only build).
|
||||
@@ -367,12 +369,12 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg
|
||||
const int gqa_ratio = Q->ne[2] / K->ne[2];
|
||||
GGML_ASSERT(gqa_ratio % 32 == 0);
|
||||
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<320, 256, 32>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<320, 256, 32, type_K, type_V>(ctx, dst);
|
||||
}
|
||||
break;
|
||||
case 512:
|
||||
GGML_ASSERT(V->ne[0] == 512);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<512, 512>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols2<512, 512, type_K, type_V>(ctx, dst);
|
||||
break;
|
||||
case 576: {
|
||||
// For Deepseek, go straight to the ncols1 switch to avoid compiling unnecessary kernels.
|
||||
@@ -386,50 +388,50 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg
|
||||
GGML_ASSERT(Q->ne[2] % K->ne[2] == 0);
|
||||
const int gqa_ratio = Q->ne[2] / K->ne[2];
|
||||
if (amd_mfma_available(cc) && ggml_cuda_flash_attn_ext_mma_f16_shall_use_sparse(cc, dst, 1, 16)) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
|
||||
} else if (gqa_ratio == 20 && GGML_CUDA_CC_IS_NVIDIA(cc)) { // GLM 4.7 Flash
|
||||
if (cc >= GGML_CUDA_CC_GB10) {
|
||||
if (Q->ne[1] <= 8) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
|
||||
break;
|
||||
}
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
|
||||
break;
|
||||
}
|
||||
if (cc >= GGML_CUDA_CC_BLACKWELL) {
|
||||
if (Q->ne[1] <= 4 && K->ne[1] >= 65536) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
|
||||
break;
|
||||
}
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
|
||||
break;
|
||||
}
|
||||
if (cc >= GGML_CUDA_CC_ADA_LOVELACE) {
|
||||
if (Q->ne[1] <= 4) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
|
||||
break;
|
||||
}
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
|
||||
break;
|
||||
}
|
||||
if (cc >= GGML_CUDA_CC_TURING) {
|
||||
if (Q->ne[1] <= 4) {
|
||||
if (K->ne[1] <= 16384) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
|
||||
break;
|
||||
}
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 32>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 32, type_K, type_V>(ctx, dst);
|
||||
break;
|
||||
}
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
|
||||
break;
|
||||
}
|
||||
// Volta:
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
|
||||
} else if (gqa_ratio % 16 == 0) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 16, type_K, type_V>(ctx, dst);
|
||||
} else {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4>(ctx, dst);
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_ncols1<576, 512, 4, type_K, type_V>(ctx, dst);
|
||||
}
|
||||
} break;
|
||||
default:
|
||||
@@ -437,6 +439,21 @@ static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, gg
|
||||
}
|
||||
}
|
||||
|
||||
static void ggml_cuda_flash_attn_ext_mma_f16(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
|
||||
const ggml_tensor * K = dst->src[1];
|
||||
const ggml_tensor * V = dst->src[2];
|
||||
|
||||
if constexpr (GGML_CUDA_FA_F16_F16) {
|
||||
if (K->type == GGML_TYPE_F16 && V->type == GGML_TYPE_F16) {
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_head_size<GGML_TYPE_F16, GGML_TYPE_F16>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: convert K and V to F16.
|
||||
ggml_cuda_flash_attn_ext_mma_f16_switch_head_size<GGML_TYPE_F16, GGML_TYPE_F16>(ctx, dst);
|
||||
}
|
||||
|
||||
#define FATTN_VEC_CASE(D, type_K_case, type_V_case) \
|
||||
if constexpr (GGML_CUDA_FA_##type_K_case##_##type_V_case) { \
|
||||
if (head_size == (D) && type_K == GGML_TYPE_##type_K_case && type_V == GGML_TYPE_##type_V_case) { \
|
||||
@@ -589,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];
|
||||
|
||||
@@ -669,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) {
|
||||
@@ -682,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;
|
||||
@@ -728,12 +763,15 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
|
||||
gqa_ratio_eff *= 2;
|
||||
}
|
||||
|
||||
// the tile kernel for DKQ=576 only has the ncols2 = 4 and 16 variants
|
||||
const best_fattn_kernel tile_kernel = Q->ne[0] == 576 && gqa_ratio % 4 != 0 ? BEST_FATTN_KERNEL_NONE : BEST_FATTN_KERNEL_TILE;
|
||||
|
||||
if (volta_mma_available(cc) && Q->ne[0] != 40 && Q->ne[0] != 72) {
|
||||
if (can_use_vector_kernel && Q->ne[1] * gqa_ratio_eff <= 2) {
|
||||
return BEST_FATTN_KERNEL_VEC;
|
||||
}
|
||||
if (Q->ne[1] * gqa_ratio_eff <= 16) {
|
||||
return BEST_FATTN_KERNEL_TILE; // On Volta tensor cores are only faster for sufficiently large matrices.
|
||||
return tile_kernel; // On Volta tensor cores are only faster for sufficiently large matrices.
|
||||
}
|
||||
return BEST_FATTN_KERNEL_MMA_F16;
|
||||
}
|
||||
@@ -779,7 +817,7 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
|
||||
}
|
||||
}
|
||||
}
|
||||
return BEST_FATTN_KERNEL_TILE;
|
||||
return tile_kernel;
|
||||
}
|
||||
|
||||
size_t ggml_cuda_flash_attn_ext_get_alloc_size(int device, const ggml_tensor * dst) {
|
||||
|
||||
+36
-19
@@ -1,9 +1,11 @@
|
||||
#include "convert.cuh"
|
||||
#include "fp8.cuh"
|
||||
|
||||
#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && CUDART_VERSION >= 11080
|
||||
|
||||
template <typename src_t>
|
||||
struct fp8_abs_src {
|
||||
const float * x;
|
||||
const src_t * x;
|
||||
int64_t ne0;
|
||||
int64_t ne1;
|
||||
int64_t ne2;
|
||||
@@ -18,12 +20,13 @@ struct fp8_abs_src {
|
||||
i /= ne1;
|
||||
const int64_t i2 = i % ne2;
|
||||
const int64_t i3 = i / ne2;
|
||||
const float value = fabsf(x[i0 + i1*s1 + i2*s2 + i3*s3]);
|
||||
const float value = fabsf(ggml_cuda_cast<float>(x[i0 + i1*s1 + i2*s2 + i3*s3]));
|
||||
return isfinite(value) ? value : 448.0f;
|
||||
}
|
||||
};
|
||||
|
||||
static __global__ void fp8_amax_partials(fp8_abs_src src, int64_t ne, float * partials) {
|
||||
template <typename src_t>
|
||||
static __global__ void fp8_amax_partials(fp8_abs_src<src_t> src, int64_t ne, float * partials) {
|
||||
float amax = 0.0f;
|
||||
for (int64_t i = (int64_t) blockIdx.x*blockDim.x + threadIdx.x; i < ne; i += (int64_t) blockDim.x*gridDim.x) {
|
||||
amax = fmaxf(amax, src(i));
|
||||
@@ -49,8 +52,9 @@ static __global__ void fp8_amax_final(const float * partials, int n, float * ama
|
||||
}
|
||||
}
|
||||
|
||||
template <typename src_t>
|
||||
static __global__ void quantize_fp8_e4m3(
|
||||
const float * __restrict__ x, uint8_t * __restrict__ y, const float * __restrict__ amax,
|
||||
const src_t * __restrict__ x, uint8_t * __restrict__ y, const float * __restrict__ amax,
|
||||
float * __restrict__ scale, int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne, int64_t s1, int64_t s2, int64_t s3) {
|
||||
const int64_t i = (int64_t) blockIdx.x*blockDim.x + threadIdx.x;
|
||||
if (i >= ne) {
|
||||
@@ -65,12 +69,26 @@ static __global__ void quantize_fp8_e4m3(
|
||||
const int64_t i3 = tmp / ne2;
|
||||
|
||||
const float d = *amax > 0.0f ? *amax / 448.0f : 1.0f;
|
||||
y[i] = ggml_cuda_fp32_to_f8_e4m3(x[i0 + i1*s1 + i2*s2 + i3*s3] / d);
|
||||
y[i] = ggml_cuda_fp32_to_f8_e4m3(ggml_cuda_cast<float>(x[i0 + i1*s1 + i2*s2 + i3*s3]) / d);
|
||||
if (i == 0) {
|
||||
*scale = d;
|
||||
}
|
||||
}
|
||||
|
||||
// src1 (F32 or BF16) to FP8 with one scale for the whole tensor: amax / 448
|
||||
template <typename src_t>
|
||||
static void fp8_quantize_src1(
|
||||
ggml_backend_cuda_context & ctx, const src_t * x, uint8_t * y, float * amax, float * scale,
|
||||
int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne, int64_t s1, int64_t s2, int64_t s3, cudaStream_t stream) {
|
||||
const fp8_abs_src<src_t> abs_src = { x, ne0, ne1, ne2, s1, s2, s3 };
|
||||
const int reduce_blocks = std::min<int64_t>((ne + 255)/256, 1024);
|
||||
ggml_cuda_pool_alloc<float> reduce_tmp(ctx.pool(), reduce_blocks);
|
||||
fp8_amax_partials<<<reduce_blocks, 256, 0, stream>>>(abs_src, ne, reduce_tmp.ptr);
|
||||
fp8_amax_final<<<1, 256, 0, stream>>>(reduce_tmp.ptr, reduce_blocks, amax);
|
||||
|
||||
quantize_fp8_e4m3<<<(ne + 255)/256, 256, 0, stream>>>(x, y, amax, scale, ne0, ne1, ne2, ne, s1, s2, s3);
|
||||
}
|
||||
|
||||
static void fp8_set_batch(cublasLtMatrixLayout_t desc, int32_t count, int64_t stride) {
|
||||
CUBLAS_CHECK(cublasLtMatrixLayoutSetAttribute(desc, CUBLASLT_MATRIX_LAYOUT_BATCH_COUNT, &count, sizeof(count)));
|
||||
CUBLAS_CHECK(cublasLtMatrixLayoutSetAttribute(desc, CUBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, &stride, sizeof(stride)));
|
||||
@@ -89,9 +107,9 @@ bool ggml_cuda_mul_mat_fp8(
|
||||
ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst,
|
||||
const ggml_tensor * weight_scale) {
|
||||
const int cc = ggml_cuda_info().devices[ctx.device].cc;
|
||||
if (!fp8_mma_hardware_available(cc) || src0->type != GGML_TYPE_F8_E4M3 || src1->type != GGML_TYPE_F32 ||
|
||||
if (!fp8_mma_hardware_available(cc) || src0->type != GGML_TYPE_F8_E4M3 || (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_BF16) ||
|
||||
dst->type != GGML_TYPE_F32 || !ggml_is_contiguous(dst) || src0->ne[0] % 16 != 0 || src0->ne[1] % 16 != 0 ||
|
||||
src0->nb[0] != sizeof(uint8_t) || src0->nb[1] != (size_t) src0->ne[0] || src1->nb[0] != sizeof(float) ||
|
||||
src0->nb[0] != sizeof(uint8_t) || src0->nb[1] != (size_t) src0->ne[0] || src1->nb[0] != ggml_type_size(src1->type) ||
|
||||
!ggml_cuda_is_aligned(src0, 16) || !ggml_cuda_is_aligned(dst, 16)) {
|
||||
return false;
|
||||
}
|
||||
@@ -110,18 +128,17 @@ bool ggml_cuda_mul_mat_fp8(
|
||||
ggml_cuda_pool_alloc<float> src1_scale(ctx.pool(), 1);
|
||||
ggml_cuda_pool_alloc<float> src1_amax(ctx.pool(), 1);
|
||||
|
||||
const fp8_abs_src abs_src = {
|
||||
(const float *) src1->data, ne10, ne11, ne12,
|
||||
(int64_t) (nb11 / sizeof(float)), (int64_t) (nb12 / sizeof(float)), (int64_t) (nb13 / sizeof(float))
|
||||
};
|
||||
const int reduce_blocks = std::min<int64_t>((ne_src1 + 255)/256, 1024);
|
||||
ggml_cuda_pool_alloc<float> reduce_tmp(ctx.pool(), reduce_blocks);
|
||||
fp8_amax_partials<<<reduce_blocks, 256, 0, stream>>>(abs_src, ne_src1, reduce_tmp.ptr);
|
||||
fp8_amax_final<<<1, 256, 0, stream>>>(reduce_tmp.ptr, reduce_blocks, src1_amax.ptr);
|
||||
|
||||
quantize_fp8_e4m3<<<(ne_src1 + 255)/256, 256, 0, stream>>>(
|
||||
(const float *) src1->data, src1_fp8.ptr, src1_amax.ptr, src1_scale.ptr, ne10, ne11, ne12, ne_src1,
|
||||
nb11 / sizeof(float), nb12 / sizeof(float), nb13 / sizeof(float));
|
||||
const int64_t s11 = nb11 / nb10;
|
||||
const int64_t s12 = nb12 / nb10;
|
||||
const int64_t s13 = nb13 / nb10;
|
||||
if (src1->type == GGML_TYPE_BF16) {
|
||||
fp8_quantize_src1(ctx, (const nv_bfloat16 *) src1->data, src1_fp8.ptr, src1_amax.ptr, src1_scale.ptr,
|
||||
ne10, ne11, ne12, ne_src1, s11, s12, s13, stream);
|
||||
} else {
|
||||
GGML_ASSERT(src1->type == GGML_TYPE_F32);
|
||||
fp8_quantize_src1(ctx, (const float *) src1->data, src1_fp8.ptr, src1_amax.ptr, src1_scale.ptr,
|
||||
ne10, ne11, ne12, ne_src1, s11, s12, s13, stream);
|
||||
}
|
||||
CUDA_CHECK(cudaGetLastError());
|
||||
|
||||
cublasLtMatmulDesc_t op_desc;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user