mirror of
https://github.com/ggml-org/llama.cpp.git
synced 2026-11-27 05:07:41 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2a8bf0f593 | ||
|
|
e7ec6361dc | ||
|
|
69812f63c2 | ||
|
|
f351f415d6 | ||
|
|
00d5c142c8 | ||
|
|
ca123ba763 | ||
|
|
f89a243d53 |
@@ -18,6 +18,8 @@ ARG NODE_VERSION=24
|
||||
FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
|
||||
ARG VITE_PUBLIC_HUGGING_FACE=false
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
|
||||
@@ -25,11 +27,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
|
||||
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
|
||||
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM ${CANN_BASE_IMAGE} AS build
|
||||
|
||||
@@ -8,6 +8,8 @@ ARG NODE_VERSION=24
|
||||
FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
|
||||
ARG VITE_PUBLIC_HUGGING_FACE=false
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
|
||||
@@ -15,11 +17,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
|
||||
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
|
||||
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM docker.io/ubuntu:$UBUNTU_VERSION AS build
|
||||
|
||||
@@ -16,6 +16,8 @@ ARG NODE_VERSION=24
|
||||
FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
|
||||
ARG VITE_PUBLIC_HUGGING_FACE=false
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
|
||||
@@ -23,11 +25,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
|
||||
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
|
||||
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM ${BASE_CUDA_DEV_CONTAINER} AS build
|
||||
|
||||
@@ -10,6 +10,8 @@ ARG NODE_VERSION=24
|
||||
FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
|
||||
ARG VITE_PUBLIC_HUGGING_FACE=false
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
|
||||
@@ -17,11 +19,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
|
||||
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
|
||||
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM docker.io/intel/deep-learning-essentials:$ONEAPI_VERSION AS build
|
||||
|
||||
@@ -14,6 +14,8 @@ ARG NODE_VERSION=24
|
||||
FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
|
||||
ARG VITE_PUBLIC_HUGGING_FACE=false
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
|
||||
@@ -21,11 +23,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
|
||||
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
|
||||
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM ${BASE_MUSA_DEV_CONTAINER} AS build
|
||||
|
||||
@@ -27,6 +27,8 @@ ARG NODE_VERSION=24
|
||||
FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
|
||||
ARG VITE_PUBLIC_HUGGING_FACE=false
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
|
||||
@@ -34,11 +36,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
|
||||
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
|
||||
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
## Build Image
|
||||
|
||||
@@ -16,6 +16,8 @@ ARG NODE_VERSION=24
|
||||
FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
|
||||
ARG VITE_PUBLIC_HUGGING_FACE=false
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
|
||||
@@ -23,11 +25,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
|
||||
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
|
||||
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
### Build image
|
||||
|
||||
@@ -8,6 +8,8 @@ ARG NODE_VERSION=24
|
||||
FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
|
||||
ARG VITE_PUBLIC_HUGGING_FACE=false
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
|
||||
@@ -15,11 +17,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
|
||||
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
|
||||
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM docker.io/ubuntu:$UBUNTU_VERSION AS build
|
||||
|
||||
@@ -8,6 +8,8 @@ ARG NODE_VERSION=24
|
||||
FROM docker.io/node:$NODE_VERSION AS web
|
||||
|
||||
ARG APP_VERSION
|
||||
# true builds the UI with sharing conversations to Hugging Face, as the llama-server images do
|
||||
ARG VITE_PUBLIC_HUGGING_FACE=false
|
||||
|
||||
WORKDIR /app/ui/apps/chat
|
||||
|
||||
@@ -15,11 +17,12 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY ui/apps/chat/ ./
|
||||
# the app compiles Llama UI, Llama Voice and the harness from their sources next to it
|
||||
# the app compiles Llama UI, Llama Voice, the harness and Llama Hugging Face from their sources next to it
|
||||
COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json
|
||||
COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/
|
||||
COPY ui/lib/voice/src/ /app/ui/lib/voice/src/
|
||||
COPY ui/lib/harness/src/ /app/ui/lib/harness/src/
|
||||
COPY ui/lib/huggingface/src/ /app/ui/lib/huggingface/src/
|
||||
RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build
|
||||
|
||||
FROM docker.io/ubuntu:$UBUNTU_VERSION AS build
|
||||
|
||||
@@ -269,6 +269,7 @@ jobs:
|
||||
build-args: |
|
||||
BUILD_DATE=${{ steps.build_date.outputs.date }}
|
||||
APP_VERSION=${{ needs.create_tag.outputs.source_tag }}
|
||||
VITE_PUBLIC_HUGGING_FACE=true
|
||||
APP_REVISION=${{ steps.checkout.outputs.commit }}
|
||||
IMAGE_URL=${{ github.server_url }}/${{ github.repository }}
|
||||
IMAGE_SOURCE=${{ github.server_url }}/${{ github.repository }}
|
||||
@@ -306,6 +307,7 @@ jobs:
|
||||
build-args: |
|
||||
BUILD_DATE=${{ steps.build_date.outputs.date }}
|
||||
APP_VERSION=${{ needs.create_tag.outputs.source_tag }}
|
||||
VITE_PUBLIC_HUGGING_FACE=true
|
||||
APP_REVISION=${{ steps.checkout.outputs.commit }}
|
||||
IMAGE_URL=${{ github.server_url }}/${{ github.repository }}
|
||||
IMAGE_SOURCE=${{ github.server_url }}/${{ github.repository }}
|
||||
@@ -343,6 +345,7 @@ jobs:
|
||||
build-args: |
|
||||
BUILD_DATE=${{ steps.build_date.outputs.date }}
|
||||
APP_VERSION=${{ needs.create_tag.outputs.source_tag }}
|
||||
VITE_PUBLIC_HUGGING_FACE=true
|
||||
APP_REVISION=${{ steps.checkout.outputs.commit }}
|
||||
IMAGE_URL=${{ github.server_url }}/${{ github.repository }}
|
||||
IMAGE_SOURCE=${{ github.server_url }}/${{ github.repository }}
|
||||
|
||||
@@ -33,6 +33,9 @@ jobs:
|
||||
- name: Build application
|
||||
run: npm run build
|
||||
working-directory: ui/apps/chat
|
||||
env:
|
||||
# as in ui-build.yml: the UI under test has the Hugging Face lib
|
||||
VITE_PUBLIC_HUGGING_FACE: "true"
|
||||
|
||||
- name: Upload built UI
|
||||
uses: actions/upload-artifact@v6
|
||||
|
||||
@@ -47,6 +47,8 @@ jobs:
|
||||
- name: Build application
|
||||
env:
|
||||
LLAMA_BUILD_NUMBER: ${{ steps.version.outputs.ui_version }}
|
||||
# the UI that the releases and the prebuilt download are made of has the Hugging Face lib
|
||||
VITE_PUBLIC_HUGGING_FACE: "true"
|
||||
run: npm run build
|
||||
working-directory: ui/apps/chat
|
||||
|
||||
|
||||
@@ -94,6 +94,9 @@ jobs:
|
||||
# This folder's .npmrc sets ignore-scripts, so npm never builds it: this step does.
|
||||
run: LLAMA_BUILD_NUMBER="b$(git rev-list --count HEAD)" npm run build
|
||||
working-directory: ${{ env.APP_DIR }}
|
||||
env:
|
||||
# the same app as the UI llama-server embeds, with the Hugging Face lib
|
||||
VITE_PUBLIC_HUGGING_FACE: "true"
|
||||
|
||||
- name: Test the CLI and the alias version
|
||||
run: npx vitest --project=unit --run tests/unit/cli.test.ts
|
||||
|
||||
@@ -21,6 +21,7 @@ on:
|
||||
'ui/lib/ui/**.*',
|
||||
'ui/lib/voice/**.*',
|
||||
'ui/lib/harness/**.*',
|
||||
'ui/lib/huggingface/**.*',
|
||||
'tools/server/tests/**.*'
|
||||
]
|
||||
pull_request:
|
||||
@@ -32,6 +33,7 @@ on:
|
||||
'ui/lib/ui/**.*',
|
||||
'ui/lib/voice/**.*',
|
||||
'ui/lib/harness/**.*',
|
||||
'ui/lib/huggingface/**.*',
|
||||
'tools/server/tests/**.*'
|
||||
]
|
||||
|
||||
@@ -127,6 +129,9 @@ jobs:
|
||||
if: ${{ always() && steps.setup.conclusion == 'success' }}
|
||||
run: npm run build-storybook
|
||||
working-directory: ui/apps/chat
|
||||
env:
|
||||
# its stories show the Hugging Face lib
|
||||
VITE_PUBLIC_HUGGING_FACE: "true"
|
||||
|
||||
- name: Run UI tests
|
||||
if: ${{ always() && steps.setup.conclusion == 'success' }}
|
||||
|
||||
@@ -49,6 +49,9 @@ jobs:
|
||||
- name: Build Storybook
|
||||
run: npm run build-storybook
|
||||
working-directory: ui/apps/chat
|
||||
env:
|
||||
# its stories show the Hugging Face lib
|
||||
VITE_PUBLIC_HUGGING_FACE: "true"
|
||||
|
||||
- name: Write the Space card
|
||||
run: |
|
||||
|
||||
@@ -275,6 +275,71 @@ jobs:
|
||||
fi
|
||||
working-directory: ui/apps/chat
|
||||
|
||||
huggingface-lib-bundle:
|
||||
name: Hugging Face lib in the bundle
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24"
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
working-directory: ui/apps/chat
|
||||
|
||||
- name: Build with and without the Hugging Face lib
|
||||
run: |
|
||||
npm run build
|
||||
VITE_PUBLIC_HUGGING_FACE=true LLAMA_UI_OUT_DIR=dist-with-sharing npm run build
|
||||
working-directory: ui/apps/chat
|
||||
|
||||
# a text of the lib's sign-in: it is in the bundle only when the lib is
|
||||
- name: Check the Hugging Face lib is only in the bundle built with it
|
||||
run: |
|
||||
marker="Hugging Face sent no access token back"
|
||||
if ! grep -rlq "$marker" dist-with-sharing; then
|
||||
echo "The bundle built with the Hugging Face lib does not contain it" && exit 1
|
||||
fi
|
||||
if grep -rlq "$marker" dist; then
|
||||
echo "The default bundle contains the Hugging Face lib" && exit 1
|
||||
fi
|
||||
working-directory: ui/apps/chat
|
||||
|
||||
huggingface-lib-checks:
|
||||
name: Hugging Face lib checks
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24"
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
working-directory: ui/lib/huggingface
|
||||
|
||||
# its plain TypeScript; the components are checked with the app that compiles them
|
||||
- name: Run type checking
|
||||
run: npm run check
|
||||
working-directory: ui/lib/huggingface
|
||||
|
||||
- name: Run tests
|
||||
run: npm test
|
||||
working-directory: ui/lib/huggingface
|
||||
|
||||
e2e-tests:
|
||||
name: E2E Tests
|
||||
needs: ui-build
|
||||
@@ -317,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' }}
|
||||
|
||||
@@ -272,7 +272,7 @@ void ggml_cuda_mul_mat_q(
|
||||
ggml_cuda_pool_alloc<char> src1_q8_1(ctx.pool(), nbytes_src1_q8_1);
|
||||
ggml_cuda_pool_alloc<float> src1_scale(ctx.pool());
|
||||
if (src0->type == GGML_TYPE_NVFP4 && use_native_fp4) {
|
||||
src1_scale.alloc(ne13*ne12*ne11);
|
||||
src1_scale.alloc(ne13*ne12*ne11 + J_best-1); // Needs to be padded for unconditional memory access.
|
||||
}
|
||||
|
||||
{
|
||||
@@ -342,7 +342,7 @@ void ggml_cuda_mul_mat_q(
|
||||
ggml_cuda_pool_alloc<char> src1_q8_1(ctx.pool(), nbytes_src1_q8_1);
|
||||
ggml_cuda_pool_alloc<float> src1_scale(ctx.pool());
|
||||
if (src0->type == GGML_TYPE_NVFP4 && use_native_fp4) {
|
||||
src1_scale.alloc(ne12*n_expert_used);
|
||||
src1_scale.alloc(ne12*n_expert_used + J_best-1); // Needs to be padded for unconditional memory access.
|
||||
}
|
||||
|
||||
const int64_t ne11_flat = ne12*n_expert_used;
|
||||
|
||||
@@ -134,7 +134,7 @@ size_t opt_mbuf_dyn = 512ul * 1024 * 1024; // max dynamic (compute) buff
|
||||
size_t opt_mbuf_static = 1ul * 1024 * 1024 * 1024; // max static (weight/KV) buffer size
|
||||
size_t opt_mbuf_total = 0; // total buffer space limit (0 = unconstrained)
|
||||
|
||||
int opt_mm_select = 3; // 4 = pure W8A8, 3 = hybrid W8A8 + FP16 post-GLU (default), 2 = FP16 HMX -> HVX -> CPU, 1 = HVX -> CPU, 0 = CPU
|
||||
int opt_mm_select = 3; // 3 = W8A8 INT HMX -> FP16 HMX -> HVX -> CPU (default), 2 = FP16 HMX -> HVX -> CPU, 1 = HVX -> CPU, 0 = CPU
|
||||
int opt_fa_select = 3; // 3 = INT HMX W8A8 (default) -> FP16 HMX -> HVX -> CPU, 2 = FP16 HMX -> HVX -> CPU, 1 = HVX -> CPU, 0 = CPU
|
||||
int opt_fa_split = 1; // 1 = head-split + team-split when n_kv_heads < N_cores (default), 0 = off
|
||||
int opt_li_select = 2; // 2 = HMX -> HVX, 1 = HVX, 0 = CPU (unsupported)
|
||||
|
||||
@@ -706,29 +706,6 @@ static bool htp_matmul_is_hmx_eligible(
|
||||
return true;
|
||||
}
|
||||
|
||||
// Post-GLU/gated projections (e.g. ffn_down, gated attn_output) have sharp channel outliers
|
||||
// that degrade W8A8 activation quantization; route them to FP16 HMX under MM_SELECT=3.
|
||||
static bool htp_mm_is_post_glu(const struct ggml_tensor * act) {
|
||||
while (act && (act->op == GGML_OP_VIEW || act->op == GGML_OP_RESHAPE || act->op == GGML_OP_CONT || act->op == GGML_OP_CPY)) {
|
||||
act = act->view_src ? act->view_src : act->src[0];
|
||||
}
|
||||
if (!act) {
|
||||
return false;
|
||||
}
|
||||
if (act->op == GGML_OP_GLU) {
|
||||
return true;
|
||||
}
|
||||
if (act->op == GGML_OP_MUL) {
|
||||
const struct ggml_tensor * a0 = act->src[0];
|
||||
const struct ggml_tensor * a1 = act->src[1];
|
||||
if ((a0 && (a0->op == GGML_OP_UNARY || a0->op == GGML_OP_GLU)) ||
|
||||
(a1 && (a1->op == GGML_OP_UNARY || a1->op == GGML_OP_GLU))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool htp_kparams_solve_hmx_mm(
|
||||
const struct ggml_hexagon_session * sess,
|
||||
const struct ggml_tensor * src0,
|
||||
@@ -748,6 +725,7 @@ static bool htp_kparams_solve_hmx_mm(
|
||||
struct htp_mm_kernel_params * kparams,
|
||||
bool is_glu = false
|
||||
) {
|
||||
GGML_UNUSED(act);
|
||||
const bool bias_is_2d = bias && (bias->ne[1] > 1);
|
||||
const bool bias_batched = bias && (bias->ne[2] > 1 || bias->ne[3] > 1);
|
||||
const bool is_tiled = ggml_hexagon_tensor_will_tile(src0);
|
||||
@@ -776,9 +754,7 @@ static bool htp_kparams_solve_hmx_mm(
|
||||
const uint8_t fp16_kernel_type = (is_batched && !is_matmul_id) ? HTP_MM_KERNEL_HMX_BATCHED : HTP_MM_KERNEL_HMX_2D;
|
||||
uint8_t kernel_type = fp16_kernel_type;
|
||||
const uint32_t min_k = htp_int_hmx_min_k((int) wtype);
|
||||
const bool allow_w8a8 = (opt_mm_select >= 4) ||
|
||||
(opt_mm_select == 3 && !htp_mm_is_post_glu(act) &&
|
||||
(!dst || ggml_prec_get_acc(dst) != GGML_PREC_F32));
|
||||
const bool allow_w8a8 = (opt_mm_select >= 3) && (!dst || ggml_prec_get_acc(dst) != GGML_PREC_F32);
|
||||
if (is_tiled && htp_is_int_hmx_weight_type((int) wtype) && allow_w8a8 &&
|
||||
ne00_padded >= (int) min_k && (ne00_padded % min_k) == 0) {
|
||||
kernel_type = (is_batched && !is_matmul_id) ? HTP_MM_KERNEL_HMX_W8A8_BATCHED : HTP_MM_KERNEL_HMX_W8A8_2D;
|
||||
|
||||
@@ -103,7 +103,6 @@ static __attribute__((noinline)) void hmx_fa_w8a8_q_prep_quad_f32(
|
||||
Q6_Vub_vmax_VubVub(Q6_V_vxor_VV(Q6_V_lo_W(w_u8), v_zp_u8), v_min_u8b);
|
||||
}
|
||||
#else
|
||||
const HVX_Vector v_bias_u8 = Q6_V_vsplat_R(0x4B400080); // 12582912.0f + 128.0f
|
||||
const HVX_Vector v_min_u8 = Q6_Vh_vsplat_R(1);
|
||||
const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255);
|
||||
|
||||
@@ -114,10 +113,10 @@ static __attribute__((noinline)) void hmx_fa_w8a8_q_prep_quad_f32(
|
||||
HVX_Vector vx2 = *(const HVX_UVector *) (p2 + off);
|
||||
HVX_Vector vx3 = *(const HVX_UVector *) (p3 + off);
|
||||
|
||||
HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0), v_bias_u8));
|
||||
HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1), v_bias_u8));
|
||||
HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2), v_bias_u8));
|
||||
HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3), v_bias_u8));
|
||||
HVX_Vector y0 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0));
|
||||
HVX_Vector y1 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1));
|
||||
HVX_Vector y2 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2));
|
||||
HVX_Vector y3 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3));
|
||||
|
||||
HVX_Vector vh02 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y2, y0), v_min_u8), v_max_u8);
|
||||
HVX_Vector vh13 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y3, y1), v_min_u8), v_max_u8);
|
||||
@@ -248,7 +247,6 @@ static __attribute__((noinline)) void hmx_fa_w8a8_q_prep_quad_f16(
|
||||
Q6_Vub_vmax_VubVub(Q6_V_vxor_VV(Q6_V_lo_W(w_u8), v_zp_u8), v_min_u8b);
|
||||
}
|
||||
#else
|
||||
const HVX_Vector v_bias_u8 = Q6_V_vsplat_R(0x4B400080);
|
||||
const HVX_Vector v_min_u8 = Q6_Vh_vsplat_R(1);
|
||||
const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255);
|
||||
|
||||
@@ -261,19 +259,19 @@ static __attribute__((noinline)) void hmx_fa_w8a8_q_prep_quad_f16(
|
||||
HVX_VectorPair vp3 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p3 + off)), v_one_f16);
|
||||
|
||||
{
|
||||
HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf), v_bias_u8));
|
||||
HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf), v_bias_u8));
|
||||
HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf), v_bias_u8));
|
||||
HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf), v_bias_u8));
|
||||
HVX_Vector y0 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf));
|
||||
HVX_Vector y1 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf));
|
||||
HVX_Vector y2 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf));
|
||||
HVX_Vector y3 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf));
|
||||
HVX_Vector vh02 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y2, y0), v_min_u8), v_max_u8);
|
||||
HVX_Vector vh13 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y3, y1), v_min_u8), v_max_u8);
|
||||
((HVX_Vector *) (tile_row_base + (size_t) (kt + 0) * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_Vb_vshuffe_VbVb(vh13, vh02);
|
||||
}
|
||||
{
|
||||
HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp0), v_inv0_qf), v_bias_u8));
|
||||
HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp1), v_inv1_qf), v_bias_u8));
|
||||
HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp2), v_inv2_qf), v_bias_u8));
|
||||
HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp3), v_inv3_qf), v_bias_u8));
|
||||
HVX_Vector y0 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp0), v_inv0_qf));
|
||||
HVX_Vector y1 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp1), v_inv1_qf));
|
||||
HVX_Vector y2 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp2), v_inv2_qf));
|
||||
HVX_Vector y3 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp3), v_inv3_qf));
|
||||
HVX_Vector vh02 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y2, y0), v_min_u8), v_max_u8);
|
||||
HVX_Vector vh13 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y3, y1), v_min_u8), v_max_u8);
|
||||
((HVX_Vector *) (tile_row_base + (size_t) (kt + 1) * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_Vb_vshuffe_VbVb(vh13, vh02);
|
||||
@@ -287,10 +285,10 @@ static __attribute__((noinline)) void hmx_fa_w8a8_q_prep_quad_f16(
|
||||
HVX_VectorPair vp2 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p2 + off)), v_one_f16);
|
||||
HVX_VectorPair vp3 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(*(const HVX_UVector *) (p3 + off)), v_one_f16);
|
||||
|
||||
HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf), v_bias_u8));
|
||||
HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf), v_bias_u8));
|
||||
HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf), v_bias_u8));
|
||||
HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf), v_bias_u8));
|
||||
HVX_Vector y0 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf));
|
||||
HVX_Vector y1 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf));
|
||||
HVX_Vector y2 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf));
|
||||
HVX_Vector y3 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf));
|
||||
HVX_Vector vh02 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y2, y0), v_min_u8), v_max_u8);
|
||||
HVX_Vector vh13 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y3, y1), v_min_u8), v_max_u8);
|
||||
((HVX_Vector *) (tile_row_base + (size_t) kt * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_Vb_vshuffe_VbVb(vh13, vh02);
|
||||
@@ -583,7 +581,6 @@ static inline void hmx_fa_w8a8_pack_p_quad_u8_sm(
|
||||
}
|
||||
#else
|
||||
const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f);
|
||||
const HVX_Vector v_bias_zp0 = Q6_V_vsplat_R(0x4B400000); // 12582912.0f
|
||||
const HVX_Vector v_zero = Q6_V_vzero();
|
||||
const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255);
|
||||
|
||||
@@ -593,19 +590,19 @@ static inline void hmx_fa_w8a8_pack_p_quad_u8_sm(
|
||||
HVX_VectorPair vp3 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(hf3), v_one_f16);
|
||||
|
||||
{
|
||||
HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_lo_W(vp0), v_bias_zp0));
|
||||
HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_lo_W(vp1), v_bias_zp0));
|
||||
HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_lo_W(vp2), v_bias_zp0));
|
||||
HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_lo_W(vp3), v_bias_zp0));
|
||||
HVX_Vector y0 = hvx_vec_i32_from_qf32_rnd(Q6_V_lo_W(vp0));
|
||||
HVX_Vector y1 = hvx_vec_i32_from_qf32_rnd(Q6_V_lo_W(vp1));
|
||||
HVX_Vector y2 = hvx_vec_i32_from_qf32_rnd(Q6_V_lo_W(vp2));
|
||||
HVX_Vector y3 = hvx_vec_i32_from_qf32_rnd(Q6_V_lo_W(vp3));
|
||||
HVX_Vector vh02 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y2, y0), v_zero), v_max_u8);
|
||||
HVX_Vector vh13 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y3, y1), v_zero), v_max_u8);
|
||||
((HVX_Vector *) (tile_base + (size_t) (kt + 0) * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_Vb_vshuffe_VbVb(vh13, vh02);
|
||||
}
|
||||
if (write_hi) {
|
||||
HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_hi_W(vp0), v_bias_zp0));
|
||||
HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_hi_W(vp1), v_bias_zp0));
|
||||
HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_hi_W(vp2), v_bias_zp0));
|
||||
HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_V_hi_W(vp3), v_bias_zp0));
|
||||
HVX_Vector y0 = hvx_vec_i32_from_qf32_rnd(Q6_V_hi_W(vp0));
|
||||
HVX_Vector y1 = hvx_vec_i32_from_qf32_rnd(Q6_V_hi_W(vp1));
|
||||
HVX_Vector y2 = hvx_vec_i32_from_qf32_rnd(Q6_V_hi_W(vp2));
|
||||
HVX_Vector y3 = hvx_vec_i32_from_qf32_rnd(Q6_V_hi_W(vp3));
|
||||
HVX_Vector vh02 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y2, y0), v_zero), v_max_u8);
|
||||
HVX_Vector vh13 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vshuffe_VhVh(y3, y1), v_zero), v_max_u8);
|
||||
((HVX_Vector *) (tile_base + (size_t) (kt + 1) * HMX_W8A8_ACT_TILE_SIZE))[rg] = Q6_Vb_vshuffe_VbVb(vh13, vh02);
|
||||
@@ -664,7 +661,6 @@ static __attribute__((noinline)) void hmx_fa_w8a8_v_prep_tile(
|
||||
|
||||
// Pass 2: 4-row vshuff interleave + per-KV-row int8 scale multiply -> S8 weight.b
|
||||
const HVX_Vector v_one_f16 = hvx_vec_splat_f16(1.0f);
|
||||
const HVX_Vector v12M_sf = Q6_V_vsplat_R(0x4B400000);
|
||||
const HVX_Vector v_ones_s8 = Q6_Vb_vsplat_R(1);
|
||||
HVX_Vector v_l1_w = Q6_V_vzero();
|
||||
|
||||
@@ -673,7 +669,7 @@ static __attribute__((noinline)) void hmx_fa_w8a8_v_prep_tile(
|
||||
HVX_Vector * tile_dst = tile_dst_all + kt * 8;
|
||||
|
||||
HVX_Vector v_sc_qf = Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(tile_dst[7]), v_one_f16));
|
||||
HVX_Vector v_m_biased = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(v_sc_qf, v_inv127_qf), v12M_sf));
|
||||
HVX_Vector v_m_biased = hvx_vec_i32_from_qf32_rnd(Q6_Vqf32_vmpy_Vqf32Vqf32(v_sc_qf, v_inv127_qf));
|
||||
HVX_Vector v_m_h = Q6_Vh_vpacke_VwVw(v_m_biased, v_m_biased);
|
||||
HVX_Vector v_m_b = Q6_Vb_vpacke_VhVh(v_m_h, v_m_h);
|
||||
|
||||
|
||||
@@ -26,6 +26,11 @@ static inline HVX_Vector hvx_qf32_mul_sf_scalar(HVX_Vector v_sf, uint32_t scalar
|
||||
#endif
|
||||
}
|
||||
|
||||
static inline HVX_Vector hmx_qf32_to_i32_zp128(HVX_Vector v_qf) {
|
||||
const HVX_Vector v_128p5 = Q6_V_vsplat_R(0x43008000);
|
||||
return Q6_Vw_equals_Vsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(v_qf, v_128p5)));
|
||||
}
|
||||
|
||||
static inline void emit_int_hmx_scales_and_bias(
|
||||
HVX_Vector v_max_sf,
|
||||
float scale_const,
|
||||
@@ -35,9 +40,11 @@ static inline void emit_int_hmx_scales_and_bias(
|
||||
HVX_Vector * restrict bias_out) {
|
||||
|
||||
// |sum_k (a - zp) * w_hat| < 128 * l1_w = (l1_w << 7) <= 32768 * 2^p
|
||||
// Add half-ULP (2^(p-1) for p > 0) so truncating the low p bits rounds to nearest instead of biasing negative.
|
||||
HVX_Vector v_max_mag = Q6_Vw_vasl_VwR(v_l1_w, 7);
|
||||
HVX_Vector v_p = Q6_Vw_vmax_VwVw(Q6_V_vzero(), Q6_Vw_vsub_VwVw(Q6_V_vsplat_R(17), Q6_Vuw_vcl0_Vuw(v_max_mag)));
|
||||
HVX_Vector v_ib = Q6_Vw_vsub_VwVw(Q6_Vw_vasl_VwVw(Q6_V_vsplat_R(32768), v_p), Q6_Vw_vasl_VwR(v_sum_w, 7));
|
||||
HVX_Vector v_rnd = Q6_Vw_vasr_VwR(Q6_Vw_vasl_VwVw(Q6_V_vsplat_R(1), v_p), 1);
|
||||
HVX_Vector v_ib = Q6_Vw_vsub_VwVw(Q6_Vw_vadd_VwVw(Q6_Vw_vasl_VwVw(Q6_V_vsplat_R(32768), v_p), v_rnd), Q6_Vw_vasl_VwR(v_sum_w, 7));
|
||||
|
||||
HVX_Vector v_dw_base = hvx_vec_mul_f32_f32(v_max_sf, hvx_vec_splat_f32(scale_const));
|
||||
HVX_Vector v_pow2_sf = Q6_Vsf_equals_Vw(Q6_Vw_vasl_VwVw(Q6_V_vsplat_R(1), v_p));
|
||||
@@ -59,9 +66,11 @@ static inline void emit_int_hmx_scales_and_bias_zp0(
|
||||
HVX_Vector * restrict bias_out) {
|
||||
|
||||
// Unsigned a_u8 in [0, 255] (zp = 0): |sum_k a_u8 * w_hat| <= 255 * l1_w < (l1_w << 8) <= 32768 * 2^p
|
||||
// Add half-ULP (2^(p-1) for p > 0) so truncating the low p bits rounds to nearest instead of biasing negative.
|
||||
HVX_Vector v_max_mag = Q6_Vw_vasl_VwR(v_l1_w, 8);
|
||||
HVX_Vector v_p = Q6_Vw_vmax_VwVw(Q6_V_vzero(), Q6_Vw_vsub_VwVw(Q6_V_vsplat_R(17), Q6_Vuw_vcl0_Vuw(v_max_mag)));
|
||||
HVX_Vector v_ib = Q6_Vw_vasl_VwVw(Q6_V_vsplat_R(32768), v_p);
|
||||
HVX_Vector v_rnd = Q6_Vw_vasr_VwR(Q6_Vw_vasl_VwVw(Q6_V_vsplat_R(1), v_p), 1);
|
||||
HVX_Vector v_ib = Q6_Vw_vadd_VwVw(Q6_Vw_vasl_VwVw(Q6_V_vsplat_R(32768), v_p), v_rnd);
|
||||
|
||||
HVX_Vector v_dw_base = hvx_vec_mul_f32_f32(v_max_sf, hvx_vec_splat_f32(scale_const));
|
||||
HVX_Vector v_pow2_sf = Q6_Vsf_equals_Vw(Q6_Vw_vasl_VwVw(Q6_V_vsplat_R(1), v_p));
|
||||
@@ -97,8 +106,7 @@ static inline void int_hmx_inv127_from_max_f16(
|
||||
}
|
||||
|
||||
static inline HVX_Vector int_hmx_m_b4_from_sc_qf(HVX_Vector v_sc_qf, HVX_Vector v_inv127_qf) {
|
||||
const HVX_Vector v12M_sf = Q6_V_vsplat_R(0x4B400000);
|
||||
HVX_Vector v_m_biased = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(v_sc_qf, v_inv127_qf), v12M_sf));
|
||||
HVX_Vector v_m_biased = hvx_vec_i32_from_qf32_rnd(Q6_Vqf32_vmpy_Vqf32Vqf32(v_sc_qf, v_inv127_qf));
|
||||
HVX_Vector v_m_h = Q6_Vh_vpacke_VwVw(v_m_biased, v_m_biased);
|
||||
return Q6_Vh_vshuff_Vh(Q6_Vb_vshuff_Vb(Q6_Vb_vpacke_VhVh(v_m_h, v_m_h)));
|
||||
}
|
||||
|
||||
@@ -625,9 +625,8 @@ static inline void int_hmx_asym_alpha_beta_wb(
|
||||
HVX_Vector * restrict v_alpha_h_out,
|
||||
HVX_Vector * restrict v_beta_h_out) {
|
||||
|
||||
const HVX_Vector v12M_sf = Q6_V_vsplat_R(0x4B400000);
|
||||
HVX_Vector v_a_bias = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(vd_qf, v_scale_q6_qf), v12M_sf));
|
||||
HVX_Vector v_b_bias = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(vm_qf, v_scale_q6_qf), v12M_sf));
|
||||
HVX_Vector v_a_bias = hvx_vec_i32_from_qf32_rnd(Q6_Vqf32_vmpy_Vqf32Vqf32(vd_qf, v_scale_q6_qf));
|
||||
HVX_Vector v_b_bias = hvx_vec_i32_from_qf32_rnd(Q6_Vqf32_vmpy_Vqf32Vqf32(vm_qf, v_scale_q6_qf));
|
||||
*v_alpha_h_out = Q6_Vh_vshuffe_VhVh(v_a_bias, v_a_bias);
|
||||
*v_beta_h_out = Q6_Vh_vshuffe_VhVh(v_b_bias, v_b_bias);
|
||||
}
|
||||
@@ -709,7 +708,6 @@ static inline void rescale_iq2_xxs_weight_superblock_impl(
|
||||
const HVX_Vector v_abs_mask_sf = Q6_V_vsplat_R(0x7fffffff);
|
||||
const HVX_Vector v_one_w = Q6_V_vsplat_R(1);
|
||||
const HVX_Vector v_one_s8 = Q6_Vb_vsplat_R(1);
|
||||
const HVX_Vector v12M_sf = Q6_V_vsplat_R(0x4B400000);
|
||||
const HVX_Vector v_nib_lut = hvx_vmem(iq2xxs_vtcm_lut);
|
||||
|
||||
HVX_Vector v_max_sf = Q6_V_vzero();
|
||||
@@ -757,7 +755,7 @@ static inline void rescale_iq2_xxs_weight_superblock_impl(
|
||||
|
||||
HVX_Vector v_ls = Q6_Vw_vadd_VwVw(Q6_Vw_vasl_VwR(Q6_Vuw_vlsr_VuwR(v_sgn_cur, IQ2XXS_SCALE_SHIFT), 1), v_one_w);
|
||||
HVX_Vector v_ls_qf = hvx_vec_f32_to_qf32(Q6_Vsf_equals_Vw(v_ls));
|
||||
HVX_Vector v_m_bias = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(v_d_sc_qf, v_ls_qf), v12M_sf));
|
||||
HVX_Vector v_m_bias = hvx_vec_i32_from_qf32_rnd(Q6_Vqf32_vmpy_Vqf32Vqf32(v_d_sc_qf, v_ls_qf));
|
||||
HVX_Vector v_alpha_h = Q6_Vh_vshuffe_VhVh(v_m_bias, v_m_bias);
|
||||
|
||||
#pragma clang loop pipeline(disable) unroll(disable)
|
||||
@@ -1053,12 +1051,10 @@ static inline void quantize_f16_quad_step_to_u8_sm(
|
||||
HVX_Vector v_inv2_qf,
|
||||
HVX_Vector v_inv3_qf,
|
||||
HVX_Vector v_one_f16,
|
||||
HVX_Vector v_bias_u8,
|
||||
HVX_Vector v_min_u8,
|
||||
HVX_Vector v_max_u8) {
|
||||
|
||||
#if __HVX_ARCH__ >= 81
|
||||
(void) v_bias_u8;
|
||||
(void) v_min_u8;
|
||||
(void) v_max_u8;
|
||||
|
||||
@@ -1088,19 +1084,19 @@ static inline void quantize_f16_quad_step_to_u8_sm(
|
||||
HVX_VectorPair vp3 = Q6_Wqf32_vmpy_VhfVhf(Q6_Vh_vshuff_Vh(vh3), v_one_f16);
|
||||
|
||||
{
|
||||
HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf), v_bias_u8));
|
||||
HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf), v_bias_u8));
|
||||
HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf), v_bias_u8));
|
||||
HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf), v_bias_u8));
|
||||
HVX_Vector y0 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp0), v_inv0_qf));
|
||||
HVX_Vector y1 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp1), v_inv1_qf));
|
||||
HVX_Vector y2 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp2), v_inv2_qf));
|
||||
HVX_Vector y3 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_lo_W(vp3), v_inv3_qf));
|
||||
HVX_Vector vh01 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y1, y0), v_min_u8), v_max_u8);
|
||||
HVX_Vector vh23 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y3, y2), v_min_u8), v_max_u8);
|
||||
((HVX_Vector *) (tile_row_base + (size_t) (kt + 0) * HTP_MM_HMX_TILE_SIZE))[rg] = Q6_Vb_vpacke_VhVh(vh23, vh01);
|
||||
}
|
||||
{
|
||||
HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp0), v_inv0_qf), v_bias_u8));
|
||||
HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp1), v_inv1_qf), v_bias_u8));
|
||||
HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp2), v_inv2_qf), v_bias_u8));
|
||||
HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp3), v_inv3_qf), v_bias_u8));
|
||||
HVX_Vector y0 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp0), v_inv0_qf));
|
||||
HVX_Vector y1 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp1), v_inv1_qf));
|
||||
HVX_Vector y2 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp2), v_inv2_qf));
|
||||
HVX_Vector y3 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_Vqf32Vqf32(Q6_V_hi_W(vp3), v_inv3_qf));
|
||||
HVX_Vector vh01 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y1, y0), v_min_u8), v_max_u8);
|
||||
HVX_Vector vh23 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y3, y2), v_min_u8), v_max_u8);
|
||||
((HVX_Vector *) (tile_row_base + (size_t) (kt + 1) * HTP_MM_HMX_TILE_SIZE))[rg] = Q6_Vb_vpacke_VhVh(vh23, vh01);
|
||||
@@ -1189,7 +1185,6 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f32_to_u8_sm_
|
||||
hmx_pack_hf_quad_to_u8_cm_pair(tile_dst_base, step * 2, rg, hf0, hf1, hf2, hf3);
|
||||
}
|
||||
#else
|
||||
const HVX_Vector v_bias_u8 = Q6_V_vsplat_R(0x4B400080); // 12582912.0f + 128.0f
|
||||
const HVX_Vector v_min_u8 = Q6_Vh_vsplat_R(1);
|
||||
const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255);
|
||||
|
||||
@@ -1200,10 +1195,10 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f32_to_u8_sm_
|
||||
HVX_Vector vx2 = hvx_vmem(p2_base + off);
|
||||
HVX_Vector vx3 = hvx_vmem(p3_base + off);
|
||||
|
||||
HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0), v_bias_u8));
|
||||
HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1), v_bias_u8));
|
||||
HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2), v_bias_u8));
|
||||
HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3), v_bias_u8));
|
||||
HVX_Vector y0 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0));
|
||||
HVX_Vector y1 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1));
|
||||
HVX_Vector y2 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2));
|
||||
HVX_Vector y3 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3));
|
||||
|
||||
HVX_Vector vh01 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y1, y0), v_min_u8), v_max_u8);
|
||||
HVX_Vector vh23 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y3, y2), v_min_u8), v_max_u8);
|
||||
@@ -1288,7 +1283,6 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f32_to_u8_sm(
|
||||
HVX_Vector v_inv2 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax2, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax2), v_127), Q6_V_vzero());
|
||||
HVX_Vector v_inv3 = Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax3, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax3), v_127), Q6_V_vzero());
|
||||
|
||||
const HVX_Vector v_bias_u8 = Q6_V_vsplat_R(0x4B400080); // 12582912.0f + 128.0f
|
||||
const HVX_Vector v_min_u8 = Q6_Vh_vsplat_R(1);
|
||||
const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255);
|
||||
|
||||
@@ -1298,10 +1292,10 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f32_to_u8_sm(
|
||||
HVX_Vector vx2 = hvx_vmem(p2 + c);
|
||||
HVX_Vector vx3 = hvx_vmem(p3 + c);
|
||||
|
||||
HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0), v_bias_u8));
|
||||
HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1), v_bias_u8));
|
||||
HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2), v_bias_u8));
|
||||
HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3), v_bias_u8));
|
||||
HVX_Vector y0 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0));
|
||||
HVX_Vector y1 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1));
|
||||
HVX_Vector y2 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2));
|
||||
HVX_Vector y3 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3));
|
||||
|
||||
HVX_Vector vh01 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y1, y0), v_min_u8), v_max_u8);
|
||||
HVX_Vector vh23 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y3, y2), v_min_u8), v_max_u8);
|
||||
@@ -1323,10 +1317,10 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f32_to_u8_sm(
|
||||
vx2 = Q6_V_vmux_QVV(mask, hvx_vmem(p2 + c), Q6_V_vzero());
|
||||
vx3 = Q6_V_vmux_QVV(mask, hvx_vmem(p3 + c), Q6_V_vzero());
|
||||
}
|
||||
HVX_Vector y0 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0), v_bias_u8));
|
||||
HVX_Vector y1 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1), v_bias_u8));
|
||||
HVX_Vector y2 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2), v_bias_u8));
|
||||
HVX_Vector y3 = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3), v_bias_u8));
|
||||
HVX_Vector y0 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx0, v_inv0));
|
||||
HVX_Vector y1 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx1, v_inv1));
|
||||
HVX_Vector y2 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx2, v_inv2));
|
||||
HVX_Vector y3 = hmx_qf32_to_i32_zp128(Q6_Vqf32_vmpy_VsfVsf(vx3, v_inv3));
|
||||
|
||||
HVX_Vector vh01 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y1, y0), v_min_u8), v_max_u8);
|
||||
HVX_Vector vh23 = Q6_Vh_vmin_VhVh(Q6_Vh_vmax_VhVh(Q6_Vh_vpacke_VwVw(y3, y2), v_min_u8), v_max_u8);
|
||||
@@ -1406,7 +1400,6 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f16_to_u8_sm_
|
||||
HVX_Vector v_inv2_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax2, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax2), v_127), Q6_V_vzero()));
|
||||
HVX_Vector v_inv3_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax3, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax3), v_127), Q6_V_vzero()));
|
||||
|
||||
const HVX_Vector v_bias_u8 = Q6_V_vsplat_R(0x4B400080);
|
||||
const HVX_Vector v_min_u8 = Q6_Vh_vsplat_R(1);
|
||||
const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255);
|
||||
|
||||
@@ -1418,7 +1411,7 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f16_to_u8_sm_
|
||||
HVX_Vector vh3 = hvx_vmem(p3_base + off);
|
||||
quantize_f16_quad_step_to_u8_sm(tile_dst_base, step * 2, rg, vh0, vh1, vh2, vh3,
|
||||
v_inv0_qf, v_inv1_qf, v_inv2_qf, v_inv3_qf,
|
||||
v_one_f16, v_bias_u8, v_min_u8, v_max_u8);
|
||||
v_one_f16, v_min_u8, v_max_u8);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1503,7 +1496,6 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f16_to_u8_sm(
|
||||
HVX_Vector v_inv2_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax2, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax2), v_127), Q6_V_vzero()));
|
||||
HVX_Vector v_inv3_qf = hvx_vec_f32_to_qf32(Q6_V_vmux_QVV(Q6_Q_vcmp_gt_VsfVsf(vmax3, v_eps), hvx_vec_mul_f32_f32(hvx_vec_inverse_f32(vmax3), v_127), Q6_V_vzero()));
|
||||
|
||||
const HVX_Vector v_bias_u8 = Q6_V_vsplat_R(0x4B400080);
|
||||
const HVX_Vector v_min_u8 = Q6_Vh_vsplat_R(1);
|
||||
const HVX_Vector v_max_u8 = Q6_Vh_vsplat_R(255);
|
||||
|
||||
@@ -1512,7 +1504,7 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f16_to_u8_sm(
|
||||
HVX_Vector vh1 = hvx_vmem(p1 + c);
|
||||
HVX_Vector vh2 = hvx_vmem(p2 + c);
|
||||
HVX_Vector vh3 = hvx_vmem(p3 + c);
|
||||
quantize_f16_quad_step_to_u8_sm(tile_row_base, c >> 5, rg, vh0, vh1, vh2, vh3, v_inv0_qf, v_inv1_qf, v_inv2_qf, v_inv3_qf, v_one_f16, v_bias_u8, v_min_u8, v_max_u8);
|
||||
quantize_f16_quad_step_to_u8_sm(tile_row_base, c >> 5, rg, vh0, vh1, vh2, vh3, v_inv0_qf, v_inv1_qf, v_inv2_qf, v_inv3_qf, v_one_f16, v_min_u8, v_max_u8);
|
||||
}
|
||||
for (uint32_t c = c_end_full; c < k_end; c += 64) {
|
||||
HVX_Vector vh0 = Q6_V_vzero();
|
||||
@@ -1527,7 +1519,7 @@ static __attribute__((noinline)) void quantize_act_superblock_quad_f16_to_u8_sm(
|
||||
vh2 = Q6_V_vmux_QVV(mask, hvx_vmem(p2 + c), Q6_V_vzero());
|
||||
vh3 = Q6_V_vmux_QVV(mask, hvx_vmem(p3 + c), Q6_V_vzero());
|
||||
}
|
||||
quantize_f16_quad_step_to_u8_sm(tile_row_base, c >> 5, rg, vh0, vh1, vh2, vh3, v_inv0_qf, v_inv1_qf, v_inv2_qf, v_inv3_qf, v_one_f16, v_bias_u8, v_min_u8, v_max_u8);
|
||||
quantize_f16_quad_step_to_u8_sm(tile_row_base, c >> 5, rg, vh0, vh1, vh2, vh3, v_inv0_qf, v_inv1_qf, v_inv2_qf, v_inv3_qf, v_one_f16, v_min_u8, v_max_u8);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -218,6 +218,19 @@ static inline HVX_Vector hvx_vec_i16_from_hf_rnd_sat(HVX_Vector vin) {
|
||||
#endif
|
||||
}
|
||||
|
||||
static inline HVX_Vector hvx_vec_i32_from_qf32_rnd(HVX_Vector v_qf) {
|
||||
#if __HVX_ARCH__ >= 79
|
||||
HVX_Vector v_sf = Q6_Vsf_equals_Vqf32(v_qf);
|
||||
const HVX_Vector v_half = Q6_V_vor_VV(Q6_V_vsplat_R(0x3F000000),
|
||||
Q6_V_vand_VV(v_sf, Q6_V_vsplat_R(0x80000000)));
|
||||
return Q6_Vw_equals_Vsf(Q6_Vsf_vadd_VsfVsf(v_sf, v_half));
|
||||
#else
|
||||
const HVX_Vector v_half = Q6_V_vor_VV(Q6_V_vsplat_R(0x3F000000),
|
||||
Q6_V_vand_VV(v_qf, Q6_V_vsplat_R(0x80000000)));
|
||||
return Q6_Vw_equals_Vsf(Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vsf(v_qf, v_half)));
|
||||
#endif
|
||||
}
|
||||
|
||||
#if __HVX_ARCH__ < 79
|
||||
|
||||
static inline HVX_VectorPair hvx_vec_mpy_f32_f16(HVX_Vector x, HVX_Vector y)
|
||||
|
||||
@@ -236,8 +236,13 @@ static int ggml_metal_op_encode_impl(ggml_metal_op_t ctx, int idx) {
|
||||
int n_fuse = 1;
|
||||
const ggml_metal_fusion * fusion = ctx->can_fuse(idx, GGML_METAL_FUSION_FULL, &n_fuse);
|
||||
if (fusion) {
|
||||
// fused kernels write to the last node of the group, not necessarily to the first node's dst
|
||||
is_concurrent = ggml_mem_ranges_check(ctx->mem_ranges, ctx->node(idx + n_fuse - 1));
|
||||
// every node of the group contributes sources and destinations, check all of them
|
||||
for (int j = 0; j < n_fuse; ++j) {
|
||||
if (!ggml_mem_ranges_check(ctx->mem_ranges, ctx->node(idx + j))) {
|
||||
is_concurrent = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ bool ggml_vk_intel_windows_driver_in_range(uint32_t driver_version, uint32_t low
|
||||
// shaders
|
||||
void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline);
|
||||
vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, ggml_type k_type, ggml_type v_type, bool f32acc, uint32_t qk_ratio, bool allow_flip = true);
|
||||
vk_fa_pipeline_state get_fa_pipeline_state(const vk_device& device, const vk_fa_tuning_params& params, uint32_t hsk, uint32_t hsv, bool aligned, bool f32acc, bool use_mask, bool use_mask_opt, bool use_logit_softcap, bool use_sparse, ggml_type k_type, ggml_type v_type);
|
||||
vk_fa_pipeline_state get_fa_pipeline_state(const vk_device& device, const vk_fa_tuning_params& params, uint32_t hsk, uint32_t hsv, bool aligned, bool f32acc, bool use_mask, bool use_mask_opt, bool use_logit_softcap, bool use_sparse, ggml_type k_type, ggml_type v_type, uint32_t bias_bins);
|
||||
uint32_t get_subgroup_size(const std::string &pipeline_name, const vk_device_architecture &arch);
|
||||
void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested = nullptr);
|
||||
bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const vk_fa_tuning_params& params, uint32_t hsk, uint32_t hsv, bool f32acc, ggml_type k_type, ggml_type v_type);
|
||||
|
||||
@@ -450,10 +450,11 @@ struct vk_fa_pipeline_state {
|
||||
uint32_t limit_occupancy_shmem;
|
||||
ggml_type k_type;
|
||||
ggml_type v_type;
|
||||
uint32_t bias_bins;
|
||||
|
||||
bool operator<(const vk_fa_pipeline_state &b) const {
|
||||
return std::tie(HSK, HSV, Br, Bc, D_split, row_split, shmem_staging, path, workgroup_size, subgroup_size, aligned, f32acc, flags, limit_occupancy_shmem, k_type, v_type) <
|
||||
std::tie(b.HSK, b.HSV, b.Br, b.Bc, b.D_split, b.row_split, b.shmem_staging, b.path, b.workgroup_size, b.subgroup_size, b.aligned, b.f32acc, b.flags, b.limit_occupancy_shmem, b.k_type, b.v_type);
|
||||
return std::tie(HSK, HSV, Br, Bc, D_split, row_split, shmem_staging, path, workgroup_size, subgroup_size, aligned, f32acc, flags, limit_occupancy_shmem, k_type, v_type, bias_bins) <
|
||||
std::tie(b.HSK, b.HSV, b.Br, b.Bc, b.D_split, b.row_split, b.shmem_staging, b.path, b.workgroup_size, b.subgroup_size, b.aligned, b.f32acc, b.flags, b.limit_occupancy_shmem, b.k_type, b.v_type, b.bias_bins);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -465,10 +466,11 @@ struct vk_xe_fa_pipeline_state {
|
||||
bool unaligned_q;
|
||||
bool partial_row_mask;
|
||||
bool multi_head_mask;
|
||||
uint32_t bias_bins;
|
||||
|
||||
bool operator<(const vk_xe_fa_pipeline_state &b) const {
|
||||
return std::tie(HSK, HSV, qk_ratio, pv_ratio, decode_n, unaligned_seq_len, unaligned_q, partial_row_mask, multi_head_mask) <
|
||||
std::tie(b.HSK, b.HSV, b.qk_ratio, b.pv_ratio, b.decode_n, b.unaligned_seq_len, b.unaligned_q, b.partial_row_mask, b.multi_head_mask);
|
||||
return std::tie(HSK, HSV, qk_ratio, pv_ratio, decode_n, unaligned_seq_len, unaligned_q, partial_row_mask, multi_head_mask, bias_bins) <
|
||||
std::tie(b.HSK, b.HSV, b.qk_ratio, b.pv_ratio, b.decode_n, b.unaligned_seq_len, b.unaligned_q, b.partial_row_mask, b.multi_head_mask, b.bias_bins);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -810,6 +812,7 @@ struct vk_device_struct {
|
||||
bool coopmat2_bf16_support {};
|
||||
bool coopmat2_gdn_support {};
|
||||
bool coopmat2_decode_vector;
|
||||
uint32_t coopmat2_reserved_shmem {};
|
||||
|
||||
bool dot2_f16 {};
|
||||
bool ocp_fp4 {};
|
||||
|
||||
@@ -1446,8 +1446,12 @@ vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk,
|
||||
}
|
||||
}
|
||||
|
||||
// cm2 only: selects the flash_attn_cm2 SPIR-V built with FA_BIAS_STAGE
|
||||
static constexpr uint32_t FA_FLAG_BIAS_STAGE = 256;
|
||||
|
||||
vk_fa_pipeline_state get_fa_pipeline_state(const vk_device& device, const vk_fa_tuning_params& params, uint32_t hsk, uint32_t hsv, bool aligned, bool f32acc,
|
||||
bool use_mask, bool use_mask_opt, bool use_logit_softcap, bool use_sparse, ggml_type k_type, ggml_type v_type) {
|
||||
bool use_mask, bool use_mask_opt, bool use_logit_softcap, bool use_sparse, ggml_type k_type, ggml_type v_type,
|
||||
uint32_t bias_bins) {
|
||||
const bool old_amd_windows = device->vendor_id == VK_VENDOR_ID_AMD && device->driver_id == vk::DriverId::eAmdProprietary &&
|
||||
(device->architecture == AMD_GCN || device->architecture == AMD_RDNA1 || device->architecture == AMD_RDNA2);
|
||||
|
||||
@@ -1462,7 +1466,7 @@ vk_fa_pipeline_state get_fa_pipeline_state(const vk_device& device, const vk_fa_
|
||||
|
||||
const uint32_t subgroup_size = params.disable_subgroups ? 0 : params.subgroup_size;
|
||||
|
||||
return vk_fa_pipeline_state{hsk, hsv, params.block_rows, params.block_cols, params.d_split, params.row_split, params.shmem_staging, params.path, params.workgroup_size, subgroup_size, aligned, f32acc, flags, params.limit_occupancy_shmem, k_type, v_type};
|
||||
return vk_fa_pipeline_state{hsk, hsv, params.block_rows, params.block_cols, params.d_split, params.row_split, params.shmem_staging, params.path, params.workgroup_size, subgroup_size, aligned, f32acc, flags, params.limit_occupancy_shmem, k_type, v_type, bias_bins};
|
||||
}
|
||||
|
||||
static uint32_t fa_block_bytes(ggml_type t) {
|
||||
@@ -1490,6 +1494,7 @@ static std::vector<uint32_t> get_fa_spec_constants(const vk_fa_pipeline_state& s
|
||||
/*13 FaTypeV */ static_cast<uint32_t>(state.v_type),
|
||||
/*14 FaBlockBytesK */ fa_block_bytes(state.k_type),
|
||||
/*15 FaBlockBytesV */ fa_block_bytes(state.v_type),
|
||||
/*16 BiasBins */ state.bias_bins,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2371,7 +2376,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
}
|
||||
name = aligned ? "flash_attn_f32_f16_aligned" : "flash_attn_f32_f16";
|
||||
}
|
||||
ggml_vk_create_pipeline(device, fa.second, name, spv_size, spv_data, "main", 8,
|
||||
ggml_vk_create_pipeline(device, fa.second, name, spv_size, spv_data, "main", 10,
|
||||
sizeof(vk_flash_attn_push_constants), {Br, 1, 1},
|
||||
get_fa_spec_constants(fa.first), aligned ? Bc : 1, true,
|
||||
!fa_ds, !fa_ds ? fa_sgs : 0);
|
||||
@@ -2418,7 +2423,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
else { spv_data = flash_attn_f32_f16_f16acc_cm1_data; spv_size = flash_attn_f32_f16_f16acc_cm1_len; }
|
||||
name = aligned ? "flash_attn_f32_f16_aligned_cm1" : "flash_attn_f32_f16_cm1";
|
||||
}
|
||||
ggml_vk_create_pipeline(device, fa.second, name, spv_size, spv_data, "main", 8,
|
||||
ggml_vk_create_pipeline(device, fa.second, name, spv_size, spv_data, "main", 10,
|
||||
sizeof(vk_flash_attn_push_constants), {Br, 1, 1},
|
||||
get_fa_spec_constants(fa.first), aligned ? Bc : 1, true,
|
||||
!fa_ds, !fa_ds ? fa_sgs : 0);
|
||||
@@ -2436,18 +2441,23 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
const bool f32acc = fa.first.f32acc;
|
||||
|
||||
const bool bf16_kv = fa.first.k_type == GGML_TYPE_BF16;
|
||||
const bool bias_stage = (fa.first.flags & FA_FLAG_BIAS_STAGE) != 0;
|
||||
const void * spv_data;
|
||||
size_t spv_size;
|
||||
const char * name;
|
||||
if (bf16_kv) {
|
||||
#if defined(VK_KHR_shader_bfloat16) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT)
|
||||
if (!device->coopmat2_bf16_support) continue;
|
||||
spv_data = flash_attn_f32_f16_bf16_cm2_data;
|
||||
spv_size = flash_attn_f32_f16_bf16_cm2_len;
|
||||
name = aligned ? "flash_attn_f32_bf16_aligned_cm2" : "flash_attn_f32_bf16_cm2";
|
||||
spv_data = bias_stage ? flash_attn_f32_f16_bf16_cm2_bias_data : flash_attn_f32_f16_bf16_cm2_data;
|
||||
spv_size = bias_stage ? flash_attn_f32_f16_bf16_cm2_bias_len : flash_attn_f32_f16_bf16_cm2_len;
|
||||
name = bias_stage ? (aligned ? "flash_attn_f32_bf16_aligned_cm2_bias" : "flash_attn_f32_bf16_cm2_bias") :
|
||||
(aligned ? "flash_attn_f32_bf16_aligned_cm2" : "flash_attn_f32_bf16_cm2");
|
||||
#else
|
||||
continue;
|
||||
#endif
|
||||
} else if (bias_stage) {
|
||||
if (f32acc) { spv_data = flash_attn_f32_f16_cm2_bias_data; spv_size = flash_attn_f32_f16_cm2_bias_len; name = aligned ? "flash_attn_f32_f16_aligned_f32acc_cm2_bias" : "flash_attn_f32_f16_f32acc_cm2_bias"; }
|
||||
else { spv_data = flash_attn_f32_f16_f16acc_cm2_bias_data; spv_size = flash_attn_f32_f16_f16acc_cm2_bias_len; name = aligned ? "flash_attn_f32_f16_aligned_f16acc_cm2_bias" : "flash_attn_f32_f16_f16acc_cm2_bias"; }
|
||||
} else if (aligned) {
|
||||
if (f32acc) { spv_data = flash_attn_f32_f16_cm2_data; spv_size = flash_attn_f32_f16_cm2_len; name = "flash_attn_f32_f16_aligned_f32acc_cm2"; }
|
||||
else { spv_data = flash_attn_f32_f16_f16acc_cm2_data; spv_size = flash_attn_f32_f16_f16acc_cm2_len; name = "flash_attn_f32_f16_aligned_f16acc_cm2"; }
|
||||
@@ -2455,7 +2465,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
if (f32acc) { spv_data = flash_attn_f32_f16_cm2_data; spv_size = flash_attn_f32_f16_cm2_len; name = "flash_attn_f32_f16_f32acc_cm2"; }
|
||||
else { spv_data = flash_attn_f32_f16_f16acc_cm2_data; spv_size = flash_attn_f32_f16_f16acc_cm2_len; name = "flash_attn_f32_f16_f16acc_cm2"; }
|
||||
}
|
||||
ggml_vk_create_pipeline(device, fa.second, name, spv_size, spv_data, "main", 8,
|
||||
ggml_vk_create_pipeline(device, fa.second, name, spv_size, spv_data, "main", 10,
|
||||
sizeof(vk_flash_attn_push_constants), {Br, 1, 1},
|
||||
get_fa_spec_constants(fa.first), aligned ? Bc : 1, true, false, 0);
|
||||
}
|
||||
@@ -3616,12 +3626,12 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
std::vector<uint32_t> sc_ph1 = { xe_fa_params.workgroup_size[0], pipeline_state.qk_ratio, pipeline_state.HSK,
|
||||
xe_fa_params.subgroup_size[0], xe_fa_params.decode_params.p_chunk_ph1,
|
||||
xe_fa_params.decode_params.out_per_wg_ph1, xe_fa_params.decode_params.p_chunk_ph1 / xe_fa_params.tm,
|
||||
xe_fa_params.tm, xe_fa_params.tn, shmem_sz };
|
||||
xe_fa_params.tm, xe_fa_params.tn, shmem_sz, pipeline_state.bias_bins };
|
||||
std::vector<uint32_t> sc_ph2 = { xe_fa_params.workgroup_size[1], pipeline_state.pv_ratio, pipeline_state.HSV,
|
||||
xe_fa_params.decode_params.out_row_per_wg_ph2, xe_fa_params.subgroup_size[1], xe_fa_params.decode_params.split_p_per_iter_ph2,
|
||||
xe_fa_params.decode_params.p_chunk_ph1, xe_fa_params.decode_params.out_col_per_wg_ph2,
|
||||
xe_fa_params.tm, xe_fa_params.tn, xe_fa_params.decode_params.pipeline_flag_ph2 };
|
||||
ggml_vk_create_pipeline(device, pipelines.first, "xe_fa_decode_ph1", fa_decode_ph1_cm1_len, fa_decode_ph1_cm1_data, "main", 5, sizeof(vk_xe_fa_push_constants), { 1, xe_fa_params.decode_params.p_chunk_ph1, 1 }, sc_ph1, 1, false, true, xe_fa_params.subgroup_size[0]);
|
||||
ggml_vk_create_pipeline(device, pipelines.first, "xe_fa_decode_ph1", fa_decode_ph1_cm1_len, fa_decode_ph1_cm1_data, "main", 7, sizeof(vk_xe_fa_push_constants), { 1, xe_fa_params.decode_params.p_chunk_ph1, 1 }, sc_ph1, 1, false, true, xe_fa_params.subgroup_size[0]);
|
||||
ggml_vk_create_pipeline(device, pipelines.second, "xe_fa_decode_ph2", fa_decode_ph2_cm1_len, fa_decode_ph2_cm1_data, "main", 5, sizeof(vk_xe_fa_push_constants), { 1, 1, 1 }, sc_ph2, 1, false, true, xe_fa_params.subgroup_size[0]);
|
||||
}
|
||||
|
||||
@@ -3633,8 +3643,9 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
std::vector<uint32_t> sc = { xe_fa_params.workgroup_size[0], xe_fa_params.prefill_params.wg_row, xe_fa_params.prefill_params.sg_col,
|
||||
pipeline_state.HSK, pipeline_state.HSV, pipeline_state.qk_ratio, xe_fa_params.prefill_params.p_per_iter,
|
||||
xe_fa_params.tm, xe_fa_params.tn, xe_fa_params.prefill_params.q_in_reg, shmem_sz, xe_fa_params.prefill_params.acc_count,
|
||||
xe_fa_params.prefill_params.pipeline_flag, xe_fa_params.subgroup_size[0], xe_fa_params.prefill_params.gqa_fold };
|
||||
ggml_vk_create_pipeline(device, pipelines, "xe_fa_prefill", fa_prefill_cm1_len, fa_prefill_cm1_data, "main", 6, sizeof(vk_xe_fa_push_constants), { xe_fa_params.prefill_params.gqa_fold, xe_fa_params.prefill_params.wg_row / xe_fa_params.prefill_params.gqa_fold, 1 }, sc, 1, false, true, xe_fa_params.subgroup_size[0]);
|
||||
xe_fa_params.prefill_params.pipeline_flag, xe_fa_params.subgroup_size[0], xe_fa_params.prefill_params.gqa_fold,
|
||||
pipeline_state.bias_bins };
|
||||
ggml_vk_create_pipeline(device, pipelines, "xe_fa_prefill", fa_prefill_cm1_len, fa_prefill_cm1_data, "main", 8, sizeof(vk_xe_fa_push_constants), { xe_fa_params.prefill_params.gqa_fold, xe_fa_params.prefill_params.wg_row / xe_fa_params.prefill_params.gqa_fold, 1 }, sc, 1, false, true, xe_fa_params.subgroup_size[0]);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -5312,6 +5323,7 @@ vk_device ggml_vk_get_device(size_t idx) {
|
||||
device->coopmat2 = true;
|
||||
device->coopmat2_bf16_support = found_bf16_128 && found_bf16_256;
|
||||
device->coopmat2_decode_vector = coopmat2_decode_vector_support && coopmat2_decode_vector_features.cooperativeMatrixDecodeVector;
|
||||
device->coopmat2_reserved_shmem = coopmat2_props.cooperativeMatrixWorkgroupScopeReservedSharedMemory;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -9024,6 +9036,15 @@ bool ggml_vk_flash_attn_coopmat_shmem_support(const vk_device& device, const vk_
|
||||
return supported;
|
||||
}
|
||||
|
||||
static bool ggml_vk_flash_attn_cm2_bias_stage_shmem_support(const vk_device& device, const vk_fa_tuning_params& params, bool f32acc) {
|
||||
// Needs to be kept up to date on shader changes
|
||||
const uint32_t acctype = f32acc ? 4 : 2;
|
||||
const uint32_t bias_sh = params.block_rows * params.block_cols * acctype;
|
||||
const uint32_t iq_shmem = 16 * sizeof(ggml_fp16_t);
|
||||
|
||||
return uint64_t(bias_sh) + iq_shmem + device->coopmat2_reserved_shmem <= device->properties.limits.maxComputeSharedMemorySize;
|
||||
}
|
||||
|
||||
void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * q, const ggml_tensor * k, const ggml_tensor * v, const ggml_tensor * mask, const ggml_tensor * sinks, ggml_tensor * dst) {
|
||||
VK_LOG_DEBUG("ggml_vk_flash_attn((" << q << ", name=" << q->name << ", type=" << q->type << ", ne0=" << q->ne[0] << ", ne1=" << q->ne[1] << ", ne2=" << q->ne[2] << ", ne3=" << q->ne[3] << ", nb0=" << q->nb[0] << ", nb1=" << q->nb[1] << ", nb2=" << q->nb[2] << ", nb3=" << q->nb[3];
|
||||
std::cerr << "), (" << k << ", name=" << k->name << ", type=" << k->type << ", ne0=" << k->ne[0] << ", ne1=" << k->ne[1] << ", ne2=" << k->ne[2] << ", ne3=" << k->ne[3] << ", nb0=" << k->nb[0] << ", nb1=" << k->nb[1] << ", nb2=" << k->nb[2] << ", nb3=" << k->nb[3];
|
||||
@@ -9048,6 +9069,11 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
|
||||
const uint32_t nem2 = mask ? mask->ne[2] : 0;
|
||||
const uint32_t nem3 = mask ? mask->ne[3] : 0;
|
||||
|
||||
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_idx = has_bias ? dst->src[7] : nullptr;
|
||||
const uint32_t bias_bins = has_bias ? (uint32_t)bias_table->ne[0] : 0;
|
||||
|
||||
const uint32_t HSK = nek0;
|
||||
const uint32_t HSV = nev0;
|
||||
uint32_t N = neq1;
|
||||
@@ -9226,7 +9252,13 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
|
||||
bool use_mask_opt = mask && !use_sparse && nem1 >= 32 && nem0 * nem1 > 32768 && nem0 >= tuning_params.block_cols * 16
|
||||
&& (ctx->device->architecture != vk_device_architecture::AMD_GCN || HSK > 256 || HSV > 256);
|
||||
vk_fa_pipeline_state fa_pipeline_state = get_fa_pipeline_state(ctx->device, tuning_params, HSK, HSV, aligned, f32acc,
|
||||
mask != nullptr, use_mask_opt, logit_softcap != 0, use_sparse, k_type_eff, v_type_eff);
|
||||
mask != nullptr, use_mask_opt, logit_softcap != 0, use_sparse, k_type_eff, v_type_eff,
|
||||
bias_bins);
|
||||
// GQA rows share one index row, the per-element bias is cheaper there
|
||||
if (bias_bins && gqa_ratio == 1 && tuning_params.path == FA_COOPMAT2 &&
|
||||
ggml_vk_flash_attn_cm2_bias_stage_shmem_support(ctx->device, tuning_params, f32acc)) {
|
||||
fa_pipeline_state.flags |= FA_FLAG_BIAS_STAGE;
|
||||
}
|
||||
|
||||
vk_pipeline pipeline = nullptr;
|
||||
|
||||
@@ -9258,7 +9290,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
|
||||
if (neq1 > 8 || pv_ratio > 64) {
|
||||
uint32_t head_stride_q = uint32_t(nbq2 / ggml_type_size(q->type));
|
||||
uint32_t batch_stride_q = uint32_t(nbq3 / ggml_type_size(q->type));
|
||||
vk_xe_fa_pipeline_state prefill_state = { (uint32_t)neq0, (uint32_t)nev0, qk_ratio, pv_ratio, 0, false, false, false, false };
|
||||
vk_xe_fa_pipeline_state prefill_state = { (uint32_t)neq0, (uint32_t)nev0, qk_ratio, pv_ratio, 0, false, false, false, false, bias_bins };
|
||||
prefill_state.unaligned_seq_len = nek1 % 32 != 0;
|
||||
prefill_state.unaligned_q = head_stride_q % 8 != 0 || q_stride % 8 != 0 || batch_stride_q % 8 != 0;
|
||||
prefill_state.partial_row_mask = neq1 > nem1;
|
||||
@@ -9276,7 +9308,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
|
||||
xe_fa_opt = false;
|
||||
}
|
||||
} else {
|
||||
vk_xe_fa_pipeline_state decode_state = { (uint32_t)neq0, (uint32_t)nev0, qk_ratio, pv_ratio, (uint32_t)neq1, false, false, false, false };
|
||||
vk_xe_fa_pipeline_state decode_state = { (uint32_t)neq0, (uint32_t)nev0, qk_ratio, pv_ratio, (uint32_t)neq1, false, false, false, false, bias_bins };
|
||||
decode_state.unaligned_seq_len = nek1 % 256 != 0;
|
||||
xe_fa_params = get_xe_fa_tuning_params(vk_dev, decode_state, false);
|
||||
const uint32_t split_p_size = xe_fa_params.decode_params.p_chunk_ph1;
|
||||
@@ -9454,6 +9486,8 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
|
||||
vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
|
||||
vk_subbuffer mask_buf = mask ? ggml_vk_tensor_subbuffer(ctx, mask) : q_buf;
|
||||
vk_subbuffer sinks_buf = sinks ? ggml_vk_tensor_subbuffer(ctx, sinks) : q_buf;
|
||||
vk_subbuffer bias_table_buf = bias_table ? ggml_vk_tensor_subbuffer(ctx, bias_table) : q_buf;
|
||||
vk_subbuffer bias_idx_buf = bias_idx ? ggml_vk_tensor_subbuffer(ctx, bias_idx) : q_buf;
|
||||
vk_subbuffer mask_opt_buf = use_mask_opt ? ggml_vk_subbuffer(ctx, ctx->prealloc_y, 0) : q_buf;
|
||||
vk_subbuffer sparse_buf = use_sparse ? ggml_vk_subbuffer(ctx, ctx->prealloc_y, 0) : q_buf;
|
||||
if (use_mask_opt || use_sparse) {
|
||||
@@ -9608,7 +9642,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
|
||||
|
||||
ggml_pipeline_request_descriptor_sets(ctx, xe_fa_pipeline_dual_phases.first, 1);
|
||||
ggml_vk_dispatch_pipeline(ctx, subctx, xe_fa_pipeline_dual_phases.first,
|
||||
{ q_temp_buf, k_buf, mask_buf, p_temp_buf, max_temp_buf },
|
||||
{ q_temp_buf, k_buf, mask_buf, p_temp_buf, max_temp_buf, bias_table_buf, bias_idx_buf },
|
||||
pc_xe_fa, { (uint32_t)ph1_wg, (uint32_t)nek1, (uint32_t)neq3 });
|
||||
|
||||
ggml_vk_sync_buffers(ctx, subctx);
|
||||
@@ -9621,7 +9655,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
|
||||
} else {
|
||||
ggml_pipeline_request_descriptor_sets(ctx, xe_fa_pipeline, 1);
|
||||
ggml_vk_dispatch_pipeline(ctx, subctx, xe_fa_pipeline,
|
||||
{ q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf },
|
||||
{ q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf, bias_table_buf, bias_idx_buf },
|
||||
pc_xe_fa, { (uint32_t)neq2, (uint32_t)neq1, (uint32_t)neq3 });
|
||||
}
|
||||
} else if (split_k > 1) {
|
||||
@@ -9643,7 +9677,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
|
||||
|
||||
vk_subbuffer split_k_buf = ggml_vk_subbuffer(ctx, ctx->prealloc_split_k, 0);
|
||||
ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
|
||||
{q_buf, k_buf, v_buf, mask_buf, sinks_buf, split_k_buf, mask_opt_buf, sparse_buf},
|
||||
{q_buf, k_buf, v_buf, mask_buf, sinks_buf, split_k_buf, mask_opt_buf, sparse_buf, bias_table_buf, bias_idx_buf},
|
||||
pc, { dispatch_x, workgroups_y, workgroups_z });
|
||||
|
||||
ggml_vk_sync_buffers(ctx, subctx);
|
||||
@@ -9658,7 +9692,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const
|
||||
workgroups_x *= pipeline->wg_denoms[0];
|
||||
}
|
||||
ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
|
||||
{q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf, mask_opt_buf, sparse_buf},
|
||||
{q_buf, k_buf, v_buf, mask_buf, sinks_buf, dst_buf, mask_opt_buf, sparse_buf, bias_table_buf, bias_idx_buf},
|
||||
pc, { workgroups_x, workgroups_y, workgroups_z });
|
||||
}
|
||||
|
||||
@@ -16838,7 +16872,11 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
|
||||
}
|
||||
case GGML_OP_FLASH_ATTN_EXT:
|
||||
{
|
||||
if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) {
|
||||
if (op->src[5] != nullptr) {
|
||||
return false;
|
||||
}
|
||||
if (ggml_flash_attn_ext_has_indexed_bias(op) &&
|
||||
((uint64_t)ggml_nelements(op->src[6]) > UINT32_MAX || (uint64_t)ggml_nelements(op->src[7]) > UINT32_MAX)) {
|
||||
return false;
|
||||
}
|
||||
bool coopmat2 = device->coopmat2;
|
||||
|
||||
@@ -32,6 +32,7 @@ const uint32_t rows_per_thread = Br / row_split;
|
||||
const uint32_t cols_per_iter = WorkGroupSize / D_split / row_split;
|
||||
const uint32_t cols_per_thread = Bc / cols_per_iter;
|
||||
const uint32_t num_subgroups = SubGroupSize == 0 ? 0 : WorkGroupSize / SubGroupSize;
|
||||
const uint32_t mask_iters = (Bc * Br + WorkGroupSize - 1) / WorkGroupSize;
|
||||
|
||||
|
||||
layout (binding = 0) readonly buffer Q {float data_q[];};
|
||||
@@ -201,11 +202,39 @@ void main() {
|
||||
// skip this block
|
||||
continue;
|
||||
}
|
||||
// Only load if the block is not all zeros
|
||||
if (mask_opt_bits != MASK_OPT_ALL_ZERO) {
|
||||
// Skip all-zero blocks unless a bias has to be staged
|
||||
if (mask_opt_bits != MASK_OPT_ALL_ZERO || USE_BIAS) {
|
||||
const bool mask_zero = USE_BIAS && mask_opt_bits == MASK_OPT_ALL_ZERO;
|
||||
bool nem1_bounds_check = !(p.gqa_ratio > 1) && (p.nem1 % Br) != 0;
|
||||
|
||||
float max_mask = NEG_FLT_MAX_OVER_2;
|
||||
|
||||
// Bias: all mask, index and table loads before the barrier; the max keeps them there
|
||||
FLOAT_TYPE mb[mask_iters];
|
||||
if (USE_BIAS) {
|
||||
bool mact[mask_iters], bact[mask_iters];
|
||||
FLOAT_TYPE mv[mask_iters];
|
||||
uint32_t bin_base[mask_iters];
|
||||
int32_t bin[mask_iters];
|
||||
[[unroll]] for (uint32_t it = 0; it < mask_iters; ++it) {
|
||||
const uint32_t c = (it * WorkGroupSize + tid) % Bc;
|
||||
const uint32_t r = (it * WorkGroupSize + tid) / Bc;
|
||||
uint32_t kcol, bq, bh;
|
||||
const bool kv_active = fa_kv_index(j * Bc + c, kcol);
|
||||
mact[it] = it * WorkGroupSize + tid < Bc * Br && kv_active && (!nem1_bounds_check || i * Br + r < p.nem1);
|
||||
bact[it] = fa_bias_row(r, bq, bh) && mact[it];
|
||||
mv[it] = FLOAT_TYPE(data_m[mact[it] && !mask_zero ? m_offset + (i * Br + r) * m_stride + kcol : 0]);
|
||||
bin_base[it] = (bq * p.neq2 + bh) * BiasBins;
|
||||
bin[it] = data_bias_idx[bact[it] ? bq * p.KV + kcol : 0];
|
||||
}
|
||||
[[unroll]] for (uint32_t it = 0; it < mask_iters; ++it) {
|
||||
const float t = data_bias_table[bact[it] ? bin_base[it] + uint32_t(bin[it]) : 0];
|
||||
const float m = mask_zero ? 0.0f : float(mv[it]);
|
||||
mb[it] = FLOAT_TYPE(bact[it] ? m + t : m);
|
||||
max_mask = mact[it] ? max(max_mask, float(mb[it])) : max_mask;
|
||||
}
|
||||
}
|
||||
|
||||
barrier();
|
||||
[[unroll]] for (uint32_t idx = 0; idx < Bc * Br; idx += gl_WorkGroupSize.x) {
|
||||
uint32_t c = (idx + tid) % Bc;
|
||||
@@ -214,9 +243,9 @@ void main() {
|
||||
uint32_t kcol;
|
||||
bool kv_active = fa_kv_index(j * Bc + c, kcol);
|
||||
if (kv_active && (!nem1_bounds_check || i * Br + r < p.nem1)) {
|
||||
FLOAT_TYPE m = FLOAT_TYPE(data_m[m_offset + (i * Br + r) * m_stride + kcol]);
|
||||
masksh[c * masksh_stride + r] = m;
|
||||
FLOAT_TYPE m = USE_BIAS ? mb[idx / WorkGroupSize] : FLOAT_TYPE(data_m[m_offset + (i * Br + r) * m_stride + kcol]);
|
||||
max_mask = max(max_mask, float(m));
|
||||
masksh[c * masksh_stride + r] = m;
|
||||
} else {
|
||||
#if defined(FLOAT16)
|
||||
masksh[c * masksh_stride + r] = USE_SPARSE ? FLOAT_TYPE(NEG_FLT16_MAX) : FLOAT_TYPE(0);
|
||||
@@ -452,7 +481,7 @@ void main() {
|
||||
}
|
||||
}
|
||||
|
||||
if (MASK_ENABLE && mask_opt_bits != MASK_OPT_ALL_ZERO) {
|
||||
if (MASK_ENABLE && (mask_opt_bits != MASK_OPT_ALL_ZERO || USE_BIAS)) {
|
||||
[[unroll]] for (uint32_t c = 0; c < cols_per_thread; ++c) {
|
||||
[[unroll]] for (uint32_t r = 0; r < rows_per_thread; ++r) {
|
||||
FLOAT_TYPE mvf = masksh[(c * cols_per_iter + col_tid) * masksh_stride + tile_row(r)];
|
||||
|
||||
@@ -19,6 +19,8 @@ layout (constant_id = 13) const uint32_t FaTypeV = 0;
|
||||
// sizeof(decode buffer): quants -> ggml block size; F32 -> 16 (decodeBufF32 vec4).
|
||||
layout (constant_id = 14) const uint32_t FaBlockBytesK = 2;
|
||||
layout (constant_id = 15) const uint32_t FaBlockBytesV = 2;
|
||||
// Indexed bias: table->ne[0], 0 = no bias
|
||||
layout (constant_id = 16) const uint32_t BiasBins = 0;
|
||||
|
||||
const bool USE_MASK_OPT = (Flags & 1) != 0;
|
||||
const bool MASK_ENABLE = (Flags & 2) != 0;
|
||||
@@ -30,6 +32,7 @@ const bool Q_IN_REGS = (Flags & 32) != 0;
|
||||
// coopmat1: subgroups own Q rows, O in coopmat accumulators. K/V staged in LDS, or loaded from global memory with FLIP_DIRECT.
|
||||
const bool FLIP = (Flags & 64) != 0;
|
||||
const bool FLIP_DIRECT = (Flags & 128) != 0;
|
||||
const bool USE_BIAS = BiasBins != 0;
|
||||
|
||||
// Round up head sizes to a multiple of 16, for coopmat1/coopmat2 paths
|
||||
const uint32_t HSK_pad = (HSK + 15) & ~15;
|
||||
@@ -90,6 +93,9 @@ layout (binding = 6) readonly buffer MO {uint32_t data_mask_opt[];};
|
||||
|
||||
layout (binding = 7) readonly buffer SP {int32_t data_sparse[];};
|
||||
|
||||
layout (binding = 8) readonly buffer BT {float data_bias_table[];};
|
||||
layout (binding = 9) readonly buffer BI {int32_t data_bias_idx[];};
|
||||
|
||||
// Use -FLT_MAX/2 rather than -inf to reduce the possibility of NaNs, e.g. when computing Mold-M.
|
||||
#define NEG_FLT_MAX_OVER_2 uintBitsToFloat(0xFEFFFFFF)
|
||||
// Lowest finite f16, mask value for inactive sparse KV slots
|
||||
@@ -250,6 +256,23 @@ bool fa_kv_index(uint lin, out uint kv_col) {
|
||||
return !KV_bounds_check || lin < KV;
|
||||
}
|
||||
|
||||
// Flattened query and Q head of tile row r. With GQA collapse rows are heads. False for padding rows.
|
||||
bool fa_bias_row(const in uint32_t r, out uint32_t query, out uint32_t head) {
|
||||
if (p.gqa_ratio > 1) {
|
||||
query = iq3 * p.nem1 + gqa_iq1;
|
||||
head = iq2 + r;
|
||||
return r < N;
|
||||
}
|
||||
query = iq3 * p.nem1 + i * Br + r;
|
||||
head = iq2;
|
||||
return i * Br + r < N;
|
||||
}
|
||||
|
||||
float fa_bias(const in uint32_t query, const in uint32_t head, const in uint32_t kv_col) {
|
||||
const uint32_t bin = uint32_t(data_bias_idx[query * p.KV + kv_col]);
|
||||
return data_bias_table[(query * p.neq2 + head) * BiasBins + bin];
|
||||
}
|
||||
|
||||
// Bias applied to softmax to stay in fp16 range.
|
||||
// Based on ggml-cuda issue https://github.com/ggml-org/llama.cpp/issues/18606
|
||||
const float FATTN_KQ_MAX_OFFSET = 3.0f*0.6931f;
|
||||
|
||||
@@ -230,8 +230,8 @@ void main() {
|
||||
// skip this block
|
||||
continue;
|
||||
}
|
||||
// Only load if the block is not all zeros
|
||||
if (mask_opt_bits != MASK_OPT_ALL_ZERO) {
|
||||
// Skip all-zero blocks unless a bias has to be staged
|
||||
if (mask_opt_bits != MASK_OPT_ALL_ZERO || USE_BIAS) {
|
||||
bool nem1_bounds_check = !(p.gqa_ratio > 1) && (p.nem1 % Br) != 0;
|
||||
|
||||
float max_mask = NEG_FLT_MAX_OVER_2;
|
||||
@@ -241,9 +241,27 @@ void main() {
|
||||
if (idx + tid < Bc * Br / 4 || idx + gl_WorkGroupSize.x <= Bc * Br / 4) {
|
||||
uint32_t kcol;
|
||||
bool kv_active = fa_kv_index(j * Bc + c, kcol);
|
||||
if (kv_active) {
|
||||
if (USE_BIAS && kv_active && p.gqa_ratio > 1 && mask_opt_bits != MASK_OPT_ALL_ZERO) {
|
||||
// GQA: the rows share one mask value and one bias index
|
||||
uint32_t bq, bh0;
|
||||
fa_bias_row(0, bq, bh0);
|
||||
const float mv = float(data_m[m_offset + kcol]);
|
||||
const uint32_t bin = uint32_t(data_bias_idx[bq * p.KV + kcol]);
|
||||
vec4 mb = vec4(mv);
|
||||
[[unroll]] for (uint32_t k = 0; k < 4; ++k) {
|
||||
uint32_t q, h;
|
||||
const bool v = fa_bias_row(r * 4 + k, q, h);
|
||||
const float b = data_bias_table[(bq * p.neq2 + (v ? h : bh0)) * BiasBins + bin];
|
||||
mb[k] += v ? b : 0.0;
|
||||
}
|
||||
max_mask = max(max_mask, mv);
|
||||
mask_cache[idx / WorkGroupSize] = f16vec4(mb);
|
||||
} else if (kv_active) {
|
||||
f16vec4 m;
|
||||
if (USE_SPARSE) {
|
||||
if (USE_BIAS && mask_opt_bits == MASK_OPT_ALL_ZERO) {
|
||||
m = f16vec4(0.0);
|
||||
max_mask = 0.0;
|
||||
} else if (USE_SPARSE) {
|
||||
// sparse is gqa-gated (m_stride == 0): all four rows share the value
|
||||
FLOAT_TYPE mv = FLOAT_TYPE(data_m[m_offset + kcol]);
|
||||
m = f16vec4(mv);
|
||||
@@ -275,6 +293,26 @@ void main() {
|
||||
} else {
|
||||
m = f16vec4(0.0);
|
||||
}
|
||||
uint32_t bq0, bh0;
|
||||
if (USE_BIAS && fa_bias_row(r * 4, bq0, bh0)) {
|
||||
vec4 mb = vec4(m);
|
||||
uint32_t bq[4], bh[4];
|
||||
bool bv[4];
|
||||
[[unroll]] for (uint32_t k = 0; k < 4; ++k) {
|
||||
bv[k] = fa_bias_row(r * 4 + k, bq[k], bh[k]);
|
||||
bq[k] = bv[k] ? bq[k] : bq0;
|
||||
bh[k] = bv[k] ? bh[k] : bh0;
|
||||
}
|
||||
uint32_t bin[4];
|
||||
[[unroll]] for (uint32_t k = 0; k < 4; ++k) {
|
||||
bin[k] = uint32_t(data_bias_idx[bq[k] * p.KV + kcol]);
|
||||
}
|
||||
[[unroll]] for (uint32_t k = 0; k < 4; ++k) {
|
||||
const float b = data_bias_table[(bq[k] * p.neq2 + bh[k]) * BiasBins + bin[k]];
|
||||
mb[k] += bv[k] ? b : 0.0;
|
||||
}
|
||||
m = f16vec4(mb);
|
||||
}
|
||||
mask_cache[idx / WorkGroupSize] = m;
|
||||
} else if (USE_SPARSE) {
|
||||
mask_cache[idx / WorkGroupSize] = f16vec4(NEG_FLT16_MAX);
|
||||
@@ -416,7 +454,7 @@ void main() {
|
||||
barrier();
|
||||
}
|
||||
|
||||
if (MASK_ENABLE && mask_opt_bits != MASK_OPT_ALL_ZERO) {
|
||||
if (MASK_ENABLE && (mask_opt_bits != MASK_OPT_ALL_ZERO || USE_BIAS)) {
|
||||
[[unroll]] for (uint32_t idx = 0; idx < Bc * Br / 4; idx += gl_WorkGroupSize.x) {
|
||||
uint32_t c = (idx + tid) / (Br / 4);
|
||||
uint32_t r = (idx + tid) % (Br / 4);
|
||||
|
||||
@@ -307,6 +307,25 @@ void main() {
|
||||
}
|
||||
}
|
||||
|
||||
float bv[FL_CPL];
|
||||
[[unroll]] for (uint32_t k = 0; k < FL_CPL; ++k) {
|
||||
bv[k] = 0.0;
|
||||
}
|
||||
{
|
||||
uint32_t bq, bh;
|
||||
if (USE_BIAS && myrow < p.nem1 && fa_bias_row(sg * 16 + lr, bq, bh)) {
|
||||
const uint32_t ioff = bq * p.KV + j * Bc + lc * FL_CPL;
|
||||
const uint32_t toff = (bq * p.neq2 + bh) * BiasBins;
|
||||
uint32_t bin[FL_CPL];
|
||||
[[unroll]] for (uint32_t k = 0; k < FL_CPL; ++k) {
|
||||
bin[k] = uint32_t(data_bias_idx[ioff + k]);
|
||||
}
|
||||
[[unroll]] for (uint32_t k = 0; k < FL_CPL; ++k) {
|
||||
bv[k] = data_bias_table[toff + bin[k]];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
coopmat<ACC_TYPE, gl_ScopeSubgroup, 16, 16, gl_MatrixUseAccumulator> Sacc[Bc / 16];
|
||||
[[unroll]] for (uint32_t c = 0; c < Bc / 16; ++c) {
|
||||
Sacc[c] = coopmat<ACC_TYPE, gl_ScopeSubgroup, 16, 16, gl_MatrixUseAccumulator>(0);
|
||||
@@ -342,10 +361,15 @@ void main() {
|
||||
}
|
||||
}
|
||||
|
||||
if (MASK_ENABLE && mask_bits != MASK_OPT_ALL_ZERO && myrow < p.nem1) {
|
||||
if (MASK_ENABLE && (mask_bits != MASK_OPT_ALL_ZERO || USE_BIAS) && myrow < p.nem1) {
|
||||
const uint32_t moff = m_offset + myrow * KV + j * Bc + lc * FL_CPL;
|
||||
if (!USE_BIAS || mask_bits != MASK_OPT_ALL_ZERO) {
|
||||
[[unroll]] for (uint32_t k = 0; k < FL_CPL; ++k) {
|
||||
bv[k] += float(data_m[moff + k]);
|
||||
}
|
||||
}
|
||||
[[unroll]] for (uint32_t k = 0; k < FL_CPL; ++k) {
|
||||
s[k] += slope_v * float(data_m[moff + k]);
|
||||
s[k] += slope_v * bv[k];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -203,9 +203,49 @@ ACC_TYPE faAddSparseMask(const uint32_t row, const uint32_t col, const ACC_TYPE
|
||||
const uint32_t kvslot = jblk * Bc + col;
|
||||
if (kvslot >= p.split_kv) { return ACC_TYPE_NEG; }
|
||||
const int r = data_sparse[sparse_base + kvslot];
|
||||
return r < 0 ? ACC_TYPE_NEG : elem + ACC_TYPE(data_mf16[g_m_off_elem + row * m_stride + uint(r)]);
|
||||
if (r < 0) { return ACC_TYPE_NEG; }
|
||||
ACC_TYPE mv = ACC_TYPE(data_mf16[g_m_off_elem + row * m_stride + uint(r)]);
|
||||
uint32_t bq, bh;
|
||||
if (USE_BIAS && fa_bias_row(row, bq, bh)) {
|
||||
mv += ACC_TYPE(fa_bias(bq, bh, uint(r)));
|
||||
}
|
||||
return elem + mv;
|
||||
}
|
||||
|
||||
ACC_TYPE faAddBias(const uint32_t row, const uint32_t col, const ACC_TYPE elem, const uint32_t jblk) {
|
||||
const uint32_t kv_col = jblk * Bc + col;
|
||||
uint32_t bq, bh;
|
||||
if ((KV_bounds_check && kv_col >= KV) || !fa_bias_row(row, bq, bh)) {
|
||||
return elem;
|
||||
}
|
||||
return elem + ACC_TYPE(fa_bias(bq, bh, kv_col));
|
||||
}
|
||||
|
||||
#ifdef FA_BIAS_STAGE
|
||||
const uint32_t BIAS_ROW_STEP = WorkGroupSize / Bc;
|
||||
const uint32_t BIAS_ROWS = Br / BIAS_ROW_STEP;
|
||||
shared ACC_TYPE bias_sh[Br * Bc];
|
||||
|
||||
// Subgroups read contiguous columns of one row, so the index and table loads coalesce.
|
||||
void faStageBias(const uint32_t jblk) {
|
||||
const uint32_t col = gl_LocalInvocationIndex % Bc;
|
||||
const uint32_t r0 = gl_LocalInvocationIndex / Bc;
|
||||
const uint32_t kv_col = jblk * Bc + col;
|
||||
int32_t bins[BIAS_ROWS];
|
||||
uint32_t boff[BIAS_ROWS];
|
||||
bool ok[BIAS_ROWS];
|
||||
[[unroll]] for (uint32_t k = 0; k < BIAS_ROWS; ++k) {
|
||||
uint32_t bq, bh;
|
||||
ok[k] = (!KV_bounds_check || kv_col < KV) && fa_bias_row(r0 + k * BIAS_ROW_STEP, bq, bh);
|
||||
boff[k] = (bq * p.neq2 + bh) * BiasBins;
|
||||
bins[k] = ok[k] ? data_bias_idx[bq * p.KV + kv_col] : 0;
|
||||
}
|
||||
[[unroll]] for (uint32_t k = 0; k < BIAS_ROWS; ++k) {
|
||||
bias_sh[(r0 + k * BIAS_ROW_STEP) * Bc + col] = ok[k] ? ACC_TYPE(data_bias_table[boff[k] + uint32_t(bins[k])]) : ACC_TYPE(0);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
ACC_TYPE maxReduce(const in ACC_TYPE x, const in ACC_TYPE y) {
|
||||
return max(x, y);
|
||||
}
|
||||
@@ -408,6 +448,14 @@ void main() {
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef FA_BIAS_STAGE
|
||||
if (MASK_ENABLE) {
|
||||
barrier();
|
||||
faStageBias(j);
|
||||
barrier();
|
||||
}
|
||||
#endif
|
||||
|
||||
coopmat<ACC_TYPE, gl_ScopeWorkgroup, Br, Bc, gl_MatrixUseAccumulator> S = coopmat<ACC_TYPE, gl_ScopeWorkgroup, Br, Bc, gl_MatrixUseAccumulator>(0);
|
||||
|
||||
coopmat<FLOAT_TYPE, gl_ScopeWorkgroup, HSK_pad, Bc, gl_MatrixUseB> K_T;
|
||||
@@ -435,7 +483,17 @@ void main() {
|
||||
if (MASK_ENABLE && USE_SPARSE) {
|
||||
coopMatPerElementNV(S, S, faAddSparseMask, j);
|
||||
} else if (MASK_ENABLE) {
|
||||
S += slopeMat*coopmat<ACC_TYPE, gl_ScopeWorkgroup, Br, Bc, gl_MatrixUseAccumulator>(mv);
|
||||
coopmat<ACC_TYPE, gl_ScopeWorkgroup, Br, Bc, gl_MatrixUseAccumulator> mva = coopmat<ACC_TYPE, gl_ScopeWorkgroup, Br, Bc, gl_MatrixUseAccumulator>(mv);
|
||||
#ifdef FA_BIAS_STAGE
|
||||
coopmat<ACC_TYPE, gl_ScopeWorkgroup, Br, Bc, gl_MatrixUseAccumulator> bias;
|
||||
coopMatLoad(bias, bias_sh, 0, Bc, gl_CooperativeMatrixLayoutRowMajor);
|
||||
mva += bias;
|
||||
#else
|
||||
if (USE_BIAS) {
|
||||
coopMatPerElementNV(mva, mva, faAddBias, j);
|
||||
}
|
||||
#endif
|
||||
S += slopeMat*mva;
|
||||
}
|
||||
|
||||
// Clear padding elements to -inf, so they don't contribute to rowmax
|
||||
|
||||
@@ -16,6 +16,8 @@ layout (binding = 1) readonly buffer KV4 {f16vec4 data_kv4[];};
|
||||
layout (binding = 2) readonly buffer M {float16_t data_m[];};
|
||||
layout (binding = 3) buffer P {float16_t data_p[];};
|
||||
layout (binding = 4) buffer MAX {float data_max[];};
|
||||
layout (binding = 5) readonly buffer BT {float data_bias_table[];};
|
||||
layout (binding = 6) readonly buffer BI {int data_bias_idx[];};
|
||||
|
||||
layout (push_constant) uniform parameter
|
||||
{
|
||||
@@ -54,6 +56,7 @@ layout (constant_id = 6) const uint pmat_count = 4;
|
||||
layout (constant_id = 7) const uint TM = 8;
|
||||
layout (constant_id = 8) const uint TN = 16;
|
||||
layout (constant_id = 9) const uint shmem_size = 49152;
|
||||
layout (constant_id = 10) const uint BiasBins = 0;
|
||||
|
||||
const uint TK = 16;
|
||||
const uint sg_count = WorkGroupSize / SubGroupSize;
|
||||
@@ -295,6 +298,17 @@ void main() {
|
||||
Of[r][idx] = Of[r][idx] + Maskf[idx];
|
||||
}
|
||||
|
||||
if (BiasBins != 0 && sg * warp_o_row + r < gqa_ratio) {
|
||||
const uint bias_q = batch_idx * p.neq1 + out_r + out_idx * Br;
|
||||
const uint bias_t = (bias_q * p.neq2 + head_q_idx) * BiasBins;
|
||||
[[unroll]] for (uint idx = 0; idx < p_reduce / SubGroupSize; ++idx) {
|
||||
const uint mask_offset = idx * SubGroupSize + mask_base;
|
||||
if (mask_offset < p.nek1) {
|
||||
Of[r][idx] += data_bias_table[bias_t + data_bias_idx[bias_q * p.nek1 + mask_offset]];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
float Mtempf = NEG_FLT_MAX_OVER_2;
|
||||
[[unroll]] for (uint idx = 0; idx < p_reduce / SubGroupSize; ++idx) {
|
||||
const uint p_col_offset = idx * SubGroupSize + mask_base;
|
||||
|
||||
@@ -24,6 +24,8 @@ layout (binding = 3) readonly buffer MV2 {f16vec2 data_mv2[];};
|
||||
layout (binding = 3) readonly buffer MV4 {f16vec4 data_mv4[];};
|
||||
layout (binding = 4) readonly buffer S {float data_s[];};
|
||||
layout (binding = 5) buffer OV4 {vec4 data_ov4[];};
|
||||
layout (binding = 6) readonly buffer BT {float data_bias_table[];};
|
||||
layout (binding = 7) readonly buffer BI {int data_bias_idx[];};
|
||||
|
||||
layout (push_constant) uniform parameter
|
||||
{
|
||||
@@ -67,6 +69,7 @@ layout (constant_id = 11) const uint acc_count = 1;
|
||||
layout (constant_id = 12) const uint Flags = 0;
|
||||
layout (constant_id = 13) const uint SubGroupSize = 16;
|
||||
layout (constant_id = 14) const uint gqa_fold = 1;
|
||||
layout (constant_id = 15) const uint BiasBins = 0;
|
||||
|
||||
#define UNALIGNED_SEQ_LEN_BIT (1 << 0)
|
||||
#define UNALIGNED_Q_STRIDE_BIT (1 << 1)
|
||||
@@ -532,6 +535,20 @@ void main() {
|
||||
}
|
||||
}
|
||||
|
||||
if (BiasBins != 0) {
|
||||
const uint bias_row = out_r * folded_row_wg + sg_o_r_row * TN + lane_c;
|
||||
if (bias_row < p.neq1) {
|
||||
const uint bias_q = batch_idx * p.neq1 + bias_row;
|
||||
const uint bias_t = (bias_q * p.neq2 + head_q_idx * gqa_fold + sg_o_r_h) * BiasBins;
|
||||
const uint bias_col = loop * step_p + lane_r * softmax_loops;
|
||||
[[unroll]] for (uint idx = 0; idx < softmax_loops; ++idx) {
|
||||
if (!seq_boundary_check || bias_col + idx < p.nek1) {
|
||||
Pf[idx] += data_bias_table[bias_t + data_bias_idx[bias_q * p.nek1 + bias_col + idx]];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (seq_boundary_check && loop + 1 == loop_count) {
|
||||
[[unroll]] for (uint idx = 0; idx < softmax_loops; ++idx) {
|
||||
if (loop * step_p + idx + lane_r * softmax_loops < p.nek1) {
|
||||
|
||||
@@ -736,6 +736,8 @@ void process_shaders() {
|
||||
#if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
|
||||
string_to_spv("flash_attn_f32_f16", "flash_attn_cm2.comp",
|
||||
merge_maps(fa_base_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"D_TYPEV4", "vec4"}}), fp16, false, true, f16acc);
|
||||
string_to_spv("flash_attn_f32_f16", "flash_attn_cm2.comp",
|
||||
merge_maps(fa_base_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"D_TYPEV4", "vec4"}, {"FA_BIAS_STAGE", "1"}}), fp16, false, true, f16acc, "_bias");
|
||||
#endif
|
||||
|
||||
#if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
|
||||
@@ -787,6 +789,9 @@ void process_shaders() {
|
||||
string_to_spv("flash_attn_f32_f16_bf16", "flash_attn_cm2.comp",
|
||||
merge_maps(fa_bf16_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"D_TYPEV4", "vec4"}}),
|
||||
true, false, true, false);
|
||||
string_to_spv("flash_attn_f32_f16_bf16", "flash_attn_cm2.comp",
|
||||
merge_maps(fa_bf16_dict, {{"Q_TYPE", "float"}, {"D_TYPE", "float"}, {"D_TYPEV4", "vec4"}, {"FA_BIAS_STAGE", "1"}}),
|
||||
true, false, true, false, "_bias");
|
||||
#endif
|
||||
|
||||
std::map<std::string, std::string> base_dict = {{"FLOAT_TYPE", "float"}, {"FLOAT_TYPEV2", "vec2"}};
|
||||
|
||||
+40
-4
@@ -16,19 +16,24 @@ set(HF_VERSION "" CACHE STRING "Version to download (empty = resolve from
|
||||
set(HF_ENABLED "" CACHE STRING "Whether to allow HF Bucket download (ON/OFF)")
|
||||
set(BUILD_UI "" CACHE STRING "Build UI via npm (ON/OFF)")
|
||||
set(LLAMA_UI_GZIP "" CACHE STRING "Apply gzip compress to assets to save bandwidth")
|
||||
# OFF unless it is turned on: a UI built here has sharing conversations to Hugging Face in it
|
||||
# only when asked for (the prebuilt one, which releases are made of, has it)
|
||||
set(LLAMA_UI_HUGGING_FACE OFF CACHE STRING "Whether the UI built here has sharing to Hugging Face (ON/OFF)")
|
||||
|
||||
set(DIST_DIR "${UI_BINARY_DIR}/dist")
|
||||
set(SRC_DIST_DIR "${UI_SOURCE_DIR}/dist")
|
||||
# The stage keeps the layout of ui/: the app in apps/chat, with the sources of
|
||||
# Llama UI that it compiles next to it in lib/ui (see ui/apps/chat/scripts/llama-ui.js),
|
||||
# and those of Llama Voice and the harness in lib/voice and lib/harness (see
|
||||
# ui/apps/chat/vite.config.ts).
|
||||
# and those of Llama Voice, the harness and Llama Hugging Face in lib/voice, lib/harness and
|
||||
# lib/huggingface (see ui/apps/chat/vite.config.ts).
|
||||
set(STAGE_DIR "${UI_BINARY_DIR}/ui-src")
|
||||
set(WORK_DIR "${STAGE_DIR}/apps/chat")
|
||||
set(UI_LIB_DIR "${UI_SOURCE_DIR}/../../lib/ui")
|
||||
set(UI_VOICE_DIR "${UI_SOURCE_DIR}/../../lib/voice")
|
||||
set(HARNESS_DIR "${UI_SOURCE_DIR}/../../lib/harness")
|
||||
set(UI_HUGGINGFACE_DIR "${UI_SOURCE_DIR}/../../lib/huggingface")
|
||||
set(STAMP_FILE "${UI_BINARY_DIR}/.ui-stamp")
|
||||
set(BUILD_OPTIONS_STAMP "${UI_BINARY_DIR}/.ui-build-options")
|
||||
set(EMBED_STAMP "${UI_BINARY_DIR}/.ui-embed.sha256")
|
||||
set(UI_CPP "${UI_BINARY_DIR}/ui.cpp")
|
||||
set(UI_H "${UI_BINARY_DIR}/ui.h")
|
||||
@@ -295,6 +300,16 @@ function(emit_files dist_dir)
|
||||
message(STATUS "UI: embedded ${n_assets} assets")
|
||||
endfunction()
|
||||
|
||||
# What the npm build is told, as environment variables (see ui/apps/chat/vite.config.ts).
|
||||
# They are set either way, so the build does not depend on the environment it runs in.
|
||||
function(ui_build_options out_var)
|
||||
if(LLAMA_UI_HUGGING_FACE)
|
||||
set(${out_var} "VITE_PUBLIC_HUGGING_FACE=true" PARENT_SCOPE)
|
||||
else()
|
||||
set(${out_var} "VITE_PUBLIC_HUGGING_FACE=false" PARENT_SCOPE)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
function(npm_build_should_skip out_var)
|
||||
set(${out_var} FALSE PARENT_SCOPE)
|
||||
|
||||
@@ -306,6 +321,18 @@ function(npm_build_should_skip out_var)
|
||||
return()
|
||||
endif()
|
||||
|
||||
# an output built with other options is out of date, whatever its sources;
|
||||
# one from before the options has none of the opt-in features
|
||||
ui_build_options(options)
|
||||
set(built_with "VITE_PUBLIC_HUGGING_FACE=false")
|
||||
if(EXISTS "${BUILD_OPTIONS_STAMP}")
|
||||
file(READ "${BUILD_OPTIONS_STAMP}" built_with)
|
||||
string(STRIP "${built_with}" built_with)
|
||||
endif()
|
||||
if(NOT built_with STREQUAL options)
|
||||
return()
|
||||
endif()
|
||||
|
||||
if(NOT EXISTS "${UI_SOURCE_DIR}/sources.cmake")
|
||||
return()
|
||||
endif()
|
||||
@@ -380,6 +407,12 @@ function(stage_sources)
|
||||
DESTINATION "${STAGE_DIR}/lib/harness"
|
||||
NO_SOURCE_PERMISSIONS
|
||||
)
|
||||
|
||||
# and of Llama Hugging Face, its sources only too
|
||||
file(COPY "${UI_HUGGINGFACE_DIR}/src"
|
||||
DESTINATION "${STAGE_DIR}/lib/huggingface"
|
||||
NO_SOURCE_PERMISSIONS
|
||||
)
|
||||
endfunction()
|
||||
|
||||
function(npm_build out_var)
|
||||
@@ -440,9 +473,11 @@ function(npm_build out_var)
|
||||
|
||||
file(MAKE_DIRECTORY "${DIST_DIR}")
|
||||
|
||||
message(STATUS "UI: running npm run build, output -> ${DIST_DIR}")
|
||||
ui_build_options(options)
|
||||
|
||||
message(STATUS "UI: running npm run build (${options}), output -> ${DIST_DIR}")
|
||||
execute_process(
|
||||
COMMAND ${CMAKE_COMMAND} -E env "LLAMA_UI_OUT_DIR=${DIST_DIR}" "LLAMA_UI_VERSION=${HF_VERSION}" "LLAMA_BUILD_NUMBER=${LLAMA_BUILD_NUMBER}"
|
||||
COMMAND ${CMAKE_COMMAND} -E env "LLAMA_UI_OUT_DIR=${DIST_DIR}" "LLAMA_UI_VERSION=${HF_VERSION}" "LLAMA_BUILD_NUMBER=${LLAMA_BUILD_NUMBER}" "${options}"
|
||||
${NPM_EXECUTABLE} run build
|
||||
WORKING_DIRECTORY "${WORK_DIR}"
|
||||
RESULT_VARIABLE rc
|
||||
@@ -461,6 +496,7 @@ function(npm_build out_var)
|
||||
|
||||
message(STATUS "UI: npm build succeeded")
|
||||
file(REMOVE "${STAMP_FILE}")
|
||||
file(WRITE "${BUILD_OPTIONS_STAMP}" "${options}")
|
||||
set(${out_var} TRUE PARENT_SCOPE)
|
||||
endfunction()
|
||||
|
||||
|
||||
@@ -674,8 +674,6 @@ enum llm_tensor {
|
||||
LLM_TENSOR_LAYER_OUT_NORM,
|
||||
LLM_TENSOR_LAYER_OUT_SCALE,
|
||||
LLM_TENSOR_ATTN_VRES_LAMBDA,
|
||||
LLM_TENSOR_POST_ATTN_NORM,
|
||||
LLM_TENSOR_POST_MLP_NORM,
|
||||
LLM_TENSOR_PER_LAYER_TOKEN_EMBD, // gemma3n
|
||||
LLM_TENSOR_PER_LAYER_MODEL_PROJ, // gemma3n
|
||||
LLM_TENSOR_PER_LAYER_INP_GATE, // gemma3n
|
||||
|
||||
@@ -350,6 +350,7 @@ struct llama_moe_cache::impl {
|
||||
ggml_tensor * cpu_map = nullptr; // I32 [1, n_expert] in host memory, if cpu_share > 0
|
||||
std::vector<int32_t> cpu_experts; // experts set in cpu_map
|
||||
uint32_t cpu_acc = 0; // fraction of a miss carried over to the next plan, in 1/65536
|
||||
int32_t n_used = 0; // experts selected per token by the graph, set by build_lookup
|
||||
std::vector<ggml_tensor *> experts; // host expert tensors, in the order of the banks
|
||||
};
|
||||
|
||||
@@ -789,6 +790,7 @@ struct llama_moe_cache::impl {
|
||||
|
||||
// the selected experts must be computed in an earlier split
|
||||
// the scheduler starts a new split at the lookup because it reads a host weight, unless the lookup is the first node of its split
|
||||
// if they are selected on another backend (e.g. the loop passes of inkling2_loop), sel is the copy made by the scheduler before this callback
|
||||
const ggml_tensor * sel = lookup->src[1];
|
||||
for (int i = 0; i < n_nodes; ++i) {
|
||||
const ggml_tensor * node = ggml_graph_node(graph, i);
|
||||
@@ -797,9 +799,11 @@ struct llama_moe_cache::impl {
|
||||
}
|
||||
}
|
||||
GGML_ASSERT(ggml_is_contiguous(sel));
|
||||
GGML_ASSERT(sel->op == GGML_OP_RESHAPE); // of the [n_expert_used, n_tokens] ids, see build_lookup
|
||||
|
||||
const int32_t n_used = (int32_t) sel->src[0]->ne[0];
|
||||
// a copy of the 1D ids has no source to read the shape from
|
||||
const int32_t n_used = l.n_used;
|
||||
GGML_ASSERT(n_used > 0 && ggml_nelements(sel) % n_used == 0);
|
||||
const int64_t n_tokens = ggml_nelements(sel)/n_used;
|
||||
|
||||
ids.resize(ggml_nelements(sel));
|
||||
ggml_backend_tensor_get_async(backend, sel, ids.data(), 0, ggml_nbytes(sel));
|
||||
@@ -817,7 +821,7 @@ struct llama_moe_cache::impl {
|
||||
return (size_t) (acc >> 16);
|
||||
};
|
||||
size_t n_hit = 0;
|
||||
if (!g.lru.plan(il, ids.data(), ids.size(), sel->src[0]->ne[1], n_used, n_zero, n_cpu, fills, cpu, n_hit)) {
|
||||
if (!g.lru.plan(il, ids.data(), ids.size(), n_tokens, n_used, n_zero, n_cpu, fills, cpu, n_hit)) {
|
||||
GGML_ABORT("the MoE cache is too small for the experts selected in layer %d", il);
|
||||
}
|
||||
if (has_cpu) {
|
||||
@@ -933,6 +937,8 @@ llama_moe_cache_lookup llama_moe_cache::build_lookup(const llm_graph_context & g
|
||||
ggml_backend_sched_set_tensor_backend(g.sched, slots, pimpl->backend(il));
|
||||
g.cb(slots, "ffn_moe_slots", il);
|
||||
|
||||
pimpl->layers[il].n_used = (int32_t) selected_experts->ne[0];
|
||||
|
||||
// add the lookup now: the transform of a Hadamard-folded expert reads host weights and would start its split first
|
||||
ggml_build_forward_expand(g.gf, slots);
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ bailingmoe3 ,1 ,any ,GATED_DELTA_NET+CPY , 1
|
||||
bailingmoe3 ,1 ,any ,MUL+ADD , 2
|
||||
bailingmoe3 ,1 ,any ,RMS_NORM+MUL , 8
|
||||
bailingmoe3 ,1 ,any ,RMS_NORM+SCALE , 2
|
||||
bailingmoe3 ,1 ,any ,SSM_CONV+UNARY , 3
|
||||
bailingmoe3 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
beam ,1 ,any ,MUL+ADD , 6
|
||||
beam ,1 ,any ,RMS_NORM+MUL , 25
|
||||
|
||||
|
@@ -10466,11 +10466,14 @@ struct test_flash_attn_ext_indexed_bias : public test_case {
|
||||
const ggml_type type_KV;
|
||||
const float logit_softcap;
|
||||
const bool mask_row; // query 0 of each stream sees no key
|
||||
const bool causal; // prefix of 0 per query, -inf after, distance bins
|
||||
const int64_t n_kv_max; // sparse hint
|
||||
|
||||
std::vector<int32_t> rows;
|
||||
std::vector<int64_t> visible;
|
||||
|
||||
std::string vars() override {
|
||||
return VARS_TO_STR12(hs, nh, gqa, kv, nb, n_stream, n_bins, kv_rows, sinks, type_KV, logit_softcap, mask_row);
|
||||
return VARS_TO_STR14(hs, nh, gqa, kv, nb, n_stream, n_bins, kv_rows, sinks, type_KV, logit_softcap, mask_row, causal, n_kv_max);
|
||||
}
|
||||
|
||||
double max_nmse_err() override {
|
||||
@@ -10479,9 +10482,9 @@ struct test_flash_attn_ext_indexed_bias : public test_case {
|
||||
|
||||
test_flash_attn_ext_indexed_bias(int64_t hs = 128, int64_t nh = 2, int64_t gqa = 3, int64_t kv = 768, int64_t nb = 7, int64_t n_stream = 2,
|
||||
int64_t n_bins = 17, bool kv_rows = false, bool sinks = true, ggml_type type_KV = GGML_TYPE_F16,
|
||||
float logit_softcap = 0.0f, bool mask_row = false)
|
||||
float logit_softcap = 0.0f, bool mask_row = false, bool causal = false, int64_t n_kv_max = 0)
|
||||
: hs(hs), nh(nh), gqa(gqa), kv(kv), nb(nb), n_stream(n_stream), n_bins(n_bins), kv_rows(kv_rows), sinks(sinks), type_KV(type_KV),
|
||||
logit_softcap(logit_softcap), mask_row(mask_row) {}
|
||||
logit_softcap(logit_softcap), mask_row(mask_row), causal(causal), n_kv_max(n_kv_max) {}
|
||||
|
||||
ggml_tensor * build_graph(ggml_context * ctx) override {
|
||||
ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, hs, nb, nh*gqa, n_stream);
|
||||
@@ -10514,6 +10517,7 @@ struct test_flash_attn_ext_indexed_bias : public test_case {
|
||||
ggml_flash_attn_ext_add_sinks(out, s);
|
||||
}
|
||||
ggml_flash_attn_ext_add_indexed_bias(out, table, indices);
|
||||
ggml_flash_attn_ext_set_n_kv_max(out, n_kv_max);
|
||||
ggml_prec_set_acc(out, GGML_PREC_F32);
|
||||
ggml_set_name(out, "out");
|
||||
|
||||
@@ -10538,18 +10542,33 @@ struct test_flash_attn_ext_indexed_bias : public test_case {
|
||||
}
|
||||
}
|
||||
|
||||
visible.assign(nb*n_stream, kv);
|
||||
if (causal) {
|
||||
for (int64_t s = 0; s < n_stream; ++s) {
|
||||
for (int64_t j = 0; j < nb; ++j) {
|
||||
visible[s*nb + j] = kv/2 + (j + 1)*(kv/2)/nb - 37*s;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
|
||||
if (strcmp(t->name, "r") == 0) {
|
||||
ggml_backend_tensor_set(t, rows.data(), 0, rows.size()*sizeof(int32_t));
|
||||
} else if (strcmp(t->name, "m") == 0 && n_kv_max > 0) {
|
||||
init_tensor_kq_mask_sparse(t, n_kv_max);
|
||||
} else if (strcmp(t->name, "m") == 0) {
|
||||
std::vector<float> f(ggml_nelements(t));
|
||||
std::uniform_real_distribution<float> dis(-1.0f, 1.0f);
|
||||
for (int64_t s = 0; s < n_stream; ++s) {
|
||||
for (int64_t j = 0; j < nb; ++j) {
|
||||
for (int64_t i = 0; i < kv; ++i) {
|
||||
const bool pad = kv_rows && rows[s*kv + i] < 0;
|
||||
const bool drop = (i + 3*j + 5*s) % 11 == 0 || (mask_row && j == 0);
|
||||
f[(s*nb + j)*kv + i] = pad || drop ? -INFINITY : dis(gen);
|
||||
const bool masked = (kv_rows && rows[s*kv + i] < 0) || (mask_row && j == 0);
|
||||
if (causal) {
|
||||
f[(s*nb + j)*kv + i] = masked || i >= visible[s*nb + j] ? -INFINITY : 0.0f;
|
||||
continue;
|
||||
}
|
||||
const bool drop = (i + 3*j + 5*s) % 11 == 0;
|
||||
f[(s*nb + j)*kv + i] = masked || drop ? -INFINITY : dis(gen);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10562,6 +10581,14 @@ struct test_flash_attn_ext_indexed_bias : public test_case {
|
||||
for (auto & i : idx) {
|
||||
i = dis(gen);
|
||||
}
|
||||
if (causal) {
|
||||
for (int64_t q = 0; q < nb*n_stream; ++q) {
|
||||
for (int64_t i = 0; i < kv; ++i) {
|
||||
const int64_t dist = visible[q] - 1 - i;
|
||||
idx[q*kv + i] = dist < 0 ? n_bins - 1 : (int32_t) std::min<int64_t>(dist, n_bins - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
ggml_backend_tensor_set(t, idx.data(), 0, idx.size()*sizeof(int32_t));
|
||||
} else if (strcmp(t->name, "table") == 0) {
|
||||
init_tensor_uniform(t, -4.0f, 4.0f);
|
||||
@@ -13424,6 +13451,8 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
|
||||
test_cases.emplace_back(new test_mul_mat_id_w4a8(GGML_TYPE_NVFP4, GGML_TYPE_F32, 4, 2, true, 64, 16, 256));
|
||||
test_cases.emplace_back(new test_mul_mat_id_w4a4(GGML_TYPE_NVFP4, GGML_TYPE_F32, 8, 2, false, 32, 32, 256));
|
||||
test_cases.emplace_back(new test_mul_mat_id_w4a4(GGML_TYPE_NVFP4, GGML_TYPE_F32, 4, 2, true, 64, 16, 256));
|
||||
// stream-k fixup with a partial column tile
|
||||
test_cases.emplace_back(new test_mul_mat_id_w4a4(GGML_TYPE_NVFP4, GGML_TYPE_F32, 4, 4, false, 32, 17, 1024));
|
||||
test_cases.emplace_back(new test_mul_mat_w4a8(GGML_TYPE_MXFP4, GGML_TYPE_F32, 32, 32, 256));
|
||||
test_cases.emplace_back(new test_mul_mat_w4a8(GGML_TYPE_MXFP4, GGML_TYPE_F32, 64, 16, 512));
|
||||
test_cases.emplace_back(new test_mul_mat_w4a4(GGML_TYPE_MXFP4, GGML_TYPE_F32, 32, 32, 256));
|
||||
@@ -14866,6 +14895,22 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
|
||||
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, nb, 2, 17, kv_rows, false, GGML_TYPE_F16, 0.0f, true));
|
||||
}
|
||||
}
|
||||
for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0}) {
|
||||
for (int64_t nb : {1, 4, 64}) {
|
||||
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 2048, nb, 2, 33, false, true, type, 0.0f, false, true));
|
||||
}
|
||||
}
|
||||
for (int64_t nb : {1, 4}) {
|
||||
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 4096, nb, 2, 33, false, true, GGML_TYPE_F16, 0.0f, false, false, 512));
|
||||
}
|
||||
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(256, 2, 3, 768, 65, 2, 17));
|
||||
for (int64_t hs : {128, 256}) {
|
||||
for (int64_t nb : {1, 7, 65}) {
|
||||
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(hs, 2, 3, 1000, nb, 2, 17));
|
||||
}
|
||||
}
|
||||
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 8, 3, 1100, 256, 2, 33, false, true, GGML_TYPE_F16, 0.0f, false, true));
|
||||
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 1100, 7, 2, 33, false, true, GGML_TYPE_Q8_0));
|
||||
|
||||
// sparse mask with large batch size
|
||||
test_cases.emplace_back(new test_flash_attn_ext(512, 512, 1, { 8, 1}, 4096, 64, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 512));
|
||||
|
||||
+8
-4
@@ -5,10 +5,11 @@ The UI of llama.cpp: the packages in `lib` and the apps built on them.
|
||||
```text
|
||||
ui/
|
||||
├── lib/
|
||||
│ ├── ui/ @ggml-org/llama-ui: design tokens, fonts, surfaces and components
|
||||
│ ├── voice/ @ggml-org/llama-voice: microphone capture, transcription and dictation
|
||||
│ ├── harness/ @ggml-org/llama-harness: the agentic loop, headless
|
||||
│ └── demo/ @ggml-org/llama-demo: scripted demo videos for PRs and docs
|
||||
│ ├── ui/ @ggml-org/llama-ui: design tokens, fonts, surfaces and components
|
||||
│ ├── voice/ @ggml-org/llama-voice: microphone capture, transcription and dictation
|
||||
│ ├── harness/ @ggml-org/llama-harness: the agentic loop, headless
|
||||
│ ├── demo/ @ggml-org/llama-demo: scripted demo videos for PRs and docs
|
||||
│ └── huggingface/ @ggml-org/llama-huggingface: a Hugging Face account, and sharing to it
|
||||
└── apps/
|
||||
└── chat/ Llama Chat, the chat app that llama-server serves
|
||||
```
|
||||
@@ -24,6 +25,9 @@ ui/
|
||||
- [`lib/demo`](lib/demo/README.md) records scripted demo videos of the apps for PRs and docs, and renders them on the
|
||||
Llama brand. It is Node TypeScript that an app adds as a local `file:` dependency and imports by name, with the app's own
|
||||
Playwright; it is private, not published to npm.
|
||||
- [`lib/huggingface`](lib/huggingface/README.md) gives an app a Hugging Face account: signing in from the browser,
|
||||
and sharing a conversation to a dataset as an agent trace, with the components for both. It knows no app; apps in
|
||||
this repo compile its sources too. It is not published yet.
|
||||
- [`apps/chat`](apps/chat/README.md) talks to llama-server, stores conversations and runs the agentic loop through the
|
||||
harness. CMake builds it into llama-server (see `scripts/ui-assets.cmake`), and it is published to npm as
|
||||
`@ggml-org/llama-chat` (with `llama-chat` as its short name), so `npx llama-chat` runs it against any llama-server.
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
VITE_PUBLIC_APP_NAME='Llama Chat'
|
||||
# 'false' builds a chat-only app: no tools, no MCP, no agentic loop
|
||||
# VITE_PUBLIC_AGENTIC='false'
|
||||
# 'true' builds an app with sharing conversations to Hugging Face, and its sign-in; a build
|
||||
# has neither without it, the dev server has both unless this is 'false'
|
||||
# VITE_PUBLIC_HUGGING_FACE='true'
|
||||
VITE_DEBUG='true'
|
||||
VITE_PUBLIC_SERVER_ORIGIN='http://localhost:8033'
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ set(TARGET llama-ui)
|
||||
|
||||
set(LLAMA_UI_HF_BUCKET "ggml-org/llama-ui" CACHE STRING "Hugging Face bucket name for prebuilt UI assets")
|
||||
set(LLAMA_UI_GZIP ON CACHE BOOL "Apply gzip compress to assets to save bandwidth")
|
||||
set(LLAMA_UI_HUGGING_FACE OFF CACHE BOOL "Include sharing conversations to Hugging Face, and its sign-in, in a UI built from source (the prebuilt UI has them)")
|
||||
|
||||
# Backward compat: forward old var to new one
|
||||
if(DEFINED LLAMA_BUILD_WEBUI)
|
||||
@@ -79,6 +80,7 @@ add_custom_target(llama-ui-assets ALL
|
||||
"-DHF_ENABLED=${LLAMA_USE_PREBUILT_UI}"
|
||||
"-DBUILD_UI=${LLAMA_BUILD_UI}"
|
||||
"-DLLAMA_UI_GZIP=${LLAMA_UI_GZIP}"
|
||||
"-DLLAMA_UI_HUGGING_FACE=${LLAMA_UI_HUGGING_FACE}"
|
||||
-P "${PROJECT_SOURCE_DIR}/scripts/ui-assets.cmake"
|
||||
COMMENT "Provisioning UI assets"
|
||||
VERBATIM
|
||||
|
||||
@@ -715,6 +715,9 @@ here; if something really is missing, add it here first.
|
||||
- **Sizes:** Tailwind's 4px spacing scale. Icons are Lucide, `size-icon-md` (16px), or
|
||||
`size-icon-sm` (14px) in compact controls. Controls are `h-control-sm`, `h-control-md` or
|
||||
`h-control-lg` (32, 36, 40px).
|
||||
- **Sharing:** anything that shares out of the app (an action, a button, a dialog title) uses
|
||||
one icon, Lucide's `Share`: a box with an arrow leaving it (`SHARE_ICON`). Never `Share2`,
|
||||
the three joined dots.
|
||||
- **Surfaces:** one surface utility per element (`card-surface`, `matte-float`, `matte-key`,
|
||||
`matte-well`), never raw `shadow-*`, `border-*` and `backdrop-blur-*` combinations.
|
||||
- **Tokens:** read a semantic token directly. A component token is only for a value the
|
||||
|
||||
+14
-11
@@ -92,17 +92,18 @@ Llama Chat is the first app on Llama UI, and the reference for the line between
|
||||
|
||||
The app imports the library as `@ggml-org/llama-ui/ui/<name>` and compiles its sources in its own build, with no install of the library (see `scripts/vite-plugin-llama-ui.ts`). Data flows one way, through these layers:
|
||||
|
||||
| Layer | Lives in | What it holds |
|
||||
| -------------- | ------------------------- | ---------------------------------------------------------------------------------------------------- |
|
||||
| Routes | `src/routes` | `/`, `/chat/[id]`, `/models`, `/mcp-servers`, `/settings`, `/search` |
|
||||
| App components | `src/lib/components/app` | Chat, navigation, models, MCP, settings and dialogs, grouped by area |
|
||||
| UI components | `ui/lib/ui` | shadcn-svelte on bits-ui, from Llama UI |
|
||||
| Voice | `ui/lib/voice` | Microphone capture, transcription and dictation, from Llama Voice (`@ggml-org/llama-voice`) |
|
||||
| Hooks | `src/lib/hooks` | View logic between components and stores: scroll, drag and drop, pickers, keyboard |
|
||||
| Stores | `src/lib/stores` | Application state as Svelte 5 runes: chat, conversations, the agentic loop, tools, models, settings |
|
||||
| Agentic loop | `ui/lib/harness` | Llama Harness: streams a turn, runs the tools the model called, repeats until it answers without one |
|
||||
| Services | `src/lib/services` | Stateless I/O: the llama-server API, IndexedDB, MCP, the Hugging Face Hub, the tool sandbox |
|
||||
| Storage + API | the browser, llama-server | IndexedDB and localStorage; llama-server's `/v1`, `/props`, `/models`, `/tools`, `/slots` |
|
||||
| Layer | Lives in | What it holds |
|
||||
| -------------- | ------------------------- | --------------------------------------------------------------------------------------------------------- |
|
||||
| Routes | `src/routes` | `/`, `/chat/[id]`, `/models`, `/mcp-servers`, `/settings`, `/search` |
|
||||
| App components | `src/lib/components/app` | Chat, navigation, models, MCP, settings and dialogs, grouped by area |
|
||||
| UI components | `ui/lib/ui` | shadcn-svelte on bits-ui, from Llama UI |
|
||||
| Voice | `ui/lib/voice` | Microphone capture, transcription and dictation, from Llama Voice (`@ggml-org/llama-voice`) |
|
||||
| Hugging Face | `ui/lib/huggingface` | A Hugging Face account: sign-in and sharing conversations as agent traces (`@ggml-org/llama-huggingface`) |
|
||||
| Hooks | `src/lib/hooks` | View logic between components and stores: scroll, drag and drop, pickers, keyboard |
|
||||
| Stores | `src/lib/stores` | Application state as Svelte 5 runes: chat, conversations, the agentic loop, tools, models, settings |
|
||||
| Agentic loop | `ui/lib/harness` | Llama Harness: streams a turn, runs the tools the model called, repeats until it answers without one |
|
||||
| Services | `src/lib/services` | Stateless I/O: the llama-server API, IndexedDB, MCP, the Hugging Face Hub, the tool sandbox |
|
||||
| Storage + API | the browser, llama-server | IndexedDB and localStorage; llama-server's `/v1`, `/props`, `/models`, `/tools`, `/slots` |
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
@@ -166,6 +167,8 @@ llama-server embeds it: when llama-server is built, `scripts/ui-assets.cmake` ta
|
||||
|
||||
**Chat-only build.** `VITE_PUBLIC_AGENTIC=false npm run build` builds an app that is a plain chat for every server, and `npm run dev:chat-only` runs the dev server the same way. Llama Harness's loop is left out of its bundle.
|
||||
|
||||
**Sharing to Hugging Face.** Sharing a conversation to a Hugging Face dataset, and the sign-in it needs, is in the builds we release: the prebuilt UI llama-server downloads, the llama-server Docker images and the npm package. A build of your own leaves it out unless you ask for it: `npm run build` bundles an app without `@ggml-org/llama-huggingface`, whose sign-in, upload and dialogs are then not in it, and the app offers no sharing; `VITE_PUBLIC_HUGGING_FACE=true npm run build` bundles one with it. The dev server, the tests and Storybook have it. To embed a UI with it that llama-server builds from source (`-DLLAMA_BUILD_UI=ON`), configure with `-DLLAMA_UI_HUGGING_FACE=ON`; it builds again when the option changes, and the default prebuilt UI has the sharing whatever the option. A Docker image takes `--build-arg VITE_PUBLIC_HUGGING_FACE=true`. A `dist/` you put in `ui/apps/chat` is embedded as it is.
|
||||
|
||||
```text
|
||||
ui/apps/chat/
|
||||
├── src/
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "llama-chat",
|
||||
"version": "0.3.1",
|
||||
"version": "0.4.0",
|
||||
"description": "npx llama-chat: runs Llama Chat, the chat app for llama.cpp. Same as npx @ggml-org/llama-chat.",
|
||||
"keywords": [
|
||||
"llama.cpp",
|
||||
@@ -28,6 +28,6 @@
|
||||
"node": ">=20"
|
||||
},
|
||||
"dependencies": {
|
||||
"@ggml-org/llama-chat": "0.3.1"
|
||||
"@ggml-org/llama-chat": "0.4.0"
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@ggml-org/llama-chat",
|
||||
"version": "0.3.1",
|
||||
"version": "0.4.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@ggml-org/llama-chat",
|
||||
"version": "0.3.1",
|
||||
"version": "0.4.0",
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"llama-chat": "bin/cli.js"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ggml-org/llama-chat",
|
||||
"version": "0.3.1",
|
||||
"version": "0.4.0",
|
||||
"description": "Llama Chat, the chat app for llama.cpp. Run it with npx @ggml-org/llama-chat against any llama-server.",
|
||||
"keywords": [
|
||||
"llama.cpp",
|
||||
|
||||
@@ -8,6 +8,8 @@ set(UI_SOURCE_GLOBS
|
||||
# Llama Voice, also compiled from source
|
||||
../../lib/voice/src/*
|
||||
../../lib/harness/src/*
|
||||
# and Llama Hugging Face
|
||||
../../lib/huggingface/src/*
|
||||
)
|
||||
|
||||
set(UI_SOURCE_FILES
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
which this Storybook shows as well */
|
||||
@source '../tests/stories';
|
||||
@source '../../../lib/ui/tests/stories';
|
||||
/* Llama Hugging Face's components (ui/lib/huggingface), compiled as part of this app */
|
||||
@source '../../../lib/huggingface/src';
|
||||
@plugin '@tailwindcss/forms';
|
||||
@plugin '@tailwindcss/typography';
|
||||
@import 'tw-animate-css';
|
||||
|
||||
+11
-1
@@ -9,6 +9,7 @@
|
||||
} from '#lib/components/app/chat/index.ts';
|
||||
import {
|
||||
AGENTIC_TEXT_COPY_SEPARATOR,
|
||||
HUGGING_FACE_ENABLED,
|
||||
REASONING_TAGS,
|
||||
ROUTES,
|
||||
SYSTEM_MESSAGE_PLACEHOLDER
|
||||
@@ -21,7 +22,7 @@
|
||||
MessageType
|
||||
} from '#lib/enums/index.ts';
|
||||
import { DatabaseService } from '#lib/services/database.service.ts';
|
||||
import { chatStore, conversationsStore, deviceStore } from '#lib/stores/index.ts';
|
||||
import { chatStore, conversationsStore, deviceStore, uiStore } from '#lib/stores/index.ts';
|
||||
import type {
|
||||
ChatMessageActions,
|
||||
ChatMessageDeletionInfo,
|
||||
@@ -197,6 +198,7 @@
|
||||
setShowForkDialog: (show: boolean) => {
|
||||
showForkDialog = show;
|
||||
},
|
||||
share: HUGGING_FACE_ENABLED ? handleShare : undefined,
|
||||
get showDeleteDialog() {
|
||||
return showDeleteDialog;
|
||||
},
|
||||
@@ -339,6 +341,14 @@
|
||||
chatActions.forkConversation(message, options);
|
||||
}
|
||||
|
||||
// an agentic turn renders as one message, so a share from it ends at its last step
|
||||
function handleShare() {
|
||||
uiStore.openConversationShare({
|
||||
conversationId: message.convId,
|
||||
messageId: toolMessages.at(-1)?.id ?? message.id
|
||||
});
|
||||
}
|
||||
|
||||
function handleNavigateToSibling(siblingId: string) {
|
||||
chatActions.navigateToSibling(siblingId);
|
||||
}
|
||||
|
||||
+9
@@ -9,6 +9,7 @@
|
||||
ChatMessageActionIconsBranchingControls,
|
||||
DialogConfirmation
|
||||
} from '#lib/components/app/index.ts';
|
||||
import { SHARE_ACTION } from '#lib/constants/index.ts';
|
||||
import { getChatMessageActionsContext, getChatMessageEditContext } from '#lib/contexts/index.ts';
|
||||
import { conversationsStore } from '#lib/stores/index.ts';
|
||||
import { untrack } from 'svelte';
|
||||
@@ -97,6 +98,14 @@
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if messageActions.share}
|
||||
<ActionIcon
|
||||
icon={SHARE_ACTION.icon}
|
||||
onclick={messageActions.share}
|
||||
tooltip={SHARE_ACTION.label}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<ActionIcon icon={Trash2} onclick={messageActions.requestDelete} tooltip="Delete" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+2
-1
@@ -1,7 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { ArrowRight, Copy, Edit, GitBranch, RefreshCw, Trash2 } from '@lucide/svelte';
|
||||
import { ContextMenuActions } from '#lib/components/app/index.ts';
|
||||
import { NATIVE_CONTEXT_MENU_SELECTOR } from '#lib/constants/index.ts';
|
||||
import { NATIVE_CONTEXT_MENU_SELECTOR, SHARE_ACTION } from '#lib/constants/index.ts';
|
||||
import { getChatMessageActionsContext, getChatMessageEditContext } from '#lib/contexts/index.ts';
|
||||
import { MessageRole } from '#lib/enums/index.ts';
|
||||
import type { MenuAction } from '#lib/types/index.ts';
|
||||
@@ -39,6 +39,7 @@
|
||||
}
|
||||
]
|
||||
: []),
|
||||
...(messageActions.share ? [{ ...SHARE_ACTION, onclick: messageActions.share }] : []),
|
||||
{
|
||||
icon: Trash2,
|
||||
label: 'Delete',
|
||||
|
||||
@@ -2,7 +2,11 @@
|
||||
import ChatTabsItem from './ChatTabsItem.svelte';
|
||||
import ChatTabsNewChatButton from './ChatTabsNewChatButton.svelte';
|
||||
import { ArrowRightToLine, ListX, Square, SquarePen, X } from '@lucide/svelte';
|
||||
import { ContextMenuActions, ScrollCarousel } from '#lib/components/app/index.ts';
|
||||
import {
|
||||
ContextMenuActions,
|
||||
ConversationActions,
|
||||
ScrollCarousel
|
||||
} from '#lib/components/app/index.ts';
|
||||
import {
|
||||
CHAT_TABS_MAX_WIDTH,
|
||||
NEW_CHAT_LABEL,
|
||||
@@ -25,16 +29,20 @@
|
||||
let activeId = $derived(view.activeId);
|
||||
|
||||
let tabs = $derived(
|
||||
view.ids.map((id) =>
|
||||
id === NEW_CHAT_TAB_ID
|
||||
? { href: view.hrefFor(id), icon: SquarePen, id, name: NEW_CHAT_LABEL }
|
||||
: {
|
||||
href: view.hrefFor(id),
|
||||
id,
|
||||
name:
|
||||
conversationsStore.conversations.find((c) => c.id === id)?.name ?? UNNAMED_CHAT_LABEL
|
||||
}
|
||||
)
|
||||
view.ids.map((id) => {
|
||||
if (id === NEW_CHAT_TAB_ID) {
|
||||
return { href: view.hrefFor(id), icon: SquarePen, id, name: NEW_CHAT_LABEL };
|
||||
}
|
||||
|
||||
const conversation = conversationsStore.conversations.find((c) => c.id === id);
|
||||
|
||||
return {
|
||||
conversation,
|
||||
href: view.hrefFor(id),
|
||||
id,
|
||||
name: conversation?.name ?? UNNAMED_CHAT_LABEL
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
// hide the New chat button while a new-chat tab is already open
|
||||
@@ -126,6 +134,20 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
{#snippet tabItem(tab: (typeof tabs)[number], actions: MenuAction[])}
|
||||
<ContextMenuActions {actions}>
|
||||
<ChatTabsItem
|
||||
isActive={tab.id === activeId}
|
||||
isLoading={loadingIds.has(tab.id)}
|
||||
onActivate={(id) => tabsStore.activate(id)}
|
||||
onAuxClick={handleAuxClick}
|
||||
onClose={handleClose}
|
||||
onStop={handleStop}
|
||||
{tab}
|
||||
/>
|
||||
</ContextMenuActions>
|
||||
{/snippet}
|
||||
|
||||
<nav
|
||||
aria-label="Open conversations"
|
||||
class={[
|
||||
@@ -143,17 +165,21 @@
|
||||
innerClass="items-center gap-1.25"
|
||||
>
|
||||
{#each tabs as tab (tab.id)}
|
||||
<ContextMenuActions actions={tabActions(tab.id)}>
|
||||
<ChatTabsItem
|
||||
<!-- a chat's tab also offers what its sidebar row does, after the tab's own actions -->
|
||||
{#if tab.conversation}
|
||||
<ConversationActions
|
||||
conversation={tab.conversation}
|
||||
isActive={tab.id === activeId}
|
||||
isLoading={loadingIds.has(tab.id)}
|
||||
onActivate={(id) => tabsStore.activate(id)}
|
||||
onAuxClick={handleAuxClick}
|
||||
onClose={handleClose}
|
||||
onStop={handleStop}
|
||||
{tab}
|
||||
/>
|
||||
</ContextMenuActions>
|
||||
leadingActions={tabActions(tab.id)}
|
||||
showOpenInNewTab={false}
|
||||
>
|
||||
{#snippet children(actions)}
|
||||
{@render tabItem(tab, actions)}
|
||||
{/snippet}
|
||||
</ConversationActions>
|
||||
{:else}
|
||||
{@render tabItem(tab, tabActions(tab.id))}
|
||||
{/if}
|
||||
{/each}
|
||||
|
||||
{#if showNewChatButton}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
<script lang="ts">
|
||||
import type { HfShareScope, HfTraceFile } from '@ggml-org/llama-huggingface';
|
||||
import { HfShareDialog } from '@ggml-org/llama-huggingface/svelte';
|
||||
import { CONVERSATION_SHARE_TEXT as TEXT, HUGGING_FACE_ENABLED } from '#lib/constants/index.ts';
|
||||
import { ConversationShareScope } from '#lib/enums/index.ts';
|
||||
import { ConversationTransferService } from '#lib/services/conversation-transfer.service.ts';
|
||||
import { conversationsStore, huggingFace, uiStore } from '#lib/stores/index.ts';
|
||||
import {
|
||||
buildConversationTrace,
|
||||
buildTracePreview,
|
||||
copyToClipboard,
|
||||
filterByLeafNodeId
|
||||
} from '#lib/utils/index.ts';
|
||||
import { toast } from 'svelte-sonner';
|
||||
|
||||
// what a conversation is, for the share dialog: its branches as scopes, and its trace
|
||||
|
||||
let options = $derived(uiStore.conversationShare);
|
||||
let conversation = $derived(
|
||||
conversationsStore.conversations.find((conv) => conv.id === options?.conversationId)
|
||||
);
|
||||
|
||||
let messages = $state<DatabaseMessage[]>([]);
|
||||
|
||||
$effect.pre(() => {
|
||||
const conversationId = options?.conversationId;
|
||||
|
||||
messages = [];
|
||||
|
||||
if (!conversationId) return;
|
||||
|
||||
void conversationsStore.getConversationMessages(conversationId).then((loaded) => {
|
||||
if (uiStore.conversationShare?.conversationId === conversationId) messages = loaded;
|
||||
});
|
||||
});
|
||||
|
||||
function scopeOf(id: ConversationShareScope, label: string, leafId: string): HfShareScope {
|
||||
const path = filterByLeafNodeId(messages, leafId);
|
||||
|
||||
return {
|
||||
// nothing to count while the messages load
|
||||
detail: path.length ? TEXT.messageCount(path.length) : undefined,
|
||||
hasAttachments: path.some((message) => !!message.extra?.length),
|
||||
id,
|
||||
isEmpty: !path.length,
|
||||
label
|
||||
};
|
||||
}
|
||||
|
||||
let scopes = $derived([
|
||||
...(options?.messageId
|
||||
? [scopeOf(ConversationShareScope.UP_TO_MESSAGE, TEXT.SCOPE_UP_TO_MESSAGE, options.messageId)]
|
||||
: []),
|
||||
scopeOf(ConversationShareScope.ALL, TEXT.SCOPE_ALL, conversation?.currNode ?? '')
|
||||
]);
|
||||
|
||||
async function buildTrace(scope: string, includeAttachments: boolean): Promise<HfTraceFile> {
|
||||
const conversationId = options?.conversationId ?? '';
|
||||
const [exported] = await conversationsStore.getConversationsForExport([conversationId]);
|
||||
|
||||
if (!exported) throw new Error(TEXT.CONVERSATION_NOT_FOUND);
|
||||
|
||||
const trace = buildConversationTrace(exported, {
|
||||
includeAttachments,
|
||||
upToMessageId: scope === ConversationShareScope.UP_TO_MESSAGE ? options?.messageId : undefined
|
||||
});
|
||||
|
||||
return {
|
||||
commitMessage: TEXT.commitMessage(trace.conv.name),
|
||||
content: ConversationTransferService.serializeSessionToJsonl(trace),
|
||||
path: ConversationTransferService.generateConversationFilename(trace.conv, trace.messages),
|
||||
preview: buildTracePreview(trace)
|
||||
};
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if HUGGING_FACE_ENABLED}
|
||||
<HfShareDialog
|
||||
bind:open={() => options !== null, (open) => !open && (uiStore.conversationShare = null)}
|
||||
account={huggingFace}
|
||||
{buildTrace}
|
||||
onCopyLink={(url) => void copyToClipboard(url, TEXT.LINK_COPIED)}
|
||||
onShared={() => toast.success(TEXT.SHARED)}
|
||||
{scopes}
|
||||
subject={conversation ? TEXT.subject(conversation.name) : TEXT.SUBJECT_FALLBACK}
|
||||
/>
|
||||
{/if}
|
||||
@@ -145,6 +145,16 @@ export { default as DialogConversationDelete } from './DialogConversationDelete.
|
||||
*/
|
||||
export { default as DialogConversationRename } from './DialogConversationRename.svelte';
|
||||
|
||||
/**
|
||||
* **DialogConversationShare** - Share a conversation to Hugging Face
|
||||
*
|
||||
* Uploads a conversation, or its branch up to a message, to a dataset of the user's Hugging
|
||||
* Face account as an agent trace. The dialog itself (sign-in, dataset picker, upload) is
|
||||
* `HfShareDialog` of @ggml-org/llama-huggingface; this component says what a conversation is:
|
||||
* its scopes and its trace. It opens from `uiStore.conversationShare`, so it is mounted once.
|
||||
*/
|
||||
export { default as DialogConversationShare } from './DialogConversationShare.svelte';
|
||||
|
||||
/**
|
||||
* **DialogGroup** - Name a new sidebar group, or rename one
|
||||
*
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
<script lang="ts">
|
||||
import SidebarNavigationGroupSubmenu from './SidebarNavigation/SidebarNavigationGroupSubmenu.svelte';
|
||||
import {
|
||||
Download,
|
||||
FolderInput,
|
||||
ListChecks,
|
||||
PanelTopOpen,
|
||||
Pencil,
|
||||
Pin,
|
||||
PinOff,
|
||||
Trash2,
|
||||
Unlink
|
||||
} from '@lucide/svelte';
|
||||
import {
|
||||
HUGGING_FACE_ENABLED,
|
||||
SHARE_ACTION,
|
||||
SHORTCUT_DELETE_CONVERSATION,
|
||||
SHORTCUT_EDIT_CONVERSATION,
|
||||
SHORTCUT_EXPORT_CONVERSATION
|
||||
} from '#lib/constants/index.ts';
|
||||
import type { MenuKind } from '#lib/enums/index.ts';
|
||||
import {
|
||||
conversationsStore,
|
||||
groupsStore,
|
||||
settingsStore,
|
||||
tabsStore,
|
||||
uiStore
|
||||
} from '#lib/stores/index.ts';
|
||||
import type { MenuAction } from '#lib/types/index.ts';
|
||||
import type { Snippet } from 'svelte';
|
||||
|
||||
const MOVE_TO_GROUP_LABEL = 'Move to group';
|
||||
|
||||
interface Props {
|
||||
conversation: DatabaseConversation;
|
||||
/** The active conversation's menu shows the shortcuts, which act on it. */
|
||||
isActive?: boolean;
|
||||
/** Offer "Open in new tab"; a tab's own menu leaves it out. */
|
||||
showOpenInNewTab?: boolean;
|
||||
/** Actions of the caller's own, listed before the conversation's, with a separator between. */
|
||||
leadingActions?: MenuAction[];
|
||||
/** Enter the sidebar's selection mode; the action shows only when given. */
|
||||
onEnterSelectionMode?: () => void;
|
||||
/** Renders the menu that shows the actions. */
|
||||
children: Snippet<[MenuAction[]]>;
|
||||
}
|
||||
|
||||
let {
|
||||
children,
|
||||
conversation,
|
||||
isActive = false,
|
||||
leadingActions = [],
|
||||
onEnterSelectionMode,
|
||||
showOpenInNewTab = true
|
||||
}: Props = $props();
|
||||
|
||||
let canOpenInNewTab = $derived(
|
||||
showOpenInNewTab && Boolean(settingsStore.config.conversationTabs)
|
||||
);
|
||||
|
||||
// a group the chat points at may be gone; then it is in none
|
||||
let groupId = $derived(groupsStore.groupIdOf(conversation));
|
||||
|
||||
// menus sit on clickable rows and tabs, so an action must not also click them
|
||||
function run(action: () => void) {
|
||||
return (event: Event) => {
|
||||
event.stopPropagation();
|
||||
action();
|
||||
};
|
||||
}
|
||||
|
||||
function setGroup(groupId: string | null) {
|
||||
void conversationsStore.setConversationGroup(conversation.id, groupId);
|
||||
}
|
||||
|
||||
let conversationActions = $derived<MenuAction[]>([
|
||||
...(canOpenInNewTab
|
||||
? [
|
||||
{
|
||||
icon: PanelTopOpen,
|
||||
label: 'Open in new tab',
|
||||
onclick: run(() => void tabsStore.openInNewTab(conversation.id))
|
||||
}
|
||||
]
|
||||
: []),
|
||||
{
|
||||
icon: conversation.pinned ? PinOff : Pin,
|
||||
label: conversation.pinned ? 'Unpin' : 'Pin',
|
||||
onclick: run(() => void conversationsStore.toggleConversationPin(conversation.id)),
|
||||
separator: canOpenInNewTab
|
||||
},
|
||||
{
|
||||
icon: Pencil,
|
||||
label: 'Edit',
|
||||
onclick: run(() => uiStore.openConversationRename(conversation.id)),
|
||||
shortcut: isActive ? SHORTCUT_EDIT_CONVERSATION : undefined
|
||||
},
|
||||
// the picker stands in for the submenu where a phone's menu shows no flyouts
|
||||
{
|
||||
icon: FolderInput,
|
||||
label: MOVE_TO_GROUP_LABEL,
|
||||
onclick: run(() => uiStore.openGroupPicker({ currentGroupId: groupId, onSelect: setGroup })),
|
||||
submenu: groupSubmenu
|
||||
},
|
||||
...(groupId
|
||||
? [{ icon: Unlink, label: 'Remove from group', onclick: run(() => setGroup(null)) }]
|
||||
: []),
|
||||
{
|
||||
icon: Download,
|
||||
label: 'Export',
|
||||
onclick: run(() => void conversationsStore.downloadConversation(conversation.id)),
|
||||
shortcut: isActive ? SHORTCUT_EXPORT_CONVERSATION : undefined
|
||||
},
|
||||
...(HUGGING_FACE_ENABLED
|
||||
? [
|
||||
{
|
||||
...SHARE_ACTION,
|
||||
onclick: run(() => uiStore.openConversationShare({ conversationId: conversation.id }))
|
||||
}
|
||||
]
|
||||
: []),
|
||||
...(onEnterSelectionMode
|
||||
? [{ icon: ListChecks, label: 'Select', onclick: run(onEnterSelectionMode) }]
|
||||
: []),
|
||||
{
|
||||
icon: Trash2,
|
||||
label: 'Delete',
|
||||
onclick: run(() => uiStore.openConversationDelete(conversation.id)),
|
||||
separator: true,
|
||||
shortcut: isActive ? SHORTCUT_DELETE_CONVERSATION : undefined,
|
||||
variant: 'destructive'
|
||||
}
|
||||
]);
|
||||
|
||||
// the caller's own actions come first, and the conversation's start under a separator
|
||||
let actions = $derived<MenuAction[]>(
|
||||
leadingActions.length
|
||||
? [
|
||||
...leadingActions,
|
||||
{ ...conversationActions[0], separator: true },
|
||||
...conversationActions.slice(1)
|
||||
]
|
||||
: conversationActions
|
||||
);
|
||||
</script>
|
||||
|
||||
{@render children(actions)}
|
||||
|
||||
{#snippet groupSubmenu({ close, kind }: { close: () => void; kind: MenuKind })}
|
||||
<SidebarNavigationGroupSubmenu
|
||||
currentGroupId={groupId}
|
||||
{kind}
|
||||
label={MOVE_TO_GROUP_LABEL}
|
||||
onClose={close}
|
||||
onSelect={setGroup}
|
||||
/>
|
||||
{/snippet}
|
||||
+26
-35
@@ -5,6 +5,7 @@
|
||||
ActionIcon,
|
||||
DialogConversationDelete,
|
||||
DialogConversationRename,
|
||||
DialogConversationShare,
|
||||
DialogDiscoverModels,
|
||||
DialogGroup,
|
||||
DialogGroupPicker,
|
||||
@@ -45,7 +46,7 @@
|
||||
import { buildConversationTree, hapticTap, remToPx } from '#lib/utils/index.ts';
|
||||
import { goto } from '$app/navigation';
|
||||
import { page } from '$app/state';
|
||||
import { tick } from 'svelte';
|
||||
import { tick, untrack } from 'svelte';
|
||||
import { SvelteSet } from 'svelte/reactivity';
|
||||
import { fade } from 'svelte/transition';
|
||||
|
||||
@@ -172,11 +173,9 @@
|
||||
let isSelectionMode = $state(false);
|
||||
let selectedIds = new SvelteSet<string>();
|
||||
|
||||
let renameDialogOpen = $state(false);
|
||||
let settingsDialogOpen = $state(false);
|
||||
// a phone's settings: a sheet over the page, where a desktop or tablet opens the dialog
|
||||
let settingsSheetOpen = $state(false);
|
||||
let renameTargetConversationId = $state<string | null>(null);
|
||||
let renameDraft = $state('');
|
||||
let renameOriginalTitle = $state('');
|
||||
|
||||
@@ -314,19 +313,25 @@
|
||||
navigateBehind(() => goto(RouterService.chat(id)));
|
||||
}
|
||||
|
||||
async function handleEditConversation(id: string) {
|
||||
const conversation = conversationsStore.conversations.find((conv) => conv.id === id);
|
||||
// the sidebar hosts the rename and delete dialogs for every conversation menu, tabs included
|
||||
let renameTarget = $derived(
|
||||
conversationsStore.conversations.find((conv) => conv.id === uiStore.conversationRenameId)
|
||||
);
|
||||
|
||||
if (!conversation) return;
|
||||
let renameTargetId = $derived(renameTarget?.id);
|
||||
|
||||
renameTargetConversationId = id;
|
||||
renameOriginalTitle = conversation.name;
|
||||
renameDraft = conversation.name;
|
||||
renameDialogOpen = true;
|
||||
}
|
||||
// a fresh draft every time the rename dialog opens, not when the conversation changes under it
|
||||
$effect.pre(() => {
|
||||
if (!renameTargetId) return;
|
||||
|
||||
untrack(() => {
|
||||
renameOriginalTitle = renameTarget?.name ?? '';
|
||||
renameDraft = renameOriginalTitle;
|
||||
});
|
||||
});
|
||||
|
||||
async function handleRenameConfirm() {
|
||||
const id = renameTargetConversationId;
|
||||
const id = renameTarget?.id;
|
||||
|
||||
if (!id) return;
|
||||
|
||||
@@ -336,33 +341,19 @@
|
||||
|
||||
await conversationsStore.updateConversationName(id, nextName);
|
||||
|
||||
renameDialogOpen = false;
|
||||
renameTargetConversationId = null;
|
||||
uiStore.conversationRenameId = null;
|
||||
}
|
||||
|
||||
function handleRenameCancel() {
|
||||
renameDialogOpen = false;
|
||||
renameTargetConversationId = null;
|
||||
uiStore.conversationRenameId = null;
|
||||
renameDraft = '';
|
||||
renameOriginalTitle = '';
|
||||
}
|
||||
|
||||
let deleteDialogOpen = $state(false);
|
||||
let deleteTargetId = $state<string | null>(null);
|
||||
|
||||
function handleDeleteConversation(id: string) {
|
||||
const conversation = conversationsStore.conversations.find((conv) => conv.id === id);
|
||||
|
||||
if (!conversation) return;
|
||||
|
||||
deleteTargetId = conversation.id;
|
||||
deleteDialogOpen = true;
|
||||
}
|
||||
|
||||
async function handleDeleteConfirm() {
|
||||
const id = deleteTargetId;
|
||||
const id = uiStore.conversationDeleteId;
|
||||
|
||||
deleteDialogOpen = false;
|
||||
uiStore.conversationDeleteId = null;
|
||||
|
||||
if (!id) return;
|
||||
|
||||
@@ -370,7 +361,7 @@
|
||||
}
|
||||
|
||||
function handleDeleteCancel() {
|
||||
deleteDialogOpen = false;
|
||||
uiStore.conversationDeleteId = null;
|
||||
}
|
||||
|
||||
function handleStopGeneration(id: string) {
|
||||
@@ -688,8 +679,6 @@
|
||||
onBulkExport={handleBulkExport}
|
||||
onBulkPinToggle={handleBulkPinToggle}
|
||||
onCloseSelection={exitSelectionMode}
|
||||
onDelete={handleDeleteConversation}
|
||||
onEdit={handleEditConversation}
|
||||
onEnterSelectionMode={enterSelectionMode}
|
||||
onRowMouseDown={handleRowMouseDown}
|
||||
onSelect={selectConversation}
|
||||
@@ -771,7 +760,7 @@
|
||||
{/if}
|
||||
|
||||
<DialogConversationRename
|
||||
bind:open={renameDialogOpen}
|
||||
bind:open={() => !!renameTarget, (open) => !open && handleRenameCancel()}
|
||||
bind:value={renameDraft}
|
||||
currentTitle={renameOriginalTitle}
|
||||
onCancel={handleRenameCancel}
|
||||
@@ -779,7 +768,7 @@
|
||||
/>
|
||||
|
||||
<DialogConversationDelete
|
||||
bind:open={deleteDialogOpen}
|
||||
bind:open={() => uiStore.conversationDeleteId !== null, (open) => !open && handleDeleteCancel()}
|
||||
onCancel={handleDeleteCancel}
|
||||
onConfirm={handleDeleteConfirm}
|
||||
/>
|
||||
@@ -800,6 +789,8 @@
|
||||
|
||||
<DialogGroupPicker />
|
||||
|
||||
<DialogConversationShare />
|
||||
|
||||
<ModelsManagerModelDrawer />
|
||||
|
||||
<style>
|
||||
|
||||
+140
-262
@@ -1,41 +1,24 @@
|
||||
<script lang="ts">
|
||||
import SidebarNavigationGroupSubmenu from './SidebarNavigationGroupSubmenu.svelte';
|
||||
import { Checkbox } from '@ggml-org/llama-ui/ui/checkbox';
|
||||
import * as Tooltip from '@ggml-org/llama-ui/ui/tooltip';
|
||||
import { GitBranch, Loader2, MoreHorizontal, Square } from '@lucide/svelte';
|
||||
import {
|
||||
Download,
|
||||
FolderInput,
|
||||
GitBranch,
|
||||
ListChecks,
|
||||
Loader2,
|
||||
MoreHorizontal,
|
||||
PanelTopOpen,
|
||||
Pencil,
|
||||
Pin,
|
||||
PinOff,
|
||||
Square,
|
||||
Trash2,
|
||||
Unlink
|
||||
} from '@lucide/svelte';
|
||||
import { ContextMenuActions, DropdownMenuActions } from '#lib/components/app/index.ts';
|
||||
ContextMenuActions,
|
||||
ConversationActions,
|
||||
DropdownMenuActions
|
||||
} from '#lib/components/app/index.ts';
|
||||
import { TruncatedText } from '#lib/components/app/index.ts';
|
||||
import {
|
||||
FORK_TREE_DEPTH_PADDING,
|
||||
ICON_CLASS_DEFAULT,
|
||||
ROW_LONG_PRESS_MS,
|
||||
SHORTCUT_DELETE_CONVERSATION,
|
||||
SHORTCUT_EDIT_CONVERSATION,
|
||||
SHORTCUT_EXPORT_CONVERSATION,
|
||||
UI_DATA_ATTRS
|
||||
} from '#lib/constants/index.ts';
|
||||
import type { MenuKind } from '#lib/enums/index.ts';
|
||||
import { useLongPress } from '#lib/hooks/use-long-press.svelte.ts';
|
||||
import { RouterService } from '#lib/services/router.service.ts';
|
||||
import {
|
||||
chatStore,
|
||||
conversationsStore,
|
||||
deviceStore,
|
||||
groupsStore,
|
||||
settingsStore,
|
||||
sidebarDragStore,
|
||||
tabsStore,
|
||||
@@ -51,8 +34,6 @@
|
||||
conversation: DatabaseConversation;
|
||||
isSelectionMode?: boolean;
|
||||
isSelected?: boolean;
|
||||
onDelete?: (id: string) => void;
|
||||
onEdit?: (id: string) => void;
|
||||
onSelect?: (id: string) => void;
|
||||
onStop?: (id: string) => void;
|
||||
onToggleSelect?: (id: string) => void;
|
||||
@@ -67,8 +48,6 @@
|
||||
isActive = false,
|
||||
isSelected = false,
|
||||
isSelectionMode = false,
|
||||
onDelete,
|
||||
onEdit,
|
||||
onEnterSelectionMode,
|
||||
onRowMouseDown,
|
||||
onSelect,
|
||||
@@ -111,16 +90,6 @@
|
||||
sidebarDragStore.pressConversation(event, conversation.id);
|
||||
}
|
||||
|
||||
function handleEdit(event: Event) {
|
||||
event.stopPropagation();
|
||||
onEdit?.(conversation.id);
|
||||
}
|
||||
|
||||
function handleDelete(event: Event) {
|
||||
event.stopPropagation();
|
||||
onDelete?.(conversation.id);
|
||||
}
|
||||
|
||||
function handleStop(event: Event) {
|
||||
event.stopPropagation();
|
||||
onStop?.(conversation.id);
|
||||
@@ -140,102 +109,7 @@
|
||||
openInNewTab();
|
||||
}
|
||||
|
||||
function setGroup(groupId: string | null) {
|
||||
void conversationsStore.setConversationGroup(conversation.id, groupId);
|
||||
}
|
||||
|
||||
// a group the chat points at may be gone; then it is in none
|
||||
let groupId = $derived(groupsStore.groupIdOf(conversation));
|
||||
|
||||
// the picker stands in for the submenu where a phone's menu shows no flyouts
|
||||
function handlePickGroup(event: Event) {
|
||||
event.stopPropagation();
|
||||
uiStore.openGroupPicker({ currentGroupId: groupId, onSelect: setGroup });
|
||||
}
|
||||
|
||||
// a chat in a group can move to another one or leave it, a loose chat can join one
|
||||
let groupActions = $derived<MenuAction[]>([
|
||||
{
|
||||
icon: FolderInput,
|
||||
label: 'Move to group',
|
||||
onclick: handlePickGroup,
|
||||
submenu: groupSubmenu
|
||||
},
|
||||
...(groupId
|
||||
? [
|
||||
{
|
||||
icon: Unlink,
|
||||
label: 'Remove from group',
|
||||
onclick: (event: Event) => {
|
||||
event.stopPropagation();
|
||||
setGroup(null);
|
||||
}
|
||||
}
|
||||
]
|
||||
: [])
|
||||
]);
|
||||
|
||||
// the "more actions" dropdown and the right-click menu offer the same actions; the
|
||||
// shortcuts act on the active conversation, so only its row shows them
|
||||
let actions = $derived<MenuAction[]>([
|
||||
...(canOpenInNewTab
|
||||
? [
|
||||
{
|
||||
icon: PanelTopOpen,
|
||||
label: 'Open in new tab',
|
||||
onclick: (e: Event) => {
|
||||
e.stopPropagation();
|
||||
openInNewTab();
|
||||
}
|
||||
}
|
||||
]
|
||||
: []),
|
||||
{
|
||||
icon: conversation.pinned ? PinOff : Pin,
|
||||
label: conversation.pinned ? 'Unpin' : 'Pin',
|
||||
onclick: (e: Event) => {
|
||||
e.stopPropagation();
|
||||
handleTogglePin();
|
||||
},
|
||||
separator: canOpenInNewTab
|
||||
},
|
||||
{
|
||||
icon: Pencil,
|
||||
label: 'Edit',
|
||||
onclick: handleEdit,
|
||||
shortcut: isActive ? SHORTCUT_EDIT_CONVERSATION : undefined
|
||||
},
|
||||
...groupActions,
|
||||
{
|
||||
icon: Download,
|
||||
label: 'Export',
|
||||
onclick: (e: Event) => {
|
||||
e.stopPropagation();
|
||||
conversationsStore.downloadConversation(conversation.id);
|
||||
},
|
||||
shortcut: isActive ? SHORTCUT_EXPORT_CONVERSATION : undefined
|
||||
},
|
||||
{
|
||||
icon: ListChecks,
|
||||
label: 'Select',
|
||||
onclick: handleEnterSelectionMode
|
||||
},
|
||||
{
|
||||
icon: Trash2,
|
||||
label: 'Delete',
|
||||
onclick: handleDelete,
|
||||
separator: true,
|
||||
shortcut: isActive ? SHORTCUT_DELETE_CONVERSATION : undefined,
|
||||
variant: 'destructive'
|
||||
}
|
||||
]);
|
||||
|
||||
function handleTogglePin() {
|
||||
conversationsStore.toggleConversationPin(conversation.id);
|
||||
}
|
||||
|
||||
function handleEnterSelectionMode(event: Event) {
|
||||
event.stopPropagation();
|
||||
function handleEnterSelectionMode() {
|
||||
onEnterSelectionMode?.(conversation.id);
|
||||
}
|
||||
|
||||
@@ -243,7 +117,7 @@
|
||||
const customEvent = event as CustomEvent<{ conversationId: string }>;
|
||||
|
||||
if (customEvent.detail.conversationId === conversation.id && isActive) {
|
||||
handleEdit(event);
|
||||
uiStore.openConversationRename(conversation.id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -316,142 +190,146 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
<ContextMenuActions bind:open={contextMenuOpen} {actions} disabled={isSelectionMode}>
|
||||
<button
|
||||
bind:this={rowElement}
|
||||
style:--row-hold-ms="{ROW_LONG_PRESS_MS}ms"
|
||||
class={[
|
||||
'group flex min-h-9 w-full cursor-pointer items-center justify-between space-x-3 rounded-lg px-2 py-1.5 text-left select-none [-webkit-touch-callout:none] transition-[background-color,color,scale] hover:bg-foreground/10 hover:text-foreground max-md:min-h-12 max-md:rounded-2xl max-md:px-3.5 max-md:py-3 md:min-h-8 md:py-1',
|
||||
isLanding && 'invisible',
|
||||
isActive ? 'selected-row-surface text-accent-foreground' : 'text-foreground/75',
|
||||
contextMenuOpen && 'bg-foreground/10',
|
||||
isSelected && 'bg-primary/10 hover:bg-primary/15',
|
||||
isSelectionMode && 'is-selection-mode',
|
||||
// the row sinks while a finger holds it, and stays lit while its menu is open
|
||||
longPress.isPressing && 'scale-97 bg-foreground/10 duration-(--row-hold-ms) ease-out',
|
||||
deviceStore.isMobile && dropdownOpen && 'bg-foreground/10'
|
||||
]}
|
||||
{...{ [UI_DATA_ATTRS.CONVERSATION_ROW]: conversation.id }}
|
||||
onauxclick={handleAuxClick}
|
||||
onclick={(e) => handleSelect(e)}
|
||||
onclickcapture={longPress.handleClickCapture}
|
||||
oncontextmenu={longPress.handleContextMenu}
|
||||
ondragstart={(e) => e.preventDefault()}
|
||||
onfocusin={handleMouseOver}
|
||||
onfocusout={(e) => {
|
||||
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {
|
||||
handleMouseLeave();
|
||||
}
|
||||
}}
|
||||
onmousedown={(e) => handleRowMouseDown(e)}
|
||||
onmouseleave={handleMouseLeave}
|
||||
onmouseover={handleMouseOver}
|
||||
onpointercancel={longPress.handlePointerEnd}
|
||||
onpointerdown={(e) => {
|
||||
// a mouse drags the row, a finger holds it for its menu
|
||||
handlePointerDown(e);
|
||||
longPress.handlePointerDown(e);
|
||||
}}
|
||||
onpointermove={longPress.handlePointerMove}
|
||||
onpointerup={longPress.handlePointerEnd}
|
||||
>
|
||||
<div
|
||||
style:padding-left="{depth * FORK_TREE_DEPTH_PADDING}px"
|
||||
class="flex min-w-0 flex-1 items-center gap-2"
|
||||
<ConversationActions
|
||||
{conversation}
|
||||
{isActive}
|
||||
onEnterSelectionMode={onEnterSelectionMode ? handleEnterSelectionMode : undefined}
|
||||
>
|
||||
{#snippet children(actions)}
|
||||
{@render row(actions)}
|
||||
{/snippet}
|
||||
</ConversationActions>
|
||||
|
||||
{#snippet row(actions: MenuAction[])}
|
||||
<ContextMenuActions bind:open={contextMenuOpen} {actions} disabled={isSelectionMode}>
|
||||
<button
|
||||
bind:this={rowElement}
|
||||
style:--row-hold-ms="{ROW_LONG_PRESS_MS}ms"
|
||||
class={[
|
||||
'group flex min-h-9 w-full cursor-pointer items-center justify-between space-x-3 rounded-lg px-2 py-1.5 text-left select-none [-webkit-touch-callout:none] transition-[background-color,color,scale] hover:bg-foreground/10 hover:text-foreground max-md:min-h-12 max-md:rounded-2xl max-md:px-3.5 max-md:py-3 md:min-h-8 md:py-1',
|
||||
isLanding && 'invisible',
|
||||
isActive ? 'selected-row-surface text-accent-foreground' : 'text-foreground/75',
|
||||
contextMenuOpen && 'bg-foreground/10',
|
||||
isSelected && 'bg-primary/10 hover:bg-primary/15',
|
||||
isSelectionMode && 'is-selection-mode',
|
||||
// the row sinks while a finger holds it, and stays lit while its menu is open
|
||||
longPress.isPressing && 'scale-97 bg-foreground/10 duration-(--row-hold-ms) ease-out',
|
||||
deviceStore.isMobile && dropdownOpen && 'bg-foreground/10'
|
||||
]}
|
||||
{...{ [UI_DATA_ATTRS.CONVERSATION_ROW]: conversation.id }}
|
||||
onauxclick={handleAuxClick}
|
||||
onclick={(e) => handleSelect(e)}
|
||||
onclickcapture={longPress.handleClickCapture}
|
||||
oncontextmenu={longPress.handleContextMenu}
|
||||
ondragstart={(e) => e.preventDefault()}
|
||||
onfocusin={handleMouseOver}
|
||||
onfocusout={(e) => {
|
||||
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) {
|
||||
handleMouseLeave();
|
||||
}
|
||||
}}
|
||||
onmousedown={(e) => handleRowMouseDown(e)}
|
||||
onmouseleave={handleMouseLeave}
|
||||
onmouseover={handleMouseOver}
|
||||
onpointercancel={longPress.handlePointerEnd}
|
||||
onpointerdown={(e) => {
|
||||
// a mouse drags the row, a finger holds it for its menu
|
||||
handlePointerDown(e);
|
||||
longPress.handlePointerDown(e);
|
||||
}}
|
||||
onpointermove={longPress.handlePointerMove}
|
||||
onpointerup={longPress.handlePointerEnd}
|
||||
>
|
||||
{#if isSelectionMode}
|
||||
<div
|
||||
aria-checked={isSelected}
|
||||
aria-label={isSelected ? `Deselect ${conversation.name}` : `Select ${conversation.name}`}
|
||||
class="shrink-0"
|
||||
onclick={(e) => handleCheckboxClick(e)}
|
||||
onkeydown={handleCheckboxKeydown}
|
||||
role="checkbox"
|
||||
tabindex="-1"
|
||||
>
|
||||
<Checkbox
|
||||
<div
|
||||
style:padding-left="{depth * FORK_TREE_DEPTH_PADDING}px"
|
||||
class="flex min-w-0 flex-1 items-center gap-2"
|
||||
>
|
||||
{#if isSelectionMode}
|
||||
<div
|
||||
aria-checked={isSelected}
|
||||
aria-label={isSelected
|
||||
? `Deselect ${conversation.name}`
|
||||
: `Select ${conversation.name}`}
|
||||
checked={isSelected}
|
||||
class="shrink-0"
|
||||
onclick={(e) => handleCheckboxClick(e)}
|
||||
onkeydown={handleCheckboxKeydown}
|
||||
role="checkbox"
|
||||
tabindex="-1"
|
||||
>
|
||||
<Checkbox
|
||||
aria-label={isSelected
|
||||
? `Deselect ${conversation.name}`
|
||||
: `Select ${conversation.name}`}
|
||||
checked={isSelected}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if depth > 0}
|
||||
<Tooltip.Root>
|
||||
<Tooltip.Trigger>
|
||||
<!-- prevent another nested button element -->
|
||||
{#snippet child({ props })}
|
||||
<a
|
||||
{...props}
|
||||
class="flex shrink-0 items-center text-muted-foreground transition-colors hover:text-foreground"
|
||||
href={RouterService.chat(conversation.forkedFromConversationId)}
|
||||
>
|
||||
<GitBranch class="h-3.5 w-3.5" />
|
||||
</a>
|
||||
{/snippet}
|
||||
</Tooltip.Trigger>
|
||||
|
||||
<Tooltip.Content>
|
||||
<p>See parent conversation</p>
|
||||
</Tooltip.Content>
|
||||
</Tooltip.Root>
|
||||
{/if}
|
||||
|
||||
{#if isLoading}
|
||||
<Tooltip.Root>
|
||||
<Tooltip.Trigger>
|
||||
<div
|
||||
aria-label="Stop generation"
|
||||
class="stop-button flex {ICON_CLASS_DEFAULT} shrink-0 cursor-pointer items-center justify-center rounded text-muted-foreground transition-colors hover:text-foreground"
|
||||
onclick={handleStop}
|
||||
onkeydown={(e) => e.key === 'Enter' && handleStop(e)}
|
||||
role="button"
|
||||
tabindex="0"
|
||||
>
|
||||
<Loader2 class="loading-icon h-3.5 w-3.5 animate-spin" />
|
||||
|
||||
<Square class="stop-icon hidden h-3 w-3 fill-current text-destructive" />
|
||||
</div>
|
||||
</Tooltip.Trigger>
|
||||
|
||||
<Tooltip.Content>
|
||||
<p>Stop generation</p>
|
||||
</Tooltip.Content>
|
||||
</Tooltip.Root>
|
||||
{/if}
|
||||
|
||||
<TruncatedText
|
||||
class="text-body-sm max-md:text-body"
|
||||
showTooltip={false}
|
||||
text={conversation.name}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{#if !isSelectionMode && renderActionsDropdown}
|
||||
<!-- a phone opens the menu by holding the row, so it shows no trigger -->
|
||||
<div class="actions flex items-center" hidden={deviceStore.isMobile}>
|
||||
<DropdownMenuActions
|
||||
bind:open={dropdownOpen}
|
||||
{actions}
|
||||
anchor={deviceStore.isMobile ? rowElement : null}
|
||||
triggerIcon={MoreHorizontal}
|
||||
triggerTooltip="More actions"
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if depth > 0}
|
||||
<Tooltip.Root>
|
||||
<Tooltip.Trigger>
|
||||
<!-- prevent another nested button element -->
|
||||
{#snippet child({ props })}
|
||||
<a
|
||||
{...props}
|
||||
class="flex shrink-0 items-center text-muted-foreground transition-colors hover:text-foreground"
|
||||
href={RouterService.chat(conversation.forkedFromConversationId)}
|
||||
>
|
||||
<GitBranch class="h-3.5 w-3.5" />
|
||||
</a>
|
||||
{/snippet}
|
||||
</Tooltip.Trigger>
|
||||
|
||||
<Tooltip.Content>
|
||||
<p>See parent conversation</p>
|
||||
</Tooltip.Content>
|
||||
</Tooltip.Root>
|
||||
{/if}
|
||||
|
||||
{#if isLoading}
|
||||
<Tooltip.Root>
|
||||
<Tooltip.Trigger>
|
||||
<div
|
||||
aria-label="Stop generation"
|
||||
class="stop-button flex {ICON_CLASS_DEFAULT} shrink-0 cursor-pointer items-center justify-center rounded text-muted-foreground transition-colors hover:text-foreground"
|
||||
onclick={handleStop}
|
||||
onkeydown={(e) => e.key === 'Enter' && handleStop(e)}
|
||||
role="button"
|
||||
tabindex="0"
|
||||
>
|
||||
<Loader2 class="loading-icon h-3.5 w-3.5 animate-spin" />
|
||||
|
||||
<Square class="stop-icon hidden h-3 w-3 fill-current text-destructive" />
|
||||
</div>
|
||||
</Tooltip.Trigger>
|
||||
|
||||
<Tooltip.Content>
|
||||
<p>Stop generation</p>
|
||||
</Tooltip.Content>
|
||||
</Tooltip.Root>
|
||||
{/if}
|
||||
|
||||
<TruncatedText
|
||||
class="text-body-sm max-md:text-body"
|
||||
showTooltip={false}
|
||||
text={conversation.name}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{#if !isSelectionMode && renderActionsDropdown}
|
||||
<!-- a phone opens the menu by holding the row, so it shows no trigger -->
|
||||
<div class="actions flex items-center" hidden={deviceStore.isMobile}>
|
||||
<DropdownMenuActions
|
||||
bind:open={dropdownOpen}
|
||||
{actions}
|
||||
anchor={deviceStore.isMobile ? rowElement : null}
|
||||
triggerIcon={MoreHorizontal}
|
||||
triggerTooltip="More actions"
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
</button>
|
||||
</ContextMenuActions>
|
||||
|
||||
{#snippet groupSubmenu({ close, kind }: { close: () => void; kind: MenuKind })}
|
||||
<SidebarNavigationGroupSubmenu
|
||||
currentGroupId={groupId}
|
||||
{kind}
|
||||
label="Move to group"
|
||||
onClose={close}
|
||||
onSelect={setGroup}
|
||||
/>
|
||||
</button>
|
||||
</ContextMenuActions>
|
||||
{/snippet}
|
||||
|
||||
<style>
|
||||
|
||||
-6
@@ -34,8 +34,6 @@
|
||||
isSelectionMode?: boolean;
|
||||
selectedIds?: Set<string>;
|
||||
onSelect: (id: string) => void;
|
||||
onEdit: (id: string) => void;
|
||||
onDelete: (id: string) => void;
|
||||
onStop: (id: string) => void;
|
||||
onToggleSelect?: (id: string) => void;
|
||||
onEnterSelectionMode?: (id: string) => void;
|
||||
@@ -64,8 +62,6 @@
|
||||
onBulkExport,
|
||||
onBulkPinToggle,
|
||||
onCloseSelection,
|
||||
onDelete,
|
||||
onEdit,
|
||||
onEnterSelectionMode,
|
||||
onRowMouseDown,
|
||||
onSelect,
|
||||
@@ -274,8 +270,6 @@
|
||||
isActive={currentChatId === conversation.id}
|
||||
isSelected={selectedIds.has(conversation.id)}
|
||||
{isSelectionMode}
|
||||
{onDelete}
|
||||
{onEdit}
|
||||
{onEnterSelectionMode}
|
||||
{onRowMouseDown}
|
||||
{onSelect}
|
||||
|
||||
-6
@@ -10,8 +10,6 @@
|
||||
isSelectionMode?: boolean;
|
||||
selectedIds?: Set<string>;
|
||||
onSelect: (id: string) => void;
|
||||
onEdit: (id: string) => void;
|
||||
onDelete: (id: string) => void;
|
||||
onStop: (id: string) => void;
|
||||
onToggleSelect?: (id: string) => void;
|
||||
onEnterSelectionMode?: (id: string) => void;
|
||||
@@ -24,8 +22,6 @@
|
||||
currentChatId,
|
||||
filteredConversations,
|
||||
isSelectionMode = false,
|
||||
onDelete,
|
||||
onEdit,
|
||||
onEnterSelectionMode,
|
||||
onRowMouseDown,
|
||||
onSelect,
|
||||
@@ -68,8 +64,6 @@
|
||||
isActive={currentChatId === conversation.id}
|
||||
isSelected={selectedIds.has(conversation.id)}
|
||||
{isSelectionMode}
|
||||
{onDelete}
|
||||
{onEdit}
|
||||
{onEnterSelectionMode}
|
||||
{onRowMouseDown}
|
||||
{onSelect}
|
||||
|
||||
@@ -173,8 +173,6 @@ export { default as SidebarNavigationSelectionBar } from './SidebarNavigation/Si
|
||||
* {conversations}
|
||||
* {currentChatId}
|
||||
* onSelect={...}
|
||||
* onEdit={...}
|
||||
* onDelete={...}
|
||||
* onStop={...}
|
||||
* />
|
||||
* ```
|
||||
@@ -185,6 +183,27 @@ export { default as SidebarNavigationActions } from './SidebarNavigation/Sidebar
|
||||
/** The sidebar's footer: Models and Settings in a group inset in the sidebar. */
|
||||
export { default as SidebarNavigationFooter } from './SidebarNavigation/SidebarNavigationFooter.svelte';
|
||||
|
||||
/**
|
||||
* **ConversationActions** - The actions a conversation's menus offer
|
||||
*
|
||||
* Owns which actions a conversation has and what they do: open in a new tab,
|
||||
* pin, rename, move to a group, export, share to Hugging Face, select and
|
||||
* delete. It draws no menu itself: it hands the actions to its `children`,
|
||||
* so the sidebar row's dropdown and right-click menu and a tab's right-click
|
||||
* menu all show the same list. Rename, delete and share open the dialogs the
|
||||
* sidebar hosts through `uiStore`.
|
||||
*
|
||||
* @example
|
||||
* ```svelte
|
||||
* <ConversationActions {conversation} isActive showOpenInNewTab={false}>
|
||||
* {#snippet children(actions)}
|
||||
* <ContextMenuActions {actions}>...</ContextMenuActions>
|
||||
* {/snippet}
|
||||
* </ConversationActions>
|
||||
* ```
|
||||
*/
|
||||
export { default as ConversationActions } from './ConversationActions.svelte';
|
||||
|
||||
/**
|
||||
* **SidebarNavigationSearchResults** - Filtered conversation list for search.
|
||||
*
|
||||
@@ -203,8 +222,6 @@ export { default as SidebarNavigationFooter } from './SidebarNavigation/SidebarN
|
||||
* {filteredConversations}
|
||||
* {currentChatId}
|
||||
* onSelect={...}
|
||||
* onEdit={...}
|
||||
* onDelete={...}
|
||||
* onStop={...}
|
||||
* />
|
||||
* ```
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
SettingsChatToolsTab,
|
||||
SettingsChatVoiceTab,
|
||||
SettingsFooter,
|
||||
SettingsHuggingFaceAccount,
|
||||
SettingsResetButton
|
||||
} from '#lib/components/app/settings/index.ts';
|
||||
import {
|
||||
@@ -225,6 +226,8 @@
|
||||
/>
|
||||
|
||||
{#if currentSection.slug === SETTINGS_SECTION_SLUGS.GENERAL}
|
||||
<SettingsHuggingFaceAccount />
|
||||
|
||||
<div class="flex justify-end gap-2">
|
||||
<SettingsResetButton onReset={handleReset} />
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
<script lang="ts">
|
||||
import { HfAccountPanel, HfLogo } from '@ggml-org/llama-huggingface/svelte';
|
||||
import { InsetList } from '@ggml-org/llama-ui/app/sheets';
|
||||
import { HUGGING_FACE_ENABLED } from '#lib/constants/index.ts';
|
||||
import { huggingFace } from '#lib/stores/index.ts';
|
||||
|
||||
interface Props {
|
||||
/** As a group of a phone's settings sheet, where the desktop settings show a labelled row. */
|
||||
inset?: boolean;
|
||||
}
|
||||
|
||||
let { inset = false }: Props = $props();
|
||||
|
||||
const TITLE = 'Hugging Face';
|
||||
const CAPTION =
|
||||
"Conversations you share go to this account's datasets. The sign-in stays in this browser.";
|
||||
</script>
|
||||
|
||||
<!-- a share is what signs the app in, so there is nothing to show before one did -->
|
||||
{#if HUGGING_FACE_ENABLED && huggingFace.user}
|
||||
{#if inset}
|
||||
<InsetList caption={CAPTION} title={TITLE}>
|
||||
<div class="px-4 py-2">
|
||||
<HfAccountPanel account={huggingFace} />
|
||||
</div>
|
||||
</InsetList>
|
||||
{:else}
|
||||
<section aria-labelledby="settings-hugging-face-account" class="flex flex-col gap-2">
|
||||
<h3 class="flex items-center gap-1.5 text-label" id="settings-hugging-face-account">
|
||||
<HfLogo class="size-icon-md" />
|
||||
|
||||
{TITLE}
|
||||
</h3>
|
||||
|
||||
<HfAccountPanel account={huggingFace} />
|
||||
|
||||
<p class="text-caption text-muted-foreground">{CAPTION}</p>
|
||||
</section>
|
||||
{/if}
|
||||
{/if}
|
||||
@@ -20,6 +20,7 @@
|
||||
SettingsChatFieldsInset,
|
||||
SettingsChatImportExportTab,
|
||||
SettingsChatVoiceTab,
|
||||
SettingsHuggingFaceAccount,
|
||||
SettingsMcpServers
|
||||
} from '#lib/components/app/settings/index.ts';
|
||||
import {
|
||||
@@ -356,6 +357,8 @@
|
||||
/>
|
||||
|
||||
{#if slug === SETTINGS_SECTION_SLUGS.GENERAL}
|
||||
<SettingsHuggingFaceAccount inset />
|
||||
|
||||
<InsetList title={SETTINGS_SHEET_TEXT.APP}>
|
||||
<InsetListRow icon={RefreshCw} onclick={() => window.location.reload()}>
|
||||
{SETTINGS_SHEET_TEXT.RELOAD_APP}
|
||||
|
||||
@@ -34,6 +34,12 @@ export { default as SettingsChatParameterSourceIndicator } from './SettingsChat/
|
||||
*/
|
||||
export { default as SettingsGroup } from './SettingsGroup.svelte';
|
||||
|
||||
/**
|
||||
* The Hugging Face account the app is signed in with, and its Sign out. Shows nothing until
|
||||
* a share has signed the app in.
|
||||
*/
|
||||
export { default as SettingsHuggingFaceAccount } from './SettingsHuggingFaceAccount.svelte';
|
||||
|
||||
/**
|
||||
* Sticky footer with the save button for settings panel, shown only when
|
||||
* there are unsaved changes. Save commits form state to config store.
|
||||
|
||||
@@ -8,3 +8,11 @@ export const APP_NAME = import.meta.env?.VITE_PUBLIC_APP_NAME || 'Llama Chat';
|
||||
* `agenticMode.enabled`, not this constant, to decide what to show.
|
||||
*/
|
||||
export const AGENTIC_ENABLED = import.meta.env?.VITE_PUBLIC_AGENTIC !== 'false';
|
||||
|
||||
/**
|
||||
* Whether this build can share conversations to Hugging Face: a build has the
|
||||
* sharing and its sign-in only when made with VITE_PUBLIC_HUGGING_FACE=true
|
||||
* (the release builds are); the dev server, the tests and Storybook have it
|
||||
* without (see vite.config.ts).
|
||||
*/
|
||||
export const HUGGING_FACE_ENABLED = import.meta.env?.VITE_PUBLIC_HUGGING_FACE === 'true';
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* What Llama Chat tells Hugging Face about itself when it signs in, which it does to share a
|
||||
* conversation as an agent trace.
|
||||
*/
|
||||
|
||||
/**
|
||||
* What the sign-in is asked for: read the account, and create datasets and commit traces to
|
||||
* the ones the app created. No scope reaches any other repository.
|
||||
*/
|
||||
export const HUGGING_FACE_SCOPES = ['openid', 'profile', 'contribute-repos'] as const;
|
||||
/** The scope a share cannot do without: creating a dataset and committing a trace. */
|
||||
export const HUGGING_FACE_REQUIRED_SCOPE = 'contribute-repos';
|
||||
/** The name the app registers under, shown on the Hugging Face authorization page. */
|
||||
export const HUGGING_FACE_CLIENT_NAME = 'Llama Chat';
|
||||
/** The app's icon, shown for it on Hugging Face (@ggml-org/llama-brand, from npm's CDN). */
|
||||
export const HUGGING_FACE_LOGO_URL =
|
||||
'https://cdn.jsdelivr.net/npm/@ggml-org/llama-brand@0.1.0/logo/svg/app/web/maskable-icon-512x512.svg';
|
||||
/** The dataset a first share suggests, under the account's name. */
|
||||
export const HUGGING_FACE_DEFAULT_DATASET_NAME = 'llama-chat-traces';
|
||||
/** How long a finished sign-in popup waits to close itself before saying it can be closed. */
|
||||
export const HUGGING_FACE_POPUP_CLOSE_GRACE_MS = 400;
|
||||
|
||||
/** What the share dialog and the sign-in say for the app: they are about a conversation. */
|
||||
export const CONVERSATION_SHARE_TEXT = {
|
||||
commitMessage: (name: string) => `Add trace: ${name}`,
|
||||
CONVERSATION_NOT_FOUND: 'Conversation not found.',
|
||||
LINK_COPIED: 'Link copied',
|
||||
messageCount: (count: number) => (count === 1 ? '1 message' : `${count} messages`),
|
||||
SCOPE_ALL: 'Whole conversation',
|
||||
SCOPE_UP_TO_MESSAGE: 'Up to this message',
|
||||
SHARED: 'Conversation shared to Hugging Face',
|
||||
subject: (name: string) => `"${name}"`,
|
||||
SUBJECT_FALLBACK: 'this conversation'
|
||||
} as const;
|
||||
|
||||
export const HUGGING_FACE_SIGN_IN_TEXT = {
|
||||
CLOSE_WINDOW: 'You can close this window.',
|
||||
FAILED: 'The sign-in failed.',
|
||||
SIGNED_IN: 'Signed in to Hugging Face'
|
||||
} as const;
|
||||
@@ -5,6 +5,7 @@
|
||||
* Reference: https://huggingface.co/docs/huggingface_hub/package_reference/hf_api
|
||||
*/
|
||||
|
||||
import { HF_BASE_URL } from '@ggml-org/llama-huggingface';
|
||||
import { GIGABYTE, KILOBYTE, MEGABYTE } from '@ggml-org/llama-ui/models';
|
||||
export {
|
||||
BYTE_LABEL,
|
||||
@@ -19,7 +20,7 @@ export {
|
||||
|
||||
// API endpoints
|
||||
|
||||
export const HF_BASE_URL = 'https://huggingface.co';
|
||||
export { HF_BASE_URL };
|
||||
export const HF_API_MODELS_URL = `${HF_BASE_URL}/api/models`;
|
||||
|
||||
// Query params
|
||||
|
||||
@@ -18,6 +18,8 @@ import PauseDownloadIcon from '@lucide/svelte/icons/pause';
|
||||
import ResumeDownloadIcon from '@lucide/svelte/icons/play';
|
||||
import LoadIcon from '@lucide/svelte/icons/power';
|
||||
import RetryIcon from '@lucide/svelte/icons/rotate-cw';
|
||||
// the box with an arrow leaving it, not the three joined dots
|
||||
import ShareIcon from '@lucide/svelte/icons/share';
|
||||
import VideoIcon from '@lucide/svelte/icons/video';
|
||||
import CancelLoadIcon from '@lucide/svelte/icons/x';
|
||||
import { FileTypeCategory, ModelCapability } from '#lib/enums/index.ts';
|
||||
@@ -44,6 +46,12 @@ export const DEFAULT_FILE_ICON = FileIcon;
|
||||
/** The mark for a model, wherever one is listed. */
|
||||
export const MODEL_ICON = ModelIcon;
|
||||
|
||||
/** Sharing something out of the app: every share action, button and dialog uses this one icon. */
|
||||
export const SHARE_ICON = ShareIcon;
|
||||
|
||||
/** What sharing a conversation looks like as an action, on a message and in every conversation menu. */
|
||||
export const SHARE_ACTION = { icon: SHARE_ICON, label: 'Share' } as const;
|
||||
|
||||
/** The mark for the Discover Models surface and its entry points. */
|
||||
export const DISCOVER_ICON = DiscoverIcon;
|
||||
|
||||
|
||||
@@ -55,6 +55,7 @@ export * from './models-discover.constants';
|
||||
export * from './models-discover-download.constants';
|
||||
export * from './model-compatibility.constants';
|
||||
export * from './huggingface.constants';
|
||||
export * from './huggingface-account.constants';
|
||||
export * from './precision.constants';
|
||||
export * from './pwa.constants';
|
||||
export * from './routes.constants';
|
||||
|
||||
@@ -80,6 +80,12 @@ export enum PdfViewMode {
|
||||
TEXT = 'text'
|
||||
}
|
||||
|
||||
/** How much of a conversation a share uploads. */
|
||||
export enum ConversationShareScope {
|
||||
ALL = 'all',
|
||||
UP_TO_MESSAGE = 'up-to-message'
|
||||
}
|
||||
|
||||
export enum ChatFormCommandAction {
|
||||
COMPACT = 'compact',
|
||||
CWD = 'cwd',
|
||||
|
||||
@@ -22,6 +22,7 @@ export {
|
||||
StreamConnectionState,
|
||||
ContentPartType,
|
||||
ConversationSelectionMode,
|
||||
ConversationShareScope,
|
||||
ErrorDialogType,
|
||||
MessageRole,
|
||||
MessageType,
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
// What `@ggml-org/llama-huggingface/svelte` resolves to in a build without sharing to
|
||||
// Hugging Face (a build not made with VITE_PUBLIC_HUGGING_FACE=true, see vite.config.ts):
|
||||
// an account that is never signed in and components that draw nothing, so the sign-in, the
|
||||
// upload and the dialogs are not in the bundle. The app reads HUGGING_FACE_ENABLED before it
|
||||
// shows or starts any of them.
|
||||
|
||||
import type { HfAccount as HfAccountState } from '@ggml-org/llama-huggingface/svelte';
|
||||
|
||||
type HfAccountApp = Pick<HfAccountState, 'completeSignInFromLocation' | 'restoreSession' | 'user'>;
|
||||
|
||||
export class HfAccount implements HfAccountApp {
|
||||
user = null;
|
||||
|
||||
async completeSignInFromLocation(): Promise<null> {
|
||||
return null;
|
||||
}
|
||||
|
||||
async restoreSession(): Promise<void> {}
|
||||
}
|
||||
|
||||
/** A component that draws nothing: a Svelte component is a function of its anchor and props. */
|
||||
const NO_COMPONENT = (): void => {};
|
||||
|
||||
export const HfAccountPanel = NO_COMPONENT;
|
||||
export const HfLogo = NO_COMPONENT;
|
||||
export const HfShareDialog = NO_COMPONENT;
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* huggingFace - the Hugging Face account Llama Chat is signed in with
|
||||
*
|
||||
* The account, its sign-in and the upload of a trace live in @ggml-org/llama-huggingface;
|
||||
* this file says who the app is. Sharing a conversation is what asks for the sign-in, so it
|
||||
* starts in the share dialog, and Settings > General shows the account once there is one.
|
||||
*/
|
||||
|
||||
import { HfAccount } from '@ggml-org/llama-huggingface/svelte';
|
||||
import { HUGGING_FACE_ENABLED } from '#lib/constants/app.constants.ts';
|
||||
import {
|
||||
HUGGING_FACE_CLIENT_NAME,
|
||||
HUGGING_FACE_DEFAULT_DATASET_NAME,
|
||||
HUGGING_FACE_LOGO_URL,
|
||||
HUGGING_FACE_POPUP_CLOSE_GRACE_MS,
|
||||
HUGGING_FACE_REQUIRED_SCOPE,
|
||||
HUGGING_FACE_SCOPES,
|
||||
HUGGING_FACE_SIGN_IN_TEXT
|
||||
} from '#lib/constants/huggingface-account.constants.ts';
|
||||
import { STORAGE_APP_NAME } from '#lib/constants/storage.constants.ts';
|
||||
import { withBase } from '#lib/utils/base-path.ts';
|
||||
import { toast } from 'svelte-sonner';
|
||||
|
||||
export const huggingFace = new HfAccount({
|
||||
callbackUrl: () => `${window.location.origin}${withBase('/')}`,
|
||||
clientName: HUGGING_FACE_CLIENT_NAME,
|
||||
defaultDatasetName: HUGGING_FACE_DEFAULT_DATASET_NAME,
|
||||
logoUrl: HUGGING_FACE_LOGO_URL,
|
||||
requiredScope: HUGGING_FACE_REQUIRED_SCOPE,
|
||||
scopes: HUGGING_FACE_SCOPES,
|
||||
storagePrefix: STORAGE_APP_NAME
|
||||
});
|
||||
|
||||
const { CLOSE_WINDOW, FAILED, SIGNED_IN } = HUGGING_FACE_SIGN_IN_TEXT;
|
||||
|
||||
/** Finishes a sign-in when this page load is Hugging Face sending the browser back. */
|
||||
async function completeSignIn(): Promise<void> {
|
||||
const outcome = await huggingFace.completeSignInFromLocation();
|
||||
|
||||
if (!outcome?.result) return;
|
||||
|
||||
const { result } = outcome;
|
||||
|
||||
if (outcome.closeWindow) {
|
||||
window.close();
|
||||
|
||||
// a browser may keep a window its script did not open in this document: say so
|
||||
setTimeout(() => {
|
||||
if (result.ok) toast.success(`${SIGNED_IN} ${CLOSE_WINDOW}`);
|
||||
else toast.error(`${result.error ?? FAILED} ${CLOSE_WINDOW}`);
|
||||
}, HUGGING_FACE_POPUP_CLOSE_GRACE_MS);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.ok) toast.success(SIGNED_IN);
|
||||
else toast.error(result.error ?? FAILED);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run once when the app starts: finishes a sign-in this page load brings back, and looks up
|
||||
* who a remembered sign-in belongs to. Without either, no request leaves the browser. A build
|
||||
* without sharing does neither.
|
||||
*/
|
||||
export function startHuggingFace(): void {
|
||||
if (!HUGGING_FACE_ENABLED) return;
|
||||
|
||||
void completeSignIn();
|
||||
void huggingFace.restoreSession();
|
||||
}
|
||||
@@ -44,6 +44,9 @@ export { mcpStore } from './mcp/index.svelte';
|
||||
// GROUPS (named sidebar sections for chats)
|
||||
export { groupsStore } from './groups.svelte';
|
||||
|
||||
// HUGGING FACE ACCOUNT (sharing conversations as traces)
|
||||
export { huggingFace } from './huggingface.svelte';
|
||||
|
||||
// MODELS
|
||||
export { modelsStore } from './models/index.svelte';
|
||||
|
||||
|
||||
@@ -27,6 +27,12 @@ import { goto } from '$app/navigation';
|
||||
import { page } from '$app/state';
|
||||
import { SvelteSet } from 'svelte/reactivity';
|
||||
|
||||
interface ConversationShareOptions {
|
||||
conversationId: string;
|
||||
/** The message a share can end at, when it was started from one. */
|
||||
messageId?: string;
|
||||
}
|
||||
|
||||
interface GroupDialogOptions {
|
||||
/** Group to rename; without it the dialog creates a new one. */
|
||||
groupId?: string;
|
||||
@@ -75,6 +81,15 @@ class UiStore {
|
||||
/** Set when a flow outside the chat wants the composer focused once it can take it. */
|
||||
composerFocusRequested = $state(false);
|
||||
|
||||
/** Conversation the delete dialog asks about, `null` while closed. */
|
||||
conversationDeleteId = $state<string | null>(null);
|
||||
|
||||
/** Conversation the rename dialog edits, `null` while closed. */
|
||||
conversationRenameId = $state<string | null>(null);
|
||||
|
||||
/** The share the share dialog is open for, `null` while closed. */
|
||||
conversationShare = $state<ConversationShareOptions | null>(null);
|
||||
|
||||
/** Repo the Discover dialog selects when it opens, set by a model row. */
|
||||
discoverModelFocus = $state<string | null>(null);
|
||||
|
||||
@@ -193,6 +208,21 @@ class UiStore {
|
||||
return !this.collapsedSidebarSections.has(id);
|
||||
}
|
||||
|
||||
/** Ask to delete a conversation, from any of its menus. */
|
||||
openConversationDelete(conversationId: string): void {
|
||||
this.conversationDeleteId = conversationId;
|
||||
}
|
||||
|
||||
/** Rename a conversation, from any of its menus. */
|
||||
openConversationRename(conversationId: string): void {
|
||||
this.conversationRenameId = conversationId;
|
||||
}
|
||||
|
||||
/** Share a conversation to Hugging Face, from any of its menus or from a message. */
|
||||
openConversationShare(options: ConversationShareOptions): void {
|
||||
this.conversationShare = options;
|
||||
}
|
||||
|
||||
/** Open the group dialog to create a group, or to rename `groupId`. */
|
||||
openGroupDialog(options: GroupDialogOptions = {}): void {
|
||||
this.groupDialog = options;
|
||||
|
||||
Vendored
+2
@@ -328,6 +328,8 @@ export interface ChatMessageActionsContext {
|
||||
setShowForkDialog: (show: boolean) => void;
|
||||
navigateToSibling: (siblingId: string) => void;
|
||||
forkConversation?: (options: { name: string; includeAttachments: boolean }) => void;
|
||||
/** Shares the conversation up to this message; absent in a build without sharing. */
|
||||
share?: () => void;
|
||||
}
|
||||
|
||||
export interface ChatMessageEditState {
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* Builds the trace a share uploads: one branch of a conversation, from its start to a message.
|
||||
*/
|
||||
|
||||
import {
|
||||
HF_PREVIEW_LINES_MAX,
|
||||
HF_PREVIEW_TEXT_MAX,
|
||||
type HfTracePreviewLine
|
||||
} from '@ggml-org/llama-huggingface';
|
||||
import { MessageRole, MessageType } from '#lib/enums/index.ts';
|
||||
import { filterByLeafNodeId } from '#lib/utils/branching.ts';
|
||||
|
||||
const WHITESPACE = /\s+/g;
|
||||
/** A fenced code block, or what is left of one the preview cut short. */
|
||||
const FENCED_CODE = /```[\s\S]*?(?:```|$)/g;
|
||||
const BACKTICKS = /`/g;
|
||||
|
||||
export interface ConversationTraceOptions {
|
||||
/** Last message of the trace; the conversation's current message when omitted. */
|
||||
upToMessageId?: string;
|
||||
includeAttachments?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks the branch that ends at `upToMessageId` out of the conversation's message tree.
|
||||
* The trace viewer reads messages as one line, so other branches are left out.
|
||||
* Local details (working directories, sidebar group) stay on this device.
|
||||
* @returns The trace as an exported conversation, ready for the JSONL serializer
|
||||
*/
|
||||
export function buildConversationTrace(
|
||||
data: ExportedConversation,
|
||||
options: ConversationTraceOptions = {}
|
||||
): ExportedConversation {
|
||||
const { conv, messages } = data;
|
||||
const leafId = options.upToMessageId ?? conv.currNode ?? '';
|
||||
const path = filterByLeafNodeId(messages, leafId);
|
||||
const pathIds = new Set(path.map((message) => message.id));
|
||||
const traceMessages = path.map((message) => {
|
||||
const { extra, toolCwd: _toolCwd, ...rest } = message;
|
||||
const traceMessage: DatabaseMessage = {
|
||||
...rest,
|
||||
children: message.children.filter((id: string) => pathIds.has(id))
|
||||
};
|
||||
|
||||
if (options.includeAttachments && extra?.length) traceMessage.extra = extra;
|
||||
|
||||
return traceMessage;
|
||||
});
|
||||
const { cwd: _cwd, groupId: _groupId, ...sharedConv } = conv;
|
||||
|
||||
return {
|
||||
conv: { ...sharedConv, currNode: traceMessages.at(-1)?.id ?? null },
|
||||
messages: traceMessages
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The first messages of a trace, as the dialog shows them faded once the trace is shared:
|
||||
* what the user and the assistant said, in one line each, without code blocks. Tool calls,
|
||||
* reasoning, a compaction and messages the app made itself have no place in it.
|
||||
*/
|
||||
export function buildTracePreview(trace: ExportedConversation): HfTracePreviewLine[] {
|
||||
const lines: HfTracePreviewLine[] = [];
|
||||
|
||||
for (const message of trace.messages) {
|
||||
if (lines.length >= HF_PREVIEW_LINES_MAX) break;
|
||||
|
||||
if (message.isSynthetic || message.type !== MessageType.TEXT) continue;
|
||||
|
||||
const role =
|
||||
message.role === MessageRole.USER
|
||||
? 'user'
|
||||
: message.role === MessageRole.ASSISTANT
|
||||
? 'assistant'
|
||||
: null;
|
||||
const text = message.content
|
||||
.replace(FENCED_CODE, ' ')
|
||||
.replace(BACKTICKS, '')
|
||||
.replace(WHITESPACE, ' ')
|
||||
.trim()
|
||||
.slice(0, HF_PREVIEW_TEXT_MAX);
|
||||
|
||||
if (role && text) lines.push({ role, text });
|
||||
}
|
||||
|
||||
return lines;
|
||||
}
|
||||
@@ -39,6 +39,13 @@ export {
|
||||
buildSiblingInfoMap
|
||||
} from './branching';
|
||||
|
||||
// Conversation traces (sharing to Hugging Face)
|
||||
export {
|
||||
buildConversationTrace,
|
||||
buildTracePreview,
|
||||
type ConversationTraceOptions
|
||||
} from './conversation-trace';
|
||||
|
||||
// Code
|
||||
export {
|
||||
highlightCode,
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
import { usePwa } from '#lib/hooks/use-pwa.svelte.ts';
|
||||
import { useSidebarReveal } from '#lib/hooks/use-sidebar-reveal.svelte.ts';
|
||||
import { RouterService } from '#lib/services/router.service.ts';
|
||||
import { startHuggingFace } from '#lib/stores/huggingface.svelte.ts';
|
||||
import {
|
||||
chatStore,
|
||||
conversationsStore,
|
||||
@@ -213,6 +214,9 @@
|
||||
|
||||
onMount(() => {
|
||||
updateFavicon();
|
||||
|
||||
startHuggingFace();
|
||||
|
||||
// snapshot of every backend running stream on first load, populates the sidebar spinners
|
||||
// so the user sees each conv that has a live inference, even ones not opened yet
|
||||
void chatStore.syncRemoteRunningStreams();
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
DialogConversationDelete,
|
||||
SearchInput,
|
||||
SidebarNavigationSearchResults
|
||||
} from '#lib/components/app/index.ts';
|
||||
import { SearchInput, SidebarNavigationSearchResults } from '#lib/components/app/index.ts';
|
||||
import { ROUTES } from '#lib/constants/index.ts';
|
||||
import { RouterService } from '#lib/services/router.service.ts';
|
||||
import { chatStore, conversationsStore, deviceStore } from '#lib/stores/index.ts';
|
||||
@@ -36,44 +32,6 @@
|
||||
await goto(RouterService.chat(id));
|
||||
}
|
||||
|
||||
async function handleEditConversation(id: string) {
|
||||
const conversation = conversationsStore.conversations.find((c) => c.id === id);
|
||||
|
||||
if (!conversation) return;
|
||||
|
||||
const newName = window.prompt('Rename conversation', conversation.name);
|
||||
|
||||
if (newName && newName.trim()) {
|
||||
await conversationsStore.updateConversationName(id, newName.trim());
|
||||
}
|
||||
}
|
||||
|
||||
let deleteDialogOpen = $state(false);
|
||||
let deleteTargetId = $state<string | null>(null);
|
||||
|
||||
function handleDeleteConversation(id: string) {
|
||||
const conversation = conversationsStore.conversations.find((c) => c.id === id);
|
||||
|
||||
if (!conversation) return;
|
||||
|
||||
deleteTargetId = conversation.id;
|
||||
deleteDialogOpen = true;
|
||||
}
|
||||
|
||||
async function handleDeleteConfirm() {
|
||||
const id = deleteTargetId;
|
||||
|
||||
deleteDialogOpen = false;
|
||||
|
||||
if (!id) return;
|
||||
|
||||
await conversationsStore.deleteConversation(id, { deleteWithForks: false });
|
||||
}
|
||||
|
||||
function handleDeleteCancel() {
|
||||
deleteDialogOpen = false;
|
||||
}
|
||||
|
||||
function handleStopGeneration(id: string) {
|
||||
chatStore.stopGenerationForChat(id);
|
||||
}
|
||||
@@ -105,16 +63,8 @@
|
||||
<SidebarNavigationSearchResults
|
||||
{currentChatId}
|
||||
{filteredConversations}
|
||||
onDelete={handleDeleteConversation}
|
||||
onEdit={handleEditConversation}
|
||||
onSelect={selectConversation}
|
||||
onStop={handleStopGeneration}
|
||||
{searchQuery}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DialogConversationDelete
|
||||
bind:open={deleteDialogOpen}
|
||||
onCancel={handleDeleteCancel}
|
||||
onConfirm={handleDeleteConfirm}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
// The share dialog of Llama Hugging Face, against an account it does not call out of: which
|
||||
// datasets it offers as tiles, and that its pick never points at one the account cannot add to.
|
||||
|
||||
import HfShareDialogStoryHost from '../stories/dialogs/HfShareDialogStoryHost.svelte';
|
||||
import {
|
||||
FAKE_OWNER,
|
||||
type FakeAccount,
|
||||
fakeAccountWith
|
||||
} from '../stories/fixtures/hf-fake-account.svelte.ts';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { page, userEvent } from 'vitest/browser';
|
||||
import { render } from 'vitest-browser-svelte';
|
||||
|
||||
function renderDialog(account: FakeAccount) {
|
||||
render(HfShareDialogStoryHost, { account });
|
||||
}
|
||||
|
||||
const tile = (name: string) => page.getByRole('button', { name: new RegExp(`^${name}\\b`) });
|
||||
|
||||
describe('HfShareDialog datasets', () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it('offers the datasets as tiles, with the first picked, and a tile for a new one', async () => {
|
||||
renderDialog(fakeAccountWith('alpha', 'beta'));
|
||||
|
||||
await expect.element(tile('alpha')).toHaveAttribute('aria-pressed', 'true');
|
||||
await expect.element(tile('beta')).toHaveAttribute('aria-pressed', 'false');
|
||||
await expect.element(page.getByRole('button', { name: /^New dataset/ })).toBeVisible();
|
||||
});
|
||||
|
||||
it('goes straight to naming a new dataset when there is none to add to', async () => {
|
||||
renderDialog(fakeAccountWith());
|
||||
|
||||
await expect
|
||||
.element(page.getByLabelText('New dataset name'))
|
||||
.toHaveValue('me/llama-chat-traces');
|
||||
await expect.element(page.getByText('Create a dataset')).toBeVisible();
|
||||
});
|
||||
|
||||
it('shows a few tiles and the rest behind "Show more"', async () => {
|
||||
renderDialog(fakeAccountWith('a', 'b', 'c', 'd', 'e'));
|
||||
|
||||
await expect.element(tile('c')).toBeVisible();
|
||||
expect(page.getByRole('button', { name: /^d\b/ }).elements()).toHaveLength(0);
|
||||
|
||||
await userEvent.click(page.getByRole('button', { name: 'Show 2 more' }));
|
||||
await expect.element(tile('e')).toBeVisible();
|
||||
});
|
||||
|
||||
it('picks again when the Hub turns the picked dataset down, instead of keeping a stale pick', async () => {
|
||||
const account = fakeAccountWith('alpha', 'beta');
|
||||
|
||||
account.refused.add(`${FAKE_OWNER}/alpha`);
|
||||
renderDialog(account);
|
||||
|
||||
await userEvent.click(page.getByRole('button', { exact: true, name: 'Share' }));
|
||||
await expect.element(page.getByText('cannot add traces to me/alpha')).toBeVisible();
|
||||
|
||||
// the refused tile is gone and the next one is picked: Share does not aim at it again
|
||||
expect(page.getByRole('button', { name: /^alpha\b/ }).elements()).toHaveLength(0);
|
||||
await expect.element(tile('beta')).toHaveAttribute('aria-pressed', 'true');
|
||||
|
||||
await userEvent.click(page.getByRole('button', { exact: true, name: 'Share' }));
|
||||
await expect.element(page.getByText('Shared to Hugging Face')).toBeVisible();
|
||||
expect(account.uploads).toEqual([`${FAKE_OWNER}/alpha`, `${FAKE_OWNER}/beta`]);
|
||||
});
|
||||
|
||||
it('picks again for the next account when the signed-in one changes', async () => {
|
||||
const account = fakeAccountWith('alpha');
|
||||
|
||||
renderDialog(account);
|
||||
await expect.element(tile('alpha')).toHaveAttribute('aria-pressed', 'true');
|
||||
|
||||
// another account signs in, with a dataset of its own, while the dialog is open
|
||||
account.user = null;
|
||||
account.datasets = [{ id: 'you/zeta', isPrivate: false }];
|
||||
account.user = { name: 'you' };
|
||||
|
||||
await expect.element(tile('zeta')).toHaveAttribute('aria-pressed', 'true');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,277 @@
|
||||
import {
|
||||
HF_STORAGE_KEY_OAUTH,
|
||||
HF_STORAGE_KEY_SEPARATOR,
|
||||
HF_STORAGE_KEY_TOKEN
|
||||
} from '@ggml-org/llama-huggingface';
|
||||
import { STORAGE_APP_NAME } from '#lib/constants/index.ts';
|
||||
import { huggingFace } from '#lib/stores/huggingface.svelte.ts';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// the sign-in itself is tested in ui/lib/huggingface; these cover what the account does around
|
||||
// it, as Llama Chat sets it up
|
||||
|
||||
const HF_OAUTH_LOCALSTORAGE_KEY = [STORAGE_APP_NAME, HF_STORAGE_KEY_OAUTH].join(
|
||||
HF_STORAGE_KEY_SEPARATOR
|
||||
);
|
||||
const HF_TOKEN_LOCALSTORAGE_KEY = [STORAGE_APP_NAME, HF_STORAGE_KEY_TOKEN].join(
|
||||
HF_STORAGE_KEY_SEPARATOR
|
||||
);
|
||||
|
||||
interface HubMock {
|
||||
/** The datasets the account lists; one of them by default. */
|
||||
datasets?: { id: string; private: boolean }[];
|
||||
/** Status a share's preupload answers with, instead of accepting the file. */
|
||||
preupload?: number;
|
||||
register?: () => Response;
|
||||
whoami?: () => Response;
|
||||
}
|
||||
|
||||
// the Hub's lookup of one dataset: /api/datasets/<owner>/<name>
|
||||
const DATASET_LOOKUP_URL = /\/api\/datasets\/[^/]+\/[^/?]+$/;
|
||||
|
||||
function json(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), { status });
|
||||
}
|
||||
|
||||
function mockHub({ datasets, preupload, register, whoami }: HubMock = {}) {
|
||||
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
|
||||
const url = String(input instanceof Request ? input.url : input);
|
||||
|
||||
if (url.endsWith('/oauth/register')) {
|
||||
return register ? register() : json({ client_id: 'client-1' }, 201);
|
||||
}
|
||||
|
||||
if (url.endsWith('/oauth/token')) {
|
||||
return json({ access_token: 'hf_oauth_a', expires_in: 3600, refresh_token: 'r1' });
|
||||
}
|
||||
|
||||
if (url.endsWith('/api/whoami-v2')) return whoami ? whoami() : json({ name: 'me' });
|
||||
|
||||
if (url.includes('/api/datasets?')) {
|
||||
return json(datasets ?? [{ id: 'me/traces', private: false }]);
|
||||
}
|
||||
|
||||
// a share to a dataset that exists: look it up, check the file, commit it
|
||||
if (DATASET_LOOKUP_URL.test(url)) return json({});
|
||||
|
||||
if (url.endsWith('/preupload/main')) {
|
||||
return preupload
|
||||
? json({ error: 'Forbidden' }, preupload)
|
||||
: json({ files: [{ uploadMode: 'regular' }] });
|
||||
}
|
||||
|
||||
if (url.endsWith('/commit/main')) return json({});
|
||||
|
||||
throw new Error(`unexpected request: ${url}`);
|
||||
});
|
||||
}
|
||||
|
||||
function fakePopup() {
|
||||
return { close: vi.fn(), location: { href: '' } };
|
||||
}
|
||||
|
||||
/** Signs in through a popup, up to Hugging Face sending the browser back. */
|
||||
async function signInWithHuggingFace() {
|
||||
const popup = fakePopup();
|
||||
|
||||
await huggingFace.signInWithHuggingFace(popup as unknown as Window);
|
||||
|
||||
const authorization = new URL(popup.location.href);
|
||||
const callback = new URL(authorization.searchParams.get('redirect_uri') ?? '');
|
||||
|
||||
callback.searchParams.set('code', 'code-1');
|
||||
callback.searchParams.set('state', authorization.searchParams.get('state') ?? '');
|
||||
|
||||
return huggingFace.completeSignInFromLocation(callback);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.removeItem(HF_OAUTH_LOCALSTORAGE_KEY);
|
||||
huggingFace.signOut();
|
||||
huggingFace.oauthError = null;
|
||||
// the callback clears its parameters from the address; leave the test page's own alone
|
||||
vi.spyOn(window.history, 'replaceState').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
huggingFace.cancelSignInWithHf();
|
||||
vi.restoreAllMocks();
|
||||
// other tests share this browser's storage: leave no sign-in behind
|
||||
huggingFace.signOut();
|
||||
});
|
||||
|
||||
describe('the Hugging Face account of Llama Chat', () => {
|
||||
it('signs in with Hugging Face, then checks who signed in and lists their datasets', async () => {
|
||||
mockHub();
|
||||
|
||||
const outcome = await signInWithHuggingFace();
|
||||
|
||||
expect(outcome).toEqual({ closeWindow: true, result: { ok: true } });
|
||||
await vi.waitFor(() => expect(huggingFace.datasets).toHaveLength(1));
|
||||
expect(huggingFace.user?.name).toBe('me');
|
||||
expect(huggingFace.isSigningInWithHf).toBe(false);
|
||||
});
|
||||
|
||||
it('says when the datasets of the signed-in account are listed, so a share can wait for them', async () => {
|
||||
mockHub();
|
||||
expect(huggingFace.hasListedDatasets).toBe(false);
|
||||
|
||||
await signInWithHuggingFace();
|
||||
await vi.waitFor(() => expect(huggingFace.hasListedDatasets).toBe(true));
|
||||
expect(huggingFace.datasets).toHaveLength(1);
|
||||
|
||||
huggingFace.signOut();
|
||||
|
||||
expect(huggingFace.hasListedDatasets).toBe(false);
|
||||
});
|
||||
|
||||
it('points back to token sign-in when Hugging Face will not register the app', async () => {
|
||||
mockHub({ register: () => json({ error: 'invalid_redirect_uri' }, 400) });
|
||||
|
||||
await huggingFace.signInWithHuggingFace(fakePopup() as unknown as Window);
|
||||
|
||||
expect(huggingFace.isSigningInWithHf).toBe(false);
|
||||
expect(huggingFace.oauthError).toContain('does not allow signing in from');
|
||||
expect(huggingFace.oauthError).toContain('Sign in with an access token instead.');
|
||||
});
|
||||
|
||||
it('signs in with a pasted token and refuses one the Hub rejects', async () => {
|
||||
mockHub({ whoami: () => json({ error: 'Invalid credentials' }, 401) });
|
||||
await expect(huggingFace.signIn('hf_bad')).rejects.toThrow('did not accept this token');
|
||||
expect(localStorage.getItem(HF_TOKEN_LOCALSTORAGE_KEY)).toBeNull();
|
||||
|
||||
vi.restoreAllMocks();
|
||||
mockHub();
|
||||
await huggingFace.signIn(' hf_good ');
|
||||
|
||||
expect(huggingFace.user?.name).toBe('me');
|
||||
expect(localStorage.getItem(HF_TOKEN_LOCALSTORAGE_KEY)).toBe('hf_good');
|
||||
});
|
||||
|
||||
it('keeps a remembered token when the Hub cannot be reached, forgets one it rejects', async () => {
|
||||
mockHub();
|
||||
await huggingFace.signIn('hf_good');
|
||||
huggingFace.user = null;
|
||||
|
||||
vi.restoreAllMocks();
|
||||
mockHub({ whoami: () => json({ error: 'Down' }, 503) });
|
||||
await huggingFace.restoreSession();
|
||||
|
||||
expect(localStorage.getItem(HF_TOKEN_LOCALSTORAGE_KEY)).toBe('hf_good');
|
||||
|
||||
vi.restoreAllMocks();
|
||||
mockHub({ whoami: () => json({ error: 'Invalid credentials' }, 401) });
|
||||
await huggingFace.restoreSession();
|
||||
|
||||
expect(localStorage.getItem(HF_TOKEN_LOCALSTORAGE_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it('forgets the account and its last dataset on sign-out', async () => {
|
||||
mockHub();
|
||||
await signInWithHuggingFace();
|
||||
await vi.waitFor(() => expect(huggingFace.user?.name).toBe('me'));
|
||||
huggingFace.lastDataset = 'me/traces';
|
||||
huggingFace.signOut();
|
||||
|
||||
expect(huggingFace.user).toBeNull();
|
||||
expect(huggingFace.suggestedDataset).toBe('');
|
||||
expect(
|
||||
JSON.parse(localStorage.getItem(HF_OAUTH_LOCALSTORAGE_KEY) ?? '{}').tokens
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
describe('the datasets a share can go to', () => {
|
||||
const TRACE = { commitMessage: 'Add trace', content: '{}', isPrivate: false, path: 't.jsonl' };
|
||||
|
||||
// the account remembers what each account shared to, so every test signs in as another one
|
||||
let owner = '';
|
||||
let datasets: { id: string; private: boolean }[] = [];
|
||||
let accountNumber = 0;
|
||||
|
||||
const writableIds = () => huggingFace.writableDatasets.map((dataset) => dataset.id);
|
||||
const whoamiAs = (role?: string) => () =>
|
||||
json({ auth: role ? { accessToken: { role } } : undefined, name: owner });
|
||||
|
||||
beforeEach(() => {
|
||||
owner = `account-${accountNumber++}`;
|
||||
datasets = [
|
||||
{ id: `${owner}/notes`, private: true },
|
||||
{ id: `${owner}/traces`, private: false },
|
||||
{ id: `${owner}/images`, private: false }
|
||||
];
|
||||
});
|
||||
|
||||
it('offers none to a sign-in with Hugging Face, which has shared to none yet', async () => {
|
||||
mockHub({ datasets, whoami: whoamiAs() });
|
||||
await signInWithHuggingFace();
|
||||
await vi.waitFor(() => expect(huggingFace.datasets).toHaveLength(3));
|
||||
|
||||
expect(huggingFace.writableDatasets).toEqual([]);
|
||||
});
|
||||
|
||||
it('offers the ones it shared to, the last one first, and remembers them', async () => {
|
||||
mockHub({ datasets, whoami: whoamiAs() });
|
||||
await signInWithHuggingFace();
|
||||
await vi.waitFor(() => expect(huggingFace.datasets).toHaveLength(3));
|
||||
|
||||
await huggingFace.uploadTrace({ ...TRACE, repoId: `${owner}/images` });
|
||||
await huggingFace.uploadTrace({ ...TRACE, repoId: `${owner}/notes` });
|
||||
|
||||
expect(writableIds()).toEqual([`${owner}/notes`, `${owner}/images`]);
|
||||
|
||||
// the same account signing in again still has them
|
||||
huggingFace.signOut();
|
||||
await signInWithHuggingFace();
|
||||
await vi.waitFor(() => expect(huggingFace.datasets).toHaveLength(3));
|
||||
|
||||
expect(writableIds().sort()).toEqual([`${owner}/images`, `${owner}/notes`]);
|
||||
});
|
||||
|
||||
it('stops offering one the Hub turns down', async () => {
|
||||
mockHub({ datasets, whoami: whoamiAs() });
|
||||
await signInWithHuggingFace();
|
||||
await vi.waitFor(() => expect(huggingFace.datasets).toHaveLength(3));
|
||||
await huggingFace.uploadTrace({ ...TRACE, repoId: `${owner}/images` });
|
||||
|
||||
vi.restoreAllMocks();
|
||||
mockHub({ datasets, preupload: 403, whoami: whoamiAs() });
|
||||
|
||||
await expect(
|
||||
huggingFace.uploadTrace({ ...TRACE, repoId: `${owner}/images` })
|
||||
).rejects.toThrow(`cannot add traces to ${owner}/images`);
|
||||
expect(huggingFace.writableDatasets).toEqual([]);
|
||||
});
|
||||
|
||||
it('offers every one to a pasted token, and none to a token that only reads', async () => {
|
||||
mockHub({ datasets, whoami: whoamiAs('write') });
|
||||
await huggingFace.signIn('hf_good');
|
||||
await vi.waitFor(() => expect(huggingFace.datasets).toHaveLength(3));
|
||||
|
||||
expect(huggingFace.writableDatasets).toHaveLength(3);
|
||||
|
||||
huggingFace.signOut();
|
||||
vi.restoreAllMocks();
|
||||
mockHub({ datasets, whoami: whoamiAs('read') });
|
||||
await huggingFace.signIn('hf_read');
|
||||
await vi.waitFor(() => expect(huggingFace.datasets).toHaveLength(3));
|
||||
|
||||
expect(huggingFace.isReadOnly).toBe(true);
|
||||
expect(huggingFace.writableDatasets).toEqual([]);
|
||||
});
|
||||
|
||||
it('starts a new name with the usual dataset, unless it exists', async () => {
|
||||
mockHub({ datasets, whoami: whoamiAs('write') });
|
||||
await huggingFace.signIn('hf_good');
|
||||
await vi.waitFor(() => expect(huggingFace.datasets).toHaveLength(3));
|
||||
|
||||
expect(huggingFace.newDatasetStart).toBe(`${owner}/llama-chat-traces`);
|
||||
|
||||
huggingFace.datasets = [
|
||||
...huggingFace.datasets,
|
||||
{ id: `${owner}/llama-chat-traces`, isPrivate: false }
|
||||
];
|
||||
|
||||
expect(huggingFace.newDatasetStart).toBe(`${owner}/`);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
<script lang="ts" module>
|
||||
import { fakeAccountWith } from '../fixtures/hf-fake-account.svelte.ts';
|
||||
import HfShareDialogStoryHost from './HfShareDialogStoryHost.svelte';
|
||||
import { defineMeta } from '@storybook/addon-svelte-csf';
|
||||
import { expect, screen, waitFor, within } from 'storybook/test';
|
||||
|
||||
const { Story } = defineMeta({
|
||||
component: HfShareDialogStoryHost,
|
||||
parameters: {
|
||||
layout: 'centered'
|
||||
},
|
||||
tags: ['!dev'],
|
||||
title: 'Llama Chat/Dialogs/HfShareDialog/Accessibility'
|
||||
});
|
||||
</script>
|
||||
|
||||
<Story
|
||||
args={{ account: fakeAccountWith('alpha') }}
|
||||
name="DialogIsNamedAndTakesFocus"
|
||||
play={async () => {
|
||||
const dialog = await screen.findByRole('alertdialog', { name: /Share to Hugging Face/ });
|
||||
|
||||
await waitFor(() => expect(dialog).toContainElement(document.activeElement as HTMLElement));
|
||||
}}
|
||||
/>
|
||||
|
||||
<Story
|
||||
args={{ account: fakeAccountWith('alpha', 'beta') }}
|
||||
name="DatasetsAreOneGroupOfToggleButtons"
|
||||
play={async () => {
|
||||
const group = await screen.findByRole('group', { name: 'Dataset' });
|
||||
const alpha = await within(group).findByRole('button', { name: /^alpha\b/ });
|
||||
const beta = await within(group).findByRole('button', { name: /^beta\b/ });
|
||||
|
||||
await expect(alpha).toHaveAttribute('aria-pressed', 'true');
|
||||
await expect(beta).toHaveAttribute('aria-pressed', 'false');
|
||||
}}
|
||||
/>
|
||||
|
||||
<Story
|
||||
args={{ account: fakeAccountWith('alpha', 'beta') }}
|
||||
name="KeyboardPicksATile"
|
||||
play={async ({ userEvent }) => {
|
||||
const dialog = await screen.findByRole('alertdialog');
|
||||
const alpha = await screen.findByRole('button', { name: /^alpha\b/ });
|
||||
const beta = await screen.findByRole('button', { name: /^beta\b/ });
|
||||
|
||||
// the dialog moves focus itself as it opens: start from the tile once that has settled
|
||||
await waitFor(() => expect(dialog).toContainElement(document.activeElement as HTMLElement));
|
||||
alpha.focus();
|
||||
await expect(alpha).toHaveFocus();
|
||||
await userEvent.tab();
|
||||
await expect(beta).toHaveFocus();
|
||||
|
||||
await userEvent.keyboard('{Enter}');
|
||||
await waitFor(() => expect(beta).toHaveAttribute('aria-pressed', 'true'));
|
||||
await expect(alpha).toHaveAttribute('aria-pressed', 'false');
|
||||
}}
|
||||
/>
|
||||
|
||||
<Story
|
||||
args={{ account: fakeAccountWith() }}
|
||||
name="NewDatasetNameIsLabelled"
|
||||
play={async () => {
|
||||
const field = await screen.findByLabelText('New dataset name');
|
||||
|
||||
// the dialog fades in: it is visible once it has finished
|
||||
await waitFor(() => expect(field).toBeVisible());
|
||||
}}
|
||||
/>
|
||||
@@ -0,0 +1,47 @@
|
||||
<script lang="ts" module>
|
||||
import { fakeAccountWith } from '../fixtures/hf-fake-account.svelte.ts';
|
||||
import HfShareDialogStoryHost from './HfShareDialogStoryHost.svelte';
|
||||
import { defineMeta } from '@storybook/addon-svelte-csf';
|
||||
import { expect, screen, userEvent, waitFor } from 'storybook/test';
|
||||
|
||||
// the dialog that shares a conversation to a Hugging Face dataset; an account with no calls out of it
|
||||
const { Story } = defineMeta({
|
||||
component: HfShareDialogStoryHost,
|
||||
parameters: {
|
||||
layout: 'centered'
|
||||
},
|
||||
title: 'Llama Chat/Dialogs/HfShareDialog'
|
||||
});
|
||||
</script>
|
||||
|
||||
<Story
|
||||
args={{ account: fakeAccountWith('agent-traces', 'llama-chat-traces') }}
|
||||
name="DatasetsToAddTo"
|
||||
/>
|
||||
|
||||
<Story args={{ account: fakeAccountWith() }} name="NoDatasetYet" />
|
||||
|
||||
<Story
|
||||
args={{ account: fakeAccountWith('a', 'b', 'c', 'd', 'e') }}
|
||||
name="MoreDatasets"
|
||||
play={async () => {
|
||||
await userEvent.click(await screen.findByRole('button', { name: 'Show 2 more' }));
|
||||
|
||||
const tile = await screen.findByRole('button', { name: /^e\b/ });
|
||||
|
||||
// the dialog fades in: it is visible once it has finished
|
||||
await waitFor(() => expect(tile).toBeVisible());
|
||||
}}
|
||||
/>
|
||||
|
||||
<Story
|
||||
args={{ account: fakeAccountWith('agent-traces') }}
|
||||
name="Shared"
|
||||
play={async () => {
|
||||
await userEvent.click(await screen.findByRole('button', { name: 'Share' }));
|
||||
|
||||
const title = await screen.findByText('Shared to Hugging Face');
|
||||
|
||||
await waitFor(() => expect(title).toBeVisible());
|
||||
}}
|
||||
/>
|
||||
@@ -0,0 +1,34 @@
|
||||
<script lang="ts">
|
||||
import { asHfAccount, type FakeAccount } from '../fixtures/hf-fake-account.svelte.ts';
|
||||
import type { HfTraceFile } from '@ggml-org/llama-huggingface';
|
||||
import { HfShareDialog } from '@ggml-org/llama-huggingface/svelte';
|
||||
|
||||
// the share dialog, open, on an account that calls out of nowhere: what its stories and its tests share
|
||||
|
||||
interface Props {
|
||||
account: FakeAccount;
|
||||
}
|
||||
|
||||
const SCOPES = [
|
||||
{ id: 'conversation', label: 'This conversation' },
|
||||
{ id: 'branch', label: 'This branch only' }
|
||||
];
|
||||
const TRACE: HfTraceFile = {
|
||||
commitMessage: 'Add trace',
|
||||
content: '{"type":"user","message":{"role":"user","content":"Hello"}}',
|
||||
path: 'trace.jsonl'
|
||||
};
|
||||
|
||||
let { account }: Props = $props();
|
||||
|
||||
let open = $state(true);
|
||||
</script>
|
||||
|
||||
<HfShareDialog
|
||||
bind:open
|
||||
account={asHfAccount(account)}
|
||||
buildTrace={async () => TRACE}
|
||||
onCopyLink={() => {}}
|
||||
scopes={SCOPES}
|
||||
subject="this conversation"
|
||||
/>
|
||||
@@ -0,0 +1,63 @@
|
||||
// A stand-in for the Hugging Face account that the share dialog reads and calls, as plain state:
|
||||
// it calls out of nowhere, so a test or a story can set up who is signed in and which datasets
|
||||
// the account can add to, and watch what the dialog does with them.
|
||||
|
||||
import { type HfDataset, HfNotWritableError } from '@ggml-org/llama-huggingface';
|
||||
import type { HfAccount } from '@ggml-org/llama-huggingface/svelte';
|
||||
import { SvelteSet } from 'svelte/reactivity';
|
||||
|
||||
export const FAKE_OWNER = 'me';
|
||||
export const FAKE_SHARED_URL = 'https://huggingface.co/datasets/me/a/blob/main/t.jsonl';
|
||||
|
||||
/** The part of an account the dialog reads and calls, as plain state. */
|
||||
export class FakeAccount {
|
||||
datasets = $state<HfDataset[]>([]);
|
||||
hasListedDatasets = $state(true);
|
||||
isLoadingDatasets = $state(false);
|
||||
isReadOnly = false;
|
||||
isSigningInWithHf = $state(false);
|
||||
lastDataset = $state<string | null>(null);
|
||||
loadDatasets = async () => {};
|
||||
newDatasetStart = `${FAKE_OWNER}/llama-chat-traces`;
|
||||
oauthError = $state<string | null>(null);
|
||||
/** Repo IDs the Hub turns down. */
|
||||
refused = new SvelteSet<string>();
|
||||
restoreSession = async () => {};
|
||||
signOut = () => {
|
||||
this.user = null;
|
||||
};
|
||||
|
||||
suggestedDataset = '';
|
||||
|
||||
uploads: string[] = [];
|
||||
uploadTrace = async ({ repoId }: { repoId: string }): Promise<string> => {
|
||||
this.uploads.push(repoId);
|
||||
|
||||
if (this.refused.has(repoId)) {
|
||||
// as the real account does: the dataset is not one it can add to any more
|
||||
this.datasets = this.datasets.filter((dataset) => dataset.id !== repoId);
|
||||
|
||||
throw new HfNotWritableError(repoId);
|
||||
}
|
||||
|
||||
return FAKE_SHARED_URL;
|
||||
};
|
||||
user = $state<{ name: string } | null>({ name: FAKE_OWNER });
|
||||
|
||||
get writableDatasets(): HfDataset[] {
|
||||
return this.datasets;
|
||||
}
|
||||
}
|
||||
|
||||
/** An account that can add to datasets of the given names, as the account `me`. */
|
||||
export function fakeAccountWith(...names: string[]): FakeAccount {
|
||||
const account = new FakeAccount();
|
||||
|
||||
account.datasets = names.map((name) => ({ id: `${FAKE_OWNER}/${name}`, isPrivate: false }));
|
||||
|
||||
return account;
|
||||
}
|
||||
|
||||
export function asHfAccount(account: FakeAccount): HfAccount {
|
||||
return account as unknown as HfAccount;
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import { HF_PREVIEW_LINES_MAX, HF_PREVIEW_TEXT_MAX } from '@ggml-org/llama-huggingface';
|
||||
import { ConversationTransferService } from '#lib/services/conversation-transfer.service.ts';
|
||||
import { buildConversationTrace, buildTracePreview } from '#lib/utils/conversation-trace.ts';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
function message(
|
||||
id: string,
|
||||
parent: string | null,
|
||||
children: string[],
|
||||
overrides: Partial<DatabaseMessage> = {}
|
||||
): DatabaseMessage {
|
||||
return {
|
||||
children,
|
||||
content: id,
|
||||
convId: 'conv',
|
||||
id,
|
||||
parent,
|
||||
role: 'user',
|
||||
timestamp: Number(id.replace(/\D/g, '') || 0),
|
||||
type: 'text',
|
||||
...overrides
|
||||
} as DatabaseMessage;
|
||||
}
|
||||
|
||||
// root -> m1 -> m2 -> m3
|
||||
// \-> m4 (another branch, current)
|
||||
const exported: ExportedConversation = {
|
||||
conv: {
|
||||
currNode: 'm4',
|
||||
cwd: '/home/me/project',
|
||||
groupId: 'g1',
|
||||
id: 'conv',
|
||||
lastModified: 4,
|
||||
name: 'Trace test'
|
||||
},
|
||||
group: { id: 'g1', name: 'Work' },
|
||||
messages: [
|
||||
message('root', null, ['m1'], { type: 'root' }),
|
||||
message('m1', 'root', ['m2'], {
|
||||
extra: [{ content: 'notes', name: 'a.txt', type: 'TEXT' } as unknown as DatabaseMessageExtra]
|
||||
}),
|
||||
message('m2', 'm1', ['m3', 'm4'], { role: 'assistant', toolCwd: '/home/me/project' }),
|
||||
message('m3', 'm2', []),
|
||||
message('m4', 'm2', [])
|
||||
]
|
||||
};
|
||||
|
||||
describe('buildConversationTrace', () => {
|
||||
it('keeps the current branch only, without the root', () => {
|
||||
const trace = buildConversationTrace(exported);
|
||||
|
||||
expect(trace.messages.map((m: DatabaseMessage) => m.id)).toEqual(['m1', 'm2', 'm4']);
|
||||
expect(trace.messages[1].children).toEqual(['m4']);
|
||||
expect(trace.conv.currNode).toBe('m4');
|
||||
});
|
||||
|
||||
it('ends the trace at the given message', () => {
|
||||
const trace = buildConversationTrace(exported, { upToMessageId: 'm2' });
|
||||
|
||||
expect(trace.messages.map((m: DatabaseMessage) => m.id)).toEqual(['m1', 'm2']);
|
||||
expect(trace.messages[1].children).toEqual([]);
|
||||
expect(trace.conv.currNode).toBe('m2');
|
||||
});
|
||||
|
||||
it('leaves local paths, the group and attachments on this device', () => {
|
||||
const trace = buildConversationTrace(exported);
|
||||
|
||||
expect(trace.conv).not.toHaveProperty('cwd');
|
||||
expect(trace.conv).not.toHaveProperty('groupId');
|
||||
expect(trace).not.toHaveProperty('group');
|
||||
expect(trace.messages[0]).not.toHaveProperty('extra');
|
||||
expect(trace.messages[1]).not.toHaveProperty('toolCwd');
|
||||
});
|
||||
|
||||
it('keeps attachments when asked to', () => {
|
||||
const trace = buildConversationTrace(exported, { includeAttachments: true });
|
||||
|
||||
expect(trace.messages[0].extra).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('serializes to the Session Traces Format the Hub reads', () => {
|
||||
const jsonl = ConversationTransferService.serializeSessionToJsonl(
|
||||
buildConversationTrace(exported)
|
||||
);
|
||||
const [header, ...lines] = jsonl.split('\n').map((line) => JSON.parse(line));
|
||||
|
||||
expect(header).toMatchObject({ harness: 'llama.app', id: 'conv', type: 'session' });
|
||||
expect(lines).toHaveLength(3);
|
||||
expect(lines[0]).toMatchObject({ message: { content: 'm1', role: 'user' }, type: 'message' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildTracePreview', () => {
|
||||
function talk(overrides: Record<string, Partial<DatabaseMessage>>): ExportedConversation {
|
||||
const ids = ['u1', 'a1', 'u2', 'a2', 'u3', 'a3'];
|
||||
|
||||
return {
|
||||
conv: { ...exported.conv, currNode: 'a3' },
|
||||
messages: ids.map((id, index) =>
|
||||
message(id, index ? ids[index - 1] : null, ids[index + 1] ? [ids[index + 1]] : [], {
|
||||
content: `${id} said`,
|
||||
role: id.startsWith('u') ? 'user' : 'assistant',
|
||||
...overrides[id]
|
||||
})
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
it("takes the first messages, up to the package's cap, one line each, by who said them", () => {
|
||||
const preview = buildTracePreview(talk({}));
|
||||
|
||||
expect(preview).toHaveLength(HF_PREVIEW_LINES_MAX);
|
||||
expect(preview.slice(0, 2)).toEqual([
|
||||
{ role: 'user', text: 'u1 said' },
|
||||
{ role: 'assistant', text: 'a1 said' }
|
||||
]);
|
||||
});
|
||||
|
||||
it('skips what is not talk: tool calls, reasoning, messages the app made, empty ones', () => {
|
||||
const preview = buildTracePreview(
|
||||
talk({
|
||||
a1: { content: '' },
|
||||
a2: { isSynthetic: true },
|
||||
u2: { type: 'think' },
|
||||
u3: { role: 'tool' }
|
||||
})
|
||||
);
|
||||
|
||||
expect(preview).toEqual([
|
||||
{ role: 'user', text: 'u1 said' },
|
||||
{ role: 'assistant', text: 'a3 said' }
|
||||
]);
|
||||
});
|
||||
|
||||
it('folds whitespace and cuts a long message', () => {
|
||||
const [line] = buildTracePreview(
|
||||
talk({ u1: { content: ` one\n\n two\t${'x'.repeat(400)}` } })
|
||||
);
|
||||
|
||||
expect(line.text.startsWith('one two xxx')).toBe(true);
|
||||
expect(line.text).toHaveLength(HF_PREVIEW_TEXT_MAX);
|
||||
});
|
||||
|
||||
it('leaves out code blocks, and a message that is only code', () => {
|
||||
const preview = buildTracePreview(
|
||||
talk({
|
||||
a1: { content: '```rust\nfn main() {}\n```' },
|
||||
u1: { content: 'Fix `foo`:\n```rust\nfn main() {}\n```\nthanks' },
|
||||
u2: { content: 'cut short\n```rust\nfn ma' }
|
||||
})
|
||||
);
|
||||
|
||||
expect(preview.map((line) => line.text).slice(0, 2)).toEqual(['Fix foo: thanks', 'cut short']);
|
||||
});
|
||||
|
||||
it('is empty for a conversation with no talk', () => {
|
||||
expect(buildTracePreview({ conv: exported.conv, messages: [] })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -6,7 +6,13 @@ import { describe, expect, it } from 'vitest';
|
||||
// Type is set through the roles in ui/lib/ui/src/lib/styles/tokens/semantic.css (text-body-sm, text-label,
|
||||
// text-caption ...), never Tailwind's own sizes or a size in brackets: see Typography in DESIGN.md.
|
||||
const ui = fileURLToPath(new URL('../../../../', import.meta.url));
|
||||
const ROOTS = ['apps/chat/src', 'apps/chat/tests/stories', 'lib/ui/src', 'lib/ui/tests/stories'];
|
||||
const ROOTS = [
|
||||
'apps/chat/src',
|
||||
'apps/chat/tests/stories',
|
||||
'lib/huggingface/src',
|
||||
'lib/ui/src',
|
||||
'lib/ui/tests/stories'
|
||||
];
|
||||
const SOURCE = /\.(svelte|ts|js|css|svx)$/;
|
||||
const TAILWIND_SIZE = /(?<![\w-])text-(?:xs|sm|base|lg|xl|[2-9]xl)(?![\w-])/g;
|
||||
// a size relative to the text around it (text-[0.875em]) is not one off the scale
|
||||
@@ -16,6 +22,8 @@ const BRACKET_SIZE = /(?<![\w-])text-\[[\d.]+(?:px|rem)\]/g;
|
||||
const TAILWIND_SHADOW = /(?<![\w-])shadow-(?:2xs|xs|sm|md|lg|xl|2xl)(?![\w-])/g;
|
||||
const CORNER_ROLE =
|
||||
/(?<![\w-])rounded(?:-[a-z]{1,2})?-(?:control|panel|card|container|surface)(?![\w])/g;
|
||||
// sharing is one icon everywhere, the box with an arrow leaving it: see Sharing in DESIGN.md
|
||||
const SHARE2_ICON = /(?<![\w-])(?:Share2|share-2)(?![\w-])/g;
|
||||
|
||||
function sources(dir: string): string[] {
|
||||
return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
|
||||
@@ -54,3 +62,9 @@ describe('shadows and corners', () => {
|
||||
expect(matches(CORNER_ROLE)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('icons', () => {
|
||||
it('shares with no other icon than Share', () => {
|
||||
expect(matches(SHARE2_ICON)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
"@ggml-org/llama-ui": ["../../lib/ui/src/lib/index.ts"],
|
||||
"@ggml-org/llama-voice": ["../../lib/voice/src/index.ts"],
|
||||
"@ggml-org/llama-voice/svelte": ["../../lib/voice/src/svelte/index.ts"],
|
||||
"@ggml-org/llama-huggingface": ["../../lib/huggingface/src/index.ts"],
|
||||
"@ggml-org/llama-huggingface/svelte": ["../../lib/huggingface/src/svelte/index.ts"],
|
||||
"$llama-ui-stories/*": ["../../lib/ui/tests/stories/*"],
|
||||
"@internationalized/date": ["./node_modules/@internationalized/date"],
|
||||
"@internationalized/date/*": ["./node_modules/@internationalized/date/*"],
|
||||
@@ -67,6 +69,8 @@
|
||||
"tests/**/*.svelte",
|
||||
".storybook/**/*.ts",
|
||||
"../../lib/ui/tests/stories/svx.d.ts",
|
||||
"../../lib/huggingface/src/**/*.ts",
|
||||
"../../lib/huggingface/src/**/*.svelte",
|
||||
".storybook/**/*.svelte"
|
||||
],
|
||||
"exclude": ["src/lib/services/sandbox-worker.js", "src/lib/vendors/**", "src/service-worker"]
|
||||
|
||||
@@ -17,6 +17,8 @@ import { defineConfig, loadEnv, searchForWorkspaceRoot } from 'vite';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const LLAMA_VOICE_SOURCE = resolve(__dirname, '../../lib/voice/src');
|
||||
// Llama Hugging Face has no build step in the repo either: the app compiles it from source
|
||||
const LLAMA_HUGGINGFACE_ROOT = resolve(__dirname, '../../lib/huggingface');
|
||||
// the harness has no build step in the repo: the app compiles it from source
|
||||
const LLAMA_HARNESS_ENTRY = resolve(__dirname, '../../lib/harness/src/index.ts');
|
||||
const LLAMA_HARNESS_TRACE_ENTRY = resolve(__dirname, '../../lib/harness/src/trace/index.ts');
|
||||
@@ -25,6 +27,13 @@ const LLAMA_HARNESS_CHAT_ONLY_ENTRY = resolve(
|
||||
__dirname,
|
||||
'src/lib/stores/agentic/harness-chat-only.ts'
|
||||
);
|
||||
// what a build without sharing to Hugging Face (a build that is not asked for it with
|
||||
// VITE_PUBLIC_HUGGING_FACE=true) gets in place of the package's Svelte entry: an account that is
|
||||
// never signed in, and components that draw nothing
|
||||
const LLAMA_HUGGINGFACE_DISABLED_ENTRY = resolve(
|
||||
__dirname,
|
||||
'src/lib/stores/huggingface-disabled.ts'
|
||||
);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const browserBaseConfig: any = {
|
||||
enabled: true,
|
||||
@@ -41,9 +50,14 @@ const browserBaseConfig: any = {
|
||||
// `npm run build` runs without the env var default to ./dist.
|
||||
const outDir = process.env.LLAMA_UI_OUT_DIR ?? './dist';
|
||||
|
||||
export default defineConfig(({ mode }) => {
|
||||
export default defineConfig(({ command, mode }) => {
|
||||
const env = loadEnv(mode, process.cwd(), 'VITE_PUBLIC_');
|
||||
const SERVER_ORIGIN = env.VITE_PUBLIC_SERVER_ORIGIN || 'http://localhost:9931';
|
||||
// A build has sharing to Hugging Face only when asked for: VITE_PUBLIC_HUGGING_FACE=true. The
|
||||
// dev server, the tests and Storybook have it unless told otherwise (=false).
|
||||
const huggingFace = env.VITE_PUBLIC_HUGGING_FACE
|
||||
? env.VITE_PUBLIC_HUGGING_FACE === 'true'
|
||||
: command === 'serve';
|
||||
|
||||
return {
|
||||
build: {
|
||||
@@ -52,6 +66,11 @@ export default defineConfig(({ mode }) => {
|
||||
minify: true
|
||||
},
|
||||
|
||||
// what the app reads as HUGGING_FACE_ENABLED, so it agrees with the alias below
|
||||
define: {
|
||||
'import.meta.env.VITE_PUBLIC_HUGGING_FACE': JSON.stringify(String(huggingFace))
|
||||
},
|
||||
|
||||
plugins: [
|
||||
llamaUiPlugin(),
|
||||
tailwindcss(),
|
||||
@@ -93,6 +112,16 @@ export default defineConfig(({ mode }) => {
|
||||
replacement: resolve(LLAMA_VOICE_SOURCE, 'svelte/index.ts')
|
||||
},
|
||||
{ find: /^@ggml-org\/llama-voice$/, replacement: resolve(LLAMA_VOICE_SOURCE, 'index.ts') },
|
||||
{
|
||||
find: /^@ggml-org\/llama-huggingface\/svelte$/,
|
||||
replacement: huggingFace
|
||||
? resolve(LLAMA_HUGGINGFACE_ROOT, 'src/svelte/index.ts')
|
||||
: LLAMA_HUGGINGFACE_DISABLED_ENTRY
|
||||
},
|
||||
{
|
||||
find: /^@ggml-org\/llama-huggingface$/,
|
||||
replacement: resolve(LLAMA_HUGGINGFACE_ROOT, 'src/index.ts')
|
||||
},
|
||||
{ find: /^@ggml-org\/llama-harness\/trace$/, replacement: LLAMA_HARNESS_TRACE_ENTRY },
|
||||
{
|
||||
find: /^@ggml-org\/llama-harness$/,
|
||||
@@ -111,6 +140,7 @@ export default defineConfig(({ mode }) => {
|
||||
searchForWorkspaceRoot(process.cwd()),
|
||||
resolve(__dirname, 'tests'),
|
||||
LLAMA_VOICE_SOURCE,
|
||||
LLAMA_HUGGINGFACE_ROOT,
|
||||
resolve(__dirname, '../../lib/harness')
|
||||
]
|
||||
},
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
node_modules
|
||||
/dist
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
@@ -0,0 +1 @@
|
||||
engine-strict=true
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"useTabs": true,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "none",
|
||||
"printWidth": 100,
|
||||
"plugins": ["prettier-plugin-svelte", "prettier-plugin-tailwindcss"],
|
||||
"overrides": [
|
||||
{
|
||||
"files": "*.svelte",
|
||||
"options": {
|
||||
"parser": "svelte"
|
||||
}
|
||||
}
|
||||
],
|
||||
"tailwindStylesheet": "../../apps/chat/src/app.css"
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) ggml
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,69 @@
|
||||
# Llama Hugging Face
|
||||
|
||||
`@ggml-org/llama-huggingface` gives an app that runs in the browser, with no server of its own, a Hugging Face account: signing in, and sharing a conversation to a dataset as an [agent trace](https://huggingface.co/docs/hub/agent-traces).
|
||||
|
||||
It knows no app. The app says who it is, hands over what to share, and decides where the components show.
|
||||
|
||||
| Entry | What it holds |
|
||||
| ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `@ggml-org/llama-huggingface` | Plain TypeScript, no dependencies: "Sign in with Hugging Face" (OAuth with PKCE and dynamic client registration, `HfOAuthSignIn`) and the Hub calls (`whoAmI`, `listDatasets`, `uploadTrace`). |
|
||||
| `@ggml-org/llama-huggingface/svelte` | The account as Svelte state (`HfAccount`) and the components that show it, built on `@ggml-org/llama-ui`: `HfAccountPanel`, `HfShareDialog`, `HfLogo`. |
|
||||
|
||||
## Use
|
||||
|
||||
```ts
|
||||
import { HfAccount } from '@ggml-org/llama-huggingface/svelte';
|
||||
|
||||
export const account = new HfAccount({
|
||||
callbackUrl: () => new URL('/', window.location.origin).href,
|
||||
clientName: 'My app',
|
||||
defaultDatasetName: 'my-app-traces',
|
||||
logoUrl: 'https://example.com/my-app.png', // optional: shown for the app on Hugging Face
|
||||
requiredScope: 'contribute-repos',
|
||||
scopes: ['openid', 'profile', 'contribute-repos'],
|
||||
storagePrefix: 'my-app'
|
||||
});
|
||||
|
||||
// on every page load: finishes a sign-in when Hugging Face sent the browser back
|
||||
const outcome = await account.completeSignInFromLocation();
|
||||
|
||||
if (outcome?.closeWindow) window.close();
|
||||
```
|
||||
|
||||
```svelte
|
||||
<script lang="ts">
|
||||
import { HfAccountPanel, HfShareDialog } from '@ggml-org/llama-huggingface/svelte';
|
||||
</script>
|
||||
|
||||
<!-- who is signed in, or the two ways to sign in: a button, or a pasted access token -->
|
||||
<HfAccountPanel {account} />
|
||||
|
||||
<HfShareDialog
|
||||
bind:open
|
||||
{account}
|
||||
buildTrace={async (scope, includeAttachments) => ({
|
||||
commitMessage: 'Add trace: my chat',
|
||||
content: jsonl, // Session Traces Format, one JSON object per line
|
||||
path: 'my-chat.jsonl',
|
||||
preview: [{ role: 'user', text: 'What is Rust?' }] // optional: shown faded once it is shared
|
||||
})}
|
||||
onCopyLink={(url) => navigator.clipboard.writeText(url)}
|
||||
scopes={[{ id: 'all', label: 'Whole conversation', detail: '12 messages' }]}
|
||||
subject={'"My chat"'}
|
||||
/>
|
||||
```
|
||||
|
||||
- The share dialog offers the datasets a share can go to as tiles, and a tile to create one. An access token that was pasted reaches every dataset of the account; a sign-in with Hugging Face reaches only the ones the app created, which the browser knows as the ones it shared to (`HfAccount.writableDatasets`). With none, the dialog asks for the name of a new one.
|
||||
- A sign-in opens the Hugging Face authorization page in a popup, or in the tab when the popup is blocked. The app registers itself for its own origin on first use, so it works from any host and port.
|
||||
- The sign-in and the pasted token are kept in `localStorage`, under the app's `storagePrefix`.
|
||||
- With `contribute-repos`, a sign-in can write only to the datasets the app created; a pasted access token with write access is not limited that way.
|
||||
|
||||
## Development
|
||||
|
||||
The package has no build step and is not published yet: apps in this repo compile its sources, and its components are type-checked by the app that uses them.
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run check
|
||||
npm test
|
||||
```
|
||||
Generated
+1474
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"name": "@ggml-org/llama-huggingface",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "A Hugging Face account for llama.cpp frontend apps: sign in from the browser and share conversations as agent traces.",
|
||||
"homepage": "https://github.com/ggml-org/llama.cpp/tree/master/ui/lib/huggingface",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/ggml-org/llama.cpp.git",
|
||||
"directory": "ui/lib/huggingface"
|
||||
},
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./svelte": {
|
||||
"svelte": "./src/svelte/index.ts",
|
||||
"default": "./src/svelte/index.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"check": "tsc --noEmit",
|
||||
"test": "vitest --run"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@ggml-org/llama-ui": "^0.7.0",
|
||||
"@lucide/svelte": "^1.0.0",
|
||||
"svelte": "^5.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@ggml-org/llama-ui": {
|
||||
"optional": true
|
||||
},
|
||||
"@lucide/svelte": {
|
||||
"optional": true
|
||||
},
|
||||
"svelte": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "24.19.2",
|
||||
"svelte": "5.57.3",
|
||||
"typescript": "6.0.3",
|
||||
"vitest": "5.0.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* The OAuth calls of a public client in the browser: dynamic client registration, then the
|
||||
* authorization code flow with PKCE. The endpoints answer cross-origin requests, so no server
|
||||
* is involved. Stateless: HfOAuthSignIn (./sign-in.ts) keeps what a sign-in needs between them.
|
||||
*/
|
||||
|
||||
import {
|
||||
HF_CONTENT_TYPE_FORM,
|
||||
HF_CONTENT_TYPE_JSON,
|
||||
HF_HEADER_CONTENT_TYPE,
|
||||
HF_HTTP_CLIENT_ERROR_MIN,
|
||||
HF_HTTP_POST,
|
||||
HF_HTTP_SERVER_ERROR_MIN,
|
||||
HF_MS_PER_SECOND,
|
||||
HF_OAUTH_AUTHORIZE_URL,
|
||||
HF_OAUTH_CODE_CHALLENGE_HASH,
|
||||
HF_OAUTH_CODE_CHALLENGE_METHOD,
|
||||
HF_OAUTH_RANDOM_BYTES,
|
||||
HF_OAUTH_REGISTER_URL,
|
||||
HF_OAUTH_RESPONSE_TYPE,
|
||||
HF_OAUTH_SCOPE_SEPARATOR,
|
||||
HF_OAUTH_TOKEN_ENDPOINT_AUTH_METHOD,
|
||||
HF_OAUTH_TOKEN_URL
|
||||
} from './constants.js';
|
||||
import { HfOAuthGrantType, HfOAuthParam } from './enums.js';
|
||||
import { HfTokenRejectedError } from './errors.js';
|
||||
import { HF_ACTION, type HfAction, HF_MESSAGE } from './messages.js';
|
||||
import type {
|
||||
HfOAuthClient,
|
||||
HfOAuthTokens,
|
||||
HfRegistrationResponse,
|
||||
HfTokenResponse
|
||||
} from './types.js';
|
||||
import { bytesToBase64Url } from './util.js';
|
||||
|
||||
/** A random URL-safe string: a PKCE verifier, or a state. */
|
||||
export function createRandomString(): string {
|
||||
return bytesToBase64Url(crypto.getRandomValues(new Uint8Array(HF_OAUTH_RANDOM_BYTES)));
|
||||
}
|
||||
|
||||
/** The S256 challenge of a PKCE verifier. */
|
||||
export async function createCodeChallenge(verifier: string): Promise<string> {
|
||||
// the Web Crypto digest exists only on a secure page
|
||||
if (!globalThis.crypto?.subtle) throw new Error(HF_MESSAGE.SECURE_PAGE_NEEDED);
|
||||
|
||||
const digest = await crypto.subtle.digest(
|
||||
HF_OAUTH_CODE_CHALLENGE_HASH,
|
||||
new TextEncoder().encode(verifier)
|
||||
);
|
||||
|
||||
return bytesToBase64Url(new Uint8Array(digest));
|
||||
}
|
||||
|
||||
/** The OAuth error of a failed response, as one readable line. */
|
||||
async function describeError(response: Response): Promise<string> {
|
||||
try {
|
||||
const body = await response.json();
|
||||
const parts = [body?.[HfOAuthParam.ERROR], body?.[HfOAuthParam.ERROR_DESCRIPTION]].filter(
|
||||
(part) => typeof part === 'string' && part
|
||||
);
|
||||
|
||||
if (parts.length) return parts.join(': ');
|
||||
} catch {
|
||||
// not JSON; keep the status
|
||||
}
|
||||
|
||||
return HF_MESSAGE.status(response.status);
|
||||
}
|
||||
|
||||
/** A POST that says `unreachable` when no answer comes, instead of the browser's own error. */
|
||||
async function post(
|
||||
url: string,
|
||||
body: string,
|
||||
contentType: string,
|
||||
unreachable: string
|
||||
): Promise<Response> {
|
||||
try {
|
||||
return await fetch(url, {
|
||||
body,
|
||||
headers: { [HF_HEADER_CONTENT_TYPE]: contentType },
|
||||
method: HF_HTTP_POST
|
||||
});
|
||||
} catch {
|
||||
throw new Error(unreachable);
|
||||
}
|
||||
}
|
||||
|
||||
async function requestTokens(
|
||||
fields: Record<string, string>,
|
||||
action: HfAction
|
||||
): Promise<HfOAuthTokens> {
|
||||
const now = Date.now();
|
||||
const response = await post(
|
||||
HF_OAUTH_TOKEN_URL,
|
||||
new URLSearchParams(fields).toString(),
|
||||
HF_CONTENT_TYPE_FORM,
|
||||
HF_MESSAGE.tokenRequestUnreachable(action)
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const message = HF_MESSAGE.tokenRequestFailed(action, await describeError(response));
|
||||
|
||||
// a 4xx is the endpoint saying no, for good; a 5xx may pass
|
||||
throw response.status >= HF_HTTP_CLIENT_ERROR_MIN && response.status < HF_HTTP_SERVER_ERROR_MIN
|
||||
? new HfTokenRejectedError(message)
|
||||
: new Error(message);
|
||||
}
|
||||
|
||||
const body: HfTokenResponse = await response.json();
|
||||
|
||||
if (typeof body?.access_token !== 'string') throw new Error(HF_MESSAGE.ACCESS_TOKEN_MISSING);
|
||||
|
||||
return {
|
||||
accessToken: body.access_token,
|
||||
expiresAt:
|
||||
typeof body.expires_in === 'number' ? now + body.expires_in * HF_MS_PER_SECOND : undefined,
|
||||
refreshToken: typeof body.refresh_token === 'string' ? body.refresh_token : undefined,
|
||||
scope: typeof body.scope === 'string' ? body.scope : undefined
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the app as a public client for one redirect URL.
|
||||
* @returns The client ID
|
||||
* @throws When Hugging Face turns the registration down
|
||||
*/
|
||||
export async function registerClient(client: HfOAuthClient): Promise<string> {
|
||||
const response = await post(
|
||||
HF_OAUTH_REGISTER_URL,
|
||||
JSON.stringify({
|
||||
client_name: client.clientName,
|
||||
grant_types: [HfOAuthGrantType.AUTHORIZATION_CODE, HfOAuthGrantType.REFRESH_TOKEN],
|
||||
logo_uri: client.logoUrl,
|
||||
redirect_uris: [client.redirectUrl],
|
||||
response_types: [HF_OAUTH_RESPONSE_TYPE],
|
||||
scope: client.scopes.join(HF_OAUTH_SCOPE_SEPARATOR),
|
||||
token_endpoint_auth_method: HF_OAUTH_TOKEN_ENDPOINT_AUTH_METHOD
|
||||
}),
|
||||
HF_CONTENT_TYPE_JSON,
|
||||
HF_MESSAGE.APP_NOT_REGISTERED
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
HF_MESSAGE.registrationRefused(
|
||||
new URL(client.redirectUrl).origin,
|
||||
await describeError(response)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const body: HfRegistrationResponse = await response.json();
|
||||
|
||||
if (typeof body?.client_id !== 'string') throw new Error(HF_MESSAGE.CLIENT_ID_MISSING);
|
||||
|
||||
return body.client_id;
|
||||
}
|
||||
|
||||
/** The Hugging Face page that asks the user to let the app in. */
|
||||
export function authorizationUrl(params: {
|
||||
clientId: string;
|
||||
codeChallenge: string;
|
||||
redirectUrl: string;
|
||||
scopes: readonly string[];
|
||||
state: string;
|
||||
}): URL {
|
||||
const url = new URL(HF_OAUTH_AUTHORIZE_URL);
|
||||
|
||||
url.searchParams.set(HfOAuthParam.CLIENT_ID, params.clientId);
|
||||
url.searchParams.set(HfOAuthParam.CODE_CHALLENGE, params.codeChallenge);
|
||||
url.searchParams.set(HfOAuthParam.CODE_CHALLENGE_METHOD, HF_OAUTH_CODE_CHALLENGE_METHOD);
|
||||
url.searchParams.set(HfOAuthParam.REDIRECT_URI, params.redirectUrl);
|
||||
url.searchParams.set(HfOAuthParam.RESPONSE_TYPE, HF_OAUTH_RESPONSE_TYPE);
|
||||
url.searchParams.set(HfOAuthParam.SCOPE, params.scopes.join(HF_OAUTH_SCOPE_SEPARATOR));
|
||||
url.searchParams.set(HfOAuthParam.STATE, params.state);
|
||||
|
||||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trades the code the authorization page sent back for tokens.
|
||||
* @throws When Hugging Face refuses the code
|
||||
*/
|
||||
export function exchangeCode(params: {
|
||||
clientId: string;
|
||||
code: string;
|
||||
codeVerifier: string;
|
||||
redirectUrl: string;
|
||||
}): Promise<HfOAuthTokens> {
|
||||
return requestTokens(
|
||||
{
|
||||
[HfOAuthParam.CLIENT_ID]: params.clientId,
|
||||
[HfOAuthParam.CODE]: params.code,
|
||||
[HfOAuthParam.CODE_VERIFIER]: params.codeVerifier,
|
||||
[HfOAuthParam.GRANT_TYPE]: HfOAuthGrantType.AUTHORIZATION_CODE,
|
||||
[HfOAuthParam.REDIRECT_URI]: params.redirectUrl
|
||||
},
|
||||
HF_ACTION.SIGN_IN
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a new access token with a refresh token.
|
||||
* @throws HfTokenRejectedError when the refresh token is no longer good; any other error when
|
||||
* Hugging Face could not be reached or failed
|
||||
*/
|
||||
export async function refreshTokens(
|
||||
clientId: string,
|
||||
refreshToken: string
|
||||
): Promise<HfOAuthTokens> {
|
||||
const tokens = await requestTokens(
|
||||
{
|
||||
[HfOAuthParam.CLIENT_ID]: clientId,
|
||||
[HfOAuthParam.GRANT_TYPE]: HfOAuthGrantType.REFRESH_TOKEN,
|
||||
[HfOAuthParam.REFRESH_TOKEN]: refreshToken
|
||||
},
|
||||
HF_ACTION.SIGN_IN_RENEWAL
|
||||
);
|
||||
|
||||
// a refresh may hand out no new refresh token: the old one stays good
|
||||
return { ...tokens, refreshToken: tokens.refreshToken ?? refreshToken };
|
||||
}
|
||||
|
||||
/** Whether tokens carry a scope; tokens that do not say which they carry are let through. */
|
||||
export function hasScope(tokens: HfOAuthTokens, scope: string): boolean {
|
||||
return !tokens.scope || tokens.scope.split(HF_OAUTH_SCOPE_SEPARATOR).includes(scope);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user