mirror of
https://github.com/ggml-org/llama.cpp.git
synced 2026-11-26 12:47:42 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fa9f928f25 | ||
|
|
0e4e925e8f | ||
|
|
6aad4c7efd | ||
|
|
46ba8b7008 | ||
|
|
436d7e81ca | ||
|
|
a866b4ade6 | ||
|
|
4ba835c637 | ||
|
|
689194808a | ||
|
|
fd4b137e38 | ||
|
|
55d482814b | ||
|
|
7365e4793c | ||
|
|
b16f15350a | ||
|
|
b671865c7b | ||
|
|
8c6418001d | ||
|
|
09c1410642 |
@@ -49,94 +49,94 @@ env:
|
||||
|
||||
jobs:
|
||||
gpu-vulkan-nvidia-cm:
|
||||
# runs-on: "hf-jobs-t4-small:ubuntu26_04"
|
||||
runs-on: [self-hosted, Linux, NVIDIA]
|
||||
runs-on: [self-hosted, Linux, gb10]
|
||||
container: "ubuntu:26.04"
|
||||
|
||||
steps:
|
||||
- name: Clone
|
||||
id: checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
# - name: Install dependencies
|
||||
# run: |
|
||||
# sudo apt update
|
||||
# sudo apt install -y build-essential cmake libxcb-xinput0 libxcb-xinerama0 libxcb-cursor-dev libvulkan-dev glslc spirv-headers vulkan-tools mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 libssl-dev time unzip wget python3 python3-venv python3-pip
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
apt update
|
||||
apt install -y build-essential cmake jq git git-lfs libxcb-xinput0 libxcb-xinerama0 libxcb-cursor-dev libvulkan-dev glslc spirv-headers vulkan-tools mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 libssl-dev time unzip wget python3 python3-venv python3-pip
|
||||
|
||||
# - name: ccache
|
||||
# uses: ggml-org/ccache-action@v1.2.24
|
||||
# with:
|
||||
# restore: false
|
||||
# save: false
|
||||
- name: ccache
|
||||
uses: ggml-org/ccache-action@v1.2.24
|
||||
with:
|
||||
restore: false
|
||||
save: false
|
||||
|
||||
# - name: ccache-buckets-restore
|
||||
# uses: ./.github/actions/ccache-buckets
|
||||
# with:
|
||||
# key: self-hosted-vulkan-nvidia-cm
|
||||
# folder: llama.cpp
|
||||
# hf_bucket: ggml-org/cache
|
||||
- name: ccache-buckets-restore
|
||||
uses: ./.github/actions/ccache-buckets
|
||||
with:
|
||||
key: self-hosted-vulkan-nvidia-cm-gb10
|
||||
folder: llama.cpp
|
||||
hf_bucket: ggml-org/cache
|
||||
|
||||
- name: Test
|
||||
id: ggml-ci
|
||||
run: |
|
||||
vulkaninfo --summary
|
||||
GG_BUILD_VULKAN=1 GGML_VK_DISABLE_COOPMAT2=1 bash ./ci/run.sh ~/results/llama.cpp/$RUNNER_NAME ~/mnt/llama.cpp
|
||||
GG_BUILD_VULKAN=1 GGML_VK_DISABLE_COOPMAT2=1 bash ./ci/run.sh ~/results/llama.cpp /mnt/cache/llama.cpp
|
||||
|
||||
# - name: ccache-buckets-save
|
||||
# if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
|
||||
# uses: ./.github/actions/ccache-buckets
|
||||
# env:
|
||||
# HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
|
||||
# with:
|
||||
# key: self-hosted-vulkan-nvidia-cm
|
||||
# folder: llama.cpp
|
||||
# evict-old-files: 1d
|
||||
# hf_bucket: ggml-org/cache
|
||||
# save: true
|
||||
- name: ccache-buckets-save
|
||||
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
|
||||
uses: ./.github/actions/ccache-buckets
|
||||
env:
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
|
||||
with:
|
||||
key: self-hosted-vulkan-nvidia-cm-gb10
|
||||
folder: llama.cpp
|
||||
evict-old-files: 1d
|
||||
hf_bucket: ggml-org/cache
|
||||
save: true
|
||||
|
||||
gpu-vulkan-nvidia-cm2:
|
||||
# runs-on: "hf-jobs-t4-small:ubuntu26_04"
|
||||
runs-on: [self-hosted, Linux, NVIDIA, COOPMAT2]
|
||||
runs-on: [self-hosted, Linux, gb10]
|
||||
container: "ubuntu:26.04"
|
||||
|
||||
steps:
|
||||
- name: Clone
|
||||
id: checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
# - name: Install dependencies
|
||||
# run: |
|
||||
# sudo apt update
|
||||
# sudo apt install -y build-essential cmake libxcb-xinput0 libxcb-xinerama0 libxcb-cursor-dev libvulkan-dev glslc spirv-headers vulkan-tools mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 libssl-dev time unzip wget python3 python3-venv python3-pip
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
apt update
|
||||
apt install -y build-essential cmake jq git git-lfs libxcb-xinput0 libxcb-xinerama0 libxcb-cursor-dev libvulkan-dev glslc spirv-headers vulkan-tools mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 libssl-dev time unzip wget python3 python3-venv python3-pip
|
||||
|
||||
# - name: ccache
|
||||
# uses: ggml-org/ccache-action@v1.2.24
|
||||
# with:
|
||||
# restore: false
|
||||
# save: false
|
||||
- name: ccache
|
||||
uses: ggml-org/ccache-action@v1.2.24
|
||||
with:
|
||||
restore: false
|
||||
save: false
|
||||
|
||||
# - name: ccache-buckets-restore
|
||||
# uses: ./.github/actions/ccache-buckets
|
||||
# with:
|
||||
# key: self-hosted-vulkan-nvidia-cm2
|
||||
# folder: llama.cpp
|
||||
# hf_bucket: ggml-org/cache
|
||||
- name: ccache-buckets-restore
|
||||
uses: ./.github/actions/ccache-buckets
|
||||
with:
|
||||
key: self-hosted-vulkan-nvidia-cm2-gb10
|
||||
folder: llama.cpp
|
||||
hf_bucket: ggml-org/cache
|
||||
|
||||
- name: Test
|
||||
id: ggml-ci
|
||||
run: |
|
||||
vulkaninfo --summary
|
||||
GG_BUILD_VULKAN=1 bash ./ci/run.sh ~/results/llama.cpp/$RUNNER_NAME ~/mnt/llama.cpp
|
||||
GG_BUILD_VULKAN=1 bash ./ci/run.sh ~/results/llama.cpp /mnt/cache/llama.cpp
|
||||
|
||||
# - name: ccache-buckets-save
|
||||
# if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
|
||||
# uses: ./.github/actions/ccache-buckets
|
||||
# env:
|
||||
# HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
|
||||
# with:
|
||||
# key: self-hosted-vulkan-nvidia-cm2
|
||||
# folder: llama.cpp
|
||||
# evict-old-files: 1d
|
||||
# hf_bucket: ggml-org/cache
|
||||
# save: true
|
||||
- name: ccache-buckets-save
|
||||
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
|
||||
uses: ./.github/actions/ccache-buckets
|
||||
env:
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
|
||||
with:
|
||||
key: self-hosted-vulkan-nvidia-cm2-gb10
|
||||
folder: llama.cpp
|
||||
evict-old-files: 1d
|
||||
hf_bucket: ggml-org/cache
|
||||
save: true
|
||||
|
||||
gpu-vulkan-apple:
|
||||
runs-on: [self-hosted, macOS, ARM64]
|
||||
|
||||
@@ -11,7 +11,8 @@ on:
|
||||
'**/*.cuh',
|
||||
'ggml/src/ggml-hip/CMakeLists.txt',
|
||||
'ggml/src/ggml-cuda/vendors/hip.h',
|
||||
'scripts/hip/gcn-cdna-vgpr-check.py'
|
||||
'scripts/hip/gcn-cdna-metrics.py',
|
||||
'scripts/hip/test_gcn_cdna_metrics.py'
|
||||
]
|
||||
|
||||
pull_request:
|
||||
@@ -22,7 +23,8 @@ on:
|
||||
'**/*.cuh',
|
||||
'ggml/src/ggml-hip/CMakeLists.txt',
|
||||
'ggml/src/ggml-cuda/vendors/hip.h',
|
||||
'scripts/hip/gcn-cdna-vgpr-check.py'
|
||||
'scripts/hip/gcn-cdna-metrics.py',
|
||||
'scripts/hip/test_gcn_cdna_metrics.py'
|
||||
]
|
||||
|
||||
cache-mode: none
|
||||
@@ -45,15 +47,32 @@ jobs:
|
||||
runs-on: ubuntu-22.04
|
||||
container: rocm/dev-ubuntu-22.04:7.2.1
|
||||
steps:
|
||||
- name: Clone
|
||||
id: checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Dependencies
|
||||
id: depends
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y build-essential git cmake rocblas-dev hipblas-dev libssl-dev python3 python3-venv python3-pip jq
|
||||
sudo apt-get install -y build-essential git cmake rocblas-dev hipblas-dev libssl-dev python3 python3-venv python3-pip python3-yaml jq
|
||||
|
||||
- name: Clone
|
||||
id: checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 2
|
||||
|
||||
# The first parent of the tested merge commit is the exact baseline.
|
||||
- name: Get baseline SHA
|
||||
if: ${{ github.event_name == 'pull_request' }}
|
||||
id: master_sha
|
||||
run: |
|
||||
git config --global --add safe.directory "$GITHUB_WORKSPACE"
|
||||
git rev-parse --verify HEAD^2 > /dev/null
|
||||
baseline_sha=$(git rev-parse HEAD^1)
|
||||
pr_sha=$(git rev-parse HEAD)
|
||||
printf 'sha=%s\npr_sha=%s\n' "$baseline_sha" "$pr_sha" >> "$GITHUB_OUTPUT"
|
||||
printf 'Baseline commit: %s\nPR merge commit: %s\n' "$baseline_sha" "$pr_sha"
|
||||
|
||||
- name: Test HIP kernel metrics scripts
|
||||
run: python3 -m unittest discover -s scripts/hip -p 'test_gcn_cdna_metrics.py'
|
||||
|
||||
- name: ccache
|
||||
uses: ggml-org/ccache-action@v1.2.24
|
||||
@@ -70,6 +89,21 @@ jobs:
|
||||
folder: llama.cpp
|
||||
hf_bucket: ggml-org/cache
|
||||
|
||||
# Verify device optimization records before starting the expensive builds.
|
||||
- name: Validate HIP resource remarks
|
||||
run: |
|
||||
mkdir -p hip-metrics-probe
|
||||
cd hip-metrics-probe
|
||||
printf '%s\n' '#include <hip/hip_runtime.h>' '__global__ void metrics_probe(float * out) { *out = 1.0f; }' > probe.hip
|
||||
"$(hipconfig -l)/clang" -x hip --offload-arch=gfx908 -O2 -c probe.hip -o probe.o \
|
||||
-Rpass-analysis=kernel-resource-usage --save-temps \
|
||||
-Xarch_device -fsave-optimization-record=yaml \
|
||||
-Xarch_device -foptimization-record-passes=kernel-resource-usage
|
||||
for metric in NumVGPR Occupancy VGPRSpill SGPRSpill; do
|
||||
grep -q "Name: *$metric$" probe.opt.yaml || { echo "Missing $metric in GPU optimization records"; exit 1; }
|
||||
done
|
||||
python3 ../scripts/hip/gcn-cdna-metrics.py vgpr probe.opt.yaml
|
||||
|
||||
- name: Build with Werror
|
||||
id: cmake_build
|
||||
run: |
|
||||
@@ -83,19 +117,178 @@ jobs:
|
||||
cd build
|
||||
make -j $(nproc)
|
||||
|
||||
- name: Check for major VGPR spills
|
||||
- name: Build HIP kernel resource metrics
|
||||
id: vgpr_check
|
||||
shell: bash
|
||||
run: |
|
||||
cmake -B build -S . \
|
||||
-DCMAKE_HIP_COMPILER="$(hipconfig -l)/clang" \
|
||||
-DGPU_TARGETS=gfx908 \
|
||||
-DGGML_HIP=ON \
|
||||
-DGGML_HIP_EXPORT_METRICS=On \
|
||||
-DCMAKE_HIP_FLAGS="" \
|
||||
-DCMAKE_HIP_FLAGS="-Xarch_device -fsave-optimization-record=yaml -Xarch_device -foptimization-record-passes=kernel-resource-usage" \
|
||||
-DCMAKE_BUILD_TYPE=Release
|
||||
cd build
|
||||
make -j $(nproc) 2>&1 | tee metrics.log | grep -v 'Rpass-analysis=kernel-resource-usage\|remark:\|^$'
|
||||
python3 ../scripts/hip/gcn-cdna-vgpr-check.py metrics.log
|
||||
set -o pipefail
|
||||
CCACHE_DISABLE=1 make -j $(nproc) ggml-hip 2>&1 | tee metrics.log | sed -e '/Rpass-analysis=kernel-resource-usage/d' -e '/remark:/d' -e '/^$/d'
|
||||
echo "Optimization record files:"
|
||||
find . -type f -name '*.opt.yaml' | sed -n '1,10p'
|
||||
echo "GPU kernel remarks in YAML:"
|
||||
grep -rl --include='*.opt.yaml' 'kernel-resource-usage' . | sed -n '1,10p' || true
|
||||
echo "First YAML record:"
|
||||
first_yaml=$(find ggml/src/ggml-hip -type f -name '*.opt.yaml' -print -quit)
|
||||
if [ -n "$first_yaml" ]; then head -n 35 "$first_yaml"; fi
|
||||
echo "GPU resource diagnostics in compiler log:"
|
||||
grep -m 3 'Function Name:' metrics.log || true
|
||||
|
||||
# The PR comparison evaluates every rule and reports all failures at the end.
|
||||
- name: Check VGPR limit on master
|
||||
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
|
||||
run: python3 scripts/hip/gcn-cdna-metrics.py vgpr build/ggml/src/ggml-hip
|
||||
|
||||
# On master pushes, cache the device optimization records as the baseline for PR checks.
|
||||
- name: Save master metrics baseline
|
||||
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
|
||||
run: |
|
||||
mkdir -p hip-baseline-metrics
|
||||
find build/ggml/src/ggml-hip -type f -name '*.opt.yaml' -exec cp --parents {} hip-baseline-metrics/ \;
|
||||
|
||||
- name: Cache master metrics baseline
|
||||
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
|
||||
env:
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
|
||||
run: |
|
||||
if [ -n "$HF_TOKEN" ]; then
|
||||
tar -czf hip-baseline-metrics.tar.gz -C hip-baseline-metrics .
|
||||
.venv-hf/bin/hf buckets cp hip-baseline-metrics.tar.gz "hf://buckets/ggml-org/cache/llama.cpp/hip-quality-check-yaml-device-rocm-7.2.1-gfx908-${{ github.sha }}.tar.gz" || echo "Failed to save HIP metrics baseline"
|
||||
fi
|
||||
|
||||
- name: Remove old HIP metrics baselines
|
||||
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
|
||||
shell: bash
|
||||
env:
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN_CACHE_OUTPUT }}
|
||||
run: |
|
||||
if [ -z "$HF_TOKEN" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if ! cache_files=$(.venv-hf/bin/hf buckets list "hf://buckets/ggml-org/cache/llama.cpp/hip-quality-check-yaml-device-rocm-" --json | jq -r '
|
||||
.[]
|
||||
| select(.type == "file")
|
||||
| select(.path | endswith(".tar.gz"))
|
||||
| select(try ((.uploaded_at | .[:19]+"Z" | fromdateiso8601) < (now - 30 * 24 * 60 * 60)) catch false)
|
||||
| .path
|
||||
'); then
|
||||
echo "Failed to list HIP metrics baselines"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
while IFS= read -r cache_path; do
|
||||
[ -n "$cache_path" ] || continue
|
||||
.venv-hf/bin/hf buckets rm "hf://buckets/ggml-org/cache/$cache_path" -y || echo "Failed to remove $cache_path"
|
||||
done <<< "$cache_files"
|
||||
|
||||
# Restore the device optimization records for the exact baseline commit.
|
||||
- name: Restore master metrics baseline
|
||||
if: ${{ github.event_name == 'pull_request' }}
|
||||
id: baseline_cache
|
||||
env:
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN_CI }}
|
||||
run: |
|
||||
cache_url="hf://buckets/ggml-org/cache/llama.cpp/hip-quality-check-yaml-device-rocm-7.2.1-gfx908-${{ steps.master_sha.outputs.sha }}.tar.gz"
|
||||
if .venv-hf/bin/hf buckets cp "$cache_url" hip-baseline-metrics.tar.gz; then
|
||||
mkdir -p hip-baseline-metrics
|
||||
if tar -xzf hip-baseline-metrics.tar.gz -C hip-baseline-metrics && [ -n "$(find hip-baseline-metrics -type f -name '*.opt.yaml' -print -quit)" ]; then
|
||||
echo "cache-hit=true" >> "$GITHUB_OUTPUT"
|
||||
echo "Restored HIP metrics baseline from HF Buckets"
|
||||
else
|
||||
rm -rf hip-baseline-metrics
|
||||
echo "Invalid HIP metrics baseline cache"
|
||||
fi
|
||||
rm -f hip-baseline-metrics.tar.gz
|
||||
else
|
||||
echo "No HIP metrics baseline in HF Buckets; building from source"
|
||||
fi
|
||||
|
||||
# Fallback when the baseline commit has no cached metrics.
|
||||
- name: Checkout baseline (master)
|
||||
if: ${{ github.event_name == 'pull_request' && steps.baseline_cache.outputs.cache-hit != 'true' }}
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ steps.master_sha.outputs.sha }}
|
||||
path: hip-baseline
|
||||
|
||||
- name: Build master metrics baseline
|
||||
if: ${{ github.event_name == 'pull_request' && steps.baseline_cache.outputs.cache-hit != 'true' }}
|
||||
shell: bash
|
||||
run: |
|
||||
cd hip-baseline
|
||||
cmake -B build -S . \
|
||||
-DCMAKE_HIP_COMPILER="$(hipconfig -l)/clang" \
|
||||
-DGPU_TARGETS=gfx908 \
|
||||
-DGGML_HIP=ON \
|
||||
-DGGML_HIP_EXPORT_METRICS=On \
|
||||
-DCMAKE_HIP_FLAGS="-Xarch_device -fsave-optimization-record=yaml -Xarch_device -foptimization-record-passes=kernel-resource-usage" \
|
||||
-DCMAKE_BUILD_TYPE=Release
|
||||
cd build
|
||||
set -o pipefail
|
||||
CCACHE_DISABLE=1 make -j $(nproc) ggml-hip 2>&1 | tee metrics.log | sed -e '/Rpass-analysis=kernel-resource-usage/d' -e '/remark:/d' -e '/^$/d'
|
||||
mkdir -p ../../hip-baseline-metrics
|
||||
find ggml/src/ggml-hip -type f -name '*.opt.yaml' -exec cp --parents {} ../../hip-baseline-metrics/ \;
|
||||
|
||||
- name: Check kernel resource rules vs master
|
||||
if: ${{ github.event_name == 'pull_request' }}
|
||||
id: occupancy_check
|
||||
env:
|
||||
BASELINE_SHA: ${{ steps.master_sha.outputs.sha }}
|
||||
PR_SHA: ${{ steps.master_sha.outputs.pr_sha }}
|
||||
run: |
|
||||
# The PR optimization records come from the VGPR spill check build above, so
|
||||
# this step adds no extra build when the baseline cache hits.
|
||||
python3 scripts/hip/gcn-cdna-metrics.py compare hip-baseline-metrics build/ggml/src/ggml-hip \
|
||||
--dump hip-kernel-metrics-deltas.tsv || check_failed=true
|
||||
if [ ! -s hip-kernel-metrics-deltas.tsv ]; then
|
||||
echo "Kernel metrics comparison failed before producing a TSV report"
|
||||
exit 1
|
||||
fi
|
||||
python3 scripts/hip/gcn-cdna-metrics.py report hip-kernel-metrics-deltas.tsv \
|
||||
-o hip-kernel-metrics-report.md
|
||||
sed -i "3i\\- Baseline commit: $BASELINE_SHA\\n- PR merge commit: $PR_SHA" hip-kernel-metrics-report.md
|
||||
if [ -n "$check_failed" ]; then
|
||||
echo "check_failed=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
exit 0
|
||||
|
||||
- name: Upload kernel metrics report
|
||||
if: ${{ github.event_name == 'pull_request' }}
|
||||
id: metrics_report
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: hip-kernel-metrics-report
|
||||
path: hip-kernel-metrics-report.md
|
||||
|
||||
- name: Publish kernel metrics summary
|
||||
if: ${{ github.event_name == 'pull_request' }}
|
||||
shell: bash
|
||||
env:
|
||||
ARTIFACT_URL: ${{ steps.metrics_report.outputs.artifact-url }}
|
||||
run: |
|
||||
{
|
||||
if [ "$(wc -c < hip-kernel-metrics-report.md)" -le 1000000 ]; then
|
||||
cat hip-kernel-metrics-report.md
|
||||
else
|
||||
sed -n -e '/^# /p' -e '/^- Baseline/p' -e '/^- PR/p' -e '/^Kernels compared:/p' -e 's/^## /- /p' hip-kernel-metrics-report.md
|
||||
printf '\nThe full report exceeds the GitHub job summary size limit.\n'
|
||||
fi
|
||||
printf '\n[Download the full kernel metrics report](%s)\n' "$ARTIFACT_URL"
|
||||
} | tee -a "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- name: Fail on blocking regressions
|
||||
if: ${{ github.event_name == 'pull_request' && steps.occupancy_check.outputs.check_failed == 'true' }}
|
||||
run: |
|
||||
echo "Blocking kernel metrics regressions detected, see the job summary and hip-kernel-metrics-report artifact"
|
||||
exit 1
|
||||
|
||||
- name: ccache-buckets-save
|
||||
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/master' }}
|
||||
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
BODY: ${{ github.event.pull_request.body }}
|
||||
HAS_LABEL: ${{ contains(github.event.pull_request.labels.*.name, 'video demo') }}
|
||||
run: |
|
||||
# sections written by demo:pr (see ui/apps/chat/demo/cli.ts): the managed comment
|
||||
# sections written by demo:pr (see ui/lib/demo/src/cli.ts): the managed comment
|
||||
# markers, or a preview linking to a demo video uploaded for this PR
|
||||
has_demo=false
|
||||
if { grep -qF '<!-- demo:start -->' <<< "$BODY" && grep -qF '<!-- demo:end -->' <<< "$BODY"; } ||
|
||||
|
||||
@@ -212,6 +212,29 @@ jobs:
|
||||
run: npm run prepack
|
||||
working-directory: ui/lib/harness
|
||||
|
||||
demo-checks:
|
||||
name: Demo harness checks
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24"
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
working-directory: ui/lib/demo
|
||||
|
||||
- name: Run type checking
|
||||
run: npm run check
|
||||
working-directory: ui/lib/demo
|
||||
|
||||
chat-only-build:
|
||||
name: Chat-only build
|
||||
runs-on: ubuntu-24.04
|
||||
|
||||
+44
-14
@@ -868,6 +868,22 @@ class Qwen3_5MoeTextModel(_Qwen35MRopeMixin, _LinearAttentionVReorderBase):
|
||||
class DFlashModel(Qwen3Model):
|
||||
model_arch = gguf.MODEL_ARCH.DFLASH
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self._target_is_inkling2 = False
|
||||
if self.target_model_dir is not None:
|
||||
target_hparams = ModelBase.load_hparams(self.target_model_dir, False)
|
||||
self._target_is_inkling2 = get_model_architecture(target_hparams, ModelType.TEXT).startswith("Inkling2")
|
||||
if self._target_is_inkling2:
|
||||
# the target GGUF keeps only the tokenizer rows of the padded vocab
|
||||
target_hparams = {**target_hparams, **target_hparams.get("text_config", {})}
|
||||
self.hparams["vocab_size"] = target_hparams["unpadded_vocab_size"]
|
||||
self.hparams["eos_token_id"] = target_hparams["eos_token_id"]
|
||||
# the loop core runs num_passes times, other looping targets need their own visit count
|
||||
self._target_n_visits = target_hparams["num_hidden_layers"]
|
||||
if (loop := target_hparams.get("loop_config")) is not None:
|
||||
self._target_n_visits += (loop["num_passes"] - 1) * (loop["core_end"] - loop["core_start"])
|
||||
|
||||
def set_vocab(self):
|
||||
if self.target_model_dir is None:
|
||||
raise ValueError(
|
||||
@@ -917,6 +933,11 @@ class DFlashModel(Qwen3Model):
|
||||
self.gguf_writer.add_conv_group_size(int(dflash_config["conv_group_size"]))
|
||||
self.gguf_writer.add_selector_rank(int(dflash_config["selector_rank"]))
|
||||
self.gguf_writer.add_selector_top_k(int(dflash_config["selector_top_k"]))
|
||||
softcap_mode = dflash_config.get("selector_softcap_mode", "before_correction")
|
||||
if softcap_mode not in ("before_correction", "after_correction"):
|
||||
raise ValueError(f"DFlash2: unknown selector_softcap_mode {softcap_mode!r}")
|
||||
if softcap_mode == "after_correction":
|
||||
self.gguf_writer.add_selector_softcap_after_correction(True)
|
||||
|
||||
output_multiplier = dflash_config.get(
|
||||
"output_multiplier", self.hparams.get("output_multiplier")
|
||||
@@ -942,7 +963,10 @@ class DFlashModel(Qwen3Model):
|
||||
|
||||
target_layer_ids = dflash_config.get("target_layer_ids", self.hparams.get("target_layer_ids", []))
|
||||
if target_layer_ids:
|
||||
extract_layer_ids = [i + 1 for i in target_layer_ids]
|
||||
# Inkling ids count loop visits, the last one is the final norm output
|
||||
if self._target_is_inkling2 and target_layer_ids[-1] != self._target_n_visits:
|
||||
raise ValueError(f"Inkling2 DFlash2: target_layer_ids {target_layer_ids} must end at the Inkling final norm ({self._target_n_visits})")
|
||||
extract_layer_ids = target_layer_ids if self._target_is_inkling2 else [i + 1 for i in target_layer_ids]
|
||||
self.gguf_writer.add_target_layers(extract_layer_ids)
|
||||
|
||||
use_sliding_window = self.hparams.get("use_sliding_window", False) or dflash_config.get("use_swa", False)
|
||||
@@ -969,19 +993,6 @@ class DFlashModel(Qwen3Model):
|
||||
def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]:
|
||||
yield from super().generate_extra_tensors()
|
||||
|
||||
mask_path = self.dir_model / "mask_embedding.pt"
|
||||
if not mask_path.is_file():
|
||||
return
|
||||
|
||||
mask = torch.load(mask_path, map_location="cpu", weights_only=True)
|
||||
mask_id = self.hparams.get("dflash_config", {}).get("mask_token_id")
|
||||
if mask_id is None or mask["mask_token_id"] != mask_id:
|
||||
raise ValueError("mask_embedding.pt mask_token_id does not match dflash_config")
|
||||
if tuple(mask["embedding"].shape) != (self.hparams["hidden_size"],):
|
||||
raise ValueError("mask_embedding.pt has an unexpected embedding shape")
|
||||
if not 0 <= mask_id < self.hparams["vocab_size"]:
|
||||
raise ValueError("mask_embedding.pt mask_token_id is outside the vocabulary")
|
||||
|
||||
def target_tensor(name: str) -> Tensor:
|
||||
if self.target_model_dir is None:
|
||||
raise ValueError("mask_embedding.pt requires --target-model-dir with the target embeddings and output head")
|
||||
@@ -999,6 +1010,23 @@ class DFlashModel(Qwen3Model):
|
||||
return LazyTorchTensor.from_local_tensor(part[name])
|
||||
raise ValueError(f"Target tensor {name!r} was not found in safetensors")
|
||||
|
||||
if self._target_is_inkling2:
|
||||
# the draft borrows the raw target embeddings, Inkling norms them before its first layer
|
||||
yield "model.embed_norm.weight", target_tensor("model.llm.embed_norm.weight")
|
||||
|
||||
mask_path = self.dir_model / "mask_embedding.pt"
|
||||
if not mask_path.is_file():
|
||||
return
|
||||
|
||||
mask = torch.load(mask_path, map_location="cpu", weights_only=True)
|
||||
mask_id = self.hparams.get("dflash_config", {}).get("mask_token_id")
|
||||
if mask_id is None or mask["mask_token_id"] != mask_id:
|
||||
raise ValueError("mask_embedding.pt mask_token_id does not match dflash_config")
|
||||
if tuple(mask["embedding"].shape) != (self.hparams["hidden_size"],):
|
||||
raise ValueError("mask_embedding.pt has an unexpected embedding shape")
|
||||
if not 0 <= mask_id < self.hparams["vocab_size"]:
|
||||
raise ValueError("mask_embedding.pt mask_token_id is outside the vocabulary")
|
||||
|
||||
embedding_name = "model.embed_tokens.weight"
|
||||
if embedding_name in self.model_tensors:
|
||||
embeddings = self.model_tensors.pop(embedding_name)()
|
||||
@@ -1061,6 +1089,8 @@ class DFlashModel(Qwen3Model):
|
||||
"model.candidate_selector.predecessor_codebook",
|
||||
"model.candidate_selector.successor_codebook",
|
||||
):
|
||||
# padded vocabs (Inkling): the selector only indexes the draft vocab
|
||||
data_torch = data_torch[:self.hparams["vocab_size"]]
|
||||
name += ".weight"
|
||||
|
||||
yield from super().modify_tensors(data_torch, name, bid)
|
||||
|
||||
@@ -112,7 +112,6 @@
|
||||
systems = [
|
||||
"aarch64-darwin"
|
||||
"aarch64-linux"
|
||||
"x86_64-darwin" # x86_64-darwin isn't tested (and likely isn't relevant)
|
||||
"x86_64-linux"
|
||||
];
|
||||
|
||||
|
||||
@@ -2449,10 +2449,12 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten
|
||||
switch (op->src[0]->type) {
|
||||
#ifndef ASCEND_310P
|
||||
case GGML_TYPE_BF16:
|
||||
return true;
|
||||
#endif
|
||||
case GGML_TYPE_F16:
|
||||
case GGML_TYPE_F32:
|
||||
return true;
|
||||
// src1 goes to aclnn as is: a BF16 src1 with F16/F32 weights is not verified
|
||||
return op->src[1]->type != GGML_TYPE_BF16;
|
||||
case GGML_TYPE_Q8_0:
|
||||
case GGML_TYPE_Q4_0:
|
||||
#ifdef ASCEND_310P
|
||||
@@ -2470,7 +2472,8 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten
|
||||
switch (op->src[0]->type) {
|
||||
case GGML_TYPE_F16:
|
||||
case GGML_TYPE_F32:
|
||||
return true;
|
||||
// src1 goes to aclnn as is: a BF16 src1 with F16/F32 weights is not verified
|
||||
return op->src[1]->type != GGML_TYPE_BF16;
|
||||
case GGML_TYPE_Q8_0:
|
||||
case GGML_TYPE_Q4_0:
|
||||
#ifdef ASCEND_310P
|
||||
|
||||
@@ -1287,6 +1287,25 @@ static void ggml_compute_forward_mul_mat_one_chunk(
|
||||
}
|
||||
}
|
||||
|
||||
// converts n BF16 values (whole blocks of vec_dot_type) to vec_dot_type: widened directly to F32, otherwise via F32 in chunks
|
||||
static void ggml_cpu_bf16_to_vec_dot_type(const ggml_bf16_t * x, void * y, int64_t n, enum ggml_type vec_dot_type) {
|
||||
if (vec_dot_type == GGML_TYPE_F32) {
|
||||
ggml_cpu_bf16_to_fp32(x, (float *) y, n);
|
||||
return;
|
||||
}
|
||||
|
||||
ggml_from_float_t const from_float = type_traits_cpu[vec_dot_type].from_float;
|
||||
const int64_t bs = ggml_blck_size(vec_dot_type);
|
||||
|
||||
float tmp[1024];
|
||||
const int64_t chunk = (1024/bs)*bs;
|
||||
for (int64_t i = 0; i < n; i += chunk) {
|
||||
const int64_t nc = MIN(chunk, n - i);
|
||||
ggml_cpu_bf16_to_fp32(x + i, tmp, nc);
|
||||
from_float(tmp, (char *) y + (i/bs)*ggml_type_size(vec_dot_type), nc);
|
||||
}
|
||||
}
|
||||
|
||||
void ggml_compute_forward_mul_mat(
|
||||
const struct ggml_compute_params * params,
|
||||
struct ggml_tensor * dst) {
|
||||
@@ -1372,11 +1391,9 @@ UseGgmlGemm1:;
|
||||
const size_t nbw3 = nbw2*ne12;
|
||||
|
||||
assert(params->wsize >= ne13*nbw3);
|
||||
// src1 is either packed from F32 into vec_dot_type, or widened from F16 or BF16 into the F32 work buffer
|
||||
const bool widen = src1->type != GGML_TYPE_F32;
|
||||
|
||||
GGML_ASSERT(!widen || vec_dot_type == GGML_TYPE_F32);
|
||||
GGML_ASSERT(!widen || src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_BF16);
|
||||
// src1 is either packed from F32 or BF16 into vec_dot_type, or widened from F16 or BF16 into the F32 work buffer
|
||||
GGML_ASSERT(src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16 ||
|
||||
(src1->type == GGML_TYPE_F16 && vec_dot_type == GGML_TYPE_F32));
|
||||
|
||||
#if 0
|
||||
for (int64_t i13 = 0; i13 < ne13; ++i13) {
|
||||
@@ -1404,7 +1421,7 @@ UseGgmlGemm1:;
|
||||
if (src1->type == GGML_TYPE_F16) {
|
||||
ggml_cpu_fp16_to_fp32((const ggml_fp16_t *) src1_row, (float *) wdata_row, ne10_block_size);
|
||||
} else if (src1->type == GGML_TYPE_BF16) {
|
||||
ggml_cpu_bf16_to_fp32((const ggml_bf16_t *) src1_row, (float *) wdata_row, ne10_block_size);
|
||||
ggml_cpu_bf16_to_vec_dot_type((const ggml_bf16_t *) src1_row, wdata_row, ne10_block_size, vec_dot_type);
|
||||
} else {
|
||||
from_float((const float *) src1_row, wdata_row, ne10_block_size);
|
||||
}
|
||||
@@ -1656,7 +1673,7 @@ static void ggml_compute_forward_mul_mat_id(
|
||||
const size_t nbw3 = nbw2*ne12;
|
||||
|
||||
assert(params->wsize >= ne13*nbw3);
|
||||
GGML_ASSERT(src1->type == GGML_TYPE_F32);
|
||||
GGML_ASSERT(src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16);
|
||||
|
||||
#if 0
|
||||
for (int64_t i13 = 0; i13 < ne13; ++i13) {
|
||||
@@ -1675,9 +1692,13 @@ static void ggml_compute_forward_mul_mat_id(
|
||||
size_t bs = ggml_blck_size(vec_dot_type);
|
||||
int64_t ne10_block_start = (ith * ne10/bs) / nth;
|
||||
int64_t ne10_block_end = ((ith + 1) * ne10/bs) / nth;
|
||||
from_float((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + ne10_block_start*bs*nb10),
|
||||
(void *) (wdata + i13*nbw3 + i12*nbw2 + i11*nbw1 + ne10_block_start*nbw0),
|
||||
(ne10_block_end - ne10_block_start) * bs);
|
||||
const void * src1_row = (const char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + ne10_block_start*bs*nb10;
|
||||
void * wdata_row = wdata + i13*nbw3 + i12*nbw2 + i11*nbw1 + ne10_block_start*nbw0;
|
||||
if (src1->type == GGML_TYPE_BF16) {
|
||||
ggml_cpu_bf16_to_vec_dot_type((const ggml_bf16_t *) src1_row, wdata_row, (ne10_block_end - ne10_block_start) * bs, vec_dot_type);
|
||||
} else {
|
||||
from_float((const float *) src1_row, wdata_row, (ne10_block_end - ne10_block_start) * bs);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -453,14 +453,19 @@ static bool ggml_backend_cpu_device_supports_op(ggml_backend_dev_t dev, const st
|
||||
op->type != GGML_TYPE_IQ1_M; // missing type_traits.from_float
|
||||
case GGML_OP_MUL_MAT:
|
||||
if (ggml_get_op_params_i32(op, 1) == GGML_HINT_SRC0_IS_HADAMARD &&
|
||||
src0->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32) {
|
||||
return src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16;
|
||||
src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_F16) {
|
||||
// the hinted matmul is an FWHT of src1 for every src0 type, which reads F32 or F16 only;
|
||||
// with use_ref it takes the general path instead, so src1 has to pass the check below too
|
||||
return false;
|
||||
}
|
||||
// F16 or BF16 in src1 is widened into the F32 work buffer
|
||||
return src1->type == GGML_TYPE_F32 ||
|
||||
// F16 in src1 is widened into the F32 work buffer, BF16 is widened or converted to vec_dot_type
|
||||
return src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16 ||
|
||||
src1->type == ggml_get_type_traits_cpu(src0->type)->vec_dot_type ||
|
||||
((src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_BF16) &&
|
||||
ggml_get_type_traits_cpu(src0->type)->vec_dot_type == GGML_TYPE_F32);
|
||||
(src1->type == GGML_TYPE_F16 && ggml_get_type_traits_cpu(src0->type)->vec_dot_type == GGML_TYPE_F32);
|
||||
case GGML_OP_MUL_MAT_ID:
|
||||
// src1 is converted to vec_dot_type from F32 or BF16 only
|
||||
return src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16 ||
|
||||
src1->type == ggml_get_type_traits_cpu(src0->type)->vec_dot_type;
|
||||
case GGML_OP_SOFT_MAX_BACK: {
|
||||
if (op->src[0]->type != GGML_TYPE_F32 || op->src[1]->type != GGML_TYPE_F32) {
|
||||
return false;
|
||||
|
||||
@@ -627,7 +627,7 @@ static bool ggml_tiled_supported(const struct ggml_tensor * src0,
|
||||
case GGML_TYPE_IQ3_S:
|
||||
case GGML_TYPE_IQ1_S:
|
||||
case GGML_TYPE_IQ1_M:
|
||||
return true;
|
||||
break;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -412,6 +412,11 @@ static bool ggml_cuda_is_aligned(const ggml_tensor * tensor, const size_t alignm
|
||||
tensor->nb[3] % alignment == 0;
|
||||
}
|
||||
|
||||
static bool ggml_cuda_is_view_or_noop(const ggml_tensor * t) {
|
||||
return ggml_is_empty(t) || t->op == GGML_OP_RESHAPE || t->op == GGML_OP_TRANSPOSE ||
|
||||
t->op == GGML_OP_VIEW || t->op == GGML_OP_PERMUTE || t->op == GGML_OP_NONE;
|
||||
}
|
||||
|
||||
static constexpr __device__ int ggml_cuda_get_physical_warp_size() {
|
||||
#if defined(GGML_USE_HIP) && (defined(__GFX9__) || defined(__GFX8__))
|
||||
return 64;
|
||||
|
||||
+36
-19
@@ -1,9 +1,11 @@
|
||||
#include "convert.cuh"
|
||||
#include "fp8.cuh"
|
||||
|
||||
#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) && CUDART_VERSION >= 11080
|
||||
|
||||
template <typename src_t>
|
||||
struct fp8_abs_src {
|
||||
const float * x;
|
||||
const src_t * x;
|
||||
int64_t ne0;
|
||||
int64_t ne1;
|
||||
int64_t ne2;
|
||||
@@ -18,12 +20,13 @@ struct fp8_abs_src {
|
||||
i /= ne1;
|
||||
const int64_t i2 = i % ne2;
|
||||
const int64_t i3 = i / ne2;
|
||||
const float value = fabsf(x[i0 + i1*s1 + i2*s2 + i3*s3]);
|
||||
const float value = fabsf(ggml_cuda_cast<float>(x[i0 + i1*s1 + i2*s2 + i3*s3]));
|
||||
return isfinite(value) ? value : 448.0f;
|
||||
}
|
||||
};
|
||||
|
||||
static __global__ void fp8_amax_partials(fp8_abs_src src, int64_t ne, float * partials) {
|
||||
template <typename src_t>
|
||||
static __global__ void fp8_amax_partials(fp8_abs_src<src_t> src, int64_t ne, float * partials) {
|
||||
float amax = 0.0f;
|
||||
for (int64_t i = (int64_t) blockIdx.x*blockDim.x + threadIdx.x; i < ne; i += (int64_t) blockDim.x*gridDim.x) {
|
||||
amax = fmaxf(amax, src(i));
|
||||
@@ -49,8 +52,9 @@ static __global__ void fp8_amax_final(const float * partials, int n, float * ama
|
||||
}
|
||||
}
|
||||
|
||||
template <typename src_t>
|
||||
static __global__ void quantize_fp8_e4m3(
|
||||
const float * __restrict__ x, uint8_t * __restrict__ y, const float * __restrict__ amax,
|
||||
const src_t * __restrict__ x, uint8_t * __restrict__ y, const float * __restrict__ amax,
|
||||
float * __restrict__ scale, int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne, int64_t s1, int64_t s2, int64_t s3) {
|
||||
const int64_t i = (int64_t) blockIdx.x*blockDim.x + threadIdx.x;
|
||||
if (i >= ne) {
|
||||
@@ -65,12 +69,26 @@ static __global__ void quantize_fp8_e4m3(
|
||||
const int64_t i3 = tmp / ne2;
|
||||
|
||||
const float d = *amax > 0.0f ? *amax / 448.0f : 1.0f;
|
||||
y[i] = ggml_cuda_fp32_to_f8_e4m3(x[i0 + i1*s1 + i2*s2 + i3*s3] / d);
|
||||
y[i] = ggml_cuda_fp32_to_f8_e4m3(ggml_cuda_cast<float>(x[i0 + i1*s1 + i2*s2 + i3*s3]) / d);
|
||||
if (i == 0) {
|
||||
*scale = d;
|
||||
}
|
||||
}
|
||||
|
||||
// src1 (F32 or BF16) to FP8 with one scale for the whole tensor: amax / 448
|
||||
template <typename src_t>
|
||||
static void fp8_quantize_src1(
|
||||
ggml_backend_cuda_context & ctx, const src_t * x, uint8_t * y, float * amax, float * scale,
|
||||
int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne, int64_t s1, int64_t s2, int64_t s3, cudaStream_t stream) {
|
||||
const fp8_abs_src<src_t> abs_src = { x, ne0, ne1, ne2, s1, s2, s3 };
|
||||
const int reduce_blocks = std::min<int64_t>((ne + 255)/256, 1024);
|
||||
ggml_cuda_pool_alloc<float> reduce_tmp(ctx.pool(), reduce_blocks);
|
||||
fp8_amax_partials<<<reduce_blocks, 256, 0, stream>>>(abs_src, ne, reduce_tmp.ptr);
|
||||
fp8_amax_final<<<1, 256, 0, stream>>>(reduce_tmp.ptr, reduce_blocks, amax);
|
||||
|
||||
quantize_fp8_e4m3<<<(ne + 255)/256, 256, 0, stream>>>(x, y, amax, scale, ne0, ne1, ne2, ne, s1, s2, s3);
|
||||
}
|
||||
|
||||
static void fp8_set_batch(cublasLtMatrixLayout_t desc, int32_t count, int64_t stride) {
|
||||
CUBLAS_CHECK(cublasLtMatrixLayoutSetAttribute(desc, CUBLASLT_MATRIX_LAYOUT_BATCH_COUNT, &count, sizeof(count)));
|
||||
CUBLAS_CHECK(cublasLtMatrixLayoutSetAttribute(desc, CUBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET, &stride, sizeof(stride)));
|
||||
@@ -89,9 +107,9 @@ bool ggml_cuda_mul_mat_fp8(
|
||||
ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst,
|
||||
const ggml_tensor * weight_scale) {
|
||||
const int cc = ggml_cuda_info().devices[ctx.device].cc;
|
||||
if (!fp8_mma_hardware_available(cc) || src0->type != GGML_TYPE_F8_E4M3 || src1->type != GGML_TYPE_F32 ||
|
||||
if (!fp8_mma_hardware_available(cc) || src0->type != GGML_TYPE_F8_E4M3 || (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_BF16) ||
|
||||
dst->type != GGML_TYPE_F32 || !ggml_is_contiguous(dst) || src0->ne[0] % 16 != 0 || src0->ne[1] % 16 != 0 ||
|
||||
src0->nb[0] != sizeof(uint8_t) || src0->nb[1] != (size_t) src0->ne[0] || src1->nb[0] != sizeof(float) ||
|
||||
src0->nb[0] != sizeof(uint8_t) || src0->nb[1] != (size_t) src0->ne[0] || src1->nb[0] != ggml_type_size(src1->type) ||
|
||||
!ggml_cuda_is_aligned(src0, 16) || !ggml_cuda_is_aligned(dst, 16)) {
|
||||
return false;
|
||||
}
|
||||
@@ -110,18 +128,17 @@ bool ggml_cuda_mul_mat_fp8(
|
||||
ggml_cuda_pool_alloc<float> src1_scale(ctx.pool(), 1);
|
||||
ggml_cuda_pool_alloc<float> src1_amax(ctx.pool(), 1);
|
||||
|
||||
const fp8_abs_src abs_src = {
|
||||
(const float *) src1->data, ne10, ne11, ne12,
|
||||
(int64_t) (nb11 / sizeof(float)), (int64_t) (nb12 / sizeof(float)), (int64_t) (nb13 / sizeof(float))
|
||||
};
|
||||
const int reduce_blocks = std::min<int64_t>((ne_src1 + 255)/256, 1024);
|
||||
ggml_cuda_pool_alloc<float> reduce_tmp(ctx.pool(), reduce_blocks);
|
||||
fp8_amax_partials<<<reduce_blocks, 256, 0, stream>>>(abs_src, ne_src1, reduce_tmp.ptr);
|
||||
fp8_amax_final<<<1, 256, 0, stream>>>(reduce_tmp.ptr, reduce_blocks, src1_amax.ptr);
|
||||
|
||||
quantize_fp8_e4m3<<<(ne_src1 + 255)/256, 256, 0, stream>>>(
|
||||
(const float *) src1->data, src1_fp8.ptr, src1_amax.ptr, src1_scale.ptr, ne10, ne11, ne12, ne_src1,
|
||||
nb11 / sizeof(float), nb12 / sizeof(float), nb13 / sizeof(float));
|
||||
const int64_t s11 = nb11 / nb10;
|
||||
const int64_t s12 = nb12 / nb10;
|
||||
const int64_t s13 = nb13 / nb10;
|
||||
if (src1->type == GGML_TYPE_BF16) {
|
||||
fp8_quantize_src1(ctx, (const nv_bfloat16 *) src1->data, src1_fp8.ptr, src1_amax.ptr, src1_scale.ptr,
|
||||
ne10, ne11, ne12, ne_src1, s11, s12, s13, stream);
|
||||
} else {
|
||||
GGML_ASSERT(src1->type == GGML_TYPE_F32);
|
||||
fp8_quantize_src1(ctx, (const float *) src1->data, src1_fp8.ptr, src1_amax.ptr, src1_scale.ptr,
|
||||
ne10, ne11, ne12, ne_src1, s11, s12, s13, stream);
|
||||
}
|
||||
CUDA_CHECK(cudaGetLastError());
|
||||
|
||||
cublasLtMatmulDesc_t op_desc;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
|
||||
#include "common.cuh"
|
||||
#include "ggml-backend-impl.h"
|
||||
|
||||
// try and fuse nodes starting at node i and return the number of nodes to skip
|
||||
int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i);
|
||||
|
||||
// add alloc deps for the fusions that need their inputs to stay alive (called from graph_optimize)
|
||||
void ggml_cuda_fusion_add_alloc_deps(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, ggml_backend_graph_optimize_params * params);
|
||||
+23
-2385
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
// CUDA graph capture and concurrent stream state, only needed by ggml-cuda.cu
|
||||
// CUDA graph capture and concurrent stream state, only needed by ggml-cuda.cu and fusion.cu
|
||||
|
||||
#include "common.cuh"
|
||||
|
||||
|
||||
@@ -0,0 +1,396 @@
|
||||
#include "inkling2.cuh"
|
||||
|
||||
// the fused kernels keep the operation order of the unfused graph where it is cheap to do so,
|
||||
// __fmul_rn/__fadd_rn stop the compiler from contracting a separate MUL and ADD into one FMA
|
||||
|
||||
static __global__ void situ_f32(
|
||||
const float * gate, const float * up, float * dst, const int ne0, const int ne1, const int ne2, const int64_t nrows,
|
||||
const int64_t g_s1, const int64_t g_s2, const int64_t g_s3, const int64_t u_s1, const int64_t u_s2, const int64_t u_s3,
|
||||
const float s0, const float b0, const float s1, const float b1, const float s2, const float b2, const float s3, const float b3) {
|
||||
ggml_cuda_pdl_lc();
|
||||
const int i0 = blockIdx.x*blockDim.x + threadIdx.x;
|
||||
|
||||
ggml_cuda_pdl_sync();
|
||||
if (i0 >= ne0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (int64_t row = blockIdx.y; row < nrows; row += gridDim.y) {
|
||||
const int64_t i1 = row % ne1;
|
||||
const int64_t i2 = (row / ne1) % ne2;
|
||||
const int64_t i3 = row / ((int64_t) ne1*ne2);
|
||||
|
||||
const float g = gate[i3*g_s3 + i2*g_s2 + i1*g_s1 + i0];
|
||||
const float u = up [i3*u_s3 + i2*u_s2 + i1*u_s1 + i0];
|
||||
|
||||
const float act = s1*tanhf(s0*g + b0) + b1;
|
||||
const float sig = 1.0f/(1.0f + expf(-g));
|
||||
const float lin = s3*tanhf(s2*u + b2) + b3;
|
||||
|
||||
dst[row*ne0 + i0] = __fmul_rn(__fmul_rn(act, sig), lin);
|
||||
}
|
||||
}
|
||||
|
||||
void ggml_cuda_op_situ(ggml_backend_cuda_context & ctx, const ggml_tensor * gate, const ggml_tensor * up,
|
||||
const float * s, const float * b, ggml_tensor * dst) {
|
||||
GGML_ASSERT(gate->type == GGML_TYPE_F32 && up->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32);
|
||||
GGML_ASSERT(gate->nb[0] == sizeof(float) && up->nb[0] == sizeof(float) && ggml_is_contiguous(dst));
|
||||
GGML_ASSERT(ggml_are_same_shape(gate, up) && ggml_are_same_shape(gate, dst));
|
||||
|
||||
const int64_t ne0 = gate->ne[0];
|
||||
const int64_t nrows = ggml_nrows(gate);
|
||||
|
||||
const int block_size = 256;
|
||||
const dim3 grid((ne0 + block_size - 1)/block_size, std::min<int64_t>(nrows, 65535), 1);
|
||||
|
||||
const ggml_cuda_kernel_launch_params params(grid, dim3(block_size, 1, 1), 0, ctx.stream());
|
||||
ggml_cuda_kernel_launch(situ_f32, params,
|
||||
(const float *) gate->data, (const float *) up->data, (float *) dst->data, (int) ne0, (int) gate->ne[1], (int) gate->ne[2], nrows,
|
||||
(int64_t) (gate->nb[1]/sizeof(float)), (int64_t) (gate->nb[2]/sizeof(float)), (int64_t) (gate->nb[3]/sizeof(float)),
|
||||
(int64_t) (up->nb[1]/sizeof(float)), (int64_t) (up->nb[2]/sizeof(float)), (int64_t) (up->nb[3]/sizeof(float)),
|
||||
s[0], b[0], s[1], b[1], s[2], b[2], s[3], b[3]);
|
||||
}
|
||||
|
||||
// one thread per (channel, run of tokens of one sequence). the last K columns of x stay in registers, right-aligned in
|
||||
// M = GGML_CUDA_SHORT_CONV_MAX_K slots with zero weights in front, so K needs no template and the sums keep their order.
|
||||
// a thread reads cur at a token before it writes dst there and never again, so dst may be cur itself when a thread has
|
||||
// the whole sequence
|
||||
template <bool has_dyn, bool has_res>
|
||||
static __global__ void short_conv_f32(const ggml_cuda_short_conv_args a) {
|
||||
ggml_cuda_pdl_lc();
|
||||
constexpr int M = GGML_CUDA_SHORT_CONV_MAX_K;
|
||||
|
||||
const int K = a.K;
|
||||
const int K1 = K - 1;
|
||||
const int c = blockIdx.x*blockDim.x + threadIdx.x;
|
||||
|
||||
ggml_cuda_pdl_sync();
|
||||
if (c >= a.C) {
|
||||
return;
|
||||
}
|
||||
|
||||
float w[M];
|
||||
#pragma unroll
|
||||
for (int m = 0; m < M; ++m) {
|
||||
w[m] = m >= M - K ? a.w[c*K + m - (M - K)] : 0.0f;
|
||||
}
|
||||
|
||||
const int n_runs = (a.Ts + a.run - 1)/a.run;
|
||||
for (int r = blockIdx.y; r < a.S*n_runs; r += gridDim.y) {
|
||||
const int s = r / n_runs;
|
||||
const int t0 = (r - s*n_runs)*a.run;
|
||||
const int t1 = min(t0 + a.run, a.Ts);
|
||||
|
||||
const float * pc = a.past + c*a.past_s1 + s*a.past_s2;
|
||||
const float * xc = a.cur + (int64_t) s*a.Ts*a.C + c;
|
||||
|
||||
// x[M - K + k] is column ts + k of [past; cur^T]
|
||||
float x[M];
|
||||
#pragma unroll
|
||||
for (int m = 0; m < M - 1; ++m) {
|
||||
const int j = t0 + m - (M - K);
|
||||
x[m] = j < 0 ? 0.0f : j < K1 ? pc[j] : xc[(int64_t) (j - K1)*a.C];
|
||||
}
|
||||
|
||||
for (int ts = t0; ts < t1; ++ts) {
|
||||
const int64_t t = (int64_t) s*a.Ts + ts;
|
||||
|
||||
x[M - 1] = xc[(int64_t) ts*a.C];
|
||||
|
||||
float y = 0.0f;
|
||||
#pragma unroll
|
||||
for (int m = 0; m < M; ++m) {
|
||||
y += x[m]*w[m];
|
||||
}
|
||||
|
||||
if constexpr (has_dyn) {
|
||||
const float * d = a.dyn + t*a.dyn_s1 + (c / (a.C / a.n_heads))*K;
|
||||
#pragma unroll
|
||||
for (int lag = 0; lag < M; ++lag) {
|
||||
if (lag < K) {
|
||||
y = __fadd_rn(y, __fmul_rn(x[M - 1 - lag], d[lag]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
float o = a.scale*__fadd_rn(x[M - 1], y) + a.bias;
|
||||
if constexpr (has_res) {
|
||||
o = __fadd_rn(a.res[t*a.C + c], o);
|
||||
}
|
||||
a.dst[t*a.C + c] = o;
|
||||
|
||||
#pragma unroll
|
||||
for (int m = 0; m < M - 1; ++m) {
|
||||
x[m] = x[m + 1];
|
||||
}
|
||||
|
||||
// x now holds the K - 1 columns that end at token ts: the conv state of slot Ts - 1 - ts, if it is kept
|
||||
if (ts >= a.Ts - a.kw) {
|
||||
float * st = a.state + (a.Ts - 1 - ts)*a.state_slot_s + c*a.state_ch_s + s*a.state_seq_s;
|
||||
#pragma unroll
|
||||
for (int m = 0; m < M - 1; ++m) {
|
||||
if (m >= M - K) {
|
||||
st[m - (M - K)] = x[m];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ggml_cuda_op_short_conv(ggml_backend_cuda_context & ctx, const ggml_cuda_short_conv_args & a) {
|
||||
GGML_ASSERT(a.K >= 2 && a.K <= GGML_CUDA_SHORT_CONV_MAX_K);
|
||||
|
||||
const int block_size = 128;
|
||||
const int n_runs = (a.Ts + a.run - 1)/a.run;
|
||||
const dim3 grid((a.C + block_size - 1)/block_size, std::min(a.S*n_runs, 65535), 1);
|
||||
|
||||
const ggml_cuda_kernel_launch_params params(grid, dim3(block_size, 1, 1), 0, ctx.stream());
|
||||
if (a.dyn) {
|
||||
if (a.res) {
|
||||
ggml_cuda_kernel_launch(short_conv_f32<true, true>, params, a);
|
||||
} else {
|
||||
ggml_cuda_kernel_launch(short_conv_f32<true, false>, params, a);
|
||||
}
|
||||
} else {
|
||||
if (a.res) {
|
||||
ggml_cuda_kernel_launch(short_conv_f32<false, true>, params, a);
|
||||
} else {
|
||||
ggml_cuda_kernel_launch(short_conv_f32<false, false>, params, a);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// one block per (query, token): the dot products of the B stack rows and of cur with the query, the softmax over the
|
||||
// B + 1 rows and the weighted sum; the norm of cur is a scale of its dot product
|
||||
template <int block_size>
|
||||
static __global__ void depth_mix_f32(
|
||||
const float * stack, const float * cur, const float * query, float * dst, const int n, const int B, const int Q,
|
||||
const int64_t stack_s1, const int64_t stack_s2, const int64_t cur_s1, const int64_t query_s1,
|
||||
const bool norm_cur, const float eps, const float scale) {
|
||||
ggml_cuda_pdl_lc();
|
||||
constexpr int MAX = GGML_CUDA_DEPTH_MIX_MAX_ROWS;
|
||||
constexpr int NW = block_size/WARP_SIZE;
|
||||
|
||||
const int q = blockIdx.x;
|
||||
const int t = blockIdx.y;
|
||||
const int tid = threadIdx.x;
|
||||
const int lane = tid % WARP_SIZE;
|
||||
const int warp = tid / WARP_SIZE;
|
||||
|
||||
const float * qv = query + q*query_s1;
|
||||
const float * st = stack + t*stack_s2;
|
||||
const float * xc = cur + t*cur_s1;
|
||||
|
||||
// [0, B): the stack rows, MAX: cur, MAX + 1: the sum of squares of cur
|
||||
float acc[MAX + 2];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < MAX + 2; ++r) {
|
||||
acc[r] = 0.0f;
|
||||
}
|
||||
|
||||
ggml_cuda_pdl_sync();
|
||||
|
||||
for (int i = tid; i < n; i += block_size) {
|
||||
const float qi = qv[i];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < MAX; ++r) {
|
||||
if (r < B) {
|
||||
acc[r] += st[r*stack_s1 + i]*qi;
|
||||
}
|
||||
}
|
||||
const float xi = xc[i];
|
||||
acc[MAX] += xi*qi;
|
||||
acc[MAX + 1] += xi*xi;
|
||||
}
|
||||
|
||||
__shared__ float s_acc[NW][MAX + 2];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < MAX + 2; ++r) {
|
||||
if (r < B || r >= MAX) {
|
||||
acc[r] = warp_reduce_sum(acc[r]);
|
||||
if (lane == 0) {
|
||||
s_acc[warp][r] = acc[r];
|
||||
}
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int r = 0; r < MAX + 2; ++r) {
|
||||
if (r < B || r >= MAX) {
|
||||
acc[r] = 0.0f;
|
||||
#pragma unroll
|
||||
for (int w = 0; w < NW; ++w) {
|
||||
acc[r] += s_acc[w][r];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const float sc = norm_cur ? rsqrtf(acc[MAX + 1]/n + eps) : 1.0f;
|
||||
|
||||
float mx = scale*(sc*acc[MAX]);
|
||||
#pragma unroll
|
||||
for (int r = 0; r < MAX; ++r) {
|
||||
if (r < B) {
|
||||
acc[r] = scale*acc[r];
|
||||
mx = fmaxf(mx, acc[r]);
|
||||
}
|
||||
}
|
||||
|
||||
float p_cur = expf(scale*(sc*acc[MAX]) - mx);
|
||||
float sum = 0.0f;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < MAX; ++r) {
|
||||
if (r < B) {
|
||||
acc[r] = expf(acc[r] - mx);
|
||||
sum += acc[r];
|
||||
}
|
||||
}
|
||||
sum += p_cur;
|
||||
|
||||
const float inv = 1.0f/sum;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < MAX; ++r) {
|
||||
acc[r] *= inv;
|
||||
}
|
||||
p_cur *= inv*sc;
|
||||
|
||||
for (int i = tid; i < n; i += block_size) {
|
||||
float o = 0.0f;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < MAX; ++r) {
|
||||
if (r < B) {
|
||||
o += acc[r]*st[r*stack_s1 + i];
|
||||
}
|
||||
}
|
||||
o += p_cur*xc[i];
|
||||
dst[((int64_t) t*n + i)*Q + q] = o;
|
||||
}
|
||||
}
|
||||
|
||||
void ggml_cuda_op_depth_mix(ggml_backend_cuda_context & ctx, const ggml_tensor * stack, const ggml_tensor * cur,
|
||||
bool norm_cur, float eps, const ggml_tensor * query, float scale, ggml_tensor * dst) {
|
||||
const int64_t n = cur->ne[0];
|
||||
const int64_t B = stack->ne[1];
|
||||
const int64_t T = stack->ne[2];
|
||||
const int64_t Q = query->ne[1];
|
||||
|
||||
GGML_ASSERT(B >= 1 && B <= GGML_CUDA_DEPTH_MIX_MAX_ROWS);
|
||||
GGML_ASSERT(stack->nb[0] == sizeof(float) && cur->nb[0] == sizeof(float) && query->nb[0] == sizeof(float));
|
||||
GGML_ASSERT(ggml_is_contiguous(dst) && dst->ne[0] == Q && dst->ne[1] == n && dst->ne[2] == T);
|
||||
GGML_ASSERT(T <= 65535 && Q <= 65535);
|
||||
|
||||
const int block_size = 256;
|
||||
const dim3 grid(Q, T, 1);
|
||||
|
||||
const ggml_cuda_kernel_launch_params params(grid, dim3(block_size, 1, 1), 0, ctx.stream());
|
||||
ggml_cuda_kernel_launch(depth_mix_f32<block_size>, params,
|
||||
(const float *) stack->data, (const float *) cur->data, (const float *) query->data, (float *) dst->data,
|
||||
(int) n, (int) B, (int) Q,
|
||||
(int64_t) (stack->nb[1]/sizeof(float)), (int64_t) (stack->nb[2]/sizeof(float)),
|
||||
(int64_t) (cur->nb[2]/sizeof(float)), (int64_t) (query->nb[1]/sizeof(float)),
|
||||
norm_cur, eps, scale);
|
||||
}
|
||||
|
||||
// one block per (rank row, token): the sums of squares of cur and msg and their dot products with the two halves of the row
|
||||
template <int block_size>
|
||||
static __global__ void loop_ctrl_down_f32(
|
||||
const float * cur, const float * msg, const float * w, float * gate, const int n,
|
||||
const int64_t cur_s1, const int64_t msg_s1, const int64_t w_s1, const int64_t gate_s1, const float eps) {
|
||||
ggml_cuda_pdl_lc();
|
||||
const int r = blockIdx.x;
|
||||
const int t = blockIdx.y;
|
||||
const int tid = threadIdx.x;
|
||||
|
||||
const float * xc = cur + t*cur_s1;
|
||||
const float * xm = msg + t*msg_s1;
|
||||
const float * wr = w + r*w_s1;
|
||||
|
||||
ggml_cuda_pdl_sync();
|
||||
|
||||
float2 ss = make_float2(0.0f, 0.0f);
|
||||
float2 dd = make_float2(0.0f, 0.0f);
|
||||
for (int i = tid; i < n; i += block_size) {
|
||||
const float c = xc[i];
|
||||
const float m = xm[i];
|
||||
ss.x += c*c;
|
||||
ss.y += m*m;
|
||||
dd.x += wr[i]*c;
|
||||
dd.y += wr[n + i]*m;
|
||||
}
|
||||
|
||||
__shared__ float2 s_ss[32];
|
||||
__shared__ float2 s_dd[32];
|
||||
ss = block_reduce<block_reduce_method::SUM, block_size>(ss, s_ss);
|
||||
dd = block_reduce<block_reduce_method::SUM, block_size>(dd, s_dd);
|
||||
|
||||
if (tid == 0) {
|
||||
gate[t*gate_s1 + r] = rsqrtf(ss.x/n + eps)*dd.x + rsqrtf(ss.y/n + eps)*dd.y;
|
||||
}
|
||||
}
|
||||
|
||||
// one warp per (output channel, token): the gain and forget dot products over the rank and the combine
|
||||
static __global__ void loop_ctrl_up_f32(
|
||||
const float * cur, const float * msg, const float * gate, const float * wg, const float * wf, float * dst,
|
||||
const int n, const int rank, const int64_t cur_s1, const int64_t msg_s1, const int64_t gate_s1,
|
||||
const int64_t wg_s1, const int64_t wf_s1, const int64_t dst_s1) {
|
||||
ggml_cuda_pdl_lc();
|
||||
const int i = blockIdx.x*blockDim.y + threadIdx.y;
|
||||
const int t = blockIdx.y;
|
||||
const int lane = threadIdx.x;
|
||||
|
||||
ggml_cuda_pdl_sync();
|
||||
if (i >= n) {
|
||||
return;
|
||||
}
|
||||
|
||||
const float * gt = gate + t*gate_s1;
|
||||
|
||||
float g = 0.0f;
|
||||
float f = 0.0f;
|
||||
for (int k = lane; k < rank; k += WARP_SIZE) {
|
||||
const float x = gt[k];
|
||||
g += wg[i*wg_s1 + k]*x;
|
||||
f += wf[i*wf_s1 + k]*x;
|
||||
}
|
||||
g = warp_reduce_sum(g);
|
||||
f = warp_reduce_sum(f);
|
||||
|
||||
if (lane == 0) {
|
||||
const float c = cur[t*cur_s1 + i];
|
||||
const float m = msg[t*msg_s1 + i];
|
||||
const float a = __fsub_rn(c, __fmul_rn(tanhf(f), c));
|
||||
dst[t*dst_s1 + i] = __fadd_rn(a, __fmul_rn(tanhf(g), m));
|
||||
}
|
||||
}
|
||||
|
||||
void ggml_cuda_op_loop_ctrl(ggml_backend_cuda_context & ctx, const ggml_tensor * cur, const ggml_tensor * msg, float eps,
|
||||
const ggml_tensor * w_down, const ggml_tensor * w_gain, const ggml_tensor * w_forget, ggml_tensor * gate, ggml_tensor * dst) {
|
||||
const int64_t n = cur->ne[0];
|
||||
const int64_t T = cur->ne[1];
|
||||
const int64_t rank = w_down->ne[1];
|
||||
|
||||
GGML_ASSERT(cur->nb[0] == sizeof(float) && msg->nb[0] == sizeof(float) && gate->nb[0] == sizeof(float) && dst->nb[0] == sizeof(float));
|
||||
GGML_ASSERT(w_down->ne[0] == 2*n && w_gain->ne[0] == rank && w_forget->ne[0] == rank && w_gain->ne[1] == n && w_forget->ne[1] == n);
|
||||
GGML_ASSERT(T <= GGML_CUDA_LOOP_CTRL_MAX_TOKENS);
|
||||
|
||||
cudaStream_t stream = ctx.stream();
|
||||
|
||||
{
|
||||
const int block_size = 256;
|
||||
const ggml_cuda_kernel_launch_params params(dim3(rank, T, 1), dim3(block_size, 1, 1), 0, stream);
|
||||
ggml_cuda_kernel_launch(loop_ctrl_down_f32<block_size>, params,
|
||||
(const float *) cur->data, (const float *) msg->data, (const float *) w_down->data, (float *) gate->data, (int) n,
|
||||
(int64_t) (cur->nb[1]/sizeof(float)), (int64_t) (msg->nb[1]/sizeof(float)),
|
||||
(int64_t) (w_down->nb[1]/sizeof(float)), (int64_t) (gate->nb[1]/sizeof(float)), eps);
|
||||
}
|
||||
{
|
||||
const int rows_per_block = 8;
|
||||
const ggml_cuda_kernel_launch_params params(dim3((n + rows_per_block - 1)/rows_per_block, T, 1), dim3(WARP_SIZE, rows_per_block, 1), 0, stream);
|
||||
ggml_cuda_kernel_launch(loop_ctrl_up_f32, params,
|
||||
(const float *) cur->data, (const float *) msg->data, (const float *) gate->data,
|
||||
(const float *) w_gain->data, (const float *) w_forget->data, (float *) dst->data, (int) n, (int) rank,
|
||||
(int64_t) (cur->nb[1]/sizeof(float)), (int64_t) (msg->nb[1]/sizeof(float)), (int64_t) (gate->nb[1]/sizeof(float)),
|
||||
(int64_t) (w_gain->nb[1]/sizeof(float)), (int64_t) (w_forget->nb[1]/sizeof(float)), (int64_t) (dst->nb[1]/sizeof(float)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
|
||||
#include "common.cuh"
|
||||
|
||||
// fused op chains of the Inkling 2 graph
|
||||
|
||||
// largest conv width and stack depth the fused kernels handle
|
||||
#define GGML_CUDA_SHORT_CONV_MAX_K 8
|
||||
#define GGML_CUDA_DEPTH_MIX_MAX_ROWS 16
|
||||
|
||||
// the most tokens the fused loop controller handles, larger batches use the matrix multiplications
|
||||
#define GGML_CUDA_LOOP_CTRL_MAX_TOKENS 8
|
||||
|
||||
// situ(g, u) = (s1*tanh(s0*g + b0) + b1)*sigmoid(g)*(s3*tanh(s2*u + b2) + b3), with s and b of the four SCALE nodes
|
||||
void ggml_cuda_op_situ(ggml_backend_cuda_context & ctx, const ggml_tensor * gate, const ggml_tensor * up,
|
||||
const float * s, const float * b, ggml_tensor * dst);
|
||||
|
||||
// causal short conv: x = [past; cur^T], y = conv(x, w) (+ input-dependent taps per head), dst = s*(cur + y) + b (+ res)
|
||||
// the K - 1 columns of x that end at token Ts - 1 - slot are the conv state of slot, for the last kw slots (kw = 1 without rollback)
|
||||
// each thread does `run` tokens of a sequence in order, run == Ts lets dst be cur
|
||||
struct ggml_cuda_short_conv_args {
|
||||
const float * past; // [K - 1, C, S], strides in elements
|
||||
int64_t past_s1;
|
||||
int64_t past_s2;
|
||||
const float * cur; // [C, Ts*S], contiguous
|
||||
const float * w; // [K, C], contiguous
|
||||
const float * dyn; // [K*H, Ts*S] taps or nullptr
|
||||
int64_t dyn_s1;
|
||||
int n_heads;
|
||||
const float * res; // [C, Ts*S], contiguous, or nullptr
|
||||
float * dst; // [C, Ts*S], contiguous
|
||||
float * state; // [K - 1, slot, C, S], strides in elements
|
||||
int64_t state_slot_s;
|
||||
int64_t state_ch_s;
|
||||
int64_t state_seq_s;
|
||||
int kw;
|
||||
int run;
|
||||
int C;
|
||||
int K;
|
||||
int Ts;
|
||||
int S;
|
||||
float scale;
|
||||
float bias;
|
||||
};
|
||||
|
||||
void ggml_cuda_op_short_conv(ggml_backend_cuda_context & ctx, const ggml_cuda_short_conv_args & args);
|
||||
|
||||
// depth mix: states = [stack; rms_norm(cur)], p = softmax(scale*(states . query)), dst = p . states, written as [Q, n, T]
|
||||
// norm_cur false: cur is already normalized
|
||||
void ggml_cuda_op_depth_mix(ggml_backend_cuda_context & ctx, const ggml_tensor * stack, const ggml_tensor * cur,
|
||||
bool norm_cur, float eps, const ggml_tensor * query, float scale, ggml_tensor * dst);
|
||||
|
||||
// loop controller: gate = w_down . [rms_norm(cur); rms_norm(msg)], dst = cur - tanh(w_forget . gate)*cur + tanh(w_gain . gate)*msg
|
||||
void ggml_cuda_op_loop_ctrl(ggml_backend_cuda_context & ctx, const ggml_tensor * cur, const ggml_tensor * msg, float eps,
|
||||
const ggml_tensor * w_down, const ggml_tensor * w_gain, const ggml_tensor * w_forget, ggml_tensor * gate, ggml_tensor * dst);
|
||||
@@ -799,10 +799,10 @@ static void launch_mul_mat_q_few_switch_ncg(const ggml_tensor * src0, const ggml
|
||||
void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst) {
|
||||
GGML_TENSOR_BINARY_OP_LOCALS;
|
||||
|
||||
GGML_ASSERT(src1->type == GGML_TYPE_F32);
|
||||
GGML_ASSERT(src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16);
|
||||
GGML_ASSERT( dst->type == GGML_TYPE_F32);
|
||||
GGML_ASSERT(nb00 == ggml_type_size(src0->type));
|
||||
GGML_ASSERT(nb10 == sizeof(float));
|
||||
GGML_ASSERT(nb10 == ggml_type_size(src1->type));
|
||||
GGML_ASSERT(nb0 == sizeof(float));
|
||||
GGML_ASSERT(ne00 % QK_K == 0);
|
||||
|
||||
@@ -828,14 +828,14 @@ void ggml_cuda_mul_mat_q_few(ggml_backend_cuda_context & ctx, const ggml_tensor
|
||||
|
||||
pairs.alloc(int64_t(npairs_max)*MMQ_FEW_PAIR_INTS);
|
||||
src1_q.alloc(int64_t(npairs_max)*nunits*MMQ_FEW_Q8_1_INT4);
|
||||
quantize_mmq_few_id_q8_1_cuda((const float *) src1->data, (const int32_t *) ids->data, src1_q.get(), pairs.get(), mmq_few_ds_layout(src0->type),
|
||||
ne00, nb11/sizeof(float), nb12/sizeof(float), ne11, ne02, n_expert_used, n_tokens, ids->nb[1]/sizeof(int32_t), npairs_max, stream);
|
||||
quantize_mmq_few_id_q8_1_cuda(src1->data, src1->type, (const int32_t *) ids->data, src1_q.get(), pairs.get(), mmq_few_ds_layout(src0->type),
|
||||
ne00, nb11/nb10, nb12/nb10, ne11, ne02, n_expert_used, n_tokens, ids->nb[1]/sizeof(int32_t), npairs_max, stream);
|
||||
} else {
|
||||
GGML_ASSERT(ne11 <= MMQ_FEW_MAX_NCG*MMQ_FEW_NCOLS);
|
||||
GGML_ASSERT(ne12 % ne02 == 0 && ne13 % ne03 == 0);
|
||||
|
||||
src1_q.alloc(int64_t(ne12)*ne13*nunits*ncg*MMQ_FEW_Q8_1_INT4);
|
||||
quantize_mmq_few_q8_1_cuda((const float *) src1->data, src1_q.get(), mmq_few_ds_layout(src0->type), ne10, nb11/sizeof(float), nb12/sizeof(float), nb13/sizeof(float),
|
||||
quantize_mmq_few_q8_1_cuda(src1->data, src1->type, src1_q.get(), mmq_few_ds_layout(src0->type), ne10, nb11/nb10, nb12/nb10, nb13/nb10,
|
||||
ne11, ne12, ne13, stream);
|
||||
}
|
||||
|
||||
|
||||
@@ -164,7 +164,7 @@ static int ggml_cuda_mmq_get_J_best(
|
||||
void ggml_cuda_mul_mat_q(
|
||||
ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst,
|
||||
const ggml_cuda_mm_fusion_args_host * fusion) {
|
||||
GGML_ASSERT( src1->type == GGML_TYPE_F32);
|
||||
GGML_ASSERT( src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16);
|
||||
GGML_ASSERT( dst->type == GGML_TYPE_F32);
|
||||
GGML_ASSERT(!ids || ids->type == GGML_TYPE_I32); // Optional, used for batched GGML_MUL_MAT_ID.
|
||||
|
||||
@@ -210,7 +210,6 @@ void ggml_cuda_mul_mat_q(
|
||||
GGML_ASSERT(!ids || ids->nb[0] == ggml_type_size(ids->type));
|
||||
|
||||
const char * src0_d = (const char *) src0->data;
|
||||
const float * src1_d = (const float *) src1->data;
|
||||
float * dst_d = (float *) dst->data;
|
||||
|
||||
// If src0 (or the fused gate weight) is a temporary compute buffer, clear any potential padding.
|
||||
@@ -284,11 +283,11 @@ void ggml_cuda_mul_mat_q(
|
||||
static constexpr size_t align_float8 = 32;
|
||||
const bool use_aligned_float8 = ggml_cuda_is_aligned(src1, align_float8);
|
||||
static_assert(sizeof(block_fp4_mmq) == 4 * sizeof(block_q8_1));
|
||||
quantize_mmq_fp4_cuda(src1_d, nullptr, src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10, s11, s12, s13, ne10_padded,
|
||||
quantize_mmq_fp4_cuda(src1->data, src1->type, nullptr, src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10, s11, s12, s13, ne10_padded,
|
||||
ne11, ne12, ne13, stream);
|
||||
|
||||
} else {
|
||||
quantize_mmq_q8_1_cuda(src1_d, nullptr, src1_q8_1.get(), src0->type, ne10, s11, s12, s13, ne10_padded,
|
||||
quantize_mmq_q8_1_cuda(src1->data, src1->type, nullptr, src1_q8_1.get(), src0->type, ne10, s11, s12, s13, ne10_padded,
|
||||
ne11, ne12, ne13, stream);
|
||||
}
|
||||
CUDA_CHECK(cudaGetLastError());
|
||||
@@ -359,17 +358,17 @@ void ggml_cuda_mul_mat_q(
|
||||
static constexpr size_t align_float8 = 32;
|
||||
const bool use_aligned_float8 = ggml_cuda_is_aligned(src1, align_float8);
|
||||
if (dedup_bcast) {
|
||||
quantize_scatter_mmq_fp4_cuda(src1_d, ids_src1.get(), src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10,
|
||||
quantize_scatter_mmq_fp4_cuda(src1->data, src1->type, ids_src1.get(), src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10,
|
||||
/*stride_token=*/s12, ne10_padded, ne12, ne11_flat, n_expert_used, stream);
|
||||
} else {
|
||||
quantize_mmq_fp4_cuda(src1_d, ids_src1.get(), src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10, s11, s12, s13,
|
||||
quantize_mmq_fp4_cuda(src1->data, src1->type, ids_src1.get(), src1_q8_1.get(), src1_scale.ptr, src0->type, use_aligned_float8, ne10, s11, s12, s13,
|
||||
ne10_padded, ne11_flat, ne12_flat, ne13_flat, stream);
|
||||
}
|
||||
} else if (dedup_bcast) {
|
||||
quantize_scatter_mmq_q8_1_cuda(src1_d, ids_src1.get(), src1_q8_1.get(), src0->type, ne10,
|
||||
quantize_scatter_mmq_q8_1_cuda(src1->data, src1->type, ids_src1.get(), src1_q8_1.get(), src0->type, ne10,
|
||||
/*stride_token=*/s12, ne10_padded, ne12, ne11_flat, n_expert_used, stream);
|
||||
} else {
|
||||
quantize_mmq_q8_1_cuda(src1_d, ids_src1.get(), src1_q8_1.get(), src0->type, ne10, s11, s12, s13,
|
||||
quantize_mmq_q8_1_cuda(src1->data, src1->type, ids_src1.get(), src1_q8_1.get(), src0->type, ne10, s11, s12, s13,
|
||||
ne10_padded, ne11_flat, ne12_flat, ne13_flat, stream);
|
||||
}
|
||||
CUDA_CHECK(cudaGetLastError());
|
||||
|
||||
+66
-27
@@ -13,15 +13,20 @@ static __device__ __forceinline__ float2 mmvf_load_fp8x2(const ggml_fp8_e4m3_t *
|
||||
#endif
|
||||
}
|
||||
|
||||
template <typename T, typename type_acc, int ncols_dst, int block_size, bool has_fusion = false, bool is_multi_token_id = false>
|
||||
template <typename T, typename type_acc, int ncols_dst, int block_size, bool has_fusion = false, bool is_multi_token_id = false,
|
||||
typename T_y = float>
|
||||
static __global__ void mul_mat_vec_f(
|
||||
const T * x_ptr, const float * y_ptr, const int32_t * ids_ptr, const ggml_cuda_mm_fusion_args_device fusion, float * dst_ptr,
|
||||
const T * x_ptr, const T_y * y_ptr, const int32_t * ids_ptr, const ggml_cuda_mm_fusion_args_device fusion, float * dst_ptr,
|
||||
const int ncols2, const uint3 nchannels_y, const int stride_row, const int stride_col_y2, const int stride_col_dst,
|
||||
const uint3 channel_ratio, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
|
||||
const uint3 sample_ratio, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst,
|
||||
const int ids_stride) {
|
||||
static_assert(std::is_same_v<T_y, float> || (std::is_same_v<T_y, nv_bfloat16> &&
|
||||
(std::is_same_v<T, nv_bfloat16> || std::is_same_v<T, ggml_fp8_e4m3_t>)), "a BF16 src1 needs BF16 or FP8 weights");
|
||||
using T_y2 = std::conditional_t<std::is_same_v<T_y, nv_bfloat16>, nv_bfloat162, float2>; // a pair of src1 values
|
||||
|
||||
const T * GGML_CUDA_RESTRICT x = x_ptr;
|
||||
const float * GGML_CUDA_RESTRICT y = y_ptr;
|
||||
const T_y * GGML_CUDA_RESTRICT y = y_ptr;
|
||||
const int32_t * GGML_CUDA_RESTRICT ids = ids_ptr;
|
||||
float * GGML_CUDA_RESTRICT dst = dst_ptr;
|
||||
const int row = blockIdx.x;
|
||||
@@ -257,7 +262,7 @@ static __global__ void mul_mat_vec_f(
|
||||
#endif // FP16_AVAILABLE
|
||||
}
|
||||
} else if constexpr (std::is_same_v<T, nv_bfloat16>) {
|
||||
const float2 * y2 = (const float2 *) y;
|
||||
const T_y2 * y2 = (const T_y2 *) y;
|
||||
//TODO: add support for ggml_cuda_mad for hip_bfloat162
|
||||
#if defined(GGML_USE_HIP)
|
||||
const int * x2 = (const int *) x;
|
||||
@@ -277,7 +282,7 @@ static __global__ void mul_mat_vec_f(
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < ncols_dst; ++j) {
|
||||
const float2 tmpy = y2[j*stride_col_y2 + col2];
|
||||
const float2 tmpy = ggml_cuda_cast<float2>(y2[j*stride_col_y2 + col2]);
|
||||
const float tmpx0 = ggml_cuda_cast<float>(reinterpret_cast<const nv_bfloat16 *>(&tmpx)[0]);
|
||||
const float tmpx1 = ggml_cuda_cast<float>(reinterpret_cast<const nv_bfloat16 *>(&tmpx)[1]);
|
||||
ggml_cuda_mad(sumf[j], tmpx0, tmpy.x);
|
||||
@@ -311,7 +316,7 @@ static __global__ void mul_mat_vec_f(
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < ncols_dst; ++j) {
|
||||
const float2 tmpy = y2[j*stride_col_y2 + col2];
|
||||
const float2 tmpy = ggml_cuda_cast<float2>(y2[j*stride_col_y2 + col2]);
|
||||
ggml_cuda_mad(sumf[j], tmpx.x, tmpy.x);
|
||||
ggml_cuda_mad(sumf[j], tmpx.y, tmpy.y);
|
||||
|
||||
@@ -325,7 +330,7 @@ static __global__ void mul_mat_vec_f(
|
||||
}
|
||||
#endif
|
||||
} else if constexpr (std::is_same_v<T, ggml_fp8_e4m3_t>) {
|
||||
const float2 * y2 = (const float2 *) y;
|
||||
const T_y2 * y2 = (const T_y2 *) y;
|
||||
for (int col2 = tid; col2 < ncols2; col2 += block_size) {
|
||||
const float2 tmpx = mmvf_load_fp8x2(x, col2);
|
||||
float2 tmpx_gate = {};
|
||||
@@ -336,7 +341,7 @@ static __global__ void mul_mat_vec_f(
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < ncols_dst; ++j) {
|
||||
const float2 tmpy = y2[j*stride_col_y2 + col2];
|
||||
const float2 tmpy = ggml_cuda_cast<float2>(y2[j*stride_col_y2 + col2]);
|
||||
ggml_cuda_mad(sumf[j], tmpx, tmpy);
|
||||
|
||||
if constexpr (has_fusion) {
|
||||
@@ -439,9 +444,9 @@ static __global__ void mul_mat_vec_f(
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T, typename type_acc, int ncols_dst, int block_size, bool is_multi_token_id = false>
|
||||
template<typename T, typename type_acc, int ncols_dst, int block_size, bool is_multi_token_id = false, typename T_y = float>
|
||||
static void mul_mat_vec_f_switch_fusion(
|
||||
const T * x, const float * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
|
||||
const T * x, const T_y * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
|
||||
const int64_t ncols, const uint3 nchannels_y,
|
||||
const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst,
|
||||
const uint3 channel_ratio, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst,
|
||||
@@ -454,7 +459,7 @@ static void mul_mat_vec_f_switch_fusion(
|
||||
fusion.x_scale != nullptr || fusion.gate_scale != nullptr;
|
||||
if constexpr (ncols_dst == 1) {
|
||||
if (has_fusion) {
|
||||
ggml_cuda_kernel_launch(mul_mat_vec_f<T, type_acc, ncols_dst, block_size, true, is_multi_token_id>, launch_params,
|
||||
ggml_cuda_kernel_launch(mul_mat_vec_f<T, type_acc, ncols_dst, block_size, true, is_multi_token_id, T_y>, launch_params,
|
||||
x, y, ids, fusion, dst, ncols, nchannels_y, stride_row, stride_col_y, stride_col_dst,
|
||||
channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst,
|
||||
sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, ids_stride);
|
||||
@@ -464,16 +469,16 @@ static void mul_mat_vec_f_switch_fusion(
|
||||
|
||||
GGML_ASSERT(!has_fusion && "fusion only supported for ncols_dst=1");
|
||||
|
||||
ggml_cuda_kernel_launch(mul_mat_vec_f<T, type_acc, ncols_dst, block_size, false, is_multi_token_id>, launch_params,
|
||||
ggml_cuda_kernel_launch(mul_mat_vec_f<T, type_acc, ncols_dst, block_size, false, is_multi_token_id, T_y>, launch_params,
|
||||
x, y, ids, fusion, dst, ncols, nchannels_y, stride_row, stride_col_y, stride_col_dst,
|
||||
channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst,
|
||||
sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, ids_stride);
|
||||
|
||||
}
|
||||
|
||||
template <typename T, typename type_acc, int ncols_dst, bool is_multi_token_id = false>
|
||||
template <typename T, typename type_acc, int ncols_dst, bool is_multi_token_id = false, typename T_y = float>
|
||||
void launch_mul_mat_vec_f_cuda(
|
||||
const T * x, const float * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
|
||||
const T * x, const T_y * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
|
||||
const int64_t ncols, const int64_t nrows,
|
||||
const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst,
|
||||
const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst,
|
||||
@@ -565,9 +570,9 @@ void launch_mul_mat_vec_f_cuda(
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T, typename type_acc>
|
||||
template <typename T, typename type_acc, typename T_y>
|
||||
static void mul_mat_vec_f_cuda_switch_ncols_dst(
|
||||
const T * x, const float * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
|
||||
const T * x, const T_y * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
|
||||
const int64_t ncols, const int64_t nrows, const int64_t ncols_dst,
|
||||
const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst,
|
||||
const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst,
|
||||
@@ -661,9 +666,9 @@ static void mul_mat_vec_f_cuda_switch_ncols_dst(
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
template<typename T, typename T_y>
|
||||
static void mul_mat_vec_f_cuda(
|
||||
const T * x, const float * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
|
||||
const T * x, const T_y * y, const int32_t * ids, const ggml_cuda_mm_fusion_args_device fusion, float * dst,
|
||||
const int64_t ncols, const int64_t nrows, const int64_t ncols_dst,
|
||||
const int64_t stride_row, const int64_t stride_col_y, const int stride_col_dst,
|
||||
const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst,
|
||||
@@ -688,7 +693,9 @@ static void mul_mat_vec_f_cuda(
|
||||
|
||||
void ggml_cuda_mul_mat_vec_f(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst,
|
||||
const ggml_cuda_mm_fusion_args_host * fusion) {
|
||||
GGML_ASSERT( src1->type == GGML_TYPE_F32);
|
||||
// a BF16 src1 only for BF16 and FP8 weights
|
||||
GGML_ASSERT( src1->type == GGML_TYPE_F32 ||
|
||||
(src1->type == GGML_TYPE_BF16 && (src0->type == GGML_TYPE_BF16 || src0->type == GGML_TYPE_F8_E4M3)));
|
||||
GGML_ASSERT(!ids || ids->type == GGML_TYPE_I32);
|
||||
GGML_ASSERT( dst->type == GGML_TYPE_F32);
|
||||
|
||||
@@ -790,12 +797,24 @@ void ggml_cuda_mul_mat_vec_f(ggml_backend_cuda_context & ctx, const ggml_tensor
|
||||
} break;
|
||||
case GGML_TYPE_BF16: {
|
||||
const nv_bfloat16 * src0_d = (const nv_bfloat16 *) src0->data;
|
||||
if (src1->type == GGML_TYPE_BF16) {
|
||||
mul_mat_vec_f_cuda(src0_d, (const nv_bfloat16 *) src1->data, ids_d, fusion_local, dst_d, ne00, ne01, ncols_dst, s01,
|
||||
stride_col_y, stride_col_dst, ne02, nchannels_y, nchannels_dst, s02, stride_channel_y, stride_channel_dst,
|
||||
ne03, ne3, s03, s13, s3, ids_stride, prec, ctx.stream());
|
||||
break;
|
||||
}
|
||||
mul_mat_vec_f_cuda(src0_d, src1_d, ids_d, fusion_local, dst_d, ne00, ne01, ncols_dst, s01, stride_col_y, stride_col_dst,
|
||||
ne02, nchannels_y, nchannels_dst, s02, stride_channel_y, stride_channel_dst,
|
||||
ne03, ne3, s03, s13, s3, ids_stride, prec, ctx.stream());
|
||||
} break;
|
||||
case GGML_TYPE_F8_E4M3: {
|
||||
const ggml_fp8_e4m3_t * src0_d = (const ggml_fp8_e4m3_t *) src0->data;
|
||||
if (src1->type == GGML_TYPE_BF16) {
|
||||
mul_mat_vec_f_cuda(src0_d, (const nv_bfloat16 *) src1->data, ids_d, fusion_local, dst_d, ne00, ne01, ncols_dst, s01,
|
||||
stride_col_y, stride_col_dst, ne02, nchannels_y, nchannels_dst, s02, stride_channel_y, stride_channel_dst,
|
||||
ne03, ne3, s03, s13, s3, ids_stride, prec, ctx.stream());
|
||||
break;
|
||||
}
|
||||
mul_mat_vec_f_cuda(src0_d, src1_d, ids_d, fusion_local, dst_d, ne00, ne01, ncols_dst, s01, stride_col_y, stride_col_dst,
|
||||
ne02, nchannels_y, nchannels_dst, s02, stride_channel_y, stride_channel_dst,
|
||||
ne03, ne3, s03, s13, s3, ids_stride, prec, ctx.stream());
|
||||
@@ -866,8 +885,8 @@ void ggml_cuda_op_mul_mat_vec_f(
|
||||
GGML_UNUSED_VARS(ctx, src1, dst, src1_ddq_i, src1_ncols, src1_padded_row_size);
|
||||
}
|
||||
|
||||
bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size, int64_t ne11) {
|
||||
const ggml_type type = src0->type;
|
||||
bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, ggml_type type_src1, int cc, int warp_size, int64_t ne11, bool mul_mat_id) {
|
||||
const ggml_type type_src0 = src0->type;
|
||||
const int64_t * src0_ne = src0->ne;
|
||||
const size_t * src0_nb = src0->nb;
|
||||
|
||||
@@ -875,7 +894,7 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size,
|
||||
return false;
|
||||
}
|
||||
|
||||
const size_t ts = ggml_type_size(type);
|
||||
const size_t ts = ggml_type_size(type_src0);
|
||||
if (src0_nb[0] != ts) {
|
||||
return false;
|
||||
}
|
||||
@@ -884,7 +903,27 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size,
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (type) {
|
||||
// MMVF reads a BF16 src1 only for BF16 and FP8 weights
|
||||
if (type_src1 == GGML_TYPE_BF16 && type_src0 != GGML_TYPE_BF16 && type_src0 != GGML_TYPE_F8_E4M3) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (mul_mat_id) {
|
||||
// FP8 experts on all GPUs, F32/F16/BF16 experts on AMD, and BF16 experts with a BF16 src1, which MMF can not read
|
||||
// (with an F32 src1 NVIDIA takes MMF where it supports the experts, otherwise the sorted fallback)
|
||||
switch (type_src0) {
|
||||
case GGML_TYPE_F32:
|
||||
case GGML_TYPE_F16:
|
||||
case GGML_TYPE_BF16:
|
||||
return ne11 <= MMVF_MAX_BATCH_SIZE && (GGML_CUDA_CC_IS_AMD(cc) || type_src1 == GGML_TYPE_BF16);
|
||||
case GGML_TYPE_F8_E4M3:
|
||||
return ne11 <= MMVF_MAX_BATCH_SIZE;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
switch (type_src0) {
|
||||
case GGML_TYPE_F32:
|
||||
if (GGML_CUDA_CC_IS_NVIDIA(cc)) {
|
||||
if (ampere_mma_available(cc)) {
|
||||
@@ -905,7 +944,7 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size,
|
||||
if (GGML_CUDA_CC_IS_NVIDIA(cc)) {
|
||||
const bool src0_small = (src0_ne[1] <= 512 || src0_ne[2]*src0_ne[3] == 1);
|
||||
// MMF needs full row tiles, for other row counts MMVF still beats cuBLAS at small batch size
|
||||
if (src0_small && !ggml_cuda_should_use_mmf(type, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
|
||||
if (src0_small && !ggml_cuda_should_use_mmf(type_src0, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
|
||||
return ne11 <= MMVF_MAX_BATCH_SIZE;
|
||||
}
|
||||
if (ampere_mma_available(cc)) {
|
||||
@@ -919,7 +958,7 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size,
|
||||
}
|
||||
return ne11 <= MMVF_MAX_BATCH_SIZE;
|
||||
} else if (GGML_CUDA_CC_IS_AMD(cc)) {
|
||||
if (GGML_CUDA_CC_IS_RDNA(cc) && !ggml_cuda_should_use_mmf(type, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
|
||||
if (GGML_CUDA_CC_IS_RDNA(cc) && !ggml_cuda_should_use_mmf(type_src0, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
|
||||
return ne11 <= MMVF_MAX_BATCH_SIZE;
|
||||
}
|
||||
if (fp16_mma_hardware_available(cc)) {
|
||||
@@ -938,7 +977,7 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size,
|
||||
if (GGML_CUDA_CC_IS_NVIDIA(cc)) {
|
||||
const bool src0_small = (src0_ne[1] <= 512 || src0_ne[2]*src0_ne[3] == 1);
|
||||
// MMF needs full row tiles, for other row counts MMVF still beats cuBLAS at small batch size
|
||||
if (src0_small && !ggml_cuda_should_use_mmf(type, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
|
||||
if (src0_small && !ggml_cuda_should_use_mmf(type_src0, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
|
||||
return ne11 <= MMVF_MAX_BATCH_SIZE;
|
||||
}
|
||||
// MMF tiles 32 rows per block, so a matrix of few rows leaves most SMs idle while MMVF runs a block
|
||||
@@ -964,7 +1003,7 @@ bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size,
|
||||
}
|
||||
return ne11 <= MMVF_MAX_BATCH_SIZE;
|
||||
} else if (GGML_CUDA_CC_IS_AMD(cc)) {
|
||||
if (GGML_CUDA_CC_IS_RDNA(cc) && !ggml_cuda_should_use_mmf(type, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
|
||||
if (GGML_CUDA_CC_IS_RDNA(cc) && !ggml_cuda_should_use_mmf(type_src0, cc, warp_size, src0_ne, src0_nb, ne11, /*mul_mat_id =*/ false)) {
|
||||
return ne11 <= MMVF_MAX_BATCH_SIZE;
|
||||
}
|
||||
if (bf16_mma_hardware_available(cc)) {
|
||||
|
||||
@@ -11,4 +11,4 @@ void ggml_cuda_op_mul_mat_vec_f(
|
||||
const char * src1_ddq_i, float * dst_dd_i, const int64_t row_low, const int64_t row_high, const int64_t src1_ncols,
|
||||
const int64_t src1_padded_row_size, cudaStream_t stream);
|
||||
|
||||
bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, int cc, int warp_size, int64_t ne11);
|
||||
bool ggml_cuda_should_use_mmvf(const ggml_tensor * src0, ggml_type type_src1, int cc, int warp_size, int64_t ne11, bool mul_mat_id);
|
||||
|
||||
@@ -1538,7 +1538,7 @@ static void mul_mat_vec_q_switch_type(
|
||||
void ggml_cuda_mul_mat_vec_q(
|
||||
ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst,
|
||||
const ggml_cuda_mm_fusion_args_host * fusion) {
|
||||
GGML_ASSERT( src1->type == GGML_TYPE_F32);
|
||||
GGML_ASSERT( src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16);
|
||||
GGML_ASSERT( dst->type == GGML_TYPE_F32);
|
||||
GGML_ASSERT(!ids || ids->type == GGML_TYPE_I32); // Optional, used for batched GGML_MUL_MAT_ID.
|
||||
|
||||
@@ -1557,7 +1557,6 @@ void ggml_cuda_mul_mat_vec_q(
|
||||
|
||||
GGML_ASSERT(!ids || ne12 <= MMVQ_MAX_BATCH_SIZE);
|
||||
|
||||
const float * src1_d = (const float *) src1->data;
|
||||
const int32_t * ids_d = ids ? (const int32_t *) ids->data : nullptr;
|
||||
float * dst_d = (float *) dst->data;
|
||||
|
||||
@@ -1637,7 +1636,7 @@ void ggml_cuda_mul_mat_vec_q(
|
||||
const int64_t s11 = src1->nb[1] / ts_src1;
|
||||
const int64_t s12 = src1->nb[2] / ts_src1;
|
||||
const int64_t s13 = src1->nb[3] / ts_src1;
|
||||
quantize_row_q8_1_cuda(src1_d, src1_q8_1.get(), ne10, s11, s12, s13, ne10_padded, ne11, ne12, ne13, stream);
|
||||
quantize_row_q8_1_cuda(src1->data, src1->type, src1_q8_1.get(), ne10, s11, s12, s13, ne10_padded, ne11, ne12, ne13, stream);
|
||||
}
|
||||
|
||||
const int64_t s01 = src0->nb[1] / ts_src0;
|
||||
|
||||
@@ -399,6 +399,54 @@ static __global__ void l2_norm_f32(
|
||||
}
|
||||
}
|
||||
|
||||
// l2_norm with an optional per-column weight before it and SCALE (+ an optional MUL by a per-channel/sample factor) after it,
|
||||
// with the reduction of l2_norm_f32
|
||||
template <int block_size, bool has_w, bool has_f>
|
||||
static __global__ void l2_clip_f32(
|
||||
const float * x, const float * w, const float * f, float * dst, const int ncols, const int nchannels, const int nsamples,
|
||||
const int64_t stride_row, const int64_t stride_channel, const int64_t stride_sample,
|
||||
const int64_t w_stride_row, const int64_t w_stride_channel, const int64_t w_stride_sample,
|
||||
const int64_t f_stride_channel, const int64_t f_stride_sample, const float eps, const float scale, const float bias) {
|
||||
ggml_cuda_pdl_lc();
|
||||
const int nrows = gridDim.x;
|
||||
const int row = blockIdx.x;
|
||||
const int tid = threadIdx.x;
|
||||
|
||||
extern __shared__ float s_sum[];
|
||||
|
||||
ggml_cuda_pdl_sync();
|
||||
|
||||
for (int sample = blockIdx.z; sample < nsamples; sample += gridDim.z) {
|
||||
for (int channel = blockIdx.y; channel < nchannels; channel += gridDim.y) {
|
||||
const float * xc = x + sample*stride_sample + channel*stride_channel + row*stride_row;
|
||||
const float * wc = has_w ? w + sample*w_stride_sample + channel*w_stride_channel + row*w_stride_row : nullptr;
|
||||
float * dstc = dst + ((sample*nchannels + channel)*nrows + row)*ncols;
|
||||
|
||||
float tmp = 0.0f;
|
||||
|
||||
for (int col = tid; col < ncols; col += block_size) {
|
||||
const float xi = has_w ? xc[col]*wc[col] : xc[col];
|
||||
tmp += xi * xi;
|
||||
}
|
||||
|
||||
tmp = block_reduce<block_reduce_method::SUM, block_size>(tmp, s_sum);
|
||||
|
||||
const float l2 = rsqrtf(fmaxf(tmp, eps * eps));
|
||||
const float fc = has_f ? f[sample*f_stride_sample + channel*f_stride_channel] : 1.0f;
|
||||
|
||||
for (int col = tid; col < ncols; col += block_size) {
|
||||
const float xi = has_w ? xc[col]*wc[col] : xc[col];
|
||||
const float yi = scale*(l2*xi) + bias;
|
||||
dstc[col] = has_f ? yi*fc : yi;
|
||||
}
|
||||
|
||||
if constexpr (block_size > WARP_SIZE) {
|
||||
__syncthreads();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <bool do_multiply = false, bool do_add = false>
|
||||
static void norm_f32_cuda(const float * x,
|
||||
float * dst,
|
||||
@@ -623,6 +671,71 @@ static void l2_norm_f32_cuda(
|
||||
}
|
||||
}
|
||||
|
||||
template <bool has_w, bool has_f>
|
||||
static void l2_clip_f32_cuda(
|
||||
const float * x, const float * w, const float * f, float * dst, const int ncols, const int nrows, const int nchannels, const int nsamples,
|
||||
const int64_t stride_row, const int64_t stride_channel, const int64_t stride_sample,
|
||||
const int64_t w_stride_row, const int64_t w_stride_channel, const int64_t w_stride_sample,
|
||||
const int64_t f_stride_channel, const int64_t f_stride_sample, const float eps, const float scale, const float bias, cudaStream_t stream) {
|
||||
const dim3 blocks_num(nrows, MIN(nchannels, UINT16_MAX), MIN(nsamples, UINT16_MAX));
|
||||
if (ncols < 1024) {
|
||||
const ggml_cuda_kernel_launch_params params(blocks_num, dim3(WARP_SIZE, 1, 1), 0, stream);
|
||||
ggml_cuda_kernel_launch(l2_clip_f32<WARP_SIZE, has_w, has_f>, params, x, w, f, dst, ncols, nchannels, nsamples,
|
||||
stride_row, stride_channel, stride_sample, w_stride_row, w_stride_channel, w_stride_sample,
|
||||
f_stride_channel, f_stride_sample, eps, scale, bias);
|
||||
} else {
|
||||
const ggml_cuda_kernel_launch_params params(blocks_num, dim3(1024, 1, 1), 32 * sizeof(float), stream);
|
||||
ggml_cuda_kernel_launch(l2_clip_f32<1024, has_w, has_f>, params, x, w, f, dst, ncols, nchannels, nsamples,
|
||||
stride_row, stride_channel, stride_sample, w_stride_row, w_stride_channel, w_stride_sample,
|
||||
f_stride_channel, f_stride_sample, eps, scale, bias);
|
||||
}
|
||||
}
|
||||
|
||||
void ggml_cuda_op_l2_clip(ggml_backend_cuda_context & ctx, const ggml_tensor * x, const ggml_tensor * w, const ggml_tensor * l2_norm,
|
||||
const ggml_tensor * scale, const ggml_tensor * f, ggml_tensor * dst) {
|
||||
GGML_ASSERT(x->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32 && x->nb[0] == sizeof(float));
|
||||
GGML_ASSERT(ggml_is_contiguous(dst) && ggml_are_same_shape(x, dst));
|
||||
|
||||
GGML_TENSOR_LOCALS(int64_t, ne0, x, ne);
|
||||
GGML_TENSOR_LOCALS(size_t, nb0, x, nb);
|
||||
|
||||
// broadcast dimensions of w and f have a stride of 0
|
||||
auto bcast_stride = [](const ggml_tensor * t, int dim) -> int64_t {
|
||||
return t->ne[dim] == 1 ? 0 : (int64_t) (t->nb[dim]/sizeof(float));
|
||||
};
|
||||
|
||||
const int64_t ws1 = w ? bcast_stride(w, 1) : 0;
|
||||
const int64_t ws2 = w ? bcast_stride(w, 2) : 0;
|
||||
const int64_t ws3 = w ? bcast_stride(w, 3) : 0;
|
||||
const int64_t fs2 = f ? bcast_stride(f, 2) : 0;
|
||||
const int64_t fs3 = f ? bcast_stride(f, 3) : 0;
|
||||
|
||||
const float * x_d = (const float *) x->data;
|
||||
const float * w_d = w ? (const float *) w->data : nullptr;
|
||||
const float * f_d = f ? (const float *) f->data : nullptr;
|
||||
float * d_d = (float *) dst->data;
|
||||
|
||||
const float eps = ggml_get_op_params_f32(l2_norm, 0);
|
||||
const float s = ggml_get_op_params_f32(scale, 0);
|
||||
const float b = ggml_get_op_params_f32(scale, 1);
|
||||
|
||||
const int64_t s01 = nb01/sizeof(float);
|
||||
const int64_t s02 = nb02/sizeof(float);
|
||||
const int64_t s03 = nb03/sizeof(float);
|
||||
|
||||
cudaStream_t stream = ctx.stream();
|
||||
|
||||
if (w && f) {
|
||||
l2_clip_f32_cuda<true, true >(x_d, w_d, f_d, d_d, ne00, ne01, ne02, ne03, s01, s02, s03, ws1, ws2, ws3, fs2, fs3, eps, s, b, stream);
|
||||
} else if (w) {
|
||||
l2_clip_f32_cuda<true, false>(x_d, w_d, f_d, d_d, ne00, ne01, ne02, ne03, s01, s02, s03, ws1, ws2, ws3, fs2, fs3, eps, s, b, stream);
|
||||
} else if (f) {
|
||||
l2_clip_f32_cuda<false, true >(x_d, w_d, f_d, d_d, ne00, ne01, ne02, ne03, s01, s02, s03, ws1, ws2, ws3, fs2, fs3, eps, s, b, stream);
|
||||
} else {
|
||||
l2_clip_f32_cuda<false, false>(x_d, w_d, f_d, d_d, ne00, ne01, ne02, ne03, s01, s02, s03, ws1, ws2, ws3, fs2, fs3, eps, s, b, stream);
|
||||
}
|
||||
}
|
||||
|
||||
void ggml_cuda_op_norm(ggml_backend_cuda_context & ctx, ggml_tensor * dst, ggml_tensor * mul, ggml_tensor * add) {
|
||||
const ggml_tensor * src0 = dst->src[0];
|
||||
const float * src0_d = (const float *) src0->data;
|
||||
|
||||
@@ -21,3 +21,7 @@ void ggml_cuda_op_rms_norm_fused_add(ggml_backend_cuda_context & ctx,
|
||||
void ggml_cuda_op_rms_norm_back(ggml_backend_cuda_context & ctx, ggml_tensor * dst);
|
||||
|
||||
void ggml_cuda_op_l2_norm(ggml_backend_cuda_context & ctx, ggml_tensor * dst);
|
||||
|
||||
// [MUL by w ->] L2_NORM -> SCALE [-> MUL by f], w broadcasts over the rows, f is one value per channel/sample
|
||||
void ggml_cuda_op_l2_clip(ggml_backend_cuda_context & ctx, const ggml_tensor * x, const ggml_tensor * w, const ggml_tensor * l2_norm,
|
||||
const ggml_tensor * scale, const ggml_tensor * f, ggml_tensor * dst);
|
||||
|
||||
+170
-59
@@ -1,6 +1,21 @@
|
||||
#include "quantize.cuh"
|
||||
#include "convert.cuh"
|
||||
#include <cstdint>
|
||||
|
||||
// 4 consecutive values of x as float4, x + 4*i is aligned to 4 values
|
||||
template <typename src_t>
|
||||
static __device__ __forceinline__ float4 quantize_load4(const src_t * x, const int64_t i) {
|
||||
if constexpr (std::is_same_v<src_t, nv_bfloat16>) {
|
||||
__align__(8) nv_bfloat162 v[2];
|
||||
ggml_cuda_memcpy_1<sizeof(v)>(v, x + 4*i);
|
||||
const float2 lo = ggml_cuda_cast<float2>(v[0]);
|
||||
const float2 hi = ggml_cuda_cast<float2>(v[1]);
|
||||
return make_float4(lo.x, lo.y, hi.x, hi.y);
|
||||
} else {
|
||||
return ((const float4 *) x)[i];
|
||||
}
|
||||
}
|
||||
|
||||
#if defined(BLACKWELL_MMA_AVAILABLE)
|
||||
// this maps to 256-bit loads in PTX on supported devices,
|
||||
// and otherwise falls back to 2 128-bit loads
|
||||
@@ -9,6 +24,23 @@ struct __builtin_align__(32) float8 {
|
||||
float p; float q; float r; float s;
|
||||
};
|
||||
|
||||
// 8 consecutive values of x as float8, x is aligned to 8 values
|
||||
// for float it returns a reference like a direct load, a copy changes the register allocation of the kernels
|
||||
template <typename src_t>
|
||||
static __device__ __forceinline__ decltype(auto) quantize_load8(const src_t * x) {
|
||||
if constexpr (std::is_same_v<src_t, nv_bfloat16>) {
|
||||
__align__(16) nv_bfloat162 v[4];
|
||||
ggml_cuda_memcpy_1<sizeof(v)>(v, x);
|
||||
const float2 a = ggml_cuda_cast<float2>(v[0]);
|
||||
const float2 b = ggml_cuda_cast<float2>(v[1]);
|
||||
const float2 c = ggml_cuda_cast<float2>(v[2]);
|
||||
const float2 d = ggml_cuda_cast<float2>(v[3]);
|
||||
return float8{a.x, a.y, b.x, b.y, c.x, c.y, d.x, d.y};
|
||||
} else {
|
||||
return reinterpret_cast<const float8 *>(x)[0];
|
||||
}
|
||||
}
|
||||
|
||||
#if CUDART_VERSION >= 12080
|
||||
static __device__ __forceinline__ float nvfp4_native_scale_error(
|
||||
const float vals[QK_NVFP4_SUB], const float inv_col_scale, const float inv_scale, const float scale) {
|
||||
@@ -50,13 +82,14 @@ static __device__ __forceinline__ float nvfp4_native_scale_error(
|
||||
#endif // CUDART_VERSION >= 12080
|
||||
#endif // defined(BLACKWELL_MMA_AVAILABLE)
|
||||
|
||||
template <typename src_t>
|
||||
__launch_bounds__(CUDA_QUANTIZE_BLOCK_SIZE, 1)
|
||||
static __global__ void quantize_q8_1(
|
||||
const float * x_ptr, void * vy_ptr,
|
||||
const src_t * x_ptr, void * vy_ptr,
|
||||
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const int64_t ne0, const uint32_t ne1, const uint3 ne2) {
|
||||
ggml_cuda_pdl_lc();
|
||||
const float * GGML_CUDA_RESTRICT x = x_ptr;
|
||||
const src_t * GGML_CUDA_RESTRICT x = x_ptr;
|
||||
void * GGML_CUDA_RESTRICT vy = vy_ptr;
|
||||
const int64_t i0 = (int64_t)blockDim.x*blockIdx.x + threadIdx.x;
|
||||
|
||||
@@ -81,7 +114,7 @@ static __global__ void quantize_q8_1(
|
||||
const int64_t iqs = i_cont % QK8_1; // quant index
|
||||
|
||||
ggml_cuda_pdl_sync();
|
||||
const float xi = i0 < ne00 ? x[i03*s03 + i02*s02 + i01*s01 + i00] : 0.0f;
|
||||
const float xi = i0 < ne00 ? ggml_cuda_cast<float>(x[i03*s03 + i02*s02 + i01*s01 + i00]) : 0.0f;
|
||||
float amax = fabsf(xi);
|
||||
|
||||
amax = warp_reduce_max<QK8_1>(amax);
|
||||
@@ -124,9 +157,9 @@ __device__ __forceinline__ uint8_t compute_e8m0_scale(float amax) {
|
||||
}
|
||||
|
||||
// scatter: grid over tokens, quantize once, write to all the token's compact rows
|
||||
template <bool scatter, bool use_aligned_float8>
|
||||
template <typename src_t, bool scatter, bool use_aligned_float8>
|
||||
static __global__ void quantize_mmq_nvfp4(
|
||||
const float * __restrict__ x, const int32_t * __restrict__ ids, void * __restrict__ vy, float * __restrict__ scale,
|
||||
const src_t * __restrict__ x, const int32_t * __restrict__ ids, void * __restrict__ vy, float * __restrict__ scale,
|
||||
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int n_expert_used) {
|
||||
#if defined(BLACKWELL_MMA_AVAILABLE)
|
||||
@@ -140,13 +173,12 @@ static __global__ void quantize_mmq_nvfp4(
|
||||
const int64_t i01 = ids ? ids[blockIdx.x] : blockIdx.x;
|
||||
base_idx = i3 * s03 + i2 * s02 + i01 * s01;
|
||||
}
|
||||
const float * __restrict__ x_row = x + base_idx;
|
||||
const src_t * __restrict__ x_row = x + base_idx;
|
||||
|
||||
float amax = 0.0f;
|
||||
if constexpr (use_aligned_float8) {
|
||||
for (int64_t i0 = 8 * threadIdx.x; i0 < ne00; i0 += 8 * blockDim.x) {
|
||||
const float * x_base = x_row + i0;
|
||||
const float8 v = reinterpret_cast<const float8 *>(x_base)[0];
|
||||
const float8 v = quantize_load8(x_row + i0);
|
||||
amax = fmaxf(amax, fabsf(v.x));
|
||||
amax = fmaxf(amax, fabsf(v.y));
|
||||
amax = fmaxf(amax, fabsf(v.z));
|
||||
@@ -158,7 +190,7 @@ static __global__ void quantize_mmq_nvfp4(
|
||||
}
|
||||
} else {
|
||||
for (int64_t i0 = threadIdx.x; i0 < ne00; i0 += blockDim.x) {
|
||||
amax = fmaxf(amax, fabsf(x_row[i0]));
|
||||
amax = fmaxf(amax, fabsf(ggml_cuda_cast<float>(x_row[i0])));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,9 +236,9 @@ static __global__ void quantize_mmq_nvfp4(
|
||||
|
||||
float vals[QK_NVFP4_SUB];
|
||||
if constexpr (use_aligned_float8) {
|
||||
const float * x_base = x_row + i0_base;
|
||||
const float8 v0 = i0_base + 7 < ne00 ? reinterpret_cast<const float8 *>(x_base)[0] : float8{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
|
||||
const float8 v1 = i0_base + 15 < ne00 ? reinterpret_cast<const float8 *>(x_base + 8)[0] : float8{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
|
||||
const src_t * x_base = x_row + i0_base;
|
||||
const float8 v0 = i0_base + 7 < ne00 ? quantize_load8(x_base) : float8{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
|
||||
const float8 v1 = i0_base + 15 < ne00 ? quantize_load8(x_base + 8) : float8{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
|
||||
vals[0] = v0.x; vals[1] = v0.y; vals[2] = v0.z; vals[3] = v0.w;
|
||||
vals[4] = v0.p; vals[5] = v0.q; vals[6] = v0.r; vals[7] = v0.s;
|
||||
vals[8] = v1.x; vals[9] = v1.y; vals[10] = v1.z; vals[11] = v1.w;
|
||||
@@ -215,7 +247,7 @@ static __global__ void quantize_mmq_nvfp4(
|
||||
#pragma unroll
|
||||
for (int k = 0; k < QK_NVFP4_SUB; ++k) {
|
||||
const int64_t i00 = i0_base + k;
|
||||
vals[k] = i00 < ne00 ? x_row[i00] : 0.0f;
|
||||
vals[k] = i00 < ne00 ? ggml_cuda_cast<float>(x_row[i00]) : 0.0f;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -333,8 +365,8 @@ static __global__ void quantize_mmq_nvfp4(
|
||||
// quantize values in the format mxfp4 is stored which is interleaved nibbles
|
||||
// i.e. a block a0-a31 is represented as a0a16,a1a17 ...a15a31
|
||||
// scatter: grid over tokens, quantize once, write to all the token's compact rows
|
||||
template <bool scatter>
|
||||
static __global__ void quantize_mmq_mxfp4(const float * __restrict__ x,
|
||||
template <typename src_t, bool scatter>
|
||||
static __global__ void quantize_mmq_mxfp4(const src_t * __restrict__ x,
|
||||
const int32_t * __restrict__ ids,
|
||||
void * __restrict__ vy,
|
||||
const int64_t ne00,
|
||||
@@ -384,7 +416,7 @@ static __global__ void quantize_mmq_mxfp4(const float * __restrict__ x,
|
||||
#pragma unroll
|
||||
for (int b = 0; b < 2; ++b) {
|
||||
const int64_t i0 = warp_start_offset + b * vals_per_scale + lane_id_32;
|
||||
const float xi = (i0 < ne00) ? x[base_pos + i0] : 0.0f;
|
||||
const float xi = (i0 < ne00) ? ggml_cuda_cast<float>(x[base_pos + i0]) : 0.0f;
|
||||
|
||||
float amax = fabsf(xi);
|
||||
#pragma unroll
|
||||
@@ -453,9 +485,9 @@ static __global__ void quantize_mmq_mxfp4(const float * __restrict__ x,
|
||||
}
|
||||
|
||||
// scatter: grid over tokens, quantize once, write to all the token's compact rows
|
||||
template <mmq_q8_1_ds_layout ds_layout, bool scatter>
|
||||
template <typename src_t, mmq_q8_1_ds_layout ds_layout, bool scatter>
|
||||
static __global__ void quantize_mmq_q8_1(
|
||||
const float * __restrict__ x, const int32_t * __restrict__ ids, void * __restrict__ vy,
|
||||
const src_t * __restrict__ x, const int32_t * __restrict__ ids, void * __restrict__ vy,
|
||||
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const int64_t ne0, const int ne1, const int ne2, const int n_expert_used) {
|
||||
|
||||
@@ -481,14 +513,13 @@ static __global__ void quantize_mmq_q8_1(
|
||||
base_idx = i3*s03 + i2*s02 + i01*s01;
|
||||
}
|
||||
|
||||
const float4 * x4 = (const float4 *) x;
|
||||
block_q8_1_mmq * y = (block_q8_1_mmq *) vy;
|
||||
|
||||
const int64_t k_block = i0 / QK8_1_MMQ; // column block in the channel
|
||||
const int64_t iqs = i0 % QK8_1_MMQ; // quant index in block
|
||||
|
||||
// Load 4 floats per thread and calculate max. abs. value between them:
|
||||
const float4 xi = i0 < ne00 ? x4[(base_idx + i00)/4] : make_float4(0.0f, 0.0f, 0.0f, 0.0f);
|
||||
const float4 xi = i0 < ne00 ? quantize_load4(x, (base_idx + i00)/4) : make_float4(0.0f, 0.0f, 0.0f, 0.0f);
|
||||
float amax = fabsf(xi.x);
|
||||
amax = fmaxf(amax, fabsf(xi.y));
|
||||
amax = fmaxf(amax, fabsf(xi.z));
|
||||
@@ -556,8 +587,20 @@ static __global__ void quantize_mmq_q8_1(
|
||||
GGML_UNUSED(n_expert_used);
|
||||
}
|
||||
|
||||
void quantize_row_q8_1_cuda(
|
||||
const float * x, void * vy,
|
||||
// calls launch with x as const float * or const nv_bfloat16 *, the src1 types that the quantize kernels read
|
||||
template <typename F>
|
||||
static void quantize_launch_typed(const void * x, const ggml_type type_src1, const F & launch) {
|
||||
if (type_src1 == GGML_TYPE_BF16) {
|
||||
launch((const nv_bfloat16 *) x);
|
||||
} else {
|
||||
GGML_ASSERT(type_src1 == GGML_TYPE_F32);
|
||||
launch((const float *) x);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename src_t>
|
||||
static void quantize_row_q8_1_cuda(
|
||||
const src_t * x, void * vy,
|
||||
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
|
||||
GGML_ASSERT(ne0 % QK8_1 == 0);
|
||||
@@ -568,11 +611,21 @@ void quantize_row_q8_1_cuda(
|
||||
const dim3 num_blocks(block_num_x, ne1, ne2*ne3);
|
||||
const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE, 1, 1);
|
||||
const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(num_blocks, block_size, 0, stream);
|
||||
ggml_cuda_kernel_launch(quantize_q8_1, launch_params, x, vy, ne00, s01, s02, s03, ne0, ne1, ne2_fastdiv);
|
||||
ggml_cuda_kernel_launch(quantize_q8_1<src_t>, launch_params, x, vy, ne00, s01, s02, s03, ne0, ne1, ne2_fastdiv);
|
||||
}
|
||||
|
||||
void quantize_mmq_q8_1_cuda(
|
||||
const float * x, const int32_t * ids, void * vy, const ggml_type type_src0,
|
||||
void quantize_row_q8_1_cuda(
|
||||
const void * x, const ggml_type type_src1, void * vy,
|
||||
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
|
||||
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
|
||||
quantize_row_q8_1_cuda(x_t, vy, ne00, s01, s02, s03, ne0, ne1, ne2, ne3, stream);
|
||||
});
|
||||
}
|
||||
|
||||
template <typename src_t>
|
||||
static void quantize_mmq_q8_1_cuda(
|
||||
const src_t * x, const int32_t * ids, void * vy, const ggml_type type_src0,
|
||||
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
|
||||
GGML_ASSERT(ne00 % 4 == 0);
|
||||
@@ -584,15 +637,15 @@ void quantize_mmq_q8_1_cuda(
|
||||
const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1);
|
||||
switch (mmq_get_q8_1_ds_layout(type_src0)) {
|
||||
case MMQ_Q8_1_DS_LAYOUT_D4:
|
||||
quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_D4, false>
|
||||
quantize_mmq_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D4, false>
|
||||
<<<num_blocks, block_size, 0, stream>>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
|
||||
break;
|
||||
case MMQ_Q8_1_DS_LAYOUT_DS4:
|
||||
quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_DS4, false>
|
||||
quantize_mmq_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_DS4, false>
|
||||
<<<num_blocks, block_size, 0, stream>>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
|
||||
break;
|
||||
case MMQ_Q8_1_DS_LAYOUT_D2S6:
|
||||
quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_D2S6, false>
|
||||
quantize_mmq_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D2S6, false>
|
||||
<<<num_blocks, block_size, 0, stream>>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
|
||||
break;
|
||||
default:
|
||||
@@ -600,6 +653,15 @@ void quantize_mmq_q8_1_cuda(
|
||||
}
|
||||
}
|
||||
|
||||
void quantize_mmq_q8_1_cuda(
|
||||
const void * x, const ggml_type type_src1, const int32_t * ids, void * vy, const ggml_type type_src0,
|
||||
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
|
||||
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
|
||||
quantize_mmq_q8_1_cuda(x_t, ids, vy, type_src0, ne00, s01, s02, s03, ne0, ne1, ne2, ne3, stream);
|
||||
});
|
||||
}
|
||||
|
||||
// Stores the 4 values xi of a thread, values [iu, iu + 4) of column g in a unit of 256 values, in the column group yg of the unit, see quantize.cuh for the layout.
|
||||
template <mmq_q8_1_ds_layout ds_layout>
|
||||
static __device__ __forceinline__ void quantize_mmq_few_store(const float4 xi, int4 * yg, const int iu, const int g) {
|
||||
@@ -635,12 +697,12 @@ static __device__ __forceinline__ void quantize_mmq_few_store(const float4 xi, i
|
||||
}
|
||||
|
||||
// Each thread quantizes 4 values of one column, see quantize.cuh for the layout.
|
||||
template <mmq_q8_1_ds_layout ds_layout>
|
||||
template <typename src_t, mmq_q8_1_ds_layout ds_layout>
|
||||
static __global__ void quantize_mmq_few_q8_1(
|
||||
const float * x_ptr, void * vy_ptr, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const src_t * x_ptr, void * vy_ptr, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const int ne1, const int ne2) {
|
||||
ggml_cuda_pdl_lc();
|
||||
const float * GGML_CUDA_RESTRICT x = x_ptr;
|
||||
const src_t * GGML_CUDA_RESTRICT x = x_ptr;
|
||||
int4 * GGML_CUDA_RESTRICT vy = (int4 *) vy_ptr;
|
||||
const int64_t i0 = ((int64_t)blockDim.x*blockIdx.y + threadIdx.x)*4;
|
||||
|
||||
@@ -651,7 +713,7 @@ static __global__ void quantize_mmq_few_q8_1(
|
||||
|
||||
const int64_t i2 = blockIdx.z % ne2;
|
||||
const int64_t i3 = blockIdx.z / ne2;
|
||||
const float4 xi = (int) blockIdx.x < ne1 ? *(const float4 *) (x + i3*s03 + i2*s02 + blockIdx.x*s01 + i0) : make_float4(0.0f, 0.0f, 0.0f, 0.0f);
|
||||
const float4 xi = (int) blockIdx.x < ne1 ? quantize_load4(x + i3*s03 + i2*s02 + blockIdx.x*s01 + i0, 0) : make_float4(0.0f, 0.0f, 0.0f, 0.0f);
|
||||
|
||||
const int g = blockIdx.x % MMQ_FEW_NCOLS; // column in group
|
||||
int4 * yg = vy + ((blockIdx.z*(ne00/QK_K) + i0/QK_K)*(gridDim.x/MMQ_FEW_NCOLS) + blockIdx.x/MMQ_FEW_NCOLS)*MMQ_FEW_Q8_1_INT4;
|
||||
@@ -660,9 +722,9 @@ static __global__ void quantize_mmq_few_q8_1(
|
||||
|
||||
// MUL_MAT_ID: block x is the (token, slot) entry, ids are as in mm_ids_helper. Each block finds the pair of its entry in shared memory, block (0, 0) also writes all pairs.
|
||||
// Entry rank r = number of earlier tokens with the same expert, pair = first pair of the expert + r/MMQ_FEW_NCOLS, column = r % MMQ_FEW_NCOLS.
|
||||
template <mmq_q8_1_ds_layout ds_layout>
|
||||
template <typename src_t, mmq_q8_1_ds_layout ds_layout>
|
||||
static __global__ void quantize_mmq_few_id_q8_1(
|
||||
const float * x_ptr, const int32_t * ids, void * vy_ptr, int * pairs, const int64_t ne00, const int64_t s11, const int64_t s12,
|
||||
const src_t * x_ptr, const int32_t * ids, void * vy_ptr, int * pairs, const int64_t ne00, const int64_t s11, const int64_t s12,
|
||||
const int ne11, const int n_experts, const int n_expert_used, const int64_t si1, const int npairs_max) {
|
||||
// per expert: bit t set if token t uses it and the index of its first pair; then the total number of pairs
|
||||
extern __shared__ unsigned int data_mmq_few_id[];
|
||||
@@ -671,7 +733,7 @@ static __global__ void quantize_mmq_few_id_q8_1(
|
||||
int & npairs = pair0[n_experts];
|
||||
|
||||
ggml_cuda_pdl_lc();
|
||||
const float * GGML_CUDA_RESTRICT x = x_ptr;
|
||||
const src_t * GGML_CUDA_RESTRICT x = x_ptr;
|
||||
int4 * GGML_CUDA_RESTRICT vy = (int4 *) vy_ptr;
|
||||
ggml_cuda_pdl_sync();
|
||||
|
||||
@@ -741,15 +803,16 @@ static __global__ void quantize_mmq_few_id_q8_1(
|
||||
}
|
||||
const int it = blockIdx.x / n_expert_used;
|
||||
const int is = blockIdx.x % n_expert_used;
|
||||
const float4 xi = *(const float4 *) (x + it*s12 + (is % ne11)*s11 + i0);
|
||||
const float4 xi = quantize_load4(x + it*s12 + (is % ne11)*s11 + i0, 0);
|
||||
|
||||
const int r = rank(blockIdx.x, e);
|
||||
int4 * yg = vy + (int64_t(pair0[e] + r/MMQ_FEW_NCOLS)*(ne00/QK_K) + i0/QK_K)*MMQ_FEW_Q8_1_INT4;
|
||||
quantize_mmq_few_store<ds_layout>(xi, yg, i0 % QK_K, r % MMQ_FEW_NCOLS);
|
||||
}
|
||||
|
||||
void quantize_mmq_few_q8_1_cuda(
|
||||
const float * x, void * vy, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
template <typename src_t>
|
||||
static void quantize_mmq_few_q8_1_cuda(
|
||||
const src_t * x, void * vy, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
|
||||
GGML_ASSERT(ne00 % QK_K == 0);
|
||||
|
||||
@@ -759,11 +822,11 @@ void quantize_mmq_few_q8_1_cuda(
|
||||
const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(num_blocks, block_size, 0, stream);
|
||||
switch (ds_layout) {
|
||||
case MMQ_Q8_1_DS_LAYOUT_D4:
|
||||
ggml_cuda_kernel_launch(quantize_mmq_few_q8_1<MMQ_Q8_1_DS_LAYOUT_D4>, launch_params,
|
||||
ggml_cuda_kernel_launch(quantize_mmq_few_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D4>, launch_params,
|
||||
x, vy, ne00, s01, s02, s03, (int) ne1, (int) ne2);
|
||||
break;
|
||||
case MMQ_Q8_1_DS_LAYOUT_DS4:
|
||||
ggml_cuda_kernel_launch(quantize_mmq_few_q8_1<MMQ_Q8_1_DS_LAYOUT_DS4>, launch_params,
|
||||
ggml_cuda_kernel_launch(quantize_mmq_few_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_DS4>, launch_params,
|
||||
x, vy, ne00, s01, s02, s03, (int) ne1, (int) ne2);
|
||||
break;
|
||||
default:
|
||||
@@ -771,8 +834,17 @@ void quantize_mmq_few_q8_1_cuda(
|
||||
}
|
||||
}
|
||||
|
||||
void quantize_mmq_few_id_q8_1_cuda(
|
||||
const float * x, const int32_t * ids, void * vy, int * pairs, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s11, const int64_t s12,
|
||||
void quantize_mmq_few_q8_1_cuda(
|
||||
const void * x, const ggml_type type_src1, void * vy, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
|
||||
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
|
||||
quantize_mmq_few_q8_1_cuda(x_t, vy, ds_layout, ne00, s01, s02, s03, ne1, ne2, ne3, stream);
|
||||
});
|
||||
}
|
||||
|
||||
template <typename src_t>
|
||||
static void quantize_mmq_few_id_q8_1_cuda(
|
||||
const src_t * x, const int32_t * ids, void * vy, int * pairs, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s11, const int64_t s12,
|
||||
const int64_t ne11, const int64_t n_experts, const int64_t n_expert_used, const int64_t n_tokens, const int64_t si1, const int64_t npairs_max, cudaStream_t stream) {
|
||||
GGML_ASSERT(ne00 % QK_K == 0);
|
||||
GGML_ASSERT(n_tokens <= 32); // one bit per token
|
||||
@@ -785,11 +857,11 @@ void quantize_mmq_few_id_q8_1_cuda(
|
||||
const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(num_blocks, block_size, nbytes_shared, stream);
|
||||
switch (ds_layout) {
|
||||
case MMQ_Q8_1_DS_LAYOUT_D4:
|
||||
ggml_cuda_kernel_launch(quantize_mmq_few_id_q8_1<MMQ_Q8_1_DS_LAYOUT_D4>, launch_params,
|
||||
ggml_cuda_kernel_launch(quantize_mmq_few_id_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D4>, launch_params,
|
||||
x, ids, vy, pairs, ne00, s11, s12, (int) ne11, (int) n_experts, (int) n_expert_used, si1, (int) npairs_max);
|
||||
break;
|
||||
case MMQ_Q8_1_DS_LAYOUT_DS4:
|
||||
ggml_cuda_kernel_launch(quantize_mmq_few_id_q8_1<MMQ_Q8_1_DS_LAYOUT_DS4>, launch_params,
|
||||
ggml_cuda_kernel_launch(quantize_mmq_few_id_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_DS4>, launch_params,
|
||||
x, ids, vy, pairs, ne00, s11, s12, (int) ne11, (int) n_experts, (int) n_expert_used, si1, (int) npairs_max);
|
||||
break;
|
||||
default:
|
||||
@@ -797,9 +869,18 @@ void quantize_mmq_few_id_q8_1_cuda(
|
||||
}
|
||||
}
|
||||
|
||||
void quantize_mmq_few_id_q8_1_cuda(
|
||||
const void * x, const ggml_type type_src1, const int32_t * ids, void * vy, int * pairs, const mmq_q8_1_ds_layout ds_layout, const int64_t ne00, const int64_t s11, const int64_t s12,
|
||||
const int64_t ne11, const int64_t n_experts, const int64_t n_expert_used, const int64_t n_tokens, const int64_t si1, const int64_t npairs_max, cudaStream_t stream) {
|
||||
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
|
||||
quantize_mmq_few_id_q8_1_cuda(x_t, ids, vy, pairs, ds_layout, ne00, s11, s12, ne11, n_experts, n_expert_used, n_tokens, si1, npairs_max, stream);
|
||||
});
|
||||
}
|
||||
|
||||
// scatter=true reuses the quant kernel: grid over tokens, ids = inverse map (token slot -> compact row)
|
||||
void quantize_scatter_mmq_q8_1_cuda(
|
||||
const float * x, const int32_t * ids_src1_inv, void * vy, const ggml_type type_src0,
|
||||
template <typename src_t>
|
||||
static void quantize_scatter_mmq_q8_1_cuda(
|
||||
const src_t * x, const int32_t * ids_src1_inv, void * vy, const ggml_type type_src0,
|
||||
const int64_t ne00, const int64_t stride_token, const int64_t ne0,
|
||||
const int64_t n_tokens, const int64_t nrows_dst, const int n_expert_used, cudaStream_t stream) {
|
||||
GGML_ASSERT(ne00 % 4 == 0);
|
||||
@@ -810,15 +891,15 @@ void quantize_scatter_mmq_q8_1_cuda(
|
||||
const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1);
|
||||
switch (mmq_get_q8_1_ds_layout(type_src0)) {
|
||||
case MMQ_Q8_1_DS_LAYOUT_D4:
|
||||
quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_D4, true><<<num_blocks, block_size, 0, stream>>>(
|
||||
quantize_mmq_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D4, true><<<num_blocks, block_size, 0, stream>>>(
|
||||
x, ids_src1_inv, vy, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/(int) nrows_dst, /*ne2=*/1, n_expert_used);
|
||||
break;
|
||||
case MMQ_Q8_1_DS_LAYOUT_DS4:
|
||||
quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_DS4, true><<<num_blocks, block_size, 0, stream>>>(
|
||||
quantize_mmq_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_DS4, true><<<num_blocks, block_size, 0, stream>>>(
|
||||
x, ids_src1_inv, vy, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/(int) nrows_dst, /*ne2=*/1, n_expert_used);
|
||||
break;
|
||||
case MMQ_Q8_1_DS_LAYOUT_D2S6:
|
||||
quantize_mmq_q8_1<MMQ_Q8_1_DS_LAYOUT_D2S6, true><<<num_blocks, block_size, 0, stream>>>(
|
||||
quantize_mmq_q8_1<src_t, MMQ_Q8_1_DS_LAYOUT_D2S6, true><<<num_blocks, block_size, 0, stream>>>(
|
||||
x, ids_src1_inv, vy, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/(int) nrows_dst, /*ne2=*/1, n_expert_used);
|
||||
break;
|
||||
default:
|
||||
@@ -826,9 +907,19 @@ void quantize_scatter_mmq_q8_1_cuda(
|
||||
}
|
||||
}
|
||||
|
||||
void quantize_scatter_mmq_q8_1_cuda(
|
||||
const void * x, const ggml_type type_src1, const int32_t * ids_src1_inv, void * vy, const ggml_type type_src0,
|
||||
const int64_t ne00, const int64_t stride_token, const int64_t ne0,
|
||||
const int64_t n_tokens, const int64_t nrows_dst, const int n_expert_used, cudaStream_t stream) {
|
||||
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
|
||||
quantize_scatter_mmq_q8_1_cuda(x_t, ids_src1_inv, vy, type_src0, ne00, stride_token, ne0, n_tokens, nrows_dst, n_expert_used, stream);
|
||||
});
|
||||
}
|
||||
|
||||
// scatter=true reuses the quant kernels: grid over tokens, ids = inverse map (token slot -> compact row)
|
||||
void quantize_scatter_mmq_fp4_cuda(
|
||||
const float * x, const int32_t * ids_src1_inv, void * vy, float * scale, const ggml_type type_src0, const bool use_aligned_float8,
|
||||
template <typename src_t>
|
||||
static void quantize_scatter_mmq_fp4_cuda(
|
||||
const src_t * x, const int32_t * ids_src1_inv, void * vy, float * scale, const ggml_type type_src0, const bool use_aligned_float8,
|
||||
const int64_t ne00, const int64_t stride_token, const int64_t ne0,
|
||||
const int64_t n_tokens, const int64_t nrows_dst, const int n_expert_used, cudaStream_t stream) {
|
||||
GGML_ASSERT(ne0 > 0);
|
||||
@@ -838,10 +929,10 @@ void quantize_scatter_mmq_fp4_cuda(
|
||||
const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1);
|
||||
const dim3 num_blocks(n_tokens, 1, 1);
|
||||
if (use_aligned_float8) {
|
||||
quantize_mmq_nvfp4<true, true><<<num_blocks, block_size, 0, stream>>>(
|
||||
quantize_mmq_nvfp4<src_t, true, true><<<num_blocks, block_size, 0, stream>>>(
|
||||
x, ids_src1_inv, vy, scale, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/nrows_dst, /*ne2=*/1, n_expert_used);
|
||||
} else {
|
||||
quantize_mmq_nvfp4<true, false><<<num_blocks, block_size, 0, stream>>>(
|
||||
quantize_mmq_nvfp4<src_t, true, false><<<num_blocks, block_size, 0, stream>>>(
|
||||
x, ids_src1_inv, vy, scale, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/nrows_dst, /*ne2=*/1, n_expert_used);
|
||||
}
|
||||
} else {
|
||||
@@ -851,13 +942,24 @@ void quantize_scatter_mmq_fp4_cuda(
|
||||
const int64_t block_num_y = (ne0 + vals_per_block - 1) / vals_per_block;
|
||||
const dim3 block_size(WARP_SIZE, nwarps, 1);
|
||||
const dim3 num_blocks(n_tokens, block_num_y, 1);
|
||||
quantize_mmq_mxfp4<true><<<num_blocks, block_size, 0, stream>>>(
|
||||
quantize_mmq_mxfp4<src_t, true><<<num_blocks, block_size, 0, stream>>>(
|
||||
x, ids_src1_inv, vy, ne00, /*s01=*/0, /*s02=*/stride_token, /*s03=*/0, ne0, /*ne1=*/(int) nrows_dst, /*ne2=*/1, n_expert_used);
|
||||
}
|
||||
}
|
||||
|
||||
void quantize_mmq_fp4_cuda(
|
||||
const float * x, const int32_t * ids, void * vy, float * scale, const ggml_type type_src0, const bool use_aligned_float8,
|
||||
void quantize_scatter_mmq_fp4_cuda(
|
||||
const void * x, const ggml_type type_src1, const int32_t * ids_src1_inv, void * vy, float * scale, const ggml_type type_src0,
|
||||
const bool use_aligned_float8, const int64_t ne00, const int64_t stride_token, const int64_t ne0,
|
||||
const int64_t n_tokens, const int64_t nrows_dst, const int n_expert_used, cudaStream_t stream) {
|
||||
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
|
||||
quantize_scatter_mmq_fp4_cuda(x_t, ids_src1_inv, vy, scale, type_src0, use_aligned_float8, ne00, stride_token, ne0,
|
||||
n_tokens, nrows_dst, n_expert_used, stream);
|
||||
});
|
||||
}
|
||||
|
||||
template <typename src_t>
|
||||
static void quantize_mmq_fp4_cuda(
|
||||
const src_t * x, const int32_t * ids, void * vy, float * scale, const ggml_type type_src0, const bool use_aligned_float8,
|
||||
const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
|
||||
GGML_ASSERT(type_src0 == GGML_TYPE_MXFP4 || type_src0 == GGML_TYPE_NVFP4);
|
||||
@@ -869,10 +971,10 @@ void quantize_mmq_fp4_cuda(
|
||||
const dim3 block_size(CUDA_QUANTIZE_BLOCK_SIZE_MMQ, 1, 1);
|
||||
const dim3 num_blocks(ne1, ne2 * ne3, 1);
|
||||
if (use_aligned_float8) {
|
||||
quantize_mmq_nvfp4<false, true><<<num_blocks, block_size, 0, stream>>>(
|
||||
quantize_mmq_nvfp4<src_t, false, true><<<num_blocks, block_size, 0, stream>>>(
|
||||
x, ids, vy, scale, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
|
||||
} else {
|
||||
quantize_mmq_nvfp4<false, false><<<num_blocks, block_size, 0, stream>>>(
|
||||
quantize_mmq_nvfp4<src_t, false, false><<<num_blocks, block_size, 0, stream>>>(
|
||||
x, ids, vy, scale, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
|
||||
}
|
||||
} else {
|
||||
@@ -886,6 +988,15 @@ void quantize_mmq_fp4_cuda(
|
||||
const dim3 num_blocks(ne1, block_num_y, ne2 * ne3);
|
||||
const dim3 block_size(WARP_SIZE, nwarps, 1);
|
||||
|
||||
quantize_mmq_mxfp4<false><<<num_blocks, block_size, 0, stream>>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
|
||||
quantize_mmq_mxfp4<src_t, false><<<num_blocks, block_size, 0, stream>>>(x, ids, vy, ne00, s01, s02, s03, ne0, ne1, ne2, /*n_expert_used=*/0);
|
||||
}
|
||||
}
|
||||
|
||||
void quantize_mmq_fp4_cuda(
|
||||
const void * x, const ggml_type type_src1, const int32_t * ids, void * vy, float * scale, const ggml_type type_src0,
|
||||
const bool use_aligned_float8, const int64_t ne00, const int64_t s01, const int64_t s02, const int64_t s03,
|
||||
const int64_t ne0, const int64_t ne1, const int64_t ne2, const int64_t ne3, cudaStream_t stream) {
|
||||
quantize_launch_typed(x, type_src1, [&](auto * x_t) {
|
||||
quantize_mmq_fp4_cuda(x_t, ids, vy, scale, type_src0, use_aligned_float8, ne00, s01, s02, s03, ne0, ne1, ne2, ne3, stream);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -11,13 +11,15 @@
|
||||
static_assert(MATRIX_ROW_PADDING % CUDA_QUANTIZE_BLOCK_SIZE == 0, "Risk of out-of-bounds access.");
|
||||
static_assert(MATRIX_ROW_PADDING % (4*CUDA_QUANTIZE_BLOCK_SIZE_MMQ) == 0, "Risk of out-of-bounds access.");
|
||||
|
||||
// x holds the src1 values, type_src1 is GGML_TYPE_F32 or GGML_TYPE_BF16
|
||||
|
||||
void quantize_row_q8_1_cuda(
|
||||
const float * x, void * vy,
|
||||
const void * x, ggml_type type_src1, void * vy,
|
||||
int64_t ne00, int64_t s01, int64_t s02, int64_t s03,
|
||||
int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3, cudaStream_t stream);
|
||||
|
||||
void quantize_mmq_q8_1_cuda(
|
||||
const float * x, const int32_t * ids, void * vy,
|
||||
const void * x, ggml_type type_src1, const int32_t * ids, void * vy,
|
||||
ggml_type type_src0, int64_t ne00, int64_t s01, int64_t s02, int64_t s03,
|
||||
int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3, cudaStream_t stream);
|
||||
|
||||
@@ -29,7 +31,7 @@ static constexpr int MMQ_FEW_NCOLS = 8; // src1 columns per column group
|
||||
static constexpr int MMQ_FEW_Q8_1_INT4 = 4*WARP_SIZE + 4*4; // int4 per 256 values and column group
|
||||
|
||||
void quantize_mmq_few_q8_1_cuda(
|
||||
const float * x, void * vy, mmq_q8_1_ds_layout ds_layout, int64_t ne00, int64_t s01, int64_t s02, int64_t s03,
|
||||
const void * x, ggml_type type_src1, void * vy, mmq_q8_1_ds_layout ds_layout, int64_t ne00, int64_t s01, int64_t s02, int64_t s03,
|
||||
int64_t ne1, int64_t ne2, int64_t ne3, cudaStream_t stream);
|
||||
|
||||
// MUL_MAT_ID: a pair is an expert and one column group of up to MMQ_FEW_NCOLS of its (token, slot) entries. The src1 of pair p is channel p above, its columns past the entries are not written.
|
||||
@@ -37,10 +39,11 @@ void quantize_mmq_few_q8_1_cuda(
|
||||
static constexpr int MMQ_FEW_PAIR_INTS = 2 + MMQ_FEW_NCOLS;
|
||||
|
||||
void quantize_mmq_few_id_q8_1_cuda(
|
||||
const float * x, const int32_t * ids, void * vy, int * pairs, mmq_q8_1_ds_layout ds_layout, int64_t ne00, int64_t s11, int64_t s12,
|
||||
const void * x, ggml_type type_src1, const int32_t * ids, void * vy, int * pairs, mmq_q8_1_ds_layout ds_layout, int64_t ne00, int64_t s11, int64_t s12,
|
||||
int64_t ne11, int64_t n_experts, int64_t n_expert_used, int64_t n_tokens, int64_t si1, int64_t npairs_max, cudaStream_t stream);
|
||||
|
||||
void quantize_mmq_fp4_cuda(const float * x,
|
||||
void quantize_mmq_fp4_cuda(const void * x,
|
||||
ggml_type type_src1,
|
||||
const int32_t * ids,
|
||||
void * vy,
|
||||
float * scale,
|
||||
@@ -57,7 +60,8 @@ void quantize_mmq_fp4_cuda(const float * x,
|
||||
cudaStream_t stream);
|
||||
|
||||
// quantize each token once and scatter the block to its compact rows (via the inverse map)
|
||||
void quantize_scatter_mmq_fp4_cuda(const float * x,
|
||||
void quantize_scatter_mmq_fp4_cuda(const void * x,
|
||||
ggml_type type_src1,
|
||||
const int32_t * ids_src1_inv,
|
||||
void * vy,
|
||||
float * scale,
|
||||
@@ -71,7 +75,8 @@ void quantize_scatter_mmq_fp4_cuda(const float * x,
|
||||
int n_expert_used,
|
||||
cudaStream_t stream);
|
||||
|
||||
void quantize_scatter_mmq_q8_1_cuda(const float * x,
|
||||
void quantize_scatter_mmq_q8_1_cuda(const void * x,
|
||||
ggml_type type_src1,
|
||||
const int32_t * ids_src1_inv,
|
||||
void * vy,
|
||||
ggml_type type_src0,
|
||||
|
||||
@@ -1536,6 +1536,11 @@ static bool ggml_metal_supports_mul_mat_op(
|
||||
return false;
|
||||
}
|
||||
|
||||
// BF16 src1 kernels: mul_mv for F32 and BF16 src0, mul_mm for BF16 src0
|
||||
if (op->src[1]->type == GGML_TYPE_BF16) {
|
||||
return op->op == GGML_OP_MUL_MAT && (op->src[0]->type == GGML_TYPE_BF16 || (op->src[0]->type == GGML_TYPE_F32 && !mm_path));
|
||||
}
|
||||
|
||||
if (op->src[1]->type != GGML_TYPE_F16) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -2046,6 +2046,9 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
|
||||
return {false, "MUL_MAT_ID with single-expert or empty ne[2] <= 1 (ne[2]=" +
|
||||
std::to_string(op->src[0]->ne[2]) + ") is not supported"};
|
||||
}
|
||||
if (op->src[1] != nullptr && op->src[1]->type == GGML_TYPE_BF16) {
|
||||
return {false, "MUL_MAT_ID with a BF16 src1 is not supported"};
|
||||
}
|
||||
// The GPU plugin's GatherMatmul returns wrong values for the layouts test-backend-ops
|
||||
// produces: it builds a rank-4 input layout ([n_used, n_tokens, k, 1]) instead of rank 3
|
||||
// and the kernel misreads it, silently returning garbage (NMSE ~86) rather than asserting.
|
||||
|
||||
@@ -7435,6 +7435,11 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons
|
||||
return false;
|
||||
}
|
||||
|
||||
// MUL_MAT_ID copies the src1 rows as F32
|
||||
if (op->op == GGML_OP_MUL_MAT_ID && b->type != GGML_TYPE_F32) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (op->op == GGML_OP_MUL_MAT &&
|
||||
(ggml_prec_get_src(op, 1) == GGML_PREC_BF16 || ggml_prec_get_src(op, 1) == GGML_PREC_F32)) {
|
||||
return false;
|
||||
|
||||
@@ -23,7 +23,10 @@ static vk_device_architecture get_device_architecture(const vk::PhysicalDevice&
|
||||
}
|
||||
}
|
||||
|
||||
if (!amd_shader_core_properties || !integer_dot_product || !subgroup_size_control) {
|
||||
if (!subgroup_size_control) {
|
||||
return vk_device_architecture::AMD_GCN;
|
||||
}
|
||||
if (!amd_shader_core_properties) {
|
||||
return vk_device_architecture::OTHER;
|
||||
}
|
||||
|
||||
@@ -33,8 +36,10 @@ static vk_device_architecture get_device_architecture(const vk::PhysicalDevice&
|
||||
vk::PhysicalDeviceSubgroupSizeControlPropertiesEXT subgroup_size_control_props;
|
||||
|
||||
props2.pNext = &shader_core_props_amd;
|
||||
shader_core_props_amd.pNext = &integer_dot_props;
|
||||
integer_dot_props.pNext = &subgroup_size_control_props;
|
||||
shader_core_props_amd.pNext = &subgroup_size_control_props;
|
||||
if (integer_dot_product) {
|
||||
subgroup_size_control_props.pNext = &integer_dot_props;
|
||||
}
|
||||
|
||||
device.getProperties2(&props2);
|
||||
|
||||
@@ -49,7 +54,7 @@ static vk_device_architecture get_device_architecture(const vk::PhysicalDevice&
|
||||
if (shader_float8) {
|
||||
return vk_device_architecture::AMD_RDNA4;
|
||||
}
|
||||
if (integer_dot_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) {
|
||||
if (integer_dot_product && integer_dot_props.integerDotProduct4x8BitPackedMixedSignednessAccelerated) {
|
||||
return vk_device_architecture::AMD_RDNA3;
|
||||
}
|
||||
return vk_device_architecture::AMD_RDNA2;
|
||||
@@ -1215,7 +1220,8 @@ static vk_fa_tuning_params get_fa_tuning_params_scalar(const vk_device& device,
|
||||
// Disable subgroup use due to performance issues when enforcing subgroup sizes
|
||||
result.subgroup_size = 32;
|
||||
result.disable_subgroups = true;
|
||||
} else if (device->vendor_id == VK_VENDOR_ID_AMD && device->architecture != AMD_GCN) {
|
||||
} else if (device->vendor_id == VK_VENDOR_ID_AMD && device->architecture != AMD_GCN &&
|
||||
device->subgroup_size_control && device->subgroup_min_size <= 32) {
|
||||
result.subgroup_size = n_rows < 4 ? 32 : device->subgroup_size;
|
||||
} else {
|
||||
result.subgroup_size = device->subgroup_size;
|
||||
|
||||
@@ -721,6 +721,11 @@ static bool ggml_backend_zendnn_device_supports_op(ggml_backend_dev_t dev, const
|
||||
return false;
|
||||
}
|
||||
|
||||
// the inputs are read as F32; only BF16 weights also take BF16 inputs as they are
|
||||
if (inputs->type != GGML_TYPE_F32 && !(inputs->type == GGML_TYPE_BF16 && weights->type == GGML_TYPE_BF16)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (ggml_prec_get_src(op, 1) == GGML_PREC_BF16 || ggml_prec_get_src(op, 1) == GGML_PREC_F32) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -175,6 +175,7 @@ class Keys:
|
||||
CONV_GROUP_SIZE = "{arch}.conv_group_size"
|
||||
SELECTOR_RANK = "{arch}.selector_rank"
|
||||
SELECTOR_TOP_K = "{arch}.selector_top_k"
|
||||
SELECTOR_SOFTCAP_AFTER_CORRECTION = "{arch}.selector_softcap_after_correction"
|
||||
SAMPLE_FROM_ANCHOR = "{arch}.sample_from_anchor"
|
||||
HAS_CONFIDENCE_HEAD = "{arch}.has_confidence_head"
|
||||
HAS_MARKOV_CONTEXT = "{arch}.has_markov_context"
|
||||
|
||||
@@ -1107,6 +1107,9 @@ class GGUFWriter:
|
||||
def add_selector_top_k(self, value: int) -> None:
|
||||
self.add_uint32(Keys.LLM.SELECTOR_TOP_K.format(arch=self.arch), value)
|
||||
|
||||
def add_selector_softcap_after_correction(self, value: bool) -> None:
|
||||
self.add_bool(Keys.LLM.SELECTOR_SOFTCAP_AFTER_CORRECTION.format(arch=self.arch), value)
|
||||
|
||||
def add_sample_from_anchor(self, value: bool) -> None:
|
||||
self.add_bool(Keys.LLM.SAMPLE_FROM_ANCHOR.format(arch=self.arch), value)
|
||||
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# Check HIP VGPR limits, compare kernel resource usage, and generate a report.
|
||||
# Read Clang optimization records produced with -fsave-optimization-record=yaml
|
||||
# and -Rpass-analysis=kernel-resource-usage.
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
from typing import cast
|
||||
|
||||
import yaml
|
||||
|
||||
try:
|
||||
from itanium_demangler import parse as demangle # ty: ignore[import-not-found]
|
||||
except ImportError:
|
||||
demangle = None
|
||||
|
||||
METRICS = ('occupancy', 'vgpr_spill', 'sgpr_spill')
|
||||
REPORT_METRICS = METRICS + ('vgpr_total',)
|
||||
RULES = {
|
||||
'vgpr_limit': 'blocking',
|
||||
'vgpr_spill_increase': 'blocking',
|
||||
'sgpr_spill_increase': 'blocking',
|
||||
'occupancy_vgpr_increase': 'blocking',
|
||||
'occupancy_drop': 'warning',
|
||||
}
|
||||
REMARK_NAMES = {'NumVGPR': 'vgprs', 'Occupancy': 'occupancy', 'VGPRSpill': 'vgpr_spill', 'SGPRSpill': 'sgpr_spill'}
|
||||
METRIC_NAMES = {'occupancy': 'Occupancy [waves/SIMD]', 'vgpr_spill': 'VGPRs Spill', 'sgpr_spill': 'SGPRs Spill', 'vgpr_total': 'Total VGPRs (limit 256)'}
|
||||
|
||||
IGNORED_VGPR = {
|
||||
|
||||
'_ZL13rwkv_wkv7_f32ILi128EEviiiiPKfS1_S1_S1_S1_S1_S1_Pf',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi16ELi4ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi16ELb0ELb1ELb1EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi32ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi16ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi32ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi4ELi16ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi8ELi4ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type2ELS0_2ELb0EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb0EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL21gated_linear_attn_f32ILi128EEviiiifPKfS1_S1_S1_S1_Pf',
|
||||
}
|
||||
|
||||
|
||||
class RemarkLoader(yaml.SafeLoader):
|
||||
pass
|
||||
|
||||
|
||||
def construct_remark(loader, tag, node):
|
||||
return loader.construct_mapping(node)
|
||||
|
||||
|
||||
RemarkLoader.add_multi_constructor('!', construct_remark)
|
||||
|
||||
|
||||
def format_name(name):
|
||||
if demangle is None:
|
||||
return name
|
||||
try:
|
||||
demangled = demangle(name)
|
||||
except Exception:
|
||||
return name
|
||||
return f'{name} [{demangled}]' if demangled is not None else name
|
||||
|
||||
|
||||
def parse_remarks(filepath):
|
||||
path = Path(filepath)
|
||||
files = sorted(path.rglob('*.opt.yaml')) if path.is_dir() else [path] if path.is_file() else []
|
||||
if not files:
|
||||
raise ValueError(f'No optimization records found in {filepath}')
|
||||
|
||||
functions = defaultdict(lambda: {'vgprs': [], 'occupancy': [], 'vgpr_spill': [], 'sgpr_spill': [], 'location': ''})
|
||||
for file in files:
|
||||
with file.open('r') as f:
|
||||
for remark in yaml.load_all(f, Loader=RemarkLoader):
|
||||
if not isinstance(remark, dict) or remark.get('Pass') != 'kernel-resource-usage':
|
||||
continue
|
||||
key = remark.get('Name')
|
||||
if key not in REMARK_NAMES:
|
||||
continue
|
||||
name = remark.get('Function')
|
||||
if not isinstance(name, str) or not name:
|
||||
continue
|
||||
values = [arg[key] for arg in remark.get('Args', []) if isinstance(arg, dict) and key in arg]
|
||||
if len(values) != 1:
|
||||
raise ValueError(f'Invalid {key} remark for {name} in {file}')
|
||||
try:
|
||||
value = int(values[0])
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError(f'Invalid {key} value for {name} in {file}') from exc
|
||||
cast(list[int], functions[name][REMARK_NAMES[key]]).append(value)
|
||||
location = remark.get('DebugLoc') or {}
|
||||
if location.get('File') and location.get('Line'):
|
||||
functions[name]['location'] = f"{Path(location['File']).name}:{location['Line']}"
|
||||
|
||||
if not functions:
|
||||
raise ValueError(f'No kernel resource usage remarks found in {filepath}')
|
||||
return functions
|
||||
|
||||
|
||||
def load_ignore_file(filepath):
|
||||
ignored = set()
|
||||
with open(filepath, 'r') as f:
|
||||
for line in f:
|
||||
name = line.strip()
|
||||
if name and not name.startswith('#'):
|
||||
ignored.add(name)
|
||||
return ignored
|
||||
|
||||
|
||||
def check_vgpr(functions, filepath, rows=None):
|
||||
found_issues = False
|
||||
for ignored in (True, False):
|
||||
for name, data in sorted(functions.items()):
|
||||
if (name in IGNORED_VGPR) != ignored:
|
||||
continue
|
||||
vgprs = data['vgprs'][-1] if data['vgprs'] else 0
|
||||
spill = data['vgpr_spill'][-1] if data['vgpr_spill'] else 0
|
||||
total_vgprs = vgprs + spill
|
||||
if total_vgprs <= 256:
|
||||
continue
|
||||
location = data['location'] or filepath
|
||||
suffix = ' [IGNORED]' if ignored else ' '
|
||||
message = f"{location}: {format_name(name)} - Total VGPRs: {total_vgprs} ({vgprs} + {spill}){suffix}"
|
||||
blocking = RULES['vgpr_limit'] == 'blocking'
|
||||
color = '91' if blocking else '93'
|
||||
print(message if ignored else f'\033[{color}m{message}\033[0m') # noqa: NP100
|
||||
if not ignored:
|
||||
found_issues |= blocking
|
||||
if rows is not None:
|
||||
rows.append(('vgpr_total', name, location, 256, total_vgprs, 'regression' if blocking else 'warning'))
|
||||
return int(found_issues)
|
||||
|
||||
|
||||
def worst(values, metric):
|
||||
return min(values) if metric == 'occupancy' else max(values)
|
||||
|
||||
|
||||
def compare_metric(base, pr, names, metric, tolerance=0):
|
||||
regressions = []
|
||||
gains = []
|
||||
for name in names:
|
||||
if not base[name][metric] or not pr[name][metric]:
|
||||
continue
|
||||
base_val = worst(base[name][metric], metric)
|
||||
pr_val = worst(pr[name][metric], metric)
|
||||
if metric == 'occupancy':
|
||||
if pr_val < base_val - tolerance:
|
||||
regressions.append((name, base_val, pr_val))
|
||||
elif pr_val > base_val:
|
||||
gains.append((name, base_val, pr_val))
|
||||
else:
|
||||
if pr_val > base_val:
|
||||
regressions.append((name, base_val, pr_val))
|
||||
elif pr_val < base_val:
|
||||
gains.append((name, base_val, pr_val))
|
||||
return regressions, gains
|
||||
|
||||
|
||||
def dump_tsv(path, baseline_log, pr_log, base_count, pr_count, common_count, rows):
|
||||
with open(path, 'w') as f:
|
||||
f.write(f'#baseline_log\t{baseline_log}\n')
|
||||
f.write(f'#pr_log\t{pr_log}\n')
|
||||
f.write(f'#baseline_kernels\t{base_count}\n')
|
||||
f.write(f'#pr_kernels\t{pr_count}\n')
|
||||
f.write(f'#kernels_compared\t{common_count}\n')
|
||||
f.write('metric\tkernel\tlocation\tbaseline\tpr\tstatus\n')
|
||||
for row in rows:
|
||||
f.write('\t'.join(str(col) for col in row) + '\n')
|
||||
|
||||
|
||||
def check_comparison(base, pr, baseline_log, pr_log, tolerance=0, ignored=None, dump=None):
|
||||
ignored = ignored or set()
|
||||
base_names = {name for name, data in base.items() if any(data[metric] for metric in METRICS)} - ignored
|
||||
pr_names = {name for name, data in pr.items() if any(data[metric] for metric in METRICS)} - ignored
|
||||
common = base_names & pr_names
|
||||
added = pr_names - base_names
|
||||
removed = base_names - pr_names
|
||||
locations = {name: data['location'] for name, data in base.items()}
|
||||
locations.update({name: data['location'] for name, data in pr.items()})
|
||||
|
||||
changes = {metric: compare_metric(base, pr, common, metric, tolerance) for metric in METRICS}
|
||||
issues = [] # metric, kernel, baseline, PR, severity, extra details
|
||||
for metric, rule in (('vgpr_spill', 'vgpr_spill_increase'), ('sgpr_spill', 'sgpr_spill_increase')):
|
||||
for name, base_val, pr_val in changes[metric][0]:
|
||||
issues.append((metric, name, base_val, pr_val, RULES[rule], ''))
|
||||
for name, base_val, pr_val in changes['occupancy'][0]:
|
||||
base_vgprs = worst(base[name]['vgprs'], 'vgprs') if base[name]['vgprs'] else None
|
||||
pr_vgprs = worst(pr[name]['vgprs'], 'vgprs') if pr[name]['vgprs'] else None
|
||||
increasing = base_vgprs is not None and pr_vgprs is not None and pr_vgprs > base_vgprs
|
||||
rule = 'occupancy_vgpr_increase' if increasing else 'occupancy_drop'
|
||||
detail = f', VGPRs: {base_vgprs} -> {pr_vgprs}' if increasing else ''
|
||||
issues.append(('occupancy', name, base_val, pr_val, RULES[rule], detail))
|
||||
|
||||
print(f'Kernels compared: {len(common)} (baseline {len(base_names)}, PR {len(pr_names)})') # noqa: NP100
|
||||
print(f'Added kernels: {len(added)}, removed kernels: {len(removed)}') # noqa: NP100
|
||||
for severity, color, label in (('blocking', '91', 'REGRESSION'), ('warning', '93', 'WARNING')):
|
||||
for metric, name, base_val, pr_val, level, detail in sorted(issues):
|
||||
if level == severity:
|
||||
print(f"\033[{color}m{locations[name]}: {name} - {METRIC_NAMES[metric]}: {base_val} -> {pr_val}{detail} ({label})\033[0m") # noqa: NP100
|
||||
for metric in METRICS:
|
||||
for name, base_val, pr_val in sorted(changes[metric][1]):
|
||||
print(f"\033[92m{locations[name]}: {name} - {METRIC_NAMES[metric]}: {base_val} -> {pr_val} (improved)\033[0m") # noqa: NP100
|
||||
for name in sorted(added):
|
||||
print(f'note: new kernel in PR: {name}') # noqa: NP100
|
||||
for name in sorted(removed):
|
||||
print(f'note: kernel only in baseline: {name}') # noqa: NP100
|
||||
|
||||
# Check the absolute VGPR limit as well, even for kernels excluded from comparisons.
|
||||
vgpr_rows = []
|
||||
vgpr_failed = check_vgpr(pr, pr_log, vgpr_rows)
|
||||
if dump:
|
||||
rows = []
|
||||
for metric, name, base_val, pr_val, severity, _ in issues:
|
||||
rows.append((metric, name, locations[name], base_val, pr_val, 'regression' if severity == 'blocking' else 'warning'))
|
||||
for metric in METRICS:
|
||||
for name, base_val, pr_val in sorted(changes[metric][1]):
|
||||
rows.append((metric, name, locations[name], base_val, pr_val, 'improved'))
|
||||
rows.extend(vgpr_rows)
|
||||
for name in sorted(added):
|
||||
for metric in METRICS:
|
||||
if pr[name][metric]:
|
||||
rows.append((metric, name, locations[name], '', worst(pr[name][metric], metric), 'added'))
|
||||
for name in sorted(removed):
|
||||
for metric in METRICS:
|
||||
if base[name][metric]:
|
||||
rows.append((metric, name, locations[name], worst(base[name][metric], metric), '', 'removed'))
|
||||
dump_tsv(dump, baseline_log, pr_log, len(base_names), len(pr_names), len(common), rows)
|
||||
print(f'Deltas written to {dump}') # noqa: NP100
|
||||
|
||||
blocking = sum(severity == 'blocking' for _, _, _, _, severity, _ in issues)
|
||||
warnings = sum(severity == 'warning' for _, _, _, _, severity, _ in issues)
|
||||
blocking += sum(row[5] == 'regression' for row in vgpr_rows)
|
||||
warnings += sum(row[5] == 'warning' for row in vgpr_rows)
|
||||
if blocking or warnings:
|
||||
print(f'{blocking} blocking regression(s), {warnings} warning(s)') # noqa: NP100
|
||||
else:
|
||||
print('No regressions found') # noqa: NP100
|
||||
return int(bool(blocking or vgpr_failed))
|
||||
|
||||
|
||||
def read_deltas(filepath):
|
||||
meta = {}
|
||||
rows = []
|
||||
try:
|
||||
with open(filepath, 'r') as f:
|
||||
for line in f:
|
||||
line = line.rstrip('\n')
|
||||
if line.startswith('#'):
|
||||
parts = line[1:].split('\t')
|
||||
if len(parts) == 2:
|
||||
meta[parts[0].strip()] = parts[1].strip()
|
||||
continue
|
||||
cols = line.split('\t')
|
||||
if len(cols) == 6 and cols[0] in REPORT_METRICS:
|
||||
rows.append(cols)
|
||||
except FileNotFoundError:
|
||||
print(f"Error: File {filepath} not found", file=sys.stderr) # noqa: NP100
|
||||
sys.exit(1)
|
||||
return meta, rows
|
||||
|
||||
|
||||
def write_report(path, meta, rows):
|
||||
tables = {} # (metric, status) -> list of (kernel, location, baseline, pr)
|
||||
added = {} # kernel -> [location, {metric: value}]
|
||||
removed = {} # kernel -> [location, {metric: value}]
|
||||
for metric, kernel, location, baseline, pr, status in rows:
|
||||
if status in ('regression', 'warning', 'improved'):
|
||||
tables.setdefault((metric, status), []).append((kernel, location, baseline, pr))
|
||||
elif status == 'added':
|
||||
added.setdefault(kernel, [location, {}])[1][metric] = pr
|
||||
elif status == 'removed':
|
||||
removed.setdefault(kernel, [location, {}])[1][metric] = baseline
|
||||
|
||||
with open(path, 'w') as f:
|
||||
f.write('# HIP kernel metrics comparison\n\n')
|
||||
f.write(f"- Baseline: `{meta.get('baseline_log', '?')}`\n")
|
||||
f.write(f"- PR: `{meta.get('pr_log', '?')}`\n\n")
|
||||
f.write(f"Kernels compared: {meta.get('kernels_compared', '?')} "
|
||||
f"(baseline {meta.get('baseline_kernels', '?')}, PR {meta.get('pr_kernels', '?')}). "
|
||||
f"Added kernels: {len(added)}, removed kernels: {len(removed)}.\n\n")
|
||||
|
||||
for metric in REPORT_METRICS:
|
||||
name = METRIC_NAMES[metric]
|
||||
statuses = (('regression', 'regressions'), ('improved', 'improvements'))
|
||||
if metric == 'occupancy':
|
||||
statuses = (('regression', 'regressions'), ('warning', 'warnings'), ('improved', 'improvements'))
|
||||
elif metric == 'vgpr_total':
|
||||
statuses = (('regression', 'regressions'), ('warning', 'warnings'))
|
||||
if metric == 'vgpr_total':
|
||||
f.write('The baseline value for total VGPRs is the 256-register threshold.\n\n')
|
||||
for status, title in statuses:
|
||||
entries = tables.get((metric, status), [])
|
||||
f.write(f'## {name} {title} ({len(entries)})\n\n')
|
||||
if entries:
|
||||
f.write('| Location | Kernel | Baseline | PR |\n|---|---|---|---|\n')
|
||||
for kernel, location, baseline, pr in entries:
|
||||
f.write(f'| {location} | `{kernel}` | {baseline} | {pr} |\n')
|
||||
else:
|
||||
f.write('None.\n')
|
||||
f.write('\n')
|
||||
|
||||
for title, kernels in (('Added kernels', added), ('Removed kernels', removed)):
|
||||
f.write(f'## {title} ({len(kernels)})\n\n')
|
||||
if kernels:
|
||||
f.write('| Location | Kernel | Occupancy | VGPRs Spill | SGPRs Spill |\n|---|---|---|---|---|\n')
|
||||
for kernel in sorted(kernels):
|
||||
location, values = kernels[kernel]
|
||||
occupancy = values.get('occupancy', '')
|
||||
vspill = values.get('vgpr_spill', '')
|
||||
sspill = values.get('sgpr_spill', '')
|
||||
f.write(f'| {location} | `{kernel}` | {occupancy} | {vspill} | {sspill} |\n')
|
||||
else:
|
||||
f.write('None.\n')
|
||||
f.write('\n')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Check HIP kernel resource usage and generate reports')
|
||||
commands = parser.add_subparsers(dest='command', required=True)
|
||||
vgpr = commands.add_parser('vgpr', help='check the 256 VGPR limit')
|
||||
vgpr.add_argument('records', help='directory of Clang .opt.yaml files')
|
||||
compare = commands.add_parser('compare', help='compare occupancy and register spills')
|
||||
compare.add_argument('baseline_log', help='baseline optimization records')
|
||||
compare.add_argument('pr_log', help='PR optimization records')
|
||||
compare.add_argument('-t', '--tolerance', type=int, default=0, help='allowed occupancy drop in waves/SIMD')
|
||||
compare.add_argument('--ignore', help='file with kernel symbols to exclude, one per line')
|
||||
compare.add_argument('--dump', help='write all deltas to a TSV file')
|
||||
report = commands.add_parser('report', help='generate the Markdown report from a TSV dump')
|
||||
report.add_argument('deltas_tsv', help='TSV deltas from compare --dump')
|
||||
report.add_argument('-o', '--output', default='hip-kernel-metrics-report.md', help='output Markdown file')
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
if args.command == 'vgpr':
|
||||
return check_vgpr(parse_remarks(args.records), args.records)
|
||||
if args.command == 'compare':
|
||||
ignored = load_ignore_file(args.ignore) if args.ignore else set()
|
||||
return check_comparison(parse_remarks(args.baseline_log), parse_remarks(args.pr_log), args.baseline_log, args.pr_log, args.tolerance, ignored, args.dump)
|
||||
meta, rows = read_deltas(args.deltas_tsv)
|
||||
write_report(args.output, meta, rows)
|
||||
print(f'Report written to {args.output}') # noqa: NP100
|
||||
return 0
|
||||
except (OSError, ValueError, yaml.YAMLError) as exc:
|
||||
print(f'Error: {exc}', file=sys.stderr) # noqa: NP100
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -1,132 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
import re
|
||||
|
||||
try:
|
||||
from itanium_demangler import parse as demangle # ty: ignore[import-not-found]
|
||||
except ImportError:
|
||||
demangle = None
|
||||
|
||||
|
||||
def format_name(name):
|
||||
if demangle is None:
|
||||
return name
|
||||
try:
|
||||
demangled = demangle(name)
|
||||
except Exception:
|
||||
return name
|
||||
return f"{name} [{demangled}]" if demangled is not None else name
|
||||
|
||||
|
||||
def parse_log_file(filepath):
|
||||
functions = defaultdict(lambda: {'vgprs': 0, 'spill': 0, 'location': ''})
|
||||
func_stack = []
|
||||
|
||||
try:
|
||||
with open(filepath, 'r') as f:
|
||||
for line in f:
|
||||
# Match function name lines
|
||||
func_match = re.search(r'remark: ([^:]+):(\d+):\d+: Function Name: (\S+)', line)
|
||||
if func_match:
|
||||
location = func_match.group(1) + ':' + func_match.group(2)
|
||||
func_name = func_match.group(3)
|
||||
# Extract just the filename and line number
|
||||
parts = location.split('/')
|
||||
short_location = parts[-1] if len(parts) > 0 else location
|
||||
functions[func_name]['location'] = short_location
|
||||
# Push function onto stack with its location
|
||||
func_stack.append({'name': func_name, 'location': location})
|
||||
continue
|
||||
|
||||
# Match VGPR usage lines (only if we have functions in stack)
|
||||
vgpr_match = re.search(r'remark: ([^:]+):(\d+):\d+:\s+VGPRs: (\d+)', line)
|
||||
if vgpr_match:
|
||||
location = vgpr_match.group(1) + ':' + vgpr_match.group(2)
|
||||
# Find the most recent function with matching location
|
||||
for i in range(len(func_stack) - 1, -1, -1):
|
||||
if func_stack[i]['location'] == location:
|
||||
functions[func_stack[i]['name']]['vgprs'] = int(vgpr_match.group(3))
|
||||
break
|
||||
continue
|
||||
|
||||
spill_match = re.search(r'remark: ([^:]+):(\d+):\d+:\s+VGPRs Spill: (\d+)', line)
|
||||
if spill_match:
|
||||
location = spill_match.group(1) + ':' + spill_match.group(2)
|
||||
# Find the most recent function with matching location
|
||||
for i in range(len(func_stack) - 1, -1, -1):
|
||||
if func_stack[i]['location'] == location:
|
||||
functions[func_stack[i]['name']]['spill'] = int(spill_match.group(3))
|
||||
break
|
||||
continue
|
||||
except FileNotFoundError:
|
||||
print(f"Error: File {filepath} not found", file=sys.stderr) # noqa: NP100
|
||||
sys.exit(1)
|
||||
|
||||
return functions
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print("Usage: ./vgpr_check.py <log_file>", file=sys.stderr) # noqa: NP100
|
||||
sys.exit(1)
|
||||
|
||||
log_file = sys.argv[1]
|
||||
ignored = {
|
||||
'_ZL13rwkv_wkv7_f32ILi128EEviiiiPKfS1_S1_S1_S1_S1_S1_Pf',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi16ELi4ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi16ELb0ELb1ELb1EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi32ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi16ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi32ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi4ELi16ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi8ELi4ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type2ELS0_2ELb0EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb0EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill',
|
||||
'_ZL21gated_linear_attn_f32ILi128EEviiiifPKfS1_S1_S1_S1_Pf',
|
||||
}
|
||||
|
||||
functions = parse_log_file(log_file)
|
||||
found_issues = False
|
||||
|
||||
# First print all ignored functions (deduplicated)
|
||||
printed_ignored = set()
|
||||
for func_name, data in sorted(functions.items()):
|
||||
total_vgprs = int(data['vgprs']) + int(data['spill'])
|
||||
if total_vgprs > 256 and func_name in ignored and func_name not in printed_ignored:
|
||||
location = data.get('location', log_file)
|
||||
print(f"{location}: {format_name(func_name)} - Total VGPRs: {total_vgprs} ({data['vgprs']} + {data['spill']}) [IGNORED]") # noqa: NP100
|
||||
printed_ignored.add(func_name)
|
||||
|
||||
# Then print new functions with issues in red
|
||||
for func_name, data in sorted(functions.items()):
|
||||
total_vgprs = int(data['vgprs']) + int(data['spill'])
|
||||
if total_vgprs > 256 and func_name not in ignored:
|
||||
status = "[IGNORED]" if func_name in ignored else ""
|
||||
location = data.get('location', log_file)
|
||||
# Print in red if not ignored
|
||||
color_code = "\033[91m" if func_name not in ignored else ""
|
||||
reset_code = "\033[0m" if func_name not in ignored else ""
|
||||
print(f"{color_code}{location}: {format_name(func_name)} - Total VGPRs: {total_vgprs} ({data['vgprs']} + {data['spill']}) {status}{reset_code}") # noqa: NP100
|
||||
if func_name not in ignored:
|
||||
found_issues = True
|
||||
|
||||
sys.exit(1 if found_issues else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,253 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import importlib.util
|
||||
import io
|
||||
import tempfile
|
||||
import unittest
|
||||
from contextlib import redirect_stdout
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import yaml
|
||||
|
||||
SCRIPT = Path(__file__).with_name('gcn-cdna-metrics.py')
|
||||
spec = importlib.util.spec_from_file_location('gcn_cdna_metrics', SCRIPT)
|
||||
if spec is None or spec.loader is None:
|
||||
raise RuntimeError(f'Cannot load {SCRIPT}')
|
||||
metrics = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(metrics)
|
||||
|
||||
|
||||
def write_records(directory, filename, kernels):
|
||||
path = directory / filename
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with path.open('w') as f:
|
||||
for name, values in kernels.items():
|
||||
for key, value in values.items():
|
||||
f.write('--- !Analysis\n')
|
||||
yaml.safe_dump({'Pass': 'kernel-resource-usage', 'Name': key, 'Function': name,
|
||||
'DebugLoc': {'File': 'wkv.cu', 'Line': 69, 'Column': 1},
|
||||
'Args': [{'String': key + ': '}, {key: str(value)}]}, f, sort_keys=False)
|
||||
f.write('...\n')
|
||||
return path
|
||||
|
||||
|
||||
class MetricsTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.root = Path(self.tmp.name)
|
||||
self.base = self.root / 'baseline'
|
||||
self.pr = self.root / 'pr'
|
||||
self.base.mkdir()
|
||||
self.pr.mkdir()
|
||||
|
||||
def compare(self, **kwargs):
|
||||
with redirect_stdout(io.StringIO()) as out:
|
||||
result = metrics.check_comparison(metrics.parse_remarks(self.base), metrics.parse_remarks(self.pr),
|
||||
'baseline', 'PR', **kwargs)
|
||||
return result, out.getvalue()
|
||||
|
||||
def test_same_source_location_does_not_swap_kernel_specializations(self):
|
||||
write_records(self.pr, 'kernels.opt.yaml', {'_Zkernel64': {'NumVGPR': 64, 'VGPRSpill': 360},
|
||||
'_Zkernel128': {'NumVGPR': 64, 'VGPRSpill': 0}})
|
||||
data = metrics.parse_remarks(self.pr)
|
||||
self.assertEqual(data['_Zkernel64']['vgpr_spill'], [360])
|
||||
self.assertEqual(data['_Zkernel128']['vgpr_spill'], [0])
|
||||
self.assertEqual(data['_Zkernel64']['location'], 'wkv.cu:69')
|
||||
|
||||
def test_vgpr_limit_and_allowlist(self):
|
||||
write_records(self.pr, 'kernels.opt.yaml', {'bad': {'NumVGPR': 255, 'VGPRSpill': 2},
|
||||
'allowed': {'NumVGPR': 256, 'VGPRSpill': 4},
|
||||
'good': {'NumVGPR': 256, 'VGPRSpill': 0}})
|
||||
metrics.IGNORED_VGPR.add('allowed')
|
||||
self.addCleanup(metrics.IGNORED_VGPR.discard, 'allowed')
|
||||
with redirect_stdout(io.StringIO()) as out:
|
||||
code = metrics.check_vgpr(metrics.parse_remarks(self.pr), 'PR')
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn('allowed - Total VGPRs: 260 (256 + 4) [IGNORED]', out.getvalue())
|
||||
self.assertIn('bad - Total VGPRs: 257 (255 + 2)', out.getvalue())
|
||||
self.assertNotIn('good - Total VGPRs', out.getvalue())
|
||||
|
||||
def test_occupancy_spill_regressions_and_tolerance(self):
|
||||
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5, 'VGPRSpill': 0, 'SGPRSpill': 1}})
|
||||
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'VGPRSpill': 1, 'SGPRSpill': 0}})
|
||||
code, output = self.compare()
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn('Occupancy [waves/SIMD]: 5 -> 4 (WARNING)', output)
|
||||
self.assertIn('VGPRs Spill: 0 -> 1 (REGRESSION)', output)
|
||||
self.assertIn('SGPRs Spill: 1 -> 0 (improved)', output)
|
||||
code, output = self.compare(tolerance=1)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertNotIn('Occupancy [waves/SIMD]: 5 -> 4 (WARNING)', output)
|
||||
|
||||
def test_duplicate_kernel_uses_worst_per_metric(self):
|
||||
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 6, 'VGPRSpill': 0}})
|
||||
write_records(self.base, 'sub/b.opt.yaml', {'same': {'Occupancy': 5, 'VGPRSpill': 2}})
|
||||
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 6, 'VGPRSpill': 1}})
|
||||
code, output = self.compare()
|
||||
self.assertEqual(code, 0)
|
||||
self.assertIn('VGPRs Spill: 2 -> 1 (improved)', output)
|
||||
self.assertIn('Occupancy [waves/SIMD]: 5 -> 6 (improved)', output)
|
||||
|
||||
def test_added_removed_deltas_and_markdown(self):
|
||||
write_records(self.base, 'a.opt.yaml', {'removed': {'Occupancy': 5, 'VGPRSpill': 2}, 'same': {'Occupancy': 4}})
|
||||
write_records(self.pr, 'a.opt.yaml', {'added': {'Occupancy': 6, 'SGPRSpill': 1}, 'same': {'Occupancy': 5}})
|
||||
tsv = self.root / 'diff.tsv'
|
||||
report = self.root / 'report.md'
|
||||
code, _ = self.compare(dump=tsv)
|
||||
self.assertEqual(code, 0)
|
||||
self.assertIn('occupancy\tadded\twkv.cu:69\t\t6\tadded', tsv.read_text())
|
||||
meta, rows = metrics.read_deltas(tsv)
|
||||
metrics.write_report(report, meta, rows)
|
||||
result = report.read_text()
|
||||
self.assertIn('# HIP kernel metrics comparison', result)
|
||||
self.assertIn('## Occupancy [waves/SIMD] improvements (1)', result)
|
||||
self.assertIn('## Added kernels (1)', result)
|
||||
self.assertIn('## Removed kernels (1)', result)
|
||||
self.assertIn('| wkv.cu:69 | ' + chr(96) + 'same' + chr(96) + ' | 4 | 5 |', result)
|
||||
|
||||
def test_ignore_only_comparison_not_vgpr(self):
|
||||
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5}})
|
||||
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 1}})
|
||||
code, output = self.compare(ignored={'same'})
|
||||
self.assertEqual(code, 0)
|
||||
self.assertIn('Kernels compared: 0', output)
|
||||
|
||||
def test_vgpr_only_records_are_not_compared(self):
|
||||
write_records(self.base, 'a.opt.yaml', {'vgpr_only': {'NumVGPR': 64}, 'same': {'Occupancy': 4}})
|
||||
write_records(self.pr, 'a.opt.yaml', {'vgpr_only': {'NumVGPR': 128}, 'same': {'Occupancy': 4}})
|
||||
code, output = self.compare()
|
||||
self.assertEqual(code, 0)
|
||||
self.assertIn('Kernels compared: 1 (baseline 1, PR 1)', output)
|
||||
|
||||
def test_occupancy_drop_with_more_vgprs_blocks(self):
|
||||
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5, 'NumVGPR': 64}})
|
||||
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'NumVGPR': 96}})
|
||||
tsv = self.root / 'diff.tsv'
|
||||
code, output = self.compare(dump=tsv)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn('Occupancy [waves/SIMD]: 5 -> 4, VGPRs: 64 -> 96 (REGRESSION)', output)
|
||||
self.assertIn('1 blocking regression(s), 0 warning(s)', output)
|
||||
self.assertIn('occupancy\tsame\twkv.cu:69\t5\t4\tregression', tsv.read_text())
|
||||
|
||||
def test_occupancy_drop_with_fewer_vgprs_warns(self):
|
||||
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5, 'NumVGPR': 96}})
|
||||
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'NumVGPR': 64}})
|
||||
tsv = self.root / 'diff.tsv'
|
||||
report = self.root / 'report.md'
|
||||
code, output = self.compare(dump=tsv)
|
||||
self.assertEqual(code, 0)
|
||||
self.assertIn('Occupancy [waves/SIMD]: 5 -> 4 (WARNING)', output)
|
||||
self.assertIn('0 blocking regression(s), 1 warning(s)', output)
|
||||
self.assertIn('occupancy\tsame\twkv.cu:69\t5\t4\twarning', tsv.read_text())
|
||||
meta, rows = metrics.read_deltas(tsv)
|
||||
metrics.write_report(report, meta, rows)
|
||||
self.assertIn('## Occupancy [waves/SIMD] warnings (1)', report.read_text())
|
||||
self.assertIn('| wkv.cu:69 | `same` | 5 | 4 |', report.read_text())
|
||||
|
||||
def test_occupancy_drop_without_vgpr_increase_warns(self):
|
||||
write_records(self.base, 'a.opt.yaml', {'unchanged': {'Occupancy': 5, 'NumVGPR': 64},
|
||||
'missing': {'Occupancy': 5}})
|
||||
write_records(self.pr, 'a.opt.yaml', {'unchanged': {'Occupancy': 4, 'NumVGPR': 64},
|
||||
'missing': {'Occupancy': 4}})
|
||||
code, output = self.compare()
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(output.count('(WARNING)'), 2)
|
||||
self.assertIn('0 blocking regression(s), 2 warning(s)', output)
|
||||
|
||||
def test_vgpr_and_sgpr_spill_increases_block_independently(self):
|
||||
write_records(self.base, 'a.opt.yaml', {'vgpr': {'VGPRSpill': 0}, 'sgpr': {'SGPRSpill': 0}})
|
||||
write_records(self.pr, 'a.opt.yaml', {'vgpr': {'VGPRSpill': 1}, 'sgpr': {'SGPRSpill': 1}})
|
||||
code, output = self.compare()
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn('vgpr - VGPRs Spill: 0 -> 1 (REGRESSION)', output)
|
||||
self.assertIn('sgpr - SGPRs Spill: 0 -> 1 (REGRESSION)', output)
|
||||
self.assertIn('2 blocking regression(s), 0 warning(s)', output)
|
||||
|
||||
def test_vgpr_limit_blocks_comparison_and_appears_in_report(self):
|
||||
write_records(self.base, 'a.opt.yaml', {'same': {'NumVGPR': 256, 'VGPRSpill': 0}})
|
||||
write_records(self.pr, 'a.opt.yaml', {'same': {'NumVGPR': 256, 'VGPRSpill': 1}})
|
||||
tsv = self.root / 'diff.tsv'
|
||||
report = self.root / 'report.md'
|
||||
code, output = self.compare(dump=tsv)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn('Total VGPRs: 257 (256 + 1)', output)
|
||||
self.assertIn('2 blocking regression(s), 0 warning(s)', output)
|
||||
self.assertIn('vgpr_total\tsame\twkv.cu:69\t256\t257\tregression', tsv.read_text())
|
||||
meta, rows = metrics.read_deltas(tsv)
|
||||
metrics.write_report(report, meta, rows)
|
||||
self.assertIn('## Total VGPRs (limit 256) regressions (1)', report.read_text())
|
||||
self.assertIn('| wkv.cu:69 | `same` | 256 | 257 |', report.read_text())
|
||||
|
||||
def test_existing_vgpr_allowlist_preserves_comparison_checks(self):
|
||||
write_records(self.base, 'a.opt.yaml', {'allowed': {'NumVGPR': 255, 'VGPRSpill': 3}})
|
||||
write_records(self.pr, 'a.opt.yaml', {'allowed': {'NumVGPR': 255, 'VGPRSpill': 4}})
|
||||
metrics.IGNORED_VGPR.add('allowed')
|
||||
self.addCleanup(metrics.IGNORED_VGPR.discard, 'allowed')
|
||||
code, output = self.compare()
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn('Total VGPRs: 259 (255 + 4) [IGNORED]', output)
|
||||
self.assertIn('VGPRs Spill: 3 -> 4 (REGRESSION)', output)
|
||||
self.assertIn('1 blocking regression(s), 0 warning(s)', output)
|
||||
|
||||
def test_comparison_ignore_does_not_disable_vgpr_limit(self):
|
||||
write_records(self.base, 'a.opt.yaml', {'ignored': {'NumVGPR': 256, 'VGPRSpill': 0}})
|
||||
write_records(self.pr, 'a.opt.yaml', {'ignored': {'NumVGPR': 256, 'VGPRSpill': 1}})
|
||||
code, output = self.compare(ignored={'ignored'})
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn('Kernels compared: 0 (baseline 0, PR 0)', output)
|
||||
self.assertIn('Total VGPRs: 257 (256 + 1)', output)
|
||||
|
||||
def test_occupancy_tolerance_applies_to_blocking_rule(self):
|
||||
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5, 'NumVGPR': 64}})
|
||||
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'NumVGPR': 96}})
|
||||
code, output = self.compare(tolerance=1)
|
||||
self.assertEqual(code, 0)
|
||||
self.assertNotIn('Occupancy [waves/SIMD]: 5 -> 4', output)
|
||||
self.assertIn('No regressions found', output)
|
||||
|
||||
def test_all_rules_complete_and_return_error_after_dump(self):
|
||||
write_records(self.base, 'a.opt.yaml', {'occb': {'Occupancy': 5, 'NumVGPR': 64},
|
||||
'occw': {'Occupancy': 5, 'NumVGPR': 80},
|
||||
'spill': {'SGPRSpill': 0}})
|
||||
write_records(self.pr, 'a.opt.yaml', {'occb': {'Occupancy': 4, 'NumVGPR': 96},
|
||||
'occw': {'Occupancy': 4, 'NumVGPR': 64},
|
||||
'spill': {'SGPRSpill': 1}})
|
||||
tsv = self.root / 'diff.tsv'
|
||||
code, output = self.compare(dump=tsv)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn('occb - Occupancy [waves/SIMD]: 5 -> 4, VGPRs: 64 -> 96 (REGRESSION)', output)
|
||||
self.assertIn('occw - Occupancy [waves/SIMD]: 5 -> 4 (WARNING)', output)
|
||||
self.assertIn('spill - SGPRs Spill: 0 -> 1 (REGRESSION)', output)
|
||||
self.assertIn('2 blocking regression(s), 1 warning(s)', output)
|
||||
self.assertTrue(tsv.is_file())
|
||||
|
||||
def test_cli_returns_success_for_warnings_and_generates_report_after_failure(self):
|
||||
write_records(self.base, 'a.opt.yaml', {'same': {'Occupancy': 5, 'NumVGPR': 96}})
|
||||
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'NumVGPR': 64}})
|
||||
tsv = self.root / 'diff.tsv'
|
||||
report = self.root / 'report.md'
|
||||
argv = ['gcn-cdna-metrics.py', 'compare', str(self.base), str(self.pr), '--dump', str(tsv)]
|
||||
with patch('sys.argv', argv), redirect_stdout(io.StringIO()):
|
||||
self.assertEqual(metrics.main(), 0)
|
||||
self.assertIn('warning', tsv.read_text())
|
||||
|
||||
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 4, 'NumVGPR': 128}})
|
||||
with patch('sys.argv', argv), redirect_stdout(io.StringIO()):
|
||||
self.assertEqual(metrics.main(), 1)
|
||||
self.assertIn('regression', tsv.read_text())
|
||||
with patch('sys.argv', ['gcn-cdna-metrics.py', 'report', str(tsv), '-o', str(report)]), redirect_stdout(io.StringIO()):
|
||||
self.assertEqual(metrics.main(), 0)
|
||||
self.assertIn('## Occupancy [waves/SIMD] regressions (1)', report.read_text())
|
||||
|
||||
def test_missing_or_invalid_records_fail(self):
|
||||
with self.assertRaisesRegex(ValueError, 'No optimization records'):
|
||||
metrics.parse_remarks(self.pr)
|
||||
write_records(self.pr, 'a.opt.yaml', {'same': {'Occupancy': 'invalid'}})
|
||||
with self.assertRaisesRegex(ValueError, 'Invalid Occupancy value'):
|
||||
metrics.parse_remarks(self.pr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,232 @@
|
||||
---
|
||||
name: ui-demo
|
||||
description: Demo, test and document a change in Llama Chat (ui/apps/chat) or Llama UI (ui/lib/ui) with the Playwright demo harness - record a video for the PR, turn the same flow into an e2e check, and capture docs videos and screenshots. Use when a UI change needs a demo video, a Playwright check, or docs media.
|
||||
---
|
||||
|
||||
# Demo, test and document a UI change
|
||||
|
||||
One scripted flow serves three ends: a **demo** video in the PR, a Playwright **check** in `tests/e2e`, and **docs** media. The harness is `ui/lib/demo/`, and Llama Chat's fixtures for it are in `ui/apps/chat/demo/` (read both `README.md` files once). Everything below runs from `ui/apps/chat`.
|
||||
|
||||
Use it when a change in `ui/apps/chat` or `ui/lib/ui` is visible: a new or changed screen, flow or component. Skip it for refactors with no visible effect.
|
||||
|
||||
AGENTS.md still applies: the contributor writes the PR description and owns the script. `demo:pr` only fills the managed `## Demo` section.
|
||||
|
||||
## Pick the target
|
||||
|
||||
| Change in | Record | How |
|
||||
| --------------------------------- | ---------------------- | --------------------------------------------- |
|
||||
| Llama Chat flow or screen | the app, on vite dev | default |
|
||||
| Llama UI component (`ui/lib/ui`) | its Storybook story | `test.use({ story })` + `DEMO_STORYBOOK=ui` |
|
||||
| Llama Chat component in isolation | Chat's Storybook story | `test.use({ story })` + `DEMO_STORYBOOK=chat` |
|
||||
|
||||
A Storybook story is the harness page for a component: if none shows the state you need, add a story next to the others (`tests/stories/` in that package) rather than a new page.
|
||||
|
||||
## Setup (once)
|
||||
|
||||
```bash
|
||||
cd ui/apps/chat && npm ci
|
||||
```
|
||||
|
||||
```bash
|
||||
npx playwright install chromium
|
||||
```
|
||||
|
||||
Also `ffmpeg`, and `npm ci` in `ui/lib/ui` for Llama UI stories. `demo:pr` needs `gh` (edit rights on the PR) and, to link the video, an `hf` login plus `DEMO_STORAGE` and `DEMO_STORAGE_PUBLIC_URL` in `ui/apps/chat/.env` (see `.env.example`).
|
||||
|
||||
## 1. Demo
|
||||
|
||||
### Write the script
|
||||
|
||||
Scripts get `test` and `expect` from `helpers.ts`. Drive the page with `demo.*` (visible cursor, human timing), assert with `expect`, set the scene with `test.use`:
|
||||
|
||||
- `demo.click`, `demo.hover`, `demo.type`, `demo.press`, `demo.scroll`, `demo.pause`, `demo.caption(text, ms)` (a chip under the window), `demo.zoom(target, scale, ms)` (the camera moves onto a small detail and back), `demo.zoomIn(target, scale)` ... `demo.zoomOut()` (the camera stays on it across the actions between).
|
||||
- `test.use({ settings: {...} })` seeds UI settings, `startPath: '/#/...'` starts on a route.
|
||||
- Fixtures, so no real data or third-party server is needed:
|
||||
- **MCP servers:** two fixture servers (Weather, Notes) are always configured; see `demo/fixtures/demo-config.ts`.
|
||||
- **Conversations:** `traces: ['long-chat', 'agentic-debugging']` imports built-in chats (`demo/fixtures/traces.ts`); other names come from `DEMO_TRACES_DATASET`.
|
||||
- **Models and replies:** `mockServer: { models: ['org/Model-GGUF:Q4_K_M'], reply: 'Markdown **reply**' }` answers llama-server's endpoints in the browser (`demo/fixtures/llama-server.ts`): the model list, props, load, tools and a streamed reply. Nothing reaches a server and no model loads. Use it for any demo that sends a message.
|
||||
- **Stories:** `story: 'ui-forms-switch--default'`, the id from the Storybook URL (`?path=/story/<id>`).
|
||||
|
||||
Without `mockServer` the app talks to the llama-server at `DEMO_SERVER_ORIGIN` (default `:9931`, started from `build/bin/llama-server` when none runs). Sending a message there loads a model: do not do that on someone's running server without asking.
|
||||
|
||||
### Shape the video
|
||||
|
||||
The video is rendered from the recording, not the raw screencast: the app in a window on a Llama brand ground, camera moves over the whole stage with motion blur, captions under the window, and on a touch viewport taps in place of the cursor (see "The render" in the harness README). Write for that:
|
||||
|
||||
- **One thing per video.** A PR that changes several things gets several short `test()`s, not one long walk.
|
||||
- **Captions** are in the brand's voice: plain words, real numbers, no emoji, one line. `demo.caption(text, ms)` holds the caption for `ms` and the demo waits, so show it while the screen is still (before or after an action, not over one). A demo with no captions gets no caption row, and the window is larger.
|
||||
- **Zooms** are for a detail too small to read in the frame. The camera aims where the target is when the zoom starts and does not follow it, so zoom after the layout settles (wait with `expect` first), and zoom out before an action that moves the target, such as sending a message. Zoom on desktop demos; a phone's UI already fills a portrait video, so leave phone demos unzoomed unless a detail is too small to read even there.
|
||||
- **Phones:** `test.use({ hasTouch: true, isMobile: true, viewport: { height: 844, width: 390 } })` gives a 1080x1920 video with a phone's corners, and every click shows as a fingertip tap.
|
||||
- **Dark mode:** `test.use({ colorScheme: 'dark' })` records the dark theme on the night sky.
|
||||
- **Timing:** the harness adds the render's time to the test's timeout after the demo, so a demo needs no long `test.setTimeout`.
|
||||
|
||||
`DEMO_POLISH_LOGO=end` adds a Llama logo card, for a video that goes out on its own; `DEMO_POLISH=0` gives the plain screencast.
|
||||
|
||||
### Try it locally
|
||||
|
||||
Save it as `demo/<name>.demo.ts` (git-ignored), importing from `./helpers.ts`, and run:
|
||||
|
||||
```bash
|
||||
npm run demo:record -- demo/<name>
|
||||
```
|
||||
|
||||
Add `DEMO_STORYBOOK=ui` (or `chat`) when the script has a `story`. `DEMO_POLISH=0` records faster while iterating (the render takes a few times the video's length). The mp4 lands in `demo/videos/`. Look at it before going further: a sheet of frames shows the whole flow, the camera moves and the captions at once, where one still frame misses most of it:
|
||||
|
||||
```bash
|
||||
ffmpeg -loglevel error -i demo/videos/<name>.mp4 -vf "fps=2,scale=480:-1,tile=6x4" -frames:v 1 demo/videos/<name>-sheet.png
|
||||
```
|
||||
|
||||
Check that each caption is readable and on screen long enough, that every zoom lands on its detail, and that nothing is cut off at the window's edge.
|
||||
|
||||
`npm run demo:codegen` opens Playwright codegen on `:5180` for a first draft of the selectors.
|
||||
|
||||
### Put it in the PR
|
||||
|
||||
Paste the script into the PR description as a `ts demo` block, inside the last collapsible block of Additional information:
|
||||
|
||||
````md
|
||||
<details>
|
||||
<summary>Demo script</summary>
|
||||
|
||||
```ts demo
|
||||
test("demo", async ({ demo, page }) => {
|
||||
// ...
|
||||
});
|
||||
```
|
||||
|
||||
</details>
|
||||
````
|
||||
|
||||
Push the branch first: `demo:pr` records the PR's head commit as GitHub has it. Then record it and write the `## Demo` section (between `<!-- demo:start -->` and `<!-- demo:end -->`):
|
||||
|
||||
```bash
|
||||
npm run demo:pr -- <number>
|
||||
```
|
||||
|
||||
It takes a few minutes, so run it in the background. The app's UI comes from the PR's head, in a temporary worktree, but the harness and fixtures come from your checkout: a PR that changes the harness itself is recorded with the harness you have checked out. Run it again after each push that changes what the videos show.
|
||||
|
||||
- Each `test()` becomes its own video, shown in a table under its title. Give each test `{ annotation: { type: 'description', description: '...' } }` to get one video to a row with its description beside it, which reads better when the videos show different things (see the worked example). Group tests with their own `test.use` in `test.describe(() => { ... })`.
|
||||
- In a PR block, the helpers import is replaced with `test` and `expect`, so reach fixtures through `test.use` options only.
|
||||
- A PR on a fork: `DEMO_GITHUB_REPO=<owner>/llama.cpp`. A PR by someone else: read its diff and demo block, then pass `--trust <sha>`.
|
||||
|
||||
## 2. Test
|
||||
|
||||
Turn the same flow into a check in `tests/e2e/<feature>.e2e.ts`, which CI runs (`npm run test:e2e`) against the built app on `:8181`, with no llama-server:
|
||||
|
||||
- `@playwright/test` instead of the helpers: `locator.click()` / `fill()` for `demo.*`, keep every `expect`, drop captions and pauses.
|
||||
- `mockLlamaServer(page, {...})` before `page.goto`, since nothing serves the API.
|
||||
- `importTraces(page, file)` and `generateTrace(name)` seed conversations, as in a demo.
|
||||
|
||||
```bash
|
||||
npx playwright test tests/e2e/<feature>.e2e.ts
|
||||
```
|
||||
|
||||
Locally it uses the installed Chrome with its sandbox on; in CI, Playwright's Chromium.
|
||||
|
||||
For a component on its own, a `play` function on its story is the check instead (as in `ui/apps/chat/tests/stories/app/PwaRefreshAlert.stories.svelte`): both packages run their stories as vitest browser tests, `npm run test:ui` in `ui/apps/chat` and `npm test` in `ui/lib/ui`.
|
||||
|
||||
## 3. Document
|
||||
|
||||
- **Docs videos:** put the script in the storage target as `scripts/docs/<name>.demo.ts` (import `'../helpers.ts'`), then `npm run demo:docs` records every docs script and uploads `videos/docs/<name>.{mp4,gif}`. `DEMO_STORAGE=file:///some/dir` tries it without a bucket.
|
||||
- **Screenshots:** in any demo, `await page.screenshot({ path: 'demo/videos/<name>.png' })` for the frame, or `await locator.screenshot({ path })` for one component, rendered at `DEMO_SCALE` (2x by default). Paths are relative to `ui/apps/chat`.
|
||||
- **Component docs** belong in the package's Storybook: a story per state, prose in a `.svx` page (see `ui/apps/chat/AGENTS.md`).
|
||||
|
||||
## Worked example
|
||||
|
||||
A demo of chat search, then a reply from the mocked server, then a Llama UI story, in one PR block, each video with its description beside it in the `## Demo` table (record with `DEMO_STORYBOOK=ui npm run demo:pr -- <number>`):
|
||||
|
||||
```ts
|
||||
const describe = (description: string) => ({
|
||||
annotation: { description, type: "description" },
|
||||
});
|
||||
|
||||
test.describe(() => {
|
||||
test.use({ traces: ["long-chat", "agentic-debugging"] });
|
||||
|
||||
test(
|
||||
"Search finds a chat by its title",
|
||||
describe(
|
||||
"Typing a word from a chat's title lists it, and opening the result shows the conversation.",
|
||||
),
|
||||
async ({ demo, page }) => {
|
||||
await demo.click(page.getByLabel("Expand navigation"));
|
||||
await demo.click(page.getByRole("button", { name: /^Search/ }));
|
||||
|
||||
const search = page.getByRole("dialog", { name: "Search" });
|
||||
|
||||
await demo.type(
|
||||
search.getByRole("combobox", { name: "Search" }),
|
||||
"flaky",
|
||||
);
|
||||
|
||||
const result = search.getByRole("option", {
|
||||
name: /Fix the flaky cache tests/,
|
||||
});
|
||||
|
||||
await expect(result).toBeVisible();
|
||||
await demo.click(result, 1200);
|
||||
await expect(page.getByRole("main")).toContainText(
|
||||
"All 48 cache tests pass now",
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test.describe(() => {
|
||||
test.use({
|
||||
mockServer: {
|
||||
reply: "Rust is a systems language focused on **safety** and *speed*.",
|
||||
},
|
||||
});
|
||||
|
||||
test(
|
||||
"A reply from a mocked server, no model loaded",
|
||||
describe(
|
||||
"The reply streams from mockServer, so the video looks the same on every machine.",
|
||||
),
|
||||
async ({ demo, page }) => {
|
||||
await demo.type(
|
||||
page.getByRole("textbox", { name: "Type a message..." }),
|
||||
"What is Rust?",
|
||||
);
|
||||
await demo.press("Enter", 1500);
|
||||
await expect(page.getByRole("main")).toContainText(
|
||||
"focused on safety",
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test.describe(() => {
|
||||
// a small viewport frames a small component, recorded at the same scale
|
||||
test.use({
|
||||
story: "ui-forms-switch--default",
|
||||
viewport: { height: 450, width: 720 },
|
||||
});
|
||||
|
||||
test(
|
||||
"A Llama UI story: Switch",
|
||||
describe(
|
||||
"The Switch from Llama UI, recorded from its Storybook story.",
|
||||
),
|
||||
async ({ demo, page }) => {
|
||||
const off = page.getByRole("switch").first();
|
||||
|
||||
await demo.click(off, 900);
|
||||
await expect(off).toBeChecked();
|
||||
},
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
The same search flow as a check is `tests/e2e/search-chats.e2e.ts`.
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- **Ports:** vite dev `:5180` (`DEMO_UI_PORT`), fixture MCP `:8765`, llama-server `:9931`, Storybook `:6007` (`DEMO_STORYBOOK_PORT`), e2e `:8181`. Every server is reused when something already answers there, even another checkout's: stop stale servers, or pick other ports. `demo:pr` picks free ports itself.
|
||||
- **Chrome sandbox:** demos record in Playwright's bundled Chromium with the sandbox on (headless installed Chrome ignores the viewport in screencasts); local e2e runs in the installed Chrome with the sandbox on. Do not turn the sandbox off to make a run pass: a PR demo runs that PR's code.
|
||||
- **Waits:** wait on state, never on time. `expect(locator).toBeVisible()` / `toContainText()` before acting on something that appears late; `demo.pause` is pacing for the viewer only. The first load of a cold dev server reloads the page once; the harness waits for it before recording, so do not add sleeps for it.
|
||||
- **Selectors:** use roles and accessible names. Some names match twice (`Expand navigation` is both the logo and the button: use `page.getByLabel('Expand navigation')`); scope to a dialog with `page.getByRole('dialog', { name })`. A strict-mode error names both matches.
|
||||
- **Real server:** without `mockServer`, the model list and any reply come from the real llama-server and differ per machine. Mock them for anything a viewer should see the same way twice.
|
||||
- **Preview size:** keep a demo short (under ~20 s per test): the GIF preview must stay under 5 MB, so a long one is shrunk until it is hard to read.
|
||||
- **Chromium only:** the screencast and the render run on the Chrome DevTools Protocol, so a demo in Firefox or WebKit fails at its start. Show a Safari-only fix with a check in `tests/e2e`, not a demo.
|
||||
+7
-6
@@ -450,12 +450,13 @@ static const std::map<llm_kv, const char *> LLM_KV_NAMES = {
|
||||
{ LLM_KV_NORM_BEFORE_RESIDUAL, "%s.norm_before_residual" },
|
||||
{ LLM_KV_NORM_BEFORE_FC, "%s.norm_before_fc" },
|
||||
|
||||
{ LLM_KV_DFLASH_BLOCK_SIZE, "%s.block_size" },
|
||||
{ LLM_KV_DFLASH_CONV_KERNEL_SIZE, "%s.conv_kernel_size" },
|
||||
{ LLM_KV_DFLASH_CONV_GROUP_SIZE, "%s.conv_group_size" },
|
||||
{ LLM_KV_DFLASH_SELECTOR_RANK, "%s.selector_rank" },
|
||||
{ LLM_KV_DFLASH_SELECTOR_TOP_K, "%s.selector_top_k" },
|
||||
{ LLM_KV_DFLASH_HAS_MARKOV_CONTEXT, "%s.has_markov_context" },
|
||||
{ LLM_KV_DFLASH_BLOCK_SIZE, "%s.block_size" },
|
||||
{ LLM_KV_DFLASH_CONV_KERNEL_SIZE, "%s.conv_kernel_size" },
|
||||
{ LLM_KV_DFLASH_CONV_GROUP_SIZE, "%s.conv_group_size" },
|
||||
{ LLM_KV_DFLASH_SELECTOR_RANK, "%s.selector_rank" },
|
||||
{ LLM_KV_DFLASH_SELECTOR_TOP_K, "%s.selector_top_k" },
|
||||
{ LLM_KV_DFLASH_SELECTOR_SOFTCAP_AFTER_CORRECTION, "%s.selector_softcap_after_correction" },
|
||||
{ LLM_KV_DFLASH_HAS_MARKOV_CONTEXT, "%s.has_markov_context" },
|
||||
|
||||
{ LLM_KV_LILICORR_HIDDEN_SIZE, "lilicorr.hidden_size" },
|
||||
{ LLM_KV_LILICORR_CANDIDATE_TOPK, "lilicorr.candidate_topk" },
|
||||
|
||||
@@ -501,6 +501,7 @@ enum llm_kv {
|
||||
LLM_KV_DFLASH_CONV_GROUP_SIZE,
|
||||
LLM_KV_DFLASH_SELECTOR_RANK,
|
||||
LLM_KV_DFLASH_SELECTOR_TOP_K,
|
||||
LLM_KV_DFLASH_SELECTOR_SOFTCAP_AFTER_CORRECTION,
|
||||
LLM_KV_DFLASH_HAS_MARKOV_CONTEXT,
|
||||
LLM_KV_LILICORR_HIDDEN_SIZE,
|
||||
LLM_KV_LILICORR_CANDIDATE_TOPK,
|
||||
|
||||
@@ -305,6 +305,7 @@ struct llama_hparams {
|
||||
uint32_t dflash_conv_group_size = 0;
|
||||
uint32_t dflash_selector_rank = 0;
|
||||
uint32_t dflash_selector_top_k = 0;
|
||||
bool dflash_softcap_post = false; // DFlash2 softcaps the selector scores instead of the logits
|
||||
bool dspark_f_rnn = false; // rnn markov head reads f_rnn from embd_state
|
||||
uint32_t lilicorr_hidden_size = 0;
|
||||
uint32_t lilicorr_candidate_topk = 0;
|
||||
|
||||
@@ -47,6 +47,7 @@ void llama_model_dflash::load_arch_hparams(llama_model_loader & ml) {
|
||||
}
|
||||
} else if (has_selector) {
|
||||
variant = VARIANT_DFLASH2;
|
||||
ml.get_key(LLM_KV_DFLASH_SELECTOR_SOFTCAP_AFTER_CORRECTION, hparams.dflash_softcap_post, false);
|
||||
} else if (has_lilicorr) {
|
||||
variant = VARIANT_LILICORR;
|
||||
load_hparams_lilicorr(ml);
|
||||
@@ -447,6 +448,9 @@ ggml_tensor * llama_model_dflash::graph_base::build_layers(ggml_tensor * inp_tok
|
||||
ggml_tensor * inpL = model.dspark_mask_embd
|
||||
? build_dspark_inp_block(*this, model, inp_tokens)
|
||||
: ggml_get_rows(ctx0, get_tok_embd(*this, model), inp_tokens);
|
||||
if (model.tok_norm && !model.dspark_mask_embd) {
|
||||
inpL = build_norm(inpL, model.tok_norm, nullptr, LLM_NORM_RMS, -1);
|
||||
}
|
||||
if (hparams.f_embedding_scale != 0.0f) {
|
||||
inpL = ggml_scale(ctx0, inpL, hparams.f_embedding_scale);
|
||||
}
|
||||
@@ -569,7 +573,7 @@ ggml_tensor * llama_model_dflash::graph_base::build_logits(ggml_tensor * cur) {
|
||||
if (hparams.f_logit_scale != 0.0f) {
|
||||
cur = ggml_scale(ctx0, cur, hparams.f_logit_scale);
|
||||
}
|
||||
if (hparams.f_final_logit_softcapping > 0.0f) {
|
||||
if (hparams.f_final_logit_softcapping > 0.0f && !hparams.dflash_softcap_post) {
|
||||
cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_final_logit_softcapping);
|
||||
cur = ggml_tanh(ctx0, cur);
|
||||
cur = ggml_scale(ctx0, cur, hparams.f_final_logit_softcapping);
|
||||
|
||||
@@ -177,6 +177,10 @@ static void build_dflash2_selector(llm_graph_context & g, const llama_model & mo
|
||||
}
|
||||
ggml_tensor * unary_bcast = ggml_reshape_4d(ctx0, unary_run, top_k, 1, n_pos, n_blocks);
|
||||
score = ggml_add(ctx0, score, ggml_repeat(ctx0, unary_bcast, score));
|
||||
if (hparams.dflash_softcap_post && hparams.f_final_logit_softcapping > 0.0f) {
|
||||
const float cap = hparams.f_final_logit_softcapping;
|
||||
score = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, score, 1.0f / cap)), cap);
|
||||
}
|
||||
|
||||
ggml_tensor * row = ggml_concat(ctx0,
|
||||
ggml_cast(ctx0, cand_run, GGML_TYPE_F32),
|
||||
|
||||
+12
-1
@@ -220,6 +220,11 @@ ggml_tensor * llama_model_inkling2::graph::convolve(
|
||||
const int64_t n_seq_tokens = ubatch.n_seq_tokens;
|
||||
const int64_t n_seqs = ubatch.n_seqs;
|
||||
|
||||
// add the taps input first and the result right after the state store, so the conv ops are consecutive and backends can fuse them
|
||||
if (dynamic) {
|
||||
ggml_build_forward_expand(gf, dynamic);
|
||||
}
|
||||
|
||||
ggml_tensor * past = ggml_view_3d(ctx0, history, n_conv - 1, n_channels, n_seqs, history->nb[1], history->nb[2], offset*history->nb[1]);
|
||||
|
||||
ggml_tensor * x = ggml_transpose(ctx0, ggml_reshape_3d(ctx0, cur, n_channels, n_seq_tokens, n_seqs));
|
||||
@@ -248,7 +253,10 @@ ggml_tensor * llama_model_inkling2::graph::convolve(
|
||||
}
|
||||
}
|
||||
|
||||
return ggml_scale(ctx0, ggml_add(ctx0, cur, out), 1.0f/sqrtf((dynamic ? 2 : 1)*n_conv + 1));
|
||||
out = ggml_scale(ctx0, ggml_add(ctx0, cur, out), 1.0f/sqrtf((dynamic ? 2 : 1)*n_conv + 1));
|
||||
ggml_build_forward_expand(gf, out);
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
// mix a cross-pass message into a looped layer input: (1 - forget)*cur + gain*message, both gated on cur and message
|
||||
@@ -275,6 +283,7 @@ ggml_tensor * llama_model_inkling2::graph::build_inputs() {
|
||||
tau = ggml_scale_bias(ctx0, ggml_cast(ctx0, inp_pos, GGML_TYPE_F32), 1.0f, 1.0f);
|
||||
tau = ggml_log(ctx0, ggml_clamp(ctx0, ggml_scale(ctx0, tau, 1.0f/hparams.n_log_scale_floor), 1.0f, INFINITY));
|
||||
tau = ggml_reshape_3d(ctx0, ggml_scale_bias(ctx0, tau, hparams.f_log_scale_alpha, 1.0f), 1, 1, n_tokens);
|
||||
ggml_build_forward_expand(gf, tau);
|
||||
|
||||
ggml_tensor * cur = build_inp_embd(model.tok_embd);
|
||||
|
||||
@@ -390,6 +399,7 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens
|
||||
blocks.push_back(inpSA);
|
||||
} else {
|
||||
cur = ggml_add(ctx0, inpSA, cur);
|
||||
ggml_build_forward_expand(gf, cur); // right after the conv, so backends can fuse the add into it
|
||||
}
|
||||
|
||||
ggml_tensor * ffn_inp = cur;
|
||||
@@ -421,6 +431,7 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens
|
||||
cb(cur, "ffn_out", il);
|
||||
|
||||
cur = ggml_add(ctx0, ffn_inp, cur);
|
||||
ggml_build_forward_expand(gf, cur);
|
||||
cb(cur, "l_out", il);
|
||||
|
||||
return cur;
|
||||
|
||||
+191
-191
@@ -5,9 +5,9 @@ afmoe ,1 ,any ,RMS_NORM+MUL , 10
|
||||
afmoe ,1 ,any ,RMS_NORM+MUL+ADD , 3
|
||||
afmoe ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
arcee ,0 ,any ,RMS_NORM+MUL , 5
|
||||
arctic ,0 ,any ,MUL+ADD , 4
|
||||
arctic ,0 ,any ,RMS_NORM+MUL , 7
|
||||
arctic ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
arctic ,1 ,any ,MUL+ADD , 4
|
||||
arctic ,1 ,any ,RMS_NORM+MUL , 7
|
||||
arctic ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
baichuan ,0 ,any ,RMS_NORM+MUL , 5
|
||||
bailingmoe ,1 ,any ,ADD+ADD , 2
|
||||
bailingmoe ,1 ,any ,MUL+ADD , 4
|
||||
@@ -23,8 +23,8 @@ bailingmoe3 ,1 ,any ,MUL+ADD , 2
|
||||
bailingmoe3 ,1 ,any ,RMS_NORM+MUL , 8
|
||||
bailingmoe3 ,1 ,any ,RMS_NORM+SCALE , 2
|
||||
bailingmoe3 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
beam ,0 ,any ,MUL+ADD , 6
|
||||
beam ,0 ,any ,RMS_NORM+MUL , 25
|
||||
beam ,1 ,any ,MUL+ADD , 6
|
||||
beam ,1 ,any ,RMS_NORM+MUL , 25
|
||||
bloom ,0 ,any ,NORM+MUL+ADD , 6
|
||||
chatglm ,0 ,any ,RMS_NORM+MUL , 5
|
||||
clover_moe ,1 ,any ,ADD+ADD , 2
|
||||
@@ -43,45 +43,45 @@ cohere2moe ,1 ,any ,MUL+ADD , 2
|
||||
cohere2moe ,1 ,any ,RMS_NORM+MUL , 3
|
||||
command-r ,0 ,any ,ADD+ADD , 2
|
||||
command-r ,0 ,any ,NORM+MUL , 3
|
||||
dbrx ,0 ,any ,MUL+ADD , 4
|
||||
dbrx ,0 ,any ,NORM+MUL , 5
|
||||
dbrx ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
dbrx ,1 ,any ,MUL+ADD , 4
|
||||
dbrx ,1 ,any ,NORM+MUL , 5
|
||||
dbrx ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
deci ,0 ,any ,RMS_NORM+MUL , 5
|
||||
deepseek ,0 ,any ,ADD+ADD , 1
|
||||
deepseek ,0 ,any ,MUL+ADD , 2
|
||||
deepseek ,0 ,any ,RMS_NORM+MUL , 5
|
||||
deepseek ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS , 1
|
||||
deepseek2 ,0 ,any ,ADD+ADD , 1
|
||||
deepseek2 ,0 ,any ,MUL+ADD , 2
|
||||
deepseek2 ,0 ,any ,RMS_NORM+MUL , 9
|
||||
deepseek2 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
deepseek32 ,0 ,any ,ADD+ADD , 1
|
||||
deepseek32 ,0 ,any ,MUL+ADD , 2
|
||||
deepseek32 ,0 ,any ,NORM+MUL+ADD , 2
|
||||
deepseek32 ,0 ,any ,RMS_NORM+MUL , 9
|
||||
deepseek32 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
deepseek4 ,0 ,any ,MUL+ADD , 8
|
||||
deepseek4 ,0 ,any ,RMS_NORM+MUL , 20
|
||||
deepseek4 ,0 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 4
|
||||
deepseek41 ,0 ,any ,MUL+ADD , 12
|
||||
deepseek41 ,0 ,any ,RMS_NORM+MUL , 31
|
||||
deepseek41 ,0 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV, 6
|
||||
deepseek ,1 ,any ,ADD+ADD , 1
|
||||
deepseek ,1 ,any ,MUL+ADD , 2
|
||||
deepseek ,1 ,any ,RMS_NORM+MUL , 5
|
||||
deepseek ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS , 1
|
||||
deepseek2 ,1 ,any ,ADD+ADD , 1
|
||||
deepseek2 ,1 ,any ,MUL+ADD , 2
|
||||
deepseek2 ,1 ,any ,RMS_NORM+MUL , 9
|
||||
deepseek2 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
deepseek32 ,1 ,any ,ADD+ADD , 1
|
||||
deepseek32 ,1 ,any ,MUL+ADD , 2
|
||||
deepseek32 ,1 ,any ,NORM+MUL+ADD , 2
|
||||
deepseek32 ,1 ,any ,RMS_NORM+MUL , 9
|
||||
deepseek32 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
deepseek4 ,1 ,any ,MUL+ADD , 8
|
||||
deepseek4 ,1 ,any ,RMS_NORM+MUL , 20
|
||||
deepseek4 ,1 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 4
|
||||
deepseek41 ,1 ,any ,MUL+ADD , 12
|
||||
deepseek41 ,1 ,any ,RMS_NORM+MUL , 31
|
||||
deepseek41 ,1 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV, 6
|
||||
domynedge ,0 ,any ,RMS_NORM+MUL , 8
|
||||
domynedge ,0 ,any ,RMS_NORM+MUL+ADD , 3
|
||||
dots1 ,0 ,any ,ADD+ADD , 1
|
||||
dots1 ,0 ,any ,MUL+ADD , 2
|
||||
dots1 ,0 ,any ,RMS_NORM+MUL , 9
|
||||
dots1 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
dots3note ,0 ,any ,ADD+ADD , 1
|
||||
dots3note ,0 ,any ,MUL+ADD , 2
|
||||
dots3note ,0 ,any ,NORM+MUL+ADD , 1
|
||||
dots3note ,0 ,any ,RMS_NORM+MUL , 11
|
||||
dots3note ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
dots1 ,1 ,any ,ADD+ADD , 1
|
||||
dots1 ,1 ,any ,MUL+ADD , 2
|
||||
dots1 ,1 ,any ,RMS_NORM+MUL , 9
|
||||
dots1 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
dots3note ,1 ,any ,ADD+ADD , 1
|
||||
dots3note ,1 ,any ,MUL+ADD , 2
|
||||
dots3note ,1 ,any ,NORM+MUL+ADD , 1
|
||||
dots3note ,1 ,any ,RMS_NORM+MUL , 11
|
||||
dots3note ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
dream ,0 ,any ,RMS_NORM+MUL , 5
|
||||
ernie4_5-moe ,1 ,any ,ADD+ADD , 1
|
||||
ernie4_5-moe ,1 ,any ,MUL+ADD , 2
|
||||
ernie4_5-moe ,1 ,any ,RMS_NORM+MUL , 5
|
||||
ernie4_5 ,0 ,any ,RMS_NORM+MUL , 5
|
||||
ernie4_5 ,1 ,any ,RMS_NORM+MUL , 5
|
||||
exaone ,0 ,any ,RMS_NORM+MUL , 5
|
||||
exaone-moe ,1 ,any ,ADD+ADD , 1
|
||||
exaone-moe ,1 ,any ,MUL+ADD , 2
|
||||
@@ -93,10 +93,10 @@ falcon ,0 ,any ,ADD+ADD , 2
|
||||
falcon ,0 ,any ,NORM+MUL+ADD , 5
|
||||
falcon-h1 ,0 ,any ,ADD+ADD , 2
|
||||
falcon-h1 ,0 ,any ,RMS_NORM+MUL , 9
|
||||
flint ,0 ,any ,ADD+ADD , 1
|
||||
flint ,0 ,any ,MUL+ADD , 2
|
||||
flint ,0 ,any ,RMS_NORM+MUL , 9
|
||||
flint ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1
|
||||
flint ,1 ,any ,ADD+ADD , 1
|
||||
flint ,1 ,any ,MUL+ADD , 2
|
||||
flint ,1 ,any ,RMS_NORM+MUL , 9
|
||||
flint ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1
|
||||
gemma ,0 ,any ,RMS_NORM+MUL , 5
|
||||
gemma2 ,0 ,any ,RMS_NORM+MUL , 5
|
||||
gemma2 ,0 ,any ,RMS_NORM+MUL+ADD , 4
|
||||
@@ -104,42 +104,42 @@ gemma3 ,0 ,any ,RMS_NORM+MUL , 9
|
||||
gemma3 ,0 ,any ,RMS_NORM+MUL+ADD , 4
|
||||
gemma4 ,0 ,any ,RMS_NORM+MUL , 37
|
||||
gemma4 ,0 ,any ,RMS_NORM+MUL+ADD , 30
|
||||
glm-dsa ,0 ,any ,ADD+ADD , 1
|
||||
glm-dsa ,0 ,any ,MUL+ADD , 2
|
||||
glm-dsa ,0 ,any ,NORM+MUL+ADD , 2
|
||||
glm-dsa ,0 ,any ,RMS_NORM+MUL , 9
|
||||
glm-dsa ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
glm-dsa ,1 ,any ,ADD+ADD , 1
|
||||
glm-dsa ,1 ,any ,MUL+ADD , 2
|
||||
glm-dsa ,1 ,any ,NORM+MUL+ADD , 2
|
||||
glm-dsa ,1 ,any ,RMS_NORM+MUL , 9
|
||||
glm-dsa ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
glm4 ,0 ,any ,RMS_NORM+MUL , 5
|
||||
glm4 ,0 ,any ,RMS_NORM+MUL+ADD , 4
|
||||
glm4moe ,1 ,any ,ADD+ADD , 1
|
||||
glm4moe ,1 ,any ,MUL+ADD , 2
|
||||
glm4moe ,1 ,any ,RMS_NORM+MUL , 9
|
||||
glm4moe ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
glm5-next ,0 ,any ,ADD+ADD+ADD , 1
|
||||
glm5-next ,0 ,any ,GATED_DELTA_NET+CPY , 1
|
||||
glm5-next ,0 ,any ,MUL+ADD , 2
|
||||
glm5-next ,0 ,any ,NORM+MUL+ADD , 1
|
||||
glm5-next ,0 ,any ,RMS_NORM+MUL , 8
|
||||
glm5-next ,0 ,any ,RMS_NORM+SCALE , 2
|
||||
glm5-next ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
gpt-oss ,0 ,any ,MUL+ADD , 4
|
||||
gpt-oss ,0 ,any ,RMS_NORM+MUL , 5
|
||||
glm5-next ,1 ,any ,ADD+ADD+ADD , 1
|
||||
glm5-next ,1 ,any ,GATED_DELTA_NET+CPY , 1
|
||||
glm5-next ,1 ,any ,MUL+ADD , 2
|
||||
glm5-next ,1 ,any ,NORM+MUL+ADD , 1
|
||||
glm5-next ,1 ,any ,RMS_NORM+MUL , 8
|
||||
glm5-next ,1 ,any ,RMS_NORM+SCALE , 2
|
||||
glm5-next ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
gpt-oss ,1 ,any ,MUL+ADD , 4
|
||||
gpt-oss ,1 ,any ,RMS_NORM+MUL , 5
|
||||
gpt2 ,0 ,any ,NORM+MUL+ADD , 5
|
||||
gptneox ,0 ,any ,NORM+MUL+ADD , 5
|
||||
granite ,0 ,any ,RMS_NORM+MUL , 5
|
||||
granite ,0 ,any ,MUL+ADD , 4
|
||||
granite ,0 ,any ,RMS_NORM+MUL , 5
|
||||
granite ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
granite ,1 ,any ,MUL+ADD , 4
|
||||
granite ,1 ,any ,RMS_NORM+MUL , 5
|
||||
granite ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
granite_swa ,0 ,any ,RMS_NORM+MUL , 5
|
||||
granitehybrid ,0 ,any ,RMS_NORM+MUL , 6
|
||||
granitemoe ,1 ,any ,RMS_NORM+MUL , 5
|
||||
granitemoe ,0 ,any ,RMS_NORM+MUL , 5
|
||||
granitemoe ,1 ,any ,MUL+ADD , 4
|
||||
granitemoe ,1 ,any ,RMS_NORM+MUL , 5
|
||||
granitemoe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
grok ,0 ,any ,MUL+ADD , 4
|
||||
grok ,0 ,any ,RMS_NORM+MUL , 5
|
||||
grok ,0 ,any ,RMS_NORM+MUL+ADD , 4
|
||||
grok ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
grok ,1 ,any ,MUL+ADD , 4
|
||||
grok ,1 ,any ,RMS_NORM+MUL , 5
|
||||
grok ,1 ,any ,RMS_NORM+MUL+ADD , 4
|
||||
grok ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
grovemoe ,1 ,any ,ADD+ADD , 2
|
||||
grovemoe ,1 ,any ,MUL+ADD , 8
|
||||
grovemoe ,1 ,any ,RMS_NORM+MUL , 9
|
||||
@@ -149,53 +149,53 @@ hunyuan-moe ,1 ,any ,MUL+ADD , 4
|
||||
hunyuan-moe ,1 ,any ,RMS_NORM+MUL , 9
|
||||
hunyuan-moe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
hunyuan_vl ,0 ,any ,RMS_NORM+MUL , 9
|
||||
hy_v3 ,0 ,any ,ADD+ADD , 2
|
||||
hy_v3 ,0 ,any ,MUL+ADD , 4
|
||||
hy_v3 ,0 ,any ,RMS_NORM+MUL , 9
|
||||
hy_v3 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 2
|
||||
hy_v4 ,0 ,any ,MUL+ADD , 2
|
||||
hy_v4 ,0 ,any ,NORM+MUL+ADD , 1
|
||||
hy_v4 ,0 ,any ,RMS_NORM+MUL , 9
|
||||
hy_v4 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1
|
||||
hy_v4_flash ,0 ,any ,MUL+ADD , 6
|
||||
hy_v4_flash ,0 ,any ,RMS_NORM+MUL , 32
|
||||
hy_v4_flash ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 3
|
||||
inkling2 ,0 ,any ,MUL+ADD , 6
|
||||
inkling2 ,0 ,any ,RMS_NORM+MUL , 10
|
||||
inkling2 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV+SCALE, 3
|
||||
hy_v3 ,1 ,any ,ADD+ADD , 2
|
||||
hy_v3 ,1 ,any ,MUL+ADD , 4
|
||||
hy_v3 ,1 ,any ,RMS_NORM+MUL , 9
|
||||
hy_v3 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 2
|
||||
hy_v4 ,1 ,any ,MUL+ADD , 2
|
||||
hy_v4 ,1 ,any ,NORM+MUL+ADD , 1
|
||||
hy_v4 ,1 ,any ,RMS_NORM+MUL , 9
|
||||
hy_v4 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1
|
||||
hy_v4_flash ,1 ,any ,MUL+ADD , 6
|
||||
hy_v4_flash ,1 ,any ,RMS_NORM+MUL , 32
|
||||
hy_v4_flash ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 3
|
||||
inkling2 ,1 ,any ,MUL+ADD , 6
|
||||
inkling2 ,1 ,any ,RMS_NORM+MUL , 10
|
||||
inkling2 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV+SCALE, 3
|
||||
internlm2 ,0 ,any ,RMS_NORM+MUL , 5
|
||||
jais ,0 ,any ,NORM+MUL+ADD , 5
|
||||
jais2 ,0 ,any ,NORM+MUL+ADD , 5
|
||||
jamba ,0 ,any ,RMS_NORM+MUL , 8
|
||||
k2-horizon ,0 ,any ,RMS_NORM+MUL , 4
|
||||
k2-horizon ,0 ,any ,ADD+ADD , 1
|
||||
k2-horizon ,0 ,any ,MUL+ADD , 2
|
||||
k2-horizon ,0 ,any ,RMS_NORM+MUL , 4
|
||||
k2-horizon ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
kimi-k3 ,0 ,any ,GATED_DELTA_NET+CPY , 1
|
||||
kimi-k3 ,0 ,any ,MUL+ADD , 2
|
||||
kimi-k3 ,0 ,any ,RMS_NORM+MUL , 17
|
||||
kimi-k3 ,0 ,any ,RMS_NORM+SCALE , 2
|
||||
kimi-k3 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
kimi-k31 ,0 ,any ,GATED_DELTA_NET+CPY , 1
|
||||
kimi-k31 ,0 ,any ,MUL+ADD , 2
|
||||
kimi-k31 ,0 ,any ,NORM+MUL+ADD , 1
|
||||
kimi-k31 ,0 ,any ,RMS_NORM+MUL , 17
|
||||
kimi-k31 ,0 ,any ,RMS_NORM+SCALE , 2
|
||||
kimi-k31 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
kimi-linear ,0 ,any ,ADD+ADD , 1
|
||||
kimi-linear ,0 ,any ,GATED_DELTA_NET+CPY , 1
|
||||
kimi-linear ,0 ,any ,MUL+ADD , 2
|
||||
kimi-linear ,0 ,any ,RMS_NORM+MUL , 7
|
||||
kimi-linear ,0 ,any ,RMS_NORM+SCALE , 2
|
||||
kimi-linear ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1
|
||||
kolibri1 ,0 ,any ,MUL+ADD , 4
|
||||
kolibri1 ,0 ,any ,RMS_NORM+MUL , 10
|
||||
kolibri1 ,0 ,any ,RMS_NORM+MUL+ADD , 3
|
||||
laguna ,0 ,any ,ADD+ADD , 1
|
||||
laguna ,0 ,any ,MUL+ADD , 2
|
||||
laguna ,0 ,any ,RMS_NORM+MUL , 9
|
||||
laguna ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
k2-horizon ,1 ,any ,ADD+ADD , 1
|
||||
k2-horizon ,1 ,any ,MUL+ADD , 2
|
||||
k2-horizon ,1 ,any ,RMS_NORM+MUL , 4
|
||||
k2-horizon ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
kimi-k3 ,1 ,any ,GATED_DELTA_NET+CPY , 1
|
||||
kimi-k3 ,1 ,any ,MUL+ADD , 2
|
||||
kimi-k3 ,1 ,any ,RMS_NORM+MUL , 17
|
||||
kimi-k3 ,1 ,any ,RMS_NORM+SCALE , 2
|
||||
kimi-k3 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
kimi-k31 ,1 ,any ,GATED_DELTA_NET+CPY , 1
|
||||
kimi-k31 ,1 ,any ,MUL+ADD , 2
|
||||
kimi-k31 ,1 ,any ,NORM+MUL+ADD , 1
|
||||
kimi-k31 ,1 ,any ,RMS_NORM+MUL , 17
|
||||
kimi-k31 ,1 ,any ,RMS_NORM+SCALE , 2
|
||||
kimi-k31 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
kimi-linear ,1 ,any ,ADD+ADD , 1
|
||||
kimi-linear ,1 ,any ,GATED_DELTA_NET+CPY , 1
|
||||
kimi-linear ,1 ,any ,MUL+ADD , 2
|
||||
kimi-linear ,1 ,any ,RMS_NORM+MUL , 7
|
||||
kimi-linear ,1 ,any ,RMS_NORM+SCALE , 2
|
||||
kimi-linear ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 1
|
||||
kolibri1 ,1 ,any ,MUL+ADD , 4
|
||||
kolibri1 ,1 ,any ,RMS_NORM+MUL , 10
|
||||
kolibri1 ,1 ,any ,RMS_NORM+MUL+ADD , 3
|
||||
laguna ,1 ,any ,ADD+ADD , 1
|
||||
laguna ,1 ,any ,MUL+ADD , 2
|
||||
laguna ,1 ,any ,RMS_NORM+MUL , 9
|
||||
laguna ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
lfm2 ,0 ,any ,RMS_NORM+MUL , 7
|
||||
lfm2moe ,1 ,any ,MUL+ADD , 2
|
||||
lfm2moe ,1 ,any ,RMS_NORM+MUL , 7
|
||||
@@ -207,69 +207,69 @@ llada-moe ,1 ,any ,MUL+ADD , 4
|
||||
llada-moe ,1 ,any ,RMS_NORM+MUL , 9
|
||||
llada-moe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS , 2
|
||||
llama ,0 ,any ,RMS_NORM+MUL , 5
|
||||
llama ,0 ,any ,MUL+ADD , 4
|
||||
llama ,0 ,any ,RMS_NORM+MUL , 5
|
||||
llama ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
llama4 ,0 ,any ,ADD+ADD , 2
|
||||
llama4 ,0 ,any ,MUL+ADD , 4
|
||||
llama4 ,0 ,any ,RMS_NORM+MUL , 9
|
||||
llama ,1 ,any ,MUL+ADD , 4
|
||||
llama ,1 ,any ,RMS_NORM+MUL , 5
|
||||
llama ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
llama4 ,1 ,any ,ADD+ADD , 2
|
||||
llama4 ,1 ,any ,MUL+ADD , 4
|
||||
llama4 ,1 ,any ,RMS_NORM+MUL , 9
|
||||
maincoder ,0 ,any ,RMS_NORM+MUL , 9
|
||||
maion-coder ,0 ,any ,MUL+ADD , 4
|
||||
maion-coder ,0 ,any ,RMS_NORM+MUL , 17
|
||||
maion-coder ,0 ,any ,RMS_NORM+MUL+ADD , 8
|
||||
maion-coder ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
maion-coder ,1 ,any ,MUL+ADD , 4
|
||||
maion-coder ,1 ,any ,RMS_NORM+MUL , 17
|
||||
maion-coder ,1 ,any ,RMS_NORM+MUL+ADD , 8
|
||||
maion-coder ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
mamba ,0 ,any ,RMS_NORM+MUL , 3
|
||||
mamba2 ,0 ,any ,RMS_NORM+MUL , 5
|
||||
maple ,0 ,any ,MUL+ADD , 4
|
||||
maple ,0 ,any ,RMS_NORM+MUL , 9
|
||||
maple ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
mellum ,0 ,any ,MUL+ADD , 4
|
||||
mellum ,0 ,any ,RMS_NORM+MUL , 9
|
||||
mellum ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
metis16 ,0 ,any ,MUL+ADD , 8
|
||||
metis16 ,0 ,any ,RMS_NORM+MUL , 11
|
||||
mimo2 ,0 ,any ,MUL+ADD , 4
|
||||
mimo2 ,0 ,any ,RMS_NORM+MUL , 5
|
||||
mimo2 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
maple ,1 ,any ,MUL+ADD , 4
|
||||
maple ,1 ,any ,RMS_NORM+MUL , 9
|
||||
maple ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
mellum ,1 ,any ,MUL+ADD , 4
|
||||
mellum ,1 ,any ,RMS_NORM+MUL , 9
|
||||
mellum ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
metis16 ,1 ,any ,MUL+ADD , 8
|
||||
metis16 ,1 ,any ,RMS_NORM+MUL , 11
|
||||
mimo2 ,1 ,any ,MUL+ADD , 4
|
||||
mimo2 ,1 ,any ,RMS_NORM+MUL , 5
|
||||
mimo2 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
minicpm ,0 ,any ,RMS_NORM+MUL , 5
|
||||
minicpm ,0 ,any ,MUL+ADD , 4
|
||||
minicpm ,0 ,any ,RMS_NORM+MUL , 5
|
||||
minicpm ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
minicpm ,1 ,any ,MUL+ADD , 4
|
||||
minicpm ,1 ,any ,RMS_NORM+MUL , 5
|
||||
minicpm ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
minicpm3 ,0 ,any ,RMS_NORM+MUL , 9
|
||||
minimax-01 ,0 ,any ,MUL+ADD , 4
|
||||
minimax-01 ,0 ,any ,RMS_NORM+MUL , 6
|
||||
minimax-01 ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
minimax-m2 ,0 ,any ,MUL+ADD , 4
|
||||
minimax-m2 ,0 ,any ,RMS_NORM+MUL , 9
|
||||
minimax-m2 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
minimax-m3 ,0 ,any ,ADD+ADD , 1
|
||||
minimax-m3 ,0 ,any ,MUL+ADD , 2
|
||||
minimax-m3 ,0 ,any ,RMS_NORM+MUL , 11
|
||||
minimax-m3 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
mistral-large4 ,0 ,any ,ADD+ADD , 3
|
||||
mistral-large4 ,0 ,any ,MUL+ADD , 6
|
||||
mistral-large4 ,0 ,any ,NORM+MUL+ADD , 6
|
||||
mistral-large4 ,0 ,any ,RMS_NORM+MUL , 12
|
||||
minimax-01 ,1 ,any ,MUL+ADD , 4
|
||||
minimax-01 ,1 ,any ,RMS_NORM+MUL , 6
|
||||
minimax-01 ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
minimax-m2 ,1 ,any ,MUL+ADD , 4
|
||||
minimax-m2 ,1 ,any ,RMS_NORM+MUL , 9
|
||||
minimax-m2 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
minimax-m3 ,1 ,any ,ADD+ADD , 1
|
||||
minimax-m3 ,1 ,any ,MUL+ADD , 2
|
||||
minimax-m3 ,1 ,any ,RMS_NORM+MUL , 11
|
||||
minimax-m3 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
mistral-large4 ,1 ,any ,ADD+ADD , 3
|
||||
mistral-large4 ,1 ,any ,MUL+ADD , 6
|
||||
mistral-large4 ,1 ,any ,NORM+MUL+ADD , 6
|
||||
mistral-large4 ,1 ,any ,RMS_NORM+MUL , 12
|
||||
mistral3 ,0 ,any ,RMS_NORM+MUL , 5
|
||||
mistral3 ,0 ,any ,MUL+ADD , 4
|
||||
mistral3 ,0 ,any ,RMS_NORM+MUL , 5
|
||||
mistral3 ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
mistral4 ,0 ,any ,ADD+ADD , 1
|
||||
mistral4 ,0 ,any ,MUL+ADD , 2
|
||||
mistral4 ,0 ,any ,RMS_NORM+MUL , 9
|
||||
mistral4 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
mistral3 ,1 ,any ,MUL+ADD , 4
|
||||
mistral3 ,1 ,any ,RMS_NORM+MUL , 5
|
||||
mistral3 ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
mistral4 ,1 ,any ,ADD+ADD , 1
|
||||
mistral4 ,1 ,any ,MUL+ADD , 2
|
||||
mistral4 ,1 ,any ,RMS_NORM+MUL , 9
|
||||
mistral4 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
moshi ,0 ,any ,RMS_NORM+MUL , 5
|
||||
mpt ,0 ,any ,NORM+MUL+ADD , 5
|
||||
muse-glimmer ,0 ,any ,RMS_NORM+MUL , 10
|
||||
muse-glimmer ,0 ,any ,RMS_NORM+MUL+ADD , 3
|
||||
muse-spark ,0 ,any ,MUL+ADD , 4
|
||||
muse-spark ,0 ,any ,RMS_NORM+MUL , 11
|
||||
muse-spark ,0 ,any ,RMS_NORM+MUL+ADD , 3
|
||||
muse-spark ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
muse-spark ,1 ,any ,MUL+ADD , 4
|
||||
muse-spark ,1 ,any ,RMS_NORM+MUL , 11
|
||||
muse-spark ,1 ,any ,RMS_NORM+MUL+ADD , 3
|
||||
muse-spark ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
nanbeige ,0 ,any ,RMS_NORM+MUL , 5
|
||||
nemotron ,0 ,any ,NORM+MUL+ADD , 5
|
||||
nemotron_h ,0 ,any ,RMS_NORM+MUL , 5
|
||||
nemotron_h_moe ,1 ,any ,RMS_NORM+MUL , 5
|
||||
nemotron_h_moe ,0 ,any ,RMS_NORM+MUL , 5
|
||||
olmo2 ,0 ,any ,RMS_NORM+MUL , 5
|
||||
olmo2 ,0 ,any ,RMS_NORM+MUL+ADD , 4
|
||||
olmoe ,1 ,any ,MUL+ADD , 4
|
||||
@@ -277,7 +277,7 @@ olmoe ,1 ,any ,RMS_NORM+MUL , 9
|
||||
olmoe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS , 2
|
||||
openelm ,0 ,any ,RMS_NORM+MUL , 9
|
||||
orion ,0 ,any ,NORM+MUL+ADD , 5
|
||||
paddleocr ,0 ,any ,RMS_NORM+MUL , 5
|
||||
paddleocr ,1 ,any ,RMS_NORM+MUL , 5
|
||||
pangu-embedded ,0 ,any ,RMS_NORM+MUL , 5
|
||||
phi2 ,0 ,any ,ADD+ADD , 2
|
||||
phi2 ,0 ,any ,NORM+MUL+ADD , 3
|
||||
@@ -315,40 +315,40 @@ qwen35moe ,1 ,any ,SSM_CONV+UNARY , 1
|
||||
qwen3moe ,1 ,any ,MUL+ADD , 4
|
||||
qwen3moe ,1 ,any ,RMS_NORM+MUL , 9
|
||||
qwen3moe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
qwen3next ,0 ,any ,ADD+ADD , 2
|
||||
qwen3next ,0 ,any ,GATED_DELTA_NET+CPY , 1
|
||||
qwen3next ,0 ,any ,MUL+ADD , 4
|
||||
qwen3next ,0 ,any ,RMS_NORM+MUL , 8
|
||||
qwen3next ,0 ,any ,RMS_NORM+SCALE , 2
|
||||
qwen3next ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
qwen3next ,0 ,any ,SSM_CONV+UNARY , 1
|
||||
qwen3next ,1 ,any ,ADD+ADD , 2
|
||||
qwen3next ,1 ,any ,GATED_DELTA_NET+CPY , 1
|
||||
qwen3next ,1 ,any ,MUL+ADD , 4
|
||||
qwen3next ,1 ,any ,RMS_NORM+MUL , 8
|
||||
qwen3next ,1 ,any ,RMS_NORM+SCALE , 2
|
||||
qwen3next ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
qwen3next ,1 ,any ,SSM_CONV+UNARY , 1
|
||||
qwen3tts ,0 ,any ,RMS_NORM+MUL , 9
|
||||
qwen3vl ,0 ,any ,RMS_NORM+MUL , 9
|
||||
qwen3vlmoe ,1 ,any ,MUL+ADD , 4
|
||||
qwen3vlmoe ,1 ,any ,RMS_NORM+MUL , 9
|
||||
qwen3vlmoe ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
qwen4exp ,0 ,any ,ADD+ADD+ADD , 2
|
||||
qwen4exp ,0 ,any ,GATED_DELTA_NET+CPY , 1
|
||||
qwen4exp ,0 ,any ,MUL+ADD , 4
|
||||
qwen4exp ,0 ,any ,RMS_NORM+MUL , 13
|
||||
qwen4exp ,0 ,any ,RMS_NORM+SCALE , 2
|
||||
qwen4exp ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
qwen4exp ,0 ,any ,SSM_CONV+UNARY , 1
|
||||
raon1 ,0 ,any ,ADD+ADD+ADD , 1
|
||||
raon1 ,0 ,any ,GATED_DELTA_NET+CPY , 1
|
||||
raon1 ,0 ,any ,MUL+ADD , 2
|
||||
raon1 ,0 ,any ,RMS_NORM+MUL , 8
|
||||
raon1 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV, 1
|
||||
refact ,0 ,any ,RMS_NORM+MUL , 5
|
||||
qwen4exp ,1 ,any ,ADD+ADD+ADD , 2
|
||||
qwen4exp ,1 ,any ,GATED_DELTA_NET+CPY , 1
|
||||
qwen4exp ,1 ,any ,MUL+ADD , 4
|
||||
qwen4exp ,1 ,any ,RMS_NORM+MUL , 13
|
||||
qwen4exp ,1 ,any ,RMS_NORM+SCALE , 2
|
||||
qwen4exp ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
qwen4exp ,1 ,any ,SSM_CONV+UNARY , 1
|
||||
raon1 ,1 ,any ,ADD+ADD+ADD , 1
|
||||
raon1 ,1 ,any ,GATED_DELTA_NET+CPY , 1
|
||||
raon1 ,1 ,any ,MUL+ADD , 2
|
||||
raon1 ,1 ,any ,RMS_NORM+MUL , 8
|
||||
raon1 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV, 1
|
||||
refact ,0 ,any ,RMS_NORM+MUL , 5
|
||||
refact ,1 ,any ,RMS_NORM+MUL , 5
|
||||
ricursive ,0 ,any ,RMS_NORM+MUL , 9
|
||||
ricursive ,0 ,any ,RMS_NORM+MUL+ADD , 4
|
||||
rnd1 ,0 ,any ,MUL+ADD , 4
|
||||
rnd1 ,0 ,any ,RMS_NORM+MUL , 9
|
||||
rnd1 ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
rnd1 ,1 ,any ,MUL+ADD , 4
|
||||
rnd1 ,1 ,any ,RMS_NORM+MUL , 9
|
||||
rnd1 ,1 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2
|
||||
seed_oss ,0 ,any ,RMS_NORM+MUL , 5
|
||||
smallthinker ,0 ,any ,MUL+ADD , 4
|
||||
smallthinker ,0 ,any ,RMS_NORM+MUL , 5
|
||||
smallthinker ,1 ,any ,MUL+ADD , 4
|
||||
smallthinker ,1 ,any ,RMS_NORM+MUL , 5
|
||||
smollm3 ,0 ,any ,RMS_NORM+MUL , 5
|
||||
spark2_5 ,0 ,any ,RMS_NORM+MUL , 5
|
||||
stablelm ,0 ,any ,NORM+MUL , 4
|
||||
@@ -356,14 +356,14 @@ stablelm ,0 ,any ,NORM+MUL+ADD , 5
|
||||
starcoder ,0 ,any ,NORM+MUL+ADD , 5
|
||||
starcoder2 ,0 ,any ,NORM+MUL+ADD , 5
|
||||
talkie ,0 ,any ,ADD+ADD , 2
|
||||
xing4_0 ,0 ,any ,ADD+ADD+ADD , 1
|
||||
xing4_0 ,0 ,any ,MUL+ADD , 2
|
||||
xing4_0 ,0 ,any ,RMS_NORM+MUL , 9
|
||||
xing4_0 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
xing4_0 ,1 ,any ,ADD+ADD+ADD , 1
|
||||
xing4_0 ,1 ,any ,MUL+ADD , 2
|
||||
xing4_0 ,1 ,any ,RMS_NORM+MUL , 9
|
||||
xing4_0 ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1
|
||||
xverse ,0 ,any ,RMS_NORM+MUL , 5
|
||||
zaya1 ,0 ,any ,RMS_NORM+MUL , 7
|
||||
zonos3 ,0 ,any ,GATED_DELTA_NET+CPY , 1
|
||||
zonos3 ,0 ,any ,MUL+ADD , 2
|
||||
zonos3 ,0 ,any ,RMS_NORM+MUL , 12
|
||||
zonos3 ,0 ,any ,RMS_NORM+SCALE , 2
|
||||
zonos3 ,0 ,any ,SSM_CONV+UNARY , 1
|
||||
zaya1 ,1 ,any ,RMS_NORM+MUL , 7
|
||||
zonos3 ,1 ,any ,GATED_DELTA_NET+CPY , 1
|
||||
zonos3 ,1 ,any ,MUL+ADD , 2
|
||||
zonos3 ,1 ,any ,RMS_NORM+MUL , 12
|
||||
zonos3 ,1 ,any ,RMS_NORM+SCALE , 2
|
||||
zonos3 ,1 ,any ,SSM_CONV+UNARY , 1
|
||||
|
||||
|
+389
-5
@@ -4834,6 +4834,297 @@ struct test_unary_scale_fusion : public test_case {
|
||||
// SNAKE activation fusion: y = x + sin(a*x)^2 * inv_b
|
||||
// CUDA backend matches the naive 5-op chain (mul, sin, sqr, mul, add)
|
||||
// and dispatches a single fused kernel.
|
||||
// the situ activation of the Inkling 2 experts on the halves of a merged gate_up, as build_moe_ffn builds it
|
||||
struct test_situ : public test_case {
|
||||
const std::array<int64_t, 3> ne; // n_ff, n_expert_used, n_tokens
|
||||
const float beta;
|
||||
const float lb;
|
||||
|
||||
std::string op_desc(ggml_tensor * t) override {
|
||||
GGML_UNUSED(t);
|
||||
return "SITU";
|
||||
}
|
||||
|
||||
bool run_whole_graph() override { return true; }
|
||||
|
||||
std::string vars() override {
|
||||
return VARS_TO_STR3(ne, beta, lb);
|
||||
}
|
||||
|
||||
test_situ(std::array<int64_t, 3> ne = {1152, 8, 1}, float beta = 4.0f, float lb = 25.0f) : ne(ne), beta(beta), lb(lb) {}
|
||||
|
||||
ggml_tensor * build_graph(ggml_context * ctx) override {
|
||||
ggml_tensor * gu = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, 2*ne[0], ne[1], ne[2]);
|
||||
ggml_set_name(gu, "gate_up");
|
||||
gu = ggml_scale(ctx, gu, 1.0f);
|
||||
|
||||
ggml_tensor * g = ggml_view_3d(ctx, gu, ne[0], ne[1], ne[2], gu->nb[1], gu->nb[2], 0);
|
||||
ggml_tensor * u = ggml_view_3d(ctx, gu, ne[0], ne[1], ne[2], gu->nb[1], gu->nb[2], ne[0]*gu->nb[0]);
|
||||
|
||||
ggml_tensor * act = ggml_scale(ctx, ggml_tanh(ctx, ggml_scale(ctx, g, 1.0f/beta)), beta);
|
||||
act = ggml_mul(ctx, act, ggml_sigmoid(ctx, g));
|
||||
u = ggml_scale(ctx, ggml_tanh(ctx, ggml_scale(ctx, u, 1.0f/lb)), lb);
|
||||
ggml_tensor * out = ggml_mul(ctx, act, u);
|
||||
ggml_set_name(out, "out");
|
||||
return out;
|
||||
}
|
||||
|
||||
void initialize_tensors(ggml_context * ctx) override {
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
|
||||
init_tensor_uniform(t, -40.0f, 40.0f);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// the row L2 clip of Inkling 2: [x*w ->] l2_norm(x, t)*t [-> *f with one f per token]
|
||||
struct test_l2_clip : public test_case {
|
||||
const std::array<int64_t, 4> ne;
|
||||
const bool with_w;
|
||||
const bool with_f;
|
||||
const float thr;
|
||||
|
||||
std::string op_desc(ggml_tensor * t) override {
|
||||
GGML_UNUSED(t);
|
||||
return "L2_CLIP";
|
||||
}
|
||||
|
||||
bool run_whole_graph() override { return true; }
|
||||
|
||||
std::string vars() override {
|
||||
return VARS_TO_STR4(ne, with_w, with_f, thr);
|
||||
}
|
||||
|
||||
test_l2_clip(std::array<int64_t, 4> ne = {128, 24, 3, 1}, bool with_w = true, bool with_f = false, float thr = 22.6f)
|
||||
: ne(ne), with_w(with_w), with_f(with_f), thr(thr) {}
|
||||
|
||||
ggml_tensor * build_graph(ggml_context * ctx) override {
|
||||
ggml_tensor * a = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne.data());
|
||||
ggml_set_name(a, "a");
|
||||
ggml_tensor * cur = ggml_scale(ctx, a, 1.0f);
|
||||
if (with_w) {
|
||||
ggml_tensor * w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, ne[0], ne[1]);
|
||||
ggml_set_name(w, "w");
|
||||
cur = ggml_mul(ctx, cur, w);
|
||||
}
|
||||
cur = ggml_scale(ctx, ggml_l2_norm(ctx, cur, thr), thr);
|
||||
if (with_f) {
|
||||
ggml_tensor * f = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 1, 1, ne[2], ne[3]);
|
||||
ggml_set_name(f, "f");
|
||||
cur = ggml_mul(ctx, cur, f);
|
||||
}
|
||||
ggml_set_name(cur, "out");
|
||||
return cur;
|
||||
}
|
||||
|
||||
void initialize_tensors(ggml_context * ctx) override {
|
||||
// rows with norms both below and above the threshold
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
|
||||
init_tensor_uniform(t, -4.0f, 4.0f);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// the causal short conv of Inkling 2 as convolve() builds it: CONCAT(past, cur^T), the state store (a CPY of the last
|
||||
// columns, or SET_ROWS of the windows of n_slots rollback slots), SSM_CONV, the optional input-dependent taps of H heads,
|
||||
// the residual ADD and SCALE, and an optional residual add after it
|
||||
struct test_short_conv : public test_case {
|
||||
const int64_t C, Ts, S, H, n_slots;
|
||||
const bool res;
|
||||
const int64_t K; // the conv width
|
||||
|
||||
std::vector<ggml_tensor *> verify;
|
||||
|
||||
std::string op_desc(ggml_tensor * t) override {
|
||||
GGML_UNUSED(t);
|
||||
return "SHORT_CONV";
|
||||
}
|
||||
|
||||
bool run_whole_graph() override { return true; }
|
||||
std::vector<ggml_tensor *> fusion_test_nodes() override { return verify; }
|
||||
|
||||
std::string vars() override {
|
||||
return VARS_TO_STR7(C, Ts, S, H, n_slots, res, K);
|
||||
}
|
||||
|
||||
test_short_conv(int64_t C = 1024, int64_t Ts = 1, int64_t S = 1, int64_t H = 0, int64_t n_slots = 0, bool res = false, int64_t K = 4)
|
||||
: C(C), Ts(Ts), S(S), H(H), n_slots(n_slots), res(res), K(K) {}
|
||||
|
||||
// the inputs only: the rollback windows are an overlapping view
|
||||
void initialize_tensors(ggml_context * ctx) override {
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
|
||||
if (t->op == GGML_OP_NONE && t->view_src == NULL) {
|
||||
init_tensor_uniform(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ggml_tensor * build_graph(ggml_context * ctx) override {
|
||||
verify.clear();
|
||||
const int64_t K1 = K - 1;
|
||||
const int64_t T = Ts*S;
|
||||
|
||||
ggml_tensor * hist = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, K1, C + 64, S);
|
||||
ggml_tensor * past = ggml_view_3d(ctx, hist, K1, C, S, hist->nb[1], hist->nb[2], 32*hist->nb[1]);
|
||||
ggml_tensor * cur = ggml_scale(ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, C, T), 0.5f);
|
||||
ggml_tensor * w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, K, C);
|
||||
ggml_set_name(hist, "hist");
|
||||
|
||||
ggml_tensor * dyn = nullptr;
|
||||
if (H) {
|
||||
dyn = ggml_scale(ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, K*H, T), 1.0f);
|
||||
if (gf) {
|
||||
ggml_build_forward_expand(gf, dyn);
|
||||
}
|
||||
}
|
||||
|
||||
const int64_t n_planes = std::max<int64_t>(1, n_slots);
|
||||
ggml_tensor * state = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, K1*(C + 64), S*n_planes);
|
||||
ggml_set_name(state, "state");
|
||||
const size_t row_size = state->nb[1];
|
||||
|
||||
ggml_tensor * x = ggml_concat(ctx, past, ggml_transpose(ctx, ggml_reshape_3d(ctx, cur, C, Ts, S)), 0);
|
||||
|
||||
ggml_tensor * st;
|
||||
if (n_slots == 0) {
|
||||
ggml_tensor * tail = ggml_view_3d(ctx, x, K1, C, S, x->nb[1], x->nb[2], Ts*sizeof(float));
|
||||
ggml_tensor * cell = ggml_view_2d(ctx, state, K1*C, S, row_size, 32*K1*sizeof(float));
|
||||
st = ggml_cpy(ctx, tail, cell);
|
||||
} else {
|
||||
const int64_t kw = std::min(Ts, n_slots);
|
||||
ggml_tensor * order = ggml_arange(ctx, 0.0f, (float) n_slots, 1.0f);
|
||||
order = ggml_cast(ctx, ggml_scale_bias(ctx, order, -1.0f, (float) (n_slots - 1)), GGML_TYPE_I32);
|
||||
order = ggml_view_1d(ctx, order, kw, (n_slots - kw)*sizeof(int32_t));
|
||||
ggml_tensor * windows = ggml_view_4d(ctx, x, K1, kw, C, S, sizeof(float), x->nb[1], x->nb[2], (Ts - (kw - 1))*sizeof(float));
|
||||
ggml_tensor * slots = ggml_view_4d(ctx, state, K1, n_slots, C, S, S*row_size, K1*sizeof(float), row_size, 32*K1*sizeof(float));
|
||||
st = ggml_set_rows(ctx, slots, windows, order);
|
||||
}
|
||||
if (gf) {
|
||||
ggml_build_forward_expand(gf, st);
|
||||
}
|
||||
verify.push_back(st);
|
||||
|
||||
ggml_tensor * out = ggml_reshape_2d(ctx, ggml_ssm_conv(ctx, x, w), C, T);
|
||||
if (dyn) {
|
||||
ggml_tensor * d3 = ggml_reshape_3d(ctx, dyn, K, H, T);
|
||||
for (int64_t lag = 0; lag < K; ++lag) {
|
||||
ggml_tensor * tap = ggml_view_3d(ctx, d3, 1, H, T, d3->nb[1], d3->nb[2], lag*d3->nb[0]);
|
||||
ggml_tensor * window = ggml_view_3d(ctx, x, Ts, C, S, x->nb[1], x->nb[2], (K1 - lag)*x->nb[0]);
|
||||
window = ggml_reshape_3d(ctx, ggml_cont(ctx, ggml_transpose(ctx, window)), C/H, H, T);
|
||||
out = ggml_add(ctx, out, ggml_reshape_2d(ctx, ggml_mul(ctx, window, tap), C, T));
|
||||
}
|
||||
}
|
||||
out = ggml_scale(ctx, ggml_add(ctx, cur, out), 1.0f/sqrtf((float) ((H ? 2 : 1)*K + 1)));
|
||||
if (res) {
|
||||
out = ggml_add(ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, C, T), out);
|
||||
}
|
||||
ggml_set_name(out, "out");
|
||||
verify.push_back(out);
|
||||
return out;
|
||||
}
|
||||
};
|
||||
|
||||
// the depth mix of Inkling 2 as mix() builds it: states = [stack; rms_norm(cur)], softmax of the scores against Q queries,
|
||||
// the weighted sum as [Q, n, T]; shared_norm: the norm of cur also has another use, so it is computed before the mix
|
||||
struct test_depth_mix : public test_case {
|
||||
const int64_t n, B, Q, T;
|
||||
const bool shared_norm;
|
||||
|
||||
std::vector<ggml_tensor *> verify;
|
||||
|
||||
std::string op_desc(ggml_tensor * t) override {
|
||||
GGML_UNUSED(t);
|
||||
return "DEPTH_MIX";
|
||||
}
|
||||
|
||||
bool run_whole_graph() override { return true; }
|
||||
std::vector<ggml_tensor *> fusion_test_nodes() override { return verify; }
|
||||
|
||||
std::string vars() override {
|
||||
return VARS_TO_STR5(n, B, Q, T, shared_norm);
|
||||
}
|
||||
|
||||
test_depth_mix(int64_t n = 2304, int64_t B = 8, int64_t Q = 1, int64_t T = 1, bool shared_norm = false)
|
||||
: n(n), B(B), Q(Q), T(T), shared_norm(shared_norm) {}
|
||||
|
||||
ggml_tensor * build_graph(ggml_context * ctx) override {
|
||||
verify.clear();
|
||||
ggml_tensor * stack = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n, B, T);
|
||||
ggml_tensor * cur = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n, T);
|
||||
ggml_tensor * query = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n, Q);
|
||||
ggml_set_name(stack, "stack");
|
||||
ggml_set_name(cur, "cur");
|
||||
|
||||
ggml_tensor * norm = ggml_rms_norm(ctx, ggml_reshape_3d(ctx, cur, n, 1, T), 1e-6f);
|
||||
if (shared_norm) {
|
||||
ggml_tensor * other = ggml_scale(ctx, norm, 2.0f);
|
||||
if (gf) {
|
||||
ggml_build_forward_expand(gf, other);
|
||||
}
|
||||
verify.push_back(other);
|
||||
}
|
||||
|
||||
ggml_tensor * states = ggml_concat(ctx, stack, norm, 1);
|
||||
ggml_tensor * queries = T == 1 ? query : ggml_repeat(ctx, query, ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n, Q, T));
|
||||
ggml_tensor * scores = ggml_soft_max_ext(ctx, ggml_mul_mat(ctx, states, queries), nullptr, 1.0f/sqrtf((float) n), 0.0f);
|
||||
ggml_tensor * out = ggml_mul_mat(ctx, scores, ggml_cont(ctx, ggml_transpose(ctx, states)));
|
||||
ggml_set_name(out, "out");
|
||||
verify.push_back(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
void initialize_tensors(ggml_context * ctx) override {
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
|
||||
init_tensor_uniform(t, -3.0f, 3.0f);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// the loop controller of Inkling 2 as control() builds it: one rms_norm of [cur; msg], the rank r down projection, the gain
|
||||
// and forget projections and (cur - tanh(forget)*cur) + tanh(gain)*msg
|
||||
struct test_loop_ctrl : public test_case {
|
||||
const int64_t n, r, T;
|
||||
|
||||
std::string op_desc(ggml_tensor * t) override {
|
||||
GGML_UNUSED(t);
|
||||
return "LOOP_CTRL";
|
||||
}
|
||||
|
||||
bool run_whole_graph() override { return true; }
|
||||
|
||||
std::string vars() override {
|
||||
return VARS_TO_STR3(n, r, T);
|
||||
}
|
||||
|
||||
test_loop_ctrl(int64_t n = 2304, int64_t r = 64, int64_t T = 1) : n(n), r(r), T(T) {}
|
||||
|
||||
ggml_tensor * build_graph(ggml_context * ctx) override {
|
||||
ggml_tensor * cur = ggml_scale(ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n, T), 1.0f);
|
||||
ggml_tensor * msg = ggml_scale(ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n, T), 1.0f);
|
||||
ggml_tensor * wd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 2*n, r);
|
||||
ggml_tensor * wg = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, r, n);
|
||||
ggml_tensor * wf = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, r, n);
|
||||
ggml_set_name(cur, "cur");
|
||||
ggml_set_name(msg, "msg");
|
||||
|
||||
ggml_tensor * gate = ggml_concat(ctx, ggml_reshape_3d(ctx, cur, n, 1, T), ggml_reshape_3d(ctx, msg, n, 1, T), 1);
|
||||
gate = ggml_reshape_2d(ctx, ggml_rms_norm(ctx, gate, 1e-6f), 2*n, T);
|
||||
gate = ggml_mul_mat(ctx, wd, gate);
|
||||
|
||||
ggml_tensor * gain = ggml_tanh(ctx, ggml_mul_mat(ctx, wg, gate));
|
||||
ggml_tensor * forget = ggml_tanh(ctx, ggml_mul_mat(ctx, wf, gate));
|
||||
|
||||
ggml_tensor * out = ggml_add(ctx, ggml_sub(ctx, cur, ggml_mul(ctx, forget, cur)), ggml_mul(ctx, gain, msg));
|
||||
ggml_set_name(out, "out");
|
||||
return out;
|
||||
}
|
||||
|
||||
void initialize_tensors(ggml_context * ctx) override {
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
|
||||
init_tensor_uniform(t, -0.5f, 0.5f);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
struct test_snake_fuse : public test_case {
|
||||
const ggml_type type;
|
||||
const std::array<int64_t, 4> ne; // [T, C, D2, D3]
|
||||
@@ -9012,19 +9303,25 @@ struct test_mul_mat_fusion : public test_case {
|
||||
const bool with_lane_scale;
|
||||
std::array<int64_t, 2> batch_dims;
|
||||
const bool skip; // set some ids to a negative value (only for use_id)
|
||||
const ggml_type type_b; // type of the input
|
||||
|
||||
test_mul_mat_fusion(ggml_type type, ggml_glu_op op, int64_t m, int64_t n, int64_t k,
|
||||
bool use_id = false, int n_mats = 1, int n_used = 1, bool b = false, bool with_bias = false, bool with_gate = true,
|
||||
bool with_lane_scale = false, std::array<int64_t, 2> batch_dims = {4, 2}, bool skip = false)
|
||||
bool with_lane_scale = false, std::array<int64_t, 2> batch_dims = {4, 2}, bool skip = false,
|
||||
ggml_type type_b = GGML_TYPE_F32)
|
||||
: type(type), glu_op(op), m(m), n(n), k(k), use_id(use_id), n_mats(n_mats), n_used(n_used), b(b), with_bias(with_bias),
|
||||
with_gate(with_gate), with_lane_scale(with_lane_scale), batch_dims(batch_dims), skip(skip) {
|
||||
with_gate(with_gate), with_lane_scale(with_lane_scale), batch_dims(batch_dims), skip(skip), type_b(type_b) {
|
||||
if (use_id) {
|
||||
GGML_ASSERT(n_used <= n_mats);
|
||||
}
|
||||
}
|
||||
|
||||
std::string vars() override {
|
||||
return VARS_TO_STR14(type, glu_op, m, n, k, use_id, n_mats, n_used, b, with_bias, with_gate, with_lane_scale, batch_dims, skip);
|
||||
std::string s = VARS_TO_STR14(type, glu_op, m, n, k, use_id, n_mats, n_used, b, with_bias, with_gate, with_lane_scale, batch_dims, skip);
|
||||
if (type_b != GGML_TYPE_F32) {
|
||||
s += "," + VAR_TO_STR(type_b);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
std::string op_desc(ggml_tensor * t) override {
|
||||
@@ -9078,7 +9375,7 @@ struct test_mul_mat_fusion : public test_case {
|
||||
std::array<int64_t, 4> ne = { k, m, channels, samples };
|
||||
std::array<int64_t, 4> ne0 = { k, n, channels, samples };
|
||||
|
||||
ggml_tensor * cur = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne.data());
|
||||
ggml_tensor * cur = ggml_new_tensor(ctx, type_b, 4, ne.data());
|
||||
ggml_tensor * gate = with_gate ? ggml_new_tensor(ctx, type, 4, ne0.data()) : nullptr;
|
||||
ggml_tensor * up = ggml_new_tensor(ctx, type, 4, ne0.data());
|
||||
|
||||
@@ -9128,7 +9425,7 @@ struct test_mul_mat_fusion : public test_case {
|
||||
ids = ggml_view_2d(ctx, ids, n_used, m, ids->nb[1], 0);
|
||||
}
|
||||
|
||||
ggml_tensor * cur = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, k, this->b ? 1 : n_used, m);
|
||||
ggml_tensor * cur = ggml_new_tensor_3d(ctx, type_b, k, this->b ? 1 : n_used, m);
|
||||
ggml_set_name(cur, "cur");
|
||||
|
||||
auto build_lane_up = [&]() {
|
||||
@@ -11740,6 +12037,47 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
|
||||
test_cases.emplace_back(new test_snake_fuse(type, { 64, 32, 2, 3})); // ne[2] > 1 and ne[3] > 1
|
||||
}
|
||||
|
||||
// the fused op chains of the Inkling 2 graph
|
||||
for (int64_t n_tokens : { 1, 3, 32 }) {
|
||||
test_cases.emplace_back(new test_situ({1152, 8, n_tokens}, 4.0f, 25.0f));
|
||||
}
|
||||
test_cases.emplace_back(new test_situ({64, 2, 5}, 2.0f, 10.0f));
|
||||
for (bool with_w : { false, true }) {
|
||||
for (bool with_f : { false, true }) {
|
||||
for (std::array<int64_t, 4> ne : std::initializer_list<std::array<int64_t, 4>>{ {128, 24, 1, 1}, {128, 4, 7, 1}, {16, 24, 3, 1}, {1500, 2, 3, 2} }) {
|
||||
test_cases.emplace_back(new test_l2_clip(ne, with_w, with_f, ne[0] == 16 ? 8.0f : 22.6f));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (int64_t H : { 0, 8 }) {
|
||||
for (int64_t n_slots : { 0, 4 }) {
|
||||
for (bool res : { false, true }) {
|
||||
for (int64_t Ts : { 1, 3, 5, 33 }) {
|
||||
for (int64_t S : { 1, 2 }) {
|
||||
test_cases.emplace_back(new test_short_conv(1024, Ts, S, H, n_slots, res));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (int64_t K : { 2, 3, 8 }) {
|
||||
test_cases.emplace_back(new test_short_conv(256, 5, 2, 4, 0, true, K));
|
||||
test_cases.emplace_back(new test_short_conv(256, 3, 1, 0, 6, false, K));
|
||||
}
|
||||
for (int64_t T : { 1, 3 }) {
|
||||
for (int64_t Q : { 1, 3, 4 }) {
|
||||
for (int64_t B : { 1, 3, 12 }) {
|
||||
test_cases.emplace_back(new test_depth_mix(2304, B, Q, T));
|
||||
}
|
||||
}
|
||||
test_cases.emplace_back(new test_depth_mix(2304, 5, 3, T, true));
|
||||
test_cases.emplace_back(new test_depth_mix(100, 2, 2, T));
|
||||
}
|
||||
for (int64_t T : { 1, 4, 8 }) {
|
||||
test_cases.emplace_back(new test_loop_ctrl(2304, 64, T));
|
||||
}
|
||||
test_cases.emplace_back(new test_loop_ctrl(256, 40, 3));
|
||||
|
||||
test_cases.emplace_back(new test_dsv4_hc_comb(1, 1));
|
||||
test_cases.emplace_back(new test_dsv4_hc_comb(17, 4));
|
||||
test_cases.emplace_back(new test_dsv4_hc_comb(257, 8));
|
||||
@@ -13364,6 +13702,44 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_BF16, 16, 1, 256, {3, 2}, {2, 2}));
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_BF16, 16, 8, 256, {1, 1}, {1, 1}));
|
||||
|
||||
// BF16 in src1 (activations): MMVQ, few-row MMQ, MMQ with each layout of the Q8_1 src1 and the FP4 src1,
|
||||
// cuBLAS for F16 weights, MMVF for BF16 weights and the transposed F32 vector
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_0, GGML_TYPE_BF16, 256, 1, 4096, {1, 1}, {1, 1}));
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q8_0, GGML_TYPE_BF16, 256, 8, 4096, {1, 1}, {1, 1}));
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 256, 8, 4096, {1, 1}, {1, 1}));
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q8_0, GGML_TYPE_BF16, 256, 64, 4096, {1, 1}, {1, 1}));
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 256, 64, 4096, {1, 1}, {1, 1}));
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q2_K, GGML_TYPE_BF16, 256, 64, 4096, {1, 1}, {1, 1}));
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_NVFP4, GGML_TYPE_BF16, 256, 64, 4096, {1, 1}, {1, 1}));
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_MXFP4, GGML_TYPE_BF16, 256, 64, 4096, {1, 1}, {1, 1}));
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F16, GGML_TYPE_BF16, 256, 1, 4096, {1, 1}, {1, 1}));
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_BF16, GGML_TYPE_BF16, 256, 1, 4096, {1, 1}, {1, 1}));
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F32, GGML_TYPE_BF16, 1, 16, 2048, {1, 1}, {1, 1}));
|
||||
// FP8 weights with more tokens than MMVF takes: src1 quantized to FP8 for cuBLASLt
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F8_E4M3, GGML_TYPE_BF16, 16, 16, 64, {1, 1}, {1, 1}));
|
||||
// BF16 src1 as a permuted view (rows 4*k values apart, channels k apart): MMVQ, few-row MMQ, MMQ with the Q8_1 and the FP4 src1,
|
||||
// FP8 on cuBLASLt, MMVF for BF16 and FP8 weights
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 16, 3, 256, {1, 1}, {4, 2}, {0, 2, 1, 3}));
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 64, 13, 4608, {1, 1}, {4, 2}, {0, 2, 1, 3}));
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 16, 64, 256, {1, 1}, {4, 2}, {0, 2, 1, 3}));
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_NVFP4, GGML_TYPE_BF16, 16, 64, 256, {1, 1}, {4, 2}, {0, 2, 1, 3}));
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F8_E4M3, GGML_TYPE_BF16, 16, 16, 64, {1, 1}, {4, 2}, {0, 2, 1, 3}));
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_BF16, GGML_TYPE_BF16, 16, 3, 256, {1, 1}, {4, 2}, {0, 2, 1, 3}));
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_F8_E4M3, GGML_TYPE_BF16, 16, 3, 256, {1, 1}, {4, 2}, {0, 2, 1, 3}));
|
||||
// MUL_MAT_ID: MMVQ, MMQ without and with a broadcast src1 (quantized once per token), MMVF with several tokens
|
||||
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 8, 2, true, 256, 1, 1024));
|
||||
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 8, 2, false, 256, 32, 1024));
|
||||
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 8, 2, true, 256, 32, 1024));
|
||||
// MUL_MAT_ID few-row MMQ (CUDA, from MMVQ's max. batch size up to 24 tokens)
|
||||
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_Q4_K, GGML_TYPE_BF16, 16, 4, false, 72, 13, 2048));
|
||||
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_NVFP4, GGML_TYPE_BF16, 8, 2, true, 256, 32, 1024));
|
||||
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_MXFP4, GGML_TYPE_BF16, 8, 2, true, 256, 32, 1024));
|
||||
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_F8_E4M3, GGML_TYPE_BF16, 8, 2, false, 256, 4, 1024));
|
||||
// float experts (MMF reads only an F32 src1): MMVF for BF16 experts up to 8 tokens, the fallback that sorts src1 by expert for F16
|
||||
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_BF16, GGML_TYPE_BF16, 8, 2, false, 256, 1, 1024));
|
||||
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_BF16, GGML_TYPE_BF16, 8, 2, false, 256, 4, 1024));
|
||||
test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_F16, GGML_TYPE_BF16, 8, 2, false, 256, 32, 1024));
|
||||
|
||||
// token-tile boundary coverage. With n_used == n_mats every token routes to every expert, so
|
||||
// each expert receives exactly n rows, with no dependence on the random draw. mul_mm_id is used
|
||||
// from 32 tokens up: n = 32, 33, 47, 48, 49 reach it, leaving a last tile of 32, 1, 15, 16 and
|
||||
@@ -14732,6 +15108,14 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
|
||||
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 9, 128, 2048, false, 1, 1, false, false, true, false, { 1, 1 }));
|
||||
// on DGX Spark also the expert gate and up matmuls at 8 tokens, instead of the fused MMVQ path
|
||||
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 8, 128, 2048, true, 16, 4, true));
|
||||
// BF16 input to MUL_MAT_ID: fused gate/up + GLU on MMVF (BF16 experts with more than 512 rows) and on MMQ (broadcast input)
|
||||
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_BF16, GGML_GLU_OP_SWIGLU, 1, 1024, 256, true, 16, 8, false, false, true, false, { 1, 1 }, false, GGML_TYPE_BF16));
|
||||
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 17, 5120, 256, true, 16, 8, true, false, true, false, { 4, 2 }, false, GGML_TYPE_BF16));
|
||||
// BF16 input: fused gate/up + GLU on MMVQ, MMVF and MMQ (NVFP4 with weight scales), and the NVFP4 weight scale on MMQ
|
||||
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_Q4_K, GGML_GLU_OP_SWIGLU, 1, 32, 256, false, 1, 1, false, false, true, false, { 1, 1 }, false, GGML_TYPE_BF16));
|
||||
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_BF16, GGML_GLU_OP_SWIGLU, 1, 32, 256, false, 1, 1, false, false, true, false, { 1, 1 }, false, GGML_TYPE_BF16));
|
||||
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 6912, 256, false, 1, 1, false, false, true, true, { 2, 3 }, false, GGML_TYPE_BF16));
|
||||
test_cases.emplace_back(new test_mul_mat_fusion(GGML_TYPE_NVFP4, GGML_GLU_OP_SWIGLU, 150, 2560, 256, false, 1, 1, false, false, false, true, { 1, 1 }, false, GGML_TYPE_BF16));
|
||||
|
||||
for (int64_t n_tok : {1, 4, 16}) {
|
||||
test_cases.emplace_back(new test_moe_router_prec_f32(128, 64, n_tok, 8));
|
||||
|
||||
@@ -377,7 +377,8 @@ int main(int argc, char ** argv) {
|
||||
|
||||
for (const auto & model_path : models) {
|
||||
const std::string arch = get_arch(model_path);
|
||||
const bool moe = arch.find("moe") != std::string::npos;
|
||||
const std::string stem = std::filesystem::path(model_path).stem().string();
|
||||
const bool moe = stem.size() >= 4 && stem.compare(stem.size() - 4, 4, "-moe") == 0;
|
||||
|
||||
llama_model_ptr model;
|
||||
llama_model_ptr model_cpu;
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
#include <memory>
|
||||
#include <random>
|
||||
#include <regex>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
@@ -176,6 +177,7 @@ static void usage(char ** argv) {
|
||||
LOG(" -o, --out <dir> Save generated test models to <dir> instead of running backend tests\n");
|
||||
LOG(" -v <N> Set log verbosity level\n");
|
||||
LOG(" -b, --backend <backend> Run only on the given backend device\n");
|
||||
LOG(" --rpc <endpoints> Add RPC servers (comma-separated host:port), must precede -b\n");
|
||||
LOG(" --kv-shift Check K-shift against a decode at the shifted positions (CPU only)\n");
|
||||
LOG(" -h, --help Show this help message\n\n");
|
||||
LOG("Examples:\n");
|
||||
@@ -1982,6 +1984,31 @@ static int test_kv_shift(const std::string & arch_filter, const size_t seed, con
|
||||
return n_failed == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
static bool add_rpc_devices(const std::string & endpoints) {
|
||||
ggml_backend_reg_t rpc_reg = ggml_backend_reg_by_name("RPC");
|
||||
if (rpc_reg == nullptr) {
|
||||
LOG_ERR("%s: RPC backend not available\n", __func__);
|
||||
return false;
|
||||
}
|
||||
typedef ggml_backend_reg_t (*add_server_t)(const char * endpoint);
|
||||
auto add_server = (add_server_t) ggml_backend_reg_get_proc_address(rpc_reg, "ggml_backend_rpc_add_server");
|
||||
if (add_server == nullptr) {
|
||||
LOG_ERR("%s: RPC backend has no ggml_backend_rpc_add_server\n", __func__);
|
||||
return false;
|
||||
}
|
||||
std::stringstream ss(endpoints);
|
||||
std::string endpoint;
|
||||
while (std::getline(ss, endpoint, ',')) {
|
||||
ggml_backend_reg_t reg = add_server(endpoint.c_str());
|
||||
if (reg == nullptr) {
|
||||
LOG_ERR("%s: failed to connect to RPC server %s\n", __func__, endpoint.c_str());
|
||||
return false;
|
||||
}
|
||||
ggml_backend_register(reg);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int main(int argc, char ** argv) {
|
||||
// init the logger at max verbosity. filter with a custom callback respecting the user-configure verbosity
|
||||
common_log_set_verbosity_thold(LOG_LEVEL_DEBUG);
|
||||
@@ -2063,6 +2090,16 @@ int main(int argc, char ** argv) {
|
||||
usage(argv);
|
||||
return 1;
|
||||
}
|
||||
} else if (strcmp(argv[i], "--rpc") == 0) {
|
||||
if (i + 1 < argc) {
|
||||
// must precede -b so that the RPC devices can be selected by name
|
||||
if (!add_rpc_devices(argv[++i])) {
|
||||
return 1;
|
||||
}
|
||||
} else {
|
||||
usage(argv);
|
||||
return 1;
|
||||
}
|
||||
} else if (strcmp(argv[i], "--kv-shift") == 0) {
|
||||
kv_shift = true;
|
||||
} else {
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <clocale>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
|
||||
@@ -2671,6 +2671,12 @@ You can specify default preferences for Llama Chat using `--ui-config <JSON conf
|
||||
./llama-server -m model.gguf --ui-config '{"pasteLongTextToFileLen": 0, "renderUserContentAsMarkdown": true}'
|
||||
```
|
||||
|
||||
You can also set the DPI used when parsing a PDF as images (default 108), e.g. 216 for dense tables:
|
||||
|
||||
```bash
|
||||
./llama-server -m model.gguf --ui-config '{"pdfAsImage": true, "pdfDpi": 216}'
|
||||
```
|
||||
|
||||
> **Note:** The old flags `--webui-config` and `--webui-config-file` are deprecated but still work as aliases.
|
||||
|
||||
You may find available preferences in [settings-keys.ts](../ui/src/lib/constants/settings-keys.ts).
|
||||
|
||||
+6
-2
@@ -7,7 +7,8 @@ ui/
|
||||
├── lib/
|
||||
│ ├── ui/ @ggml-org/llama-ui: design tokens, fonts, surfaces and components
|
||||
│ ├── voice/ @ggml-org/llama-voice: microphone capture, transcription and dictation
|
||||
│ └── harness/ @ggml-org/llama-harness: the agentic loop, headless
|
||||
│ ├── harness/ @ggml-org/llama-harness: the agentic loop, headless
|
||||
│ └── demo/ @ggml-org/llama-demo: scripted demo videos for PRs and docs
|
||||
└── apps/
|
||||
└── chat/ Llama Chat, the chat app that llama-server serves
|
||||
```
|
||||
@@ -20,12 +21,15 @@ ui/
|
||||
(`@ggml-org/llama-voice/svelte`). Apps in this repo compile its sources too. It is not published to npm yet.
|
||||
- [`lib/harness`](lib/harness/README.md) is the agentic loop: plain TypeScript with no UI and no dependencies. An app
|
||||
gives it an inference client and tools, and reads its events.
|
||||
- [`lib/demo`](lib/demo/README.md) records scripted demo videos of the apps for PRs and docs, and renders them on the
|
||||
Llama brand. It is Node TypeScript that an app adds as a local `file:` dependency and imports by name, with the app's own
|
||||
Playwright; it is private, not published to npm.
|
||||
- [`apps/chat`](apps/chat/README.md) talks to llama-server, stores conversations and runs the agentic loop through the
|
||||
harness. CMake builds it into llama-server (see `scripts/ui-assets.cmake`), and it is published to npm as
|
||||
`@ggml-org/llama-chat` (with `llama-chat` as its short name), so `npx llama-chat` runs it against any llama-server.
|
||||
|
||||
Each folder is its own npm package with its own `package-lock.json`: run `npm ci` in the one you work on. Building,
|
||||
checking and testing `apps/chat` needs no install in `lib/ui`, `lib/voice` or `lib/harness`.
|
||||
checking and testing `apps/chat` needs no install in `lib/ui`, `lib/voice`, `lib/harness` or `lib/demo`.
|
||||
|
||||
The split between library and app is not finished. Llama Chat takes its tokens, fonts, surfaces and base components
|
||||
from `lib/ui`, but still has its own versions of what the library holds above those (ActionIcon, SearchInput, Logo,
|
||||
|
||||
@@ -17,7 +17,16 @@ VITE_PUBLIC_SERVER_ORIGIN='http://localhost:8033'
|
||||
# DEMO_SERVER_ORIGIN='http://localhost:9931'
|
||||
# DEMO_LLAMA_SERVER='../../../build/bin/llama-server'
|
||||
# DEMO_COLOR_SCHEME='light'
|
||||
# Also start a Storybook for story demos: ui (Llama UI) or chat (Llama Chat)
|
||||
# DEMO_STORYBOOK='ui'
|
||||
# DEMO_STORYBOOK_PORT='6007'
|
||||
# Device pixel ratio demos render and record at (1440x900 viewport)
|
||||
# DEMO_SCALE='2'
|
||||
# 0 records the plain screencast instead of the branded render
|
||||
# DEMO_POLISH='1'
|
||||
# Ground of the render: day | night | light | dark | sand (default: day, night for a dark recording)
|
||||
# DEMO_POLISH_GROUND='day'
|
||||
# A Llama logo card: start | end | both (default: none)
|
||||
# DEMO_POLISH_LOGO='end'
|
||||
# Longer side of the GIF preview, in pixels; it shrinks further to stay under 5 MB
|
||||
# DEMO_PREVIEW_WIDTH='800'
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
These add to the repository's [AGENTS.md](../../../AGENTS.md) for work in `ui/apps/chat`: **Llama Chat**, the chat client that llama-server bundles. **Llama UI**, the library, is `ui/lib/ui` (`@ggml-org/llama-ui`): Chat imports its tokens, fonts and base components from there (`@ggml-org/llama-ui/ui/<name>`) and keeps no copy of them. `DESIGN.md` and the Storybook live here; the brand book, `BRAND.md`, and the brand and communications pages are in [ggml-org/llama-brand](https://github.com/ggml-org/llama-brand), with their own Storybook. The agentic loop is `ui/lib/harness` (`@ggml-org/llama-harness`).
|
||||
|
||||
- **Design:** [DESIGN.md](DESIGN.md) holds the tokens, roles and rules, written for agents. Follow it for anything visual. Its token sections (`colors`, `typography`, `rounded`) are generated from the CSS with `npm run design:tokens`, and CI checks they are current; the rest is written by hand, and when it and the CSS disagree, the CSS wins and DESIGN.md is updated.
|
||||
- **Demos, checks and docs media:** [skills/ui-demo](../../../skills/ui-demo/SKILL.md) records a PR's demo video, turns its flow into an e2e check and captures docs videos and screenshots, for Llama Chat and Llama UI alike.
|
||||
- **Stories:** a story lives with the code it shows. Llama UI's (its foundations, base components, app components and Model UI) are in `ui/lib/ui/tests/stories`, titled `Llama UI/...`, and run as the library's tests; this app's Storybook shows them too. Llama Chat's are in `tests/stories/<area>`, one folder per `src/lib/components/app/<area>` (`chat/` has one per Chat folder), titled `Llama Chat/<Area>/<Component>`. How the app works on a phone (the sidebar's keys, the sheets and the pages each pushes) is written up in `tests/stories/mobile`, titled `Llama Chat/Mobile/Flows`: update it when a sheet gains or loses a page. An accessibility story sits next to its component's, as `<Component>.a11y.stories.svelte`, titled `.../<Component>/Accessibility`. The story helpers both Storybooks use (the Editorial the prose pages are set in, `StateGallery`) live with the library's stories and are imported here as `$llama-ui-stories/...`; reuse them rather than copying them here.
|
||||
- **Releases:** `@ggml-org/llama-chat` and `@ggml-org/llama-ui` are versioned by hand and published by CI when a new version reaches `master` (see [Releases](../../README.md#releases)). Bump a version only when asked to release, never as a side effect of a change; Chat's version and its alias's (`alias/package.json`) always move together.
|
||||
- **Components:** the `SKILL.md` next to a component folder (such as [src/lib/components/app/SKILL.md](src/lib/components/app/SKILL.md)) holds that folder's conventions.
|
||||
|
||||
+31
-105
@@ -1,57 +1,50 @@
|
||||
# Demo videos
|
||||
# Llama Chat demo videos
|
||||
|
||||
Scripted Playwright walkthroughs of the UI, exported as mp4 with an animated GIF preview, for pull requests and documentation. The harness lives here; the demo scripts don't:
|
||||
Llama Chat's fixtures for the demo harness in [`ui/lib/demo`](../../../lib/demo/README.md), which records, renders and publishes the videos. Setup, PR and docs recording, the `demo.*` API and the render are described there; this folder sets the scene for Chat.
|
||||
|
||||
- **PR demos** live in the PR description, as a `ts demo` code block.
|
||||
- **Docs demos** live in the storage target, under `scripts/docs/`.
|
||||
|
||||
```
|
||||
```text
|
||||
demo/
|
||||
├── cli.ts demo:pr, demo:docs and demo:traces
|
||||
├── storage.ts storage targets (hf://, file://)
|
||||
├── helpers.ts `test` with a `demo` fixture: cursor, captions, human-like timing
|
||||
├── recorder.ts screencast recording and mp4 export
|
||||
├── fixtures/ fixture MCP servers, seeded settings and demo conversations
|
||||
└── videos/ output (git-ignored)
|
||||
├── cli.ts demo:pr, demo:docs and demo:traces
|
||||
├── helpers.ts `test` with Chat's fixtures and the `demo` fixture
|
||||
├── playwright.config.ts the servers: fixture MCP servers, llama-server, vite and Storybook
|
||||
├── fixtures/ fixture MCP servers, seeded settings, demo conversations, a mocked llama-server
|
||||
└── videos/ output (git-ignored)
|
||||
```
|
||||
|
||||
## Setup
|
||||
| Command | Does |
|
||||
| ------------------------------------ | ----------------------------------------------------------------- |
|
||||
| `npm run demo:record -- demo/<name>` | records `demo/<name>.demo.ts` (git-ignored) into `demo/videos/` |
|
||||
| `npm run demo:pr -- <number>` | records the PR's `ts demo` block and writes its `## Demo` section |
|
||||
| `npm run demo:docs` | records the docs scripts from `DEMO_STORAGE` |
|
||||
| `npm run demo:traces` | writes the built-in traces to `demo/traces/`, and pushes them |
|
||||
| `npm run demo:codegen` | opens Playwright codegen against `:5180` for a first draft |
|
||||
|
||||
### Tools
|
||||
Settings come from `ui/apps/chat/.env` (see `.env.example`).
|
||||
|
||||
| Tool | Used for |
|
||||
| ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Node 22.18+ | runs `demo/cli.ts` directly (TypeScript type stripping) |
|
||||
| `npx playwright install chromium` | the browser demos record in, with its sandbox on |
|
||||
| `ffmpeg` | mp4 encoding and the GIF preview |
|
||||
| `gh`, logged in | reads the PR description and writes the `## Demo` section, so you need edit rights on the PR |
|
||||
| `hf`, logged in with a write token (`hf auth login`) | uploads to the bucket and the traces dataset |
|
||||
| `llama-server` | `build/bin/llama-server`, or one already running at `DEMO_SERVER_ORIGIN` (default `:9931`). It runs in router mode, so demos can pick any model in the local cache; scripts that send messages need at least one. |
|
||||
## Setting the scene
|
||||
|
||||
`gh` is only needed for `demo:pr`, and `hf` only with the bucket or dataset below. Without them, the video stays in `demo/videos/`.
|
||||
Scripts get `test` and `expect` from `helpers.ts` without importing them. Use `test.use({ settings, startPath })` to seed other settings or start on another route, and `chats: <n>` to add empty conversations to the library.
|
||||
|
||||
Videos are recorded through Chromium's screencast at `DEMO_SCALE` (2x by default, so 2880x1800) and 60 fps, starting once the page has settled.
|
||||
### A mocked llama-server
|
||||
|
||||
### Hugging Face bucket (videos, previews, scripts)
|
||||
`test.use({ mockServer: { models: ['org/Model-GGUF:Q4_K_M'], reply: 'A **Markdown** reply' } })` answers llama-server's endpoints in the browser (`fixtures/llama-server.ts`): the model list, props, model loading, tools and a streamed reply. Nothing reaches the server and no model loads, so a demo that sends a message looks the same on every machine. `tests/e2e` checks call `mockLlamaServer(page)` directly, since the e2e build runs without a server.
|
||||
|
||||
The bucket must be public, since GitHub loads the preview from it:
|
||||
### Storybook stories
|
||||
|
||||
`test.use({ story: 'ui-forms-switch--default' })` records a Storybook story (the id from its `?path=/story/<id>` URL) instead of Llama Chat, from the Storybook that `DEMO_STORYBOOK` adds to the servers: `ui` for Llama UI (`ui/lib/ui`), `chat` for Llama Chat's. It runs on `DEMO_STORYBOOK_PORT` (default `:6007`). A small component reads better at a smaller `viewport` than zoomed in.
|
||||
|
||||
```bash
|
||||
hf buckets create <owner>/llama-ui-demos
|
||||
DEMO_STORYBOOK=ui npm run demo:record -- demo/<name>
|
||||
```
|
||||
|
||||
Then set it in `ui/apps/chat/.env` (see `.env.example`):
|
||||
### Conversations
|
||||
|
||||
```bash
|
||||
DEMO_STORAGE='hf://buckets/<owner>/llama-ui-demos'
|
||||
DEMO_STORAGE_PUBLIC_URL='https://huggingface.co/buckets/<owner>/llama-ui-demos/resolve'
|
||||
```
|
||||
Demos that need existing chats import them with `test.use({ traces: ['long-chat'] })`, through Settings > Data before the video starts. Traces use the export format (llama.app JSONL), so the Hub shows them as Llama traces:
|
||||
|
||||
Layout: `videos/pr/<number>/<sha>.{mp4,gif,demo.ts}`, `videos/docs/<name>.{mp4,gif}` and `scripts/docs/*.demo.ts` (the docs scripts). Without `DEMO_STORAGE_PUBLIC_URL`, videos are uploaded but not linked in the PR. `DEMO_STORAGE='file:///some/dir'` stores them in a local folder instead.
|
||||
- `fixtures/traces.ts` generates the built-in ones: `long-chat` (36 tall exchanges) and `agentic-debugging` (long reasoning, shell output and code blocks).
|
||||
- Any other name is downloaded as `<name>.jsonl` from `DEMO_TRACES_DATASET`, e.g. an exported conversation uploaded there.
|
||||
|
||||
### Hugging Face dataset (conversations, optional)
|
||||
|
||||
Only needed for demos that import conversations other than the built-in ones, or to publish the built-in ones with `npm run demo:traces`. It can be private: it is read with your `hf` login.
|
||||
The dataset is only needed for other conversations, or to publish the built-in ones with `npm run demo:traces`. It can be private: it is read with your `hf` login.
|
||||
|
||||
```bash
|
||||
hf repos create <owner>/llama-ui-demo-traces --repo-type dataset --private
|
||||
@@ -61,73 +54,6 @@ hf repos create <owner>/llama-ui-demo-traces --repo-type dataset --private
|
||||
DEMO_TRACES_DATASET='<owner>/llama-ui-demo-traces'
|
||||
```
|
||||
|
||||
### Other storage
|
||||
## Servers
|
||||
|
||||
Only Hugging Face buckets and `file://` folders are supported for now. S3, R2 or similar would be one more class in `storage.ts` (`upload` and `downloadDir`) plus the matching `DEMO_STORAGE_PUBLIC_URL`.
|
||||
|
||||
## Recording a pull request
|
||||
|
||||
Add the script to the PR description:
|
||||
|
||||
````md
|
||||
<details>
|
||||
<summary>Demo script</summary>
|
||||
|
||||
```ts demo
|
||||
test('demo', async ({ demo, page }) => {
|
||||
await demo.click(page.getByRole('button', { exact: true, name: 'Settings' }));
|
||||
await demo.caption('What this shows');
|
||||
});
|
||||
```
|
||||
|
||||
</details>
|
||||
````
|
||||
|
||||
Then run:
|
||||
|
||||
```bash
|
||||
npm run demo:pr -- 31303
|
||||
```
|
||||
|
||||
A PR by someone else runs its code and demo script on your machine, with your `gh` and `hf` logins, so `demo:pr` refuses it until you've read its diff and demo block and pass the head commit you read: `npm run demo:pr -- 31303 --trust <sha>`. If the PR gets new commits, it refuses again.
|
||||
|
||||
It checks out the PR head in a temporary worktree, records the script against it, uploads `videos/pr/<number>/<sha>.{mp4,gif,demo.ts}` and adds or updates a `## Demo` section in the PR description with the preview linking to the video.
|
||||
|
||||
A large PR can show its changes in several shorter videos: each `test()` in the block is recorded as its own video (`<sha>-1.mp4`, `<sha>-2.mp4`, ...), and the `## Demo` section shows their previews in a table, each headed by its test's title: up to four portrait (phone) videos to a row, or two landscape ones. Helpers and `test.use` at the top of the block are shared by all of them.
|
||||
|
||||
````ts
|
||||
test('Header and safe areas', async ({ demo, page }) => {
|
||||
// ...
|
||||
});
|
||||
|
||||
test('Sidebar gestures', async ({ demo, page }) => {
|
||||
// ...
|
||||
});
|
||||
``` GitHub has no API for attachments, so for an inline player drag `demo/videos/pr-<number>.mp4` into the description instead.
|
||||
|
||||
## Recording docs
|
||||
|
||||
```bash
|
||||
npm run demo:docs
|
||||
````
|
||||
|
||||
Records every `scripts/docs/*.demo.ts` from the storage target and uploads `videos/docs/<name>.{mp4,gif}`.
|
||||
|
||||
## Writing a demo
|
||||
|
||||
Scripts get `test` and `expect` from `helpers.ts` without importing them. `demo.click`, `demo.hover` and `demo.type` glide a visible cursor to the target before acting, with timing varied like a person's (seeded per demo, so re-takes match); `demo.scroll` turns the mouse wheel over a target; `demo.zoom` pinches in on a control or a point to show a detail too small to read in the frame, holds, and pinches back out (with the fingertips drawn on a touch device); `demo.caption` shows a caption at the top of the frame. For voice input, `demo.microphone()` gives the page a microphone that hears nothing but `demo.speak(text)`, which reads the text in a synthetic voice (macOS `say`) and shows it as a caption, since the video has no sound. Use `test.use({ settings, startPath })` to seed other settings or start on another route.
|
||||
|
||||
## Conversations
|
||||
|
||||
Demos that need existing chats import them with `test.use({ traces: ['long-chat'] })`, through Settings > Import/Export before the video starts. Traces use the export format (llama.app JSONL), so the Hub shows them as Llama traces:
|
||||
|
||||
- `fixtures/traces.ts` generates the built-in ones: `long-chat` (36 tall exchanges) and `agentic-debugging` (long reasoning, shell output and code blocks).
|
||||
- Any other name is downloaded as `<name>.jsonl` from `DEMO_TRACES_DATASET`, e.g. an exported conversation uploaded there.
|
||||
|
||||
`npm run demo:traces` writes the built-in traces to `demo/traces/` and pushes them to `DEMO_TRACES_DATASET`.
|
||||
|
||||
## Trying a script locally
|
||||
|
||||
To try a script locally, put it in `demo/` as `<name>.demo.ts`, importing from `./helpers.ts`, and run `npm run demo:record -- demo/<name>`. `npm run demo:codegen` opens Playwright codegen against `:5180` for a first draft.
|
||||
|
||||
The config starts, or reuses when already running, the fixture MCP servers on `:8765`, `llama-server` on `:9931` (router mode, `--tools all`) and the UI's vite dev server.
|
||||
The config starts, or reuses when already running, the fixture MCP servers on `:8765`, `llama-server` on `:9931` (`build/bin/llama-server` in router mode with `--tools all`, so demos can pick any model in the local cache), the UI's vite dev server and, with `DEMO_STORYBOOK`, a Storybook. Scripts that send messages to the real server need at least one model; `mockServer` needs none.
|
||||
|
||||
+11
-361
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Records demo videos for pull requests and docs.
|
||||
* Records Llama Chat's demo videos with the harness in ui/lib/demo:
|
||||
*
|
||||
* node demo/cli.ts pr <number> record the ```ts demo block from a PR description, a video per test
|
||||
* (--trust <sha> to record someone else's PR at that head commit)
|
||||
@@ -10,357 +10,13 @@
|
||||
*/
|
||||
|
||||
import { DEMO_TRACES, generateTrace } from './fixtures/traces.ts';
|
||||
import { type DemoStorage, getDemoStorage, getPublicUrl } from './storage.ts';
|
||||
import { runDemoCli } from '@ggml-org/llama-demo/cli';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
symlinkSync,
|
||||
writeFileSync
|
||||
} from 'node:fs';
|
||||
import { createServer } from 'node:net';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { basename, join, relative, resolve } from 'node:path';
|
||||
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { join, resolve } from 'node:path';
|
||||
|
||||
const DEMO_DIR = import.meta.dirname;
|
||||
const UI_DIR = resolve(DEMO_DIR, '..');
|
||||
const RUNS_DIR = join(DEMO_DIR, '.runs');
|
||||
const VIDEOS_DIR = join(DEMO_DIR, 'videos');
|
||||
const TRACES_DIR = join(DEMO_DIR, 'traces');
|
||||
const DEMO_BLOCK = /```(?:ts|typescript)[ \t]+demo[ \t]*\r?\n([\s\S]*?)```/;
|
||||
const HELPERS_IMPORT = /^import\s[^;]*from\s+['"][^'"]*helpers(?:\.ts)?['"];?\s*$/gm;
|
||||
const SECTION_START = '<!-- demo:start -->';
|
||||
const SECTION_END = '<!-- demo:end -->';
|
||||
/** GitHub's image proxy refuses larger images, so a bigger preview shows as a broken image. */
|
||||
const PREVIEW_MAX_BYTES = 5 * 1024 * 1024;
|
||||
const envFile = join(UI_DIR, '.env');
|
||||
|
||||
if (existsSync(envFile)) process.loadEnvFile(envFile);
|
||||
|
||||
const REPO = process.env.DEMO_GITHUB_REPO ?? 'ggml-org/llama.cpp';
|
||||
|
||||
function run(
|
||||
cmd: string,
|
||||
args: string[],
|
||||
opts: { cwd?: string; env?: NodeJS.ProcessEnv } = {}
|
||||
): string {
|
||||
return execFileSync(cmd, args, {
|
||||
cwd: opts.cwd ?? UI_DIR,
|
||||
encoding: 'utf8',
|
||||
env: opts.env
|
||||
}).trim();
|
||||
}
|
||||
|
||||
/** Writes a demo script into .runs/, importing the harness helpers. */
|
||||
function writeDemoScript(name: string, source: string): string {
|
||||
const file = join(RUNS_DIR, `${name}.demo.ts`);
|
||||
const helpers = relative(RUNS_DIR, join(DEMO_DIR, 'helpers.ts'));
|
||||
const body = source.replace(HELPERS_IMPORT, '').trim();
|
||||
|
||||
mkdirSync(RUNS_DIR, { recursive: true });
|
||||
writeFileSync(file, `import { expect, test } from './${helpers}';\n\n${body}\n`);
|
||||
|
||||
return file;
|
||||
}
|
||||
|
||||
async function freePort(): Promise<number> {
|
||||
return new Promise((done, fail) => {
|
||||
const server = createServer();
|
||||
|
||||
server.once('error', fail);
|
||||
server.listen(0, () => {
|
||||
const { port } = server.address() as { port: number };
|
||||
|
||||
server.close(() => done(port));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** A video recorded from one `test()` of a script. */
|
||||
interface Video {
|
||||
mp4: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
/** Records the given scripts; returns a video for each of their tests, in order. */
|
||||
async function record(scripts: string[], uiDir = UI_DIR): Promise<Video[]> {
|
||||
const port = await freePort();
|
||||
const manifests = scripts.map((s) => join(VIDEOS_DIR, `${basename(s, '.demo.ts')}.videos.jsonl`));
|
||||
|
||||
for (const manifest of manifests) rmSync(manifest, { force: true });
|
||||
|
||||
execFileSync(
|
||||
'npx',
|
||||
[
|
||||
'playwright',
|
||||
'test',
|
||||
'--config=demo/playwright.config.ts',
|
||||
...scripts.map((s) => relative(UI_DIR, s))
|
||||
],
|
||||
{
|
||||
cwd: UI_DIR,
|
||||
env: { ...process.env, DEMO_UI_DIR: uiDir, DEMO_UI_PORT: String(port) },
|
||||
stdio: 'inherit'
|
||||
}
|
||||
);
|
||||
|
||||
// helpers.ts lists each video it encodes in the script's manifest
|
||||
return manifests.flatMap((manifest) =>
|
||||
readFileSync(manifest, 'utf8')
|
||||
.trim()
|
||||
.split('\n')
|
||||
.map((line) => JSON.parse(line) as Video)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Animated GIF preview that GitHub renders inline, its longer side DEMO_PREVIEW_WIDTH (so a
|
||||
* phone's portrait video is that tall), shrunk until it fits under PREVIEW_MAX_BYTES.
|
||||
*/
|
||||
function makePreview(mp4: string): string {
|
||||
const gif = mp4.replace(/\.mp4$/, '.gif');
|
||||
|
||||
for (let side = Number(process.env.DEMO_PREVIEW_WIDTH ?? 800); ; side = Math.round(side * 0.8)) {
|
||||
execFileSync('ffmpeg', [
|
||||
'-y',
|
||||
'-loglevel',
|
||||
'error',
|
||||
'-i',
|
||||
mp4,
|
||||
'-vf',
|
||||
`fps=10,scale='if(gt(iw,ih),${side},-2)':'if(gt(iw,ih),-2,${side})':flags=lanczos,split[a][b];[a]palettegen=stats_mode=diff[p];[b][p]paletteuse=dither=bayer:bayer_scale=5:diff_mode=rectangle`,
|
||||
'-loop',
|
||||
'0',
|
||||
gif
|
||||
]);
|
||||
|
||||
if (statSync(gif).size <= PREVIEW_MAX_BYTES || side < 320) return gif;
|
||||
}
|
||||
}
|
||||
|
||||
function upload(storage: DemoStorage, files: Record<string, string>): void {
|
||||
for (const [key, file] of Object.entries(files)) {
|
||||
storage.upload(file, key);
|
||||
console.log(`uploaded ${key}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Public URL with a content hash, so a re-recorded file at the same key gets a new
|
||||
* URL: GitHub's image proxy caches previews by URL.
|
||||
*/
|
||||
function versionedUrl(key: string, file: string): null | string {
|
||||
const url = getPublicUrl(key);
|
||||
const version = createHash('sha1').update(readFileSync(file)).digest('hex').slice(0, 10);
|
||||
|
||||
return url && `${url}?v=${version}`;
|
||||
}
|
||||
|
||||
/** Whether a video is taller than wide, like a phone's. */
|
||||
function isPortrait(mp4: string): boolean {
|
||||
const [width, height] = run('ffprobe', [
|
||||
'-v',
|
||||
'error',
|
||||
'-select_streams',
|
||||
'v:0',
|
||||
'-show_entries',
|
||||
'stream=width,height',
|
||||
'-of',
|
||||
'csv=p=0',
|
||||
mp4
|
||||
])
|
||||
.split(',')
|
||||
.map(Number);
|
||||
|
||||
return height > width;
|
||||
}
|
||||
|
||||
/**
|
||||
* One preview, or a table of them when the script has several tests, each headed by its
|
||||
* test's title: up to four portrait videos to a row, or two landscape ones, so each stays
|
||||
* large enough to read.
|
||||
*/
|
||||
function demoSection(
|
||||
links: { gif: string; mp4: string; title: string }[],
|
||||
sha: string,
|
||||
columns: number
|
||||
): string {
|
||||
const preview = ({ gif, mp4, title }: (typeof links)[number]) =>
|
||||
`[![${title.replace(/[[\]|]/g, '')}](${gif})](${mp4})`;
|
||||
const cell = (text: string) => text.replace(/\|/g, '\\|');
|
||||
const rows = Array.from({ length: Math.ceil(links.length / columns) }, (_, i) =>
|
||||
links.slice(i * columns, (i + 1) * columns)
|
||||
);
|
||||
const pad = (cells: string[]) => [...cells, ...Array(columns - cells.length).fill(' ')];
|
||||
const body =
|
||||
links.length === 1
|
||||
? [preview({ ...links[0], title: 'Demo' })]
|
||||
: rows.flatMap((row, i) => [
|
||||
// a table has one header row, so later rows title their videos in bold
|
||||
`| ${pad(row.map((l) => (i === 0 ? cell(l.title) : `**${cell(l.title)}**`))).join(' | ')} |`,
|
||||
...(i === 0 ? [`|${Array(columns).fill('---').join('|')}|`] : []),
|
||||
`| ${pad(row.map(preview)).join(' | ')} |`
|
||||
]);
|
||||
const note =
|
||||
links.length === 1 ? 'the preview for the full video' : 'a preview for its full video';
|
||||
|
||||
return [
|
||||
SECTION_START,
|
||||
...body,
|
||||
'',
|
||||
`Recorded at ${sha.slice(0, 10)}; click ${note}.`,
|
||||
SECTION_END
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
/** Replaces the managed demo section, or adds a `## Demo` section before the details. */
|
||||
function withDemoSection(body: string, section: string): string {
|
||||
const start = body.indexOf(SECTION_START);
|
||||
const end = body.indexOf(SECTION_END);
|
||||
|
||||
if (start !== -1 && end > start) {
|
||||
return body.slice(0, start) + section + body.slice(end + SECTION_END.length);
|
||||
}
|
||||
|
||||
const block = `## Demo\n\n${section}\n\n`;
|
||||
const anchor = body.search(/^## (Additional information|Requirements)\b/m);
|
||||
|
||||
return anchor === -1
|
||||
? `${body.trimEnd()}\n\n${block}`
|
||||
: body.slice(0, anchor) + block + body.slice(anchor);
|
||||
}
|
||||
|
||||
async function recordPr(number: string, trustedSha?: string): Promise<void> {
|
||||
const pr = JSON.parse(
|
||||
run('gh', ['pr', 'view', number, '--repo', REPO, '--json', 'author,body,headRefOid'])
|
||||
) as { author: { login: string }; body: string; headRefOid: string };
|
||||
const source = DEMO_BLOCK.exec(pr.body)?.[1];
|
||||
|
||||
if (!source) throw new Error(`PR #${number} has no \`\`\`ts demo block in its description`);
|
||||
|
||||
const sha = pr.headRefOid;
|
||||
|
||||
// the PR's code and demo script run on this machine, with the gh and hf logins,
|
||||
// so someone else's PR only runs at a head commit you've read and passed to --trust
|
||||
if (pr.author.login !== run('gh', ['api', 'user', '--jq', '.login'])) {
|
||||
if (!trustedSha) {
|
||||
throw new Error(
|
||||
`PR #${number} is by ${pr.author.login}, and recording it runs its code here: ` +
|
||||
`read its diff and demo block, then run again with --trust ${sha.slice(0, 10)}`
|
||||
);
|
||||
}
|
||||
|
||||
if (trustedSha.length < 7 || !sha.startsWith(trustedSha)) {
|
||||
throw new Error(`PR #${number} head is ${sha.slice(0, 10)}, not the trusted ${trustedSha}`);
|
||||
}
|
||||
}
|
||||
|
||||
const worktree = join(tmpdir(), `llama-ui-demo-pr-${number}`);
|
||||
|
||||
run('git', ['fetch', '--no-tags', `https://github.com/${REPO}.git`, `pull/${number}/head`]);
|
||||
|
||||
if (run('git', ['rev-parse', 'FETCH_HEAD']) !== sha) {
|
||||
throw new Error(`PR #${number} head moved while fetching, run again`);
|
||||
}
|
||||
|
||||
rmSync(worktree, { force: true, recursive: true });
|
||||
run('git', ['worktree', 'prune']);
|
||||
run('git', ['worktree', 'add', '--detach', worktree, sha]);
|
||||
symlinkSync(join(UI_DIR, 'node_modules'), join(worktree, 'ui/apps/chat/node_modules'));
|
||||
|
||||
const name = `pr-${number}`;
|
||||
const script = writeDemoScript(name, source);
|
||||
|
||||
try {
|
||||
const videos = (await record([script], join(worktree, 'ui/apps/chat'))).map((video) => ({
|
||||
...video,
|
||||
gif: makePreview(video.mp4)
|
||||
}));
|
||||
const storage = getDemoStorage();
|
||||
|
||||
for (const { gif, mp4 } of videos) console.log(`\nvideo: ${mp4}\npreview: ${gif}`);
|
||||
|
||||
if (!storage) {
|
||||
console.log('DEMO_STORAGE is not set: drag the mp4 into the PR description.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const prefix = `videos/pr/${number}/${sha.slice(0, 10)}`;
|
||||
// a script with several tests gets <sha>-1.mp4, <sha>-2.mp4 and so on
|
||||
const keys = videos.map((_, i) => (videos.length === 1 ? prefix : `${prefix}-${i + 1}`));
|
||||
|
||||
upload(storage, { [`${prefix}.demo.ts`]: script });
|
||||
videos.forEach(({ gif, mp4 }, i) => {
|
||||
upload(storage, { [`${keys[i]}.gif`]: gif, [`${keys[i]}.mp4`]: mp4 });
|
||||
});
|
||||
|
||||
if (!getPublicUrl(prefix)) {
|
||||
console.log('DEMO_STORAGE_PUBLIC_URL is not set: not linking the video in the PR.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const links = videos.map(({ gif, mp4, title }, i) => ({
|
||||
gif: versionedUrl(`${keys[i]}.gif`, gif) ?? '',
|
||||
mp4: versionedUrl(`${keys[i]}.mp4`, mp4) ?? '',
|
||||
title
|
||||
}));
|
||||
|
||||
execFileSync('gh', ['pr', 'edit', number, '--repo', REPO, '--body-file', '-'], {
|
||||
cwd: UI_DIR,
|
||||
input: withDemoSection(
|
||||
pr.body,
|
||||
demoSection(links, sha, Math.min(links.length, isPortrait(videos[0].mp4) ? 4 : 2))
|
||||
),
|
||||
stdio: ['pipe', 'inherit', 'inherit']
|
||||
});
|
||||
console.log(`linked the demo in https://github.com/${REPO}/pull/${number}`);
|
||||
} finally {
|
||||
rmSync(script, { force: true });
|
||||
run('git', ['worktree', 'remove', '--force', worktree]);
|
||||
}
|
||||
}
|
||||
|
||||
async function recordDocs(): Promise<void> {
|
||||
const storage = getDemoStorage();
|
||||
|
||||
if (!storage) throw new Error('DEMO_STORAGE is not set: docs demo scripts are read from it');
|
||||
|
||||
const downloaded = join(RUNS_DIR, 'docs-source');
|
||||
|
||||
rmSync(downloaded, { force: true, recursive: true });
|
||||
|
||||
if (!storage.downloadDir('scripts/docs', downloaded)) {
|
||||
throw new Error('no scripts/docs/*.demo.ts in DEMO_STORAGE');
|
||||
}
|
||||
|
||||
const scripts = readdirSync(downloaded)
|
||||
.filter((f) => f.endsWith('.demo.ts'))
|
||||
.map((f) =>
|
||||
writeDemoScript(basename(f, '.demo.ts'), readFileSync(join(downloaded, f), 'utf8'))
|
||||
);
|
||||
|
||||
try {
|
||||
const videos = await record(scripts);
|
||||
|
||||
for (const { mp4 } of videos) {
|
||||
const name = basename(mp4, '.mp4');
|
||||
|
||||
upload(storage, {
|
||||
[`videos/docs/${name}.gif`]: makePreview(mp4),
|
||||
[`videos/docs/${name}.mp4`]: mp4
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
rmSync(RUNS_DIR, { force: true, recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes the built-in traces to demo/traces/ and uploads them to the traces dataset. */
|
||||
function writeTraces(): void {
|
||||
@@ -396,16 +52,10 @@ function writeTraces(): void {
|
||||
);
|
||||
}
|
||||
|
||||
const [command, arg, ...flags] = process.argv.slice(2);
|
||||
const trustIndex = flags.indexOf('--trust');
|
||||
|
||||
if (command === 'pr' && arg) {
|
||||
await recordPr(arg, trustIndex === -1 ? undefined : flags[trustIndex + 1]);
|
||||
} else if (command === 'docs') {
|
||||
await recordDocs();
|
||||
} else if (command === 'traces') {
|
||||
writeTraces();
|
||||
} else {
|
||||
console.error('usage: node demo/cli.ts pr <number> [--trust <sha>] | docs | traces');
|
||||
process.exit(1);
|
||||
}
|
||||
await runDemoCli({
|
||||
commands: { traces: writeTraces },
|
||||
demoDir: DEMO_DIR,
|
||||
dir: resolve(DEMO_DIR, '..'),
|
||||
// Chat builds Llama UI from source, and DEMO_STORYBOOK=ui runs its Storybook
|
||||
linkNodeModules: ['../../lib/ui']
|
||||
});
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* A canned llama-server for demos and e2e checks that should not need a real one, or a model:
|
||||
* routes its endpoints in the browser, so nothing reaches a server and no model loads.
|
||||
*/
|
||||
|
||||
import type { BrowserContext, Page } from '@playwright/test';
|
||||
|
||||
export interface MockServerOptions {
|
||||
/** Model ids the router lists, all loaded. */
|
||||
models?: string[];
|
||||
/** The assistant's reply to every message, streamed a word per chunk. */
|
||||
reply?: string;
|
||||
}
|
||||
|
||||
function completionStream(reply: string): string {
|
||||
const words = reply.match(/\S+\s*/g) ?? [];
|
||||
const chunk = (delta: object, finish: null | string = null) =>
|
||||
`data: ${JSON.stringify({ choices: [{ delta, finish_reason: finish, index: 0 }], object: 'chat.completion.chunk' })}\n\n`;
|
||||
|
||||
return [
|
||||
chunk({ role: 'assistant' }),
|
||||
...words.map((word) => chunk({ content: word })),
|
||||
chunk({}, 'stop'),
|
||||
'data: [DONE]\n\n'
|
||||
].join('');
|
||||
}
|
||||
|
||||
/** Call before the page opens; a demo sets `test.use({ mockServer: {...} })` instead. */
|
||||
export async function mockLlamaServer(
|
||||
target: BrowserContext | Page,
|
||||
{
|
||||
models = ['ggml-org/gemma-3-4b-it-GGUF:Q4_K_M'],
|
||||
reply = 'Hello! How can I help?'
|
||||
}: MockServerOptions = {}
|
||||
): Promise<void> {
|
||||
const data = models.map((id) => ({
|
||||
id,
|
||||
object: 'model',
|
||||
owned_by: 'llamacpp',
|
||||
status: { value: 'loaded' }
|
||||
}));
|
||||
|
||||
await target.route(/\/props(\?|$)/, (route) =>
|
||||
route.fulfill({
|
||||
json: { build_info: 'mock', model_path: 'none', role: 'router', ui_settings: {} }
|
||||
})
|
||||
);
|
||||
await target.route(/\/(v1\/)?models(\?|$)/, (route) =>
|
||||
route.fulfill({ json: { data, object: 'list' } })
|
||||
);
|
||||
await target.route(/\/models\/(load|unload)$/, (route) =>
|
||||
route.fulfill({ json: { success: true } })
|
||||
);
|
||||
await target.route(/\/models\/sse$/, (route) => route.abort());
|
||||
await target.route(/\/tools(\?|$)/, (route) => route.fulfill({ json: [] }));
|
||||
await target.route(/\/v1\/streams\/lookup$/, (route) => route.fulfill({ status: 404 }));
|
||||
await target.route(/\/v1\/chat\/completions$/, (route) =>
|
||||
route.fulfill({
|
||||
body: completionStream(reply),
|
||||
headers: { 'content-type': 'text/event-stream' }
|
||||
})
|
||||
);
|
||||
}
|
||||
+85
-519
@@ -1,115 +1,21 @@
|
||||
/**
|
||||
* Llama Chat's demo fixtures on the harness in ui/lib/demo: settings, conversations and a mocked
|
||||
* llama-server set the scene, or a Storybook story stands in for the app.
|
||||
*/
|
||||
|
||||
import { demoMcpServerSettings } from './fixtures/demo-config.ts';
|
||||
import { mockLlamaServer, type MockServerOptions } from './fixtures/llama-server.ts';
|
||||
import { generateTrace } from './fixtures/traces.ts';
|
||||
import { ScreencastRecorder } from './recorder.ts';
|
||||
import { type CDPSession, type Locator, type Page, test as base } from '@playwright/test';
|
||||
import { Demo, prepareDemoPage, recordDemo } from '@ggml-org/llama-demo';
|
||||
import { type Locator, type Page, test as base, type TestInfo } from '@playwright/test';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import {
|
||||
appendFileSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
writeFileSync
|
||||
} from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { basename, join, resolve } from 'node:path';
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { join, resolve } from 'node:path';
|
||||
|
||||
const VIDEOS_DIR = resolve(import.meta.dirname, 'videos');
|
||||
const BRAND_DIR = resolve(import.meta.dirname, '../node_modules/@ggml-org/llama-brand');
|
||||
/** How long a demo waits for the app to be ready before it starts recording. */
|
||||
const APP_READY_TIMEOUT_MS = 90000;
|
||||
/** How far below the viewport's top a pinch has to start for Chromium to zoom at all. */
|
||||
const ZOOM_TOP_INSET_PX = 64;
|
||||
|
||||
/**
|
||||
* Draws a fake cursor and click ripples, since recorded videos don't include
|
||||
* the OS pointer, and a fingertip per touch, so a pinch shows as two fingers.
|
||||
* Runs in the page via addInitScript.
|
||||
*/
|
||||
function installCursorOverlay(): void {
|
||||
const mount = () => {
|
||||
const style = document.createElement('style');
|
||||
|
||||
style.textContent = `
|
||||
#demo-cursor { position: fixed; top: 0; left: 0; z-index: 2147483647; pointer-events: none;
|
||||
width: 22px; height: 22px; margin: -3px 0 0 -3px; transition: transform 80ms ease-out; }
|
||||
#demo-cursor.down { transform: scale(0.85); }
|
||||
.demo-ripple { position: fixed; z-index: 2147483646; pointer-events: none; width: 36px; height: 36px;
|
||||
margin: -18px 0 0 -18px; border-radius: 50%; background: rgba(59, 130, 246, 0.35);
|
||||
animation: demo-ripple 450ms ease-out forwards; }
|
||||
@keyframes demo-ripple { from { transform: scale(0.3); opacity: 1; } to { transform: scale(1.4); opacity: 0; } }
|
||||
#demo-caption { position: fixed; left: 50%; top: 72px; z-index: 2147483647; pointer-events: none;
|
||||
transform: translate(-50%, -8px); opacity: 0; transition: opacity 200ms ease, transform 200ms ease;
|
||||
max-width: 80%; padding: 10px 18px; border-radius: 10px; background: rgba(17, 17, 17, 0.88);
|
||||
color: #fff; font: 500 18px/1.4 system-ui, sans-serif; text-align: center; }
|
||||
#demo-caption.visible { opacity: 1; transform: translate(-50%, 0); }
|
||||
.demo-finger { position: fixed; z-index: 2147483646; pointer-events: none; width: 40px; height: 40px;
|
||||
margin: -20px 0 0 -20px; border-radius: 50%; background: rgba(59, 130, 246, 0.3);
|
||||
border: 2px solid rgba(59, 130, 246, 0.55); transition: opacity 200ms ease; }
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
|
||||
const cursor = document.createElement('div');
|
||||
|
||||
cursor.id = 'demo-cursor';
|
||||
cursor.innerHTML = `<svg viewBox="0 0 24 24" width="22" height="22"><path d="M4 2l16 10.5-7 1.5-3.5 6.5z"
|
||||
fill="#111" stroke="#fff" stroke-width="1.5" stroke-linejoin="round"/></svg>`;
|
||||
document.documentElement.appendChild(cursor);
|
||||
|
||||
const caption = document.createElement('div');
|
||||
|
||||
caption.id = 'demo-caption';
|
||||
document.documentElement.appendChild(caption);
|
||||
|
||||
document.addEventListener(
|
||||
'mousemove',
|
||||
(e) => (cursor.style.translate = `${e.clientX}px ${e.clientY}px`),
|
||||
true
|
||||
);
|
||||
document.addEventListener(
|
||||
'mousedown',
|
||||
(e) => {
|
||||
cursor.classList.add('down');
|
||||
const ripple = document.createElement('div');
|
||||
|
||||
ripple.className = 'demo-ripple';
|
||||
ripple.style.left = `${e.clientX}px`;
|
||||
ripple.style.top = `${e.clientY}px`;
|
||||
document.documentElement.appendChild(ripple);
|
||||
setTimeout(() => ripple.remove(), 500);
|
||||
},
|
||||
true
|
||||
);
|
||||
document.addEventListener('mouseup', () => cursor.classList.remove('down'), true);
|
||||
|
||||
const fingers: HTMLDivElement[] = [];
|
||||
const placeFingers = (e: TouchEvent) => {
|
||||
Array.from(e.touches).forEach((touch, i) => {
|
||||
const finger = (fingers[i] ??= Object.assign(document.createElement('div'), {
|
||||
className: 'demo-finger'
|
||||
}));
|
||||
|
||||
finger.style.left = `${touch.clientX}px`;
|
||||
finger.style.top = `${touch.clientY}px`;
|
||||
finger.style.opacity = '1';
|
||||
document.documentElement.appendChild(finger);
|
||||
});
|
||||
fingers.slice(e.touches.length).forEach((finger) => (finger.style.opacity = '0'));
|
||||
};
|
||||
|
||||
for (const type of ['touchstart', 'touchmove', 'touchend', 'touchcancel']) {
|
||||
document.addEventListener(type, placeFingers as EventListener, {
|
||||
capture: true,
|
||||
passive: true
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', mount);
|
||||
} else {
|
||||
mount();
|
||||
}
|
||||
}
|
||||
|
||||
/** Seeds UI settings once per demo, so later reloads keep what the demo changed. */
|
||||
function seedSettings(config: Record<string, unknown>): void {
|
||||
@@ -120,364 +26,20 @@ function seedSettings(config: Record<string, unknown>): void {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Swaps the page's microphone for one that hears only what `window.demoSpeak` plays into it,
|
||||
* silence otherwise. Chromium's fake capture device crashes the page, so voice input is
|
||||
* recorded with this instead. Runs in the page.
|
||||
*/
|
||||
function installFakeMicrophone(): void {
|
||||
const context = new AudioContext();
|
||||
const output = context.createMediaStreamDestination();
|
||||
|
||||
navigator.mediaDevices.getUserMedia = async (constraints) => {
|
||||
if (!constraints?.audio || constraints.video) {
|
||||
throw new DOMException('demo: only the microphone is faked', 'NotSupportedError');
|
||||
}
|
||||
|
||||
await context.resume();
|
||||
|
||||
// each opening gets its own tracks, so a recording that stops them leaves the source on
|
||||
return new MediaStream(output.stream.getAudioTracks().map((track) => track.clone()));
|
||||
};
|
||||
|
||||
Object.assign(window, {
|
||||
demoSpeak: async (wavBase64: string) => {
|
||||
const bytes = Uint8Array.from(atob(wavBase64), (c) => c.charCodeAt(0));
|
||||
const source = context.createBufferSource();
|
||||
|
||||
source.buffer = await context.decodeAudioData(bytes.buffer);
|
||||
source.connect(output);
|
||||
await context.resume();
|
||||
await new Promise((done) => {
|
||||
source.onended = done;
|
||||
source.start();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** `text` read by a synthetic voice, as a base64 WAV. Uses macOS `say`. */
|
||||
function synthesizeSpeech(text: string, voice: string): string {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'demo-speech-'));
|
||||
const file = join(dir, 'speech.wav');
|
||||
|
||||
try {
|
||||
execFileSync('say', [
|
||||
'-v',
|
||||
voice,
|
||||
'-o',
|
||||
file,
|
||||
'--file-format=WAVE',
|
||||
'--data-format=LEI16@24000',
|
||||
text
|
||||
]);
|
||||
|
||||
return readFileSync(file).toString('base64');
|
||||
} catch (error) {
|
||||
throw new Error(`demo: speak() needs macOS \`say\` with the voice ${voice}`, {
|
||||
cause: error
|
||||
});
|
||||
} finally {
|
||||
rmSync(dir, { force: true, recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** Seeded randomness, so a demo moves the same way on every recording. */
|
||||
function createRandom(seed: string): () => number {
|
||||
let state = [...seed].reduce((h, c) => Math.imul(h ^ c.charCodeAt(0), 2654435761), 1);
|
||||
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) | 0;
|
||||
|
||||
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
||||
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
const easeInOut = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2);
|
||||
|
||||
/**
|
||||
* Drives the page like a person: the cursor glides along a slight arc with
|
||||
* Fitts-like durations, settles briefly before pressing, and typing and pauses
|
||||
* vary a little.
|
||||
*/
|
||||
export class Demo {
|
||||
private cdp: CDPSession | undefined;
|
||||
private readonly page: Page;
|
||||
private readonly random: () => number;
|
||||
private x = 0;
|
||||
private y = 0;
|
||||
|
||||
/** Shows a caption at the top of the frame for `ms`, clear of the chat form. */
|
||||
async caption(text: string, ms = 2200): Promise<void> {
|
||||
await this.showCaption(text);
|
||||
await this.page.waitForTimeout(ms);
|
||||
await this.hideCaption();
|
||||
}
|
||||
|
||||
async click(target: Locator, ms = 400): Promise<void> {
|
||||
await this.moveTo(target);
|
||||
await this.page.waitForTimeout(this.between(80, 160));
|
||||
await this.page.mouse.down();
|
||||
await this.page.waitForTimeout(this.between(50, 90));
|
||||
await this.page.mouse.up();
|
||||
await this.pause(ms);
|
||||
}
|
||||
|
||||
constructor(page: Page, seed: string) {
|
||||
this.page = page;
|
||||
this.random = createRandom(seed);
|
||||
|
||||
const viewport = page.viewportSize();
|
||||
|
||||
this.x = (viewport?.width ?? 0) / 2;
|
||||
this.y = (viewport?.height ?? 0) / 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Touches `target` for `ms` and lifts: a tap, or with a longer `ms` a press-and-hold, as a
|
||||
* phone's held rows ask for. It needs a touch device (`hasTouch`), and shows a fingertip.
|
||||
*/
|
||||
async hold(target: Locator, ms = 900, after = 500): Promise<void> {
|
||||
await target.scrollIntoViewIfNeeded();
|
||||
|
||||
const { x, y } = await this.center(target);
|
||||
const cdp = await this.session();
|
||||
|
||||
await this.page.waitForTimeout(this.between(60, 140));
|
||||
await cdp.send('Input.dispatchTouchEvent', { touchPoints: [{ x, y }], type: 'touchStart' });
|
||||
await this.page.waitForTimeout(ms);
|
||||
await cdp.send('Input.dispatchTouchEvent', { touchPoints: [], type: 'touchEnd' });
|
||||
await this.liftFingers();
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
await this.pause(after);
|
||||
}
|
||||
|
||||
async hover(target: Locator, ms = 350): Promise<void> {
|
||||
await this.moveTo(target);
|
||||
await this.pause(ms);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives the page a microphone that hears only what `speak` says, and allows the page to
|
||||
* use it. Call it before the microphone is first used.
|
||||
*/
|
||||
async microphone(): Promise<void> {
|
||||
await this.page.context().grantPermissions(['microphone']);
|
||||
await this.page.evaluate(installFakeMicrophone);
|
||||
}
|
||||
|
||||
/** Glides the cursor to a point near the center of `target`. */
|
||||
async moveTo(target: Locator): Promise<void> {
|
||||
await target.scrollIntoViewIfNeeded();
|
||||
const box = await target.boundingBox();
|
||||
|
||||
if (!box) throw new Error(`demo: ${target} has no bounding box`);
|
||||
|
||||
const x = box.x + box.width * this.between(0.4, 0.6);
|
||||
const y = box.y + box.height * this.between(0.4, 0.6);
|
||||
const dx = x - this.x;
|
||||
const dy = y - this.y;
|
||||
const distance = Math.hypot(dx, dy);
|
||||
const duration = 110 + 55 * Math.log2(distance / 40 + 1);
|
||||
// bow the path a little to one side, like a wrist turning
|
||||
const bow = distance * this.between(-0.08, 0.08);
|
||||
const fromX = this.x;
|
||||
const fromY = this.y;
|
||||
const started = Date.now();
|
||||
|
||||
for (;;) {
|
||||
const t = Math.min((Date.now() - started) / duration, 1);
|
||||
const p = easeInOut(t);
|
||||
const arc = Math.sin(Math.PI * p) * bow;
|
||||
|
||||
this.x = fromX + dx * p - (dy / (distance || 1)) * arc;
|
||||
this.y = fromY + dy * p + (dx / (distance || 1)) * arc;
|
||||
await this.page.mouse.move(this.x, this.y);
|
||||
|
||||
if (t === 1) break;
|
||||
|
||||
await this.page.waitForTimeout(8);
|
||||
}
|
||||
}
|
||||
|
||||
/** Waits about `ms`, varied by up to 15% so pauses don't feel metronomic. */
|
||||
async pause(ms = 800): Promise<void> {
|
||||
await this.page.waitForTimeout(ms * this.between(0.85, 1.15));
|
||||
}
|
||||
|
||||
async press(key: string, ms = 600): Promise<void> {
|
||||
await this.page.keyboard.press(key);
|
||||
await this.pause(ms);
|
||||
}
|
||||
|
||||
/** Scrolls the wheel over `target` by `dy` pixels (negative scrolls up), in small steps like a trackpad. */
|
||||
async scroll(target: Locator, dy: number, ms = 500): Promise<void> {
|
||||
await this.moveTo(target);
|
||||
|
||||
const step = Math.sign(dy) * 40;
|
||||
|
||||
for (let done = 0; Math.abs(done) < Math.abs(dy); done += step) {
|
||||
await this.page.mouse.wheel(0, step);
|
||||
await this.page.waitForTimeout(16);
|
||||
}
|
||||
|
||||
await this.pause(ms);
|
||||
}
|
||||
|
||||
/**
|
||||
* Says `text` into the microphone from `microphone` in a synthetic voice (macOS `say`), and
|
||||
* returns once it is said. The words show as a caption, since the video has no sound.
|
||||
*/
|
||||
async speak(text: string, voice = 'Samantha', ms = 400): Promise<void> {
|
||||
const wav = synthesizeSpeech(text, voice);
|
||||
|
||||
await this.showCaption(`“${text}”`);
|
||||
await this.page.evaluate(
|
||||
(base64) =>
|
||||
(window as unknown as { demoSpeak(wav: string): Promise<void> }).demoSpeak(base64),
|
||||
wav
|
||||
);
|
||||
await this.hideCaption();
|
||||
await this.pause(ms);
|
||||
}
|
||||
|
||||
/** Taps `target` with a fingertip, on a touch device. */
|
||||
tap(target: Locator, after = 500): Promise<void> {
|
||||
return this.hold(target, this.between(60, 110), after);
|
||||
}
|
||||
|
||||
/** Types quickly with uneven key timing, a little slower after spaces and punctuation. */
|
||||
async type(target: Locator, text: string, ms = 500): Promise<void> {
|
||||
await this.click(target, 200);
|
||||
|
||||
for (const char of text) {
|
||||
await this.page.keyboard.type(char);
|
||||
await this.page.waitForTimeout(
|
||||
this.between(15, 45) + (/[\s.,!?]/.test(char) ? this.between(20, 60) : 0)
|
||||
);
|
||||
}
|
||||
|
||||
await this.pause(ms);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pinches in on `target`, a control or a point in the viewport, holds about `ms`, and pinches
|
||||
* back out to 1x: a two-finger zoom onto a detail too small to read in the frame. On a touch
|
||||
* device the fingertips show.
|
||||
*/
|
||||
async zoom(target: Locator | { x: number; y: number }, scale = 2.5, ms = 1400): Promise<void> {
|
||||
const point = 'x' in target ? target : await this.center(target);
|
||||
// a pinch anchored in the viewport's top band does not zoom at all
|
||||
const at = { x: point.x, y: Math.max(point.y, ZOOM_TOP_INSET_PX) };
|
||||
const viewport = this.page.viewportSize() ?? { height: 0, width: 0 };
|
||||
const middle = { x: viewport.width / 2, y: viewport.height / 2 };
|
||||
|
||||
await this.pinch(at, scale, 1400);
|
||||
|
||||
// One near the bottom edge overshoots its ratio, and a pinch there again misses too. A small
|
||||
// pinch from the middle evens it out, drawing the detail toward the middle, so it stays in view
|
||||
const reached = await this.pageScale();
|
||||
|
||||
if (Math.abs(reached / scale - 1) > 0.03) await this.pinch(middle, scale / reached, 1400);
|
||||
|
||||
await this.liftFingers();
|
||||
await this.pause(ms);
|
||||
|
||||
// back to exactly 1x, which the next gesture needs, in one quick pinch from the middle of
|
||||
// the viewport, and another for what is left when one lands short
|
||||
for (let tries = 0; ; tries++) {
|
||||
const current = await this.pageScale();
|
||||
|
||||
if (current <= 1.001) break;
|
||||
|
||||
if (tries === 4) throw new Error(`demo: zoom stuck at ${current.toFixed(3)}x`);
|
||||
|
||||
await this.pinch(middle, 1 / current, 1800);
|
||||
}
|
||||
|
||||
await this.liftFingers();
|
||||
await this.pause(200);
|
||||
}
|
||||
|
||||
private between(min: number, max: number): number {
|
||||
return min + (max - min) * this.random();
|
||||
}
|
||||
|
||||
private async center(target: Locator): Promise<{ x: number; y: number }> {
|
||||
const box = await target.boundingBox();
|
||||
|
||||
if (!box) throw new Error(`demo: ${target} has no bounding box`);
|
||||
|
||||
return { x: box.x + box.width / 2, y: box.y + box.height / 2 };
|
||||
}
|
||||
|
||||
private async hideCaption(): Promise<void> {
|
||||
await this.page.evaluate(() =>
|
||||
document.getElementById('demo-caption')?.classList.remove('visible')
|
||||
);
|
||||
await this.page.waitForTimeout(250);
|
||||
}
|
||||
|
||||
/** A pinch that reaches the screen's edge can end without its last touchend reaching the page. */
|
||||
private async liftFingers(): Promise<void> {
|
||||
await this.page.evaluate(() =>
|
||||
document
|
||||
.querySelectorAll<HTMLElement>('.demo-finger')
|
||||
.forEach((finger) => (finger.style.opacity = '0'))
|
||||
);
|
||||
}
|
||||
|
||||
private pageScale(): Promise<number> {
|
||||
return this.page.evaluate(() => window.visualViewport?.scale ?? 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* A two-finger pinch by `factor` around `at`, in viewport pixels. While zoomed in, the gesture
|
||||
* reads its position in page-scale units, so it is divided by the scale the page is at.
|
||||
*/
|
||||
private async pinch(at: { x: number; y: number }, factor: number, speed: number): Promise<void> {
|
||||
const cdp = await this.session();
|
||||
const current = await this.pageScale();
|
||||
|
||||
await cdp.send('Input.synthesizePinchGesture', {
|
||||
gestureSourceType: 'touch',
|
||||
relativeSpeed: speed,
|
||||
scaleFactor: factor,
|
||||
x: at.x / current,
|
||||
y: at.y / current
|
||||
});
|
||||
}
|
||||
|
||||
private async session(): Promise<CDPSession> {
|
||||
this.cdp ??= await this.page.context().newCDPSession(this.page);
|
||||
|
||||
return this.cdp;
|
||||
}
|
||||
|
||||
private async showCaption(text: string): Promise<void> {
|
||||
await this.page.evaluate((t) => {
|
||||
const el = document.getElementById('demo-caption');
|
||||
|
||||
if (!el) return;
|
||||
|
||||
el.textContent = t;
|
||||
el.classList.add('visible');
|
||||
}, text);
|
||||
}
|
||||
}
|
||||
|
||||
interface DemoOptions {
|
||||
/** Empty conversations added to the library before the demo starts, e.g. to fill a list. */
|
||||
chats: number;
|
||||
/** Answers llama-server's endpoints in the browser instead (fixtures/llama-server.ts), so no model loads. */
|
||||
mockServer: MockServerOptions | null;
|
||||
/** Path the demo starts from. */
|
||||
startPath: string;
|
||||
/** Extra UI settings merged into the seeded config. */
|
||||
settings: Record<string, unknown>;
|
||||
/**
|
||||
* Storybook story id (`?path=/story/<id>`) recorded instead of Llama Chat, from the Storybook
|
||||
* that DEMO_STORYBOOK starts: `ui` (Llama UI) or `chat` (Llama Chat).
|
||||
*/
|
||||
story: string;
|
||||
/**
|
||||
* Conversations imported before the demo starts: built-in traces from
|
||||
* fixtures/traces.ts, or `<name>.jsonl` files from DEMO_TRACES_DATASET.
|
||||
@@ -506,7 +68,7 @@ function loadTrace(name: string, dir: string): string {
|
||||
}
|
||||
|
||||
/** Imports conversations through Settings > Data, like a user would. */
|
||||
async function importTraces(page: Page, file: string): Promise<void> {
|
||||
export async function importTraces(page: Page, file: string): Promise<void> {
|
||||
// the expanded sidebar adds the shortcut to the name
|
||||
const settings = page.getByRole('button', { name: /^Settings(\s|$)/ }).first();
|
||||
const reachable = (target: Locator) =>
|
||||
@@ -629,87 +191,91 @@ async function seedChats(page: Page, count: number): Promise<void> {
|
||||
);
|
||||
}
|
||||
|
||||
/** Seeds settings, imports the traces, adds the chats and opens `startPath` in Llama Chat. */
|
||||
async function openChat(
|
||||
page: Page,
|
||||
settings: Record<string, unknown>,
|
||||
startPath: string,
|
||||
traces: string[],
|
||||
chats: number,
|
||||
testInfo: TestInfo
|
||||
): Promise<void> {
|
||||
await page.addInitScript(seedSettings, {
|
||||
mcpServers: JSON.stringify(demoMcpServerSettings()),
|
||||
...settings
|
||||
});
|
||||
|
||||
if (traces.length > 0) {
|
||||
const dir = testInfo.outputPath('traces');
|
||||
const file = join(dir, 'import.jsonl');
|
||||
|
||||
mkdirSync(dir, { recursive: true });
|
||||
writeFileSync(file, traces.map((name) => loadTrace(name, dir)).join('\n'));
|
||||
await page.goto('/');
|
||||
await page
|
||||
.getByRole('textbox', { name: 'Type a message...' })
|
||||
.waitFor({ timeout: APP_READY_TIMEOUT_MS });
|
||||
await importTraces(page, file);
|
||||
}
|
||||
|
||||
if (chats > 0) await seedChats(page, chats);
|
||||
|
||||
await page.goto(startPath);
|
||||
|
||||
// a hash route after the import doesn't reload, which the conversations list needs
|
||||
if (traces.length > 0 || chats > 0) await page.reload();
|
||||
|
||||
// a fresh checkout's dev server optimizes its dependencies on the first load and reloads the
|
||||
// page, which can take well past an action's timeout; the recording has not started yet
|
||||
await page
|
||||
.getByRole('textbox', { name: 'Type a message...' })
|
||||
.waitFor({ timeout: APP_READY_TIMEOUT_MS });
|
||||
}
|
||||
|
||||
export const test = base.extend<DemoOptions & { demo: Demo }>({
|
||||
chats: [0, { option: true }],
|
||||
demo: async ({ page }, use, testInfo) => {
|
||||
await use(new Demo(page, `${testInfo.file}:${testInfo.title}`));
|
||||
},
|
||||
mockServer: [null, { option: true }],
|
||||
|
||||
page: async ({ chats, page, settings, startPath, traces }, use, testInfo) => {
|
||||
await page.addInitScript(installCursorOverlay);
|
||||
await page.addInitScript(seedSettings, {
|
||||
mcpServers: JSON.stringify(demoMcpServerSettings()),
|
||||
...settings
|
||||
});
|
||||
page: async (
|
||||
{ chats, colorScheme, mockServer, page, settings, startPath, story, traces },
|
||||
use,
|
||||
testInfo
|
||||
) => {
|
||||
await prepareDemoPage(page, testInfo);
|
||||
|
||||
if (traces.length > 0) {
|
||||
const dir = testInfo.outputPath('traces');
|
||||
const file = join(dir, 'import.jsonl');
|
||||
|
||||
mkdirSync(dir, { recursive: true });
|
||||
writeFileSync(file, traces.map((name) => loadTrace(name, dir)).join('\n'));
|
||||
await page.goto('/');
|
||||
await page
|
||||
.getByRole('textbox', { name: 'Type a message...' })
|
||||
.waitFor({ timeout: APP_READY_TIMEOUT_MS });
|
||||
await importTraces(page, file);
|
||||
if (story && !process.env.DEMO_STORYBOOK) {
|
||||
throw new Error('demo: a story demo needs DEMO_STORYBOOK=ui (Llama UI) or chat (Llama Chat)');
|
||||
}
|
||||
|
||||
if (chats > 0) await seedChats(page, chats);
|
||||
if (story) {
|
||||
await page.goto(
|
||||
`http://localhost:${process.env.DEMO_STORYBOOK_PORT}/iframe.html?id=${story}&viewMode=story`
|
||||
);
|
||||
await page.locator('#storybook-root > *').first().waitFor({ timeout: APP_READY_TIMEOUT_MS });
|
||||
} else {
|
||||
if (mockServer) await mockLlamaServer(page, mockServer);
|
||||
|
||||
await page.goto(startPath);
|
||||
await openChat(page, settings, startPath, traces, chats, testInfo);
|
||||
}
|
||||
|
||||
// a hash route after the import doesn't reload, which the conversations list needs
|
||||
if (traces.length > 0 || chats > 0) await page.reload();
|
||||
|
||||
// a fresh checkout's dev server optimizes its dependencies on the first load and reloads the
|
||||
// page, which can take well past an action's timeout; the recording has not started yet
|
||||
await page
|
||||
.getByRole('textbox', { name: 'Type a message...' })
|
||||
.waitFor({ timeout: APP_READY_TIMEOUT_MS });
|
||||
|
||||
const viewport = page.viewportSize();
|
||||
|
||||
if (viewport) await page.mouse.move(viewport.width / 2, viewport.height / 2);
|
||||
|
||||
// let MCP connections and fonts settle before the recording starts
|
||||
await page.waitForTimeout(1500);
|
||||
|
||||
const recorder = new ScreencastRecorder(testInfo.outputPath('frames'));
|
||||
|
||||
await recorder.start(page);
|
||||
await use(page);
|
||||
await recorder.stop();
|
||||
await page.close();
|
||||
|
||||
if (testInfo.status !== testInfo.expectedStatus) return;
|
||||
|
||||
const file = basename(testInfo.file).replace(/\.demo\.ts$/, '');
|
||||
const name = testInfo.title === 'demo' ? file : `${file}--${slugify(testInfo.title)}`;
|
||||
const mp4 = resolve(VIDEOS_DIR, `${name}.mp4`);
|
||||
|
||||
mkdirSync(VIDEOS_DIR, { recursive: true });
|
||||
recorder.encode(mp4);
|
||||
// the CLI reads which videos a script made, in order, with their titles
|
||||
appendFileSync(
|
||||
resolve(VIDEOS_DIR, `${file}.videos.jsonl`),
|
||||
`${JSON.stringify({ mp4, title: testInfo.title })}\n`
|
||||
await recordDemo(
|
||||
page,
|
||||
testInfo,
|
||||
{ brandDir: BRAND_DIR, dark: colorScheme === 'dark', videosDir: VIDEOS_DIR },
|
||||
() => use(page)
|
||||
);
|
||||
console.log(`demo video: ${mp4}`);
|
||||
},
|
||||
|
||||
settings: [{}, { option: true }],
|
||||
|
||||
startPath: ['/', { option: true }],
|
||||
|
||||
story: ['', { option: true }],
|
||||
|
||||
traces: [[], { option: true }]
|
||||
});
|
||||
|
||||
export { expect } from '@playwright/test';
|
||||
|
||||
function slugify(text: string): string {
|
||||
return text
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-|-$/g, '');
|
||||
}
|
||||
|
||||
@@ -16,6 +16,9 @@ if (existsSync(ENV_FILE)) process.loadEnvFile(ENV_FILE);
|
||||
* DEMO_SERVER_ORIGIN llama-server the UI proxies to (default: http://localhost:9931)
|
||||
* DEMO_LLAMA_SERVER llama-server binary started when none runs there (default: build/bin)
|
||||
* DEMO_COLOR_SCHEME light | dark (default: light)
|
||||
* DEMO_POLISH 0 for the plain screencast (default: the branded render, see polish.ts)
|
||||
* DEMO_STORYBOOK ui | chat: also start that Storybook (Llama UI's or Llama Chat's), for story demos
|
||||
* DEMO_STORYBOOK_PORT port for it (default: 6007)
|
||||
*/
|
||||
|
||||
// Playwright clears outputDir when a run starts, so concurrent recordings each get
|
||||
@@ -29,6 +32,10 @@ const SERVER_PORT = Number(new URL(SERVER_ORIGIN).port || 80);
|
||||
const LLAMA_SERVER =
|
||||
process.env.DEMO_LLAMA_SERVER ??
|
||||
resolve(import.meta.dirname, '../../../../build/bin/llama-server');
|
||||
const STORYBOOK = process.env.DEMO_STORYBOOK;
|
||||
|
||||
// workers read it to open the stories
|
||||
process.env.DEMO_STORYBOOK_PORT ??= '6007';
|
||||
|
||||
export const VIEWPORT = { height: 900, width: 1440 };
|
||||
/** Device pixel ratio the demos render and record at. */
|
||||
@@ -82,7 +89,18 @@ export default defineConfig({
|
||||
reuseExistingServer: true,
|
||||
timeout: 120000,
|
||||
url: `http://localhost:${UI_PORT}`
|
||||
}
|
||||
},
|
||||
...(STORYBOOK
|
||||
? [
|
||||
{
|
||||
command: `npx svelte-kit sync && npx storybook dev -p ${process.env.DEMO_STORYBOOK_PORT} --ci --exact-port`,
|
||||
cwd: STORYBOOK === 'ui' ? resolve(UI_DIR, '../../lib/ui') : UI_DIR,
|
||||
reuseExistingServer: true,
|
||||
timeout: 120000,
|
||||
url: `http://localhost:${process.env.DEMO_STORYBOOK_PORT}/iframe.html`
|
||||
}
|
||||
]
|
||||
: [])
|
||||
],
|
||||
workers: 1
|
||||
});
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
/**
|
||||
* Records a page through Chromium's screencast instead of Playwright's video,
|
||||
* which encodes VP8 at about 1 Mbit/s at 1x scale. Frames arrive at the page's
|
||||
* device pixel ratio, each with its timestamp, and are encoded once into an
|
||||
* H.264 mp4 (what GitHub accepts in PR descriptions).
|
||||
*/
|
||||
|
||||
import type { CDPSession, Page } from '@playwright/test';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
|
||||
const FPS = 60;
|
||||
const JPEG_QUALITY = 92;
|
||||
|
||||
interface Frame {
|
||||
file: string;
|
||||
/** Seconds, on the same clock as Date.now(). */
|
||||
time: number;
|
||||
}
|
||||
|
||||
export class ScreencastRecorder {
|
||||
private readonly dir: string;
|
||||
private readonly frames: Frame[] = [];
|
||||
private readonly pending: Promise<void>[] = [];
|
||||
private session: CDPSession | undefined;
|
||||
private stoppedAt = 0;
|
||||
|
||||
constructor(dir: string) {
|
||||
this.dir = dir;
|
||||
}
|
||||
|
||||
/** Encodes the frames, each held until the next one arrived (the screencast only sends changes). */
|
||||
encode(mp4: string): void {
|
||||
if (this.frames.length === 0) throw new Error('demo: the screencast captured no frames');
|
||||
|
||||
const list = this.frames.flatMap((frame, i) => {
|
||||
const end = this.frames[i + 1]?.time ?? this.stoppedAt;
|
||||
|
||||
return [`file '${frame.file}'`, `duration ${Math.max(end - frame.time, 1 / FPS).toFixed(4)}`];
|
||||
});
|
||||
const listFile = join(this.dir, 'frames.txt');
|
||||
|
||||
// the concat demuxer ignores the last entry's duration unless the file is repeated
|
||||
writeFileSync(listFile, [...list, `file '${this.frames.at(-1)!.file}'`, ''].join('\n'));
|
||||
execFileSync(
|
||||
'ffmpeg',
|
||||
[
|
||||
'-y',
|
||||
'-loglevel',
|
||||
'error',
|
||||
'-f',
|
||||
'concat',
|
||||
'-safe',
|
||||
'0',
|
||||
'-i',
|
||||
listFile,
|
||||
'-vf',
|
||||
`fps=${FPS},scale=trunc(iw/2)*2:trunc(ih/2)*2`,
|
||||
'-c:v',
|
||||
'libx264',
|
||||
'-preset',
|
||||
'slow',
|
||||
'-crf',
|
||||
'18',
|
||||
'-pix_fmt',
|
||||
'yuv420p',
|
||||
'-movflags',
|
||||
'+faststart',
|
||||
mp4
|
||||
],
|
||||
{ stdio: 'inherit' }
|
||||
);
|
||||
rmSync(this.dir, { force: true, recursive: true });
|
||||
}
|
||||
|
||||
async start(page: Page): Promise<void> {
|
||||
const size = page.viewportSize();
|
||||
const scale = await page.evaluate(() => window.devicePixelRatio);
|
||||
|
||||
rmSync(this.dir, { force: true, recursive: true });
|
||||
mkdirSync(this.dir, { recursive: true });
|
||||
|
||||
this.session = await page.context().newCDPSession(page);
|
||||
this.session.on('Page.screencastFrame', ({ data, metadata, sessionId }) => {
|
||||
const file = join(this.dir, `${String(this.frames.length).padStart(6, '0')}.jpg`);
|
||||
|
||||
// acknowledged first: Chromium sends the next frame only after the ack
|
||||
this.session?.send('Page.screencastFrameAck', { sessionId }).catch(() => {});
|
||||
this.frames.push({ file, time: metadata.timestamp ?? Date.now() / 1000 });
|
||||
this.pending.push(writeFile(file, Buffer.from(data, 'base64')));
|
||||
});
|
||||
await this.session.send('Page.startScreencast', {
|
||||
everyNthFrame: 1,
|
||||
format: 'jpeg',
|
||||
maxHeight: size ? size.height * scale : undefined,
|
||||
maxWidth: size ? size.width * scale : undefined,
|
||||
quality: JPEG_QUALITY
|
||||
});
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.stoppedAt = Date.now() / 1000;
|
||||
await this.session?.send('Page.stopScreencast').catch(() => {});
|
||||
await this.session?.detach().catch(() => {});
|
||||
await Promise.all(this.pending);
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
/**
|
||||
* Storage targets for demo scripts and videos, picked by the scheme of the
|
||||
* DEMO_STORAGE URI:
|
||||
*
|
||||
* hf://buckets/<owner>/<bucket>[/prefix] Hugging Face bucket, via the `hf` CLI login
|
||||
* file:///some/dir local or mounted directory
|
||||
*/
|
||||
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { copyFileSync, cpSync, existsSync, mkdirSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
export interface DemoStorage {
|
||||
/** Copies every file under remote `dir` into local `target`; returns false when it has none. */
|
||||
downloadDir(dir: string, target: string): boolean;
|
||||
/** Copies local `file` to remote `key`. */
|
||||
upload(file: string, key: string): void;
|
||||
}
|
||||
|
||||
function joinKey(base: string, key: string): string {
|
||||
return `${base.replace(/\/+$/, '')}/${key}`;
|
||||
}
|
||||
|
||||
// plain fields: the CLI runs under Node's type stripping, which has no parameter properties
|
||||
class HfStorage implements DemoStorage {
|
||||
private readonly base: string;
|
||||
|
||||
constructor(base: string) {
|
||||
this.base = base;
|
||||
}
|
||||
|
||||
downloadDir(dir: string, target: string): boolean {
|
||||
mkdirSync(target, { recursive: true });
|
||||
|
||||
try {
|
||||
execFileSync('hf', ['buckets', 'sync', joinKey(this.base, dir), target], {
|
||||
stdio: 'inherit'
|
||||
});
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
upload(file: string, key: string): void {
|
||||
execFileSync('hf', ['buckets', 'cp', file, joinKey(this.base, key)], { stdio: 'inherit' });
|
||||
}
|
||||
}
|
||||
|
||||
class FileStorage implements DemoStorage {
|
||||
private readonly root: string;
|
||||
|
||||
constructor(root: string) {
|
||||
this.root = root;
|
||||
}
|
||||
|
||||
downloadDir(dir: string, target: string): boolean {
|
||||
const source = join(this.root, dir);
|
||||
|
||||
if (!existsSync(source)) return false;
|
||||
|
||||
cpSync(source, target, { recursive: true });
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
upload(file: string, key: string): void {
|
||||
const target = join(this.root, key);
|
||||
|
||||
mkdirSync(dirname(target), { recursive: true });
|
||||
copyFileSync(file, target);
|
||||
}
|
||||
}
|
||||
|
||||
export function getDemoStorage(uri = process.env.DEMO_STORAGE): DemoStorage | null {
|
||||
if (!uri) return null;
|
||||
|
||||
if (uri.startsWith('hf://')) return new HfStorage(uri);
|
||||
|
||||
if (uri.startsWith('file://')) return new FileStorage(fileURLToPath(uri));
|
||||
|
||||
throw new Error(`DEMO_STORAGE: unsupported scheme in "${uri}" (use hf:// or file://)`);
|
||||
}
|
||||
|
||||
/** Public URL of a stored key, when DEMO_STORAGE_PUBLIC_URL is set. */
|
||||
export function getPublicUrl(key: string): string | null {
|
||||
const base = process.env.DEMO_STORAGE_PUBLIC_URL;
|
||||
|
||||
return base ? joinKey(base, key) : null;
|
||||
}
|
||||
Generated
+19
@@ -21,6 +21,7 @@
|
||||
"@eslint/compat": "2.1.1",
|
||||
"@eslint/js": "10.0.1",
|
||||
"@ggml-org/llama-brand": "0.1.0",
|
||||
"@ggml-org/llama-demo": "file:../../lib/demo",
|
||||
"@internationalized/date": "3.12.2",
|
||||
"@lezer/highlight": "1.2.5",
|
||||
"@lucide/svelte": "1.46.0",
|
||||
@@ -100,6 +101,20 @@
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"../../lib/demo": {
|
||||
"name": "@ggml-org/llama-demo",
|
||||
"version": "0.1.0",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@playwright/test": "1.56.1",
|
||||
"@types/node": "24.13.0",
|
||||
"typescript": "6.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.18"
|
||||
}
|
||||
},
|
||||
"node_modules/@adobe/css-tools": {
|
||||
"version": "4.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.5.0.tgz",
|
||||
@@ -1083,6 +1098,10 @@
|
||||
"dev": true,
|
||||
"license": "CC-BY-NC-4.0 AND MIT AND OFL-1.1"
|
||||
},
|
||||
"node_modules/@ggml-org/llama-demo": {
|
||||
"resolved": "../../lib/demo",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@hono/node-server": {
|
||||
"version": "2.1.6",
|
||||
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.6.tgz",
|
||||
|
||||
@@ -81,6 +81,8 @@
|
||||
"@codemirror/view": "6.43.15",
|
||||
"@eslint/compat": "2.1.1",
|
||||
"@eslint/js": "10.0.1",
|
||||
"@ggml-org/llama-brand": "0.1.0",
|
||||
"@ggml-org/llama-demo": "file:../../lib/demo",
|
||||
"@internationalized/date": "3.12.2",
|
||||
"@lezer/highlight": "1.2.5",
|
||||
"@lucide/svelte": "1.46.0",
|
||||
@@ -119,7 +121,6 @@
|
||||
"globals": "16.5.0",
|
||||
"highlight.js": "11.11.1",
|
||||
"http-server": "14.1.1",
|
||||
"@ggml-org/llama-brand": "0.1.0",
|
||||
"mdsvex": "0.12.7",
|
||||
"mode-watcher": "1.1.0",
|
||||
"pdfjs-dist": "5.4.54",
|
||||
|
||||
+20
-4
@@ -5,9 +5,11 @@
|
||||
import { SyntaxHighlightedCode } from '#lib/components/app/index.ts';
|
||||
import { ICON_CLASS_DEFAULT, PDF_AS_IMAGES_LEGACY_CONTENT_REGEX } from '#lib/constants/index.ts';
|
||||
import { AttachmentType, MimeTypeApplication, PdfViewMode } from '#lib/enums/index.ts';
|
||||
import { settingsStore } from '#lib/stores/settings/index.svelte.ts';
|
||||
import type { ChatAttachmentDisplayItem } from '#lib/types/index.ts';
|
||||
import { convertPDFToImage, convertPDFToText } from '#lib/utils/browser-only.ts';
|
||||
import { getLanguageFromFilename } from '#lib/utils/index.ts';
|
||||
import { clampPdfDpi } from '#lib/utils/pdf-dpi.ts';
|
||||
|
||||
interface Props {
|
||||
currentItem: ChatAttachmentDisplayItem | null;
|
||||
@@ -23,7 +25,9 @@
|
||||
let pdfViewMode = $state<PdfViewMode>(PdfViewMode.PAGES);
|
||||
let pdfImages = $state<string[]>([]);
|
||||
let pdfImagesLoading = $state(false);
|
||||
// a failure stays on screen: the effect does not retry while an error is set
|
||||
// DPI the last fresh render (or failed attempt) used; stored attachment images are shown as-is
|
||||
let pdfImagesDpi = $state<number | null>(null);
|
||||
// a failure stays on screen: the effect does not retry while an error is set at the current DPI
|
||||
let pdfImagesError = $state<string | null>(null);
|
||||
let pdfText = $state<string | null>(null);
|
||||
let pdfTextLoading = $state(false);
|
||||
@@ -64,7 +68,7 @@
|
||||
}
|
||||
|
||||
async function loadPdfImages() {
|
||||
if (pdfImages.length > 0 || pdfImagesLoading || !currentItem) return;
|
||||
if (!currentItem) return;
|
||||
|
||||
if (
|
||||
currentItem.attachment?.type === AttachmentType.PDF &&
|
||||
@@ -75,9 +79,16 @@
|
||||
return;
|
||||
}
|
||||
|
||||
if (pdfImagesError) return;
|
||||
const dpi = clampPdfDpi(settingsStore.config.pdfDpi);
|
||||
|
||||
if (pdfImagesLoading) return;
|
||||
|
||||
if (pdfImages.length > 0 && pdfImagesDpi === dpi) return;
|
||||
|
||||
if (pdfImagesError && pdfImagesDpi === dpi) return;
|
||||
|
||||
pdfImagesLoading = true;
|
||||
pdfImagesError = null;
|
||||
|
||||
try {
|
||||
const file = getPdfFile();
|
||||
@@ -86,10 +97,12 @@
|
||||
throw new Error('No PDF file available for conversion');
|
||||
}
|
||||
|
||||
pdfImages = await convertPDFToImage(file);
|
||||
pdfImages = await convertPDFToImage(file, dpi);
|
||||
} catch (error) {
|
||||
pdfImagesError = error instanceof Error ? error.message : 'Failed to load PDF images';
|
||||
} finally {
|
||||
// remember the attempt even on failure, so a DPI change is the one retry
|
||||
pdfImagesDpi = dpi;
|
||||
pdfImagesLoading = false;
|
||||
}
|
||||
}
|
||||
@@ -123,6 +136,9 @@
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
// reaching the DPI here re-runs the effect when the setting changes
|
||||
void settingsStore.config.pdfDpi;
|
||||
|
||||
if (pdfViewMode === PdfViewMode.PAGES) {
|
||||
loadPdfImages();
|
||||
} else {
|
||||
|
||||
+2
-2
@@ -6,7 +6,7 @@
|
||||
import { Check, ChevronDown, ChevronRight, Info, Loader2, PencilRuler } from '@lucide/svelte';
|
||||
import { ATTACHMENT_MENU_TEXT, CLI_FLAGS, ICON_CLASS_DEFAULT } from '#lib/constants/index.ts';
|
||||
import { useToolsPanel } from '#lib/hooks/use-tools-panel.svelte.ts';
|
||||
import { mcpStore, toolsStore, uiStore } from '#lib/stores/index.ts';
|
||||
import { mcpStore, toolsStore } from '#lib/stores/index.ts';
|
||||
import type { ToolGroup } from '#lib/types/index.ts';
|
||||
|
||||
const toolsPanel = useToolsPanel();
|
||||
@@ -41,7 +41,7 @@
|
||||
</span>
|
||||
|
||||
<!-- only while MCP is on -->
|
||||
{#if uiStore.isMcpEnabled}
|
||||
{#if mcpStore.isFeatureEnabled}
|
||||
<span class="flex gap-2">
|
||||
<Info class="mt-0.5 {ICON_CLASS_DEFAULT} shrink-0" />
|
||||
|
||||
|
||||
@@ -46,6 +46,7 @@ export const SETTINGS_KEYS = {
|
||||
// Display
|
||||
PASTE_LONG_TEXT_TO_FILE_LEN: 'pasteLongTextToFileLen',
|
||||
PDF_AS_IMAGE: 'pdfAsImage',
|
||||
PDF_DPI: 'pdfDpi',
|
||||
// Performance
|
||||
PRE_ENCODE_CONVERSATION: 'preEncodeConversation',
|
||||
PRESENCE_PENALTY: 'presence_penalty',
|
||||
|
||||
@@ -3,6 +3,7 @@ import { CLI_FLAGS } from './cli-flags.constants';
|
||||
import { COMPACTION } from './compaction.constants';
|
||||
import { DEFAULT_MCP_CONFIG } from './mcp.constants';
|
||||
import { SETTINGS_KEYS } from './settings-keys.constants';
|
||||
import { PDF_RENDERING } from './supported-file-types.constants';
|
||||
import { TITLE_GENERATION } from './title-generation.constants';
|
||||
import { VOICE_TRANSCRIPTION_MODEL_AUTO } from './voice.constants';
|
||||
import { FILE_GLOB_SEARCH_PICKERS } from './working-directory.constants';
|
||||
@@ -233,6 +234,18 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [
|
||||
label: 'Parse PDF as image',
|
||||
type: SettingsFieldType.CHECKBOX
|
||||
},
|
||||
{
|
||||
defaultValue: PDF_RENDERING.DEFAULT_DPI,
|
||||
dependsOn: SETTINGS_KEYS.PDF_AS_IMAGE,
|
||||
help: 'Pixels per inch each PDF page renders as when it is parsed as images. 108 is the default; 216 is a good fit for dense tables.',
|
||||
isPositiveInteger: true,
|
||||
key: SETTINGS_KEYS.PDF_DPI,
|
||||
label: 'PDF image DPI',
|
||||
max: PDF_RENDERING.MAX_DPI,
|
||||
min: PDF_RENDERING.MIN_DPI,
|
||||
placeholder: String(PDF_RENDERING.DEFAULT_DPI),
|
||||
type: SettingsFieldType.INPUT
|
||||
},
|
||||
{
|
||||
defaultValue: 0,
|
||||
help: 'Images larger than this will be resized before sending to server. Set to 0 to disable.',
|
||||
|
||||
@@ -74,6 +74,14 @@ export const IMAGE_FILE_TYPES = {
|
||||
}
|
||||
} as const;
|
||||
|
||||
/** Rendering defaults for PDF pages converted to images. PDF.js maps 1.0 scale to 72 DPI. */
|
||||
export const PDF_RENDERING = {
|
||||
DEFAULT_DPI: 108,
|
||||
MAX_DPI: 600,
|
||||
MIN_DPI: 72,
|
||||
POINTS_PER_INCH: 72
|
||||
} as const;
|
||||
|
||||
/** `content` that messages stored before the text was kept carry for a PDF sent as images. */
|
||||
export const PDF_AS_IMAGES_LEGACY_CONTENT_REGEX = /^PDF file with \d+ pages$/;
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { CLI_FLAGS } from '#lib/constants/index.ts';
|
||||
import { ToolSource } from '#lib/enums/index.ts';
|
||||
import { conversationsStore, mcpStore, toolsStore, uiStore } from '#lib/stores/index.ts';
|
||||
import { conversationsStore, mcpStore, toolsStore } from '#lib/stores/index.ts';
|
||||
import type { ToolEntry, ToolGroup } from '#lib/types/index.ts';
|
||||
import { SvelteSet } from 'svelte/reactivity';
|
||||
|
||||
@@ -48,7 +48,7 @@ export function useToolsPanel(): UseToolsPanelReturn {
|
||||
if (toolsStore.toolGroups.length > 0) return null;
|
||||
|
||||
// the MCP half only while MCP is on
|
||||
const mcpHint = uiStore.isMcpEnabled
|
||||
const mcpHint = mcpStore.isFeatureEnabled
|
||||
? ' To see MCP Tools you need to add / enable MCP Server(s).'
|
||||
: '';
|
||||
|
||||
|
||||
@@ -97,7 +97,7 @@ class MCPStore implements McpHealthHost {
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether the Enable MCP setting is on. */
|
||||
/** Whether the Enable MCP setting is on. Off by default; while off, no MCP server is connected. */
|
||||
get isFeatureEnabled(): boolean {
|
||||
return Boolean(settingsStore.config[SETTINGS_KEYS.ENABLE_MCP]);
|
||||
}
|
||||
|
||||
@@ -117,11 +117,6 @@ class UiStore {
|
||||
return Boolean(settingsStore.getConfig(SETTINGS_KEYS.ENABLE_DISCOVER_MODELS));
|
||||
}
|
||||
|
||||
/** Whether MCP is on. Off by default; while off, no MCP server is connected. */
|
||||
get isMcpEnabled(): boolean {
|
||||
return Boolean(settingsStore.getConfig(SETTINGS_KEYS.ENABLE_MCP));
|
||||
}
|
||||
|
||||
/** Whether the model details drawer is open. */
|
||||
get isModelDetailsOpen(): boolean {
|
||||
return this.modelDetailsFocus !== null;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { clampPdfDpi } from './pdf-dpi';
|
||||
import { convertPDFToImage, convertPDFToText } from './pdf-processing';
|
||||
import { isSvgMimeType, svgBase64UrlToPngDataURL } from './svg-to-png';
|
||||
import { isLikelyTextFile, readFileAsText } from './text-files';
|
||||
@@ -152,7 +153,7 @@ export async function parseFilesToMessageExtras(
|
||||
if (shouldProcessAsImages) {
|
||||
// Process PDF as images (only for vision models)
|
||||
try {
|
||||
const images = await convertPDFToImage(file.file);
|
||||
const images = await convertPDFToImage(file.file, clampPdfDpi(currentConfig.pdfDpi));
|
||||
// kept for the preview's Text view; the model only receives the images
|
||||
const content = file.textContent ?? (await convertPDFToText(file.file).catch(() => ''));
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { PDF_RENDERING } from '#lib/constants/index.ts';
|
||||
|
||||
/**
|
||||
* A PDF.js scale is the ratio of rendered pixels to PDF points: at 1.0 a page renders at
|
||||
* 72 DPI, so scale is DPI / 72.
|
||||
* @param dpi - the DPI to convert
|
||||
* @returns the PDF.js scale factor for the given DPI
|
||||
*/
|
||||
export function pdfDpiToScale(dpi: number): number {
|
||||
return dpi / PDF_RENDERING.POINTS_PER_INCH;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clamp a user-supplied DPI into the supported range. Anything that is not a finite number
|
||||
* (missing key, empty field, junk) falls back to the default the setting ships with.
|
||||
* @param value - the raw value from the settings config
|
||||
* @returns a DPI between MIN_DPI and MAX_DPI
|
||||
*/
|
||||
export function clampPdfDpi(value: unknown): number {
|
||||
const dpi = typeof value === 'string' ? (value.trim() === '' ? undefined : Number(value)) : value;
|
||||
|
||||
if (typeof dpi !== 'number' || !Number.isFinite(dpi)) return PDF_RENDERING.DEFAULT_DPI;
|
||||
|
||||
return Math.min(Math.max(Math.round(dpi), PDF_RENDERING.MIN_DPI), PDF_RENDERING.MAX_DPI);
|
||||
}
|
||||
@@ -3,7 +3,9 @@
|
||||
* Handles PDF text extraction and image conversion in the browser
|
||||
*/
|
||||
|
||||
import { PDF_RENDERING } from '#lib/constants/index.ts';
|
||||
import { MimeTypeApplication, MimeTypeImage } from '#lib/enums/index.ts';
|
||||
import { clampPdfDpi, pdfDpiToScale } from '#lib/utils/pdf-dpi.ts';
|
||||
import { browser } from '$app/env';
|
||||
import pdfWorkerUrl from 'pdfjs-dist/build/pdf.worker.min.mjs?url';
|
||||
|
||||
@@ -87,10 +89,13 @@ export async function convertPDFToText(file: File): Promise<string> {
|
||||
/**
|
||||
* Convert PDF pages to PNG images as data URLs
|
||||
* @param file - The PDF file to convert
|
||||
* @param scale - Rendering scale factor (default: 1.5)
|
||||
* @param dpi - Rendering DPI (default: 108, the scale the app shipped with)
|
||||
* @returns Promise resolving to array of PNG data URLs
|
||||
*/
|
||||
export async function convertPDFToImage(file: File, scale: number = 1.5): Promise<string[]> {
|
||||
export async function convertPDFToImage(
|
||||
file: File,
|
||||
dpi: number = PDF_RENDERING.DEFAULT_DPI
|
||||
): Promise<string[]> {
|
||||
if (!browser) {
|
||||
throw new Error('PDF processing is only available in the browser');
|
||||
}
|
||||
@@ -99,6 +104,7 @@ export async function convertPDFToImage(file: File, scale: number = 1.5): Promis
|
||||
const [pdfjs, buffer] = await Promise.all([loadPdfjs(), getFileAsBuffer(file)]);
|
||||
const doc = await pdfjs.getDocument({ data: buffer }).promise;
|
||||
const pages: Promise<string>[] = [];
|
||||
const scale = pdfDpiToScale(clampPdfDpi(dpi));
|
||||
|
||||
for (let i = 1; i <= doc.numPages; i++) {
|
||||
const page = await doc.getPage(i);
|
||||
|
||||
@@ -48,7 +48,7 @@
|
||||
import { browser } from '$app/env';
|
||||
import { afterNavigate, goto } from '$app/navigation';
|
||||
import { page } from '$app/state';
|
||||
import { ModeWatcher } from 'mode-watcher';
|
||||
import { mode, ModeWatcher } from 'mode-watcher';
|
||||
import { untrack } from 'svelte';
|
||||
import { onMount } from 'svelte';
|
||||
import { fade } from 'svelte/transition';
|
||||
@@ -467,7 +467,7 @@
|
||||
|
||||
<ModeWatcher />
|
||||
|
||||
<Toaster closeButton richColors />
|
||||
<Toaster closeButton richColors theme={mode.current} />
|
||||
|
||||
{#if dropImport.isDragOver}
|
||||
<DropImportOverlay />
|
||||
|
||||
@@ -32,6 +32,16 @@ function pdfWithText(text: string): File {
|
||||
return new File([body], 'hello.pdf', { type: 'application/pdf' });
|
||||
}
|
||||
|
||||
function imageDimensions(dataUrl: string): Promise<{ width: number; height: number }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
|
||||
img.onload = () => resolve({ height: img.naturalHeight, width: img.naturalWidth });
|
||||
img.onerror = () => reject(new Error('Failed to decode the rendered PNG'));
|
||||
img.src = dataUrl;
|
||||
});
|
||||
}
|
||||
|
||||
describe('pdf-processing', () => {
|
||||
it('extracts the text of a PDF', async () => {
|
||||
const text = await convertPDFToText(pdfWithText('Hello from a PDF'));
|
||||
@@ -45,4 +55,32 @@ describe('pdf-processing', () => {
|
||||
expect(pages).toHaveLength(1);
|
||||
expect(pages[0]).toMatch(/^data:image\/png;base64,/);
|
||||
});
|
||||
|
||||
it('renders pages at the requested DPI', async () => {
|
||||
const onePage = pdfWithText('Page one');
|
||||
const atDefault = await convertPDFToImage(onePage);
|
||||
const at216 = await convertPDFToImage(onePage, 216);
|
||||
const at72 = await convertPDFToImage(onePage, 72);
|
||||
|
||||
expect(atDefault[0]).toMatch(/^data:image\/png;base64,/);
|
||||
|
||||
const defaultSize = await imageDimensions(atDefault[0]);
|
||||
const highSize = await imageDimensions(at216[0]);
|
||||
const lowSize = await imageDimensions(at72[0]);
|
||||
|
||||
// the fixture page is 612 x 792 PDF points, so 72 DPI is 1:1
|
||||
expect(lowSize.width).toBe(612);
|
||||
expect(lowSize.height).toBe(792);
|
||||
// 216 DPI is 2x the scale the default (108) renders at
|
||||
expect(highSize.width).toBeCloseTo(defaultSize.width * 2, 0);
|
||||
expect(highSize.height).toBeCloseTo(defaultSize.height * 2, 0);
|
||||
});
|
||||
|
||||
it('clamps an out-of-range DPI instead of rendering it', async () => {
|
||||
const pages = await convertPDFToImage(pdfWithText('Page one'), 10);
|
||||
const size = await imageDimensions(pages[0]);
|
||||
|
||||
// 10 DPI clamps to 72, the 1:1 scale
|
||||
expect(size.width).toBe(612);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { mockLlamaServer } from '../../demo/fixtures/llama-server.ts';
|
||||
import { generateTrace } from '../../demo/fixtures/traces.ts';
|
||||
import { importTraces } from '../../demo/helpers.ts';
|
||||
import { expect, test } from '@playwright/test';
|
||||
import { writeFileSync } from 'node:fs';
|
||||
|
||||
test('search finds a chat by its title and opens it', async ({ page }, testInfo) => {
|
||||
const file = testInfo.outputPath('traces.jsonl');
|
||||
|
||||
writeFileSync(file, [generateTrace('long-chat'), generateTrace('agentic-debugging')].join('\n'));
|
||||
await mockLlamaServer(page);
|
||||
await page.goto('/');
|
||||
await importTraces(page, file);
|
||||
await page.reload();
|
||||
|
||||
await page.getByLabel('Expand navigation').click();
|
||||
await page.getByRole('button', { name: /^Search/ }).click();
|
||||
|
||||
const search = page.getByRole('dialog', { name: 'Search' });
|
||||
|
||||
await search.getByRole('combobox', { name: 'Search' }).fill('flaky');
|
||||
await search.getByRole('option', { name: /Fix the flaky cache tests/ }).click();
|
||||
|
||||
await expect(page.getByRole('main')).toContainText('All 48 cache tests pass now');
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { PDF_RENDERING, SETTING_CONFIG_DEFAULT, SETTINGS_KEYS } from '#lib/constants/index.ts';
|
||||
import { clampPdfDpi, pdfDpiToScale } from '#lib/utils/pdf-dpi.ts';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
describe('pdf-dpi', () => {
|
||||
it('converts DPI to a PDF.js scale factor of pixels per PDF point', () => {
|
||||
expect(pdfDpiToScale(72)).toBe(1);
|
||||
expect(pdfDpiToScale(108)).toBeCloseTo(1.5, 10);
|
||||
expect(pdfDpiToScale(216)).toBe(3);
|
||||
});
|
||||
|
||||
it('rounds, clamps and falls back to the default', () => {
|
||||
expect(clampPdfDpi(108)).toBe(108);
|
||||
expect(clampPdfDpi(216.4)).toBe(216);
|
||||
expect(clampPdfDpi(1000)).toBe(PDF_RENDERING.MAX_DPI);
|
||||
expect(clampPdfDpi(10)).toBe(PDF_RENDERING.MIN_DPI);
|
||||
expect(clampPdfDpi('216')).toBe(216);
|
||||
expect(clampPdfDpi('junk')).toBe(PDF_RENDERING.DEFAULT_DPI);
|
||||
expect(clampPdfDpi('')).toBe(PDF_RENDERING.DEFAULT_DPI);
|
||||
expect(clampPdfDpi(' ')).toBe(PDF_RENDERING.DEFAULT_DPI);
|
||||
expect(clampPdfDpi(undefined)).toBe(PDF_RENDERING.DEFAULT_DPI);
|
||||
expect(clampPdfDpi(null)).toBe(PDF_RENDERING.DEFAULT_DPI);
|
||||
expect(clampPdfDpi(NaN)).toBe(PDF_RENDERING.DEFAULT_DPI);
|
||||
expect(clampPdfDpi(Infinity)).toBe(PDF_RENDERING.DEFAULT_DPI);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PDF DPI setting', () => {
|
||||
it('ships a default that is inside its own range', () => {
|
||||
expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.PDF_DPI]).toBe(PDF_RENDERING.DEFAULT_DPI);
|
||||
expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.PDF_DPI]).toBeGreaterThanOrEqual(
|
||||
PDF_RENDERING.MIN_DPI
|
||||
);
|
||||
expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.PDF_DPI]).toBeLessThanOrEqual(
|
||||
PDF_RENDERING.MAX_DPI
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
node_modules
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
@@ -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,141 @@
|
||||
# @ggml-org/llama-demo
|
||||
|
||||
Scripted demo videos of the llama.cpp frontend apps, for pull requests and docs: a Playwright script drives the app like a person, and the harness records it and renders an mp4 with an animated GIF preview. It lives in llama.cpp at `ui/lib/demo`. It is a private package, not published to npm: an app in this repo adds it as a local dependency and imports it by name.
|
||||
|
||||
- **PR demos** live in the PR description, as a `ts demo` code block.
|
||||
- **Docs demos** live in the storage target, under `scripts/docs/`.
|
||||
|
||||
```text
|
||||
src/
|
||||
├── index.ts the entry an app's demo fixtures import
|
||||
├── demo.ts Demo: the cursor or fingertip, human timing, captions, voice, camera zooms
|
||||
├── recording.ts prepareDemoPage and recordDemo, the recording round a demo
|
||||
├── recorder.ts screencast recording and the plain mp4
|
||||
├── polish.ts the render: window, ground, camera, captions
|
||||
├── cli.ts runDemoCli: the pr and docs commands
|
||||
└── storage.ts storage targets (hf://, file://)
|
||||
```
|
||||
|
||||
Playwright is only a type here: the app passes in its page and test, so the harness loads no Playwright of its own, and runs with nothing installed in this folder. `npm ci` here is only for `npm run check`.
|
||||
|
||||
## In an app
|
||||
|
||||
Add it to the app's `devDependencies` as a local package, which npm links to this folder, so no copy is installed and nothing is published:
|
||||
|
||||
```json
|
||||
"@ggml-org/llama-demo": "file:../../lib/demo"
|
||||
```
|
||||
|
||||
Then import it by name: `@ggml-org/llama-demo` for the fixtures' parts (`Demo`, `prepareDemoPage`, `recordDemo`) and `@ggml-org/llama-demo/cli` for `runDemoCli`. Node runs its TypeScript sources directly, through the link.
|
||||
|
||||
An app has a `demo/` folder with three files ([Llama Chat's](../../apps/chat/demo/README.md) is the example):
|
||||
|
||||
- **`helpers.ts`**: a Playwright `test` with a `demo` fixture and a `page` fixture that sets the scene. The page fixture calls `prepareDemoPage(page, testInfo)` before the page loads, then `recordDemo(page, testInfo, options, () => use(page))` once the app is ready. `options` names `@ggml-org/llama-brand`'s folder, whether the page is dark, and where the videos go.
|
||||
- **`playwright.config.ts`**: the servers the app needs. `demo:pr` passes `DEMO_UI_DIR` (the PR's checkout of the app), `DEMO_UI_PORT` and `DEMO_STORYBOOK_PORT` to it.
|
||||
- **`cli.ts`**: `runDemoCli({ demoDir, dir, commands, linkNodeModules })`, with the app's own commands beside `pr` and `docs`.
|
||||
|
||||
## Setup
|
||||
|
||||
| Tool | Used for |
|
||||
| ---------------------------------------------------- | -------------------------------------------------------------------------------------------- |
|
||||
| Node 22.18+ | runs the TypeScript directly (type stripping) |
|
||||
| `npx playwright install chromium` | the browser demos record in, with its sandbox on |
|
||||
| `ffmpeg` | mp4 encoding and the GIF preview |
|
||||
| `gh`, logged in | reads the PR description and writes the `## Demo` section, so you need edit rights on the PR |
|
||||
| `hf`, logged in with a write token (`hf auth login`) | uploads to the bucket |
|
||||
|
||||
`gh` is only needed for `demo:pr`, and `hf` only with the bucket below. Without them, the video stays in the app's `demo/videos/`.
|
||||
|
||||
The page is recorded through Chromium's screencast at the device pixel ratio the app's config sets (2x in Llama Chat) and 60 fps, starting once the page has settled. The video is then rendered from those frames at 1920x1080, or 1080x1920 for a portrait viewport (see [The render](#the-render)).
|
||||
|
||||
### Hugging Face bucket (videos, previews, scripts)
|
||||
|
||||
The bucket must be public, since GitHub loads the preview from it:
|
||||
|
||||
```bash
|
||||
hf buckets create <owner>/llama-ui-demos
|
||||
```
|
||||
|
||||
Then set it in the app's `.env`:
|
||||
|
||||
```bash
|
||||
DEMO_STORAGE='hf://buckets/<owner>/llama-ui-demos'
|
||||
DEMO_STORAGE_PUBLIC_URL='https://huggingface.co/buckets/<owner>/llama-ui-demos/resolve'
|
||||
```
|
||||
|
||||
Layout: `videos/pr/<number>/<sha>.{mp4,gif,demo.ts}`, `videos/docs/<name>.{mp4,gif}` and `scripts/docs/*.demo.ts` (the docs scripts). Without `DEMO_STORAGE_PUBLIC_URL`, videos are uploaded but not linked in the PR. `DEMO_STORAGE='file:///some/dir'` stores them in a local folder instead.
|
||||
|
||||
Only Hugging Face buckets and `file://` folders are supported for now. S3, R2 or similar would be one more class in `storage.ts` (`upload` and `downloadDir`) plus the matching `DEMO_STORAGE_PUBLIC_URL`.
|
||||
|
||||
## Recording a pull request
|
||||
|
||||
Add the script to the PR description:
|
||||
|
||||
````md
|
||||
<details>
|
||||
<summary>Demo script</summary>
|
||||
|
||||
```ts demo
|
||||
test("demo", async ({ demo, page }) => {
|
||||
await demo.click(page.getByRole("button", { exact: true, name: "Settings" }));
|
||||
await demo.caption("What this shows");
|
||||
});
|
||||
```
|
||||
|
||||
</details>
|
||||
````
|
||||
|
||||
Then run `npm run demo:pr -- <number>` in the app. It checks out the PR head in a temporary worktree, records the script against it, uploads `videos/pr/<number>/<sha>.{mp4,gif,demo.ts}` and adds or updates a `## Demo` section in the PR description with the preview linking to the video. `DEMO_GITHUB_REPO` picks another repository, such as a fork.
|
||||
|
||||
A PR by someone else runs its code and demo script on your machine, with your `gh` and `hf` logins, so `demo:pr` refuses it until you've read its diff and demo block and pass the head commit you read: `npm run demo:pr -- <number> --trust <sha>`. If the PR gets new commits, it refuses again.
|
||||
|
||||
A large PR can show its changes in several shorter videos: each `test()` in the block is recorded as its own video (`<sha>-1.mp4`, `<sha>-2.mp4`, ...), and the `## Demo` section shows their previews in a table, each headed by its test's title: up to four portrait (phone) videos to a row, or two landscape ones. Helpers and `test.use` at the top of the block are shared by all of them.
|
||||
|
||||
To say what each video shows, give its test a `description` annotation. When the tests have one, the table puts one video to a row, with its title and description beside it:
|
||||
|
||||
```ts
|
||||
test(
|
||||
"Taps instead of a cursor on a phone",
|
||||
{
|
||||
annotation: {
|
||||
description: "A click shows as a fingertip tap.",
|
||||
type: "description",
|
||||
},
|
||||
},
|
||||
async ({ demo, page }) => {
|
||||
// ...
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
GitHub has no API for attachments, so for an inline player drag the mp4 from `demo/videos/` into the description instead.
|
||||
|
||||
## Recording docs
|
||||
|
||||
`npm run demo:docs` in the app records every `scripts/docs/*.demo.ts` from the storage target and uploads `videos/docs/<name>.{mp4,gif}`.
|
||||
|
||||
## Writing a demo
|
||||
|
||||
Scripts get `test` and `expect` from the app's `helpers.ts`. `demo.click`, `demo.hover` and `demo.type` glide a visible cursor to the target before acting, with timing varied like a person's (seeded per demo, so re-takes match); on a touch device (`hasTouch`) there is no cursor, and a click shows as a tap of a fingertip; `demo.scroll` turns the mouse wheel over a target; `demo.zoom` moves the camera in on a control or a point to show a detail too small to read in the frame, holds, and moves back out; `demo.zoomIn` and `demo.zoomOut` do the two halves, to keep the camera on a detail while the demo goes on (a phone demo rarely needs either, as a phone's UI already fills a portrait video); `demo.caption` shows a caption under the window. For voice input, `demo.microphone()` gives the page a microphone that hears nothing but `demo.speak(text)`, which reads the text in a synthetic voice (macOS `say`) and shows it as a caption, since the video has no sound.
|
||||
|
||||
```ts
|
||||
await demo.zoomIn(page.getByRole("dialog"), 1.5);
|
||||
await demo.type(search, "Inkling-2-Mini");
|
||||
await demo.zoomOut();
|
||||
```
|
||||
|
||||
## The render
|
||||
|
||||
A video is not the raw screencast. The app sits in a rounded window on a ground of the Llama brand (the day sky, or the night sky for a dark recording), a phone's viewport gets a phone's rounder corners, and captions are chips under the window, in Llama Sans. `demo.zoom` moves a camera over the whole stage, with eased moves and motion blur: the window itself comes closer, with its corners and the ground round it, and the app is not cropped inside a fixed window. The grounds, the fonts and the lockup come from `@ggml-org/llama-brand`, which the app depends on, and sizes follow the brand's grid (u = the short side / 24, a margin of 2u).
|
||||
|
||||
| Variable | Values | Default |
|
||||
| -------------------- | ----------------------------------------- | -------------------------------------- |
|
||||
| `DEMO_POLISH` | `0` for the plain screencast | on |
|
||||
| `DEMO_POLISH_GROUND` | `day`, `night`, `light`, `dark`, `sand` | `day`, or `night` for a dark recording |
|
||||
| `DEMO_POLISH_LOGO` | `start`, `end`, `both`: a Llama logo card | none |
|
||||
|
||||
With `DEMO_POLISH=0` the video is the screencast as recorded: `demo.zoom` pinches the page (with the fingertips drawn on a touch device), captions show over the app, and `demo.zoomIn` and `demo.zoomOut` do nothing, as the cursor cannot act on a pinched page.
|
||||
|
||||
The render needs no extra tool: a page in a Chromium of its own lays out each frame on one canvas from the recorded frames and the script's timeline, and `ffmpeg` encodes them. It takes a few times as long as the video, and longer with many camera moves.
|
||||
|
||||
For agents, [skills/ui-demo](../../../skills/ui-demo/SKILL.md) walks through a demo, an e2e check and docs media for one change.
|
||||
Generated
+115
@@ -0,0 +1,115 @@
|
||||
{
|
||||
"name": "@ggml-org/llama-demo",
|
||||
"version": "0.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@ggml-org/llama-demo",
|
||||
"version": "0.1.0",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@playwright/test": "1.56.1",
|
||||
"@types/node": "24.13.0",
|
||||
"typescript": "6.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.18"
|
||||
}
|
||||
},
|
||||
"node_modules/@playwright/test": {
|
||||
"version": "1.56.1",
|
||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.56.1.tgz",
|
||||
"integrity": "sha512-vSMYtL/zOcFpvJCW71Q/OEGQb7KYBPAdKh35WNSkaZA75JlAO8ED8UN6GUNTm3drWomcbcqRPFqQbLae8yBTdg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright": "1.56.1"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "24.13.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.0.tgz",
|
||||
"integrity": "sha512-5vtOqGQr4NJKeEzV441FcOi2MeG9UTWq9LqVLGneDdu4vlX17H8kQ2PA2UmNwCUGPVDj4oBjNhS7ReVEIWJJrg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~7.18.0"
|
||||
}
|
||||
},
|
||||
"node_modules/fsevents": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.56.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.56.1.tgz",
|
||||
"integrity": "sha512-aFi5B0WovBHTEvpM3DzXTUaeN6eN0qWnTkKx4NQaH4Wvcmc153PdaY2UBdSYKaGYw+UyWXSVyxDUg5DoPEttjw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.56.1"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"fsevents": "2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.56.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.56.1.tgz",
|
||||
"integrity": "sha512-hutraynyn31F+Bifme+Ps9Vq59hKuUCz7H1kDOcBs+2oGguKkWTU50bBWrtz34OUWmIwpBTWDxaRPXrIXkgvmQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "6.0.3",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",
|
||||
"integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "7.18.2",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
|
||||
"integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "@ggml-org/llama-demo",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Scripted demo videos of llama.cpp frontend apps, for pull requests and docs.",
|
||||
"homepage": "https://github.com/ggml-org/llama.cpp/tree/master/ui/lib/demo",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/ggml-org/llama.cpp.git",
|
||||
"directory": "ui/lib/demo"
|
||||
},
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./cli": "./src/cli.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"check": "tsc --noEmit"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "1.56.1",
|
||||
"@types/node": "24.13.0",
|
||||
"typescript": "6.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.18"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,493 @@
|
||||
/**
|
||||
* Records demo videos for pull requests and docs. An app runs it from its own demo/cli.ts:
|
||||
*
|
||||
* pr <number> record the ```ts demo block from a PR description, a video per test
|
||||
* (--trust <sha> to record someone else's PR at that head commit)
|
||||
* docs record every docs/*.demo.ts script in DEMO_STORAGE
|
||||
*
|
||||
* plus any commands of the app's own. Settings come from the app's .env.
|
||||
*/
|
||||
|
||||
import { type DemoStorage, getDemoStorage, getPublicUrl } from "./storage.ts";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { createServer } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import { basename, join, relative } from "node:path";
|
||||
|
||||
/** An app the CLI records demos of. */
|
||||
export interface DemoApp {
|
||||
/** More commands, such as writing the app's fixtures, each given the arguments after it. */
|
||||
commands?: Record<string, (args: string[]) => Promise<void> | void>;
|
||||
/** The app's demo folder: its helpers.ts, playwright.config.ts and videos/. */
|
||||
demoDir: string;
|
||||
/** The app's folder, with its node_modules and .env, where Playwright runs. */
|
||||
dir: string;
|
||||
/**
|
||||
* Folders, relative to `dir`, whose node_modules a PR's worktree also needs, such as a
|
||||
* library the app builds from source. The app's own are always linked.
|
||||
*/
|
||||
linkNodeModules?: string[];
|
||||
}
|
||||
|
||||
let app: DemoApp;
|
||||
let REPO = "";
|
||||
const runsDir = () => join(app.demoDir, ".runs");
|
||||
const videosDir = () => join(app.demoDir, "videos");
|
||||
const DEMO_BLOCK = /```(?:ts|typescript)[ \t]+demo[ \t]*\r?\n([\s\S]*?)```/;
|
||||
const HELPERS_IMPORT =
|
||||
/^import\s[^;]*from\s+['"][^'"]*helpers(?:\.ts)?['"];?\s*$/gm;
|
||||
const SECTION_START = "<!-- demo:start -->";
|
||||
const SECTION_END = "<!-- demo:end -->";
|
||||
/** GitHub's image proxy refuses larger images, so a bigger preview shows as a broken image. */
|
||||
const PREVIEW_MAX_BYTES = 5 * 1024 * 1024;
|
||||
function run(
|
||||
cmd: string,
|
||||
args: string[],
|
||||
opts: { cwd?: string; env?: NodeJS.ProcessEnv } = {},
|
||||
): string {
|
||||
return execFileSync(cmd, args, {
|
||||
cwd: opts.cwd ?? app.dir,
|
||||
encoding: "utf8",
|
||||
env: opts.env,
|
||||
}).trim();
|
||||
}
|
||||
|
||||
/** Writes a demo script into .runs/, importing the harness helpers. */
|
||||
function writeDemoScript(name: string, source: string): string {
|
||||
const file = join(runsDir(), `${name}.demo.ts`);
|
||||
const helpers = relative(runsDir(), join(app.demoDir, "helpers.ts"));
|
||||
const body = source.replace(HELPERS_IMPORT, "").trim();
|
||||
|
||||
mkdirSync(runsDir(), { recursive: true });
|
||||
writeFileSync(
|
||||
file,
|
||||
`import { expect, test } from './${helpers}';\n\n${body}\n`,
|
||||
);
|
||||
|
||||
return file;
|
||||
}
|
||||
|
||||
async function freePort(): Promise<number> {
|
||||
return new Promise((done, fail) => {
|
||||
const server = createServer();
|
||||
|
||||
server.once("error", fail);
|
||||
server.listen(0, () => {
|
||||
const { port } = server.address() as { port: number };
|
||||
|
||||
server.close(() => done(port));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** A video recorded from one `test()` of a script. */
|
||||
interface Video {
|
||||
/** From the test's `description` annotation, shown beside its video in the PR. */
|
||||
description?: string;
|
||||
mp4: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
/** Records the given scripts; returns a video for each of their tests, in order. */
|
||||
async function record(scripts: string[], uiDir = app.dir): Promise<Video[]> {
|
||||
const port = await freePort();
|
||||
const manifests = scripts.map((s) =>
|
||||
join(videosDir(), `${basename(s, ".demo.ts")}.videos.jsonl`),
|
||||
);
|
||||
|
||||
for (const manifest of manifests) rmSync(manifest, { force: true });
|
||||
|
||||
execFileSync(
|
||||
"npx",
|
||||
[
|
||||
"playwright",
|
||||
"test",
|
||||
`--config=${relative(app.dir, join(app.demoDir, "playwright.config.ts"))}`,
|
||||
...scripts.map((s) => relative(app.dir, s)),
|
||||
],
|
||||
{
|
||||
cwd: app.dir,
|
||||
env: {
|
||||
...process.env,
|
||||
DEMO_STORYBOOK_PORT: String(await freePort()),
|
||||
DEMO_UI_DIR: uiDir,
|
||||
DEMO_UI_PORT: String(port),
|
||||
},
|
||||
stdio: "inherit",
|
||||
},
|
||||
);
|
||||
|
||||
// helpers.ts lists each video it encodes in the script's manifest
|
||||
return manifests.flatMap((manifest) =>
|
||||
readFileSync(manifest, "utf8")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => JSON.parse(line) as Video),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Animated GIF preview that GitHub renders inline, its longer side DEMO_PREVIEW_WIDTH (so a
|
||||
* phone's portrait video is that tall), shrunk until it fits under PREVIEW_MAX_BYTES.
|
||||
*/
|
||||
function makePreview(mp4: string): string {
|
||||
const gif = mp4.replace(/\.mp4$/, ".gif");
|
||||
|
||||
for (
|
||||
let side = Number(process.env.DEMO_PREVIEW_WIDTH ?? 800);
|
||||
;
|
||||
side = Math.round(side * 0.8)
|
||||
) {
|
||||
execFileSync("ffmpeg", [
|
||||
"-y",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-i",
|
||||
mp4,
|
||||
"-vf",
|
||||
`fps=10,scale='if(gt(iw,ih),${side},-2)':'if(gt(iw,ih),-2,${side})':flags=lanczos,split[a][b];[a]palettegen=stats_mode=diff[p];[b][p]paletteuse=dither=bayer:bayer_scale=5:diff_mode=rectangle`,
|
||||
"-loop",
|
||||
"0",
|
||||
gif,
|
||||
]);
|
||||
|
||||
if (statSync(gif).size <= PREVIEW_MAX_BYTES || side < 320) return gif;
|
||||
}
|
||||
}
|
||||
|
||||
function upload(storage: DemoStorage, files: Record<string, string>): void {
|
||||
for (const [key, file] of Object.entries(files)) {
|
||||
storage.upload(file, key);
|
||||
console.log(`uploaded ${key}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Public URL with a content hash, so a re-recorded file at the same key gets a new
|
||||
* URL: GitHub's image proxy caches previews by URL.
|
||||
*/
|
||||
function versionedUrl(key: string, file: string): null | string {
|
||||
const url = getPublicUrl(key);
|
||||
const version = createHash("sha1")
|
||||
.update(readFileSync(file))
|
||||
.digest("hex")
|
||||
.slice(0, 10);
|
||||
|
||||
return url && `${url}?v=${version}`;
|
||||
}
|
||||
|
||||
/** Whether a video is taller than wide, like a phone's. */
|
||||
function isPortrait(mp4: string): boolean {
|
||||
const [width, height] = run("ffprobe", [
|
||||
"-v",
|
||||
"error",
|
||||
"-select_streams",
|
||||
"v:0",
|
||||
"-show_entries",
|
||||
"stream=width,height",
|
||||
"-of",
|
||||
"csv=p=0",
|
||||
mp4,
|
||||
])
|
||||
.split(",")
|
||||
.map(Number);
|
||||
|
||||
return height > width;
|
||||
}
|
||||
|
||||
/**
|
||||
* One preview, or a table of them when the script has several tests, each headed by its
|
||||
* test's title: up to four portrait videos to a row, or two landscape ones, so each stays
|
||||
* large enough to read. When the tests have descriptions, a video to a row instead, with its
|
||||
* title and description beside it.
|
||||
*/
|
||||
function demoSection(
|
||||
links: { description?: string; gif: string; mp4: string; title: string }[],
|
||||
sha: string,
|
||||
columns: number,
|
||||
): string {
|
||||
const preview = ({ gif, mp4, title }: (typeof links)[number]) =>
|
||||
`[![${title.replace(/[[\]|]/g, "")}](${gif})](${mp4})`;
|
||||
// a line break would end the table row, so it becomes one inside the cell
|
||||
const cell = (text: string) =>
|
||||
text.replace(/\|/g, "\\|").replace(/\r?\n/g, "<br>");
|
||||
const rows = Array.from(
|
||||
{ length: Math.ceil(links.length / columns) },
|
||||
(_, i) => links.slice(i * columns, (i + 1) * columns),
|
||||
);
|
||||
const pad = (cells: string[]) => [
|
||||
...cells,
|
||||
...Array(columns - cells.length).fill(" "),
|
||||
];
|
||||
const described = [
|
||||
"| Video | What it shows |",
|
||||
"|---|---|",
|
||||
...links.map(
|
||||
(l) =>
|
||||
`| ${preview(l)} | **${cell(l.title)}**${l.description ? `<br><br>${cell(l.description)}` : ""} |`,
|
||||
),
|
||||
];
|
||||
const body = links.some((l) => l.description)
|
||||
? described
|
||||
: links.length === 1
|
||||
? [preview({ ...links[0], title: "Demo" })]
|
||||
: rows.flatMap((row, i) => [
|
||||
// a table has one header row, so later rows title their videos in bold
|
||||
`| ${pad(row.map((l) => (i === 0 ? cell(l.title) : `**${cell(l.title)}**`))).join(" | ")} |`,
|
||||
...(i === 0 ? [`|${Array(columns).fill("---").join("|")}|`] : []),
|
||||
`| ${pad(row.map(preview)).join(" | ")} |`,
|
||||
]);
|
||||
const note =
|
||||
links.length === 1
|
||||
? "the preview for the full video"
|
||||
: "a preview for its full video";
|
||||
|
||||
return [
|
||||
SECTION_START,
|
||||
...body,
|
||||
"",
|
||||
`Recorded at ${sha.slice(0, 10)}; click ${note}.`,
|
||||
SECTION_END,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/** Replaces the managed demo section, or adds a `## Demo` section before the details. */
|
||||
function withDemoSection(body: string, section: string): string {
|
||||
const start = body.indexOf(SECTION_START);
|
||||
const end = body.indexOf(SECTION_END);
|
||||
|
||||
if (start !== -1 && end > start) {
|
||||
return (
|
||||
body.slice(0, start) + section + body.slice(end + SECTION_END.length)
|
||||
);
|
||||
}
|
||||
|
||||
const block = `## Demo\n\n${section}\n\n`;
|
||||
const anchor = body.search(/^## (Additional information|Requirements)\b/m);
|
||||
|
||||
return anchor === -1
|
||||
? `${body.trimEnd()}\n\n${block}`
|
||||
: body.slice(0, anchor) + block + body.slice(anchor);
|
||||
}
|
||||
|
||||
async function recordPr(number: string, trustedSha?: string): Promise<void> {
|
||||
const pr = JSON.parse(
|
||||
run("gh", [
|
||||
"pr",
|
||||
"view",
|
||||
number,
|
||||
"--repo",
|
||||
REPO,
|
||||
"--json",
|
||||
"author,body,headRefOid",
|
||||
]),
|
||||
) as { author: { login: string }; body: string; headRefOid: string };
|
||||
const source = DEMO_BLOCK.exec(pr.body)?.[1];
|
||||
|
||||
if (!source)
|
||||
throw new Error(
|
||||
`PR #${number} has no \`\`\`ts demo block in its description`,
|
||||
);
|
||||
|
||||
const sha = pr.headRefOid;
|
||||
|
||||
// the PR's code and demo script run on this machine, with the gh and hf logins,
|
||||
// so someone else's PR only runs at a head commit you've read and passed to --trust
|
||||
if (pr.author.login !== run("gh", ["api", "user", "--jq", ".login"])) {
|
||||
if (!trustedSha) {
|
||||
throw new Error(
|
||||
`PR #${number} is by ${pr.author.login}, and recording it runs its code here: ` +
|
||||
`read its diff and demo block, then run again with --trust ${sha.slice(0, 10)}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (trustedSha.length < 7 || !sha.startsWith(trustedSha)) {
|
||||
throw new Error(
|
||||
`PR #${number} head is ${sha.slice(0, 10)}, not the trusted ${trustedSha}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const worktree = join(tmpdir(), `llama-ui-demo-pr-${number}`);
|
||||
|
||||
run("git", [
|
||||
"fetch",
|
||||
"--no-tags",
|
||||
`https://github.com/${REPO}.git`,
|
||||
`pull/${number}/head`,
|
||||
]);
|
||||
|
||||
if (run("git", ["rev-parse", "FETCH_HEAD"]) !== sha) {
|
||||
throw new Error(`PR #${number} head moved while fetching, run again`);
|
||||
}
|
||||
|
||||
rmSync(worktree, { force: true, recursive: true });
|
||||
run("git", ["worktree", "prune"]);
|
||||
run("git", ["worktree", "add", "--detach", worktree, sha]);
|
||||
// git's own path from the top to the app, so a symlinked checkout path cannot skew it
|
||||
const appInWorktree = join(
|
||||
worktree,
|
||||
run("git", ["rev-parse", "--show-prefix"], { cwd: app.dir }),
|
||||
);
|
||||
|
||||
for (const dir of [".", ...(app.linkNodeModules ?? [])]) {
|
||||
const modules = join(app.dir, dir, "node_modules");
|
||||
|
||||
if (existsSync(modules))
|
||||
symlinkSync(modules, join(appInWorktree, dir, "node_modules"));
|
||||
}
|
||||
|
||||
const name = `pr-${number}`;
|
||||
const script = writeDemoScript(name, source);
|
||||
|
||||
try {
|
||||
const videos = (await record([script], appInWorktree)).map((video) => ({
|
||||
...video,
|
||||
gif: makePreview(video.mp4),
|
||||
}));
|
||||
const storage = getDemoStorage();
|
||||
|
||||
for (const { gif, mp4 } of videos)
|
||||
console.log(`\nvideo: ${mp4}\npreview: ${gif}`);
|
||||
|
||||
if (!storage) {
|
||||
console.log(
|
||||
"DEMO_STORAGE is not set: drag the mp4 into the PR description.",
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const prefix = `videos/pr/${number}/${sha.slice(0, 10)}`;
|
||||
// a script with several tests gets <sha>-1.mp4, <sha>-2.mp4 and so on
|
||||
const keys = videos.map((_, i) =>
|
||||
videos.length === 1 ? prefix : `${prefix}-${i + 1}`,
|
||||
);
|
||||
|
||||
upload(storage, { [`${prefix}.demo.ts`]: script });
|
||||
videos.forEach(({ gif, mp4 }, i) => {
|
||||
upload(storage, { [`${keys[i]}.gif`]: gif, [`${keys[i]}.mp4`]: mp4 });
|
||||
});
|
||||
|
||||
if (!getPublicUrl(prefix)) {
|
||||
console.log(
|
||||
"DEMO_STORAGE_PUBLIC_URL is not set: not linking the video in the PR.",
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const links = videos.map(({ description, gif, mp4, title }, i) => ({
|
||||
description,
|
||||
gif: versionedUrl(`${keys[i]}.gif`, gif) ?? "",
|
||||
mp4: versionedUrl(`${keys[i]}.mp4`, mp4) ?? "",
|
||||
title,
|
||||
}));
|
||||
|
||||
execFileSync(
|
||||
"gh",
|
||||
["pr", "edit", number, "--repo", REPO, "--body-file", "-"],
|
||||
{
|
||||
cwd: app.dir,
|
||||
input: withDemoSection(
|
||||
pr.body,
|
||||
demoSection(
|
||||
links,
|
||||
sha,
|
||||
Math.min(links.length, isPortrait(videos[0].mp4) ? 4 : 2),
|
||||
),
|
||||
),
|
||||
stdio: ["pipe", "inherit", "inherit"],
|
||||
},
|
||||
);
|
||||
console.log(`linked the demo in https://github.com/${REPO}/pull/${number}`);
|
||||
} finally {
|
||||
rmSync(script, { force: true });
|
||||
run("git", ["worktree", "remove", "--force", worktree]);
|
||||
}
|
||||
}
|
||||
|
||||
async function recordDocs(): Promise<void> {
|
||||
const storage = getDemoStorage();
|
||||
|
||||
if (!storage)
|
||||
throw new Error(
|
||||
"DEMO_STORAGE is not set: docs demo scripts are read from it",
|
||||
);
|
||||
|
||||
const downloaded = join(runsDir(), "docs-source");
|
||||
|
||||
rmSync(downloaded, { force: true, recursive: true });
|
||||
|
||||
if (!storage.downloadDir("scripts/docs", downloaded)) {
|
||||
throw new Error("no scripts/docs/*.demo.ts in DEMO_STORAGE");
|
||||
}
|
||||
|
||||
const scripts = readdirSync(downloaded)
|
||||
.filter((f) => f.endsWith(".demo.ts"))
|
||||
.map((f) =>
|
||||
writeDemoScript(
|
||||
basename(f, ".demo.ts"),
|
||||
readFileSync(join(downloaded, f), "utf8"),
|
||||
),
|
||||
);
|
||||
|
||||
try {
|
||||
const videos = await record(scripts);
|
||||
|
||||
for (const { mp4 } of videos) {
|
||||
const name = basename(mp4, ".mp4");
|
||||
|
||||
upload(storage, {
|
||||
[`videos/docs/${name}.gif`]: makePreview(mp4),
|
||||
[`videos/docs/${name}.mp4`]: mp4,
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
rmSync(runsDir(), { force: true, recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs the command in process.argv for `demoApp`. */
|
||||
export async function runDemoCli(demoApp: DemoApp): Promise<void> {
|
||||
app = demoApp;
|
||||
|
||||
const envFile = join(app.dir, ".env");
|
||||
|
||||
if (existsSync(envFile)) process.loadEnvFile(envFile);
|
||||
|
||||
REPO = process.env.DEMO_GITHUB_REPO ?? "ggml-org/llama.cpp";
|
||||
|
||||
const [command, ...args] = process.argv.slice(2);
|
||||
const trustIndex = args.indexOf("--trust");
|
||||
const extra = app.commands?.[command];
|
||||
|
||||
if (command === "pr" && args[0]) {
|
||||
await recordPr(
|
||||
args[0],
|
||||
trustIndex === -1 ? undefined : args[trustIndex + 1],
|
||||
);
|
||||
} else if (command === "docs") {
|
||||
await recordDocs();
|
||||
} else if (extra) {
|
||||
await extra(args);
|
||||
} else {
|
||||
const others = Object.keys(app.commands ?? {}).map((name) => ` | ${name}`);
|
||||
|
||||
console.error(
|
||||
`usage: node demo/cli.ts pr <number> [--trust <sha>] | docs${others.join("")}`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,578 @@
|
||||
/**
|
||||
* Drives a page like a person for a demo video: a visible cursor or fingertip, human timing,
|
||||
* captions, a voice, and camera zooms that the render plays (see polish.ts). Playwright is only a
|
||||
* type here: the app passes in its page, so this package loads none of its own.
|
||||
*/
|
||||
|
||||
import { CAMERA_MOVE_MS, type PolishEvent } from "./polish.ts";
|
||||
import type { CDPSession, Locator, Page } from "@playwright/test";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
/** How far below the viewport's top a pinch has to start for Chromium to zoom at all. */
|
||||
const ZOOM_TOP_INSET_PX = 64;
|
||||
/** The timeline of each page's demo, which the polished render plays over the footage. */
|
||||
export const timelines = new WeakMap<Page, PolishEvent[]>();
|
||||
|
||||
/**
|
||||
* Draws a fake cursor and click ripples, since recorded videos don't include
|
||||
* the OS pointer, and a fingertip per touch, so a pinch shows as two fingers.
|
||||
* A touch device has no cursor: a click shows as a tap of a fingertip.
|
||||
* Runs in the page via addInitScript.
|
||||
*/
|
||||
export function installCursorOverlay(): void {
|
||||
const mount = () => {
|
||||
const style = document.createElement("style");
|
||||
|
||||
style.textContent = `
|
||||
#demo-cursor { position: fixed; top: 0; left: 0; z-index: 2147483647; pointer-events: none;
|
||||
width: 22px; height: 22px; margin: -3px 0 0 -3px; transition: transform 80ms ease-out; }
|
||||
#demo-cursor.down { transform: scale(0.85); }
|
||||
.demo-ripple { position: fixed; z-index: 2147483646; pointer-events: none; width: 36px; height: 36px;
|
||||
margin: -18px 0 0 -18px; border-radius: 50%; background: rgba(59, 130, 246, 0.35);
|
||||
animation: demo-ripple 450ms ease-out forwards; }
|
||||
@keyframes demo-ripple { from { transform: scale(0.3); opacity: 1; } to { transform: scale(1.4); opacity: 0; } }
|
||||
#demo-caption { position: fixed; left: 50%; top: 72px; z-index: 2147483647; pointer-events: none;
|
||||
transform: translate(-50%, -8px); opacity: 0; transition: opacity 200ms ease, transform 200ms ease;
|
||||
max-width: 80%; padding: 10px 18px; border-radius: 10px; background: rgba(17, 17, 17, 0.88);
|
||||
color: #fff; font: 500 18px/1.4 system-ui, sans-serif; text-align: center; }
|
||||
#demo-caption.visible { opacity: 1; transform: translate(-50%, 0); }
|
||||
.demo-finger { position: fixed; z-index: 2147483646; pointer-events: none; width: 40px; height: 40px;
|
||||
margin: -20px 0 0 -20px; border-radius: 50%; background: rgba(59, 130, 246, 0.3);
|
||||
border: 2px solid rgba(59, 130, 246, 0.55); transition: opacity 200ms ease; }
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
|
||||
const cursor = document.createElement("div");
|
||||
|
||||
cursor.id = "demo-cursor";
|
||||
cursor.innerHTML = `<svg viewBox="0 0 24 24" width="22" height="22"><path d="M4 2l16 10.5-7 1.5-3.5 6.5z"
|
||||
fill="#111" stroke="#fff" stroke-width="1.5" stroke-linejoin="round"/></svg>`;
|
||||
document.documentElement.appendChild(cursor);
|
||||
|
||||
const caption = document.createElement("div");
|
||||
|
||||
caption.id = "demo-caption";
|
||||
document.documentElement.appendChild(caption);
|
||||
|
||||
const touch = navigator.maxTouchPoints > 0;
|
||||
const tap = Object.assign(document.createElement("div"), {
|
||||
className: "demo-finger",
|
||||
});
|
||||
let lift: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
if (touch) cursor.style.display = "none";
|
||||
|
||||
document.addEventListener(
|
||||
"mousemove",
|
||||
(e) => (cursor.style.translate = `${e.clientX}px ${e.clientY}px`),
|
||||
true,
|
||||
);
|
||||
document.addEventListener(
|
||||
"mousedown",
|
||||
(e) => {
|
||||
cursor.classList.add("down");
|
||||
|
||||
if (touch) {
|
||||
tap.style.left = `${e.clientX}px`;
|
||||
tap.style.top = `${e.clientY}px`;
|
||||
tap.style.opacity = "1";
|
||||
document.documentElement.appendChild(tap);
|
||||
// a quick second tap restarts the fade, so the first one's timer does not hide it
|
||||
clearTimeout(lift);
|
||||
lift = setTimeout(() => (tap.style.opacity = "0"), 250);
|
||||
}
|
||||
|
||||
const ripple = document.createElement("div");
|
||||
|
||||
ripple.className = "demo-ripple";
|
||||
ripple.style.left = `${e.clientX}px`;
|
||||
ripple.style.top = `${e.clientY}px`;
|
||||
document.documentElement.appendChild(ripple);
|
||||
setTimeout(() => ripple.remove(), 500);
|
||||
},
|
||||
true,
|
||||
);
|
||||
document.addEventListener(
|
||||
"mouseup",
|
||||
() => cursor.classList.remove("down"),
|
||||
true,
|
||||
);
|
||||
|
||||
const fingers: HTMLDivElement[] = [];
|
||||
const placeFingers = (e: TouchEvent) => {
|
||||
Array.from(e.touches).forEach((touch, i) => {
|
||||
const finger = (fingers[i] ??= Object.assign(
|
||||
document.createElement("div"),
|
||||
{
|
||||
className: "demo-finger",
|
||||
},
|
||||
));
|
||||
|
||||
finger.style.left = `${touch.clientX}px`;
|
||||
finger.style.top = `${touch.clientY}px`;
|
||||
finger.style.opacity = "1";
|
||||
document.documentElement.appendChild(finger);
|
||||
});
|
||||
fingers
|
||||
.slice(e.touches.length)
|
||||
.forEach((finger) => (finger.style.opacity = "0"));
|
||||
};
|
||||
|
||||
for (const type of ["touchstart", "touchmove", "touchend", "touchcancel"]) {
|
||||
document.addEventListener(type, placeFingers as EventListener, {
|
||||
capture: true,
|
||||
passive: true,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", mount);
|
||||
} else {
|
||||
mount();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Swaps the page's microphone for one that hears only what `window.demoSpeak` plays into it,
|
||||
* silence otherwise. Chromium's fake capture device crashes the page, so voice input is
|
||||
* recorded with this instead. Runs in the page.
|
||||
*/
|
||||
function installFakeMicrophone(): void {
|
||||
const context = new AudioContext();
|
||||
const output = context.createMediaStreamDestination();
|
||||
|
||||
navigator.mediaDevices.getUserMedia = async (constraints) => {
|
||||
if (!constraints?.audio || constraints.video) {
|
||||
throw new DOMException(
|
||||
"demo: only the microphone is faked",
|
||||
"NotSupportedError",
|
||||
);
|
||||
}
|
||||
|
||||
await context.resume();
|
||||
|
||||
// each opening gets its own tracks, so a recording that stops them leaves the source on
|
||||
return new MediaStream(
|
||||
output.stream.getAudioTracks().map((track) => track.clone()),
|
||||
);
|
||||
};
|
||||
|
||||
Object.assign(window, {
|
||||
demoSpeak: async (wavBase64: string) => {
|
||||
const bytes = Uint8Array.from(atob(wavBase64), (c) => c.charCodeAt(0));
|
||||
const source = context.createBufferSource();
|
||||
|
||||
source.buffer = await context.decodeAudioData(bytes.buffer);
|
||||
source.connect(output);
|
||||
await context.resume();
|
||||
await new Promise((done) => {
|
||||
source.onended = done;
|
||||
source.start();
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** `text` read by a synthetic voice, as a base64 WAV. Uses macOS `say`. */
|
||||
function synthesizeSpeech(text: string, voice: string): string {
|
||||
const dir = mkdtempSync(join(tmpdir(), "demo-speech-"));
|
||||
const file = join(dir, "speech.wav");
|
||||
|
||||
try {
|
||||
execFileSync("say", [
|
||||
"-v",
|
||||
voice,
|
||||
"-o",
|
||||
file,
|
||||
"--file-format=WAVE",
|
||||
"--data-format=LEI16@24000",
|
||||
text,
|
||||
]);
|
||||
|
||||
return readFileSync(file).toString("base64");
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`demo: speak() needs macOS \`say\` with the voice ${voice}`,
|
||||
{
|
||||
cause: error,
|
||||
},
|
||||
);
|
||||
} finally {
|
||||
rmSync(dir, { force: true, recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** Seeded randomness, so a demo moves the same way on every recording. */
|
||||
function createRandom(seed: string): () => number {
|
||||
let state = [...seed].reduce(
|
||||
(h, c) => Math.imul(h ^ c.charCodeAt(0), 2654435761),
|
||||
1,
|
||||
);
|
||||
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) | 0;
|
||||
|
||||
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
||||
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
const easeInOut = (t: number) =>
|
||||
t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2;
|
||||
|
||||
/**
|
||||
* Drives the page like a person: the cursor glides along a slight arc with
|
||||
* Fitts-like durations, settles briefly before pressing, and typing and pauses
|
||||
* vary a little.
|
||||
*/
|
||||
export class Demo {
|
||||
private cdp: CDPSession | undefined;
|
||||
private readonly page: Page;
|
||||
private readonly random: () => number;
|
||||
private readonly timeline: PolishEvent[] | undefined;
|
||||
private x = 0;
|
||||
private y = 0;
|
||||
|
||||
/** Shows a caption at the top of the frame for `ms`, clear of the chat form. */
|
||||
async caption(text: string, ms = 2200): Promise<void> {
|
||||
await this.showCaption(text);
|
||||
await this.page.waitForTimeout(ms);
|
||||
await this.hideCaption();
|
||||
}
|
||||
|
||||
async click(target: Locator, ms = 400): Promise<void> {
|
||||
await this.moveTo(target);
|
||||
await this.page.waitForTimeout(this.between(80, 160));
|
||||
await this.page.mouse.down();
|
||||
await this.page.waitForTimeout(this.between(50, 90));
|
||||
await this.page.mouse.up();
|
||||
await this.pause(ms);
|
||||
}
|
||||
|
||||
constructor(page: Page, seed: string) {
|
||||
this.page = page;
|
||||
this.random = createRandom(seed);
|
||||
this.timeline = timelines.get(page);
|
||||
|
||||
const viewport = page.viewportSize();
|
||||
|
||||
this.x = (viewport?.width ?? 0) / 2;
|
||||
this.y = (viewport?.height ?? 0) / 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Touches `target` for `ms` and lifts: a tap, or with a longer `ms` a press-and-hold, as a
|
||||
* phone's held rows ask for. It needs a touch device (`hasTouch`), and shows a fingertip.
|
||||
*/
|
||||
async hold(target: Locator, ms = 900, after = 500): Promise<void> {
|
||||
await target.scrollIntoViewIfNeeded();
|
||||
|
||||
const { x, y } = await this.center(target);
|
||||
const cdp = await this.session();
|
||||
|
||||
await this.page.waitForTimeout(this.between(60, 140));
|
||||
await cdp.send("Input.dispatchTouchEvent", {
|
||||
touchPoints: [{ x, y }],
|
||||
type: "touchStart",
|
||||
});
|
||||
await this.page.waitForTimeout(ms);
|
||||
await cdp.send("Input.dispatchTouchEvent", {
|
||||
touchPoints: [],
|
||||
type: "touchEnd",
|
||||
});
|
||||
await this.liftFingers();
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
await this.pause(after);
|
||||
}
|
||||
|
||||
async hover(target: Locator, ms = 350): Promise<void> {
|
||||
await this.moveTo(target);
|
||||
await this.pause(ms);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives the page a microphone that hears only what `speak` says, and allows the page to
|
||||
* use it. Call it before the microphone is first used.
|
||||
*/
|
||||
async microphone(): Promise<void> {
|
||||
await this.page.context().grantPermissions(["microphone"]);
|
||||
await this.page.evaluate(installFakeMicrophone);
|
||||
}
|
||||
|
||||
/** Glides the cursor to a point near the center of `target`. */
|
||||
async moveTo(target: Locator): Promise<void> {
|
||||
await target.scrollIntoViewIfNeeded();
|
||||
const box = await target.boundingBox();
|
||||
|
||||
if (!box) throw new Error(`demo: ${target} has no bounding box`);
|
||||
|
||||
const x = box.x + box.width * this.between(0.4, 0.6);
|
||||
const y = box.y + box.height * this.between(0.4, 0.6);
|
||||
const dx = x - this.x;
|
||||
const dy = y - this.y;
|
||||
const distance = Math.hypot(dx, dy);
|
||||
const duration = 110 + 55 * Math.log2(distance / 40 + 1);
|
||||
// bow the path a little to one side, like a wrist turning
|
||||
const bow = distance * this.between(-0.08, 0.08);
|
||||
const fromX = this.x;
|
||||
const fromY = this.y;
|
||||
const started = Date.now();
|
||||
|
||||
for (;;) {
|
||||
const t = Math.min((Date.now() - started) / duration, 1);
|
||||
const p = easeInOut(t);
|
||||
const arc = Math.sin(Math.PI * p) * bow;
|
||||
|
||||
this.x = fromX + dx * p - (dy / (distance || 1)) * arc;
|
||||
this.y = fromY + dy * p + (dx / (distance || 1)) * arc;
|
||||
await this.page.mouse.move(this.x, this.y);
|
||||
|
||||
if (t === 1) break;
|
||||
|
||||
await this.page.waitForTimeout(8);
|
||||
}
|
||||
}
|
||||
|
||||
/** Waits about `ms`, varied by up to 15% so pauses don't feel metronomic. */
|
||||
async pause(ms = 800): Promise<void> {
|
||||
await this.page.waitForTimeout(ms * this.between(0.85, 1.15));
|
||||
}
|
||||
|
||||
async press(key: string, ms = 600): Promise<void> {
|
||||
await this.page.keyboard.press(key);
|
||||
await this.pause(ms);
|
||||
}
|
||||
|
||||
/** Scrolls the wheel over `target` by `dy` pixels (negative scrolls up), in small steps like a trackpad. */
|
||||
async scroll(target: Locator, dy: number, ms = 500): Promise<void> {
|
||||
await this.moveTo(target);
|
||||
|
||||
const step = Math.sign(dy) * 40;
|
||||
|
||||
for (let done = 0; Math.abs(done) < Math.abs(dy); done += step) {
|
||||
await this.page.mouse.wheel(0, step);
|
||||
await this.page.waitForTimeout(16);
|
||||
}
|
||||
|
||||
await this.pause(ms);
|
||||
}
|
||||
|
||||
/**
|
||||
* Says `text` into the microphone from `microphone` in a synthetic voice (macOS `say`), and
|
||||
* returns once it is said. The words show as a caption, since the video has no sound.
|
||||
*/
|
||||
async speak(text: string, voice = "Samantha", ms = 400): Promise<void> {
|
||||
const wav = synthesizeSpeech(text, voice);
|
||||
|
||||
await this.showCaption(`"${text}"`);
|
||||
await this.page.evaluate(
|
||||
(base64) =>
|
||||
(
|
||||
window as unknown as { demoSpeak(wav: string): Promise<void> }
|
||||
).demoSpeak(base64),
|
||||
wav,
|
||||
);
|
||||
await this.hideCaption();
|
||||
await this.pause(ms);
|
||||
}
|
||||
|
||||
/** Taps `target` with a fingertip, on a touch device. */
|
||||
tap(target: Locator, after = 500): Promise<void> {
|
||||
return this.hold(target, this.between(60, 110), after);
|
||||
}
|
||||
|
||||
/** Types quickly with uneven key timing, a little slower after spaces and punctuation. */
|
||||
async type(target: Locator, text: string, ms = 500): Promise<void> {
|
||||
await this.click(target, 200);
|
||||
|
||||
for (const char of text) {
|
||||
await this.page.keyboard.type(char);
|
||||
await this.page.waitForTimeout(
|
||||
this.between(15, 45) +
|
||||
(/[\s.,!?]/.test(char) ? this.between(20, 60) : 0),
|
||||
);
|
||||
}
|
||||
|
||||
await this.pause(ms);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pinches in on `target`, a control or a point in the viewport, holds about `ms`, and pinches
|
||||
* back out to 1x: a two-finger zoom onto a detail too small to read in the frame. On a touch
|
||||
* device the fingertips show. In the polished render the camera moves in and out instead.
|
||||
*/
|
||||
async zoom(
|
||||
target: Locator | { x: number; y: number },
|
||||
scale = 2.5,
|
||||
ms = 1400,
|
||||
): Promise<void> {
|
||||
if (this.timeline) {
|
||||
await this.zoomIn(target, scale);
|
||||
await this.pause(ms);
|
||||
await this.zoomOut();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const point = "x" in target ? target : await this.center(target);
|
||||
// a pinch anchored in the viewport's top band does not zoom at all
|
||||
const at = { x: point.x, y: Math.max(point.y, ZOOM_TOP_INSET_PX) };
|
||||
const viewport = this.page.viewportSize() ?? { height: 0, width: 0 };
|
||||
const middle = { x: viewport.width / 2, y: viewport.height / 2 };
|
||||
|
||||
await this.pinch(at, scale, 1400);
|
||||
|
||||
// One near the bottom edge overshoots its ratio, and a pinch there again misses too. A small
|
||||
// pinch from the middle evens it out, drawing the detail toward the middle, so it stays in view
|
||||
const reached = await this.pageScale();
|
||||
|
||||
if (Math.abs(reached / scale - 1) > 0.03)
|
||||
await this.pinch(middle, scale / reached, 1400);
|
||||
|
||||
await this.liftFingers();
|
||||
await this.pause(ms);
|
||||
|
||||
// back to exactly 1x, which the next gesture needs, in one quick pinch from the middle of
|
||||
// the viewport, and another for what is left when one lands short
|
||||
for (let tries = 0; ; tries++) {
|
||||
const current = await this.pageScale();
|
||||
|
||||
if (current <= 1.001) break;
|
||||
|
||||
if (tries === 4)
|
||||
throw new Error(`demo: zoom stuck at ${current.toFixed(3)}x`);
|
||||
|
||||
await this.pinch(middle, 1 / current, 1800);
|
||||
}
|
||||
|
||||
await this.liftFingers();
|
||||
await this.pause(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the camera in on `target` and keeps it there while the demo goes on,
|
||||
* until `zoomOut` or the next `zoomIn`. A plain recording (DEMO_POLISH=0) ignores it, as the cursor cannot act
|
||||
* on a pinched page.
|
||||
*/
|
||||
async zoomIn(
|
||||
target: Locator | { x: number; y: number },
|
||||
scale = 2.5,
|
||||
): Promise<void> {
|
||||
if (!this.timeline) return;
|
||||
|
||||
if (!("x" in target)) await target.scrollIntoViewIfNeeded();
|
||||
|
||||
const point = "x" in target ? target : await this.center(target);
|
||||
|
||||
this.timeline.push({
|
||||
scale,
|
||||
time: Date.now() / 1000,
|
||||
type: "camera",
|
||||
...point,
|
||||
});
|
||||
await this.page.waitForTimeout(CAMERA_MOVE_MS);
|
||||
}
|
||||
|
||||
/** Moves the camera back out to the whole page. */
|
||||
async zoomOut(): Promise<void> {
|
||||
if (!this.timeline) return;
|
||||
|
||||
this.timeline.push({
|
||||
scale: 1,
|
||||
time: Date.now() / 1000,
|
||||
type: "camera",
|
||||
x: 0,
|
||||
y: 0,
|
||||
});
|
||||
await this.page.waitForTimeout(CAMERA_MOVE_MS);
|
||||
}
|
||||
|
||||
private between(min: number, max: number): number {
|
||||
return min + (max - min) * this.random();
|
||||
}
|
||||
|
||||
private async center(target: Locator): Promise<{ x: number; y: number }> {
|
||||
const box = await target.boundingBox();
|
||||
|
||||
if (!box) throw new Error(`demo: ${target} has no bounding box`);
|
||||
|
||||
return { x: box.x + box.width / 2, y: box.y + box.height / 2 };
|
||||
}
|
||||
|
||||
private async hideCaption(): Promise<void> {
|
||||
this.timeline?.push({
|
||||
text: null,
|
||||
time: Date.now() / 1000,
|
||||
type: "caption",
|
||||
});
|
||||
await this.page.evaluate(() =>
|
||||
document.getElementById("demo-caption")?.classList.remove("visible"),
|
||||
);
|
||||
await this.page.waitForTimeout(250);
|
||||
}
|
||||
|
||||
/** A pinch that reaches the screen's edge can end without its last touchend reaching the page. */
|
||||
private async liftFingers(): Promise<void> {
|
||||
await this.page.evaluate(() =>
|
||||
document
|
||||
.querySelectorAll<HTMLElement>(".demo-finger")
|
||||
.forEach((finger) => (finger.style.opacity = "0")),
|
||||
);
|
||||
}
|
||||
|
||||
private pageScale(): Promise<number> {
|
||||
return this.page.evaluate(() => window.visualViewport?.scale ?? 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* A two-finger pinch by `factor` around `at`, in viewport pixels. While zoomed in, the gesture
|
||||
* reads its position in page-scale units, so it is divided by the scale the page is at.
|
||||
*/
|
||||
private async pinch(
|
||||
at: { x: number; y: number },
|
||||
factor: number,
|
||||
speed: number,
|
||||
): Promise<void> {
|
||||
const cdp = await this.session();
|
||||
const current = await this.pageScale();
|
||||
|
||||
await cdp.send("Input.synthesizePinchGesture", {
|
||||
gestureSourceType: "touch",
|
||||
relativeSpeed: speed,
|
||||
scaleFactor: factor,
|
||||
x: at.x / current,
|
||||
y: at.y / current,
|
||||
});
|
||||
}
|
||||
|
||||
private async session(): Promise<CDPSession> {
|
||||
this.cdp ??= await this.page.context().newCDPSession(this.page);
|
||||
|
||||
return this.cdp;
|
||||
}
|
||||
|
||||
private async showCaption(text: string): Promise<void> {
|
||||
if (this.timeline) {
|
||||
this.timeline.push({ text, time: Date.now() / 1000, type: "caption" });
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
await this.page.evaluate((t) => {
|
||||
const el = document.getElementById("demo-caption");
|
||||
|
||||
if (!el) return;
|
||||
|
||||
el.textContent = t;
|
||||
el.classList.add("visible");
|
||||
}, text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export { Demo } from "./demo.ts";
|
||||
export {
|
||||
prepareDemoPage,
|
||||
recordDemo,
|
||||
type RecordingOptions,
|
||||
} from "./recording.ts";
|
||||
@@ -0,0 +1,572 @@
|
||||
/**
|
||||
* Polish mode, on unless DEMO_POLISH=0: renders a demo as a branded video instead of the plain screencast.
|
||||
* The app sits in a rounded window on a ground of the Llama brand, `demo.zoom` moves a camera over
|
||||
* the whole stage with eased, motion-blurred moves, and captions sit under the window. A Chromium page styled by
|
||||
* @ggml-org/llama-brand lays out each frame, and ffmpeg encodes its screenshots.
|
||||
*
|
||||
* Env:
|
||||
* DEMO_POLISH_GROUND day | night | light | dark | sand (default: day, or night for a dark recording)
|
||||
* DEMO_POLISH_LOGO start | end | both: a card with the Llama lockup (default: none)
|
||||
*/
|
||||
|
||||
import { type Footage, FPS, H264_ARGS } from "./recorder.ts";
|
||||
import type { BrowserType } from "@playwright/test";
|
||||
import { type ChildProcessByStdio, spawn } from "node:child_process";
|
||||
import { rmSync } from "node:fs";
|
||||
import { once } from "node:events";
|
||||
import type { Writable } from "node:stream";
|
||||
import { join, resolve, sep } from "node:path";
|
||||
|
||||
export const POLISH = process.env.DEMO_POLISH !== "0";
|
||||
export const CAMERA_MOVE_MS = 650;
|
||||
/** Added to a test's timeout, as the render runs in the test's teardown. */
|
||||
export const POLISH_RENDER_TIMEOUT_MS = 600_000;
|
||||
|
||||
/** The grounds of the brand, and whether each takes the light mark of the lockup. */
|
||||
const GROUNDS = {
|
||||
dark: true,
|
||||
day: false,
|
||||
light: false,
|
||||
night: true,
|
||||
sand: false,
|
||||
};
|
||||
const LOGO_CARDS = ["start", "end", "both"];
|
||||
const LANDSCAPE = { height: 1080, width: 1920 };
|
||||
const PORTRAIT = { height: 1920, width: 1080 };
|
||||
/** The brand's grid: every size is a multiple of u, this share of the format's short side. */
|
||||
const UNITS_PER_SHORT_SIDE = 24;
|
||||
const MARGIN_U = 2;
|
||||
const WINDOW_RADIUS_U = 0.55;
|
||||
/** A phone's screen has rounder corners than a window, and they are squircles. */
|
||||
const PHONE_RADIUS_U = 2.4;
|
||||
const CAPTION_HEIGHT_U = 1.6;
|
||||
const CAPTION_PAD_U = 0.8;
|
||||
const CAPTION_FONT_U = 0.84;
|
||||
/** The smallest type the brand allows, which a long caption shrinks to before it is cut. */
|
||||
const CAPTION_MIN_FONT_U = 0.58;
|
||||
const CAPTION_GAP_U = 0.5;
|
||||
const CAPTION_RISE_U = 0.3;
|
||||
const CAPTION_FADE_S = 0.35;
|
||||
const LOGO_HEIGHT_U = 3;
|
||||
const LOGO_CARD_S = 1.6;
|
||||
const LOGO_FADE_S = 0.5;
|
||||
/** Camera positions averaged into one frame while the camera moves. */
|
||||
const BLUR_SAMPLES = 12;
|
||||
/** The share of a frame's time those positions span: a film camera's 180 degree shutter. */
|
||||
const SHUTTER = 0.5;
|
||||
const SHADOW_Y_U = 0.5;
|
||||
const SHADOW_BLUR_U = 1.6;
|
||||
/** The shadow stops growing with the zoom here, so a close-up keeps a soft edge, not a cloud. */
|
||||
const SHADOW_MAX_BLUR_PX = 120;
|
||||
const SHADOW_COLOR = "rgb(0 0 0 / 0.18)";
|
||||
/** Points along each squircle corner. */
|
||||
const SQUIRCLE_STEPS = 24;
|
||||
const JPEG_QUALITY = 95;
|
||||
/** The stage page, the brand's files and the recorded frames are served from here. */
|
||||
const STAGE_ORIGIN = "http://demo.invalid";
|
||||
|
||||
/** What a demo did, with the time (seconds, on the clock of Date.now()) it did it at. */
|
||||
export type PolishEvent =
|
||||
| { scale: number; time: number; type: "camera"; x: number; y: number }
|
||||
| { text: null | string; time: number; type: "caption" };
|
||||
|
||||
interface Size {
|
||||
height: number;
|
||||
width: number;
|
||||
}
|
||||
|
||||
/** A camera move: soft at both ends and fast through the middle, so it is quick without a jolt. */
|
||||
const CAMERA_EASE_POWER = 5;
|
||||
const cameraEase = (t: number) => {
|
||||
const x = Math.min(Math.max(t, 0), 1);
|
||||
|
||||
return x < 0.5
|
||||
? 2 ** (CAMERA_EASE_POWER - 1) * x ** CAMERA_EASE_POWER
|
||||
: 1 - (2 - 2 * x) ** CAMERA_EASE_POWER / 2;
|
||||
};
|
||||
|
||||
/** Where the stage is drawn in a frame: scaled about its top left corner, then moved. */
|
||||
interface Camera {
|
||||
scale: number;
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
/** Where the window sits on the stage, and how much larger it is than the page. */
|
||||
interface Layout {
|
||||
fit: number;
|
||||
height: number;
|
||||
left: number;
|
||||
maxWidth: number;
|
||||
size: Size;
|
||||
top: number;
|
||||
u: number;
|
||||
width: number;
|
||||
}
|
||||
|
||||
interface Shot {
|
||||
caption: null | { opacity: number; text: string };
|
||||
cameras: Camera[];
|
||||
frame: string;
|
||||
/** How much of the logo card shows over the scene, 0 to 1. */
|
||||
logo: number;
|
||||
}
|
||||
|
||||
const smootherstep = (t: number) => {
|
||||
const x = Math.min(Math.max(t, 0), 1);
|
||||
|
||||
return x * x * x * (x * (x * 6 - 15) + 10);
|
||||
};
|
||||
|
||||
/**
|
||||
* The camera at any time: each move eases from where the camera was to its target. It looks at the
|
||||
* whole stage, so a zoom brings the window itself closer, with its corners and the ground round it.
|
||||
*/
|
||||
function cameraPath(
|
||||
events: PolishEvent[],
|
||||
layout: Layout,
|
||||
): (time: number) => Camera {
|
||||
/** The point of the stage at the middle of the frame, and the natural log of the scale. */
|
||||
interface View {
|
||||
zoom: number;
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
const { height, width } = layout.size;
|
||||
const rest: View = { x: width / 2, y: height / 2, zoom: 0 };
|
||||
const moves: { from: View; start: number; to: View }[] = [];
|
||||
const at = (time: number) => {
|
||||
let view = rest;
|
||||
|
||||
for (const { from, start, to } of moves) {
|
||||
if (time < start) break;
|
||||
|
||||
const k = cameraEase(((time - start) * 1000) / CAMERA_MOVE_MS);
|
||||
|
||||
view = {
|
||||
x: from.x + (to.x - from.x) * k,
|
||||
y: from.y + (to.y - from.y) * k,
|
||||
zoom: from.zoom + (to.zoom - from.zoom) * k,
|
||||
};
|
||||
}
|
||||
|
||||
return view;
|
||||
};
|
||||
|
||||
for (const event of events) {
|
||||
if (event.type !== "camera") continue;
|
||||
|
||||
// the frame stays inside the stage
|
||||
const halfWidth = width / 2 / event.scale;
|
||||
const halfHeight = height / 2 / event.scale;
|
||||
const x = layout.left + event.x * layout.fit;
|
||||
const y = layout.top + event.y * layout.fit;
|
||||
|
||||
moves.push({
|
||||
from: at(event.time),
|
||||
start: event.time,
|
||||
to: {
|
||||
x: Math.min(Math.max(x, halfWidth), width - halfWidth),
|
||||
y: Math.min(Math.max(y, halfHeight), height - halfHeight),
|
||||
zoom: Math.log(event.scale),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return (time) => {
|
||||
const { x, y, zoom } = at(time);
|
||||
const scale = Math.exp(zoom);
|
||||
|
||||
return { scale, x: width / 2 - x * scale, y: height / 2 - y * scale };
|
||||
};
|
||||
}
|
||||
|
||||
/** The caption at any time, fading in and out. */
|
||||
function captionTrack(
|
||||
events: PolishEvent[],
|
||||
end: number,
|
||||
): (time: number) => Shot["caption"] {
|
||||
const spans: { end: number; start: number; text: string }[] = [];
|
||||
|
||||
for (const event of events) {
|
||||
if (event.type !== "caption") continue;
|
||||
|
||||
const last = spans.at(-1);
|
||||
|
||||
if (last && last.end > event.time) last.end = event.time;
|
||||
|
||||
if (event.text !== null)
|
||||
spans.push({ end, start: event.time, text: event.text });
|
||||
}
|
||||
|
||||
return (time) => {
|
||||
const span = spans.find((s) => s.start < time && time < s.end);
|
||||
|
||||
if (!span) return null;
|
||||
|
||||
const opacity = smootherstep(
|
||||
Math.min(time - span.start, span.end - time) / CAPTION_FADE_S,
|
||||
);
|
||||
|
||||
return { opacity, text: span.text };
|
||||
};
|
||||
}
|
||||
|
||||
/** The window is the page's viewport, as large as fits inside the margin. */
|
||||
function stageLayout(viewport: Size, captions: boolean): Layout {
|
||||
const size = viewport.height > viewport.width ? PORTRAIT : LANDSCAPE;
|
||||
const u = Math.min(size.height, size.width) / UNITS_PER_SHORT_SIDE;
|
||||
// the caption row is kept free under the window only when the demo has captions
|
||||
const maxWidth = size.width - 2 * MARGIN_U * u;
|
||||
const maxHeight =
|
||||
size.height -
|
||||
2 * MARGIN_U * u -
|
||||
(captions ? (CAPTION_HEIGHT_U + CAPTION_GAP_U) * u : 0);
|
||||
const fit = Math.min(maxWidth / viewport.width, maxHeight / viewport.height);
|
||||
const width = Math.round(viewport.width * fit);
|
||||
const height = Math.round(viewport.height * fit);
|
||||
|
||||
return {
|
||||
fit,
|
||||
height,
|
||||
left: Math.round((size.width - width) / 2),
|
||||
maxWidth,
|
||||
size,
|
||||
top: Math.round(MARGIN_U * u + (maxHeight - height) / 2),
|
||||
u,
|
||||
width,
|
||||
};
|
||||
}
|
||||
|
||||
/** The stage: a ground of the brand with the window, the caption chip and the logo card on it. */
|
||||
function stageHtml(layout: Layout, dark: boolean): string {
|
||||
const { height, left, maxWidth, size, top, u, width } = layout;
|
||||
const ground = process.env.DEMO_POLISH_GROUND ?? (dark ? "night" : "day");
|
||||
|
||||
if (!(ground in GROUNDS))
|
||||
throw new Error(`demo: no ground "${ground}" in the brand`);
|
||||
|
||||
const phone = size.height > size.width;
|
||||
const radius = (phone ? PHONE_RADIUS_U : WINDOW_RADIUS_U) * u;
|
||||
const mark = GROUNDS[ground as keyof typeof GROUNDS] ? "dark" : "light";
|
||||
|
||||
return `<!doctype html>
|
||||
<link rel="stylesheet" href="/brand/css/colors.css" />
|
||||
<link rel="stylesheet" href="/brand/css/fonts.css" />
|
||||
<link rel="stylesheet" href="/brand/css/communications.css" />
|
||||
<style>
|
||||
body { position: relative; overflow: hidden; margin: 0; width: ${size.width}px; height: ${size.height}px; --u: ${u}px; }
|
||||
#scene, #logo { position: absolute; inset: 0; }
|
||||
#window { position: absolute; inset: 0; }
|
||||
#caption { position: absolute; left: 50%; bottom: calc(var(--u) * ${MARGIN_U}); display: flex; align-items: center;
|
||||
box-sizing: border-box; height: calc(var(--u) * ${CAPTION_HEIGHT_U}); padding: 0 calc(var(--u) * ${CAPTION_PAD_U});
|
||||
max-width: ${maxWidth}px; overflow: hidden; border-radius: 999px; background: var(--p-solid);
|
||||
color: var(--p-solid-ink); white-space: nowrap; opacity: 0; }
|
||||
#logo { opacity: 0; }
|
||||
#logo img { position: absolute; left: 50%; top: 50%; height: calc(var(--u) * ${LOGO_HEIGHT_U}); translate: -50% -50%; }
|
||||
</style>
|
||||
<body class="ground ground-${ground}">
|
||||
<div id="scene">
|
||||
<canvas id="window" width="${size.width}" height="${size.height}" data-left="${left}" data-top="${top}"
|
||||
data-width="${width}" data-height="${height}" data-radius="${radius}" data-squircle="${phone}"
|
||||
data-shadow-y="${SHADOW_Y_U * u}" data-shadow-blur="${SHADOW_BLUR_U * u}"
|
||||
data-shadow-max-blur="${SHADOW_MAX_BLUR_PX}" data-shadow-color="${SHADOW_COLOR}"
|
||||
data-squircle-steps="${SQUIRCLE_STEPS}"></canvas>
|
||||
<div id="caption" data-font="${CAPTION_FONT_U * u}" data-min-font="${CAPTION_MIN_FONT_U * u}"
|
||||
data-rise="${CAPTION_RISE_U * u}"></div>
|
||||
</div>
|
||||
<div id="logo"><img src="/brand/logo/svg/lockup/llama/logo-llama-${mark}.svg" /></div>
|
||||
</body>`;
|
||||
}
|
||||
|
||||
/** Lays out one output frame on the stage. Runs in the page. */
|
||||
async function drawFrame(shot: Shot): Promise<void> {
|
||||
const stage = window as unknown as {
|
||||
demoFrame?: string;
|
||||
demoImage?: ImageBitmap;
|
||||
};
|
||||
const caption = document.querySelector<HTMLElement>("#caption")!;
|
||||
|
||||
if (stage.demoFrame !== shot.frame) {
|
||||
const response = await fetch(shot.frame);
|
||||
|
||||
if (!response.ok)
|
||||
throw new Error(`demo: no frame at ${shot.frame} (${response.status})`);
|
||||
|
||||
stage.demoImage?.close();
|
||||
stage.demoImage = await createImageBitmap(await response.blob());
|
||||
stage.demoFrame = shot.frame;
|
||||
}
|
||||
|
||||
const image = stage.demoImage!;
|
||||
const canvas = document.querySelector<HTMLCanvasElement>("#window")!;
|
||||
const box = { ...canvas.dataset } as Record<string, string>;
|
||||
const [
|
||||
left,
|
||||
top,
|
||||
width,
|
||||
height,
|
||||
radius,
|
||||
shadowY,
|
||||
shadowBlur,
|
||||
shadowMaxBlur,
|
||||
steps,
|
||||
] = [
|
||||
"left",
|
||||
"top",
|
||||
"width",
|
||||
"height",
|
||||
"radius",
|
||||
"shadowY",
|
||||
"shadowBlur",
|
||||
"shadowMaxBlur",
|
||||
"squircleSteps",
|
||||
].map((key) => Number(box[key]));
|
||||
const squircle = box.squircle === "true";
|
||||
// a phone's corners are squircles, |x|^4 + |y|^4 = r^4, as CSS draws corner-shape: squircle
|
||||
const outline = (x: number, y: number, w: number, h: number, r: number) => {
|
||||
const path = new Path2D();
|
||||
|
||||
if (!squircle) {
|
||||
path.roundRect(x, y, w, h, r);
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
const corners = [
|
||||
[x + w - r, y + r, -Math.PI / 2],
|
||||
[x + w - r, y + h - r, 0],
|
||||
[x + r, y + h - r, Math.PI / 2],
|
||||
[x + r, y + r, Math.PI],
|
||||
];
|
||||
|
||||
for (const [cx, cy, from] of corners) {
|
||||
for (let step = 0; step <= steps; step++) {
|
||||
const angle = from + (step / steps) * (Math.PI / 2);
|
||||
const [cos, sin] = [Math.cos(angle), Math.sin(angle)];
|
||||
|
||||
path.lineTo(
|
||||
cx + r * Math.sign(cos) * Math.sqrt(Math.abs(cos)),
|
||||
cy + r * Math.sign(sin) * Math.sqrt(Math.abs(sin)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
path.closePath();
|
||||
|
||||
return path;
|
||||
};
|
||||
const output = canvas.getContext("2d")!;
|
||||
const copy = new OffscreenCanvas(canvas.width, canvas.height).getContext(
|
||||
"2d",
|
||||
)!;
|
||||
|
||||
output.clearRect(0, 0, canvas.width, canvas.height);
|
||||
|
||||
// one copy of the window per camera position, each drawn at 1/n over the ones before, which
|
||||
// leaves their mean: the motion blur. A still frame draws one copy. All of it goes on one canvas:
|
||||
// a layer per copy overruns Chromium's tile memory when the copies are large, and drops tiles
|
||||
shot.cameras.forEach(({ scale, x: cameraX, y: cameraY }, i) => {
|
||||
const shadow = Math.min(scale, shadowMaxBlur / shadowBlur);
|
||||
const [x, y, w, h] = [
|
||||
cameraX + left * scale,
|
||||
cameraY + top * scale,
|
||||
width * scale,
|
||||
height * scale,
|
||||
];
|
||||
const path = outline(x, y, w, h, radius * scale);
|
||||
|
||||
copy.clearRect(0, 0, canvas.width, canvas.height);
|
||||
copy.save();
|
||||
Object.assign(copy, {
|
||||
fillStyle: "#fff",
|
||||
shadowBlur: shadowBlur * shadow,
|
||||
shadowColor: box.shadowColor,
|
||||
shadowOffsetY: shadowY * shadow,
|
||||
});
|
||||
copy.fill(path);
|
||||
copy.restore();
|
||||
copy.save();
|
||||
copy.clip(path);
|
||||
copy.imageSmoothingQuality = "high";
|
||||
copy.drawImage(image, x, y, w, h);
|
||||
copy.restore();
|
||||
output.globalAlpha = 1 / (i + 1);
|
||||
output.drawImage(copy.canvas, 0, 0);
|
||||
});
|
||||
output.globalAlpha = 1;
|
||||
|
||||
if (shot.caption && caption.textContent !== shot.caption.text) {
|
||||
const font = Number(caption.dataset.font);
|
||||
|
||||
caption.textContent = shot.caption.text;
|
||||
caption.style.fontSize = `${font}px`;
|
||||
|
||||
// a long caption gets smaller type, down to the smallest the brand allows
|
||||
const fit = caption.clientWidth / caption.scrollWidth;
|
||||
|
||||
if (fit < 1) {
|
||||
caption.style.fontSize = `${Math.max(font * fit, Number(caption.dataset.minFont))}px`;
|
||||
}
|
||||
}
|
||||
|
||||
const opacity = shot.caption?.opacity ?? 0;
|
||||
|
||||
caption.style.opacity = String(opacity);
|
||||
caption.style.translate = `-50% ${(1 - opacity) * Number(caption.dataset.rise)}px`;
|
||||
document.getElementById("scene")!.style.opacity = String(1 - shot.logo);
|
||||
document.getElementById("logo")!.style.opacity = String(shot.logo);
|
||||
}
|
||||
|
||||
/** Renders the recorded frames and the demo's timeline into `mp4`. */
|
||||
export async function renderPolished(
|
||||
browserType: BrowserType,
|
||||
brandDir: string,
|
||||
footage: Footage,
|
||||
timeline: PolishEvent[],
|
||||
viewport: Size,
|
||||
dark: boolean,
|
||||
mp4: string,
|
||||
): Promise<void> {
|
||||
const card = process.env.DEMO_POLISH_LOGO;
|
||||
|
||||
if (card && !LOGO_CARDS.includes(card))
|
||||
throw new Error(`demo: DEMO_POLISH_LOGO is "${card}"`);
|
||||
|
||||
const layout = stageLayout(
|
||||
viewport,
|
||||
timeline.some((event) => event.type === "caption"),
|
||||
);
|
||||
const html = stageHtml(layout, dark);
|
||||
const { size } = layout;
|
||||
// a browser of its own: the demo's is launched at the recording's device scale, and draws
|
||||
// every frame of this page that many times larger
|
||||
const browser = await browserType.launch({
|
||||
args: ["--force-device-scale-factor=1"],
|
||||
chromiumSandbox: true,
|
||||
});
|
||||
let ffmpeg: ChildProcessByStdio<Writable, null, null> | undefined;
|
||||
|
||||
try {
|
||||
const page = await browser.newPage({
|
||||
deviceScaleFactor: 1,
|
||||
viewport: size,
|
||||
});
|
||||
|
||||
await page.route(`${STAGE_ORIGIN}/**`, (route) => {
|
||||
const path = decodeURIComponent(new URL(route.request().url()).pathname);
|
||||
const file = join(brandDir, path.replace(/^\/brand\//, ""));
|
||||
|
||||
if (path.startsWith("/frames/")) {
|
||||
return route.fulfill({
|
||||
path: footage.frames[Number(path.split("/")[2])].file,
|
||||
});
|
||||
}
|
||||
|
||||
return path.startsWith("/brand/") && file.startsWith(brandDir + sep)
|
||||
? route.fulfill({ path: file })
|
||||
: route.fulfill({ body: html, contentType: "text/html" });
|
||||
});
|
||||
await page.goto(STAGE_ORIGIN);
|
||||
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
|
||||
await page.evaluate(async () => {
|
||||
await Promise.all([...document.fonts].map((font) => font.load()));
|
||||
await document.querySelector("img")!.decode();
|
||||
});
|
||||
ffmpeg = spawn(
|
||||
"ffmpeg",
|
||||
[
|
||||
"-y",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-f",
|
||||
"image2pipe",
|
||||
"-c:v",
|
||||
"mjpeg",
|
||||
"-framerate",
|
||||
String(FPS),
|
||||
"-i",
|
||||
"-",
|
||||
...H264_ARGS,
|
||||
mp4,
|
||||
],
|
||||
{ stdio: ["pipe", "inherit", "inherit"] },
|
||||
);
|
||||
const start = footage.frames[0].time;
|
||||
const seconds = footage.end - start;
|
||||
const intro = card === "start" || card === "both" ? LOGO_CARD_S : 0;
|
||||
const outro = card === "end" || card === "both" ? LOGO_CARD_S : 0;
|
||||
const cameraAt = cameraPath(timeline, layout);
|
||||
const captionAt = captionTrack(timeline, footage.end);
|
||||
const moved = (a: Camera, b: Camera) =>
|
||||
Math.max(
|
||||
Math.abs(a.x - b.x),
|
||||
Math.abs(a.y - b.y),
|
||||
Math.abs(a.scale - b.scale),
|
||||
) > 1e-3;
|
||||
|
||||
let source = 0;
|
||||
let drawn = "";
|
||||
let jpeg = Buffer.alloc(0);
|
||||
|
||||
for (let i = 0; i < Math.round((intro + seconds + outro) * FPS); i++) {
|
||||
// the footage holds its first frame under the opening card and its last under the closing one
|
||||
const elapsed = i / FPS - intro;
|
||||
const time = start + Math.min(Math.max(elapsed, 0), seconds);
|
||||
|
||||
while ((footage.frames[source + 1]?.time ?? Infinity) <= time) source++;
|
||||
|
||||
const shot: Shot = {
|
||||
cameras: moved(cameraAt(time), cameraAt(time + 1 / FPS))
|
||||
? Array.from({ length: BLUR_SAMPLES }, (_, s) =>
|
||||
cameraAt(time + (s / BLUR_SAMPLES) * (SHUTTER / FPS)),
|
||||
)
|
||||
: [cameraAt(time)],
|
||||
caption: captionAt(time),
|
||||
frame: `${STAGE_ORIGIN}/frames/${source}`,
|
||||
logo:
|
||||
elapsed < 0
|
||||
? 1 - smootherstep(1 + elapsed / LOGO_FADE_S)
|
||||
: smootherstep((elapsed - seconds) / LOGO_FADE_S),
|
||||
};
|
||||
const key = JSON.stringify(shot);
|
||||
|
||||
// a still frame is drawn once
|
||||
if (key !== drawn) {
|
||||
await page.evaluate(drawFrame, shot);
|
||||
|
||||
// straight from Chromium: Playwright's own screenshot is several times slower
|
||||
const { data } = await cdp.send("Page.captureScreenshot", {
|
||||
format: "jpeg",
|
||||
optimizeForSpeed: true,
|
||||
quality: JPEG_QUALITY,
|
||||
});
|
||||
|
||||
jpeg = Buffer.from(data, "base64");
|
||||
drawn = key;
|
||||
}
|
||||
|
||||
if (!ffmpeg.stdin.write(jpeg)) await once(ffmpeg.stdin, "drain");
|
||||
}
|
||||
|
||||
ffmpeg.stdin.end();
|
||||
|
||||
const [code] = await once(ffmpeg, "close");
|
||||
|
||||
if (code !== 0)
|
||||
throw new Error(
|
||||
`demo: ffmpeg exited with ${code} on the polished render`,
|
||||
);
|
||||
} catch (error) {
|
||||
// a part-rendered mp4 would play as a shorter, valid video
|
||||
ffmpeg?.kill("SIGKILL");
|
||||
rmSync(mp4, { force: true });
|
||||
|
||||
throw error;
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* Records a page through Chromium's screencast instead of Playwright's video,
|
||||
* which encodes VP8 at about 1 Mbit/s at 1x scale. Frames arrive at the page's
|
||||
* device pixel ratio, each with its timestamp, and are encoded once into an
|
||||
* H.264 mp4 (what GitHub accepts in PR descriptions).
|
||||
*/
|
||||
|
||||
import type { CDPSession, Page } from "@playwright/test";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
export const FPS = 60;
|
||||
export const H264_ARGS = [
|
||||
"-c:v",
|
||||
"libx264",
|
||||
"-preset",
|
||||
"slow",
|
||||
"-crf",
|
||||
"18",
|
||||
"-pix_fmt",
|
||||
"yuv420p",
|
||||
"-movflags",
|
||||
"+faststart",
|
||||
];
|
||||
const JPEG_QUALITY = 92;
|
||||
|
||||
interface Frame {
|
||||
file: string;
|
||||
/** Seconds, on the same clock as Date.now(). */
|
||||
time: number;
|
||||
}
|
||||
|
||||
/** The frames as recorded, each shown until the next one's time, the last one until `end`. */
|
||||
export interface Footage {
|
||||
end: number;
|
||||
frames: Frame[];
|
||||
}
|
||||
|
||||
export class ScreencastRecorder {
|
||||
private readonly dir: string;
|
||||
private readonly frames: Frame[] = [];
|
||||
private readonly pending: Promise<void>[] = [];
|
||||
private session: CDPSession | undefined;
|
||||
private stoppedAt = 0;
|
||||
|
||||
/** For a render other than `encode`, which has to `discard` the frames after it. */
|
||||
get footage(): Footage {
|
||||
if (this.frames.length === 0)
|
||||
throw new Error("demo: the screencast captured no frames");
|
||||
|
||||
return { end: this.stoppedAt, frames: this.frames };
|
||||
}
|
||||
|
||||
constructor(dir: string) {
|
||||
this.dir = dir;
|
||||
}
|
||||
|
||||
discard(): void {
|
||||
rmSync(this.dir, { force: true, recursive: true });
|
||||
}
|
||||
|
||||
/** Encodes the frames, each held until the next one arrived (the screencast only sends changes). */
|
||||
encode(mp4: string): void {
|
||||
if (this.frames.length === 0)
|
||||
throw new Error("demo: the screencast captured no frames");
|
||||
|
||||
const list = this.frames.flatMap((frame, i) => {
|
||||
const end = this.frames[i + 1]?.time ?? this.stoppedAt;
|
||||
|
||||
return [
|
||||
`file '${frame.file}'`,
|
||||
`duration ${Math.max(end - frame.time, 1 / FPS).toFixed(4)}`,
|
||||
];
|
||||
});
|
||||
const listFile = join(this.dir, "frames.txt");
|
||||
|
||||
// the concat demuxer ignores the last entry's duration unless the file is repeated
|
||||
writeFileSync(
|
||||
listFile,
|
||||
[...list, `file '${this.frames.at(-1)!.file}'`, ""].join("\n"),
|
||||
);
|
||||
execFileSync(
|
||||
"ffmpeg",
|
||||
[
|
||||
"-y",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-f",
|
||||
"concat",
|
||||
"-safe",
|
||||
"0",
|
||||
"-i",
|
||||
listFile,
|
||||
"-vf",
|
||||
`fps=${FPS},scale=trunc(iw/2)*2:trunc(ih/2)*2`,
|
||||
...H264_ARGS,
|
||||
mp4,
|
||||
],
|
||||
{ stdio: "inherit" },
|
||||
);
|
||||
this.discard();
|
||||
}
|
||||
|
||||
async start(page: Page): Promise<void> {
|
||||
const size = page.viewportSize();
|
||||
const scale = await page.evaluate(() => window.devicePixelRatio);
|
||||
|
||||
rmSync(this.dir, { force: true, recursive: true });
|
||||
mkdirSync(this.dir, { recursive: true });
|
||||
|
||||
this.session = await page.context().newCDPSession(page);
|
||||
this.session.on("Page.screencastFrame", ({ data, metadata, sessionId }) => {
|
||||
const file = join(
|
||||
this.dir,
|
||||
`${String(this.frames.length).padStart(6, "0")}.jpg`,
|
||||
);
|
||||
|
||||
// acknowledged first: Chromium sends the next frame only after the ack
|
||||
this.session
|
||||
?.send("Page.screencastFrameAck", { sessionId })
|
||||
.catch(() => {});
|
||||
this.frames.push({ file, time: metadata.timestamp ?? Date.now() / 1000 });
|
||||
this.pending.push(writeFile(file, Buffer.from(data, "base64")));
|
||||
});
|
||||
await this.session.send("Page.startScreencast", {
|
||||
everyNthFrame: 1,
|
||||
format: "jpeg",
|
||||
maxHeight: size ? size.height * scale : undefined,
|
||||
maxWidth: size ? size.width * scale : undefined,
|
||||
quality: JPEG_QUALITY,
|
||||
});
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.stoppedAt = Date.now() / 1000;
|
||||
await this.session?.send("Page.stopScreencast").catch(() => {});
|
||||
await this.session?.detach().catch(() => {});
|
||||
await Promise.all(this.pending);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* The recording around a demo: the page is prepared before it loads, recorded while the demo drives
|
||||
* it, and rendered into an mp4 that the app's manifest lists for the CLI.
|
||||
*/
|
||||
|
||||
import { installCursorOverlay, timelines } from "./demo.ts";
|
||||
import {
|
||||
POLISH,
|
||||
POLISH_RENDER_TIMEOUT_MS,
|
||||
type PolishEvent,
|
||||
renderPolished,
|
||||
} from "./polish.ts";
|
||||
import { ScreencastRecorder } from "./recorder.ts";
|
||||
import type { Page, TestInfo } from "@playwright/test";
|
||||
import { appendFileSync, mkdirSync } from "node:fs";
|
||||
import { basename, resolve } from "node:path";
|
||||
|
||||
/** How long the page settles (connections, fonts) before the recording starts. */
|
||||
const SETTLE_MS = 1500;
|
||||
|
||||
export interface RecordingOptions {
|
||||
/** @ggml-org/llama-brand's folder: the render takes its CSS, fonts and lockup from there. */
|
||||
brandDir: string;
|
||||
/** Whether the page is in its dark scheme, which gets the night sky. */
|
||||
dark: boolean;
|
||||
/** Where the videos go, with the manifest of each script that the CLI reads. */
|
||||
videosDir: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws the cursor in `page` and, for the render, starts the timeline it plays. Call it before
|
||||
* the page loads. A page the render cannot frame (no fixed viewport) records plainly, with
|
||||
* captions and zooms in the page, rather than losing them.
|
||||
*/
|
||||
export async function prepareDemoPage(
|
||||
page: Page,
|
||||
testInfo: TestInfo,
|
||||
): Promise<void> {
|
||||
// the screencast and the render both run on the Chrome DevTools Protocol
|
||||
const browserName = page.context().browser()?.browserType().name();
|
||||
|
||||
if (browserName !== "chromium") {
|
||||
throw new Error(
|
||||
`demo: ${testInfo.title} runs in ${browserName ?? "a browser Playwright did not launch"}, and demos record in Chromium only`,
|
||||
);
|
||||
}
|
||||
|
||||
if (POLISH && page.viewportSize()) timelines.set(page, []);
|
||||
|
||||
await page.addInitScript(installCursorOverlay);
|
||||
}
|
||||
|
||||
/** Records `page` while `run` drives it, then renders the video and lists it in the script's manifest. */
|
||||
export async function recordDemo(
|
||||
page: Page,
|
||||
testInfo: TestInfo,
|
||||
options: RecordingOptions,
|
||||
run: () => Promise<void>,
|
||||
): Promise<void> {
|
||||
const timeline: PolishEvent[] | undefined = timelines.get(page);
|
||||
|
||||
const viewport = page.viewportSize();
|
||||
|
||||
if (viewport) await page.mouse.move(viewport.width / 2, viewport.height / 2);
|
||||
|
||||
await page.waitForTimeout(SETTLE_MS);
|
||||
|
||||
const browserType = page.context().browser()?.browserType();
|
||||
const recorder = new ScreencastRecorder(testInfo.outputPath("frames"));
|
||||
|
||||
await recorder.start(page);
|
||||
await run();
|
||||
await recorder.stop();
|
||||
|
||||
// added once the demo is done, so a test.setTimeout() in it cannot take the render's time away
|
||||
if (timeline)
|
||||
testInfo.setTimeout(testInfo.timeout + POLISH_RENDER_TIMEOUT_MS);
|
||||
await page.close();
|
||||
|
||||
if (testInfo.status !== testInfo.expectedStatus) return;
|
||||
|
||||
const file = basename(testInfo.file).replace(/\.demo\.ts$/, "");
|
||||
const name =
|
||||
testInfo.title === "demo" ? file : `${file}--${slugify(testInfo.title)}`;
|
||||
const mp4 = resolve(options.videosDir, `${name}.mp4`);
|
||||
|
||||
mkdirSync(options.videosDir, { recursive: true });
|
||||
|
||||
if (timeline) {
|
||||
if (!viewport || !browserType) {
|
||||
throw new Error(
|
||||
`demo: ${testInfo.title} lost its viewport or browser before the render`,
|
||||
);
|
||||
}
|
||||
|
||||
await renderPolished(
|
||||
browserType,
|
||||
options.brandDir,
|
||||
recorder.footage,
|
||||
timeline,
|
||||
viewport,
|
||||
options.dark,
|
||||
mp4,
|
||||
);
|
||||
recorder.discard();
|
||||
} else {
|
||||
recorder.encode(mp4);
|
||||
}
|
||||
|
||||
// the CLI reads which videos a script made, in order, with their titles
|
||||
appendFileSync(
|
||||
resolve(options.videosDir, `${file}.videos.jsonl`),
|
||||
`${JSON.stringify({
|
||||
description: testInfo.annotations.find((a) => a.type === "description")
|
||||
?.description,
|
||||
mp4,
|
||||
title: testInfo.title,
|
||||
})}\n`,
|
||||
);
|
||||
console.log(`demo video: ${mp4}`);
|
||||
}
|
||||
|
||||
function slugify(text: string): string {
|
||||
return text
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-|-$/g, "");
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* Storage targets for demo scripts and videos, picked by the scheme of the
|
||||
* DEMO_STORAGE URI:
|
||||
*
|
||||
* hf://buckets/<owner>/<bucket>[/prefix] Hugging Face bucket, via the `hf` CLI login
|
||||
* file:///some/dir local or mounted directory
|
||||
*/
|
||||
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { copyFileSync, cpSync, existsSync, mkdirSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
export interface DemoStorage {
|
||||
/** Copies every file under remote `dir` into local `target`; returns false when it has none. */
|
||||
downloadDir(dir: string, target: string): boolean;
|
||||
/** Copies local `file` to remote `key`. */
|
||||
upload(file: string, key: string): void;
|
||||
}
|
||||
|
||||
function joinKey(base: string, key: string): string {
|
||||
return `${base.replace(/\/+$/, "")}/${key}`;
|
||||
}
|
||||
|
||||
// plain fields: the CLI runs under Node's type stripping, which has no parameter properties
|
||||
class HfStorage implements DemoStorage {
|
||||
private readonly base: string;
|
||||
|
||||
constructor(base: string) {
|
||||
this.base = base;
|
||||
}
|
||||
|
||||
downloadDir(dir: string, target: string): boolean {
|
||||
mkdirSync(target, { recursive: true });
|
||||
|
||||
try {
|
||||
execFileSync("hf", ["buckets", "sync", joinKey(this.base, dir), target], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
upload(file: string, key: string): void {
|
||||
execFileSync("hf", ["buckets", "cp", file, joinKey(this.base, key)], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class FileStorage implements DemoStorage {
|
||||
private readonly root: string;
|
||||
|
||||
constructor(root: string) {
|
||||
this.root = root;
|
||||
}
|
||||
|
||||
downloadDir(dir: string, target: string): boolean {
|
||||
const source = join(this.root, dir);
|
||||
|
||||
if (!existsSync(source)) return false;
|
||||
|
||||
cpSync(source, target, { recursive: true });
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
upload(file: string, key: string): void {
|
||||
const target = join(this.root, key);
|
||||
|
||||
mkdirSync(dirname(target), { recursive: true });
|
||||
copyFileSync(file, target);
|
||||
}
|
||||
}
|
||||
|
||||
export function getDemoStorage(
|
||||
uri = process.env.DEMO_STORAGE,
|
||||
): DemoStorage | null {
|
||||
if (!uri) return null;
|
||||
|
||||
if (uri.startsWith("hf://")) return new HfStorage(uri);
|
||||
|
||||
if (uri.startsWith("file://")) return new FileStorage(fileURLToPath(uri));
|
||||
|
||||
throw new Error(
|
||||
`DEMO_STORAGE: unsupported scheme in "${uri}" (use hf:// or file://)`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Public URL of a stored key, when DEMO_STORAGE_PUBLIC_URL is set. */
|
||||
export function getPublicUrl(key: string): string | null {
|
||||
const base = process.env.DEMO_STORAGE_PUBLIC_URL;
|
||||
|
||||
return base ? joinKey(base, key) : null;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"noEmit": true,
|
||||
"skipLibCheck": true,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
Reference in New Issue
Block a user