mirror of
https://github.com/ggml-org/llama.cpp.git
synced 2026-11-26 20:57:42 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e0b9fd7d76 | ||
|
|
a07831a008 | ||
|
|
9fa7a33cbb | ||
|
|
e087c6c4e7 | ||
|
|
492d23cc9e | ||
|
|
e8d7128fea | ||
|
|
2a335259ca | ||
|
|
47d6192fce | ||
|
|
6d54465e9d | ||
|
|
98cc730cc8 | ||
|
|
e630f78729 | ||
|
|
5d7bb89f47 | ||
|
|
0ac39e4705 | ||
|
|
fa9f928f25 | ||
|
|
0e4e925e8f | ||
|
|
6aad4c7efd | ||
|
|
46ba8b7008 | ||
|
|
436d7e81ca | ||
|
|
a866b4ade6 | ||
|
|
4ba835c637 | ||
|
|
689194808a | ||
|
|
fd4b137e38 | ||
|
|
55d482814b |
@@ -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"; } ||
|
||||
|
||||
@@ -83,8 +83,16 @@ jobs:
|
||||
run: npm ci
|
||||
working-directory: ui/apps/chat
|
||||
|
||||
# the app's demo helpers import the demo harness (ui/lib/demo), whose sources resolve
|
||||
# @playwright/test and its other types from its own node_modules
|
||||
- name: Install demo harness dependencies
|
||||
id: setup-demo
|
||||
if: ${{ steps.setup.conclusion == 'success' }}
|
||||
run: npm ci
|
||||
working-directory: ui/lib/demo
|
||||
|
||||
- name: Run type checking
|
||||
if: ${{ always() && steps.setup.conclusion == 'success' }}
|
||||
if: ${{ always() && steps.setup.conclusion == 'success' && steps.setup-demo.conclusion == 'success' }}
|
||||
run: npm run check
|
||||
working-directory: ui/apps/chat
|
||||
|
||||
@@ -212,6 +220,29 @@ jobs:
|
||||
run: npm run prepack
|
||||
working-directory: ui/lib/harness
|
||||
|
||||
demo-checks:
|
||||
name: Demo harness checks
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }}
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24"
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
working-directory: ui/lib/demo
|
||||
|
||||
- name: Run type checking
|
||||
run: npm run check
|
||||
working-directory: ui/lib/demo
|
||||
|
||||
chat-only-build:
|
||||
name: Chat-only build
|
||||
runs-on: ubuntu-24.04
|
||||
|
||||
+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)
|
||||
|
||||
@@ -110,7 +110,7 @@ Although OpenVINO supports a wide range of [Intel hardware](https://docs.openvin
|
||||
|
||||
**NPU:**
|
||||
- All other quantized tensors are requantized to `Q4_0_128`.
|
||||
- For a `Q6_K` token embedding, `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` selects another layout.
|
||||
- For a `Q6_K` token embedding, `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` selects another layout. When it is set, it also applies to a `Q4_K` or `Q5_K` token embedding.
|
||||
- The validated models use `Q4_K_M` files.
|
||||
|
||||
**Layout names:**
|
||||
@@ -882,7 +882,9 @@ The defaults fit most models. The variables below trade one property for another
|
||||
| Variable | Device | Type | Default | Description |
|
||||
|---|---|---|---|---|
|
||||
| `GGML_OPENVINO_PREFILL_CHUNK_SIZE` | NPU | Integer | `256` | Number of tokens that the NPU processes in one prefill step. A larger value can make long prompts faster, and makes the first load longer. Zero or a negative value means the default. Example: `GGML_OPENVINO_PREFILL_CHUNK_SIZE=512`. |
|
||||
| `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` | NPU | String | `q8_0_c` | How a `Q6_K` `token_embd.weight` is stored for the NPU: `q8_0_c` (8-bit, one scale per row), `f16`, `q4_0_128` (4-bit, one scale per 128 weights) or `q4_0_c` (4-bit, one scale per row). The 4-bit layouts use less memory at some cost in accuracy; `f16` uses more memory. Keep the default unless memory is tight. |
|
||||
| `GGML_OPENVINO_KV_ONLY_PREFILL` | NPU | Boolean | `1` | For models whose last layers reuse the KV cache of an earlier layer (Gemma 3n and Gemma 4 E2B/E4B): compile the prefill with only the KV-cache writes as outputs, which drops those layers and the output layer from it, and compute the output token of a batch with one decode step. Takes effect only without `GGML_OPENVINO_NPU_HFA_PREFILL`, and not for models with recurrent state; with decode KV windows (`GGML_OPENVINO_NPU_BLOB_PREBUILD=1`) the output step runs the decode graph of the window that covers the output token. A batch that needs more than one output token switches to the full prefill. `0` turns it off. |
|
||||
| `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` | NPU | String | `q8_0_c` | How a `Q6_K` `token_embd.weight` is stored for the NPU: `q8_0_c` (8-bit, one scale per row), `f16`, `q4_0_128` (4-bit, one scale per 128 weights) or `q4_0_c` (4-bit, one scale per row). The 4-bit layouts use less memory at some cost in accuracy; `f16` uses more memory. Keep the default unless memory is tight. When set, it also applies to a `Q4_K` or `Q5_K` `token_embd.weight`, which otherwise keeps the 8-bit layout of the other weights; with a tied output layer (Gemma 4 E2B) `q4_0_128` stores it in about half the memory. |
|
||||
| `GGML_OPENVINO_NPU_HOST_GATHER` | NPU | Boolean | `0` | Look up the rows of large embedding tables (64 MiB or more) on the host, from the GGUF data, and pass them to the NPU graph as an input, instead of binding the whole table to the NPU. A table used only for such lookups, such as the per-layer embedding table of Gemma 3n and Gemma 4 E2B/E4B, is then not converted for the NPU at all. Lowers memory and decode time for such models. |
|
||||
| `GGML_OPENVINO_GDN_DECOMPOSE` | all | Boolean | auto | Translate `GATED_DELTA_NET` (Qwen3.5) into MatMul operations instead of the OpenVINO `GatedDeltaNet` op. Unset: on for the Lunar Lake NPU, off elsewhere. `0` turns it off, `1` turns it on for any device. Try `1` for Qwen3.5 on the Panther Lake NPU. |
|
||||
| `GGML_OPENVINO_MANUAL_GQA_ATTN` | CPU, GPU | Boolean | on for GPU | Build grouped-query attention from separate MatMul operations. Unset: on for GPU, off for CPU and NPU. `1` turns it on, `0` turns it off. Try `1` on the CPU for faster decode. |
|
||||
| `GGML_OPENVINO_REQUANT_KQUANT` | CPU, GPU | String | `not set` | Requantize `Q6_K` and `Q5_K` weights to a 4-bit layout instead of `Q8_0_C`: faster decode for lower accuracy. One of `q4_asym64`, `q4_asym64_all` (also `Q4_K`), `q4_sym128`, `q4_sym128_all` (also `Q4_K`) or `native` (no requantization). On GPU with `Q4_K_M` files use `q4_asym64_all`, because `q4_asym64` does not compile there. |
|
||||
@@ -903,10 +905,10 @@ export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache
|
||||
# CPU or GPU, later runs (optional): require the cached model and skip the weight upload and the compilation.
|
||||
export GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1
|
||||
|
||||
# NPU: add the weightless bank.
|
||||
# NPU: valid cached models are imported. Otherwise the run compiles them, writes them without weights plus one
|
||||
# shared weights file, and logs a warning.
|
||||
export GGML_OPENVINO_DEVICE=NPU
|
||||
export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache
|
||||
export GGML_OPENVINO_NPU_WEIGHTLESS_BANK=1
|
||||
./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512
|
||||
|
||||
# NPU, later runs (optional): use less memory. The run fails if a cached model is missing.
|
||||
@@ -919,12 +921,11 @@ export GGML_OPENVINO_SELF_CONTAINED_MMAP=1
|
||||
| Variable | Device | Type | Default | Description |
|
||||
|---|---|---|---|---|
|
||||
| `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY` | CPU, GPU | Boolean | `0` | Require an existing cached model and skip the weight upload and the compilation. Needs mmap model loading (the default on Linux and Windows) and a model that runs fully on OpenVINO. |
|
||||
| `GGML_OPENVINO_NPU_WEIGHTLESS_BANK` | NPU | Boolean | `0` | Requires `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`. Write the prefill and decode models without weights, plus one shared weights file. Later runs read the weights from that file and keep one copy in memory. |
|
||||
| `GGML_OPENVINO_SELF_CONTAINED_MMAP` | NPU | Boolean | `0` | Later runs only. Requires `GGML_OPENVINO_NPU_WEIGHTLESS_BANK=1` and an existing cache. Use the memory-mapped GGUF file as the model buffer, which lowers the host memory peak. Fails if a cached model is missing; run once without it to build the cache. |
|
||||
| `GGML_OPENVINO_SELF_CONTAINED_MMAP` | NPU | Boolean | `0` | Later runs only. Requires `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` with an existing cache. Use the memory-mapped GGUF file as the model buffer, which lowers the host memory peak. Fails if a cached model is missing, for example after a change of the model, `-c` or another setting; run once without it to build the cache. |
|
||||
| `GGML_OPENVINO_CACHE_DIR` | all | String | `not set` | Directory for the cache of the OpenVINO plugin itself. `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` is the recommended cache. |
|
||||
|
||||
- One directory can hold the cached models of different models and settings.
|
||||
- NPU: each prefill length enters the cache in a run without `GGML_OPENVINO_SELF_CONTAINED_MMAP`.
|
||||
- NPU, with the default settings: the first prompt writes the prefill model of every KV window up to `-c`, so later runs with the same `-c` find a cached model for any prompt length.
|
||||
- See [Compiled model cache](../../ggml/src/ggml-openvino/README.md#compiled-model-cache) for the workflow and the restrictions.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -818,6 +818,7 @@ User can use the device management in [docs/multi-gpu.md](https://github.com/ggm
|
||||
| GGML_SYCL_ENABLE_VMM | 0 or 1 (default) | Enable the virtual-memory device pool. |
|
||||
| GGML_SYCL_ENABLE_MKL_FA | 1 (default) or 0 | Enable oneMKL GEMM flash attention for XMX-accelerated prompt processing with quantized KV cache. Automatically activates during prefill (prompt processing) when all conditions are met: (1) flash-attn enabled (`-fa` or `--flash-attn on`), (2) KV cache quantized (`--cache-type-k q8_0 --cache-type-v q8_0` or other `*_0/*_1` types), (3) batch size ≥ 1024 (`--batch-size 1024`), (4) prompt length ≥ 1024 tokens. Set to 0 to force the TILE kernel for A/B testing. Example minimum command: `llama-cli -m model.gguf -fa -ngl 99 --cache-type-k q8_0 --cache-type-v q8_0 --batch-size 1024 -p "your prompt"` |
|
||||
| GGML_SYCL_MKL_FA_DEBUG | 0 (default) or 1 | Enable per-call diagnostic logging for MKL flash attention: GEMM/softmax timings, interleaved-head detection, and buffer memory usage. |
|
||||
| GGML_SYCL_FA_TILE_DEBUG | 0 (default) or 1 | Enable per-call diagnostic logging for the flash-attention TILE kernel dispatcher: head dims (DKQ/DV), GQA ratio, query rows, KV length, and whether the GQA-optimized variant is selected. |
|
||||
| GGML_SYCL_MEMTRACE | 0 (default), 1, 2 | Enable record and output memory allocation diagnostics. Requires `-lv 4`. <br>0 - Disable<br>1 - Basic memory info, including current and peak allocations, as well allocations from other sources, and the device free memory before each model buffer allocation, around 50 lines per model load.<br>2 - More verbose, logging around 900 specific allocations and deallocations. |
|
||||
| GGML_SYCL_MEMTRACE_STEP | 64 (default) or positive integer | With GGML_SYCL_MEMTRACE=1, the minimum growth in memory usage to trigger another log record. |
|
||||
| GGML_SYCL_MKL_FA_DIAG | 0 (default) or 1 | Enable output fingerprinting for MKL flash attention. Dumps the first 64 float output values for the first 6 FA calls with n_kv ≥ 1024, labeled with kernel type (MKL/TILE/VEC) for cross-kernel comparison. |
|
||||
|
||||
@@ -112,7 +112,6 @@
|
||||
systems = [
|
||||
"aarch64-darwin"
|
||||
"aarch64-linux"
|
||||
"x86_64-darwin" # x86_64-darwin isn't tested (and likely isn't relevant)
|
||||
"x86_64-linux"
|
||||
];
|
||||
|
||||
|
||||
@@ -441,6 +441,8 @@ static bool ggml_backend_cpu_device_supports_op(ggml_backend_dev_t dev, const st
|
||||
}
|
||||
|
||||
switch (op->op) {
|
||||
case GGML_OP_FLASH_ATTN_EXT:
|
||||
return ggml_validate_flash_attn_ext_indexed_bias(op);
|
||||
case GGML_OP_CPY:
|
||||
case GGML_OP_SET_ROWS:
|
||||
return
|
||||
|
||||
@@ -9722,6 +9722,7 @@ static void ggml_compute_forward_flash_attn_ext_f16(
|
||||
void ggml_compute_forward_flash_attn_ext(
|
||||
const ggml_compute_params * params,
|
||||
ggml_tensor * dst) {
|
||||
GGML_ASSERT(ggml_validate_flash_attn_ext_indexed_bias(dst));
|
||||
switch (ggml_prec_get_acc(dst)) {
|
||||
case GGML_PREC_UNDEFINED:
|
||||
case GGML_PREC_F32:
|
||||
|
||||
@@ -20,6 +20,28 @@
|
||||
// The macro on the following line shifts it by a factor of 2**3=8, as was needed to fix https://github.com/ggml-org/llama.cpp/issues/18606 .
|
||||
#define FATTN_KQ_MAX_OFFSET (3.0f*0.6931f)
|
||||
|
||||
struct fattn_indexed_bias {
|
||||
const float * table;
|
||||
const int32_t * indices;
|
||||
int64_t n_bins;
|
||||
int64_t n_keys;
|
||||
int64_t query_stride;
|
||||
|
||||
__device__ fattn_indexed_bias for_head(int64_t first_query, int head) const {
|
||||
return {table + first_query*query_stride + head*n_bins, indices + first_query*n_keys, n_bins, n_keys, query_stride};
|
||||
}
|
||||
|
||||
__device__ float add(float mask, int query, int key) const {
|
||||
const int bin = indices[query*n_keys + key];
|
||||
return bin >= 0 && bin < n_bins ? mask + table[query*query_stride + bin] : mask;
|
||||
}
|
||||
};
|
||||
|
||||
// ggml-cpu returns zero for the 0/0 of a fully masked query.
|
||||
static __device__ __forceinline__ float fattn_normalize(float value, float rowsum) {
|
||||
return value == 0.0f && rowsum == 0.0f ? 0.0f : value/rowsum;
|
||||
}
|
||||
|
||||
using fattn_kernel_t = void (*)(
|
||||
const float2 * __restrict__ Q,
|
||||
const char * __restrict__ K,
|
||||
@@ -42,7 +64,8 @@ using fattn_kernel_t = void (*)(
|
||||
const int32_t s11, const int32_t s12, const int64_t s13,
|
||||
const int32_t s21, const int32_t s22, const int64_t s23,
|
||||
const int32_t ne31, const int32_t ne32, const int32_t ne33,
|
||||
const int32_t s31, const int64_t s32, const int64_t s33);
|
||||
const int32_t s31, const int64_t s32, const int64_t s33,
|
||||
const fattn_indexed_bias bias);
|
||||
|
||||
typedef float (*vec_dot_KQ_t)(
|
||||
const char * __restrict__ K_c, const void * __restrict__ Q_v, const int * __restrict__ Q_q8 , const void * __restrict__ Q_ds);
|
||||
@@ -1110,7 +1133,7 @@ static __global__ void flash_attn_stream_k_fixup_uniform(
|
||||
}
|
||||
|
||||
// Write back final result:
|
||||
*dst = dst_val / rowsum;
|
||||
*dst = fattn_normalize(dst_val, rowsum);
|
||||
}
|
||||
|
||||
// General fixup kernel for the case where the number of blocks per tile is not uniform across tiles
|
||||
@@ -1221,7 +1244,7 @@ static __global__ void flash_attn_stream_k_fixup_general(
|
||||
}
|
||||
|
||||
// Write back final result:
|
||||
*dst = dst_val / rowsum;
|
||||
*dst = fattn_normalize(dst_val, rowsum);
|
||||
}
|
||||
|
||||
template<int D> // D == head size
|
||||
@@ -1279,7 +1302,7 @@ static __global__ void flash_attn_combine_results(
|
||||
VKQ_denominator += KQ_max_scale * meta[l].y;
|
||||
}
|
||||
|
||||
dst[tid] = VKQ_numerator / VKQ_denominator;
|
||||
dst[tid] = fattn_normalize(VKQ_numerator, VKQ_denominator);
|
||||
}
|
||||
|
||||
template <int DV, int ncols1, int ncols2, typename T_K_stride, typename T_V_stride>
|
||||
@@ -1301,6 +1324,10 @@ void launch_fattn(
|
||||
const ggml_tensor * sinks = dst->src[4];
|
||||
const ggml_tensor * kv_rows = dst->src[5];
|
||||
|
||||
const bool has_bias = ggml_flash_attn_ext_has_indexed_bias(dst);
|
||||
const ggml_tensor * bias_table = has_bias ? dst->src[6] : nullptr;
|
||||
const ggml_tensor * bias_indices = has_bias ? dst->src[7] : nullptr;
|
||||
|
||||
// with kv_rows the kernel iterates over the mask columns and reads K/V rows through kv_rows
|
||||
const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : K->ne[1];
|
||||
GGML_ASSERT(!kv_rows || !use_sparse);
|
||||
@@ -1433,7 +1460,9 @@ void launch_fattn(
|
||||
// Optional optimization where the mask is scanned to determine whether part of the calculation can be skipped.
|
||||
// Only worth the overhead if there is at lease one FATTN_KQ_STRIDE x FATTN_KQ_STRIDE square to be skipped or
|
||||
// multiple sequences of possibly different lengths, or kv_rows lists that end with padding.
|
||||
const bool scan_mask = !use_sparse && mask && mask->ne[2] == 1 && n_kv_cols % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1 || kv_rows);
|
||||
// The scan reads ncols1 mask rows per tile, including the last tile.
|
||||
const bool scan_mask = !has_bias && !use_sparse && mask && mask->ne[2] == 1 && mask->ne[1]/ncols1 >= ntiles_x &&
|
||||
n_kv_cols % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1 || kv_rows);
|
||||
if (scan_mask) {
|
||||
const int64_t s31 = mask->nb[1] / sizeof(half2);
|
||||
const int64_t s33 = mask->nb[3] / sizeof(half2);
|
||||
@@ -1591,7 +1620,12 @@ void launch_fattn(
|
||||
mask ? mask->ne[1] : 0, mask ? mask->ne[2] : 0, mask ? mask->ne[3] : 0,
|
||||
mask ? int32_t(mask->nb[1] / sizeof(half)) : 0,
|
||||
mask ? int64_t(mask->nb[2] / sizeof(half)) : 0,
|
||||
mask ? int64_t(mask->nb[3] / sizeof(half)) : 0
|
||||
mask ? int64_t(mask->nb[3] / sizeof(half)) : 0,
|
||||
fattn_indexed_bias{has_bias ? (const float *) bias_table->data : nullptr,
|
||||
has_bias ? (const int32_t *) bias_indices->data : nullptr,
|
||||
has_bias ? bias_table->ne[0] : 0,
|
||||
has_bias ? bias_indices->ne[0] : 0,
|
||||
has_bias ? bias_table->ne[0]*bias_table->ne[1] : 0}
|
||||
);
|
||||
CUDA_CHECK(cudaGetLastError());
|
||||
|
||||
|
||||
@@ -1807,8 +1807,8 @@ static __device__ __forceinline__ void flash_attn_ext_f16_process_tile(
|
||||
|
||||
if (!needs_fixup && !is_fixup) {
|
||||
const float KQ_rowsum_j = meta_j[1];
|
||||
dstk_val.x /= KQ_rowsum_j;
|
||||
dstk_val.y /= KQ_rowsum_j;
|
||||
dstk_val.x = fattn_normalize(dstk_val.x, KQ_rowsum_j);
|
||||
dstk_val.y = fattn_normalize(dstk_val.y, KQ_rowsum_j);
|
||||
}
|
||||
|
||||
if (is_fixup) {
|
||||
@@ -1865,7 +1865,9 @@ static __global__ void flash_attn_ext_f16(
|
||||
const int32_t s11, const int32_t s12, const int64_t s13,
|
||||
const int32_t s21, const int32_t s22, const int64_t s23,
|
||||
const int32_t ne31, const int32_t ne32, const int32_t ne33,
|
||||
const int32_t s31, const int64_t s32, const int64_t s33) {
|
||||
const int32_t s31, const int64_t s32, const int64_t s33,
|
||||
const fattn_indexed_bias bias) {
|
||||
GGML_UNUSED(bias); // biased ops are never dispatched to the mma kernel
|
||||
ggml_cuda_pdl_sync(); // TODO optimize placement
|
||||
#if defined(FLASH_ATTN_AVAILABLE) && (defined(VOLTA_MMA_AVAILABLE) || defined(TURING_MMA_AVAILABLE) || defined(AMD_WMMA_AVAILABLE) || defined(AMD_MFMA_AVAILABLE))
|
||||
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
|
||||
|
||||
@@ -375,7 +375,7 @@ static constexpr __device__ int ggml_cuda_fattn_tile_get_nbatch_K(const int DKQ,
|
||||
|
||||
// Function that performs a single iteration in for the KQ matrix multiplication:
|
||||
template <int warp_size, int nwarps, int ncols1, int ncols2, int DKQ, int nbatch_fa, int nbatch_K,
|
||||
bool use_logit_softcap, bool oob_check, typename T_vec_dot, typename T_K>
|
||||
bool use_logit_softcap, bool oob_check, bool indexed_bias, typename T_vec_dot, typename T_K>
|
||||
static __device__ __forceinline__ void flash_attn_tile_iter_KQ(
|
||||
T_vec_dot * const Q_tmp,
|
||||
const T_K * const __restrict__ K_h2,
|
||||
@@ -384,7 +384,8 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ(
|
||||
const int k_VKQ_0,
|
||||
const int k_VKQ_sup,
|
||||
const int k_KQ_0,
|
||||
float * KQ_acc) {
|
||||
float * KQ_acc,
|
||||
const int32_t * const __restrict__ rows) {
|
||||
constexpr int cpy_nb = 16;
|
||||
constexpr int cpy_ne = cpy_nb / 4;
|
||||
|
||||
@@ -393,8 +394,8 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ(
|
||||
constexpr int np = nwarps > ncols ? nwarps/ncols : 1; // number of parallel warps per Q column
|
||||
|
||||
constexpr int stride_tile_K = std::is_same_v<T_vec_dot, half2> ? nbatch_K/2 + cpy_ne : nbatch_K + cpy_ne;
|
||||
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, nbatch_K, stride_tile_K, false, oob_check, false, false, false, T_K, T_vec_dot>
|
||||
(K_h2 + k_KQ_0/2, KV_tmp, nbatch_K/2, stride_K2, k_VKQ_0, k_VKQ_sup, nullptr);
|
||||
flash_attn_load_tile<warp_size, nwarps, nbatch_fa, nbatch_K, stride_tile_K, false, oob_check, false, indexed_bias, false, T_K, T_vec_dot>
|
||||
(K_h2 + k_KQ_0/2, KV_tmp, nbatch_K/2, stride_K2, k_VKQ_0, k_VKQ_sup, rows);
|
||||
__syncthreads();
|
||||
|
||||
#ifdef FAST_FP16_AVAILABLE
|
||||
@@ -451,7 +452,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter_KQ(
|
||||
|
||||
// Function that performs a single iteration of the main loop over up to nbatch_fa tokens.
|
||||
template <int warp_size, int nwarps, int ncols1, int ncols2, int DKQ, int DV, int nbatch_fa, int nbatch_K,
|
||||
bool use_logit_softcap, bool oob_check, typename T_vec_dot, typename T_KQ, typename T_acc, typename T_K, typename T_V>
|
||||
bool use_logit_softcap, bool oob_check, bool indexed_bias, typename T_vec_dot, typename T_KQ, typename T_acc, typename T_K, typename T_V>
|
||||
static __device__ __forceinline__ void flash_attn_tile_iter(
|
||||
T_vec_dot * const Q_tmp,
|
||||
const T_K * const __restrict__ K_h2,
|
||||
@@ -470,7 +471,9 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
|
||||
T_acc * const VKQ,
|
||||
const int k_VKQ_0,
|
||||
const int k_VKQ_max,
|
||||
const int col_Q_0) {
|
||||
const int col_Q_0,
|
||||
const fattn_indexed_bias bias,
|
||||
const int32_t * const __restrict__ rows) {
|
||||
constexpr int cpy_nb = 16;
|
||||
constexpr int cpy_ne = cpy_nb / 4;
|
||||
|
||||
@@ -502,13 +505,13 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
|
||||
constexpr int nbatch_K_last = DKQ % nbatch_K;
|
||||
#pragma unroll
|
||||
for (int k_KQ_0 = 0; k_KQ_0 < DKQ - nbatch_K_last; k_KQ_0 += nbatch_K) {
|
||||
flash_attn_tile_iter_KQ<warp_size, nwarps, ncols1, ncols2, DKQ, nbatch_fa, nbatch_K, use_logit_softcap, oob_check>(
|
||||
Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc);
|
||||
flash_attn_tile_iter_KQ<warp_size, nwarps, ncols1, ncols2, DKQ, nbatch_fa, nbatch_K, use_logit_softcap, oob_check, indexed_bias>(
|
||||
Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc, rows);
|
||||
}
|
||||
if (nbatch_K_last > 0) {
|
||||
constexpr int k_KQ_0 = DKQ - nbatch_K_last;
|
||||
flash_attn_tile_iter_KQ<warp_size, nwarps, ncols1, ncols2, DKQ, nbatch_fa, nbatch_K_last, use_logit_softcap, oob_check>(
|
||||
Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc);
|
||||
flash_attn_tile_iter_KQ<warp_size, nwarps, ncols1, ncols2, DKQ, nbatch_fa, nbatch_K_last, use_logit_softcap, oob_check, indexed_bias>(
|
||||
Q_tmp, K_h2, KV_tmp, stride_K2, k_VKQ_0, k_VKQ_sup, k_KQ_0, KQ_acc, rows);
|
||||
}
|
||||
|
||||
// Apply logit softcap + mask, update KQ_max:
|
||||
@@ -531,8 +534,12 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
|
||||
}
|
||||
|
||||
if (!oob_check || i_KQ < k_VKQ_sup) {
|
||||
KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] += (ncols2 > 1 || mask) ?
|
||||
slope*__half2float(mask[j*stride_mask + k_VKQ_0 + i_KQ]) : 0.0f;
|
||||
if (indexed_bias || ncols2 > 1 || mask) {
|
||||
const int k = k_VKQ_0 + i_KQ;
|
||||
__builtin_assume(k >= 0); // avoid sign extension and register spills on RDNA
|
||||
const float m = __half2float(mask[int64_t(j)*stride_mask + k]);
|
||||
KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] += slope*(indexed_bias ? bias.add(m, j, k) : m);
|
||||
}
|
||||
|
||||
KQ_max_new[jc0] = fmaxf(KQ_max_new[jc0], KQ_acc[(i_KQ_0/(np*warp_size))*cpw + jc0] + FATTN_KQ_MAX_OFFSET);
|
||||
}
|
||||
@@ -614,8 +621,8 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
|
||||
constexpr int stride_tile_V = std::is_same_v<T_vec_dot, half2> ? DV/2 : DV;
|
||||
#pragma unroll
|
||||
for (int k0 = 0; k0 < nbatch_fa; k0 += nbatch_V) {
|
||||
flash_attn_load_tile<warp_size, nwarps, nbatch_V, DV, stride_tile_V, false, oob_check, false, false, false, T_V, T_vec_dot>
|
||||
(V_h2, KV_tmp, DV/2, stride_V2, k_VKQ_0 + k0, k_VKQ_sup - k0, nullptr);
|
||||
flash_attn_load_tile<warp_size, nwarps, nbatch_V, DV, stride_tile_V, false, oob_check, false, indexed_bias, false, T_V, T_vec_dot>
|
||||
(V_h2, KV_tmp, DV/2, stride_V2, k_VKQ_0 + k0, k_VKQ_sup - k0, rows);
|
||||
__syncthreads();
|
||||
|
||||
#ifdef FAST_FP16_AVAILABLE
|
||||
@@ -684,7 +691,7 @@ static __device__ __forceinline__ void flash_attn_tile_iter(
|
||||
}
|
||||
}
|
||||
|
||||
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap, ggml_type type_K, ggml_type type_V> // D == head size
|
||||
template<int DKQ, int DV, int ncols1, int ncols2, bool use_logit_softcap, bool indexed_bias, ggml_type type_K, ggml_type type_V, bool use_kv_rows> // D == head size
|
||||
__launch_bounds__(ggml_cuda_fattn_tile_get_nthreads(DKQ, DV, ncols1*ncols2), ggml_cuda_fattn_tile_get_occupancy(DKQ, DV, ncols1*ncols2))
|
||||
static __global__ void flash_attn_tile(
|
||||
const float2 * Q_ptr,
|
||||
@@ -708,7 +715,8 @@ static __global__ void flash_attn_tile(
|
||||
const int32_t s11, const int32_t s12, const int64_t s13,
|
||||
const int32_t s21, const int32_t s22, const int64_t s23,
|
||||
const int32_t ne31, const int32_t ne32, const int32_t ne33,
|
||||
const int32_t s31, const int64_t s32, const int64_t s33) {
|
||||
const int32_t s31, const int64_t s32, const int64_t s33,
|
||||
const fattn_indexed_bias bias) {
|
||||
#ifdef FLASH_ATTN_AVAILABLE
|
||||
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
|
||||
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
|
||||
@@ -721,7 +729,6 @@ static __global__ void flash_attn_tile(
|
||||
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
|
||||
float * GGML_CUDA_RESTRICT dst = dst_ptr;
|
||||
float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr;
|
||||
GGML_UNUSED(KV_rows_ptr);
|
||||
|
||||
// Skip unused kernel variants for faster compilation:
|
||||
|
||||
@@ -760,12 +767,15 @@ static __global__ void flash_attn_tile(
|
||||
|
||||
const int sequence = blockIdx.z / (ne02/ncols2);
|
||||
const int head0 = blockIdx.z*ncols2 - sequence*ne02; // == blockIdx.z % (ne02/ncols2)
|
||||
const int32_t * rows = use_kv_rows ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr;
|
||||
__builtin_assume(!use_kv_rows || rows != nullptr);
|
||||
const fattn_indexed_bias head_bias = indexed_bias ? bias.for_head(int64_t(sequence)*ne01.z, head0) : bias;
|
||||
const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix.
|
||||
const float2 * Q_f2 = Q + s03*sequence + s02* head0;
|
||||
const T_K * K_h2 = K + s13*sequence + s12*(head0 / gqa_ratio);
|
||||
const T_V * V_h2 = V + s23*sequence + s22*(head0 / gqa_ratio); // K and V have same shape
|
||||
|
||||
const half * maskh = mask ? mask + s33*(sequence % ne33) + s32*(head0 % ne32) : nullptr;
|
||||
const half * maskh = indexed_bias || mask ? mask + s33*(sequence % ne33) + s32*(head0 % ne32) : nullptr;
|
||||
|
||||
const int stride_K2 = s11;
|
||||
const int stride_V2 = s21;
|
||||
@@ -864,24 +874,24 @@ static __global__ void flash_attn_tile(
|
||||
int k_VKQ_0 = blockIdx.y*nbatch_fa;
|
||||
while (k_VKQ_0 <= k_VKQ_max - nbatch_fa) {
|
||||
constexpr bool oob_check = false;
|
||||
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check>
|
||||
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check, indexed_bias>
|
||||
(Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp,
|
||||
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0);
|
||||
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, head_bias, rows);
|
||||
k_VKQ_0 += gridDim.y*nbatch_fa;
|
||||
}
|
||||
if (k_VKQ_0 < k_VKQ_max) {
|
||||
constexpr bool oob_check = true;
|
||||
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check>
|
||||
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check, indexed_bias>
|
||||
(Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp,
|
||||
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0);
|
||||
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, head_bias, rows);
|
||||
}
|
||||
} else {
|
||||
// Branch without out-of-bounds checks.
|
||||
for (int k_VKQ_0 = blockIdx.y*nbatch_fa; k_VKQ_0 < k_VKQ_max; k_VKQ_0 += gridDim.y*nbatch_fa) {
|
||||
constexpr bool oob_check = false;
|
||||
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check>
|
||||
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap, oob_check, indexed_bias>
|
||||
(Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp,
|
||||
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0);
|
||||
stride_K2, stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0, head_bias, rows);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -998,7 +1008,7 @@ static __global__ void flash_attn_tile(
|
||||
return;
|
||||
}
|
||||
|
||||
const float scale = gridDim.y == 1 ? 1.0f/KQ_sum[jc0] : 1.0f;
|
||||
const float rowsum = gridDim.y == 1 ? KQ_sum[jc0] : 1.0f;
|
||||
|
||||
const int j_dst_unrolled = ((sequence*int(ne01.z) + col_Q_0 + j)*ne02 + head0 + c)*gridDim.y + blockIdx.y;
|
||||
|
||||
@@ -1010,8 +1020,8 @@ static __global__ void flash_attn_tile(
|
||||
#pragma unroll
|
||||
for (int i1 = 0; i1 < cpy_ne_D; ++i1) {
|
||||
tmp[i1] = __half22float2(VKQ[jc0*((DVp/2)/warp_size) + i0/warp_size + i1]);
|
||||
tmp[i1].x *= scale;
|
||||
tmp[i1].y *= scale;
|
||||
tmp[i1].x = fattn_normalize(tmp[i1].x, rowsum);
|
||||
tmp[i1].y = fattn_normalize(tmp[i1].y, rowsum);
|
||||
}
|
||||
if (i0 + warp_size*cpy_ne_D <= DV/2 || i0 + threadIdx.x*cpy_ne_D < DV/2) {
|
||||
ggml_cuda_memcpy_1<sizeof(tmp)>(&dst[j_dst_unrolled*DV + 2*i0 + threadIdx.x*(2*cpy_ne_D)], tmp);
|
||||
@@ -1024,8 +1034,9 @@ static __global__ void flash_attn_tile(
|
||||
if (i0 + warp_size*cpy_ne_D <= DV || i0 + threadIdx.x*cpy_ne_D < DV) {
|
||||
#pragma unroll
|
||||
for (int i1 = 0; i1 < cpy_ne_D/2; ++i1) {
|
||||
VKQ[jc0*((DVp/2)/warp_size) + i0/(2*warp_size) + i1].x *= scale;
|
||||
VKQ[jc0*((DVp/2)/warp_size) + i0/(2*warp_size) + i1].y *= scale;
|
||||
float2 & val = VKQ[jc0*((DVp/2)/warp_size) + i0/(2*warp_size) + i1];
|
||||
val.x = fattn_normalize(val.x, rowsum);
|
||||
val.y = fattn_normalize(val.y, rowsum);
|
||||
}
|
||||
ggml_cuda_memcpy_1<cpy_ne_D*4>(
|
||||
&dst[j_dst_unrolled*DV + i0 + threadIdx.x*cpy_ne_D],
|
||||
@@ -1047,12 +1058,12 @@ static __global__ void flash_attn_tile(
|
||||
s11, s12, s13,
|
||||
s21, s22, s23,
|
||||
ne31, ne32, ne33,
|
||||
s31, s32, s33);
|
||||
s31, s32, s33, bias);
|
||||
NO_DEVICE_CODE;
|
||||
#endif // FLASH_ATTN_AVAILABLE
|
||||
}
|
||||
|
||||
template <int DKQ, int DV, int ncols2, bool use_logit_softcap, ggml_type type_K, ggml_type type_V>
|
||||
template <int DKQ, int DV, int ncols2, bool use_logit_softcap, ggml_type type_K, ggml_type type_V, bool indexed_bias, bool use_kv_rows>
|
||||
static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
|
||||
using T_K = decltype(ggml_cuda_fattn_kv_dtype<type_K>());
|
||||
using T_V = decltype(ggml_cuda_fattn_kv_dtype<type_V>());
|
||||
@@ -1066,40 +1077,42 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
|
||||
constexpr size_t nbytes_shared = 0;
|
||||
|
||||
#ifdef GGML_USE_HIP
|
||||
if constexpr (DKQ <= 128) {
|
||||
// Limit indexed bias tile widths to avoid spilling registers on AMD.
|
||||
// TODO: select the tile width in one function.
|
||||
constexpr int max_cols = !indexed_bias ? 64 : DKQ == 64 ? 32 : use_kv_rows ? 16 : 8;
|
||||
if constexpr (DKQ <= 128 && max_cols >= 64) {
|
||||
if (!(amd_mfma_available(cc) && ncols2 == 1) && Q->ne[1] > 32/ncols2) {
|
||||
constexpr int cols_per_block = 64;
|
||||
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
|
||||
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, indexed_bias, type_K, type_V, use_kv_rows>;
|
||||
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
|
||||
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
|
||||
return;
|
||||
}
|
||||
}
|
||||
#else
|
||||
constexpr int max_cols = DKQ <= 256 ? 32 : 16;
|
||||
#endif // GGML_USE_HIP
|
||||
|
||||
#ifndef GGML_USE_HIP
|
||||
if constexpr (DKQ <= 256)
|
||||
#endif // GGML_USE_HIP
|
||||
{
|
||||
if constexpr (max_cols >= 32) {
|
||||
if (Q->ne[1] > 16/ncols2) {
|
||||
constexpr int cols_per_block = 32;
|
||||
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
|
||||
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, indexed_bias, type_K, type_V, use_kv_rows>;
|
||||
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
|
||||
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if constexpr (ncols2 <= 16) {
|
||||
if constexpr (ncols2 <= 16 && max_cols >= 16) {
|
||||
if (Q->ne[1] > 8/ncols2) {
|
||||
constexpr int cols_per_block = 16;
|
||||
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
|
||||
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, indexed_bias, type_K, type_V, use_kv_rows>;
|
||||
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
|
||||
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
|
||||
return;
|
||||
@@ -1111,7 +1124,7 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
|
||||
constexpr int cols_per_block = 8;
|
||||
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
|
||||
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, indexed_bias, type_K, type_V, use_kv_rows>;
|
||||
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
|
||||
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
|
||||
return;
|
||||
@@ -1123,7 +1136,7 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
|
||||
constexpr int cols_per_block = 4;
|
||||
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
|
||||
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, indexed_bias, type_K, type_V, use_kv_rows>;
|
||||
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
|
||||
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
|
||||
return;
|
||||
@@ -1134,7 +1147,7 @@ static void launch_fattn_tile_switch_ncols1(ggml_backend_cuda_context & ctx, ggm
|
||||
constexpr int cols_per_block = 2;
|
||||
const int nwarps = ggml_cuda_fattn_tile_get_nthreads (DKQ, DV, cols_per_block, cc) / warp_size;
|
||||
const int nbatch_fa = ggml_cuda_fattn_tile_get_nbatch_fa(DKQ, DV, cols_per_block, cc);
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, type_K, type_V>;
|
||||
fattn_kernel_t fattn_kernel = flash_attn_tile<DKQ, DV, cols_per_block/ncols2, ncols2, use_logit_softcap, indexed_bias, type_K, type_V, use_kv_rows>;
|
||||
launch_fattn<DV, cols_per_block/ncols2, ncols2, T_K, T_V>
|
||||
(ctx, dst, fattn_kernel, nwarps, nbytes_shared, nbatch_fa, true, true, false, false, warp_size);
|
||||
return;
|
||||
@@ -1163,6 +1176,17 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
|
||||
// a mask with a head dimension is not shared by the Q heads of a K/V head
|
||||
const bool use_gqa_opt = mask && mask->ne[2] == 1 && max_bias == 0.0f && Q->ne[1] <= gqa_limit && K->ne[1] % FATTN_KQ_STRIDE == 0;
|
||||
|
||||
if constexpr (DKQ == 64 || DKQ == 128) {
|
||||
if (ggml_flash_attn_ext_has_indexed_bias(dst)) {
|
||||
if (dst->src[5]) {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 1, use_logit_softcap, type_K, type_V, true, true>(ctx, dst);
|
||||
} else {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 1, use_logit_softcap, type_K, type_V, true, false>(ctx, dst);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if constexpr (DKQ == 320) {
|
||||
// This branch is only used for Mistral Small 4 which has a GQA ratio of 32.
|
||||
// On AMD, simply use that GQA ratio with 32 columns / block since we always have enough SRAM.
|
||||
@@ -1170,12 +1194,12 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
|
||||
// Therefore, use a GQA ratio of 16 with 16 columns / block to stay below 48 kiB of SRAM / block.
|
||||
#ifdef GGML_USE_HIP
|
||||
if (use_gqa_opt && gqa_ratio % 32 == 0) {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 32, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 32, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
#else
|
||||
if (use_gqa_opt && gqa_ratio % 16 == 0) {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
#endif // GGML_USE_HIP
|
||||
@@ -1184,11 +1208,11 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
|
||||
|
||||
if constexpr (DKQ == 576) {
|
||||
if (use_gqa_opt && gqa_ratio % 16 == 0) {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
if (use_gqa_opt && gqa_ratio % 4 == 0) {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -1196,11 +1220,11 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
|
||||
if constexpr (DKQ == 192) {
|
||||
// MiMo-V2.5 / V2.5-Pro / V2-Flash: gqa_ratio is 8 (SWA) or 16 (full attn)
|
||||
if (use_gqa_opt && gqa_ratio % 16 == 0) {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 16, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
if (use_gqa_opt && gqa_ratio % 8 == 0) {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 8, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 8, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
GGML_ABORT("flash-attn tile (192/128): expected GQA ratio multiple of 8");
|
||||
@@ -1208,22 +1232,22 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_cuda_context & ctx, ggm
|
||||
|
||||
if constexpr (DKQ <= 512 && DKQ != 320 && DKQ != 192) {
|
||||
if (use_gqa_opt && gqa_ratio % 8 == 0) {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 8, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 8, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
|
||||
if (use_gqa_opt && gqa_ratio % 4 == 0) {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 4, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
|
||||
if (use_gqa_opt && gqa_ratio % 2 == 0) {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 2, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 2, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
|
||||
if constexpr (DV <= 256) {
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 1, use_logit_softcap, type_K, type_V>(ctx, dst);
|
||||
launch_fattn_tile_switch_ncols1<DKQ, DV, 1, use_logit_softcap, type_K, type_V, false, false>(ctx, dst);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ static constexpr __device__ int ggml_cuda_fattn_vec_get_nthreads_device() {
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wpass-failed"
|
||||
#endif // __clang__
|
||||
template<int D, int ncols, ggml_type type_K, ggml_type type_V, bool use_logit_softcap> // D == head size
|
||||
template<int D, int ncols, ggml_type type_K, ggml_type type_V, bool use_logit_softcap, bool indexed_bias, bool use_kv_rows> // D == head size
|
||||
__launch_bounds__(ggml_cuda_fattn_vec_get_nthreads_device(), 1)
|
||||
static __global__ void flash_attn_ext_vec(
|
||||
const float2 * Q_ptr,
|
||||
@@ -40,7 +40,8 @@ static __global__ void flash_attn_ext_vec(
|
||||
const int32_t s11, const int32_t s12, const int64_t s13,
|
||||
const int32_t s21, const int32_t s22, const int64_t s23,
|
||||
const int32_t ne31, const int32_t ne32, const int32_t ne33,
|
||||
const int32_t s31, const int64_t s32, const int64_t s33) {
|
||||
const int32_t s31, const int64_t s32, const int64_t s33,
|
||||
const fattn_indexed_bias bias) {
|
||||
ggml_cuda_pdl_lc();
|
||||
#ifdef FLASH_ATTN_AVAILABLE
|
||||
const float2 * GGML_CUDA_RESTRICT Q = Q_ptr;
|
||||
@@ -51,7 +52,6 @@ static __global__ void flash_attn_ext_vec(
|
||||
const int * GGML_CUDA_RESTRICT KV_max = KV_max_ptr;
|
||||
float * GGML_CUDA_RESTRICT dst = dst_ptr;
|
||||
float2 * GGML_CUDA_RESTRICT dst_meta = dst_meta_ptr;
|
||||
GGML_UNUSED(KV_rows_ptr);
|
||||
|
||||
// Skip unused kernel variants for faster compilation:
|
||||
if (use_logit_softcap && !(D == 128 || D == 256)) {
|
||||
@@ -75,9 +75,9 @@ static __global__ void flash_attn_ext_vec(
|
||||
|
||||
#ifdef GGML_USE_HIP
|
||||
#ifdef RDNA
|
||||
constexpr int nthreads_KQ_q = 2;
|
||||
constexpr int nthreads_KQ_q = indexed_bias && type_K == GGML_TYPE_F8_E4M3 ? 16 : 2;
|
||||
#else
|
||||
constexpr int nthreads_KQ_q = 4;
|
||||
constexpr int nthreads_KQ_q = type_K == GGML_TYPE_F8_E4M3 && D == 256 && ncols == 2 ? 16 : 4;
|
||||
#endif // RDNA
|
||||
constexpr int nthreads_V_q = (D/4 < 32 ? D/4 : 32);
|
||||
#else
|
||||
@@ -107,12 +107,13 @@ static __global__ void flash_attn_ext_vec(
|
||||
|
||||
const int sequence = blockIdx.z / ne02;
|
||||
const int head = blockIdx.z - sequence*ne02;
|
||||
const fattn_indexed_bias head_bias = indexed_bias ? bias.for_head(int64_t(sequence)*ne01.z, head) : bias;
|
||||
const int gqa_ratio = ne02 / ne12; // With grouped query attention there are > 1 Q matrices per K, V matrix.
|
||||
Q += s03*sequence + s02* head + s01*ic0;
|
||||
K += s13*sequence + s12*(head / gqa_ratio);
|
||||
V += s23*sequence + s22*(head / gqa_ratio);
|
||||
|
||||
const half * maskh = mask ? mask + s33*(sequence % ne33) + s32*(head % ne32) + s31*ic0 : nullptr;
|
||||
const half * maskh = indexed_bias || mask ? mask + s33*(sequence % ne33) + s32*(head % ne32) + s31*ic0 : nullptr;
|
||||
|
||||
const float slope = get_alibi_slope(max_bias, head, n_head_log2, m0, m1);
|
||||
|
||||
@@ -271,12 +272,15 @@ static __global__ void flash_attn_ext_vec(
|
||||
}
|
||||
|
||||
const int k_VKQ_max = KV_max ? KV_max[sequence*gridDim.x + blockIdx.x] : ne11;
|
||||
K += blockIdx.y*nthreads * s11;
|
||||
V += blockIdx.y*nthreads * s21;
|
||||
const int32_t * rows = use_kv_rows ? KV_rows_ptr + int64_t(sequence)*ne11 : nullptr;
|
||||
if constexpr (!use_kv_rows) {
|
||||
K += blockIdx.y*nthreads * s11;
|
||||
V += blockIdx.y*nthreads * s21;
|
||||
}
|
||||
maskh += blockIdx.y*nthreads;
|
||||
for (int k_VKQ_0 = blockIdx.y*nthreads; k_VKQ_0 < k_VKQ_max; k_VKQ_0 += gridDim.y*nthreads,
|
||||
// Increment pointers after each loop:
|
||||
K += gridDim.y*nthreads*s11, V += gridDim.y*nthreads*s21, maskh += gridDim.y*nthreads) {
|
||||
K += use_kv_rows ? 0 : gridDim.y*nthreads*s11, V += use_kv_rows ? 0 : gridDim.y*nthreads*s21, maskh += gridDim.y*nthreads) {
|
||||
|
||||
// Calculate KQ tile and keep track of new maximum KQ values:
|
||||
float KQ_reg[ncols]; // KQ in registers.
|
||||
@@ -290,21 +294,24 @@ static __global__ void flash_attn_ext_vec(
|
||||
#pragma unroll
|
||||
for (int i_KQ_0 = 0; i_KQ_0 < nthreads_KQ; ++i_KQ_0) {
|
||||
const int i_KQ = threadIdx.y*WARP_SIZE + (nthreads_KQ == WARP_SIZE ? 0 : (threadIdx.x & ~(nthreads_KQ-1))) + i_KQ_0;
|
||||
const char * K_row = use_kv_rows ? K + int64_t(max(rows[k_VKQ_0 + i_KQ], 0))*s11 : K + i_KQ*s11;
|
||||
|
||||
#pragma unroll
|
||||
for (int j = 0; j < ncols; ++j) {
|
||||
float sum = vec_dot_KQ(K + i_KQ*s11, Q_reg[j], Q_i32[j], Q_ds[j]);
|
||||
float sum = vec_dot_KQ(K_row, Q_reg[j], Q_i32[j], Q_ds[j]);
|
||||
sum = warp_reduce_sum<nthreads_KQ>(sum);
|
||||
|
||||
if (use_logit_softcap) {
|
||||
sum = logit_softcap*tanhf(sum);
|
||||
}
|
||||
|
||||
if (mask && (ncols == 1 || ic0 + j < int(ne01.z))) {
|
||||
sum += slope*__half2float(maskh[j*ne11 + i_KQ]);
|
||||
}
|
||||
if constexpr (!indexed_bias) {
|
||||
if (mask && (ncols == 1 || ic0 + j < int(ne01.z))) {
|
||||
sum += slope*__half2float(maskh[j*ne11 + i_KQ]);
|
||||
}
|
||||
|
||||
KQ_max_new[j] = fmaxf(KQ_max_new[j], sum + FATTN_KQ_MAX_OFFSET);
|
||||
KQ_max_new[j] = fmaxf(KQ_max_new[j], sum + FATTN_KQ_MAX_OFFSET);
|
||||
}
|
||||
|
||||
if ((nthreads_KQ == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_KQ) == uint32_t(i_KQ_0)) {
|
||||
KQ_reg[j] = sum;
|
||||
@@ -314,8 +321,14 @@ static __global__ void flash_attn_ext_vec(
|
||||
|
||||
#pragma unroll
|
||||
for (int j = 0; j < ncols; ++j) {
|
||||
if constexpr (indexed_bias) {
|
||||
const int k = k_VKQ_0 + tid;
|
||||
const float m = head_bias.add(__half2float(maskh[j*ne11 + tid]), ic0 + j, k);
|
||||
KQ_reg[j] += slope*m;
|
||||
KQ_max_new[j] = fmaxf(KQ_max[j], KQ_reg[j] + FATTN_KQ_MAX_OFFSET);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int offset = nthreads_KQ; offset < WARP_SIZE; offset <<= 1) {
|
||||
for (int offset = indexed_bias ? 1 : nthreads_KQ; offset < WARP_SIZE; offset <<= 1) {
|
||||
KQ_max_new[j] = fmaxf(KQ_max_new[j], ggml_cuda_shfl_xor(KQ_max_new[j], offset, WARP_SIZE));
|
||||
}
|
||||
const float KQ_max_scale = expf(KQ_max[j] - KQ_max_new[j]);
|
||||
@@ -345,6 +358,7 @@ static __global__ void flash_attn_ext_vec(
|
||||
#pragma unroll
|
||||
for (int k0 = 0; k0 < WARP_SIZE; k0 += V_cols_per_iter) {
|
||||
const int k = threadIdx.y*WARP_SIZE + k0 + (nthreads_V == WARP_SIZE ? 0 : threadIdx.x / nthreads_V);
|
||||
const char * V_row = V + (use_kv_rows ? int64_t(max(rows[k_VKQ_0 + k], 0))*s21 : k*s21);
|
||||
|
||||
#ifdef V_DOT2_F32_F16_AVAILABLE
|
||||
half2 KQ_k[ncols];
|
||||
@@ -357,14 +371,14 @@ static __global__ void flash_attn_ext_vec(
|
||||
half2 tmp[V_rows_per_thread/2];
|
||||
if constexpr (type_V == GGML_TYPE_BF16) {
|
||||
float2 tmp_f[V_rows_per_thread/2];
|
||||
dequantize_V(V + k*s21, tmp_f,
|
||||
dequantize_V(V_row, tmp_f,
|
||||
2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread);
|
||||
#pragma unroll
|
||||
for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) {
|
||||
tmp[i_VKQ_1] = __float22half2_rn(tmp_f[i_VKQ_1]);
|
||||
}
|
||||
} else {
|
||||
dequantize_V(V + k*s21, tmp,
|
||||
dequantize_V(V_row, tmp,
|
||||
2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread);
|
||||
}
|
||||
#pragma unroll
|
||||
@@ -384,7 +398,7 @@ static __global__ void flash_attn_ext_vec(
|
||||
#pragma unroll
|
||||
for (int i_VKQ_0 = 0; i_VKQ_0 < D/2; i_VKQ_0 += nthreads_V*V_rows_per_thread/2) {
|
||||
float2 tmp[V_rows_per_thread/2];
|
||||
dequantize_V(V + k*s21, tmp,
|
||||
dequantize_V(V_row, tmp,
|
||||
2*i_VKQ_0 + (nthreads_V == WARP_SIZE ? threadIdx.x : threadIdx.x % nthreads_V)*V_rows_per_thread);
|
||||
#pragma unroll
|
||||
for (int i_VKQ_1 = 0; i_VKQ_1 < V_rows_per_thread/2; ++i_VKQ_1) {
|
||||
@@ -521,7 +535,7 @@ static __global__ void flash_attn_ext_vec(
|
||||
}
|
||||
}
|
||||
if (gridDim.y == 1) {
|
||||
dst_val /= KQ_sum[j_VKQ];
|
||||
dst_val = fattn_normalize(dst_val, KQ_sum[j_VKQ]);
|
||||
}
|
||||
dst[(((sequence*int(ne01.z) + ic0 + j_VKQ)*ne02 + head)*gridDim.y + blockIdx.y)*D + i0 + tid] = dst_val;
|
||||
}
|
||||
@@ -545,7 +559,7 @@ static __global__ void flash_attn_ext_vec(
|
||||
s11, s12, s13,
|
||||
s21, s22, s23,
|
||||
ne31, ne32, ne33,
|
||||
s31, s32, s33);
|
||||
s31, s32, s33, bias);
|
||||
NO_DEVICE_CODE;
|
||||
#endif // FLASH_ATTN_AVAILABLE
|
||||
}
|
||||
@@ -559,7 +573,13 @@ void ggml_cuda_flash_attn_ext_vec_case_impl(ggml_backend_cuda_context & ctx, ggm
|
||||
|
||||
const int nthreads = ggml_cuda_fattn_vec_get_nthreads_host(cc);
|
||||
const int nwarps = nthreads / WARP_SIZE;
|
||||
fattn_kernel_t fattn_kernel = flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap>;
|
||||
fattn_kernel_t fattn_kernel = flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap, false, false>;
|
||||
if constexpr (cols_per_block == 1 && (D == 64 || D == 128) && !use_logit_softcap) {
|
||||
if (ggml_flash_attn_ext_has_indexed_bias(dst)) {
|
||||
fattn_kernel = dst->src[5] ? flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap, true, true>
|
||||
: flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap, true, false>;
|
||||
}
|
||||
}
|
||||
const bool need_f16_K = type_K == GGML_TYPE_F16;
|
||||
const bool need_f16_V = type_V == GGML_TYPE_F16;
|
||||
constexpr size_t nbytes_shared = 0;
|
||||
|
||||
@@ -599,10 +599,6 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
|
||||
return BEST_FATTN_KERNEL_NONE;
|
||||
#endif// FLASH_ATTN_AVAILABLE
|
||||
|
||||
if (ggml_flash_attn_ext_has_indexed_bias(dst)) {
|
||||
return BEST_FATTN_KERNEL_NONE;
|
||||
}
|
||||
|
||||
const ggml_tensor * KQV = dst;
|
||||
const ggml_tensor * Q = dst->src[0];
|
||||
const ggml_tensor * K = dst->src[1];
|
||||
@@ -610,6 +606,10 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
|
||||
const ggml_tensor * mask = dst->src[3];
|
||||
const ggml_tensor * kv_rows = dst->src[5];
|
||||
|
||||
if (!ggml_validate_flash_attn_ext_indexed_bias(dst)) {
|
||||
return BEST_FATTN_KERNEL_NONE;
|
||||
}
|
||||
|
||||
// with kv_rows the kernel iterates over the mask columns
|
||||
const int64_t n_kv = kv_rows ? kv_rows->ne[0] : K->ne[1];
|
||||
|
||||
@@ -690,6 +690,20 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
|
||||
return BEST_FATTN_KERNEL_NONE;
|
||||
}
|
||||
|
||||
// the tile and vec kernels implement the indexed bias, the mma kernel does not
|
||||
if (ggml_flash_attn_ext_has_indexed_bias(dst)) {
|
||||
float logit_softcap;
|
||||
memcpy(&logit_softcap, (const float *) KQV->op_params + 2, sizeof(float));
|
||||
if (Q->ne[0] != 128 && !(Q->ne[0] == 64 && logit_softcap == 0.0f)) {
|
||||
return BEST_FATTN_KERNEL_NONE;
|
||||
}
|
||||
if (logit_softcap == 0.0f && Q->ne[1] == 1 && n_kv % FATTN_KQ_STRIDE == 0 &&
|
||||
ggml_cuda_get_fattn_vec_case(Q->ne[0], K->type, V->type)) {
|
||||
return BEST_FATTN_KERNEL_VEC;
|
||||
}
|
||||
return BEST_FATTN_KERNEL_TILE;
|
||||
}
|
||||
|
||||
if (mask && mask->ne[2] != 1) {
|
||||
// the kv_rows mask is compacted per sequence, it has no head dimension
|
||||
if (kv_rows) {
|
||||
@@ -703,7 +717,7 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
|
||||
}
|
||||
}
|
||||
|
||||
// only the MMA kernel reads K/V through kv_rows
|
||||
// without a bias only the MMA kernel reads K/V through kv_rows
|
||||
if (kv_rows) {
|
||||
return GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc) && mask && Q->ne[0] != 40 && Q->ne[0] != 72 ?
|
||||
BEST_FATTN_KERNEL_MMA_F16 : BEST_FATTN_KERNEL_NONE;
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "dsv4-hc.cuh"
|
||||
#include "fp8.cuh"
|
||||
#include "gated_delta_net.cuh"
|
||||
#include "inkling2.cuh"
|
||||
#include "mmq.cuh"
|
||||
#include "mmq-few.cuh"
|
||||
#include "mmvf.cuh"
|
||||
@@ -1385,8 +1386,615 @@ static bool ggml_cuda_can_fuse(const struct ggml_cgraph * cgraph,
|
||||
return false;
|
||||
}
|
||||
|
||||
// fused op chains of the Inkling 2 graph (inkling2.cuh, ggml_cuda_op_l2_clip)
|
||||
|
||||
static bool ggml_cuda_tensors_overlap(const ggml_tensor * a, const ggml_tensor * b) {
|
||||
const char * a0 = (const char *) a->data;
|
||||
const char * b0 = (const char *) b->data;
|
||||
const char * a1 = a0 + ggml_backend_buft_get_alloc_size(a->buffer->buft, a);
|
||||
const char * b1 = b0 + ggml_backend_buft_get_alloc_size(b->buffer->buft, b);
|
||||
return a0 < b1 && b0 < a1;
|
||||
}
|
||||
|
||||
// a dimension of src broadcasts to dst if it is 1 or equal
|
||||
static bool ggml_cuda_can_bcast_to(const ggml_tensor * src, const ggml_tensor * dst, int first_dim) {
|
||||
for (int d = first_dim; d < GGML_MAX_DIMS; ++d) {
|
||||
if (src->ne[d] != 1 && src->ne[d] != dst->ne[d]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// [MUL by a per-column weight] -> L2_NORM -> SCALE [-> MUL by a per-channel/sample factor]
|
||||
static int ggml_cuda_try_fuse_l2_clip(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) {
|
||||
const ggml_tensor * node = cgraph->nodes[i];
|
||||
const bool has_w = node->op == GGML_OP_MUL;
|
||||
if (!has_w && node->op != GGML_OP_L2_NORM) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const ggml_tensor * x = node->src[0];
|
||||
const ggml_tensor * w = has_w ? node->src[1] : nullptr;
|
||||
if (x->type != GGML_TYPE_F32 || x->nb[0] != sizeof(float)) {
|
||||
return 0;
|
||||
}
|
||||
if (has_w && (!ggml_are_same_shape(x, node) || w->type != GGML_TYPE_F32 || w->nb[0] != sizeof(float) ||
|
||||
w->ne[0] != x->ne[0] || !ggml_cuda_can_bcast_to(w, x, 1))) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
for (const bool has_f : { true, false }) {
|
||||
ggml_op ops[4];
|
||||
int n = 0;
|
||||
if (has_w) {
|
||||
ops[n++] = GGML_OP_MUL;
|
||||
}
|
||||
ops[n++] = GGML_OP_L2_NORM;
|
||||
ops[n++] = GGML_OP_SCALE;
|
||||
if (has_f) {
|
||||
ops[n++] = GGML_OP_MUL;
|
||||
}
|
||||
|
||||
if (!ggml_can_fuse(cgraph, i, ops, n)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const ggml_tensor * l2 = cgraph->nodes[i + n - (has_f ? 3 : 2)];
|
||||
const ggml_tensor * sc = cgraph->nodes[i + n - (has_f ? 2 : 1)];
|
||||
ggml_tensor * dst = cgraph->nodes[i + n - 1];
|
||||
const ggml_tensor * f = nullptr;
|
||||
|
||||
if (l2->type != GGML_TYPE_F32 || sc->type != GGML_TYPE_F32 || sc->src[0] != l2 || (has_w && l2->src[0] != node) ||
|
||||
!ggml_is_contiguous(dst)) {
|
||||
continue;
|
||||
}
|
||||
if (has_f) {
|
||||
f = dst->src[1];
|
||||
if (dst->src[0] != sc || f->type != GGML_TYPE_F32 || f->ne[0] != 1 || f->ne[1] != 1 || !ggml_cuda_can_bcast_to(f, dst, 2)) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// a block reads its row before it writes it, so dst may be x itself but must not overlap it otherwise
|
||||
const bool x_in_place = x->data == dst->data && ggml_is_contiguous(x);
|
||||
if ((!x_in_place && ggml_cuda_tensors_overlap(x, dst)) || (w && ggml_cuda_tensors_overlap(w, dst)) ||
|
||||
(f && ggml_cuda_tensors_overlap(f, dst))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
ggml_cuda_op_l2_clip(*cuda_ctx, x, w, l2, sc, f, dst);
|
||||
return n - 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
// situ on the halves of a merged gate_up: SCALE -> TANH -> SCALE, SIGMOID, MUL, (up view) SCALE -> TANH -> SCALE, MUL
|
||||
static int ggml_cuda_try_fuse_situ(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) {
|
||||
static constexpr ggml_op ops[] = {
|
||||
GGML_OP_SCALE, GGML_OP_UNARY, GGML_OP_SCALE, GGML_OP_UNARY, GGML_OP_MUL, GGML_OP_VIEW,
|
||||
GGML_OP_SCALE, GGML_OP_UNARY, GGML_OP_SCALE, GGML_OP_MUL,
|
||||
};
|
||||
constexpr int n = sizeof(ops)/sizeof(ops[0]);
|
||||
|
||||
if (i + n > cgraph->n_nodes) {
|
||||
return 0;
|
||||
}
|
||||
for (int k = 0; k < n; ++k) {
|
||||
if (cgraph->nodes[i + k]->op != ops[k]) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
ggml_tensor ** nd = cgraph->nodes + i;
|
||||
|
||||
const ggml_tensor * gate = nd[0]->src[0];
|
||||
const ggml_tensor * up = nd[5];
|
||||
|
||||
const auto is_mul_of = [](const ggml_tensor * t, const ggml_tensor * a, const ggml_tensor * b) {
|
||||
return (t->src[0] == a && t->src[1] == b) || (t->src[0] == b && t->src[1] == a);
|
||||
};
|
||||
|
||||
if (ggml_get_unary_op(nd[1]) != GGML_UNARY_OP_TANH || ggml_get_unary_op(nd[3]) != GGML_UNARY_OP_SIGMOID ||
|
||||
ggml_get_unary_op(nd[7]) != GGML_UNARY_OP_TANH ||
|
||||
nd[1]->src[0] != nd[0] || nd[2]->src[0] != nd[1] || nd[3]->src[0] != gate || !is_mul_of(nd[4], nd[2], nd[3]) ||
|
||||
nd[6]->src[0] != up || nd[7]->src[0] != nd[6] || nd[8]->src[0] != nd[7] || !is_mul_of(nd[9], nd[4], nd[8])) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (gate->type != GGML_TYPE_F32 || up->type != GGML_TYPE_F32 || gate->nb[0] != sizeof(float) || up->nb[0] != sizeof(float) ||
|
||||
!ggml_are_same_shape(gate, up) || !ggml_are_same_shape(gate, nd[9]) || !ggml_is_contiguous(nd[9])) {
|
||||
return 0;
|
||||
}
|
||||
for (int k = 0; k < n; ++k) {
|
||||
if (nd[k]->type != GGML_TYPE_F32) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// the up view is a view of a node outside the group, it is not part of the subgraph check
|
||||
const int idxs[] = { i, i + 1, i + 2, i + 3, i + 4, i + 6, i + 7, i + 8, i + 9 };
|
||||
const ggml_op ops_ext[] = { ops[0], ops[1], ops[2], ops[3], ops[4], ops[6], ops[7], ops[8], ops[9] };
|
||||
const int out = i + n - 1;
|
||||
if (!ggml_can_fuse_subgraph_ext(cgraph, idxs, 9, ops_ext, &out, 1) || !ggml_cuda_check_fusion_memory_ranges(cgraph, i, n, &out, 1)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const float s[4] = {
|
||||
ggml_get_op_params_f32(nd[0], 0), ggml_get_op_params_f32(nd[2], 0), ggml_get_op_params_f32(nd[6], 0), ggml_get_op_params_f32(nd[8], 0),
|
||||
};
|
||||
const float b[4] = {
|
||||
ggml_get_op_params_f32(nd[0], 1), ggml_get_op_params_f32(nd[2], 1), ggml_get_op_params_f32(nd[6], 1), ggml_get_op_params_f32(nd[8], 1),
|
||||
};
|
||||
|
||||
ggml_cuda_op_situ(*cuda_ctx, gate, up, s, b, nd[9]);
|
||||
return n - 1;
|
||||
}
|
||||
|
||||
// depth mix: [RMS_NORM(cur)] -> CONCAT(stack, norm) -> [REPEAT(query)] -> MUL_MAT -> SOFT_MAX, TRANSPOSE -> CONT -> MUL_MAT
|
||||
static int ggml_cuda_try_fuse_depth_mix(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) {
|
||||
const ggml_tensor * node = cgraph->nodes[i];
|
||||
const bool has_norm = node->op == GGML_OP_RMS_NORM;
|
||||
|
||||
const int j = i + (has_norm ? 1 : 0);
|
||||
if (j + 1 >= cgraph->n_nodes) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const ggml_tensor * cc = cgraph->nodes[j];
|
||||
if (cc->op != GGML_OP_CONCAT || ggml_get_op_params_i32(cc, 0) != 1 || (has_norm && cc->src[1] != node) ||
|
||||
(!has_norm && cc->src[1]->op != GGML_OP_RMS_NORM)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const bool has_rep = cgraph->nodes[j + 1]->op == GGML_OP_REPEAT;
|
||||
|
||||
ggml_op ops[8];
|
||||
int n = 0;
|
||||
if (has_norm) {
|
||||
ops[n++] = GGML_OP_RMS_NORM;
|
||||
}
|
||||
ops[n++] = GGML_OP_CONCAT;
|
||||
if (has_rep) {
|
||||
ops[n++] = GGML_OP_REPEAT;
|
||||
}
|
||||
ops[n++] = GGML_OP_MUL_MAT;
|
||||
ops[n++] = GGML_OP_SOFT_MAX;
|
||||
ops[n++] = GGML_OP_TRANSPOSE;
|
||||
ops[n++] = GGML_OP_CONT;
|
||||
ops[n++] = GGML_OP_MUL_MAT;
|
||||
|
||||
if (i + n > cgraph->n_nodes) {
|
||||
return 0;
|
||||
}
|
||||
for (int k = 0; k < n; ++k) {
|
||||
if (cgraph->nodes[i + k]->op != ops[k]) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
const ggml_tensor * rep = has_rep ? cgraph->nodes[j + 1] : nullptr;
|
||||
const ggml_tensor * mm1 = cgraph->nodes[i + n - 5];
|
||||
const ggml_tensor * sm = cgraph->nodes[i + n - 4];
|
||||
const ggml_tensor * tr = cgraph->nodes[i + n - 3];
|
||||
const ggml_tensor * ct = cgraph->nodes[i + n - 2];
|
||||
ggml_tensor * mm2 = cgraph->nodes[i + n - 1];
|
||||
|
||||
const ggml_tensor * stack = cc->src[0];
|
||||
const ggml_tensor * cur = has_norm ? node->src[0] : cc->src[1];
|
||||
const ggml_tensor * query = has_rep ? rep->src[0] : mm1->src[1];
|
||||
|
||||
if (mm1->src[0] != cc || mm1->src[1] != (has_rep ? rep : query) || sm->src[0] != mm1 || sm->src[1] || sm->src[2] ||
|
||||
ggml_get_op_params_f32(sm, 1) != 0.0f || tr->src[0] != cc || ct->src[0] != tr || mm2->src[0] != sm || mm2->src[1] != ct) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const int64_t ne = cur->ne[0];
|
||||
const int64_t T = cur->ne[2];
|
||||
const int64_t B = stack->ne[1];
|
||||
const int64_t Q = query->ne[1];
|
||||
|
||||
for (const ggml_tensor * t : std::initializer_list<const ggml_tensor *>{ stack, cur, query, cc, mm1, sm, mm2 }) {
|
||||
if (t->type != GGML_TYPE_F32) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
if (cur->nb[0] != sizeof(float) || cur->ne[1] != 1 || cur->ne[3] != 1 || !ggml_is_contiguous(stack) ||
|
||||
stack->ne[0] != ne || stack->ne[2] != T || stack->ne[3] != 1 || B < 1 || B > GGML_CUDA_DEPTH_MIX_MAX_ROWS ||
|
||||
!ggml_is_contiguous(query) || query->ne[0] != ne || query->ne[2] != 1 || query->ne[3] != 1 || (!has_rep && T != 1) ||
|
||||
mm2->ne[0] != Q || mm2->ne[1] != ne || mm2->ne[2] != T || !ggml_is_contiguous(mm2)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const int out = i + n - 1;
|
||||
if (!ggml_can_fuse_subgraph(cgraph, i, n, ops, &out, 1) || !ggml_cuda_check_fusion_memory_ranges(cgraph, i, n, &out, 1)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const float eps = has_norm ? ggml_get_op_params_f32(node, 0) : 0.0f;
|
||||
ggml_cuda_op_depth_mix(*cuda_ctx, stack, cur, has_norm, eps, query, ggml_get_op_params_f32(sm, 0), mm2);
|
||||
return n - 1;
|
||||
}
|
||||
|
||||
// loop controller: CONCAT(cur, msg) -> RMS_NORM -> RESHAPE -> MUL_MAT(down) -> MUL_MAT(forget) -> TANH -> MUL(cur) -> SUB(cur),
|
||||
// MUL_MAT(gain) -> TANH -> MUL(msg) -> ADD
|
||||
static int ggml_cuda_try_fuse_loop_ctrl(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) {
|
||||
static constexpr ggml_op ops[] = {
|
||||
GGML_OP_CONCAT, GGML_OP_RMS_NORM, GGML_OP_RESHAPE, GGML_OP_MUL_MAT, GGML_OP_MUL_MAT, GGML_OP_UNARY, GGML_OP_MUL, GGML_OP_SUB,
|
||||
GGML_OP_MUL_MAT, GGML_OP_UNARY, GGML_OP_MUL, GGML_OP_ADD,
|
||||
};
|
||||
constexpr int n = sizeof(ops)/sizeof(ops[0]);
|
||||
|
||||
if (i + n > cgraph->n_nodes) {
|
||||
return 0;
|
||||
}
|
||||
for (int k = 0; k < n; ++k) {
|
||||
if (cgraph->nodes[i + k]->op != ops[k]) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
ggml_tensor ** nd = cgraph->nodes + i;
|
||||
|
||||
const ggml_tensor * cc = nd[0];
|
||||
if (ggml_get_op_params_i32(cc, 0) != 1 || cc->src[0]->op != GGML_OP_RESHAPE || cc->src[1]->op != GGML_OP_RESHAPE) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const ggml_tensor * cur = cc->src[0]->src[0];
|
||||
const ggml_tensor * msg = cc->src[1]->src[0];
|
||||
const ggml_tensor * down = nd[3];
|
||||
const ggml_tensor * wd = down->src[0];
|
||||
const ggml_tensor * wf = nd[4]->src[0];
|
||||
const ggml_tensor * wg = nd[8]->src[0];
|
||||
ggml_tensor * dst = nd[11];
|
||||
|
||||
if (nd[1]->src[0] != cc || nd[2]->src[0] != nd[1] || down->src[1] != nd[2] || nd[4]->src[1] != down ||
|
||||
ggml_get_unary_op(nd[5]) != GGML_UNARY_OP_TANH || nd[5]->src[0] != nd[4] ||
|
||||
nd[6]->src[0] != nd[5] || nd[6]->src[1] != cur || nd[7]->src[0] != cur || nd[7]->src[1] != nd[6] ||
|
||||
nd[8]->src[1] != down || ggml_get_unary_op(nd[9]) != GGML_UNARY_OP_TANH || nd[9]->src[0] != nd[8] ||
|
||||
nd[10]->src[0] != nd[9] || nd[10]->src[1] != msg || dst->src[0] != nd[7] || dst->src[1] != nd[10]) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const int64_t ne = cur->ne[0];
|
||||
const int64_t T = cur->ne[1];
|
||||
const int64_t rank = wd->ne[1];
|
||||
|
||||
if (T > GGML_CUDA_LOOP_CTRL_MAX_TOKENS || !ggml_is_contiguous(cur) || !ggml_is_contiguous(msg) || !ggml_are_same_shape(cur, msg) ||
|
||||
cur->ne[2] != 1 || cur->ne[3] != 1 || !ggml_are_same_shape(cur, dst) || !ggml_is_contiguous(dst) ||
|
||||
!ggml_is_contiguous(down) || down->ne[0] != rank || down->ne[1] != T) {
|
||||
return 0;
|
||||
}
|
||||
for (const ggml_tensor * t : std::initializer_list<const ggml_tensor *>{ cur, msg, wd, wf, wg, down, dst }) {
|
||||
if (t->type != GGML_TYPE_F32) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
for (const ggml_tensor * w : { wd, wf, wg }) {
|
||||
if (!ggml_is_contiguous(w) || w->ne[2] != 1 || w->ne[3] != 1) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
if (wd->ne[0] != 2*ne || wf->ne[0] != rank || wg->ne[0] != rank || wf->ne[1] != ne || wg->ne[1] != ne) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// the down product is written by the first kernel and read by the second, so the output must not overlap it
|
||||
const int outs[] = { i + 3, i + n - 1 };
|
||||
if (!ggml_can_fuse_subgraph(cgraph, i, n, ops, outs, 2) || !ggml_cuda_check_fusion_memory_ranges(cgraph, i, n, outs, 2) ||
|
||||
ggml_cuda_tensors_overlap(dst, down)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
ggml_cuda_op_loop_ctrl(*cuda_ctx, cur, msg, ggml_get_op_params_f32(nd[1], 0), wd, wg, wf, nd[3], dst);
|
||||
return n - 1;
|
||||
}
|
||||
|
||||
// short conv: CONCAT(past, cur^T) -> the state store -> SSM_CONV -> RESHAPE -> [taps] -> ADD(cur) -> SCALE [-> ADD]
|
||||
// each tap: VIEW(x) -> TRANSPOSE -> CONT -> RESHAPE, [RESHAPE(dyn)], VIEW(dyn) -> MUL -> RESHAPE -> ADD
|
||||
static int ggml_cuda_try_fuse_short_conv(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) {
|
||||
// the subgraph nodes: 5 for the concat, state store and conv, 7 per tap, 3 for the adds and the scale
|
||||
constexpr int MAX_NODES = 8 + 7*GGML_CUDA_SHORT_CONV_MAX_K;
|
||||
|
||||
const ggml_tensor * cc = cgraph->nodes[i];
|
||||
if (cc->op != GGML_OP_CONCAT || ggml_get_op_params_i32(cc, 0) != 0 || i + 8 > cgraph->n_nodes) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const ggml_tensor * past = cc->src[0];
|
||||
const ggml_tensor * xin = cc->src[1];
|
||||
|
||||
if (cc->type != GGML_TYPE_F32 || past->type != GGML_TYPE_F32 || past->nb[0] != sizeof(float) || cc->ne[3] != 1 ||
|
||||
!ggml_is_contiguous(cc) || xin->op != GGML_OP_TRANSPOSE || xin->src[0]->op != GGML_OP_RESHAPE) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const int64_t K1 = past->ne[0];
|
||||
const int64_t C = cc->ne[1];
|
||||
const int64_t S = cc->ne[2];
|
||||
const int64_t Ts = cc->ne[0] - K1;
|
||||
const int64_t K = K1 + 1;
|
||||
|
||||
const ggml_tensor * cur = xin->src[0]->src[0];
|
||||
if (K < 2 || K > GGML_CUDA_SHORT_CONV_MAX_K || Ts < 1 || past->ne[1] != C || past->ne[2] != S || xin->ne[0] != Ts ||
|
||||
cur->type != GGML_TYPE_F32 || !ggml_is_contiguous(cur) || cur->ne[0] != C || ggml_nelements(cur) != C*Ts*S) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
int idxs[MAX_NODES];
|
||||
ggml_op ops[MAX_NODES];
|
||||
int n_sub = 0;
|
||||
auto add_node = [&](int k) {
|
||||
idxs[n_sub] = k;
|
||||
ops[n_sub] = cgraph->nodes[k]->op;
|
||||
n_sub++;
|
||||
};
|
||||
|
||||
int k = i;
|
||||
add_node(k++);
|
||||
|
||||
// the state store: the last K - 1 columns of x copied to the cell of each sequence (VIEW, VIEW, CPY), or with rollback
|
||||
// slots the windows that end at the last kw tokens set into slots kw - 1 .. 0 (VIEW, ARANGE, SCALE, CPY, VIEW, VIEW, SET_ROWS)
|
||||
const ggml_tensor * cell = nullptr;
|
||||
int st_idx = -1;
|
||||
int64_t kw = 1;
|
||||
int64_t slot_s = 0;
|
||||
int64_t ch_s = K1;
|
||||
int64_t seq_s = 0;
|
||||
if (cgraph->nodes[k + 1]->op == GGML_OP_ARANGE) {
|
||||
if (k + 7 > cgraph->n_nodes) {
|
||||
return 0;
|
||||
}
|
||||
const ggml_tensor * win = cgraph->nodes[k];
|
||||
const ggml_tensor * ar = cgraph->nodes[k + 1];
|
||||
const ggml_tensor * sb = cgraph->nodes[k + 2];
|
||||
const ggml_tensor * cs = cgraph->nodes[k + 3];
|
||||
const ggml_tensor * ord = cgraph->nodes[k + 4];
|
||||
const ggml_tensor * sl = cgraph->nodes[k + 5];
|
||||
const ggml_tensor * sr = cgraph->nodes[k + 6];
|
||||
|
||||
const int64_t n_slots = ar->ne[0];
|
||||
kw = ord->ne[0];
|
||||
|
||||
// the slot order {n_slots - 1, ..., 0}, its last kw entries
|
||||
if (win->op != GGML_OP_VIEW || sb->op != GGML_OP_SCALE || cs->op != GGML_OP_CPY || ord->op != GGML_OP_VIEW ||
|
||||
sl->op != GGML_OP_VIEW || sr->op != GGML_OP_SET_ROWS ||
|
||||
ggml_get_op_params_f32(ar, 0) != 0.0f || ggml_get_op_params_f32(ar, 2) != 1.0f || sb->src[0] != ar ||
|
||||
ggml_get_op_params_f32(sb, 0) != -1.0f || ggml_get_op_params_f32(sb, 1) != (float) (n_slots - 1) ||
|
||||
cs->src[0] != sb || cs->type != GGML_TYPE_I32 || ord->view_src != cs ||
|
||||
ord->view_offs != (size_t) (n_slots - kw)*sizeof(int32_t) || kw < 1 || kw > n_slots || kw > Ts) {
|
||||
return 0;
|
||||
}
|
||||
// window w is x[Ts - (kw - 1) + w, +K - 1) of each channel
|
||||
if (win->view_src != cc || win->ne[0] != K1 || win->ne[1] != kw || win->ne[2] != C || win->ne[3] != S ||
|
||||
win->nb[0] != sizeof(float) || win->nb[1] != sizeof(float) || win->nb[2] != cc->nb[1] || win->nb[3] != cc->nb[2] ||
|
||||
win->view_offs != (size_t) (Ts - (kw - 1))*sizeof(float)) {
|
||||
return 0;
|
||||
}
|
||||
// SET_ROWS: src[0] the rows, src[1] the indices, src[2] the destination
|
||||
if (sr->src[0] != win || sr->src[1] != ord || sr->src[2] != sl || sl->type != GGML_TYPE_F32 || sl->nb[0] != sizeof(float) ||
|
||||
sl->ne[0] != K1 || sl->ne[1] != n_slots || sl->ne[2] != C || sl->ne[3] != S) {
|
||||
return 0;
|
||||
}
|
||||
// the slot order is a constant the kernel does not need; the cast is its own src[1], so its uses are checked here
|
||||
if (ggml_node_get_use_count(cgraph, k + 1) != 1 || ggml_node_get_use_count(cgraph, k + 2) != 1 ||
|
||||
ggml_node_get_use_count(cgraph, k + 3) != 1 + (cs->src[1] == cs ? 1 : 0) || ggml_node_get_use_count(cgraph, k + 4) != 1) {
|
||||
return 0;
|
||||
}
|
||||
cell = sl;
|
||||
st_idx = k + 6;
|
||||
slot_s = sl->nb[1]/sizeof(float);
|
||||
ch_s = sl->nb[2]/sizeof(float);
|
||||
seq_s = sl->nb[3]/sizeof(float);
|
||||
add_node(k); // windows
|
||||
add_node(k + 6); // set_rows, the slots are a view of the state outside the group
|
||||
k += 7;
|
||||
} else {
|
||||
const ggml_tensor * tail = cgraph->nodes[k];
|
||||
const ggml_tensor * cpy = cgraph->nodes[k + 2];
|
||||
cell = cgraph->nodes[k + 1];
|
||||
if (tail->op != GGML_OP_VIEW || cell->op != GGML_OP_VIEW || cpy->op != GGML_OP_CPY ||
|
||||
tail->view_src != cc || tail->view_offs != (size_t) Ts*sizeof(float) || tail->ne[0] != K1 || tail->ne[1] != C ||
|
||||
tail->ne[2] != S || tail->nb[1] != cc->nb[1] || tail->nb[2] != cc->nb[2] || cpy->src[0] != tail || cpy->src[1] != cell ||
|
||||
cell->type != GGML_TYPE_F32 || cell->nb[0] != sizeof(float) || cell->ne[0] != K1*C || ggml_nrows(cell) != S ||
|
||||
ggml_get_op_params_i32(cpy, 0) != 0) {
|
||||
return 0;
|
||||
}
|
||||
st_idx = k + 2;
|
||||
seq_s = cell->nb[1]/sizeof(float);
|
||||
add_node(k); // tail
|
||||
add_node(k + 2); // cpy, the cell is a view of the state outside the group
|
||||
k += 3;
|
||||
}
|
||||
const int cpy_idx = st_idx;
|
||||
|
||||
if (k + 4 > cgraph->n_nodes) {
|
||||
return 0;
|
||||
}
|
||||
const ggml_tensor * conv = cgraph->nodes[k];
|
||||
const ggml_tensor * w = conv->src[1];
|
||||
const ggml_tensor * out = cgraph->nodes[k + 1];
|
||||
if (conv->op != GGML_OP_SSM_CONV || conv->src[0] != cc || w->type != GGML_TYPE_F32 || !ggml_is_contiguous(w) ||
|
||||
w->ne[0] != K || w->ne[1] != C || out->op != GGML_OP_RESHAPE || out->src[0] != conv || out->ne[0] != C || out->ne[1] != Ts*S) {
|
||||
return 0;
|
||||
}
|
||||
add_node(k);
|
||||
add_node(k + 1);
|
||||
k += 2;
|
||||
|
||||
// the input-dependent taps, one per lag
|
||||
const ggml_tensor * dyn = nullptr;
|
||||
int64_t n_heads = 0;
|
||||
if (cgraph->nodes[k]->op == GGML_OP_VIEW && cgraph->nodes[k]->view_src == cc) {
|
||||
for (int64_t lag = 0; lag < K; ++lag) {
|
||||
if (k + 9 > cgraph->n_nodes) {
|
||||
return 0;
|
||||
}
|
||||
const ggml_tensor * win = cgraph->nodes[k];
|
||||
const ggml_tensor * tr = cgraph->nodes[k + 1];
|
||||
const ggml_tensor * ct = cgraph->nodes[k + 2];
|
||||
const ggml_tensor * wr = cgraph->nodes[k + 3];
|
||||
if (win->op != GGML_OP_VIEW || tr->op != GGML_OP_TRANSPOSE || ct->op != GGML_OP_CONT || wr->op != GGML_OP_RESHAPE ||
|
||||
win->view_src != cc || win->view_offs != (size_t) (K1 - lag)*sizeof(float) || win->ne[0] != Ts || win->ne[1] != C ||
|
||||
win->ne[2] != S || win->nb[1] != cc->nb[1] || win->nb[2] != cc->nb[2] ||
|
||||
tr->src[0] != win || ct->src[0] != tr || wr->src[0] != ct) {
|
||||
return 0;
|
||||
}
|
||||
for (int m = 0; m < 4; ++m) {
|
||||
add_node(k + m);
|
||||
}
|
||||
k += 4;
|
||||
|
||||
if (lag == 0) {
|
||||
const ggml_tensor * d3 = cgraph->nodes[k];
|
||||
if (d3->op != GGML_OP_RESHAPE || d3->ne[0] != K || d3->ne[2] != Ts*S) {
|
||||
return 0;
|
||||
}
|
||||
dyn = d3->src[0];
|
||||
n_heads = d3->ne[1];
|
||||
if (dyn->type != GGML_TYPE_F32 || !ggml_is_contiguous(dyn) || dyn->ne[0] != K*n_heads || n_heads < 1 || C % n_heads != 0) {
|
||||
return 0;
|
||||
}
|
||||
k += 1; // a view of the taps input outside the group
|
||||
}
|
||||
|
||||
const ggml_tensor * tap = cgraph->nodes[k];
|
||||
const ggml_tensor * mul = cgraph->nodes[k + 1];
|
||||
const ggml_tensor * term = cgraph->nodes[k + 2];
|
||||
const ggml_tensor * add = cgraph->nodes[k + 3];
|
||||
if (tap->op != GGML_OP_VIEW || mul->op != GGML_OP_MUL || term->op != GGML_OP_RESHAPE || add->op != GGML_OP_ADD ||
|
||||
tap->view_src != dyn || tap->view_offs != dyn->view_offs + (size_t) lag*sizeof(float) || tap->ne[0] != 1 ||
|
||||
tap->ne[1] != n_heads || tap->nb[1] != dyn->nb[0]*K || tap->nb[2] != dyn->nb[1] ||
|
||||
wr->ne[0] != C/n_heads || wr->ne[1] != n_heads ||
|
||||
mul->src[0] != wr || mul->src[1] != tap || term->src[0] != mul || add->src[0] != out || add->src[1] != term) {
|
||||
return 0;
|
||||
}
|
||||
add_node(k + 1);
|
||||
add_node(k + 2);
|
||||
add_node(k + 3);
|
||||
k += 4;
|
||||
out = add;
|
||||
}
|
||||
}
|
||||
|
||||
if (k + 2 > cgraph->n_nodes) {
|
||||
return 0;
|
||||
}
|
||||
const ggml_tensor * res_add = cgraph->nodes[k];
|
||||
ggml_tensor * sc = cgraph->nodes[k + 1];
|
||||
if (res_add->op != GGML_OP_ADD || sc->op != GGML_OP_SCALE || res_add->src[0] != cur || res_add->src[1] != out ||
|
||||
sc->src[0] != res_add || !ggml_is_contiguous(sc) || sc->type != GGML_TYPE_F32) {
|
||||
return 0;
|
||||
}
|
||||
add_node(k);
|
||||
add_node(k + 1);
|
||||
k += 2;
|
||||
|
||||
// the residual add that follows the attention and FFN output convs
|
||||
ggml_tensor * dst = sc;
|
||||
const ggml_tensor * resid = nullptr;
|
||||
if (k < cgraph->n_nodes && cgraph->nodes[k]->op == GGML_OP_ADD &&
|
||||
(cgraph->nodes[k]->src[0] == sc || cgraph->nodes[k]->src[1] == sc)) {
|
||||
ggml_tensor * add = cgraph->nodes[k];
|
||||
const ggml_tensor * r = add->src[0] == sc ? add->src[1] : add->src[0];
|
||||
if (r != sc && r->type == GGML_TYPE_F32 && ggml_is_contiguous(r) && ggml_are_same_shape(r, sc) &&
|
||||
ggml_is_contiguous(add) && add->type == GGML_TYPE_F32) {
|
||||
int outs[] = { cpy_idx, k };
|
||||
add_node(k);
|
||||
if (ggml_can_fuse_subgraph_ext(cgraph, idxs, n_sub, ops, outs, 2)) {
|
||||
dst = add;
|
||||
resid = r;
|
||||
k += 1;
|
||||
} else {
|
||||
n_sub--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const int n = k - i;
|
||||
const int outs[] = { cpy_idx, k - 1 };
|
||||
if (!ggml_can_fuse_subgraph_ext(cgraph, idxs, n_sub, ops, outs, 2)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// the kernel reads past, cur, w, the taps and the residual and writes the state and dst. a thread reads the residual
|
||||
// and cur at a token right before it writes dst there, so dst may be either of them in place when one thread has
|
||||
// the whole sequence; any other overlap is rejected
|
||||
const bool cur_in_place = cur->data == dst->data;
|
||||
if ((cur_in_place && Ts > 64) || (!cur_in_place && ggml_cuda_tensors_overlap(cur, dst)) ||
|
||||
(resid && resid->data != dst->data && ggml_cuda_tensors_overlap(resid, dst)) ||
|
||||
ggml_cuda_tensors_overlap(cell, dst) || (resid && ggml_cuda_tensors_overlap(resid, cell))) {
|
||||
return 0;
|
||||
}
|
||||
for (const ggml_tensor * t : { cell, (const ggml_tensor *) dst }) {
|
||||
for (const ggml_tensor * src : { past, w, dyn }) {
|
||||
if (src && ggml_cuda_tensors_overlap(t, src)) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ggml_cuda_tensors_overlap(cell, cur)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
ggml_cuda_short_conv_args args = {};
|
||||
args.past = (const float *) past->data;
|
||||
args.past_s1 = past->nb[1]/sizeof(float);
|
||||
args.past_s2 = past->nb[2]/sizeof(float);
|
||||
args.cur = (const float *) cur->data;
|
||||
args.w = (const float *) w->data;
|
||||
args.dyn = dyn ? (const float *) dyn->data : nullptr;
|
||||
args.dyn_s1 = dyn ? dyn->nb[1]/sizeof(float) : 0;
|
||||
args.n_heads = n_heads;
|
||||
args.res = resid ? (const float *) resid->data : nullptr;
|
||||
args.dst = (float *) dst->data;
|
||||
args.state = (float *) cell->data;
|
||||
args.state_slot_s = slot_s;
|
||||
args.state_ch_s = ch_s;
|
||||
args.state_seq_s = seq_s;
|
||||
args.kw = kw;
|
||||
args.run = cur_in_place || Ts <= 8 ? Ts : 1;
|
||||
args.C = C;
|
||||
args.K = K;
|
||||
args.Ts = Ts;
|
||||
args.S = S;
|
||||
args.scale = ggml_get_op_params_f32(sc, 0);
|
||||
args.bias = ggml_get_op_params_f32(sc, 1);
|
||||
|
||||
ggml_cuda_op_short_conv(*cuda_ctx, args);
|
||||
return n - 1;
|
||||
}
|
||||
|
||||
static int ggml_cuda_try_fuse_inkling2(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) {
|
||||
switch (cgraph->nodes[i]->op) {
|
||||
case GGML_OP_CONCAT:
|
||||
if (int n = ggml_cuda_try_fuse_short_conv(cuda_ctx, cgraph, i)) {
|
||||
return n;
|
||||
}
|
||||
if (int n = ggml_cuda_try_fuse_loop_ctrl(cuda_ctx, cgraph, i)) {
|
||||
return n;
|
||||
}
|
||||
return ggml_cuda_try_fuse_depth_mix(cuda_ctx, cgraph, i);
|
||||
case GGML_OP_RMS_NORM:
|
||||
return ggml_cuda_try_fuse_depth_mix(cuda_ctx, cgraph, i);
|
||||
case GGML_OP_MUL:
|
||||
case GGML_OP_L2_NORM:
|
||||
return ggml_cuda_try_fuse_l2_clip(cuda_ctx, cgraph, i);
|
||||
case GGML_OP_SCALE:
|
||||
return ggml_cuda_try_fuse_situ(cuda_ctx, cgraph, i);
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// try and fuse nodes and return the number of nodes to skip
|
||||
int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i) {
|
||||
if (int n = ggml_cuda_try_fuse_inkling2(cuda_ctx, cgraph, i)) {
|
||||
return n;
|
||||
}
|
||||
|
||||
ggml_tensor * node = cgraph->nodes[i];
|
||||
|
||||
if (node->op == GGML_OP_MUL_MAT_ID && cuda_ctx->stream_context().concurrent_events.empty() &&
|
||||
|
||||
@@ -0,0 +1,396 @@
|
||||
#include "inkling2.cuh"
|
||||
|
||||
// the fused kernels keep the operation order of the unfused graph where it is cheap to do so,
|
||||
// __fmul_rn/__fadd_rn stop the compiler from contracting a separate MUL and ADD into one FMA
|
||||
|
||||
static __global__ void situ_f32(
|
||||
const float * gate, const float * up, float * dst, const int ne0, const int ne1, const int ne2, const int64_t nrows,
|
||||
const int64_t g_s1, const int64_t g_s2, const int64_t g_s3, const int64_t u_s1, const int64_t u_s2, const int64_t u_s3,
|
||||
const float s0, const float b0, const float s1, const float b1, const float s2, const float b2, const float s3, const float b3) {
|
||||
ggml_cuda_pdl_lc();
|
||||
const int i0 = blockIdx.x*blockDim.x + threadIdx.x;
|
||||
|
||||
ggml_cuda_pdl_sync();
|
||||
if (i0 >= ne0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (int64_t row = blockIdx.y; row < nrows; row += gridDim.y) {
|
||||
const int64_t i1 = row % ne1;
|
||||
const int64_t i2 = (row / ne1) % ne2;
|
||||
const int64_t i3 = row / ((int64_t) ne1*ne2);
|
||||
|
||||
const float g = gate[i3*g_s3 + i2*g_s2 + i1*g_s1 + i0];
|
||||
const float u = up [i3*u_s3 + i2*u_s2 + i1*u_s1 + i0];
|
||||
|
||||
const float act = s1*tanhf(s0*g + b0) + b1;
|
||||
const float sig = 1.0f/(1.0f + expf(-g));
|
||||
const float lin = s3*tanhf(s2*u + b2) + b3;
|
||||
|
||||
dst[row*ne0 + i0] = __fmul_rn(__fmul_rn(act, sig), lin);
|
||||
}
|
||||
}
|
||||
|
||||
void ggml_cuda_op_situ(ggml_backend_cuda_context & ctx, const ggml_tensor * gate, const ggml_tensor * up,
|
||||
const float * s, const float * b, ggml_tensor * dst) {
|
||||
GGML_ASSERT(gate->type == GGML_TYPE_F32 && up->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32);
|
||||
GGML_ASSERT(gate->nb[0] == sizeof(float) && up->nb[0] == sizeof(float) && ggml_is_contiguous(dst));
|
||||
GGML_ASSERT(ggml_are_same_shape(gate, up) && ggml_are_same_shape(gate, dst));
|
||||
|
||||
const int64_t ne0 = gate->ne[0];
|
||||
const int64_t nrows = ggml_nrows(gate);
|
||||
|
||||
const int block_size = 256;
|
||||
const dim3 grid((ne0 + block_size - 1)/block_size, std::min<int64_t>(nrows, 65535), 1);
|
||||
|
||||
const ggml_cuda_kernel_launch_params params(grid, dim3(block_size, 1, 1), 0, ctx.stream());
|
||||
ggml_cuda_kernel_launch(situ_f32, params,
|
||||
(const float *) gate->data, (const float *) up->data, (float *) dst->data, (int) ne0, (int) gate->ne[1], (int) gate->ne[2], nrows,
|
||||
(int64_t) (gate->nb[1]/sizeof(float)), (int64_t) (gate->nb[2]/sizeof(float)), (int64_t) (gate->nb[3]/sizeof(float)),
|
||||
(int64_t) (up->nb[1]/sizeof(float)), (int64_t) (up->nb[2]/sizeof(float)), (int64_t) (up->nb[3]/sizeof(float)),
|
||||
s[0], b[0], s[1], b[1], s[2], b[2], s[3], b[3]);
|
||||
}
|
||||
|
||||
// one thread per (channel, run of tokens of one sequence). the last K columns of x stay in registers, right-aligned in
|
||||
// M = GGML_CUDA_SHORT_CONV_MAX_K slots with zero weights in front, so K needs no template and the sums keep their order.
|
||||
// a thread reads cur at a token before it writes dst there and never again, so dst may be cur itself when a thread has
|
||||
// the whole sequence
|
||||
template <bool has_dyn, bool has_res>
|
||||
static __global__ void short_conv_f32(const ggml_cuda_short_conv_args a) {
|
||||
ggml_cuda_pdl_lc();
|
||||
constexpr int M = GGML_CUDA_SHORT_CONV_MAX_K;
|
||||
|
||||
const int K = a.K;
|
||||
const int K1 = K - 1;
|
||||
const int c = blockIdx.x*blockDim.x + threadIdx.x;
|
||||
|
||||
ggml_cuda_pdl_sync();
|
||||
if (c >= a.C) {
|
||||
return;
|
||||
}
|
||||
|
||||
float w[M];
|
||||
#pragma unroll
|
||||
for (int m = 0; m < M; ++m) {
|
||||
w[m] = m >= M - K ? a.w[c*K + m - (M - K)] : 0.0f;
|
||||
}
|
||||
|
||||
const int n_runs = (a.Ts + a.run - 1)/a.run;
|
||||
for (int r = blockIdx.y; r < a.S*n_runs; r += gridDim.y) {
|
||||
const int s = r / n_runs;
|
||||
const int t0 = (r - s*n_runs)*a.run;
|
||||
const int t1 = min(t0 + a.run, a.Ts);
|
||||
|
||||
const float * pc = a.past + c*a.past_s1 + s*a.past_s2;
|
||||
const float * xc = a.cur + (int64_t) s*a.Ts*a.C + c;
|
||||
|
||||
// x[M - K + k] is column ts + k of [past; cur^T]
|
||||
float x[M];
|
||||
#pragma unroll
|
||||
for (int m = 0; m < M - 1; ++m) {
|
||||
const int j = t0 + m - (M - K);
|
||||
x[m] = j < 0 ? 0.0f : j < K1 ? pc[j] : xc[(int64_t) (j - K1)*a.C];
|
||||
}
|
||||
|
||||
for (int ts = t0; ts < t1; ++ts) {
|
||||
const int64_t t = (int64_t) s*a.Ts + ts;
|
||||
|
||||
x[M - 1] = xc[(int64_t) ts*a.C];
|
||||
|
||||
float y = 0.0f;
|
||||
#pragma unroll
|
||||
for (int m = 0; m < M; ++m) {
|
||||
y += x[m]*w[m];
|
||||
}
|
||||
|
||||
if constexpr (has_dyn) {
|
||||
const float * d = a.dyn + t*a.dyn_s1 + (c / (a.C / a.n_heads))*K;
|
||||
#pragma unroll
|
||||
for (int lag = 0; lag < M; ++lag) {
|
||||
if (lag < K) {
|
||||
y = __fadd_rn(y, __fmul_rn(x[M - 1 - lag], d[lag]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
float o = a.scale*__fadd_rn(x[M - 1], y) + a.bias;
|
||||
if constexpr (has_res) {
|
||||
o = __fadd_rn(a.res[t*a.C + c], o);
|
||||
}
|
||||
a.dst[t*a.C + c] = o;
|
||||
|
||||
#pragma unroll
|
||||
for (int m = 0; m < M - 1; ++m) {
|
||||
x[m] = x[m + 1];
|
||||
}
|
||||
|
||||
// x now holds the K - 1 columns that end at token ts: the conv state of slot Ts - 1 - ts, if it is kept
|
||||
if (ts >= a.Ts - a.kw) {
|
||||
float * st = a.state + (a.Ts - 1 - ts)*a.state_slot_s + c*a.state_ch_s + s*a.state_seq_s;
|
||||
#pragma unroll
|
||||
for (int m = 0; m < M - 1; ++m) {
|
||||
if (m >= M - K) {
|
||||
st[m - (M - K)] = x[m];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ggml_cuda_op_short_conv(ggml_backend_cuda_context & ctx, const ggml_cuda_short_conv_args & a) {
|
||||
GGML_ASSERT(a.K >= 2 && a.K <= GGML_CUDA_SHORT_CONV_MAX_K);
|
||||
|
||||
const int block_size = 128;
|
||||
const int n_runs = (a.Ts + a.run - 1)/a.run;
|
||||
const dim3 grid((a.C + block_size - 1)/block_size, std::min(a.S*n_runs, 65535), 1);
|
||||
|
||||
const ggml_cuda_kernel_launch_params params(grid, dim3(block_size, 1, 1), 0, ctx.stream());
|
||||
if (a.dyn) {
|
||||
if (a.res) {
|
||||
ggml_cuda_kernel_launch(short_conv_f32<true, true>, params, a);
|
||||
} else {
|
||||
ggml_cuda_kernel_launch(short_conv_f32<true, false>, params, a);
|
||||
}
|
||||
} else {
|
||||
if (a.res) {
|
||||
ggml_cuda_kernel_launch(short_conv_f32<false, true>, params, a);
|
||||
} else {
|
||||
ggml_cuda_kernel_launch(short_conv_f32<false, false>, params, a);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// one block per (query, token): the dot products of the B stack rows and of cur with the query, the softmax over the
|
||||
// B + 1 rows and the weighted sum; the norm of cur is a scale of its dot product
|
||||
template <int block_size>
|
||||
static __global__ void depth_mix_f32(
|
||||
const float * stack, const float * cur, const float * query, float * dst, const int n, const int B, const int Q,
|
||||
const int64_t stack_s1, const int64_t stack_s2, const int64_t cur_s1, const int64_t query_s1,
|
||||
const bool norm_cur, const float eps, const float scale) {
|
||||
ggml_cuda_pdl_lc();
|
||||
constexpr int MAX = GGML_CUDA_DEPTH_MIX_MAX_ROWS;
|
||||
constexpr int NW = block_size/WARP_SIZE;
|
||||
|
||||
const int q = blockIdx.x;
|
||||
const int t = blockIdx.y;
|
||||
const int tid = threadIdx.x;
|
||||
const int lane = tid % WARP_SIZE;
|
||||
const int warp = tid / WARP_SIZE;
|
||||
|
||||
const float * qv = query + q*query_s1;
|
||||
const float * st = stack + t*stack_s2;
|
||||
const float * xc = cur + t*cur_s1;
|
||||
|
||||
// [0, B): the stack rows, MAX: cur, MAX + 1: the sum of squares of cur
|
||||
float acc[MAX + 2];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < MAX + 2; ++r) {
|
||||
acc[r] = 0.0f;
|
||||
}
|
||||
|
||||
ggml_cuda_pdl_sync();
|
||||
|
||||
for (int i = tid; i < n; i += block_size) {
|
||||
const float qi = qv[i];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < MAX; ++r) {
|
||||
if (r < B) {
|
||||
acc[r] += st[r*stack_s1 + i]*qi;
|
||||
}
|
||||
}
|
||||
const float xi = xc[i];
|
||||
acc[MAX] += xi*qi;
|
||||
acc[MAX + 1] += xi*xi;
|
||||
}
|
||||
|
||||
__shared__ float s_acc[NW][MAX + 2];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < MAX + 2; ++r) {
|
||||
if (r < B || r >= MAX) {
|
||||
acc[r] = warp_reduce_sum(acc[r]);
|
||||
if (lane == 0) {
|
||||
s_acc[warp][r] = acc[r];
|
||||
}
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
#pragma unroll
|
||||
for (int r = 0; r < MAX + 2; ++r) {
|
||||
if (r < B || r >= MAX) {
|
||||
acc[r] = 0.0f;
|
||||
#pragma unroll
|
||||
for (int w = 0; w < NW; ++w) {
|
||||
acc[r] += s_acc[w][r];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const float sc = norm_cur ? rsqrtf(acc[MAX + 1]/n + eps) : 1.0f;
|
||||
|
||||
float mx = scale*(sc*acc[MAX]);
|
||||
#pragma unroll
|
||||
for (int r = 0; r < MAX; ++r) {
|
||||
if (r < B) {
|
||||
acc[r] = scale*acc[r];
|
||||
mx = fmaxf(mx, acc[r]);
|
||||
}
|
||||
}
|
||||
|
||||
float p_cur = expf(scale*(sc*acc[MAX]) - mx);
|
||||
float sum = 0.0f;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < MAX; ++r) {
|
||||
if (r < B) {
|
||||
acc[r] = expf(acc[r] - mx);
|
||||
sum += acc[r];
|
||||
}
|
||||
}
|
||||
sum += p_cur;
|
||||
|
||||
const float inv = 1.0f/sum;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < MAX; ++r) {
|
||||
acc[r] *= inv;
|
||||
}
|
||||
p_cur *= inv*sc;
|
||||
|
||||
for (int i = tid; i < n; i += block_size) {
|
||||
float o = 0.0f;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < MAX; ++r) {
|
||||
if (r < B) {
|
||||
o += acc[r]*st[r*stack_s1 + i];
|
||||
}
|
||||
}
|
||||
o += p_cur*xc[i];
|
||||
dst[((int64_t) t*n + i)*Q + q] = o;
|
||||
}
|
||||
}
|
||||
|
||||
void ggml_cuda_op_depth_mix(ggml_backend_cuda_context & ctx, const ggml_tensor * stack, const ggml_tensor * cur,
|
||||
bool norm_cur, float eps, const ggml_tensor * query, float scale, ggml_tensor * dst) {
|
||||
const int64_t n = cur->ne[0];
|
||||
const int64_t B = stack->ne[1];
|
||||
const int64_t T = stack->ne[2];
|
||||
const int64_t Q = query->ne[1];
|
||||
|
||||
GGML_ASSERT(B >= 1 && B <= GGML_CUDA_DEPTH_MIX_MAX_ROWS);
|
||||
GGML_ASSERT(stack->nb[0] == sizeof(float) && cur->nb[0] == sizeof(float) && query->nb[0] == sizeof(float));
|
||||
GGML_ASSERT(ggml_is_contiguous(dst) && dst->ne[0] == Q && dst->ne[1] == n && dst->ne[2] == T);
|
||||
GGML_ASSERT(T <= 65535 && Q <= 65535);
|
||||
|
||||
const int block_size = 256;
|
||||
const dim3 grid(Q, T, 1);
|
||||
|
||||
const ggml_cuda_kernel_launch_params params(grid, dim3(block_size, 1, 1), 0, ctx.stream());
|
||||
ggml_cuda_kernel_launch(depth_mix_f32<block_size>, params,
|
||||
(const float *) stack->data, (const float *) cur->data, (const float *) query->data, (float *) dst->data,
|
||||
(int) n, (int) B, (int) Q,
|
||||
(int64_t) (stack->nb[1]/sizeof(float)), (int64_t) (stack->nb[2]/sizeof(float)),
|
||||
(int64_t) (cur->nb[2]/sizeof(float)), (int64_t) (query->nb[1]/sizeof(float)),
|
||||
norm_cur, eps, scale);
|
||||
}
|
||||
|
||||
// one block per (rank row, token): the sums of squares of cur and msg and their dot products with the two halves of the row
|
||||
template <int block_size>
|
||||
static __global__ void loop_ctrl_down_f32(
|
||||
const float * cur, const float * msg, const float * w, float * gate, const int n,
|
||||
const int64_t cur_s1, const int64_t msg_s1, const int64_t w_s1, const int64_t gate_s1, const float eps) {
|
||||
ggml_cuda_pdl_lc();
|
||||
const int r = blockIdx.x;
|
||||
const int t = blockIdx.y;
|
||||
const int tid = threadIdx.x;
|
||||
|
||||
const float * xc = cur + t*cur_s1;
|
||||
const float * xm = msg + t*msg_s1;
|
||||
const float * wr = w + r*w_s1;
|
||||
|
||||
ggml_cuda_pdl_sync();
|
||||
|
||||
float2 ss = make_float2(0.0f, 0.0f);
|
||||
float2 dd = make_float2(0.0f, 0.0f);
|
||||
for (int i = tid; i < n; i += block_size) {
|
||||
const float c = xc[i];
|
||||
const float m = xm[i];
|
||||
ss.x += c*c;
|
||||
ss.y += m*m;
|
||||
dd.x += wr[i]*c;
|
||||
dd.y += wr[n + i]*m;
|
||||
}
|
||||
|
||||
__shared__ float2 s_ss[32];
|
||||
__shared__ float2 s_dd[32];
|
||||
ss = block_reduce<block_reduce_method::SUM, block_size>(ss, s_ss);
|
||||
dd = block_reduce<block_reduce_method::SUM, block_size>(dd, s_dd);
|
||||
|
||||
if (tid == 0) {
|
||||
gate[t*gate_s1 + r] = rsqrtf(ss.x/n + eps)*dd.x + rsqrtf(ss.y/n + eps)*dd.y;
|
||||
}
|
||||
}
|
||||
|
||||
// one warp per (output channel, token): the gain and forget dot products over the rank and the combine
|
||||
static __global__ void loop_ctrl_up_f32(
|
||||
const float * cur, const float * msg, const float * gate, const float * wg, const float * wf, float * dst,
|
||||
const int n, const int rank, const int64_t cur_s1, const int64_t msg_s1, const int64_t gate_s1,
|
||||
const int64_t wg_s1, const int64_t wf_s1, const int64_t dst_s1) {
|
||||
ggml_cuda_pdl_lc();
|
||||
const int i = blockIdx.x*blockDim.y + threadIdx.y;
|
||||
const int t = blockIdx.y;
|
||||
const int lane = threadIdx.x;
|
||||
|
||||
ggml_cuda_pdl_sync();
|
||||
if (i >= n) {
|
||||
return;
|
||||
}
|
||||
|
||||
const float * gt = gate + t*gate_s1;
|
||||
|
||||
float g = 0.0f;
|
||||
float f = 0.0f;
|
||||
for (int k = lane; k < rank; k += WARP_SIZE) {
|
||||
const float x = gt[k];
|
||||
g += wg[i*wg_s1 + k]*x;
|
||||
f += wf[i*wf_s1 + k]*x;
|
||||
}
|
||||
g = warp_reduce_sum(g);
|
||||
f = warp_reduce_sum(f);
|
||||
|
||||
if (lane == 0) {
|
||||
const float c = cur[t*cur_s1 + i];
|
||||
const float m = msg[t*msg_s1 + i];
|
||||
const float a = __fsub_rn(c, __fmul_rn(tanhf(f), c));
|
||||
dst[t*dst_s1 + i] = __fadd_rn(a, __fmul_rn(tanhf(g), m));
|
||||
}
|
||||
}
|
||||
|
||||
void ggml_cuda_op_loop_ctrl(ggml_backend_cuda_context & ctx, const ggml_tensor * cur, const ggml_tensor * msg, float eps,
|
||||
const ggml_tensor * w_down, const ggml_tensor * w_gain, const ggml_tensor * w_forget, ggml_tensor * gate, ggml_tensor * dst) {
|
||||
const int64_t n = cur->ne[0];
|
||||
const int64_t T = cur->ne[1];
|
||||
const int64_t rank = w_down->ne[1];
|
||||
|
||||
GGML_ASSERT(cur->nb[0] == sizeof(float) && msg->nb[0] == sizeof(float) && gate->nb[0] == sizeof(float) && dst->nb[0] == sizeof(float));
|
||||
GGML_ASSERT(w_down->ne[0] == 2*n && w_gain->ne[0] == rank && w_forget->ne[0] == rank && w_gain->ne[1] == n && w_forget->ne[1] == n);
|
||||
GGML_ASSERT(T <= GGML_CUDA_LOOP_CTRL_MAX_TOKENS);
|
||||
|
||||
cudaStream_t stream = ctx.stream();
|
||||
|
||||
{
|
||||
const int block_size = 256;
|
||||
const ggml_cuda_kernel_launch_params params(dim3(rank, T, 1), dim3(block_size, 1, 1), 0, stream);
|
||||
ggml_cuda_kernel_launch(loop_ctrl_down_f32<block_size>, params,
|
||||
(const float *) cur->data, (const float *) msg->data, (const float *) w_down->data, (float *) gate->data, (int) n,
|
||||
(int64_t) (cur->nb[1]/sizeof(float)), (int64_t) (msg->nb[1]/sizeof(float)),
|
||||
(int64_t) (w_down->nb[1]/sizeof(float)), (int64_t) (gate->nb[1]/sizeof(float)), eps);
|
||||
}
|
||||
{
|
||||
const int rows_per_block = 8;
|
||||
const ggml_cuda_kernel_launch_params params(dim3((n + rows_per_block - 1)/rows_per_block, T, 1), dim3(WARP_SIZE, rows_per_block, 1), 0, stream);
|
||||
ggml_cuda_kernel_launch(loop_ctrl_up_f32, params,
|
||||
(const float *) cur->data, (const float *) msg->data, (const float *) gate->data,
|
||||
(const float *) w_gain->data, (const float *) w_forget->data, (float *) dst->data, (int) n, (int) rank,
|
||||
(int64_t) (cur->nb[1]/sizeof(float)), (int64_t) (msg->nb[1]/sizeof(float)), (int64_t) (gate->nb[1]/sizeof(float)),
|
||||
(int64_t) (w_gain->nb[1]/sizeof(float)), (int64_t) (w_forget->nb[1]/sizeof(float)), (int64_t) (dst->nb[1]/sizeof(float)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
|
||||
#include "common.cuh"
|
||||
|
||||
// fused op chains of the Inkling 2 graph
|
||||
|
||||
// largest conv width and stack depth the fused kernels handle
|
||||
#define GGML_CUDA_SHORT_CONV_MAX_K 8
|
||||
#define GGML_CUDA_DEPTH_MIX_MAX_ROWS 16
|
||||
|
||||
// the most tokens the fused loop controller handles, larger batches use the matrix multiplications
|
||||
#define GGML_CUDA_LOOP_CTRL_MAX_TOKENS 8
|
||||
|
||||
// situ(g, u) = (s1*tanh(s0*g + b0) + b1)*sigmoid(g)*(s3*tanh(s2*u + b2) + b3), with s and b of the four SCALE nodes
|
||||
void ggml_cuda_op_situ(ggml_backend_cuda_context & ctx, const ggml_tensor * gate, const ggml_tensor * up,
|
||||
const float * s, const float * b, ggml_tensor * dst);
|
||||
|
||||
// causal short conv: x = [past; cur^T], y = conv(x, w) (+ input-dependent taps per head), dst = s*(cur + y) + b (+ res)
|
||||
// the K - 1 columns of x that end at token Ts - 1 - slot are the conv state of slot, for the last kw slots (kw = 1 without rollback)
|
||||
// each thread does `run` tokens of a sequence in order, run == Ts lets dst be cur
|
||||
struct ggml_cuda_short_conv_args {
|
||||
const float * past; // [K - 1, C, S], strides in elements
|
||||
int64_t past_s1;
|
||||
int64_t past_s2;
|
||||
const float * cur; // [C, Ts*S], contiguous
|
||||
const float * w; // [K, C], contiguous
|
||||
const float * dyn; // [K*H, Ts*S] taps or nullptr
|
||||
int64_t dyn_s1;
|
||||
int n_heads;
|
||||
const float * res; // [C, Ts*S], contiguous, or nullptr
|
||||
float * dst; // [C, Ts*S], contiguous
|
||||
float * state; // [K - 1, slot, C, S], strides in elements
|
||||
int64_t state_slot_s;
|
||||
int64_t state_ch_s;
|
||||
int64_t state_seq_s;
|
||||
int kw;
|
||||
int run;
|
||||
int C;
|
||||
int K;
|
||||
int Ts;
|
||||
int S;
|
||||
float scale;
|
||||
float bias;
|
||||
};
|
||||
|
||||
void ggml_cuda_op_short_conv(ggml_backend_cuda_context & ctx, const ggml_cuda_short_conv_args & args);
|
||||
|
||||
// depth mix: states = [stack; rms_norm(cur)], p = softmax(scale*(states . query)), dst = p . states, written as [Q, n, T]
|
||||
// norm_cur false: cur is already normalized
|
||||
void ggml_cuda_op_depth_mix(ggml_backend_cuda_context & ctx, const ggml_tensor * stack, const ggml_tensor * cur,
|
||||
bool norm_cur, float eps, const ggml_tensor * query, float scale, ggml_tensor * dst);
|
||||
|
||||
// loop controller: gate = w_down . [rms_norm(cur); rms_norm(msg)], dst = cur - tanh(w_forget . gate)*cur + tanh(w_gain . gate)*msg
|
||||
void ggml_cuda_op_loop_ctrl(ggml_backend_cuda_context & ctx, const ggml_tensor * cur, const ggml_tensor * msg, float eps,
|
||||
const ggml_tensor * w_down, const ggml_tensor * w_gain, const ggml_tensor * w_forget, ggml_tensor * gate, ggml_tensor * dst);
|
||||
@@ -1430,14 +1430,14 @@ namespace ggml_cuda_mma {
|
||||
using floatx4_t = __attribute__((ext_vector_type(4))) float;
|
||||
floatx4_t& acc_frag = reinterpret_cast<floatx4_t&>(D.x[0]);
|
||||
#if defined(CDNA4) || defined(CDNA3) || defined(CDNA2)
|
||||
using bf16x4_t = __attribute__((ext_vector_type(4))) __bf16;
|
||||
using bf16x4_t = __attribute__((ext_vector_type(4))) short;
|
||||
const bf16x4_t& a_frag = reinterpret_cast<const bf16x4_t&>(A.x[0]);
|
||||
const bf16x4_t& b_frag = reinterpret_cast<const bf16x4_t&>(B.x[0]);
|
||||
acc_frag = __builtin_amdgcn_mfma_f32_16x16x16bf16_1k(a_frag, b_frag, acc_frag, 0, 0, 0);
|
||||
#elif defined(CDNA1)
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 2; ++i) {
|
||||
using bf16x2_t = __attribute__((ext_vector_type(2))) __bf16;
|
||||
using bf16x2_t = __attribute__((ext_vector_type(2))) short;
|
||||
const bf16x2_t& a_frag = reinterpret_cast<const bf16x2_t&>(A.x[i]);
|
||||
const bf16x2_t& b_frag = reinterpret_cast<const bf16x2_t&>(B.x[i]);
|
||||
acc_frag = __builtin_amdgcn_mfma_f32_16x16x8bf16(a_frag, b_frag, acc_frag, 0, 0, 0);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -114,6 +114,8 @@ GGML_API void ggml_rope_yarn_corr_dims(
|
||||
|
||||
GGML_API bool ggml_rope_get_truncate(const struct ggml_tensor * a);
|
||||
|
||||
GGML_API bool ggml_validate_flash_attn_ext_indexed_bias(const struct ggml_tensor * a);
|
||||
|
||||
//
|
||||
// logging
|
||||
//
|
||||
|
||||
@@ -1215,6 +1215,14 @@ struct ggml_backend_opencl_context {
|
||||
cl_kernel kernel_gemm_moe_q4_0_q8_1_dp4a = nullptr; // dp4a (int8) q4_0 MoE prefill GEMM
|
||||
cl_kernel kernel_gemm_moe_mxfp4_q8_1_dp4a_bin = nullptr; // binary dp4a (int8) mxfp4 MoE prefill GEMM
|
||||
cl_kernel kernel_gemm_moe_mxfp4_q8_1_dp4a_ldck_bin = nullptr; // binary dp4a (int8) mxfp4 MoE prefill GEMM using ldck
|
||||
cl_kernel kernel_gemm_moe_mxfp4_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 mxfp4 MoE prefill GEMM (A850)
|
||||
cl_kernel kernel_gemm_moe_q4_0_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q4_0 MoE prefill GEMM (A850)
|
||||
cl_kernel kernel_gemm_moe_q4_1_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q4_1 MoE prefill GEMM (A850)
|
||||
cl_kernel kernel_gemm_moe_q5_0_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q5_0 MoE prefill GEMM (A850)
|
||||
cl_kernel kernel_gemm_moe_q5_1_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q5_1 MoE prefill GEMM (A850)
|
||||
cl_kernel kernel_gemm_moe_q4_k_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q4_k MoE prefill GEMM (A850)
|
||||
cl_kernel kernel_gemm_moe_q5_k_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q5_k MoE prefill GEMM (A850)
|
||||
cl_kernel kernel_gemm_moe_q6_k_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q6_k MoE prefill GEMM (A850)
|
||||
cl_kernel kernel_gemm_moe_q4_0_q8_1_dp4a_bin = nullptr; // binary dp4a (int8) q4_0 MoE prefill GEMM
|
||||
cl_kernel kernel_gemm_moe_q4_k_q8_1_dp4a_bin = nullptr; // binary dp4a (int8) q4_k MoE prefill GEMM
|
||||
cl_kernel kernel_gemm_moe_q6_k_q8_1_dp4a_bin = nullptr; // binary dp4a (int8) q6_k MoE prefill GEMM
|
||||
@@ -1241,6 +1249,7 @@ struct ggml_backend_opencl_context {
|
||||
cl_kernel kernel_mul_mv_id_mxfp4_f32_flat;
|
||||
cl_kernel kernel_mul_mm_f32_f32_l4_lm;
|
||||
cl_kernel kernel_gemv_f32_f32_mc; // multi-column (small-N) f32 GEMV for spec/MTP verify
|
||||
cl_kernel kernel_gemv_f32_f32_mcr = nullptr;
|
||||
cl_kernel kernel_mul_mm_f16_f32_l4_lm;
|
||||
cl_kernel kernel_mul_mm_f16_f32_l4_lm_n8;
|
||||
cl_kernel kernel_mul_mm_q1_0_f32_l4_lm;
|
||||
@@ -1563,6 +1572,7 @@ struct ggml_backend_opencl_context {
|
||||
}
|
||||
#endif
|
||||
for (cl_kernel kernel : {
|
||||
kernel_gemv_f32_f32_mcr,
|
||||
kernel_xielu_f32,
|
||||
kernel_xielu_f16,
|
||||
kernel_mul_mm_f16_f32_kq_p8,
|
||||
@@ -4274,6 +4284,16 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) {
|
||||
|
||||
CL_CHECK((backend_ctx->kernel_mul_mm_f32_f32_l4_lm = clCreateKernel(backend_ctx->program_mul_mm_f32_f32_l4_lm, "kernel_mul_mm_f32_f32_l4_lm", &err), err));
|
||||
CL_CHECK((backend_ctx->kernel_gemv_f32_f32_mc = clCreateKernel(backend_ctx->program_mul_mm_f32_f32_l4_lm, "kernel_gemv_f32_f32_mc", &err), err));
|
||||
|
||||
cl_kernel mcr = clCreateKernel(backend_ctx->program_mul_mm_f32_f32_l4_lm, "kernel_gemv_f32_f32_mcr", &err);
|
||||
if (err == CL_SUCCESS) {
|
||||
if (backend_ctx->get_kernel_workgroup_size(mcr) >= 64) {
|
||||
backend_ctx->kernel_gemv_f32_f32_mcr = mcr;
|
||||
} else {
|
||||
CL_CHECK(clReleaseKernel(mcr));
|
||||
}
|
||||
}
|
||||
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
|
||||
@@ -7808,6 +7828,150 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) {
|
||||
}
|
||||
}
|
||||
|
||||
// gemm_moe_mxfp4_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850)
|
||||
if (backend_ctx->has_integer_dot) {
|
||||
size_t bin_size = 0;
|
||||
backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_malu_bin = nullptr;
|
||||
|
||||
if (use_adreno_bin_kernels(backend_ctx)) {
|
||||
const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_mxfp4_q8_1_dp4a_ila_malu", &bin_size);
|
||||
if (kernel_bin && bin_size > 0) {
|
||||
cl_program prog =
|
||||
build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size);
|
||||
|
||||
CL_CHECK((backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_mxfp4_q8_1_dp4a_ila_malu", &err), err));
|
||||
CL_CHECK(clReleaseProgram(prog));
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// gemm_moe_q4_0_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850)
|
||||
if (backend_ctx->has_integer_dot) {
|
||||
size_t bin_size = 0;
|
||||
backend_ctx->kernel_gemm_moe_q4_0_q8_1_dp4a_malu_bin = nullptr;
|
||||
|
||||
if (use_adreno_bin_kernels(backend_ctx)) {
|
||||
const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_0_q8_1_dp4a_ila_malu", &bin_size);
|
||||
if (kernel_bin && bin_size > 0) {
|
||||
cl_program prog =
|
||||
build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size);
|
||||
|
||||
CL_CHECK((backend_ctx->kernel_gemm_moe_q4_0_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_0_q8_1_dp4a_ila_malu", &err), err));
|
||||
CL_CHECK(clReleaseProgram(prog));
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// gemm_moe_q4_1_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850)
|
||||
if (backend_ctx->has_integer_dot) {
|
||||
size_t bin_size = 0;
|
||||
backend_ctx->kernel_gemm_moe_q4_1_q8_1_dp4a_malu_bin = nullptr;
|
||||
|
||||
if (use_adreno_bin_kernels(backend_ctx)) {
|
||||
const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_1_q8_1_dp4a_ila_malu", &bin_size);
|
||||
if (kernel_bin && bin_size > 0) {
|
||||
cl_program prog =
|
||||
build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size);
|
||||
|
||||
CL_CHECK((backend_ctx->kernel_gemm_moe_q4_1_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_1_q8_1_dp4a_ila_malu", &err), err));
|
||||
CL_CHECK(clReleaseProgram(prog));
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// gemm_moe_q5_0_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850)
|
||||
if (backend_ctx->has_integer_dot) {
|
||||
size_t bin_size = 0;
|
||||
backend_ctx->kernel_gemm_moe_q5_0_q8_1_dp4a_malu_bin = nullptr;
|
||||
|
||||
if (use_adreno_bin_kernels(backend_ctx)) {
|
||||
const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q5_0_q8_1_dp4a_ila_malu", &bin_size);
|
||||
if (kernel_bin && bin_size > 0) {
|
||||
cl_program prog =
|
||||
build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size);
|
||||
|
||||
CL_CHECK((backend_ctx->kernel_gemm_moe_q5_0_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q5_0_q8_1_dp4a_ila_malu", &err), err));
|
||||
CL_CHECK(clReleaseProgram(prog));
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// gemm_moe_q5_1_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850)
|
||||
if (backend_ctx->has_integer_dot) {
|
||||
size_t bin_size = 0;
|
||||
backend_ctx->kernel_gemm_moe_q5_1_q8_1_dp4a_malu_bin = nullptr;
|
||||
|
||||
if (use_adreno_bin_kernels(backend_ctx)) {
|
||||
const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q5_1_q8_1_dp4a_ila_malu", &bin_size);
|
||||
if (kernel_bin && bin_size > 0) {
|
||||
cl_program prog =
|
||||
build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size);
|
||||
|
||||
CL_CHECK((backend_ctx->kernel_gemm_moe_q5_1_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q5_1_q8_1_dp4a_ila_malu", &err), err));
|
||||
CL_CHECK(clReleaseProgram(prog));
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// gemm_moe_q4_k_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850)
|
||||
if (backend_ctx->has_integer_dot) {
|
||||
size_t bin_size = 0;
|
||||
backend_ctx->kernel_gemm_moe_q4_k_q8_1_dp4a_malu_bin = nullptr;
|
||||
|
||||
if (use_adreno_bin_kernels(backend_ctx)) {
|
||||
const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_k_q8_1_dp4a_ila_malu", &bin_size);
|
||||
if (kernel_bin && bin_size > 0) {
|
||||
cl_program prog =
|
||||
build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size);
|
||||
|
||||
CL_CHECK((backend_ctx->kernel_gemm_moe_q4_k_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_k_q8_1_dp4a_ila_malu", &err), err));
|
||||
CL_CHECK(clReleaseProgram(prog));
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// gemm_moe_q5_k_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850)
|
||||
if (backend_ctx->has_integer_dot) {
|
||||
size_t bin_size = 0;
|
||||
backend_ctx->kernel_gemm_moe_q5_k_q8_1_dp4a_malu_bin = nullptr;
|
||||
|
||||
if (use_adreno_bin_kernels(backend_ctx)) {
|
||||
const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q5_k_q8_1_dp4a_ila_malu", &bin_size);
|
||||
if (kernel_bin && bin_size > 0) {
|
||||
cl_program prog =
|
||||
build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size);
|
||||
|
||||
CL_CHECK((backend_ctx->kernel_gemm_moe_q5_k_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q5_k_q8_1_dp4a_ila_malu", &err), err));
|
||||
CL_CHECK(clReleaseProgram(prog));
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// gemm_moe_q6_k_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850)
|
||||
if (backend_ctx->has_integer_dot) {
|
||||
size_t bin_size = 0;
|
||||
backend_ctx->kernel_gemm_moe_q6_k_q8_1_dp4a_malu_bin = nullptr;
|
||||
|
||||
if (use_adreno_bin_kernels(backend_ctx)) {
|
||||
const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q6_k_q8_1_dp4a_ila_malu", &bin_size);
|
||||
if (kernel_bin && bin_size > 0) {
|
||||
cl_program prog =
|
||||
build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size);
|
||||
|
||||
CL_CHECK((backend_ctx->kernel_gemm_moe_q6_k_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q6_k_q8_1_dp4a_ila_malu", &err), err));
|
||||
CL_CHECK(clReleaseProgram(prog));
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// gemm_moe_q4_0_q8_1_dp4a (dp4a prefill GEMM)
|
||||
if (backend_ctx->has_integer_dot) {
|
||||
#ifdef GGML_OPENCL_EMBED_KERNELS
|
||||
@@ -11080,6 +11244,76 @@ static bool ggml_opencl_can_fuse_moe_bias_glu(const struct ggml_cgraph * cgraph,
|
||||
return true;
|
||||
}
|
||||
|
||||
// Run a malu int8 (dp4a ila malu bin) MoE GEMM: fused reorder + q8_1 quant of the activations, then the GEMM.
|
||||
// The weight buffers come first in the kernel args, in the order of the ns kernel of the same type.
|
||||
// use_sa: the kernel takes the q8_1 block sums (min types), or an unused buffer in that slot (q4_0).
|
||||
static void ggml_cl_moe_gemm_malu_bin(
|
||||
ggml_backend_opencl_context * backend_ctx, cl_kernel kernel, std::initializer_list<cl_mem> weights, bool use_sa,
|
||||
cl_mem sub_buf_src1_pre, cl_mem buf_src2, cl_mem buf_src2_emap,
|
||||
cl_mem dst_data, cl_ulong offsetd, size_t n_dst, const ggml_tensor * dst,
|
||||
int ne00, int ne01, unsigned short map_ratio, int max_post_router_tile, int n_tile_size) {
|
||||
cl_int status;
|
||||
|
||||
const size_t tok_slots = (size_t)max_post_router_tile * n_tile_size;
|
||||
const size_t n_blocks = tok_slots * (ne00 / 32);
|
||||
backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, tok_slots * ne00 * sizeof(cl_char));
|
||||
backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks * sizeof(cl_half));
|
||||
backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks * sizeof(cl_half));
|
||||
|
||||
const cl_uint n_kblocks = (cl_uint)(ne00 / 32);
|
||||
cl_uint ne00_u = ne00;
|
||||
cl_uint tile_u = n_tile_size;
|
||||
cl_kernel rq = backend_ctx->kernel_moe_reorder_quant_a_q8_1;
|
||||
CL_CHECK(clSetKernelArg(rq, 0, sizeof(cl_mem), &sub_buf_src1_pre));
|
||||
CL_CHECK(clSetKernelArg(rq, 1, sizeof(cl_mem), &buf_src2));
|
||||
CL_CHECK(clSetKernelArg(rq, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer));
|
||||
CL_CHECK(clSetKernelArg(rq, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer));
|
||||
CL_CHECK(clSetKernelArg(rq, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer));
|
||||
CL_CHECK(clSetKernelArg(rq, 5, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer)));
|
||||
CL_CHECK(clSetKernelArg(rq, 6, sizeof(cl_uint), &ne00_u));
|
||||
CL_CHECK(clSetKernelArg(rq, 7, sizeof(unsigned short), &map_ratio));
|
||||
CL_CHECK(clSetKernelArg(rq, 8, sizeof(cl_uint), &tile_u));
|
||||
CL_CHECK(clSetKernelArg(rq, 9, sizeof(cl_uint), &n_kblocks));
|
||||
size_t rq_local[2] = { 32, 1 };
|
||||
size_t rq_global[2] = { (size_t)(((n_kblocks + 31) / 32) * 32), tok_slots };
|
||||
backend_ctx->enqueue_ndrange_kernel(rq, 2, rq_global, rq_local, dst);
|
||||
|
||||
// dst as an image
|
||||
cl_buffer_region region;
|
||||
region.origin = offsetd;
|
||||
region.size = n_dst * sizeof(float);
|
||||
cl_mem sub_buf_dst = clCreateSubBuffer(dst_data, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status);
|
||||
CL_CHECK(status);
|
||||
cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT};
|
||||
cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, n_dst, 0,0,0,0,0,0,0, {sub_buf_dst}};
|
||||
cl_mem buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status);
|
||||
CL_CHECK(status);
|
||||
|
||||
int aidx = 0;
|
||||
for (cl_mem w : weights) {
|
||||
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &w));
|
||||
}
|
||||
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer));
|
||||
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer));
|
||||
if (use_sa) {
|
||||
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer));
|
||||
}
|
||||
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &buf_src2));
|
||||
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &buf_src2_emap));
|
||||
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &buf_dst_image));
|
||||
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer)));
|
||||
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(int), &ne00));
|
||||
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(int), &ne01));
|
||||
CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(int), &backend_ctx->adreno_use_moe_ragged_dp4));
|
||||
|
||||
size_t dp_global[3] = { 64, (size_t)((ne01 + 63) / 64), (size_t)max_post_router_tile };
|
||||
size_t dp_local[3] = { 64, 1, 1 };
|
||||
backend_ctx->enqueue_ndrange_kernel(kernel, 3, dp_global, dp_local, dst);
|
||||
|
||||
clReleaseMemObject(sub_buf_dst);
|
||||
clReleaseMemObject(buf_dst_image);
|
||||
}
|
||||
|
||||
// Run a cl_qcom_kernel_cooperative_matrix MoE GEMM: f16 reorder of the activations, then the GEMM.
|
||||
// The weight buffers come first in the kernel args, in the order of the ns kernel of the same type.
|
||||
static void ggml_cl_moe_gemm_coopmat(
|
||||
@@ -32854,6 +33088,20 @@ static void ggml_cl_fwht(ggml_backend_t backend, const ggml_tensor * src, ggml_t
|
||||
backend_ctx->enqueue_ndrange_kernel(kernel, 2, global, local, dst);
|
||||
}
|
||||
|
||||
// reduce lanes per row for short K, down to four lanes.
|
||||
static int ggml_cl_mcr_lpr_log2(int ne00) {
|
||||
int lpr_log2 = 6;
|
||||
while (lpr_log2 > 2 && ((ne00 / 4) >> lpr_log2) < 4) {
|
||||
lpr_log2--;
|
||||
}
|
||||
return lpr_log2;
|
||||
}
|
||||
|
||||
static bool ggml_cl_mcr_wide_enough(int ne00, int ne01) {
|
||||
const int rows_per_wg = 64 >> ggml_cl_mcr_lpr_log2(ne00);
|
||||
return CEIL_DIV((size_t) ne01, rows_per_wg) >= 256;
|
||||
}
|
||||
|
||||
static void ggml_cl_mul_mat(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
|
||||
GGML_ASSERT(src0);
|
||||
GGML_ASSERT(src0->extra);
|
||||
@@ -33448,8 +33696,63 @@ static void ggml_cl_mul_mat(ggml_backend_t backend, const ggml_tensor * src0, co
|
||||
// under-occupied WG at ~2.3% tile utilization. Route to a per-output
|
||||
// (m,n) GEMV (64-thread WG, K-split + __local reduce) instead.
|
||||
// 2D contiguous, small N + skinny M only. Default on for X2E, GGML_OPENCL_F32_MC=0/1 forces it.
|
||||
static const char * f32_mc_env = getenv("GGML_OPENCL_F32_MC");
|
||||
const bool f32_mc = f32_mc_env ? atoi(f32_mc_env) != 0 : backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E;
|
||||
static const int f32_mc_env = [] {
|
||||
const char * env = getenv("GGML_OPENCL_F32_MC");
|
||||
return env ? atoi(env) : -1;
|
||||
}();
|
||||
const bool f32_mc = f32_mc_env >= 0 ? f32_mc_env != 0 : backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E;
|
||||
|
||||
static const int f32_mcr_env = [] {
|
||||
const char * env = getenv("GGML_OPENCL_F32_MCR");
|
||||
return env && *env ? atoi(env) : -1;
|
||||
}();
|
||||
const bool f32_mcr = f32_mcr_env >= 0 ? f32_mcr_env != 0 :
|
||||
(backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X);
|
||||
const bool f32_mcr_allowed = f32_mc_env >= 0 ? f32_mc_env != 0 : !adreno_e17_compiler_quirks(backend_ctx);
|
||||
|
||||
if (f32_mcr && f32_mcr_allowed && backend_ctx->kernel_gemv_f32_f32_mcr != nullptr &&
|
||||
ne11 >= 2 && ne11 <= 8 && ne00 > 0 && ne00 <= INT_MAX && ne01 > 0 && ne01 <= 512 &&
|
||||
(size_t) ne01 <= SIZE_MAX / 64 && (ne00 % 4 == 0) &&
|
||||
ne02 == 1 && ne03 == 1 && ne12 == 1 && ne13 == 1 &&
|
||||
dst->ne[2] == 1 && dst->ne[3] == 1 &&
|
||||
ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst) &&
|
||||
offset0 % 16 == 0 && offset1 % 16 == 0 && offsetd % sizeof(float) == 0 &&
|
||||
ggml_cl_mcr_wide_enough((int) ne00, (int) ne01)
|
||||
) {
|
||||
const int K = (int) ne00;
|
||||
const int M = (int) ne01;
|
||||
const int N = (int) ne11;
|
||||
|
||||
const int stride_a = K;
|
||||
const int stride_b = K;
|
||||
const int stride_d = M;
|
||||
|
||||
const int lpr_log2 = ggml_cl_mcr_lpr_log2(K);
|
||||
const int rows_per_wg = 64 >> lpr_log2;
|
||||
|
||||
cl_kernel mcr = backend_ctx->kernel_gemv_f32_f32_mcr;
|
||||
|
||||
CL_CHECK(clSetKernelArg(mcr, 0, sizeof(cl_mem), &extra0->data_device));
|
||||
CL_CHECK(clSetKernelArg(mcr, 1, sizeof(cl_ulong), &offset0));
|
||||
CL_CHECK(clSetKernelArg(mcr, 2, sizeof(cl_mem), &extra1->data_device));
|
||||
CL_CHECK(clSetKernelArg(mcr, 3, sizeof(cl_ulong), &offset1));
|
||||
CL_CHECK(clSetKernelArg(mcr, 4, sizeof(cl_mem), &extrad->data_device));
|
||||
CL_CHECK(clSetKernelArg(mcr, 5, sizeof(cl_ulong), &offsetd));
|
||||
CL_CHECK(clSetKernelArg(mcr, 6, sizeof(int), &K));
|
||||
CL_CHECK(clSetKernelArg(mcr, 7, sizeof(int), &M));
|
||||
CL_CHECK(clSetKernelArg(mcr, 8, sizeof(int), &N));
|
||||
CL_CHECK(clSetKernelArg(mcr, 9, sizeof(int), &stride_a));
|
||||
CL_CHECK(clSetKernelArg(mcr, 10, sizeof(int), &stride_b));
|
||||
CL_CHECK(clSetKernelArg(mcr, 11, sizeof(int), &stride_d));
|
||||
CL_CHECK(clSetKernelArg(mcr, 12, sizeof(int), &lpr_log2));
|
||||
|
||||
size_t global[] = {CEIL_DIV((size_t) M, rows_per_wg) * 64, 1, 1};
|
||||
size_t local[] = {64, 1, 1};
|
||||
|
||||
backend_ctx->enqueue_ndrange_kernel(mcr, 3, global, local, dst);
|
||||
return;
|
||||
}
|
||||
|
||||
if (f32_mc && ne11 >= 2 && ne11 <= 8 && ne01 <= 512 && (ne00 % 4 == 0) &&
|
||||
ne02 == 1 && ne12 == 1 && ne13 == 1 &&
|
||||
ggml_is_contiguous(src0) && ggml_is_contiguous(src1)) {
|
||||
@@ -36917,6 +37220,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0,
|
||||
unsigned short map_ratio = ne20 / ne11;
|
||||
GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n");
|
||||
|
||||
// binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var
|
||||
{
|
||||
static const char * q4_0_moe_malu_env = getenv("GGML_OPENCL_Q4_0_MOE_DP4A");
|
||||
if (backend_ctx->has_integer_dot && (!q4_0_moe_malu_env || atoi(q4_0_moe_malu_env) != 0) &&
|
||||
backend_ctx->kernel_gemm_moe_q4_0_q8_1_dp4a_malu_bin != nullptr) {
|
||||
unsigned short malu_map_ratio = ne20 / ne11;
|
||||
GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n");
|
||||
ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q4_0_q8_1_dp4a_malu_bin,
|
||||
{ extra0_q4_0->q_img, extra0_q4_0->d }, true,
|
||||
sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst,
|
||||
ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size);
|
||||
clReleaseMemObject(sub_buf_src1_pre);
|
||||
clReleaseMemObject(buf_src2);
|
||||
clReleaseMemObject(buf_src2_emap);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels
|
||||
{
|
||||
static const char * q4_0_moe_coopmat_env = getenv("GGML_OPENCL_Q4_0_MOE_COOPMAT");
|
||||
@@ -37221,6 +37542,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0,
|
||||
sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status);
|
||||
CL_CHECK(status);
|
||||
|
||||
// binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var
|
||||
{
|
||||
static const char * q4_1_moe_malu_env = getenv("GGML_OPENCL_Q4_1_MOE_DP4A");
|
||||
if (backend_ctx->has_integer_dot && (!q4_1_moe_malu_env || atoi(q4_1_moe_malu_env) != 0) &&
|
||||
backend_ctx->kernel_gemm_moe_q4_1_q8_1_dp4a_malu_bin != nullptr) {
|
||||
unsigned short malu_map_ratio = ne20 / ne11;
|
||||
GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n");
|
||||
ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q4_1_q8_1_dp4a_malu_bin,
|
||||
{ extra0_q4_1->q_img, extra0_q4_1->d, extra0_q4_1->m }, true,
|
||||
sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst,
|
||||
ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size);
|
||||
clReleaseMemObject(sub_buf_src1_pre);
|
||||
clReleaseMemObject(buf_src2);
|
||||
clReleaseMemObject(buf_src2_emap);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels
|
||||
{
|
||||
static const char * q4_1_moe_coopmat_env = getenv("GGML_OPENCL_Q4_1_MOE_COOPMAT");
|
||||
@@ -37500,6 +37839,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0,
|
||||
}
|
||||
}
|
||||
|
||||
// binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var
|
||||
{
|
||||
static const char * q5_0_moe_malu_env = getenv("GGML_OPENCL_Q5_MOE_DP4A");
|
||||
if (backend_ctx->has_integer_dot && (!q5_0_moe_malu_env || atoi(q5_0_moe_malu_env) != 0) &&
|
||||
backend_ctx->kernel_gemm_moe_q5_0_q8_1_dp4a_malu_bin != nullptr) {
|
||||
unsigned short malu_map_ratio = ne20 / ne11;
|
||||
GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n");
|
||||
ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q5_0_q8_1_dp4a_malu_bin,
|
||||
{ extra0_q5_0->qs_img, extra0_q5_0->qh, extra0_q5_0->d }, false,
|
||||
sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst,
|
||||
ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size);
|
||||
clReleaseMemObject(sub_buf_src1_pre);
|
||||
clReleaseMemObject(buf_src2);
|
||||
clReleaseMemObject(buf_src2_emap);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels
|
||||
{
|
||||
static const char * q5_0_moe_coopmat_env = getenv("GGML_OPENCL_Q5_0_MOE_COOPMAT");
|
||||
@@ -37699,6 +38056,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0,
|
||||
sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status);
|
||||
CL_CHECK(status);
|
||||
|
||||
// binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var
|
||||
{
|
||||
static const char * q5_1_moe_malu_env = getenv("GGML_OPENCL_Q5_1_MOE_DP4A");
|
||||
if (backend_ctx->has_integer_dot && (!q5_1_moe_malu_env || atoi(q5_1_moe_malu_env) != 0) &&
|
||||
backend_ctx->kernel_gemm_moe_q5_1_q8_1_dp4a_malu_bin != nullptr) {
|
||||
unsigned short malu_map_ratio = ne20 / ne11;
|
||||
GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n");
|
||||
ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q5_1_q8_1_dp4a_malu_bin,
|
||||
{ extra0_q5_1->qs_img, extra0_q5_1->qh, extra0_q5_1->d, extra0_q5_1->m }, true,
|
||||
sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst,
|
||||
ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size);
|
||||
clReleaseMemObject(sub_buf_src1_pre);
|
||||
clReleaseMemObject(buf_src2);
|
||||
clReleaseMemObject(buf_src2_emap);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels
|
||||
{
|
||||
static const char * q5_1_moe_coopmat_env = getenv("GGML_OPENCL_Q5_1_MOE_COOPMAT");
|
||||
@@ -38183,6 +38558,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0,
|
||||
unsigned short map_ratio = ne20 / ne11;
|
||||
GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n");
|
||||
|
||||
// binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var
|
||||
{
|
||||
static const char * q4_k_moe_malu_env = getenv("GGML_OPENCL_Q4K_MOE_DP4A");
|
||||
if (backend_ctx->has_integer_dot && (!q4_k_moe_malu_env || atoi(q4_k_moe_malu_env) != 0) &&
|
||||
backend_ctx->kernel_gemm_moe_q4_k_q8_1_dp4a_malu_bin != nullptr) {
|
||||
unsigned short malu_map_ratio = ne20 / ne11;
|
||||
GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n");
|
||||
ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q4_k_q8_1_dp4a_malu_bin,
|
||||
{ extra0_q4_K->q_img, extra0_q4_K->d, extra0_q4_K->dm, extra0_q4_K->s }, true,
|
||||
sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst,
|
||||
ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size);
|
||||
clReleaseMemObject(sub_buf_src1_pre);
|
||||
clReleaseMemObject(buf_src2);
|
||||
clReleaseMemObject(buf_src2_emap);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels
|
||||
{
|
||||
static const char * q4_k_moe_coopmat_env = getenv("GGML_OPENCL_Q4K_MOE_COOPMAT");
|
||||
@@ -38522,6 +38915,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0,
|
||||
}
|
||||
}
|
||||
|
||||
// binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var
|
||||
{
|
||||
static const char * q5_k_moe_malu_env = getenv("GGML_OPENCL_Q5K_MOE_DP4A");
|
||||
if (backend_ctx->has_integer_dot && (!q5_k_moe_malu_env || atoi(q5_k_moe_malu_env) != 0) &&
|
||||
backend_ctx->kernel_gemm_moe_q5_k_q8_1_dp4a_malu_bin != nullptr) {
|
||||
unsigned short malu_map_ratio = ne20 / ne11;
|
||||
GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n");
|
||||
ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q5_k_q8_1_dp4a_malu_bin,
|
||||
{ extra0_q5_K->q_img, extra0_q5_K->qh, extra0_q5_K->s, extra0_q5_K->d, extra0_q5_K->dm }, true,
|
||||
sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst,
|
||||
ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size);
|
||||
clReleaseMemObject(sub_buf_src1_pre);
|
||||
clReleaseMemObject(buf_src2);
|
||||
clReleaseMemObject(buf_src2_emap);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels
|
||||
{
|
||||
static const char * q5_k_moe_coopmat_env = getenv("GGML_OPENCL_Q5K_MOE_COOPMAT");
|
||||
@@ -38742,6 +39153,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0,
|
||||
unsigned short map_ratio = ne20 / ne11;
|
||||
GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n");
|
||||
|
||||
// binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var
|
||||
{
|
||||
static const char * q6_k_moe_malu_env = getenv("GGML_OPENCL_Q6K_MOE_DP4A");
|
||||
if (backend_ctx->has_integer_dot && (!q6_k_moe_malu_env || atoi(q6_k_moe_malu_env) != 0) &&
|
||||
backend_ctx->kernel_gemm_moe_q6_k_q8_1_dp4a_malu_bin != nullptr) {
|
||||
unsigned short malu_map_ratio = ne20 / ne11;
|
||||
GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n");
|
||||
ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q6_k_q8_1_dp4a_malu_bin,
|
||||
{ extra0_q6_K->ql_img, extra0_q6_K->qh, extra0_q6_K->s, extra0_q6_K->d }, false,
|
||||
sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst,
|
||||
ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size);
|
||||
clReleaseMemObject(sub_buf_src1_pre);
|
||||
clReleaseMemObject(buf_src2);
|
||||
clReleaseMemObject(buf_src2_emap);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels
|
||||
{
|
||||
static const char * q6_k_moe_coopmat_env = getenv("GGML_OPENCL_Q6K_MOE_COOPMAT");
|
||||
@@ -39042,6 +39471,24 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0,
|
||||
unsigned short map_ratio = ne20 / ne11;
|
||||
GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n");
|
||||
|
||||
// binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var
|
||||
{
|
||||
static const char * mxfp4_moe_malu_env = getenv("GGML_OPENCL_MXFP4_MOE_DP4A");
|
||||
if (backend_ctx->has_integer_dot && (!mxfp4_moe_malu_env || atoi(mxfp4_moe_malu_env) != 0) &&
|
||||
backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_malu_bin != nullptr) {
|
||||
unsigned short malu_map_ratio = ne20 / ne11;
|
||||
GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n");
|
||||
ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_malu_bin,
|
||||
{ extra0_mxfp4->q_img, extra0_mxfp4->e }, false,
|
||||
sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst,
|
||||
ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size);
|
||||
clReleaseMemObject(sub_buf_src1_pre);
|
||||
clReleaseMemObject(buf_src2);
|
||||
clReleaseMemObject(buf_src2_emap);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (use_moe_coopmat) {
|
||||
// f16 reordered activations, read by the coopmat kernel as a buffer
|
||||
region.origin = 0;
|
||||
|
||||
@@ -194,3 +194,64 @@ kernel void kernel_gemv_f32_f32_mc(
|
||||
}
|
||||
if (lane == 0) dst[(ulong)n * (uint)stride_d + m] = red[0];
|
||||
}
|
||||
|
||||
// Reuse each weight row across the narrow batch, with one accumulator per column.
|
||||
kernel void kernel_gemv_f32_f32_mcr(
|
||||
global const float * src0, ulong offset0,
|
||||
global const float * src1, ulong offset1,
|
||||
global float * dst, ulong offsetd,
|
||||
int ne00, // K
|
||||
int ne01, // M
|
||||
int ne11, // N, 2..8
|
||||
int stride_a,
|
||||
int stride_b,
|
||||
int stride_d,
|
||||
int lpr_log2 // lanes per row = 1 << lpr_log2
|
||||
) {
|
||||
src0 = (global const float*)((global const char*)src0 + offset0);
|
||||
src1 = (global const float*)((global const char*)src1 + offset1);
|
||||
dst = (global float*)((global char*)dst + offsetd);
|
||||
|
||||
const uint lane = get_local_id(0);
|
||||
const uint lpr = 1u << lpr_log2;
|
||||
const uint l = lane & (lpr - 1);
|
||||
const uint mr = get_group_id(0) * (64u >> lpr_log2) + (lane >> lpr_log2);
|
||||
const bool valid = mr < (uint)ne01;
|
||||
// Keep padded rows in the local-memory barriers.
|
||||
const uint m = valid ? mr : (uint)ne01 - 1;
|
||||
|
||||
global const float4 * wrow = (global const float4*)(src0 + (ulong)m * (uint)stride_a);
|
||||
const uint k4 = (uint)ne00 >> 2;
|
||||
|
||||
float acc[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
|
||||
for (uint k = l; k < k4; k += lpr) {
|
||||
const float4 w = wrow[k];
|
||||
#pragma unroll
|
||||
for (int n = 0; n < 8; n++) {
|
||||
if (n < ne11) {
|
||||
acc[n] += dot(w, ((global const float4*)(src1 + (ulong)n * (uint)stride_b))[k]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
local float red[8 * 64];
|
||||
#pragma unroll
|
||||
for (int n = 0; n < 8; n++) {
|
||||
red[n * 64 + lane] = acc[n];
|
||||
}
|
||||
barrier(CLK_LOCAL_MEM_FENCE);
|
||||
for (uint s = lpr >> 1; s > 0; s >>= 1) {
|
||||
if (l < s) {
|
||||
#pragma unroll
|
||||
for (int n = 0; n < 8; n++) {
|
||||
red[n * 64 + lane] += red[n * 64 + lane + s];
|
||||
}
|
||||
}
|
||||
barrier(CLK_LOCAL_MEM_FENCE);
|
||||
}
|
||||
if (l == 0 && valid) {
|
||||
for (int n = 0; n < ne11; n++) {
|
||||
dst[(ulong)n * (uint)stride_d + m] = red[n * 64 + lane];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
if (NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64|AMD64|aarch64)$")
|
||||
message(FATAL_ERROR "OpenVINO: OpenVINO toolkit supports x86-64 and arm64 but not ${CMAKE_SYSTEM_PROCESSOR}")
|
||||
endif()
|
||||
|
||||
find_package(OpenVINO REQUIRED COMPONENTS Runtime Threading)
|
||||
find_package(OpenCL REQUIRED)
|
||||
|
||||
@@ -24,17 +28,11 @@ if (WIN32)
|
||||
target_link_libraries(ggml-openvino PRIVATE psapi)
|
||||
endif()
|
||||
|
||||
if (GGML_OPENVINO)
|
||||
if (CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64")
|
||||
elseif (CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64" OR CMAKE_SYSTEM_PROCESSOR STREQUAL "amd64" OR CMAKE_SYSTEM_PROCESSOR STREQUAL "AMD64")
|
||||
else()
|
||||
message(FATAL_ERROR "OpenVINO: OpenVINO toolkit supports x86-64 and arm64 but not ${CMAKE_SYSTEM_PROCESSOR}")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Released runtimes retain the ordinary cache translators.
|
||||
include(CheckCXXSourceCompiles)
|
||||
include(CMakePushCheckState)
|
||||
unset(GGML_OPENVINO_HAS_CACHE_UPDATE CACHE)
|
||||
cmake_push_check_state(RESET)
|
||||
set(CMAKE_REQUIRED_LIBRARIES openvino::runtime)
|
||||
set(CMAKE_REQUIRED_INCLUDES "${CMAKE_CURRENT_SOURCE_DIR}/openvino/op")
|
||||
check_cxx_source_compiles("#include <recurrent_cache_update.hpp>
|
||||
@@ -43,8 +41,7 @@ int main() {
|
||||
auto gdn = std::make_shared<ov::op::internal::RecurrentGatedDeltaNetUpdate>(ov::OutputVector{});
|
||||
}"
|
||||
GGML_OPENVINO_HAS_CACHE_UPDATE)
|
||||
unset(CMAKE_REQUIRED_LIBRARIES)
|
||||
unset(CMAKE_REQUIRED_INCLUDES)
|
||||
cmake_pop_check_state()
|
||||
if(GGML_OPENVINO_HAS_CACHE_UPDATE)
|
||||
target_compile_definitions(ggml-openvino PRIVATE GGML_OPENVINO_HAS_CACHE_UPDATE=1)
|
||||
endif()
|
||||
|
||||
@@ -87,3 +87,11 @@ The generic recurrent-cache translation invalidates blobs made with the former s
|
||||
- File identity, size, modification/change timestamps, tensor offsets, graph structure, settings, and OpenVINO version identify cache entries. Linux uses device/inode and Windows uses volume serial/file index. Replacing, copying, or modifying a GGUF invalidates its entries. This avoids reading weight bytes and ties the cache to the local source files. Keep those files unchanged throughout loading and inference.
|
||||
- Use the same target device and compatible OpenVINO/plugin installation. Import support depends on the plugin; the tested CPU plugin cannot import MoE graphs containing `GatherMatmulCompressed`. GPU MoE and CPU dense graph imports were tested.
|
||||
- Blobs contain weights and can approach model size for each compiled graph. Import still reads those blobs and initializes the device.
|
||||
|
||||
# KV-only prefill
|
||||
|
||||
On the static path (NPU, or any device with `GGML_OPENVINO_FORCE_STATIC=1`), models whose tail layers read an earlier layer's KV get a KV-only prefill by default; `GGML_OPENVINO_KV_ONLY_PREFILL=0` turns it off. It compiles the static prefill graph with only the KV-cache writes as outputs (`openvino/pass/keep_cache_results.cpp`). Everything that only feeds the logits is dropped from it: for models whose tail layers read an earlier layer's KV (Gemma 3n/4 E-series) that is every KV-shared layer, plus the LM head. When the batch needs logits, the decode graph is then run once on the output token; it rewrites that token's KV rows and computes the dropped layers against the complete cache. It is used only when attention ops of the graph share a KV cache tensor and the graph has no recurrent state. If a batch needs more than one output token, or the output step fails, the backend logs a warning and uses the full prefill from then on.
|
||||
|
||||
# NPU host gather
|
||||
|
||||
`GGML_OPENVINO_NPU_HOST_GATHER=1` (NPU, opt-in) gathers the rows of large host-resident embedding tables (at least 64 MiB, raw GGUF data) on the host. The static graph gets the gathered rows through an `ggml_host_rows_<node>` input instead of an OpenVINO Gather over the table. NPUW otherwise lifts the table to a function input, and gathering from an input that large costs about as much as streaming the whole table every call (21.6 ms of Gemma 4 E2B decode). A table used only for such lookups (the Gemma 3n/4 per-layer embedding table) is not converted or bound to the NPU at all.
|
||||
|
||||
@@ -11,6 +11,7 @@ The variables for users, and the rules for values, are in [docs/backend/OPENVINO
|
||||
| `GGML_OPENVINO_DEBUG_INPUT` | all | Boolean | `0` | Print the input tensors. |
|
||||
| `GGML_OPENVINO_DEBUG_OUTPUT` | all | Boolean | `0` | Print the output tensors. |
|
||||
| `GGML_OPENVINO_DEBUG_NODE` | all | String | `not set` | Add the named graph nodes as outputs of the compiled model. Separate several names with commas. |
|
||||
| `GGML_OPENVINO_DEBUG_DYNAMIC_DIMS` | all | Boolean | `0` | Print each graph node and its sources with their shapes when a graph is decoded. `*` marks the dynamic (token) dimension. |
|
||||
| `GGML_OPENVINO_PRINT_CGRAPH_TENSOR_ADDRESS` | all | Boolean | `0` | Print the tensor address map once. |
|
||||
| `GGML_OPENVINO_LOG_UNSUPPORTED_OPS` | all | Boolean | `0` | Log each op that the backend does not support, with the tensor details and the reason. |
|
||||
| `GGML_OPENVINO_LOG_SUPPORTS_OP` | all | Integer | `0` | Log what `supports_op` accepts and rejects. `1`: summary at exit. `2`: also each call (the first calls are missing). |
|
||||
@@ -28,6 +29,9 @@ The variables for users, and the rules for values, are in [docs/backend/OPENVINO
|
||||
GGML_OPENVINO_DUMP_CGRAPH=1 GGML_OPENVINO_DUMP_IR=1 \
|
||||
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
|
||||
|
||||
# Shapes of each graph node, with * at the dynamic (token) dimension. Printed to stdout.
|
||||
GGML_OPENVINO_DEBUG_DYNAMIC_DIMS=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 4 -no-cnv -p "Hello" > dims.txt
|
||||
|
||||
# Log unsupported ops. The lines have the WARN level, which the default log verbosity shows (-lv 2 or higher).
|
||||
GGML_OPENVINO_LOG_UNSUPPORTED_OPS=1 ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
|
||||
|
||||
@@ -50,8 +54,8 @@ Each variable turns off an optimization that is on by default, or sets its stren
|
||||
|
||||
| Variable | Device | Type | Default | Description |
|
||||
|---|---|---|---|---|
|
||||
| `GGML_OPENVINO_KV_SLICE` | all | Boolean | `1` | Bind the KV cache, and size the KQ masks, at the attended length instead of the full context. CPU and GPU: a view over the cache. NPU: the prefill graph is compiled at the attended length, rounded up to a power of two, and replaced when that size changes. With `0`, `llama-bench -d` fails on the NPU. |
|
||||
| `GGML_OPENVINO_NPU_BLOB_PREBUILD` | NPU | Boolean | `1` | Decode attends the smallest `1024 * 2^k` rows that cover the next position, with one decode graph for each window. All windows are built, or read from the cache, together with the first prefill and decode pair. `0`: one decode graph attends the whole context. Use the same value in the run that writes the cache and in the runs that read it. |
|
||||
| `GGML_OPENVINO_KV_SLICE` | all | Integer | `1` | Bind the KV cache, and size the KQ masks, at the attended length instead of the full context. `0`: off. `1`: on, KV window base 1024. `N` (a multiple of 256): on, KV window base `N`. CPU and GPU: a view over the cache (any non-zero value just turns it on). Static path (NPU): the prefill graph is compiled at the smallest `N * 2^k` rows (clamped to the context) that cover the attended length; a loaded prefill graph of a larger window also serves a shorter prompt (with `GGML_OPENVINO_NPU_KV_ON_DEMAND=1`, only the exact window); the decode KV windows of `GGML_OPENVINO_NPU_BLOB_PREBUILD` use the same base. With `0`, `llama-bench -d` fails on the NPU. Use the same value in the run that writes the cache and in the runs that read it. |
|
||||
| `GGML_OPENVINO_NPU_BLOB_PREBUILD` | NPU | Boolean | `1` | With `GGML_OPENVINO_KV_SLICE` on, decode attends the smallest `N * 2^k` rows (`N` from `GGML_OPENVINO_KV_SLICE`) that cover the next position, with one decode graph for each window, and the prefill windows are aligned to them. Every decode window is built, or read from the cache, on the first call. With `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`, the first prompt also writes (or reads) the prefill graph of every window; only the prefill graph in use stays loaded, unless `GGML_OPENVINO_SELF_CONTAINED_MMAP=1` or `GGML_OPENVINO_NPU_KV_ON_DEMAND=1` keeps them all loaded. `0`, or `GGML_OPENVINO_KV_SLICE=0`: one decode graph attends the whole context, and prefill graphs are built on first use. Use the same value in the run that writes the cache and in the runs that read it. |
|
||||
| `GGML_OPENVINO_NPU_FAST_MASK` | NPU | Boolean | `1` | Write the prefill attention mask directly into the input tensor, without an intermediate copy. The result is identical. |
|
||||
| `GGML_OPENVINO_NPU_L0_HOST_TENSORS` | NPU | Boolean | `1` | Keep the KV cache and the compute buffers in Level Zero host memory, so the plugin reads them without an extra copy. Falls back to plain host memory if the allocation is not available. |
|
||||
| `GGML_OPENVINO_GDN_Q_SCALE` | NPU | Float | `64` | Factor of the GDN q pre-scaling, which keeps the GDN output above the FP16 flush-to-zero floor of the NPU. `0` or a negative value turns it off. Values below `64` are raised to `64`. |
|
||||
@@ -75,7 +79,6 @@ These options are off by default. They are not validated for general use: some h
|
||||
| Variable | Device | Type | Default | Description |
|
||||
|---|---|---|---|---|
|
||||
| `GGML_OPENVINO_NPU_DECODE_UNFOLD` | NPU | Boolean | `0` | Set `NPUW_UNFOLD_IREQS=YES` on the decode graph only. An explicit `GGML_OPENVINO_NPUW_UNFOLD_IREQS` or `GGML_OPENVINO_NPU_CONFIG` value takes precedence. |
|
||||
| `GGML_OPENVINO_NPU_PARALLEL_COMPILE` | NPU | Boolean | `0` | Compile the prefill and decode graphs in parallel. The load is shorter and the host memory peak during compilation is higher. |
|
||||
| `GGML_OPENVINO_NPU_KV_ON_DEMAND` | NPU | Boolean | `0` | Keep the ggml KV buffer non-resident and bind storage for each layer that grows with the rows in use, so a large `-c` costs memory only for the context that is reached. K is stored head-major and V transposed, as OpenVINO GenAI does. `llama-perplexity` fails with it. |
|
||||
| `GGML_OPENVINO_NPU_REQUANT_POLICY` | NPU | String | `group-128` | Layout of requantized weights: `group-128` (`Q4_0_128`) or `channel-wise` (`Q4_0_C`, lower accuracy). |
|
||||
| `GGML_OPENVINO_GDN_DECOMPOSE_CHUNK` | all | Integer | `16` | Tokens in one chunk when `GGML_OPENVINO_GDN_DECOMPOSE` is on. A power of 2 from 2 to 128; other values use `16`. |
|
||||
@@ -90,16 +93,13 @@ These options are off by default. They are not validated for general use: some h
|
||||
| `GGML_OPENVINO_REDUCE_COMPILE_MEM` | all | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Create fewer weight nodes during compilation, to lower the host memory in use. |
|
||||
| `GGML_OPENVINO_RELEASE_WEIGHTS` | GPU | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Release the host weight buffers when the compiled model holds its own copy. Needs stable graph shapes; do not use it for workloads that compile again. |
|
||||
| `GGML_OPENVINO_SPILL_DIR` | all | String | `not set` | Directory for a disk-backed weight buffer, so its pages can be reclaimed under memory pressure. It must be on real storage, not on tmpfs (`/tmp` on many systems). It is not part of the key of the compiled model cache and is ignored in cache-only mode. |
|
||||
| `GGML_OPENVINO_SELF_CONTAINED_BLOB` | NPU | Boolean | `0` | Requires `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`. Write the prefill and decode graphs as blobs with the weights inside; each blob takes about the size of the model on disk. Decode then attends the whole context. `GGML_OPENVINO_NPU_WEIGHTLESS_BANK` is the recommended cache layout for the NPU. |
|
||||
| `GGML_OPENVINO_NPU_SHARED_BANK` | NPU | Boolean | `0` | With `GGML_OPENVINO_SELF_CONTAINED_BLOB=1`: one weights bank for the prefill and decode blobs. With OpenVINO 2026.4.1 the blobs cannot be read back, so decode is compiled again. |
|
||||
| `GGML_OPENVINO_LAZY_HOST_THRESHOLD_MB` | NPU | Integer | `2048` | With `GGML_OPENVINO_SELF_CONTAINED_MMAP=1`: buffers of at least this size get demand-zero host memory instead of Level Zero host memory. |
|
||||
|
||||
```bash
|
||||
# NPU cache with the weights inside the blobs (experimental). Keep all other NPU settings the same in both runs.
|
||||
# NPU cache: weightless blobs plus one shared weights file. Keep all other NPU settings the same in both runs.
|
||||
export GGML_OPENVINO_DEVICE=NPU
|
||||
export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache
|
||||
export GGML_OPENVINO_SELF_CONTAINED_BLOB=1
|
||||
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 -lv 4 # first run: log shows "model cache WROTE"
|
||||
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 -lv 4 # first run: warns "no usable cached blobs", exports
|
||||
|
||||
export GGML_OPENVINO_SELF_CONTAINED_MMAP=1
|
||||
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 -lv 4 # later runs: log shows "model cache HIT"
|
||||
@@ -141,7 +141,6 @@ export GGML_OPENVINO_REDUCE_COMPILE_MEM=1
|
||||
# NPU: weightless cache, then use the memory-mapped GGUF as the model buffer.
|
||||
export GGML_OPENVINO_DEVICE=NPU
|
||||
export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache
|
||||
export GGML_OPENVINO_NPU_WEIGHTLESS_BANK=1
|
||||
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 # first run writes the cache
|
||||
export GGML_OPENVINO_SELF_CONTAINED_MMAP=1
|
||||
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 # later runs
|
||||
@@ -182,11 +181,15 @@ Other properties that are useful with `GGML_OPENVINO_NPU_CONFIG`. The backend do
|
||||
| `NPUW_UNFOLD_IREQS` | Boolean | `not set` | `NO` | One infer request for each part, also for repeating blocks. |
|
||||
| `LOG_LEVEL` | String | `not set` | `LOG_ERROR` | Log level of the NPU plugin, for example `LOG_INFO`. |
|
||||
|
||||
Set properties with `GGML_OPENVINO_NPU_CONFIG`:
|
||||
|
||||
```bash
|
||||
export GGML_OPENVINO_DEVICE=NPU
|
||||
export GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN,COMPILATION_NUM_THREADS=1,LOG_LEVEL=LOG_INFO"
|
||||
```
|
||||
|
||||
List the properties of the installed NPU plugin:
|
||||
|
||||
```cpp
|
||||
// List the properties of the installed NPU plugin with their current values
|
||||
ov::Core core;
|
||||
@@ -199,6 +202,35 @@ for (const auto & name : core.get_property("NPU", ov::supported_properties)) {
|
||||
- `NPUW_*` options, with type and default: `src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc` in the OpenVINO source.
|
||||
- Graphs without a KV cache compile without NPUW: the backend removes `NPU_USE_NPUW` and the `NPUW_*` keys for them.
|
||||
|
||||
### Example: gemma-4 E2B with the model cache
|
||||
|
||||
`GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` saves the model compiled for the NPU, so only the first start compiles it. Run step 1 once, then start the model as in step 2 every later time.
|
||||
|
||||
#### Step 1: first run, compile and save the model
|
||||
|
||||
```bash
|
||||
# This start takes longer: the backend compiles the model for the NPU and saves it in the cache directory
|
||||
# (with -lv 4 the log shows "no usable cached blobs ... compiling and exporting").
|
||||
# Use the model as usual, then exit with /exit.
|
||||
export GGML_OPENVINO_DEVICE=NPU
|
||||
export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache
|
||||
export GGML_OPENVINO_NPU_HOST_GATHER=1 # optional: faster generation, less memory and disk; the output can differ slightly
|
||||
export GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT=q4_0_128 # optional: slightly less memory; may lower accuracy
|
||||
export GGML_OPENVINO_PREFILL_CHUNK_SIZE=512 # optional: can make long prompts faster; makes the first run longer
|
||||
./build/ReleaseOV/bin/llama-cli -m google_gemma-4-E2B-it-Q4_K_M.gguf -c 4096
|
||||
```
|
||||
|
||||
#### Step 2: later runs, load the model from the cache
|
||||
|
||||
```bash
|
||||
# Use the same exports as in step 1 (repeat them in a new shell) and the same command.
|
||||
# The backend loads the compiled model instead of compiling it, so the model starts much faster
|
||||
# (with -lv 4 the log shows "model cache HIT"). A changed setting or -c value compiles and saves again,
|
||||
# or stops with an error when GGML_OPENVINO_SELF_CONTAINED_MMAP=1 is set.
|
||||
export GGML_OPENVINO_SELF_CONTAINED_MMAP=1 # optional, later runs only: slightly shorter start; fails without the cache of step 1
|
||||
./build/ReleaseOV/bin/llama-cli -m google_gemma-4-E2B-it-Q4_K_M.gguf -c 4096
|
||||
```
|
||||
|
||||
## GPU and CPU plugin properties
|
||||
|
||||
The backend sets no GPU or CPU property, except `CACHE_DIR` and `CACHE_MODE=OPTIMIZE_SIZE` when `GGML_OPENVINO_CACHE_DIR` is set.
|
||||
|
||||
@@ -20,8 +20,12 @@ ExtraQuantType ggml_openvino_get_npu_requant_type() {
|
||||
std::optional<ExtraQuantType> ggml_openvino_npu_token_embd_requant_type(const ggml_tensor * tensor) {
|
||||
// A Q6_K embedding table is stored as q8_0_c by default on the NPU. The int4 layouts only pay off for a tied
|
||||
// embedding, where the table is also the lm_head weight and GET_ROWS gathers the packed rows
|
||||
// before dequantizing them (see gather_compressed_rows).
|
||||
if (tensor->type != GGML_TYPE_Q6_K) {
|
||||
// before dequantizing them (see gather_compressed_rows). Other K-quant tables default to the channel-wise
|
||||
// int8 of ggml_openvino_get_requant_type() and follow this setting only when it is set explicitly
|
||||
// (Gemma 4 E2B: a tied Q4_K table is 384 MiB as int8, 198 MiB as q4_0_128).
|
||||
if (tensor->type != GGML_TYPE_Q6_K &&
|
||||
!((tensor->type == GGML_TYPE_Q4_K || tensor->type == GGML_TYPE_Q5_K) &&
|
||||
ggml_openvino_getenv_str("GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT") != nullptr)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const std::string quant = ggml_openvino_getenv_str("GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT", "q8_0_c");
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
#include <cctype>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
@@ -313,6 +312,17 @@ static std::string get_tensor_graph_input_ov_name(const GgmlOvDecoder * decoder,
|
||||
if (GgmlOvDecoder::is_inp_emb(tensor, op)) {
|
||||
return "embd";
|
||||
}
|
||||
const auto & model_params = decoder->get_model_params();
|
||||
if (tensor == model_params.prune_ids) {
|
||||
return "inp_prune_ids";
|
||||
}
|
||||
if (tensor == model_params.prune_keep) {
|
||||
return "inp_prune_keep";
|
||||
}
|
||||
if (auto it = model_params.pruned_masks.find(tensor); it != model_params.pruned_masks.end()) {
|
||||
// not a graph input: get_kq_mask_input() gathers the rows from the input mask of this name
|
||||
return get_tensor_graph_input_ov_name(decoder, cgraph, it->second, op) + "_pruned";
|
||||
}
|
||||
// gemma-4's KV-shared layers read the mask rows of their output tokens through GET_ROWS, which is not a mask
|
||||
// consumer, so match the masks by identity too
|
||||
if (GgmlOvDecoder::is_inp_mask(tensor, op) || decoder->is_kq_mask(tensor)) {
|
||||
@@ -796,8 +806,14 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
|
||||
} else if (GgmlOvDecoder::is_conv_state_writeback(node)) {
|
||||
op_case = 2;
|
||||
break;
|
||||
} else if (is_conv_states_all_tensor(node->view_src) && node->src[1] != nullptr &&
|
||||
node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src == node->view_src) {
|
||||
} else if (node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW &&
|
||||
node->src[1]->view_src == node->view_src &&
|
||||
(is_conv_states_all_tensor(node->view_src) ||
|
||||
(node->view_src->op == GGML_OP_NONE && ggml_is_contiguous(node->src[1]) &&
|
||||
!is_recurrent_cache(node->view_src) &&
|
||||
strncmp(node->view_src->name, "cache_", strlen("cache_")) != 0))) {
|
||||
// View writeback into a contiguous block of a plain (non-KV, non-recurrent) tensor at
|
||||
// a static offset, e.g. the mamba-style conv state copy into its cache row.
|
||||
op_case = 4;
|
||||
break;
|
||||
} else if (node->src[0]->src[0]->op == GGML_OP_GET_ROWS && node->src[1] != nullptr &&
|
||||
@@ -1075,7 +1091,32 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
|
||||
layer_mask.emplace(layer.value(), mask);
|
||||
max_extent = std::max(max_extent, leaf->ne[1]);
|
||||
if (mask->op == GGML_OP_NONE) {
|
||||
model_params.kq_masks.insert(mask);
|
||||
const ggml_tensor * layer_input_mask = layer_mask[layer.value()];
|
||||
if (layer_input_mask != mask && layer_input_mask->op == GGML_OP_NONE) {
|
||||
// a second input mask on the cache of a layer: the mask rows of gemma-4's KV-shared layers
|
||||
model_params.pruned_masks.emplace(mask, layer_input_mask);
|
||||
} else {
|
||||
model_params.kq_masks.insert(mask);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!model_params.pruned_masks.empty()) {
|
||||
// The first output row index list gathers the rows of the KV-shared layers, a later one the output rows
|
||||
// among them
|
||||
for (int i = 0; i < cgraph->n_nodes; i++) {
|
||||
const ggml_tensor * node = cgraph->nodes[i];
|
||||
if (node->op != GGML_OP_GET_ROWS || !is_output_idx(node->src[1], node)) {
|
||||
continue;
|
||||
}
|
||||
if (model_params.prune_ids == nullptr) {
|
||||
model_params.prune_ids = node->src[1];
|
||||
} else if (node->src[1] != model_params.prune_ids) {
|
||||
model_params.prune_keep = node->src[1];
|
||||
}
|
||||
}
|
||||
if (model_params.prune_ids == nullptr) {
|
||||
throw std::runtime_error("OpenVINO: masks of KV-shared layers without their row index list");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1210,7 +1251,8 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
|
||||
compute_params.seq_active_start = offset / seq_size;
|
||||
|
||||
// a mask that is itself a graph input has the shape of its OV parameter
|
||||
const std::string mask_name = mask->op != GGML_OP_NONE ? std::string() :
|
||||
const std::string mask_name = mask->op != GGML_OP_NONE || model_params.pruned_masks.count(mask) ?
|
||||
std::string() :
|
||||
mask == model_params.swa_mask ? get_tensor_ov_name(cgraph, mask) + "_swa" :
|
||||
get_tensor_ov_name(cgraph, mask);
|
||||
// gemma-4's KV-shared layers come last and take their mask rows from the input masks with GET_ROWS: keep
|
||||
@@ -1229,7 +1271,8 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
|
||||
}
|
||||
}
|
||||
if (is_static) {
|
||||
const bool slice_prefill = ggml_openvino_kv_slice_enabled() && compute_params.input_len > 1;
|
||||
const bool slice_prefill =
|
||||
ggml_openvino_kv_slice_enabled() && compute_params.input_len > 1;
|
||||
if (!slice_prefill) {
|
||||
compute_params.attention_size = model_params.ctx_per_seq;
|
||||
}
|
||||
@@ -1261,10 +1304,8 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
|
||||
compute_params.token_len_per_seq = ggml_nelements(node->src[1]);
|
||||
}
|
||||
|
||||
// When multiple ROPE ops in the graph disagree on op_params (e.g. gemma4's
|
||||
// mixed SWA/non-SWA layers with different n_dims or freq_base), we cannot
|
||||
// share a single precomputed rope_sin/rope_cos. Track divergence so the
|
||||
// translator falls back to per-op make_sin_cos in that case.
|
||||
// Multiple ROPE ops can disagree on op_params (e.g. gemma4's mixed SWA/non-SWA layers with different
|
||||
// n_dims or freq_base). Track divergence for the graph key and for decoder reuse.
|
||||
static_assert(sizeof(model_params.rope_params) == sizeof(int32_t) * 16, "rope_params size");
|
||||
if (!rope_seen) {
|
||||
memcpy(model_params.rope_params, node->op_params, sizeof(int32_t) * 16);
|
||||
@@ -1402,13 +1443,13 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
|
||||
if (is_static && compute_params.output_len == 0) {
|
||||
compute_params.output_len = 1;
|
||||
}
|
||||
// A sliced static prefill attends a power-of-two number of KV rows: every attended size needs its own compiled
|
||||
// prefill model, so a growing sequence compiles one when the attended length doubles, not for each ubatch.
|
||||
// Rounding up adds masked rows, which cost prefill time, so it stops at the next power of two.
|
||||
// A sliced static prefill attends base*2^k KV rows (base from GGML_OPENVINO_KV_SLICE): every attended size needs
|
||||
// its own compiled prefill model, so a growing sequence compiles one when the attended length doubles, not for
|
||||
// each ubatch. Rounding up adds masked rows, which cost prefill time, so it stops at the next window.
|
||||
if (is_static && ggml_openvino_kv_slice_enabled() && compute_params.input_len > 1 &&
|
||||
!model_params.is_cacheless_attn && compute_params.attention_size > 0 && model_params.ctx_per_seq > 0) {
|
||||
compute_params.attention_size =
|
||||
ggml_openvino_static_kv_window(compute_params.attention_size, model_params.ctx_per_seq);
|
||||
compute_params.attention_size = ggml_openvino_static_kv_window(
|
||||
compute_params.attention_size, model_params.ctx_per_seq, ggml_openvino_kv_slice_base());
|
||||
}
|
||||
// The GPU plugin keeps device memory for each KV length it sees, and llama.cpp grows the KV length in steps of
|
||||
// 256. Round it up (ggml_openvino_gpu_kv_window), so that a long context uses a few lengths and not one per step.
|
||||
@@ -1478,8 +1519,8 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op,
|
||||
// Both masks are named "attn_inp_kq_mask", so tell them apart by tensor identity.
|
||||
const bool swa_mask = is_swa_mask(input);
|
||||
int attention_size = swa_mask ? m_model_params.ctx_per_seq_swa * m_model_params.n_seq : m_model_params.ctx;
|
||||
const bool kv_window =
|
||||
m_is_prefill ? ggml_openvino_kv_slice_enabled() : ggml_openvino_npu_decode_bucket() > 0;
|
||||
const bool kv_window = m_is_prefill ? ggml_openvino_kv_slice_enabled() :
|
||||
ggml_openvino_npu_decode_bucket() > 0;
|
||||
if (kv_window) {
|
||||
attention_size = swa_mask ? m_compute_params.attention_size_swa : m_compute_params.attention_size;
|
||||
}
|
||||
@@ -1613,8 +1654,44 @@ bool GgmlOvDecoder::is_s_copy_leaf(const ggml_tensor * tensor) const {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool GgmlOvDecoder::is_host_gather_rows(const ggml_tensor * node) {
|
||||
if (!ggml_openvino_npu_host_gather_enabled() || node == nullptr || node->op != GGML_OP_GET_ROWS) {
|
||||
return false;
|
||||
}
|
||||
const ggml_tensor * table = node->src[0];
|
||||
const ggml_tensor * ids = node->src[1];
|
||||
// The table must hold raw ggml rows in host memory. OpenVINO buffers store weights in the extracted layout, except
|
||||
// with the NPU weightless cache, where they keep (or, with SELF_CONTAINED_MMAP, wrap) the raw GGUF bytes.
|
||||
constexpr size_t min_table_bytes = 64ull * 1024 * 1024;
|
||||
if (table == nullptr || ids == nullptr || table->view_src != nullptr || table->buffer == nullptr) {
|
||||
return false;
|
||||
}
|
||||
const bool raw_cache = ggml_openvino_npu_weightless_cache_enabled();
|
||||
const bool raw_rows = ggml_backend_buffer_is_openvino(table->buffer) ? raw_cache :
|
||||
ggml_backend_buffer_is_host(table->buffer);
|
||||
return table->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS && raw_rows &&
|
||||
ggml_get_type_traits(table->type)->to_float != nullptr &&
|
||||
ggml_nbytes(table) >= min_table_bytes && ids->type == GGML_TYPE_I32 && ids->op == GGML_OP_NONE &&
|
||||
ggml_nelements(ids) == ids->ne[0] && node->ne[1] == ids->ne[0];
|
||||
}
|
||||
|
||||
void GgmlOvDecoder::add_extra_inputs() {
|
||||
m_model_extra_inputs.clear();
|
||||
m_host_gather_rows.clear();
|
||||
if (m_is_static) {
|
||||
for (const auto & info : m_node_info_list) {
|
||||
if (is_host_gather_rows(info.node)) {
|
||||
const std::string name = std::string(host_rows_prefix) + info.node_name;
|
||||
m_host_gather_rows[name] = info.node;
|
||||
m_model_extra_inputs[name] = {ov::element::f32,
|
||||
ov::Shape{1, 1, (size_t) get_static_n_tokens(), (size_t) info.node->ne[0]},
|
||||
0,
|
||||
true,
|
||||
{},
|
||||
-1};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extra inputs:
|
||||
// 1. `attention_size`, used in FLASH_ATTN where the shape of the matmul's are 256 aligned,
|
||||
@@ -1679,7 +1756,6 @@ void GgmlOvDecoder::add_extra_inputs() {
|
||||
m_model_extra_inputs["ggml_hfa_mask"] = {
|
||||
ov::element::f16, ov::Shape{1, 1, chunk_size, past_capacity + chunk_size}, 0, true, {}, -1};
|
||||
}
|
||||
// create_1d_input("token_len", m_compute_params.token_len_per_seq * m_compute_params.n_seq_active);
|
||||
|
||||
// n_seq_active and attention_size(_swa) are dimensions of the KQ masks. Read them from the mask shape inside the
|
||||
// model: the GPU plugin then gets the Q Reshape and KV Slice shapes from shape inference instead of waiting for
|
||||
@@ -1885,6 +1961,9 @@ void GgmlOvDecoder::compute_model_inputs() {
|
||||
if (m_model_inputs.find(src_name) != m_model_inputs.end()) {
|
||||
continue;
|
||||
}
|
||||
if (is_pruned_mask(src)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
m_inputs[src_name] = src;
|
||||
|
||||
@@ -2087,22 +2166,6 @@ bool GgmlOvDecoder::is_kvcache_token_rows(const ggml_tensor * cache) const {
|
||||
return true;
|
||||
}
|
||||
|
||||
const ggml_tensor * GgmlOvDecoder::get_tensor_from_name(const std::string & name) const {
|
||||
for (int i = 0; i < m_cgraph->n_nodes; i++) {
|
||||
const auto * node = m_cgraph->nodes[i];
|
||||
for (int j = 0; j < GGML_MAX_SRC; j++) {
|
||||
const auto * src = node->src[j];
|
||||
if (src == nullptr) {
|
||||
break;
|
||||
}
|
||||
if (get_tensor_ov_name(m_cgraph, src) == name) {
|
||||
return src;
|
||||
}
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::string GgmlOvDecoder::get_hfa_history_input_name() const {
|
||||
for (const auto & [name, tensor] : m_inputs) {
|
||||
const auto * op = get_tensor_used_op(tensor);
|
||||
@@ -2143,6 +2206,10 @@ std::map<std::string, std::shared_ptr<ov::Node>> GgmlOvDecoder::create_weight_no
|
||||
continue;
|
||||
}
|
||||
|
||||
// A table whose rows are gathered on the host needs no OV weight for that use.
|
||||
if (i == 0 && is_host_gather_rows(node)) {
|
||||
continue;
|
||||
}
|
||||
// A view over a weight is served by the base tensor's Constant.
|
||||
ggml_tensor * base = src->view_src ? src->view_src : src;
|
||||
std::string src_name = get_tensor_ov_name(cgraph, base);
|
||||
@@ -2242,9 +2309,9 @@ std::shared_ptr<ov::Node> GgmlOvDecoder::create_weight_node(ggml_tensor * tensor
|
||||
// pointer to avoid re-extracting on every recompile. Opt-in via
|
||||
// GGML_OPENVINO_REDUCE_COMPILE_MEM or GGML_OPENVINO_MEMORY_OPTIMIZE. Skip
|
||||
// for `naive` (test/naive path) since use_bias changes the produced node.
|
||||
// Self-contained decode-window models are built after the pair; reusing the node keeps e.g. the
|
||||
// Cached decode-window models are built after the pair; reusing the node keeps e.g. the
|
||||
// token_embd vocab on the pair's NPUW bank uid instead of embedding and importing a second copy.
|
||||
const bool keep_for_windows = ggml_openvino_npu_raw_weight_cache_enabled() && ggml_openvino_npu_decode_bucket() > 0;
|
||||
const bool keep_for_windows = ggml_openvino_npu_weightless_cache_enabled() && ggml_openvino_npu_decode_bucket() > 0;
|
||||
const bool cacheable_nonov = (ggml_openvino_reduce_compile_mem_enabled() || keep_for_windows) && !is_ov_buffer &&
|
||||
!naive && tensor->data != nullptr;
|
||||
if (cacheable_nonov) {
|
||||
@@ -2273,10 +2340,10 @@ std::shared_ptr<ov::Node> GgmlOvDecoder::create_weight_node(ggml_tensor * tensor
|
||||
if (ggml_is_quantized(tensor->type)) {
|
||||
auto use_bias = naive;
|
||||
if (is_ov_buffer) {
|
||||
const bool preserve_raw = ggml_openvino_npu_raw_weight_cache_enabled();
|
||||
const bool preserve_raw = ggml_openvino_npu_weightless_cache_enabled();
|
||||
if (preserve_raw) {
|
||||
// A later context must fingerprint the same raw GGUF bytes before importing its
|
||||
// self-contained blob, so keep the model buffer immutable in this mode.
|
||||
// cached blob, so keep the model buffer immutable in this mode.
|
||||
ov_weight = process_weight_tensor(tensor, tensor->data, nullptr, use_bias);
|
||||
} else {
|
||||
// The regular path stores extracted weights in the model buffer. Copy raw data
|
||||
@@ -2689,7 +2756,10 @@ std::vector<std::string> GgmlOvDecoder::get_output_names(int node_idx) const {
|
||||
// the written state block plus the full updated cache (see translate_cpy op_case 13)
|
||||
return {m_node_info_list[node_idx].node_name, get_tensor_ov_name(m_cgraph, node->view_src)};
|
||||
}
|
||||
if (node->op == GGML_OP_GATED_DELTA_NET && (!m_model_params.has_rs_rollback || node->op_params[0] > 1)) {
|
||||
// Naive (op test) graphs have no runtime slot inputs for the native state writeback, so they keep the packed
|
||||
// [attention | state] output, which the consumers slice through the generic view path.
|
||||
if (!m_naive && node->op == GGML_OP_GATED_DELTA_NET &&
|
||||
(!m_model_params.has_rs_rollback || node->op_params[0] > 1)) {
|
||||
std::string attn_name;
|
||||
std::string state_name;
|
||||
for (int i = node_idx + 1; i < m_cgraph->n_nodes; i++) {
|
||||
@@ -2824,43 +2894,29 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
|
||||
if (src == nullptr) {
|
||||
continue;
|
||||
}
|
||||
struct ggml_tensor * root_src = nullptr;
|
||||
// if (src->org_src) {
|
||||
// root_src = src->org_src;
|
||||
// }
|
||||
if (root_src) {
|
||||
if (is_inp_tok(root_src, node) || is_inp_pos(root_src, node) || is_get_rows_input_idx(root_src, node)) {
|
||||
m_node_dynamic_dims[root_src] = 0;
|
||||
m_node_dynamic_dims[src] = m_node_dynamic_dims[root_src];
|
||||
continue;
|
||||
}
|
||||
self(self, root_src);
|
||||
m_node_dynamic_dims[src] = m_node_dynamic_dims[root_src];
|
||||
} else {
|
||||
if (is_inp_tok(src, node) || is_inp_pos(src, node) || is_get_rows_input_idx(src, node)) {
|
||||
m_node_dynamic_dims[src] = 0;
|
||||
continue;
|
||||
}
|
||||
if (is_inp_scale_rows(src, node) || is_inp_embd_leaf(src, node)) {
|
||||
m_node_dynamic_dims[src] = 1;
|
||||
continue;
|
||||
}
|
||||
if (!m_is_static && is_activation_input(src, node)) {
|
||||
m_node_dynamic_dims[src] = 1;
|
||||
continue;
|
||||
}
|
||||
// a view of a model weight (BERT's token type row) has no token dim
|
||||
if (node->op == GGML_OP_VIEW && src->op == GGML_OP_NONE && !is_stateful() && !m_model_is_splitted &&
|
||||
!(src->buffer != nullptr && src->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS)) {
|
||||
m_node_dynamic_dims[src] = 1;
|
||||
continue;
|
||||
}
|
||||
if (is_inp_embd_2d(src, node)) {
|
||||
m_node_dynamic_dims[src] = 1;
|
||||
continue;
|
||||
}
|
||||
self(self, src);
|
||||
if (is_inp_tok(src, node) || is_inp_pos(src, node) || is_get_rows_input_idx(src, node)) {
|
||||
m_node_dynamic_dims[src] = 0;
|
||||
continue;
|
||||
}
|
||||
if (is_inp_scale_rows(src, node) || is_inp_embd_leaf(src, node)) {
|
||||
m_node_dynamic_dims[src] = 1;
|
||||
continue;
|
||||
}
|
||||
if (!m_is_static && is_activation_input(src, node)) {
|
||||
m_node_dynamic_dims[src] = 1;
|
||||
continue;
|
||||
}
|
||||
// a view of a model weight (BERT's token type row) has no token dim
|
||||
if (node->op == GGML_OP_VIEW && src->op == GGML_OP_NONE && !is_stateful() && !m_model_is_splitted &&
|
||||
!(src->buffer != nullptr && src->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS)) {
|
||||
m_node_dynamic_dims[src] = 1;
|
||||
continue;
|
||||
}
|
||||
if (is_inp_embd_2d(src, node)) {
|
||||
m_node_dynamic_dims[src] = 1;
|
||||
continue;
|
||||
}
|
||||
self(self, src);
|
||||
}
|
||||
switch (node->op) {
|
||||
case GGML_OP_NONE:
|
||||
@@ -2885,9 +2941,6 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
|
||||
}
|
||||
}
|
||||
}
|
||||
// OPENVINO_ASSERT(dynamic_dim_value == node->ne[m_node_dynamic_dims[node]],
|
||||
// "Dynamic dim value mismatch for node: " + std::string(node->name) +
|
||||
// " and its src[1]: " + std::string(node->src[1]->name));
|
||||
}
|
||||
break;
|
||||
case GGML_OP_MUL:
|
||||
@@ -2904,7 +2957,6 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
|
||||
m_node_dynamic_dims[node] = -1;
|
||||
if (m_node_dynamic_dims[node->src[0]] != -1) {
|
||||
auto dynamic_dim_idx = m_node_dynamic_dims[node->src[0]];
|
||||
// auto dynamic_dim_value = node->src[0]->ne[dynamic_dim_idx];
|
||||
// src dim i moves to dim op_params[i]
|
||||
if (dynamic_dim_idx >= 0 && dynamic_dim_idx < GGML_MAX_DIMS) {
|
||||
m_node_dynamic_dims[node] = node->op_params[dynamic_dim_idx];
|
||||
@@ -3229,8 +3281,8 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
|
||||
visit_node(visit_node, node);
|
||||
}
|
||||
|
||||
// print the nodes in m_cgraph name & shape with the dynamic dim (the dynamic dim is the dimension with -1 in m_node_dynamic_dims) for debugging
|
||||
if (0) {
|
||||
// GGML_OPENVINO_DEBUG_DYNAMIC_DIMS: print each node and its sources with their shapes, '*' marking the dynamic dim
|
||||
if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_DYNAMIC_DIMS")) {
|
||||
for (int i = 0; i < m_cgraph->n_nodes; i++) {
|
||||
ggml_tensor * node = m_cgraph->nodes[i];
|
||||
int dynamic_dim = m_node_dynamic_dims[node];
|
||||
|
||||
@@ -47,6 +47,15 @@ struct ModelParams {
|
||||
// The attention masks that are graph inputs, by identity: gemma-4's KV-shared layers also read them through
|
||||
// GET_ROWS, which must resolve to the same OV parameter as the attention ops
|
||||
std::set<const ggml_tensor *> kq_masks;
|
||||
// gemma-4's KV-shared layers attend for the output rows only (prune_shared in src/models/gemma4.cpp): llama.cpp
|
||||
// copies their mask rows from the input masks on the host into separate inputs (out_mask, out_mask_swa), and
|
||||
// gathers their activations, positions and per-layer embeddings with an index list (inp_prune_ids). The static
|
||||
// models bind the input masks per prefill chunk, so these masks are not graph inputs: each maps to the input
|
||||
// mask it copies, and the OV model gathers its rows from that mask with inp_prune_ids instead.
|
||||
std::map<const ggml_tensor *, const ggml_tensor *> pruned_masks;
|
||||
const ggml_tensor * prune_ids = nullptr;
|
||||
// the output rows among the gathered rows (inp_prune_keep)
|
||||
const ggml_tensor * prune_keep = nullptr;
|
||||
|
||||
std::vector<std::string> kv_names;
|
||||
size_t kv_buffer_ctx_id = 0;
|
||||
@@ -86,7 +95,6 @@ struct ComputeParams {
|
||||
int swa_window = -1;
|
||||
int input_len = -1;
|
||||
int token_len_per_seq = -1;
|
||||
int past_kv_len = -1;
|
||||
int output_len = 1;
|
||||
|
||||
int cache_rs_reset_idx = -1;
|
||||
@@ -288,16 +296,38 @@ public:
|
||||
|
||||
virtual std::set<std::string> get_model_output_names() const override { return m_model_output_names; }
|
||||
|
||||
virtual std::set<std::string> get_cache_output_names() const override {
|
||||
std::set<std::string> names;
|
||||
for (const auto & name : m_model_output_names) {
|
||||
const ggml_tensor * tensor = m_model_outputs.at(name);
|
||||
if (is_kvcache(tensor, nullptr) || is_recurrent_cache(tensor)) {
|
||||
names.insert(name);
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
virtual bool is_kv_only_outputs() const override { return m_kv_only_outputs; }
|
||||
|
||||
// Convert the model with only the cache writes as outputs (GGML_OPENVINO_KV_ONLY_PREFILL); the conversion pipeline
|
||||
// then drops everything that only feeds the other outputs, see pass::KeepCacheResults.
|
||||
void set_kv_only_outputs(bool kv_only) { m_kv_only_outputs = kv_only; }
|
||||
|
||||
// GET_ROWS of a large host-resident weight table by graph-input ids (GGML_OPENVINO_NPU_HOST_GATHER): its rows
|
||||
// are gathered on the host and fed through the "ggml_host_rows_<node>" input instead of an OV Gather.
|
||||
static bool is_host_gather_rows(const ggml_tensor * node);
|
||||
static constexpr const char * host_rows_prefix = "ggml_host_rows_";
|
||||
const ggml_tensor * get_host_gather_rows(const std::string & input_name) const {
|
||||
auto it = m_host_gather_rows.find(input_name);
|
||||
return it == m_host_gather_rows.end() ? nullptr : it->second;
|
||||
}
|
||||
|
||||
const std::map<std::string, ggml_tensor *> & get_model_outputs() const { return m_model_outputs; }
|
||||
|
||||
virtual int get_ctx_size() const { return m_model_params.ctx; }
|
||||
|
||||
virtual int get_ctx_per_seq() const { return m_model_params.ctx_per_seq; }
|
||||
|
||||
virtual int get_ctx_per_seq_swa() const { return m_model_params.ctx_per_seq_swa; }
|
||||
|
||||
virtual int get_n_seq() const { return m_model_params.n_seq; }
|
||||
|
||||
virtual int is_swa_layer(int layer) const override {
|
||||
return std::find(m_model_params.swa_layers.begin(), m_model_params.swa_layers.end(), layer) !=
|
||||
m_model_params.swa_layers.end();
|
||||
@@ -318,14 +348,10 @@ public:
|
||||
return m_model_params.n_heads_kv;
|
||||
}
|
||||
|
||||
int get_past_kv_len() const { return m_compute_params.past_kv_len; }
|
||||
|
||||
int get_input_len() const { return m_compute_params.input_len; }
|
||||
|
||||
virtual int32_t * get_rope_params() const override { return const_cast<int32_t *>(m_model_params.rope_params); }
|
||||
|
||||
virtual bool has_mixed_rope_params() const override { return m_model_params.mixed_rope_params; }
|
||||
|
||||
virtual int get_ssm_state_size() const override { return m_model_params.state_size; }
|
||||
|
||||
virtual std::map<std::string, std::string> get_kv_param_res_names() const override;
|
||||
@@ -417,8 +443,6 @@ public:
|
||||
return v;
|
||||
}
|
||||
|
||||
const ggml_tensor * get_tensor_from_name(const std::string & name) const;
|
||||
|
||||
std::string get_hfa_history_input_name() const;
|
||||
|
||||
void clear_model_weights() { m_model_weights.clear(); }
|
||||
@@ -608,10 +632,6 @@ public:
|
||||
|
||||
bool is_direct_gdn_view(const ggml_tensor * node) const;
|
||||
|
||||
static bool is_cache(const ggml_tensor * tensor, const ggml_tensor * op) {
|
||||
return is_recurrent_cache(tensor) || is_kvcache(tensor, op);
|
||||
}
|
||||
|
||||
static bool is_kvcache(const ggml_tensor * tensor, const ggml_tensor * op) {
|
||||
if (tensor == nullptr || is_recurrent_cache(tensor)) {
|
||||
return false;
|
||||
@@ -697,6 +717,8 @@ public:
|
||||
|
||||
bool is_kq_mask(const ggml_tensor * tensor) const { return m_model_params.kq_masks.count(tensor) != 0; }
|
||||
|
||||
bool is_pruned_mask(const ggml_tensor * tensor) const { return m_model_params.pruned_masks.count(tensor) != 0; }
|
||||
|
||||
// A graph-input index list of GET_ROWS: out_ids, or the inp->s_copy leaf when build_rs gathers
|
||||
// every recurrent state at once.
|
||||
static bool is_get_rows_input_idx(const ggml_tensor * tensor, const ggml_tensor * op) {
|
||||
@@ -722,33 +744,6 @@ public:
|
||||
op->src[0]->buffer->usage == GGML_BACKEND_BUFFER_USAGE_ANY;
|
||||
}
|
||||
|
||||
std::string get_graph_input_ov_name(const ggml_tensor * tensor, const ggml_tensor * op) const {
|
||||
if (is_inp_pos(tensor, op)) {
|
||||
return "inp_pos";
|
||||
}
|
||||
if (is_inp_emb(tensor, op)) {
|
||||
return "embd";
|
||||
}
|
||||
if (is_inp_mask(tensor, op)) {
|
||||
// Give the two attention masks distinct OV parameter names.
|
||||
//
|
||||
// An interleaved-SWA model builds one full-attention mask and one sliding-window mask,
|
||||
// but build_attn_inp_kq_mask() names them identically, so keying a parameter off
|
||||
// tensor->name alone makes the second mask OVERWRITE the first in m_model_inputs: both
|
||||
// attention types then read a single parameter, and the windowed layers silently run
|
||||
// against an unbanded mask. Disambiguate using the SWA layer set computed in
|
||||
// compute_llm_params(), which classifies by mask tensor identity rather than by name.
|
||||
//
|
||||
// When no SWA layer was found there is only one mask in play, so the plain name is
|
||||
// correct and no _swa parameter is created.
|
||||
if (m_model_params.swa_layers.empty()) {
|
||||
return "self_kq_mask";
|
||||
}
|
||||
return is_swa_mask(tensor) ? "self_kq_mask_swa" : "self_kq_mask";
|
||||
}
|
||||
return tensor->name;
|
||||
}
|
||||
|
||||
private:
|
||||
void set_input_output();
|
||||
int compute_op_case(const ggml_tensor * node) const;
|
||||
@@ -776,6 +771,8 @@ private:
|
||||
std::set<std::string> m_model_output_names;
|
||||
// The output set the compiled model was built from, for has_same_graph_io().
|
||||
std::set<std::string> m_built_output_names;
|
||||
bool m_kv_only_outputs = false;
|
||||
std::map<std::string, const ggml_tensor *> m_host_gather_rows;
|
||||
std::vector<NodeInfo> m_node_info_list;
|
||||
std::map<ggml_tensor *, int> m_node_dynamic_dims;
|
||||
std::set<const ggml_tensor *> m_kvcache_4d;
|
||||
|
||||
@@ -162,6 +162,7 @@ constexpr env_var env_vars[] = {
|
||||
{"GGML_OPENVINO_DUMP_IR", env_type::BOOL},
|
||||
{"GGML_OPENVINO_DEBUG_INPUT", env_type::BOOL},
|
||||
{"GGML_OPENVINO_DEBUG_OUTPUT", env_type::BOOL},
|
||||
{"GGML_OPENVINO_DEBUG_DYNAMIC_DIMS", env_type::BOOL},
|
||||
// Force the static (NPU-shape) compute path on any device, e.g. GGML_OPENVINO_DEVICE=CPU,
|
||||
// to test the static-shape translation without NPUW/real NPU hardware in the loop.
|
||||
{"GGML_OPENVINO_FORCE_STATIC", env_type::BOOL},
|
||||
@@ -191,14 +192,12 @@ constexpr env_var env_vars[] = {
|
||||
{"GGML_OPENVINO_GDN_NATIVE_STATE", env_type::BOOL},
|
||||
{"GGML_OPENVINO_GDN_DECOMPOSE", env_type::BOOL},
|
||||
{"GGML_OPENVINO_NPU_L0_HOST_TENSORS", env_type::BOOL},
|
||||
{"GGML_OPENVINO_KV_SLICE", env_type::BOOL},
|
||||
{"GGML_OPENVINO_KV_SLICE", env_type::INT},
|
||||
{"GGML_OPENVINO_NPU_HFA_PREFILL", env_type::BOOL},
|
||||
{"GGML_OPENVINO_NPU_DECODE_UNFOLD", env_type::BOOL},
|
||||
{"GGML_OPENVINO_NPU_PARALLEL_COMPILE", env_type::BOOL},
|
||||
{"GGML_OPENVINO_SELF_CONTAINED_BLOB", env_type::BOOL},
|
||||
{"GGML_OPENVINO_SELF_CONTAINED_MMAP", env_type::BOOL},
|
||||
{"GGML_OPENVINO_NPU_SHARED_BANK", env_type::BOOL},
|
||||
{"GGML_OPENVINO_NPU_WEIGHTLESS_BANK", env_type::BOOL},
|
||||
{"GGML_OPENVINO_KV_ONLY_PREFILL", env_type::BOOL},
|
||||
{"GGML_OPENVINO_NPU_HOST_GATHER", env_type::BOOL},
|
||||
// Build the precise (but O(n_nodes)) graph cache key. Needed by op tests.
|
||||
{"GGML_OPENVINO_FULL_GRAPH_KEY", env_type::BOOL},
|
||||
};
|
||||
@@ -260,6 +259,12 @@ std::string checked_env_value(const env_var & var, const char * value) {
|
||||
if (!parse_env_int(value, number)) {
|
||||
GGML_ABORT("ggml-openvino: %s=%s is not valid, use a whole number", var.name, value);
|
||||
}
|
||||
if (std::strcmp(var.name, "GGML_OPENVINO_KV_SLICE") == 0 && number != 0 && number != 1 &&
|
||||
(number < 0 || number % 256 != 0)) {
|
||||
GGML_ABORT("ggml-openvino: %s=%s is not valid, use 0 (off), 1 (on) or a KV window size that is a multiple "
|
||||
"of 256",
|
||||
var.name, value);
|
||||
}
|
||||
return std::to_string(number);
|
||||
case env_type::FLOAT: {
|
||||
char * end = nullptr;
|
||||
@@ -548,10 +553,7 @@ std::string ggml_openvino_config_overrides_in_use() {
|
||||
|
||||
bool ggml_openvino_manual_gqa_enabled() {
|
||||
// set: a positive value enables it, 0 disables it; unset: on GPU only
|
||||
if (ggml_openvino_getenv_str("GGML_OPENVINO_MANUAL_GQA_ATTN") != nullptr) {
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0;
|
||||
}
|
||||
return ggml_openvino_is_gpu();
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN", ggml_openvino_is_gpu() ? 1 : 0) > 0;
|
||||
}
|
||||
|
||||
bool ggml_openvino_gdn_prescale_enabled() {
|
||||
@@ -580,10 +582,7 @@ bool ggml_openvino_npu_is_4000() {
|
||||
}
|
||||
|
||||
bool ggml_openvino_gdn_decompose_enabled() {
|
||||
if (ggml_openvino_getenv_str("GGML_OPENVINO_GDN_DECOMPOSE") != nullptr) {
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_GDN_DECOMPOSE") > 0;
|
||||
}
|
||||
return ggml_openvino_npu_is_4000();
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_GDN_DECOMPOSE", ggml_openvino_npu_is_4000() ? 1 : 0) > 0;
|
||||
}
|
||||
|
||||
int ggml_openvino_gdn_decompose_chunk() {
|
||||
@@ -607,19 +606,14 @@ float ggml_openvino_gdn_q_scale() {
|
||||
}
|
||||
|
||||
bool ggml_openvino_reduce_compile_mem_enabled() {
|
||||
const char * reduce_compile_mem = ggml_openvino_getenv_str("GGML_OPENVINO_REDUCE_COMPILE_MEM");
|
||||
if (reduce_compile_mem != nullptr) {
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_REDUCE_COMPILE_MEM") != 0;
|
||||
}
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE") != 0;
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_REDUCE_COMPILE_MEM",
|
||||
ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE")) != 0;
|
||||
}
|
||||
|
||||
bool ggml_openvino_release_weights_enabled() {
|
||||
const char * release_weights = ggml_openvino_getenv_str("GGML_OPENVINO_RELEASE_WEIGHTS");
|
||||
if (release_weights != nullptr) {
|
||||
return ggml_openvino_is_gpu() && ggml_openvino_getenv_int("GGML_OPENVINO_RELEASE_WEIGHTS") != 0;
|
||||
}
|
||||
return ggml_openvino_is_gpu() && ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE") != 0;
|
||||
return ggml_openvino_is_gpu() &&
|
||||
ggml_openvino_getenv_int("GGML_OPENVINO_RELEASE_WEIGHTS",
|
||||
ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE")) != 0;
|
||||
}
|
||||
|
||||
// Check if running on NPU
|
||||
@@ -635,8 +629,13 @@ bool ggml_openvino_is_gpu() {
|
||||
return has_prefix(ggml_openvino_get_device_name(), "GPU");
|
||||
}
|
||||
|
||||
int ggml_openvino_kv_slice_base() {
|
||||
const int value = ggml_openvino_getenv_int("GGML_OPENVINO_KV_SLICE", 1);
|
||||
return value <= 0 ? 0 : value == 1 ? 1024 : value;
|
||||
}
|
||||
|
||||
bool ggml_openvino_kv_slice_enabled() {
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_KV_SLICE", 1) != 0;
|
||||
return ggml_openvino_kv_slice_base() > 0;
|
||||
}
|
||||
|
||||
bool ggml_openvino_npu_fast_mask_enabled() {
|
||||
@@ -655,26 +654,15 @@ bool ggml_openvino_npu_decode_unfold_enabled() {
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_DECODE_UNFOLD") != 0;
|
||||
}
|
||||
|
||||
bool ggml_openvino_npu_parallel_compile_enabled() {
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_PARALLEL_COMPILE") != 0;
|
||||
}
|
||||
|
||||
int ggml_openvino_npu_decode_bucket() {
|
||||
if (!ggml_openvino_is_npu()) {
|
||||
return 0;
|
||||
}
|
||||
// A self-contained blob embeds its weights bank, and NPUW cannot load a blob into a bank that already holds
|
||||
// weights, so a decode model per KV window cannot be imported next to the decode model of the pair.
|
||||
if (ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR") &&
|
||||
ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_BLOB") != 0 &&
|
||||
!ggml_openvino_npu_weightless_bank_enabled()) {
|
||||
return 0;
|
||||
}
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_BLOB_PREBUILD", 1) != 0 ? 1024 : 0;
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_BLOB_PREBUILD", 1) != 0 ? ggml_openvino_kv_slice_base() : 0;
|
||||
}
|
||||
|
||||
int ggml_openvino_static_kv_window(int rows, int ctx) {
|
||||
int window = 1;
|
||||
int ggml_openvino_static_kv_window(int rows, int ctx, int base) {
|
||||
int window = std::max(base, 1);
|
||||
while (window < rows && window < ctx) {
|
||||
window *= 2;
|
||||
}
|
||||
@@ -683,7 +671,7 @@ int ggml_openvino_static_kv_window(int rows, int ctx) {
|
||||
|
||||
int ggml_openvino_gpu_kv_window(int rows, int ctx, int n_tokens) {
|
||||
if (n_tokens > 16) {
|
||||
return ggml_openvino_static_kv_window(rows, ctx);
|
||||
return ggml_openvino_static_kv_window(rows, ctx, 1);
|
||||
}
|
||||
// a multiple of 256 and of 2^k / 4, where 2^k <= rows < 2^(k+1)
|
||||
int step = 256;
|
||||
@@ -702,13 +690,22 @@ bool ggml_openvino_npu_kv_head_major_enabled() {
|
||||
ggml_openvino_kv_slice_enabled();
|
||||
}
|
||||
|
||||
bool ggml_openvino_npu_raw_weight_cache_enabled() {
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_BLOB") != 0 ||
|
||||
ggml_openvino_npu_weightless_bank_enabled();
|
||||
bool ggml_openvino_npu_host_gather_enabled() {
|
||||
return ggml_openvino_is_npu() && ggml_openvino_getenv_int("GGML_OPENVINO_NPU_HOST_GATHER") != 0;
|
||||
}
|
||||
|
||||
bool ggml_openvino_npu_weightless_bank_enabled() {
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_WEIGHTLESS_BANK") != 0;
|
||||
bool ggml_openvino_kv_only_prefill_enabled() {
|
||||
// On by default; it only takes effect for graphs with KV-shared layers.
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_KV_ONLY_PREFILL", 1) != 0;
|
||||
}
|
||||
|
||||
bool ggml_openvino_npu_weightless_cache_enabled() {
|
||||
return ggml_openvino_is_npu() && ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR") != nullptr;
|
||||
}
|
||||
|
||||
bool ggml_openvino_self_contained_mmap_enabled() {
|
||||
return ggml_openvino_npu_weightless_cache_enabled() &&
|
||||
ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_MMAP") != 0;
|
||||
}
|
||||
|
||||
namespace {
|
||||
@@ -768,8 +765,8 @@ bool kv_grow_locked(kv_storage_entry & e, size_t rows, size_t heads) {
|
||||
if (rows <= e.cap_rows) {
|
||||
return false;
|
||||
}
|
||||
const int bucket = ggml_openvino_npu_decode_bucket();
|
||||
size_t cap = bucket > 0 ? static_cast<size_t>(bucket) : 1024;
|
||||
const int base = ggml_openvino_kv_slice_base();
|
||||
size_t cap = base > 0 ? static_cast<size_t>(base) : 1024;
|
||||
while (cap < rows) {
|
||||
cap *= 2;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
#define CL_TARGET_OPENCL_VERSION 300
|
||||
#include <CL/cl.h>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <openvino/core/node.hpp>
|
||||
@@ -140,10 +139,14 @@ bool ggml_openvino_is_static();
|
||||
// KV-cache slicing: bind the KV cache, and size the KQ masks, at the attended length instead of the full context.
|
||||
// One mechanism, two modes:
|
||||
// dynamic graphs (CPU/GPU): the KV input is a view over the cache; the graph is not recompiled.
|
||||
// static graphs (NPU, or any device with GGML_OPENVINO_FORCE_STATIC): the prefill graph is compiled at the aligned
|
||||
// attended length and recompiled when it changes; decode keeps the full context.
|
||||
// On by default for all devices; GGML_OPENVINO_KV_SLICE=0 turns it off.
|
||||
// static graphs (NPU, or any device with GGML_OPENVINO_FORCE_STATIC): the prefill graph is compiled at a KV window of
|
||||
// base*2^k rows (clamped to ctx) covering the attended length and recompiled when it changes; decode keeps the
|
||||
// full context unless NPU decode KV windows are on (see ggml_openvino_npu_decode_bucket).
|
||||
// GGML_OPENVINO_KV_SLICE: unset or 1 = on with window base 1024, N (a multiple of 256) = on with window base N,
|
||||
// 0 = off. CPU/GPU dynamic graphs only use it as on/off.
|
||||
bool ggml_openvino_kv_slice_enabled();
|
||||
// Static KV window base of GGML_OPENVINO_KV_SLICE, 0 = off.
|
||||
int ggml_openvino_kv_slice_base();
|
||||
|
||||
// On by default: back NPU buffers with Level Zero host memory; GGML_OPENVINO_NPU_L0_HOST_TENSORS=0 turns it off.
|
||||
bool ggml_openvino_npu_l0_host_tensors_enabled();
|
||||
@@ -155,17 +158,28 @@ bool ggml_openvino_npu_fast_mask_enabled();
|
||||
// env-var name lives in one place; see docs/backend/OPENVINO.md for semantics.
|
||||
bool ggml_openvino_npu_hfa_prefill_enabled();
|
||||
bool ggml_openvino_npu_decode_unfold_enabled();
|
||||
bool ggml_openvino_npu_parallel_compile_enabled();
|
||||
// Static path (NPU, or any device with GGML_OPENVINO_FORCE_STATIC): prefill only the KV-writing part of the model
|
||||
// and compute the logits with one decode step. Pays off for models whose tail layers share earlier layers' KV
|
||||
// (Gemma 3n/4 E-series), where it skips those layers for prompt tokens. On by default (it only applies to graphs
|
||||
// with KV-shared attention, at most one output token per batch, and no HFA prefill);
|
||||
// GGML_OPENVINO_KV_ONLY_PREFILL=0 turns it off.
|
||||
bool ggml_openvino_kv_only_prefill_enabled();
|
||||
// Gather the rows of large embedding tables on the host and feed them to the static graph as an input, instead of
|
||||
// binding the whole table to the NPU (NPUW lifts it to a function input, and gathering from an input that large
|
||||
// costs about as much as streaming the table).
|
||||
bool ggml_openvino_npu_host_gather_enabled();
|
||||
|
||||
// GGML_OPENVINO_NPU_BLOB_PREBUILD (default 1): static NPU graphs attend a KV window of 1024*2^k rows (clamped to ctx)
|
||||
// instead of the whole ctx, with one decode model per window, all built/imported with the prefill/decode pair;
|
||||
// with head-major KV the prefill models of every window are also exported and preloaded.
|
||||
// Returns the window base (1024), 0 = off (GGML_OPENVINO_NPU_BLOB_PREBUILD=0).
|
||||
// GGML_OPENVINO_NPU_BLOB_PREBUILD (default 1), with GGML_OPENVINO_KV_SLICE on: static NPU decode also attends a KV
|
||||
// window of base*2^k rows (clamped to ctx, base from GGML_OPENVINO_KV_SLICE) instead of the whole ctx, with one
|
||||
// decode model per window, all built/imported with the prefill/decode pair.
|
||||
// The prefill windows are aligned to the decode windows, and with the weightless bank the prefill models of every
|
||||
// window are exported too (and preloaded with head-major KV).
|
||||
// Returns the window base, 0 = off (GGML_OPENVINO_NPU_BLOB_PREBUILD=0 or GGML_OPENVINO_KV_SLICE=0: decode attends
|
||||
// the full ctx).
|
||||
int ggml_openvino_npu_decode_bucket();
|
||||
|
||||
// Rows a static prefill attends with GGML_OPENVINO_KV_SLICE: the attended length rounded up to a power of two,
|
||||
// clamped to ctx.
|
||||
int ggml_openvino_static_kv_window(int rows, int ctx);
|
||||
// Smallest base*2^k covering rows, clamped to ctx.
|
||||
int ggml_openvino_static_kv_window(int rows, int ctx, int base);
|
||||
|
||||
// Rows the dynamic GPU graph attends for a batch of n_tokens tokens per sequence, clamped to ctx. The GPU plugin keeps
|
||||
// memory for each attended length, so a long context should use a few lengths:
|
||||
@@ -176,18 +190,19 @@ int ggml_openvino_static_kv_window(int rows, int ctx);
|
||||
int ggml_openvino_gpu_kv_window(int rows, int ctx, int n_tokens);
|
||||
|
||||
// On-demand NPU KV cache (GGML_OPENVINO_NPU_KV_ON_DEMAND): the ggml KV buffer stays non-resident and the
|
||||
// NPU binds per-tensor L0 storage that grows (base*2^k rows, base = decode bucket or 1024) with the rows in use.
|
||||
// NPU binds per-tensor L0 storage that grows (base*2^k rows, base = KV_SLICE window base or 1024) with the rows in use.
|
||||
bool ggml_openvino_npu_kv_on_demand_enabled();
|
||||
// On-demand KV with BLOB_PREBUILD and KV_SLICE: K storage is [heads][rows][head_size] and V storage is
|
||||
// [heads][head_size][rows] (head-major with heads * head_size channels); every static graph binds the whole storage
|
||||
// as [1, heads, rows, head_size] / [1, heads, head_size, rows], and attention uses V^T.
|
||||
bool ggml_openvino_npu_kv_head_major_enabled();
|
||||
|
||||
// NPU blob cache modes that keep the raw GGUF weights and skip requantization on a warm hit:
|
||||
// GGML_OPENVINO_SELF_CONTAINED_BLOB (weights embedded in each blob) or
|
||||
// GGML_OPENVINO_NPU_WEIGHTLESS_BANK (weightless blobs plus one shared weights file).
|
||||
bool ggml_openvino_npu_raw_weight_cache_enabled();
|
||||
bool ggml_openvino_npu_weightless_bank_enabled();
|
||||
// NPU with GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR: graphs with a KV cache are cached as weightless blobs plus one
|
||||
// shared weights file. Valid blobs are imported; otherwise the models are compiled and exported. The raw GGUF
|
||||
// weights are kept, and requantization is skipped on a warm hit.
|
||||
bool ggml_openvino_npu_weightless_cache_enabled();
|
||||
// GGML_OPENVINO_SELF_CONTAINED_MMAP=1 with the NPU weightless cache
|
||||
bool ggml_openvino_self_contained_mmap_enabled();
|
||||
void ggml_openvino_kv_storage_register(void * data, size_t row_bytes, size_t rows);
|
||||
void ggml_openvino_kv_storage_unregister(const void * base, size_t size);
|
||||
// Storage address backing ggml address `ptr` with at least `bytes` valid (grown if needed);
|
||||
|
||||
@@ -31,9 +31,6 @@
|
||||
#include <openvino/runtime/intel_npu/level_zero/level_zero.hpp>
|
||||
#include <openvino/runtime/properties.hpp>
|
||||
#include <openvino/runtime/tensor.hpp>
|
||||
#include <algorithm>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
#include <vector>
|
||||
@@ -98,8 +95,6 @@ struct ggml_backend_openvino_buffer_context {
|
||||
std::map<const void *, uint64_t> weight_fingerprints;
|
||||
std::vector<ggml_openvino_source_mapping> source_mappings;
|
||||
|
||||
// Used for re-allocation on device for kvcache
|
||||
void * data_prev = nullptr;
|
||||
// data is in the weight buffer registry
|
||||
bool weight_registered = false;
|
||||
|
||||
@@ -149,10 +144,7 @@ struct ggml_backend_openvino_buffer_context {
|
||||
// commits/zeroes it eagerly (fully resident). For such large buffers, reserve
|
||||
// demand-zero pages instead (no L0, no memset) so they stay non-resident. KV and small
|
||||
// I/O buffers keep the L0 host tensor for zero-copy import (decode throughput).
|
||||
const bool strict_mmap = device_name == "NPU" &&
|
||||
ggml_openvino_npu_raw_weight_cache_enabled() &&
|
||||
ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_MMAP") &&
|
||||
ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR");
|
||||
const bool strict_mmap = device_name == "NPU" && ggml_openvino_self_contained_mmap_enabled();
|
||||
// 2 GiB keeps a large-context KV cache (~1 GiB at ctx 8K) on L0 while the bigger prefill
|
||||
// compute buffer still goes lazy.
|
||||
const size_t lazy_host_threshold =
|
||||
@@ -391,12 +383,6 @@ static bool is_stateful_enabled() {
|
||||
return ggml_openvino_getenv_int("GGML_OPENVINO_STATEFUL_EXECUTION") != 0;
|
||||
}
|
||||
|
||||
static bool is_self_contained_mmap_enabled() {
|
||||
return ggml_openvino_is_npu() && ggml_openvino_npu_raw_weight_cache_enabled() &&
|
||||
ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_MMAP") &&
|
||||
ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR");
|
||||
}
|
||||
|
||||
// Stores extra as the tensor's extra, deleting the one it replaces
|
||||
static void ggml_openvino_set_extra(ggml_backend_openvino_buffer_context * ctx,
|
||||
ggml_tensor * tensor,
|
||||
@@ -431,7 +417,6 @@ static bool ggml_openvino_swap_buffer_context(ggml_backend_buffer_t buffer,
|
||||
}
|
||||
|
||||
static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
|
||||
// GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
|
||||
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
|
||||
|
||||
// Put kvcache on device memory for GPU (NPU memory is too small even for kvcache). Same for the speculative
|
||||
@@ -505,7 +490,6 @@ static void ggml_backend_openvino_buffer_memset_tensor(ggml_backend_buffer_t buf
|
||||
uint8_t value,
|
||||
size_t offset,
|
||||
size_t size) {
|
||||
// GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
|
||||
GGML_ASSERT(tensor != nullptr && tensor->data != nullptr);
|
||||
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
|
||||
|
||||
@@ -617,7 +601,6 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
|
||||
const void * data,
|
||||
size_t offset,
|
||||
size_t size) {
|
||||
// GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
|
||||
GGML_ASSERT(tensor != nullptr && tensor->data != nullptr);
|
||||
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
|
||||
|
||||
@@ -642,10 +625,9 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
|
||||
bool is_supported_weight_shape = is_2d || (tensor->ne[3] == 1 && ggml_is_quantized(tensor->type));
|
||||
|
||||
if (is_weight_buffer && is_full_tensor_set && is_supported_weight_shape) {
|
||||
if (ggml_openvino_is_npu() && ggml_openvino_npu_raw_weight_cache_enabled() &&
|
||||
ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR")) {
|
||||
if (ggml_openvino_npu_weightless_cache_enabled()) {
|
||||
// Keep raw bytes for cache fingerprint validation and compile fallback; the imported
|
||||
// self-contained blob supplies the runtime weights, so eager requant is unnecessary.
|
||||
// blob supplies the runtime weights, so eager requant is unnecessary.
|
||||
memcpy(tensor->data, data, size);
|
||||
return;
|
||||
}
|
||||
@@ -653,32 +635,15 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
|
||||
auto result = process_weight_tensor(tensor, data, tensor->data);
|
||||
result.weight_node->set_friendly_name(tensor->name);
|
||||
|
||||
// const auto & layout = result.layout;
|
||||
ggml_openvino_extra_base * extra;
|
||||
|
||||
// Quantized path with extracted weight/scale/zp tensors
|
||||
if (result.is_quantized()) {
|
||||
extra = new ggml_openvino_quantized_weight_extra(std::move(result.weights), std::move(result.scales),
|
||||
std::move(result.zp), result.weight_node);
|
||||
|
||||
// if (layout.is_requant) {
|
||||
// GGML_LOG_DEBUG("%s: requantized %s to %s (u%d, block_size=%ld)\n", __func__, tensor->name,
|
||||
// extra_quant_type_name(layout.requant_type.value()), layout.is_u4 ? 4 : 8,
|
||||
// layout.weights_per_block);
|
||||
// } else {
|
||||
// int64_t n_blocks = ggml_nelements(tensor) / layout.weights_per_block;
|
||||
// GGML_LOG_DEBUG("%s: extracted quantized weight node for %s (u%d, %zu weights, %ld blocks)\n",
|
||||
// __func__, tensor->name, layout.is_u4 ? 4 : 8, layout.weights_size, n_blocks);
|
||||
// }
|
||||
} else {
|
||||
// F16/F32/BF16 weight or F16-requant
|
||||
extra = new ggml_openvino_weight_extra(std::move(result.weights), result.weight_node);
|
||||
|
||||
// if (layout.total_size > 0) {
|
||||
// GGML_LOG_DEBUG("%s: requantized %s to F16\n", __func__, tensor->name);
|
||||
// } else {
|
||||
// GGML_LOG_DEBUG("%s: created shared-memory weight node for %s\n", __func__, tensor->name);
|
||||
// }
|
||||
}
|
||||
|
||||
ggml_openvino_set_extra(ctx, tensor, extra);
|
||||
@@ -804,7 +769,6 @@ static void ggml_backend_openvino_buffer_get_tensor(ggml_backend_buffer_t buffer
|
||||
void * data,
|
||||
size_t offset,
|
||||
size_t size) {
|
||||
// GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
|
||||
GGML_ASSERT(tensor != nullptr && tensor->data != nullptr);
|
||||
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
|
||||
|
||||
@@ -843,7 +807,6 @@ static void ggml_backend_openvino_buffer_get_tensor(ggml_backend_buffer_t buffer
|
||||
static bool ggml_backend_openvino_buffer_cpy_tensor(ggml_backend_buffer_t buffer,
|
||||
const ggml_tensor * src,
|
||||
ggml_tensor * dst) {
|
||||
// GGML_LOG_DEBUG("%s: src tensor name=%s, dst tensor name=%s\n", __func__, src->name, dst->name);
|
||||
GGML_ASSERT(src != nullptr && dst != nullptr);
|
||||
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
|
||||
|
||||
@@ -978,7 +941,7 @@ static size_t ggml_backend_openvino_buffer_type_get_alloc_size(ggml_backend_buff
|
||||
const ggml_tensor * tensor) {
|
||||
GGML_UNUSED(buft);
|
||||
|
||||
if (is_self_contained_mmap_enabled()) {
|
||||
if (ggml_openvino_self_contained_mmap_enabled()) {
|
||||
return ggml_nbytes(tensor);
|
||||
}
|
||||
|
||||
@@ -1178,7 +1141,6 @@ static void ggml_backend_openvino_free(ggml_backend_t backend) {
|
||||
// reuses it instead of recompiling against zeroed weights.
|
||||
if (!ggml_openvino_weight_buffers_released()) {
|
||||
cache->graphs.clear();
|
||||
ov_clear_imported_blobs();
|
||||
std::lock_guard<std::mutex> fingerprints_lock(g_fallback_fingerprints_mutex);
|
||||
g_fallback_fingerprints.clear();
|
||||
}
|
||||
@@ -1455,7 +1417,7 @@ static void ggml_backend_openvino_device_get_props(ggml_backend_dev_t dev, ggml_
|
||||
props->caps = {
|
||||
/* .async = */ false,
|
||||
/* .host_buffer = */ false,
|
||||
/* .buffer_from_host_ptr = */ is_self_contained_mmap_enabled(),
|
||||
/* .buffer_from_host_ptr = */ ggml_openvino_self_contained_mmap_enabled(),
|
||||
/* .events = */ false,
|
||||
/* .mmap_support = */ true,
|
||||
/* .fast_async_host_input = */ false,
|
||||
@@ -1685,6 +1647,13 @@ static bool cpy_output_view_is_supported(const ggml_tensor * op) {
|
||||
GgmlOvDecoder::is_gdn_snapshot_writeback(op) || GgmlOvDecoder::is_ssm_state_writeback(op);
|
||||
}
|
||||
|
||||
// SET_ROWS writes whole rows of a contiguous destination. Other destination views (e.g. a permuted view of a
|
||||
// state tensor) are supported only for the recognized cache writes.
|
||||
static bool set_rows_output_view_is_supported(const ggml_tensor * op) {
|
||||
return op->view_src == nullptr || ggml_nbytes(op) == 0 || ggml_is_contiguous(op) ||
|
||||
GgmlOvDecoder::is_column_set_rows(op) || GgmlOvDecoder::is_conv_state_snapshot_writeback(op);
|
||||
}
|
||||
|
||||
static bool mul_mat_id_requires_large_tmp(const ggml_tensor * op) {
|
||||
const ggml_tensor * as = op->src[0];
|
||||
const ggml_tensor * ids = op->src[2];
|
||||
@@ -1795,6 +1764,9 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
|
||||
if (op->op == GGML_OP_SET_ROWS && op->src[0]->type == GGML_TYPE_BF16) {
|
||||
return {false, "SET_ROWS with BF16 src0 is not supported"};
|
||||
}
|
||||
if (op->op == GGML_OP_SET_ROWS && !set_rows_output_view_is_supported(op)) {
|
||||
return {false, "SET_ROWS with non-contiguous output view is not supported"};
|
||||
}
|
||||
if (op->ne[0] == 256 && (op->src[0]->type == GGML_TYPE_Q4_K || op->src[0]->type == GGML_TYPE_Q5_K ||
|
||||
op->src[0]->type == GGML_TYPE_Q4_1 || op->src[0]->type == GGML_TYPE_Q5_1)) {
|
||||
// These are all f16-arithmetic dequant rounding errors that intermittently exceed the
|
||||
@@ -2335,10 +2307,6 @@ static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(gg
|
||||
if (!supported) {
|
||||
return {false, "op " + std::string(ggml_op_name(op->op)) + " has no op translator"};
|
||||
}
|
||||
static std::set<ggml_op> ops_not_support_view_input{};
|
||||
if (ops_not_support_view_input.find(op->op) != ops_not_support_view_input.end() && has_view_op_input(op)) {
|
||||
return {false, "op " + std::string(ggml_op_name(op->op)) + " with VIEW input is not supported"};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,29 +8,6 @@
|
||||
|
||||
static constexpr size_t GGML_QUANTIZATION_GROUP_SIZE = 32;
|
||||
|
||||
inline const char * extra_quant_type_name(ExtraQuantType t) {
|
||||
switch (t) {
|
||||
case ExtraQuantType::F16:
|
||||
return "F16";
|
||||
case ExtraQuantType::Q4_0_C:
|
||||
return "Q4_0_C";
|
||||
case ExtraQuantType::Q4_0_128:
|
||||
return "Q4_0_128";
|
||||
case ExtraQuantType::Q8_0_C:
|
||||
return "Q8_0_C";
|
||||
case ExtraQuantType::Q8_0_32:
|
||||
return "Q8_0_32";
|
||||
case ExtraQuantType::Q8_1_C:
|
||||
return "Q8_1_C";
|
||||
case ExtraQuantType::Q4_0_64:
|
||||
return "Q4_0_64";
|
||||
case ExtraQuantType::Q4_1_64:
|
||||
return "Q4_1_64";
|
||||
default:
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
// Result from process_weight_tensor containing the weight node and tensors.
|
||||
// For quantized weights, also contains the extracted layout and scale/zp tensors.
|
||||
struct OvWeight {
|
||||
|
||||
@@ -7,20 +7,21 @@
|
||||
#include "ggml-openvino-extra.h"
|
||||
#include "openvino/rt_info/weightless_caching_attributes.hpp"
|
||||
|
||||
#include <cerrno>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <limits>
|
||||
#include <sstream>
|
||||
#include <openvino/core/model.hpp>
|
||||
#include <openvino/core/version.hpp>
|
||||
#include <openvino/op/constant.hpp>
|
||||
#include <string>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <system_error>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
@@ -113,50 +114,12 @@ std::string hex64(uint64_t v) {
|
||||
return std::string(buf);
|
||||
}
|
||||
|
||||
// Portable mkdir for a single path component. Returns true if the directory
|
||||
// exists after the call (created now or already present).
|
||||
bool make_dir(const std::string & path) {
|
||||
#if defined(_WIN32)
|
||||
int rc = _mkdir(path.c_str());
|
||||
#else
|
||||
int rc = ::mkdir(path.c_str(), 0755);
|
||||
#endif
|
||||
if (rc == 0 || errno == EEXIST) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Create `path` and any missing parents (like `mkdir -p`). Best-effort:
|
||||
// returns true only if the full directory exists afterwards.
|
||||
bool make_dirs(const std::string & path) {
|
||||
if (path.empty()) {
|
||||
return false;
|
||||
}
|
||||
std::string acc;
|
||||
for (size_t i = 0; i < path.size(); ++i) {
|
||||
const char c = path[i];
|
||||
acc.push_back(c);
|
||||
const bool sep = (c == '/'
|
||||
#if defined(_WIN32)
|
||||
|| c == '\\'
|
||||
#endif
|
||||
);
|
||||
// Create each intermediate component (skip a leading "/" root).
|
||||
if (sep && acc.size() > 1) {
|
||||
std::string component = acc.substr(0, acc.size() - 1);
|
||||
#if defined(_WIN32)
|
||||
// A drive root such as "D:" cannot be mkdir'ed (EACCES, not EEXIST).
|
||||
if (component.size() == 2 && component[1] == ':') {
|
||||
continue;
|
||||
}
|
||||
#endif
|
||||
if (!make_dir(component)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return make_dir(path);
|
||||
// Create `path` and any missing parents (like `mkdir -p`). True if the directory exists afterwards.
|
||||
bool make_dirs(const std::string & path, std::error_code & ec) {
|
||||
const auto fs_path = std::filesystem::u8path(path);
|
||||
std::filesystem::create_directories(fs_path, ec);
|
||||
std::error_code ec_dir;
|
||||
return std::filesystem::is_directory(fs_path, ec_dir);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -179,10 +142,8 @@ static const char * cache_settings[] = {
|
||||
"GGML_OPENVINO_EXACT_ZERO_POINT",
|
||||
"GGML_OPENVINO_STATEFUL_EXECUTION",
|
||||
"GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT",
|
||||
"GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS",
|
||||
"GGML_OPENVINO_REDUCE_COMPILE_MEM",
|
||||
"GGML_OPENVINO_MEMORY_OPTIMIZE",
|
||||
"GGML_OPENVINO_PROFILING",
|
||||
"GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK",
|
||||
"GGML_OPENVINO_KV_SCATTER_ELEMENTS",
|
||||
"GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN",
|
||||
@@ -337,9 +298,10 @@ std::string ggml_openvino_model_cache_dir() {
|
||||
// Create the cache directory (and parents) on first use so callers don't
|
||||
// have to pre-create it; a missing dir would otherwise silently disable the
|
||||
// cache (manifest/blob writes fail with no directory to write into).
|
||||
if (!make_dirs(path)) {
|
||||
GGML_LOG_WARN("ggml-openvino: could not create model cache dir '%s' (errno=%d); caching disabled\n",
|
||||
path.c_str(), errno);
|
||||
std::error_code ec;
|
||||
if (!make_dirs(path, ec)) {
|
||||
GGML_LOG_WARN("ggml-openvino: could not create model cache dir '%s' (%s); caching disabled\n", path.c_str(),
|
||||
ec.message().c_str());
|
||||
return std::string();
|
||||
}
|
||||
return path;
|
||||
@@ -370,13 +332,16 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph,
|
||||
// Version 7 reads ROPE frequency factors named other than rope_freqs.weight as a Constant, not a Parameter.
|
||||
// Version 8 drops result_norm from the outputs when it has a consumer, and hashes the output flags.
|
||||
// Version 9 hashes GGML_OPENVINO_ROPE_F32_ANGLE, which became opt-in.
|
||||
h = fnv1a_u64(h, 9);
|
||||
// Version 10 hashes only whether GGML_OPENVINO_PROFILING is 2 or more (it then compiles with enable_profiling),
|
||||
// and no longer GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS, which only changes the output bindings.
|
||||
h = fnv1a_u64(h, 10);
|
||||
h = fnv1a(h, graph_signature.data(), graph_signature.size());
|
||||
for (const char * name : cache_settings) {
|
||||
const char * value = ggml_openvino_getenv_str(name, "");
|
||||
h = fnv1a(h, value, strlen(value) + 1);
|
||||
}
|
||||
h = fnv1a_u64(h, ggml_openvino_gdn_decompose_enabled() ? ggml_openvino_gdn_decompose_chunk() : 0);
|
||||
h = fnv1a_u64(h, ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING") >= 2 ? 1 : 0);
|
||||
if (const char * debug_nodes = ggml_openvino_getenv_str("GGML_OPENVINO_DEBUG_NODE")) {
|
||||
h = fnv1a(h, "GGML_OPENVINO_DEBUG_NODE", sizeof("GGML_OPENVINO_DEBUG_NODE"));
|
||||
h = fnv1a(h, debug_nodes, strlen(debug_nodes) + 1);
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
// Compiled blobs include weights. Cache-only execution skips weight uploads and graph compilation.
|
||||
// On NPU, GGML_OPENVINO_SELF_CONTAINED_BLOB=1 exports embedded-weight prefill/decode
|
||||
// blobs. A warm hit skips weight requantization, graph conversion, and compilation,
|
||||
// at the cost of roughly model-size storage per blob and separate NPUW weight banks.
|
||||
// After both blobs exist, GGML_OPENVINO_SELF_CONTAINED_MMAP=1 additionally wraps the
|
||||
// GGUF mmap instead of allocating the private OpenVINO model buffer. This mode is
|
||||
// import-only and fails clearly if either required blob is missing or invalid.
|
||||
// GGML_OPENVINO_NPU_WEIGHTLESS_BANK=1 is the same raw-weight flow, but exports weightless
|
||||
// prefill/decode blobs plus ONE <weights_fp>-<weights_fp>.weights.bin shared by every prefill/decode pair
|
||||
// of the model (pairs differ only in KV window). Warm import reads the weights from that file
|
||||
// (ov::weights_path) and NPUW deduplicates all models into one bank
|
||||
// (no OpenVINO patch needed), so the weights are stored once on disk and resident once.
|
||||
// On NPU, GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR imports the cached prefill/decode blobs when they are
|
||||
// valid; otherwise it compiles them and exports weightless blobs plus ONE
|
||||
// <weights_fp>-<weights_fp>.weights.bin shared by every prefill/decode pair of the model (pairs differ
|
||||
// only in KV window), with a warning. Import reads the weights from that file (ov::weights_path) and NPUW
|
||||
// deduplicates all models into one bank, so the weights are stored once on disk and resident once.
|
||||
// GGML_OPENVINO_SELF_CONTAINED_MMAP=1 additionally wraps the GGUF mmap instead of allocating the private
|
||||
// OpenVINO model buffer. This mode is import-only and fails clearly if a required blob is missing.
|
||||
|
||||
#include "ggml.h"
|
||||
|
||||
@@ -84,7 +80,7 @@ bool ggml_openvino_model_cache_verify_manifest(const std::string & path,
|
||||
std::vector<std::string> & inputs,
|
||||
std::vector<std::string> & outputs);
|
||||
|
||||
// GGML_OPENVINO_NPU_WEIGHTLESS_BANK: a weights file shared by weightless blobs. Every weightless-tagged
|
||||
// NPU cache: a weights file shared by weightless blobs. Every weightless-tagged
|
||||
// Constant is one region keyed by its data pointer (NPUW maps a Constant to its file offset by pointer).
|
||||
struct ggml_openvino_weights_layout {
|
||||
std::string path;
|
||||
|
||||
@@ -111,11 +111,14 @@ public:
|
||||
virtual const std::map<std::string, ModelExtraInputInfo> & get_model_extra_inputs() const = 0;
|
||||
virtual const std::map<std::string, std::shared_ptr<ov::Node>> & get_model_weights() const = 0;
|
||||
virtual std::set<std::string> get_model_output_names() const = 0;
|
||||
// KV-only prefill (GGML_OPENVINO_KV_ONLY_PREFILL): the model keeps only the cache outputs, see
|
||||
// pass::KeepCacheResults.
|
||||
virtual bool is_kv_only_outputs() const { return false; }
|
||||
// The outputs that write a KV or recurrent cache.
|
||||
virtual std::set<std::string> get_cache_output_names() const { return {}; }
|
||||
|
||||
virtual int32_t * get_rope_params() const = 0;
|
||||
|
||||
virtual bool has_mixed_rope_params() const = 0;
|
||||
|
||||
virtual int get_ssm_state_size() const = 0;
|
||||
|
||||
virtual std::map<std::string, std::string> get_kv_param_res_names() const = 0;
|
||||
|
||||
@@ -16,21 +16,15 @@ typedef std::map<std::string, Output<Node>> TensorMap;
|
||||
|
||||
class NodeContext : public frontend::NodeContext {
|
||||
public:
|
||||
NodeContext(const std::shared_ptr<GgmlDecoder> & decoder,
|
||||
std::shared_ptr<TensorMap> & tensor_map,
|
||||
int node_idx,
|
||||
TranslateSession * translate_session = nullptr) :
|
||||
NodeContext(const std::shared_ptr<GgmlDecoder> & decoder, std::shared_ptr<TensorMap> & tensor_map, int node_idx) :
|
||||
ov::frontend::NodeContext(decoder->get_op_type(node_idx)),
|
||||
m_decoder(decoder),
|
||||
m_tensor_map(tensor_map),
|
||||
m_node_idx(node_idx),
|
||||
m_translate_session(translate_session) {
|
||||
m_node_idx(node_idx) {
|
||||
m_input_names = decoder->get_input_names(m_node_idx);
|
||||
m_output_names = decoder->get_output_names(m_node_idx);
|
||||
}
|
||||
|
||||
TranslateSession * get_translate_session() const { return m_translate_session; }
|
||||
|
||||
const std::vector<std::string> & get_input_names() const { return m_input_names; }
|
||||
|
||||
const std::vector<std::string> & get_output_names() const { return m_output_names; }
|
||||
@@ -172,7 +166,6 @@ private:
|
||||
std::shared_ptr<GgmlDecoder> m_decoder;
|
||||
std::shared_ptr<TensorMap> & m_tensor_map;
|
||||
int m_node_idx;
|
||||
TranslateSession * m_translate_session;
|
||||
std::vector<std::string> m_input_names;
|
||||
std::vector<std::string> m_output_names;
|
||||
};
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
#include "../node_context.h"
|
||||
#include "../op_table.h"
|
||||
#include "../utils.h"
|
||||
#include "ggml.h"
|
||||
#include "ggml-openvino/ggml-openvino-extra.h"
|
||||
#include "ggml.h"
|
||||
|
||||
#include <climits>
|
||||
#include <cstdint>
|
||||
#include <openvino/frontend/exception.hpp>
|
||||
#include <openvino/op/add.hpp>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
#include "../node_context.h"
|
||||
#include "../op_table.h"
|
||||
#include "../utils.h"
|
||||
|
||||
#include <climits>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <memory>
|
||||
#include <numeric>
|
||||
#include <openvino/frontend/exception.hpp>
|
||||
@@ -126,9 +126,13 @@ OutputVector translate_cpy(const NodeContext & context) {
|
||||
auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
|
||||
auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {3});
|
||||
|
||||
auto head_part = std::make_shared<ov::op::v8::Slice>(base, zero, begin, one, axis);
|
||||
auto tail_part = std::make_shared<ov::op::v8::Slice>(base, end, int_max, one, axis);
|
||||
auto res = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{head_part, src, tail_part}, 3);
|
||||
// The view offset is relative to the whole base buffer, so splice on the flattened base.
|
||||
auto flat_base = std::make_shared<ov::op::v1::Reshape>(base, flat_shape, false);
|
||||
auto head_part = std::make_shared<ov::op::v8::Slice>(flat_base, zero, begin, one, axis);
|
||||
auto tail_part = std::make_shared<ov::op::v8::Slice>(flat_base, end, int_max, one, axis);
|
||||
auto spliced = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{head_part, src, tail_part}, 3);
|
||||
auto res = std::make_shared<ov::op::v1::Reshape>(
|
||||
spliced, std::make_shared<ov::op::v3::ShapeOf>(base, ov::element::i64), false);
|
||||
return rename_outputs_with_suffix({res}, context.get_name());
|
||||
}
|
||||
|
||||
@@ -221,6 +225,8 @@ OutputVector translate_cpy(const NodeContext & context) {
|
||||
"CPY conv state cache update requires static source feature view");
|
||||
|
||||
const int64_t full_feature_size = base_shape[3].get_length();
|
||||
FRONT_END_OP_CONVERSION_CHECK(full_feature_size > 0,
|
||||
"CPY conv state cache update requires a non-empty base cache feature size");
|
||||
const int64_t update_feature_size = input_shape[2].get_length() * input_shape[3].get_length();
|
||||
const auto output_stride = context.get_output_stride();
|
||||
const size_t elem_size = output_stride.empty() ? context.get_output_type().size() : output_stride.back();
|
||||
|
||||
@@ -139,7 +139,6 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
|
||||
|
||||
float * params = reinterpret_cast<float *>(context.get_output_op_params());
|
||||
float scale = params[0];
|
||||
// float max_bias = params[1];
|
||||
const float logit_softcap = params[2];
|
||||
|
||||
auto q = std::make_shared<ov::op::v0::Convert>(q_f32, ov::element::f16);
|
||||
@@ -168,9 +167,6 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
|
||||
false);
|
||||
}
|
||||
|
||||
//auto tile_kv = [&](int64_t num_heads, int64_t num_heads_kv, int64_t head_size, ov::Output<Node> kv) {
|
||||
// int64_t factor = num_heads / num_heads_kv;
|
||||
// if (factor > 1 && num_heads_kv > 1) {
|
||||
auto q_shape = context.get_input_shape(0).to_shape();
|
||||
auto k_shape = context.get_input_shape(1).to_shape();
|
||||
auto v_shape = context.get_input_shape(2).to_shape();
|
||||
@@ -279,9 +275,6 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
|
||||
new_kv_shape = ov::op::v0::Constant::create(
|
||||
ov::element::i64, {4},
|
||||
transposed ? std::vector<int64_t>{0, n_heads, hs, -1} : std::vector<int64_t>{0, n_heads, -1, hs});
|
||||
// ov::element::i64, {5}, {(int64_t) 1, (int64_t) 1, factor, (int64_t) 1, (int64_t) 1});
|
||||
//new_kv_shape =
|
||||
// ov::op::v0::Constant::create(ov::element::i64, {4}, {(int64_t) 0, num_heads, (int64_t) -1, head_size});
|
||||
|
||||
kv = std::make_shared<ov::op::v3::Broadcast>(kv_unsqueezed, kv_broadcast_shape,
|
||||
ov::op::BroadcastType::BIDIRECTIONAL);
|
||||
@@ -294,9 +287,9 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
|
||||
const bool v_transposed = ggml_openvino_npu_kv_head_major_enabled() && context.is_static() &&
|
||||
context.get_input_names()[2].find("cache_v_l") != std::string::npos;
|
||||
|
||||
// the HFA prefill path has no sinks
|
||||
const bool use_hfa_gate =
|
||||
ggml_openvino_npu_hfa_prefill_enabled() && context.is_static() && context.is_prefill() && has_mask && !has_sink;
|
||||
// the HFA prefill path has no sinks, and attends the rows of a whole chunk (not those of gemma-4's KV-shared layers)
|
||||
const bool use_hfa_gate = ggml_openvino_npu_hfa_prefill_enabled() && context.is_static() && context.is_prefill() &&
|
||||
has_mask && !has_sink && !is_pruned_mask_name(context.get_input_names()[3]);
|
||||
if (use_hfa_gate) {
|
||||
const int layer = extract_layer(context.get_input_names()[1]);
|
||||
auto past_k = context.get_input("ggml_hfa_past_cache_k_l" + std::to_string(layer));
|
||||
@@ -350,10 +343,6 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
|
||||
return rename_outputs_with_suffix({res}, context.get_name());
|
||||
}
|
||||
|
||||
//auto q_shape = context.get_input_shape(0).to_shape();
|
||||
//auto k_shape = context.get_input_shape(1).to_shape();
|
||||
//k = tile_kv(q_shape[1], k_shape[1], q_shape[3], k);
|
||||
//v = tile_kv(q_shape[1], k_shape[1], q_shape[3], v);
|
||||
k = tile_kv(num_heads, num_heads_kv, head_size, k);
|
||||
v = tile_kv(num_heads, num_heads_kv, head_size, v, v_transposed);
|
||||
|
||||
|
||||
@@ -514,10 +514,6 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
|
||||
g = std::make_shared<ov::op::v1::Multiply>(g, mask);
|
||||
}
|
||||
|
||||
// std::cout << "GatedDeltaNet input shapes: q=" << q.get_partial_shape() << ", k=" << k.get_partial_shape()
|
||||
// << ", v=" << v.get_partial_shape() << ", g=" << g.get_partial_shape()
|
||||
// << ", beta=" << beta.get_partial_shape() << ", state=" << state.get_partial_shape() << std::endl;
|
||||
|
||||
#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
|
||||
if (cache_inputs) {
|
||||
OutputVector args{q, k, v, (*cache_inputs)[0], g, beta};
|
||||
|
||||
@@ -24,6 +24,13 @@ namespace op {
|
||||
OutputVector translate_get_rows(const NodeContext & context) {
|
||||
num_inputs_check(context, 2, 2);
|
||||
|
||||
// Rows gathered on the host (GGML_OPENVINO_NPU_HOST_GATHER) arrive as a [1, 1, n_tokens, row] input.
|
||||
const std::string host_rows = "ggml_host_rows_" + context.get_name();
|
||||
if (context.has_input(host_rows)) {
|
||||
// Not renamed: the output is the Parameter itself, whose name binds the input at runtime.
|
||||
return {context.get_input(host_rows)};
|
||||
}
|
||||
|
||||
Output<Node> res;
|
||||
Output<Node> data;
|
||||
int64_t row_offset = 0;
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
#include "../op_table.h"
|
||||
#include "../utils.h"
|
||||
|
||||
#include <climits>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <openvino/core/node.hpp>
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
#include "../utils.h"
|
||||
#include "ggml-openvino/ggml-openvino-extra.h"
|
||||
|
||||
#include <climits>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <openvino/core/node.hpp>
|
||||
@@ -113,10 +112,6 @@ OutputVector translate_permute(const NodeContext & context) {
|
||||
auto new_shape =
|
||||
std::make_shared<ov::op::v0::Concat>(ov::OutputVector{n_seq_active, neg_one, n_heads, head_size}, 0);
|
||||
|
||||
// // Alternative
|
||||
// auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});
|
||||
// auto new_shape = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{n_seq_active, neg_one, zero, zero}, 0);
|
||||
|
||||
auto reshaped = std::make_shared<ov::op::v1::Reshape>(src, new_shape, true);
|
||||
res = std::make_shared<ov::op::v1::Transpose>(reshaped, perm);
|
||||
} else if ((op_case == 3 || op_case == 4) && is_kvcache_4d_shape(src.get_partial_shape())) {
|
||||
|
||||
@@ -49,34 +49,29 @@ OutputVector translate_rope(const NodeContext & context) {
|
||||
|
||||
Output<Node> cos_theta_node;
|
||||
Output<Node> sin_theta_node;
|
||||
if (context.has_input("rope_cos")) {
|
||||
cos_theta_node = context.get_input("rope_cos");
|
||||
sin_theta_node = context.get_input("rope_sin");
|
||||
std::string cache_key = "rope_sin_cos";
|
||||
for (int i = 0; i < 15; i++) {
|
||||
cache_key += "_" + std::to_string(op_params[i]);
|
||||
}
|
||||
if (context.get_input_size() == 3) {
|
||||
cache_key += "_ff_" + context.get_input_names()[2];
|
||||
}
|
||||
// Not every ROPE takes inp_pos: gemma-4 rotates its KV-shared layers at the positions of the output rows only
|
||||
cache_key += "_pos_" + context.get_input_names()[1];
|
||||
if (context.has_input(cache_key + "_cos")) {
|
||||
cos_theta_node = context.get_input(cache_key + "_cos");
|
||||
sin_theta_node = context.get_input(cache_key + "_sin");
|
||||
} else {
|
||||
std::string cache_key = "rope_sin_cos";
|
||||
for (int i = 0; i < 15; i++) {
|
||||
cache_key += "_" + std::to_string(op_params[i]);
|
||||
}
|
||||
auto inp_pos = context.get_input(1).get_node_shared_ptr();
|
||||
std::shared_ptr<ov::Node> rope_freqs_weight;
|
||||
if (context.get_input_size() == 3) {
|
||||
cache_key += "_ff_" + context.get_input_names()[2];
|
||||
}
|
||||
// Not every ROPE takes inp_pos: gemma-4 rotates its KV-shared layers at the positions of the output rows only
|
||||
cache_key += "_pos_" + context.get_input_names()[1];
|
||||
if (context.has_input(cache_key + "_cos")) {
|
||||
cos_theta_node = context.get_input(cache_key + "_cos");
|
||||
sin_theta_node = context.get_input(cache_key + "_sin");
|
||||
} else {
|
||||
auto inp_pos = context.get_input(1).get_node_shared_ptr();
|
||||
std::shared_ptr<ov::Node> rope_freqs_weight;
|
||||
if (context.get_input_size() == 3) {
|
||||
rope_freqs_weight = context.get_input(2).get_node_shared_ptr();
|
||||
}
|
||||
auto sin_cos = make_sin_cos(op_params, inp_pos, rope_freqs_weight, mode, false, head_dim);
|
||||
sin_theta_node = sin_cos.first;
|
||||
cos_theta_node = sin_cos.second;
|
||||
context.put_shared(cache_key + "_cos", cos_theta_node);
|
||||
context.put_shared(cache_key + "_sin", sin_theta_node);
|
||||
rope_freqs_weight = context.get_input(2).get_node_shared_ptr();
|
||||
}
|
||||
auto sin_cos = make_sin_cos(op_params, inp_pos, rope_freqs_weight, mode, false, head_dim);
|
||||
sin_theta_node = sin_cos.first;
|
||||
cos_theta_node = sin_cos.second;
|
||||
context.put_shared(cache_key + "_cos", cos_theta_node);
|
||||
context.put_shared(cache_key + "_sin", sin_theta_node);
|
||||
}
|
||||
|
||||
auto output_type = context.get_output_type();
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
#include "../utils.h"
|
||||
#include "ggml-openvino/ggml-openvino-extra.h"
|
||||
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <numeric>
|
||||
|
||||
@@ -5,9 +5,7 @@
|
||||
#include <openvino/op/constant.hpp>
|
||||
#include <openvino/op/group_conv.hpp>
|
||||
#include <openvino/op/reshape.hpp>
|
||||
#include <openvino/op/squeeze.hpp>
|
||||
#include <openvino/op/transpose.hpp>
|
||||
#include <openvino/op/unsqueeze.hpp>
|
||||
|
||||
namespace ov {
|
||||
namespace frontend {
|
||||
@@ -23,34 +21,32 @@ OutputVector translate_ssm_conv(const NodeContext & context) {
|
||||
auto sx_shape = context.get_input_shape(0).to_shape(); // [1, n_s, d_inner, ncs]
|
||||
auto c_shape = context.get_input_shape(1).to_shape(); // [1, 1, d_inner, d_conv]
|
||||
|
||||
// int64_t n_s = sx_shape[1];
|
||||
int64_t d_inner = sx_shape[2];
|
||||
// int64_t ncs = sx_shape[3]; // d_conv - 1 + n_t
|
||||
int64_t d_conv = c_shape[3];
|
||||
// int64_t n_t = ncs - d_conv + 1;
|
||||
int64_t d_conv = c_shape[3];
|
||||
|
||||
// Reshape sx from [1, n_s, d_inner, ncs] to [n_s, d_inner, ncs] for 1D GroupConvolution
|
||||
auto sx_reshaped =
|
||||
std::make_shared<ov::op::v0::Squeeze>(sx, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
|
||||
// The depthwise conv is expressed as a 2D GroupConvolution with a unit H dim: the GPU plugin
|
||||
// (OV 2026.4, ACCURACY mode) fails to compile the 1D form ("Weights/ifm mismatch") when its
|
||||
// input comes from RMSNorm -> Transpose -> Concat.
|
||||
// Transpose sx from [1, n_s, d_inner, ncs] to [n_s, d_inner, 1, ncs]
|
||||
auto sx_perm = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 2, 0, 3});
|
||||
auto sx_reshaped = std::make_shared<ov::op::v1::Transpose>(sx, sx_perm);
|
||||
|
||||
// Reshape c from [1, 1, d_inner, d_conv] to [d_inner, 1, 1, d_conv]
|
||||
// GroupConvolution filter: [groups, out_channels/groups, in_channels/groups, kernel_size]
|
||||
auto c_new_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{d_inner, 1, 1, d_conv});
|
||||
// Reshape c from [1, 1, d_inner, d_conv] to [d_inner, 1, 1, 1, d_conv]
|
||||
// GroupConvolution filter: [groups, out_channels/groups, in_channels/groups, kH, kW]
|
||||
auto c_new_shape =
|
||||
ov::op::v0::Constant::create(ov::element::i64, {5}, std::vector<int64_t>{d_inner, 1, 1, 1, d_conv});
|
||||
auto c_reshaped = std::make_shared<ov::op::v1::Reshape>(c, c_new_shape, false);
|
||||
|
||||
// Depthwise 1D convolution: groups=d_inner, stride=1, no padding, no dilation
|
||||
// Input: [n_s, d_inner, ncs], Filter: [d_inner, 1, 1, d_conv]
|
||||
// Output: [n_s, d_inner, n_t]
|
||||
auto conv = std::make_shared<ov::op::v1::GroupConvolution>(
|
||||
sx_reshaped, c_reshaped, ov::Strides{1}, ov::CoordinateDiff{0}, ov::CoordinateDiff{0}, ov::Strides{1});
|
||||
// Depthwise convolution: groups=d_inner, stride=1, no padding, no dilation
|
||||
// Input: [n_s, d_inner, 1, ncs], Filter: [d_inner, 1, 1, 1, d_conv]
|
||||
// Output: [n_s, d_inner, 1, n_t]
|
||||
auto conv = std::make_shared<ov::op::v1::GroupConvolution>(sx_reshaped, c_reshaped, ov::Strides{1, 1},
|
||||
ov::CoordinateDiff{0, 0}, ov::CoordinateDiff{0, 0},
|
||||
ov::Strides{1, 1});
|
||||
|
||||
// Transpose from [n_s, d_inner, n_t] to [n_s, n_t, d_inner]
|
||||
auto perm = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{0, 2, 1});
|
||||
auto transposed = std::make_shared<ov::op::v1::Transpose>(conv, perm);
|
||||
|
||||
// Reshape to output shape [1, n_s, n_t, d_inner]
|
||||
auto res =
|
||||
std::make_shared<ov::op::v0::Unsqueeze>(transposed, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
|
||||
// Transpose from [n_s, d_inner, 1, n_t] to output shape [1, n_s, n_t, d_inner]
|
||||
auto perm = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{2, 0, 3, 1});
|
||||
auto res = std::make_shared<ov::op::v1::Transpose>(conv, perm);
|
||||
|
||||
return rename_outputs_with_suffix({res}, context.get_name());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
#include "keep_cache_results.h"
|
||||
|
||||
#include <openvino/core/model.hpp>
|
||||
#include <openvino/op/parameter.hpp>
|
||||
#include <openvino/op/result.hpp>
|
||||
|
||||
#include <unordered_set>
|
||||
|
||||
namespace ov {
|
||||
namespace frontend {
|
||||
namespace ggml {
|
||||
namespace pass {
|
||||
|
||||
bool KeepCacheResults::run_on_model(const std::shared_ptr<ov::Model> & model) {
|
||||
bool changed = false;
|
||||
// Copies: remove_result()/remove_parameter() modify the vectors these accessors return.
|
||||
const ov::ResultVector results = model->get_results();
|
||||
for (const auto & result : results) {
|
||||
if (m_cache_outputs.count(result->get_friendly_name()) == 0) {
|
||||
model->remove_result(result);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (!changed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Removed Results leave their producers unreachable, but those nodes still hold their inputs, so a Parameter
|
||||
// is unused when none of its consumers is still part of the model.
|
||||
std::unordered_set<const ov::Node *> live;
|
||||
for (const auto & op : model->get_ordered_ops()) {
|
||||
live.insert(op.get());
|
||||
}
|
||||
const ov::ParameterVector params = model->get_parameters();
|
||||
for (const auto & param : params) {
|
||||
bool used = false;
|
||||
for (const auto & input : param->output(0).get_target_inputs()) {
|
||||
if (live.count(input.get_node()) != 0) {
|
||||
used = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!used) {
|
||||
model->remove_parameter(param);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace pass
|
||||
} // namespace ggml
|
||||
} // namespace frontend
|
||||
} // namespace ov
|
||||
@@ -0,0 +1,30 @@
|
||||
#include "openvino/pass/pass.hpp"
|
||||
|
||||
#include <set>
|
||||
#include <string>
|
||||
|
||||
namespace ov {
|
||||
namespace frontend {
|
||||
namespace ggml {
|
||||
namespace pass {
|
||||
|
||||
// Keeps only the Results named in |cache_outputs| (the KV / recurrent cache writes) and drops every other Result,
|
||||
// so that everything that only feeds them -- for models whose tail layers read an earlier layer's KV (Gemma 3n/4
|
||||
// E-series) the KV-shared layers and the LM head -- leaves the model. Parameters that nothing reads afterwards are
|
||||
// removed too. Used for KV-only prefill on the static path (GGML_OPENVINO_KV_ONLY_PREFILL); the outputs of the
|
||||
// batch then come from one step of the decode model.
|
||||
class KeepCacheResults : public ov::pass::ModelPass {
|
||||
public:
|
||||
OPENVINO_MODEL_PASS_RTTI("ov::frontend::ggml::pass::KeepCacheResults")
|
||||
explicit KeepCacheResults(std::set<std::string> cache_outputs) : m_cache_outputs(std::move(cache_outputs)) {}
|
||||
|
||||
bool run_on_model(const std::shared_ptr<ov::Model> & model) override;
|
||||
|
||||
private:
|
||||
std::set<std::string> m_cache_outputs;
|
||||
};
|
||||
|
||||
} // namespace pass
|
||||
} // namespace ggml
|
||||
} // namespace frontend
|
||||
} // namespace ov
|
||||
@@ -1,6 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
#include "mark_decompression_convert_constant_folding.h"
|
||||
#include "openvino/core/visibility.hpp"
|
||||
#include "openvino/pass/matcher_pass.hpp"
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "ggml-openvino/openvino/decoder.h"
|
||||
#include "ggml-openvino/openvino/pass/fuse_argsort_topk.h"
|
||||
#include "ggml-openvino/openvino/pass/fuse_to_conv.h"
|
||||
#include "ggml-openvino/openvino/pass/keep_cache_results.h"
|
||||
#include "ggml-openvino/openvino/pass/kv_state_seq_axis.h"
|
||||
#include "ggml-openvino/openvino/pass/mark_decompression_convert_constant_folding.h"
|
||||
#include "ggml-openvino/openvino/pass/mark_dequantization_subgraph.h"
|
||||
@@ -21,11 +22,18 @@ GraphTraits analyze_graph(const GgmlDecoder & decoder) {
|
||||
traits.device = ggml_openvino_is_npu() ? Device::NPU : ggml_openvino_is_gpu() ? Device::GPU : Device::CPU;
|
||||
traits.is_static = decoder.is_static();
|
||||
traits.is_stateful = decoder.is_stateful();
|
||||
traits.kv_only_outputs = decoder.is_kv_only_outputs();
|
||||
if (traits.kv_only_outputs) {
|
||||
traits.cache_output_names = decoder.get_cache_output_names();
|
||||
}
|
||||
return traits;
|
||||
}
|
||||
|
||||
void register_common_passes(ov::pass::Manager & manager, const GraphTraits & traits) {
|
||||
(void) traits;
|
||||
// First, so the other passes do not work on the layers it removes.
|
||||
if (traits.kv_only_outputs) {
|
||||
manager.register_pass<pass::KeepCacheResults>(traits.cache_output_names);
|
||||
}
|
||||
manager.register_pass<ov::pass::MarkCompressedFloatConstants>();
|
||||
// Marks the Convert/Subtract/Multiply nodes of our GatherMatmul dequantization chain
|
||||
// (make_int4_weights/make_int8_weights, for_gather_matmul=true) with disable_constant_folding,
|
||||
|
||||
@@ -16,6 +16,9 @@
|
||||
#include <openvino/pass/make_stateful.hpp>
|
||||
#include <openvino/pass/manager.hpp>
|
||||
|
||||
#include <set>
|
||||
#include <string>
|
||||
|
||||
namespace ov {
|
||||
namespace frontend {
|
||||
namespace ggml {
|
||||
@@ -31,6 +34,8 @@ struct GraphTraits {
|
||||
Device device = Device::CPU;
|
||||
bool is_static = false; // static shapes (NPU, or GGML_OPENVINO_FORCE_STATIC)
|
||||
bool is_stateful = false; // KV cache kept inside the model (GGML_OPENVINO_STATEFUL_EXECUTION)
|
||||
bool kv_only_outputs = false; // static KV-only prefill: keep only the cache outputs (GGML_OPENVINO_KV_ONLY_PREFILL)
|
||||
std::set<std::string> cache_output_names;
|
||||
};
|
||||
|
||||
GraphTraits analyze_graph(const GgmlDecoder & decoder);
|
||||
|
||||
@@ -3,10 +3,8 @@
|
||||
|
||||
# include "../ggml-openvino-extra.h"
|
||||
# include "ggml-impl.h"
|
||||
# include "op/recurrent_cache_update.hpp"
|
||||
# include "op_table.h"
|
||||
# ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
|
||||
# include "op/recurrent_cache_update.hpp"
|
||||
# endif
|
||||
# include "utils.h"
|
||||
|
||||
# include <openvino/op/concat.hpp>
|
||||
|
||||
@@ -15,11 +15,9 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <limits>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <openvino/core/node.hpp>
|
||||
#include <openvino/core/preprocess/pre_post_process.hpp>
|
||||
#include <openvino/core/shape.hpp>
|
||||
@@ -53,6 +51,7 @@
|
||||
#include <openvino/op/unsqueeze.hpp>
|
||||
#include <openvino/pass/constant_folding.hpp>
|
||||
#include <openvino/pass/make_stateful.hpp>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
@@ -325,7 +324,7 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo
|
||||
auto it = m_translator_map.find(operation_type);
|
||||
FRONT_END_OP_CONVERSION_CHECK(it != m_translator_map.end(), "Translation for operation type ", operation_type,
|
||||
" is not implemented.");
|
||||
NodeContext node_context(decoder, tensor_map, node_idx, this);
|
||||
NodeContext node_context(decoder, tensor_map, node_idx);
|
||||
ov::OutputVector converted_outputs;
|
||||
#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
|
||||
converted_outputs = recurrent_fusion.translate(node_idx, node_context);
|
||||
@@ -451,9 +450,6 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo
|
||||
used_params.push_back(param);
|
||||
}
|
||||
}
|
||||
// if (auto diff = params.size() - used_params.size()) {
|
||||
// GGML_LOG_INFO("%zu parameters are not used in the model.", diff);
|
||||
// }
|
||||
resulting_model = std::make_shared<Model>(results, used_params);
|
||||
|
||||
apply_transformations(resulting_model);
|
||||
|
||||
@@ -496,15 +496,37 @@ std::shared_ptr<ov::Node> gather_compressed_rows(const ov::Output<ov::Node> & we
|
||||
return saw_compressed ? gathered : nullptr;
|
||||
}
|
||||
|
||||
bool is_pruned_mask_name(const std::string & name) {
|
||||
static const std::string suffix = "_pruned";
|
||||
return name.size() > suffix.size() && name.compare(name.size() - suffix.size(), suffix.size(), suffix) == 0;
|
||||
}
|
||||
|
||||
ov::Output<ov::Node> get_kq_mask_input(const NodeContext & context, size_t input_index) {
|
||||
const auto & name = context.get_input_names()[input_index];
|
||||
const auto & input_name = context.get_input_names()[input_index];
|
||||
const bool pruned = is_pruned_mask_name(input_name);
|
||||
const std::string name = pruned ? input_name.substr(0, input_name.size() - std::string("_pruned").size()) : input_name;
|
||||
const std::string sliced = name == "self_kq_mask_swa" ? "KQ_mask_swa_sliced" :
|
||||
name == "self_kq_mask" || name == "KQ_mask" ? "KQ_mask_sliced" :
|
||||
std::string();
|
||||
ov::Output<ov::Node> mask;
|
||||
if (!sliced.empty() && context.has_input(sliced)) {
|
||||
return context.get_input(sliced);
|
||||
mask = context.get_input(sliced);
|
||||
} else if (pruned) {
|
||||
mask = context.get_input(name);
|
||||
} else {
|
||||
return context.get_input(input_index);
|
||||
}
|
||||
return context.get_input(input_index);
|
||||
if (!pruned) {
|
||||
return mask;
|
||||
}
|
||||
// gemma-4's KV-shared layers: the rows of their output tokens, gathered from the input mask (see
|
||||
// ModelParams::pruned_masks)
|
||||
auto ids = std::make_shared<ov::op::v1::Reshape>(context.get_input("inp_prune_ids"),
|
||||
ov::op::v0::Constant::create(ov::element::i64, {1}, {-1}), false);
|
||||
const auto rank = mask.get_partial_shape().rank();
|
||||
FRONT_END_OP_CONVERSION_CHECK(rank.is_static() && rank.get_length() >= 2, "Expected a static mask rank");
|
||||
auto axis = ov::op::v0::Constant::create(ov::element::i64, {}, {rank.get_length() - 2});
|
||||
return std::make_shared<ov::op::v8::Gather>(mask, ids, axis);
|
||||
}
|
||||
|
||||
ov::Output<ov::Node> process_view_input_new(const NodeContext & context, int input_index) {
|
||||
|
||||
@@ -49,6 +49,9 @@ OutputVector translate_recurrent_cache_reset(const NodeContext & context);
|
||||
// add_sliced_mask_stateful); any other input, e.g. the mask rows gemma-4 gathers for its KV-shared layers, as is.
|
||||
ov::Output<ov::Node> get_kq_mask_input(const NodeContext & context, size_t input_index);
|
||||
|
||||
// The mask of gemma-4's KV-shared layers, whose rows get_kq_mask_input() gathers from an input mask
|
||||
bool is_pruned_mask_name(const std::string & name);
|
||||
|
||||
// A stateless KV cache in the [1, ctx, n_heads_kv, head_size] layout (GgmlOvDecoder::is_kvcache_4d), as opposed to
|
||||
// [1, n_seq, ctx, n_heads_kv * head_size]
|
||||
inline bool is_kvcache_4d_shape(const ov::PartialShape & shape) {
|
||||
|
||||
+723
-874
File diff suppressed because it is too large
Load Diff
@@ -13,6 +13,7 @@
|
||||
#include <openvino/runtime/core.hpp>
|
||||
#include <openvino/runtime/infer_request.hpp>
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <utility>
|
||||
@@ -96,43 +97,55 @@ struct graph_key_hash {
|
||||
}
|
||||
};
|
||||
|
||||
// One compiled model of a static graph: its phase, KV window, SWA window and output count.
|
||||
struct ov_static_variant_key {
|
||||
bool prefill = false;
|
||||
int attention_size = -1;
|
||||
int attention_size_swa = -1;
|
||||
int output_len = 1;
|
||||
|
||||
bool operator<(const ov_static_variant_key & other) const {
|
||||
return std::tie(prefill, output_len, attention_size_swa, attention_size) <
|
||||
std::tie(other.prefill, other.output_len, other.attention_size_swa, other.attention_size);
|
||||
}
|
||||
|
||||
bool operator==(const ov_static_variant_key & other) const { return !(*this < other) && !(other < *this); }
|
||||
};
|
||||
|
||||
struct ov_static_variant {
|
||||
ov::CompiledModel model;
|
||||
// Created on first use, so only the requests a run needs hold NPU memory.
|
||||
std::shared_ptr<ov::InferRequest> request;
|
||||
std::vector<std::string> input_names;
|
||||
std::vector<std::string> output_names;
|
||||
};
|
||||
|
||||
struct decoder_runtime_ctx {
|
||||
decoder_runtime_ctx(std::shared_ptr<std::mutex> mutex) : mutex(std::move(mutex)) {}
|
||||
|
||||
std::shared_ptr<std::mutex> mutex;
|
||||
std::shared_ptr<GgmlOvDecoder> ptr;
|
||||
// Attention sizes and output count the cached prefill model was built with; decode calls overwrite the
|
||||
// decoder's.
|
||||
int prefill_attention_size = -1;
|
||||
int prefill_attention_size_swa = -1;
|
||||
int prefill_output_len = -1;
|
||||
// KV window of the decode model in the compiled pair (GGML_OPENVINO_NPU_BLOB_PREBUILD).
|
||||
int decode_attention_size = -1;
|
||||
std::string shared_key;
|
||||
std::map<int, std::shared_ptr<ov::InferRequest>> decode_window_requests;
|
||||
|
||||
// Static path: the compiled models of this graph with their requests (ov_graph_compute_static).
|
||||
std::map<ov_static_variant_key, ov_static_variant> variants;
|
||||
// The prefill models only write the KV cache; logits come from one decode step (GGML_OPENVINO_KV_ONLY_PREFILL).
|
||||
bool kv_only_prefill = false;
|
||||
bool decode_unfold = false;
|
||||
uint64_t cache_base_extra = 0;
|
||||
// With a model cache, every window of a phase is exported (or imported) on the first call of that phase.
|
||||
bool prefill_prepared = false;
|
||||
bool decode_prepared = false;
|
||||
// NPU weightless bank: the weights file and NPUW bank of every blob of this graph, and the file's layout once
|
||||
// it is known in this process (new blobs resolve their weights through it).
|
||||
std::string weights_path;
|
||||
std::string weights_bank;
|
||||
std::shared_ptr<ggml_openvino_weights_layout> weights_layout;
|
||||
};
|
||||
|
||||
struct ov_compiled_graph {
|
||||
ov::CompiledModel decode;
|
||||
ov::CompiledModel prefill;
|
||||
std::vector<std::string> input_names;
|
||||
std::vector<std::string> output_names;
|
||||
std::vector<std::string> prefill_input_names;
|
||||
std::vector<std::string> prefill_output_names;
|
||||
// Extra decode models for other KV windows, built on first use with the pair's settings.
|
||||
int decode_attention_size = -1;
|
||||
std::map<int, ov::CompiledModel> decode_windows;
|
||||
ov::AnyMap decode_config;
|
||||
uint64_t cache_base_extra = 0;
|
||||
bool self_contained = false;
|
||||
bool decode_unfold = false;
|
||||
// GGML_OPENVINO_NPU_WEIGHTLESS_BANK: the pair's weights file, and its layout when the pair was compiled in
|
||||
// this process (window models then resolve the shared weights through the same file).
|
||||
bool weightless_bank = false;
|
||||
std::string weights_path;
|
||||
std::shared_ptr<ggml_openvino_weights_layout> weights_layout;
|
||||
// Compute params the pair's decode model was built with; window models derive from them.
|
||||
ComputeParams decode_c_params;
|
||||
};
|
||||
|
||||
// Only compilation and cache publication use this mutex. Requests, decoders and
|
||||
@@ -154,11 +167,8 @@ struct ov_runtime_context {
|
||||
bool stateful;
|
||||
std::unordered_map<graph_key, std::shared_ptr<decoder_runtime_ctx>, graph_key_hash> decoder_cache;
|
||||
std::unordered_map<graph_key, std::shared_ptr<ov::InferRequest>, graph_key_hash> infer_request_cache;
|
||||
std::unordered_map<graph_key, std::shared_ptr<ov::InferRequest>, graph_key_hash> infer_request_cache_prefill;
|
||||
std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_input_names_cache;
|
||||
std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_output_names_cache;
|
||||
std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_input_names_cache_prefill;
|
||||
std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_output_names_cache_prefill;
|
||||
// LRU order of decoder_cache's keys, oldest (least recently used) at the front. A pipeline
|
||||
// that interleaves distinct graph shapes every call -- e.g. DFlash cycling target/draft/
|
||||
// injection graphs every round -- needs a slot per shape open at once; a single-entry cache
|
||||
@@ -193,11 +203,8 @@ struct ov_runtime_context {
|
||||
lru_keys.pop_front();
|
||||
decoder_cache.erase(victim);
|
||||
infer_request_cache.erase(victim);
|
||||
infer_request_cache_prefill.erase(victim);
|
||||
ov_input_names_cache.erase(victim);
|
||||
ov_output_names_cache.erase(victim);
|
||||
ov_input_names_cache_prefill.erase(victim);
|
||||
ov_output_names_cache_prefill.erase(victim);
|
||||
}
|
||||
|
||||
// Make room for one more graph shape if the cache is at capacity, then mark `key` as most
|
||||
@@ -212,11 +219,8 @@ struct ov_runtime_context {
|
||||
void clear_caches_locked() {
|
||||
decoder_cache.clear();
|
||||
infer_request_cache.clear();
|
||||
infer_request_cache_prefill.clear();
|
||||
ov_input_names_cache.clear();
|
||||
ov_output_names_cache.clear();
|
||||
ov_input_names_cache_prefill.clear();
|
||||
ov_output_names_cache_prefill.clear();
|
||||
lru_keys.clear();
|
||||
kv_state_input_name_map.clear();
|
||||
stateful_kv_size = 0;
|
||||
@@ -230,9 +234,6 @@ struct ov_runtime_context {
|
||||
|
||||
enum ggml_status ov_graph_compute(struct ggml_cgraph * cgraph, ggml_backend_t backend);
|
||||
|
||||
// Releases the cached blobs this process imported (GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR).
|
||||
void ov_clear_imported_blobs();
|
||||
|
||||
void print_input_tensor_info(const std::string & name, const ov::Tensor & tensor);
|
||||
|
||||
void print_output_tensor_info(const std::string & name, const ov::Tensor & tensor, const void * output_dst);
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
extern int g_ggml_sycl_debug;
|
||||
extern int g_ggml_sycl_dev_debug;
|
||||
extern int g_ggml_sycl_fa_tile_debug;
|
||||
|
||||
#if defined(__clang__) && __has_builtin(__builtin_expect)
|
||||
// Hint the optimizer to pipeline the more likely following instruction in branches
|
||||
@@ -40,4 +41,10 @@ extern int g_ggml_sycl_dev_debug;
|
||||
fprintf(stderr, __VA_ARGS__); \
|
||||
} while (0)
|
||||
|
||||
#define GGML_SYCL_FA_TILE_DEBUG(...) \
|
||||
do { \
|
||||
if (UNLIKELY(g_ggml_sycl_fa_tile_debug)) \
|
||||
fprintf(stderr, __VA_ARGS__); \
|
||||
} while (0)
|
||||
|
||||
#endif // GGML_SYCL_BASE_HPP
|
||||
|
||||
@@ -880,15 +880,24 @@ static void flash_attn_tile(const char * Q,
|
||||
KQ_max_new_shared);
|
||||
}
|
||||
} else {
|
||||
// Branch without out-of-bounds checks.
|
||||
for (int k_VKQ_0 = item_ct1.get_group(1) * nbatch_fa; k_VKQ_0 < k_VKQ_max;
|
||||
k_VKQ_0 += item_ct1.get_group_range(1) * nbatch_fa) {
|
||||
|
||||
// Branch without out-of-bounds checks for full chunks; the trailing partial
|
||||
// chunk (n_kv not a multiple of nbatch_fa) takes the checked iteration, so
|
||||
// the GQA-optimized variants no longer require K->ne[1] % FATTN_KQ_STRIDE == 0.
|
||||
int k_VKQ_0 = item_ct1.get_group(1) * nbatch_fa;
|
||||
while (k_VKQ_0 < k_VKQ_max - nbatch_fa) {
|
||||
constexpr bool oob_check = false;
|
||||
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap,
|
||||
oob_check>(Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, stride_K2,
|
||||
stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0,
|
||||
KQ_max_new_shared);
|
||||
k_VKQ_0 += item_ct1.get_group_range(1) * nbatch_fa;
|
||||
}
|
||||
if (k_VKQ_0 < k_VKQ_max) {
|
||||
constexpr bool oob_check = true;
|
||||
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap,
|
||||
oob_check>(Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, stride_K2,
|
||||
stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0,
|
||||
KQ_max_new_shared);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1166,7 +1175,11 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_sycl_context & ctx, ggm
|
||||
// However, for DKQ == 576, DV == 512 only the kernel variant with GQA optimizations is implemented.
|
||||
//const bool nvidia = GGML_SYCL_CC_IS_NVIDIA(ggml_sycl_info().devices[ggml_sycl_get_device()].cc);
|
||||
const int gqa_limit = gqa_ratio <= 4 && DV <= 256 ? 16 : INT_MAX;
|
||||
const bool use_gqa_opt = mask && max_bias == 0.0f && Q->ne[1] <= gqa_limit && K->ne[1] % FATTN_KQ_STRIDE == 0;
|
||||
// n_kv need not be a multiple of FATTN_KQ_STRIDE: the kernel handles the trailing
|
||||
// partial chunk with the out-of-bounds checked iteration.
|
||||
const bool use_gqa_opt = mask && max_bias == 0.0f && Q->ne[1] <= gqa_limit;
|
||||
GGML_SYCL_FA_TILE_DEBUG("[FA-TILE] DKQ=%d DV=%d gqa=%d q=%lld n_kv=%lld gqa_opt=%d\n",
|
||||
DKQ, DV, gqa_ratio, (long long) Q->ne[1], (long long) K->ne[1], (int) use_gqa_opt);
|
||||
|
||||
if constexpr (DV == 512) {
|
||||
if (use_gqa_opt && gqa_ratio % 16 == 0) {
|
||||
|
||||
@@ -129,7 +129,9 @@ static best_fattn_kernel ggml_sycl_get_best_fattn_kernel(const int device, const
|
||||
float logit_softcap = 0.0f;
|
||||
memcpy(&logit_softcap, (const float *) KQV->op_params + 2, sizeof(float));
|
||||
|
||||
bool gqa_opt_applies = gqa_ratio >= 2 && mask && max_bias == 0.0f && K->ne[1] % FATTN_KQ_STRIDE == 0;
|
||||
// The GQA-optimized TILE variant handles a trailing partial chunk (out-of-bounds
|
||||
// checked iteration), so n_kv no longer needs to be a multiple of FATTN_KQ_STRIDE.
|
||||
bool gqa_opt_applies = gqa_ratio >= 2 && mask && max_bias == 0.0f;
|
||||
|
||||
// XMX-accelerated path: oneDNN SDPA (native F16 and dequant+non-F16).
|
||||
// ONEDNN requires min 32 query tokens — short-circuit decode to avoid
|
||||
@@ -267,7 +269,15 @@ static best_fattn_kernel ggml_sycl_get_best_fattn_kernel(const int device, const
|
||||
if (can_use_vector_kernel) {
|
||||
if (!ggml_is_quantized(K->type) && !ggml_is_quantized(V->type)) {
|
||||
if (Q->ne[1] == 1) {
|
||||
if (!gqa_opt_applies) {
|
||||
// BMG, D=256: single-query decode runs materially faster on the vector
|
||||
// kernel than on the GQA-optimized tile config (832 vs 1150 us at
|
||||
// kv=65536, GQA4, B70-measured; +4..+18% end-to-end tg at 8k..64k
|
||||
// context on spark2_5/qwen35 D=256 models). Other archs and head sizes
|
||||
// keep the tile dispatcher's original preference.
|
||||
const gpu_arch arch = ggml_sycl_info().devices[device].hw_info.arch;
|
||||
const bool vec_decode = (arch == gpu_arch::intel_gpu_bmg_g21 ||
|
||||
arch == gpu_arch::intel_gpu_bmg_g31) && Q->ne[0] == 256;
|
||||
if (vec_decode || !gqa_opt_applies) {
|
||||
return BEST_FATTN_KERNEL_VEC;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,6 +99,7 @@
|
||||
static bool g_sycl_loaded = false;
|
||||
int g_ggml_sycl_debug = 0;
|
||||
int g_ggml_sycl_dev_debug = 0;
|
||||
int g_ggml_sycl_fa_tile_debug = 0;
|
||||
int g_ggml_sycl_enable_optimize = 1;
|
||||
int g_ggml_sycl_enable_graph = 0;
|
||||
int g_ggml_sycl_enable_dnn = 1;
|
||||
@@ -434,6 +435,7 @@ static void ggml_check_sycl() try {
|
||||
|
||||
g_ggml_sycl_debug = ggml_sycl_get_env("GGML_SYCL_DEBUG", 0);
|
||||
g_ggml_sycl_dev_debug = ggml_sycl_get_env("GGML_SYCL_DEV_DEBUG", 0);
|
||||
g_ggml_sycl_fa_tile_debug = ggml_sycl_get_env("GGML_SYCL_FA_TILE_DEBUG", 0);
|
||||
g_ggml_sycl_enable_optimize = ggml_sycl_get_env("GGML_SYCL_ENABLE_OPT", 1);
|
||||
g_ggml_sycl_enable_graph = ggml_sycl_get_env("GGML_SYCL_ENABLE_GRAPH", 0);
|
||||
g_ggml_sycl_enable_dnn = ggml_sycl_get_env("GGML_SYCL_ENABLE_DNN", 1);
|
||||
@@ -542,6 +544,7 @@ static void ggml_check_sycl() try {
|
||||
GGML_LOG_INFO("Running with Environment Variables:\n");
|
||||
GGML_LOG_INFO(" GGML_SYCL_DEBUG: %d\n", g_ggml_sycl_debug);
|
||||
GGML_LOG_INFO(" GGML_SYCL_DEV_DEBUG: %d\n", g_ggml_sycl_dev_debug);
|
||||
GGML_LOG_INFO(" GGML_SYCL_FA_TILE_DEBUG: %d\n", g_ggml_sycl_fa_tile_debug);
|
||||
|
||||
#ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API
|
||||
GGML_LOG_INFO(" GGML_SYCL_DEV2DEV_MEMCPY: %d (%s)\n", g_ggml_sycl_dev2dev_memcpy, dev2dev_int2str(g_ggml_sycl_dev2dev_memcpy));
|
||||
|
||||
@@ -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;
|
||||
|
||||
+24
-13
@@ -5549,27 +5549,38 @@ bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a) {
|
||||
return a->op == GGML_OP_FLASH_ATTN_EXT && ggml_get_op_params_i32(a, 5) != 0;
|
||||
}
|
||||
|
||||
bool ggml_validate_flash_attn_ext_indexed_bias(const struct ggml_tensor * a) {
|
||||
GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT);
|
||||
const struct ggml_tensor * table = a->src[6];
|
||||
const struct ggml_tensor * indices = a->src[7];
|
||||
if (!ggml_flash_attn_ext_has_indexed_bias(a)) {
|
||||
return !table && !indices;
|
||||
}
|
||||
|
||||
const struct ggml_tensor * q = a->src[0];
|
||||
const struct ggml_tensor * k = a->src[1];
|
||||
const struct ggml_tensor * mask = a->src[3];
|
||||
const struct ggml_tensor * rows = a->src[5];
|
||||
return q && k && a->src[2] && mask && table && indices &&
|
||||
mask->type == GGML_TYPE_F16 && ggml_is_contiguous(mask) &&
|
||||
mask->ne[0] == (rows ? rows->ne[0] : k->ne[1]) && mask->ne[1] == q->ne[1] &&
|
||||
mask->ne[2] == 1 && mask->ne[3] == q->ne[3] &&
|
||||
(!rows || (rows->type == GGML_TYPE_I32 && ggml_is_contiguous(rows) && ggml_is_matrix(rows) && rows->ne[1] == q->ne[3])) &&
|
||||
table->type == GGML_TYPE_F32 && ggml_is_contiguous(table) && table->ne[0] > 0 && table->ne[1] == q->ne[2] &&
|
||||
(q->ne[1] == 0 || q->ne[3] <= INT64_MAX/q->ne[1]) && table->ne[2] == q->ne[1]*q->ne[3] && table->ne[3] == 1 &&
|
||||
indices->type == GGML_TYPE_I32 && ggml_is_contiguous(indices) && ggml_is_matrix(indices) &&
|
||||
indices->ne[0] == mask->ne[0] && indices->ne[1] == table->ne[2];
|
||||
}
|
||||
|
||||
void ggml_flash_attn_ext_add_indexed_bias(
|
||||
struct ggml_tensor * a,
|
||||
struct ggml_tensor * table,
|
||||
struct ggml_tensor * indices) {
|
||||
GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT);
|
||||
GGML_ASSERT((table == NULL) == (indices == NULL));
|
||||
a->src[6] = table;
|
||||
a->src[7] = indices;
|
||||
ggml_set_op_params_i32(a, 5, table != NULL);
|
||||
if (!table) {
|
||||
return;
|
||||
}
|
||||
|
||||
const struct ggml_tensor * q = a->src[0];
|
||||
const struct ggml_tensor * mask = a->src[3];
|
||||
GGML_ASSERT(mask && mask->ne[0] == (a->src[5] ? a->src[5]->ne[0] : a->src[1]->ne[1]) && mask->ne[1] == q->ne[1]);
|
||||
GGML_ASSERT(mask->ne[2] == 1 && mask->ne[3] == q->ne[3]);
|
||||
GGML_ASSERT(table->type == GGML_TYPE_F32 && ggml_is_contiguous(table));
|
||||
GGML_ASSERT(table->ne[1] == q->ne[2] && table->ne[0] > 0 && table->ne[2] == q->ne[1]*q->ne[3] && table->ne[3] == 1);
|
||||
GGML_ASSERT(indices->type == GGML_TYPE_I32 && ggml_is_contiguous(indices) && ggml_is_matrix(indices));
|
||||
GGML_ASSERT(indices->ne[0] == mask->ne[0] && indices->ne[1] == table->ne[2]);
|
||||
GGML_ASSERT(ggml_validate_flash_attn_ext_indexed_bias(a));
|
||||
}
|
||||
|
||||
// ggml_flash_attn_back
|
||||
|
||||
@@ -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_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi2ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi16ELi4ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi32ELi2ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi4ELi8ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi4ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb0ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_f16ILi512ELi512ELi8ELi8ELb1ELb0ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi16ELi4ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi16ELb0ELb1ELb1EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi1ELi32ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi16ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi2ELi32ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi4ELi16ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_f16ILi576ELi512ELi8ELi4ELb0ELb1ELb0EL9ggml_type1ELS0_1EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type2ELS0_2ELb0ELb0ELb0EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb0ELb0ELb0EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_ZL18flash_attn_ext_vecILi256ELi1EL9ggml_type43ELS0_43ELb1ELb0ELb0EEvPK15HIP_vector_typeIfLj2EEPKcS6_PK6__halfPKfPKiSD_PfPS2_ffffjfiS1_IjLj3EEiiiiiiiiiiiliiliiiill18fattn_indexed_bias',
|
||||
'_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;
|
||||
|
||||
@@ -189,7 +189,8 @@ ggml_tensor * llama_model_bailingmoe3::graph::build_causal_conv1d(
|
||||
|
||||
ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner);
|
||||
ggml_tensor * out = ggml_ssm_conv(ctx0, conv_x, conv_weight);
|
||||
out = ggml_silu(ctx0, ggml_reshape_2d(ctx0, out, d_inner, n_tokens));
|
||||
out = ggml_silu(ctx0, out);
|
||||
out = ggml_reshape_2d(ctx0, out, d_inner, n_tokens);
|
||||
return ggml_reshape_4d(ctx0, out, head_dim, n_head, n_seq_tokens, n_seqs);
|
||||
}
|
||||
|
||||
@@ -264,15 +265,15 @@ llama_model_bailingmoe3::graph::graph(const llm_graph_params & params) :
|
||||
ggml_tensor * state = build_rs(inp_rs, states_all, hparams.n_embd_s(), n_seqs);
|
||||
state = ggml_reshape_4d(ctx0, state, head_dim, head_dim, n_head, n_seqs);
|
||||
|
||||
ggml_tensor * out = ggml_cont(ctx0, build_recurrent_attn(
|
||||
inp_rs, states_all, q, k, v, gate, beta, state, il));
|
||||
ggml_tensor * out = build_recurrent_attn(
|
||||
inp_rs, states_all, q, k, v, gate, beta, state, il);
|
||||
|
||||
ggml_tensor * out_gate = ggml_mul_mat(ctx0, layer.ssm_g_a, cur);
|
||||
out_gate = ggml_reshape_3d(ctx0, out_gate, head_dim, n_head, n_tokens);
|
||||
out = ggml_reshape_3d(ctx0, out, head_dim, n_head, n_tokens);
|
||||
out = build_norm(out, layer.ssm_o_norm, nullptr, LLM_NORM_RMS, il);
|
||||
out = ggml_mul(ctx0, out, ggml_sigmoid(ctx0, out_gate));
|
||||
cur = ggml_mul_mat(ctx0, layer.wo, ggml_cont_2d(ctx0, out, d_inner, n_tokens));
|
||||
cur = ggml_mul_mat(ctx0, layer.wo, ggml_reshape_2d(ctx0, out, d_inner, n_tokens));
|
||||
cb(cur, "kda_out", il);
|
||||
} else {
|
||||
ggml_tensor * attn_input = cur;
|
||||
@@ -322,7 +323,7 @@ llama_model_bailingmoe3::graph::graph(const llm_graph_params & params) :
|
||||
attn_gate = ggml_sigmoid(ctx0, ggml_reshape_3d(ctx0, attn_gate, 1, n_head, n_tokens));
|
||||
cur = ggml_reshape_3d(ctx0, cur, v_head_dim, n_head, n_tokens);
|
||||
cur = ggml_mul(ctx0, cur, attn_gate);
|
||||
cur = ggml_mul_mat(ctx0, layer.wo, ggml_cont_2d(ctx0, cur, v_head_dim * n_head, n_tokens));
|
||||
cur = ggml_mul_mat(ctx0, layer.wo, ggml_reshape_2d(ctx0, cur, v_head_dim * n_head, n_tokens));
|
||||
cb(cur, "mla_out", il);
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
+351
-5
@@ -4834,6 +4834,301 @@ 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) {}
|
||||
|
||||
double max_nmse_err() override {
|
||||
return 5e-4;
|
||||
}
|
||||
|
||||
ggml_tensor * build_graph(ggml_context * ctx) override {
|
||||
verify.clear();
|
||||
ggml_tensor * stack = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n, B, T);
|
||||
ggml_tensor * cur = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n, T);
|
||||
ggml_tensor * query = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n, Q);
|
||||
ggml_set_name(stack, "stack");
|
||||
ggml_set_name(cur, "cur");
|
||||
|
||||
ggml_tensor * norm = ggml_rms_norm(ctx, ggml_reshape_3d(ctx, cur, n, 1, T), 1e-6f);
|
||||
if (shared_norm) {
|
||||
ggml_tensor * other = ggml_scale(ctx, norm, 2.0f);
|
||||
if (gf) {
|
||||
ggml_build_forward_expand(gf, other);
|
||||
}
|
||||
verify.push_back(other);
|
||||
}
|
||||
|
||||
ggml_tensor * states = ggml_concat(ctx, stack, norm, 1);
|
||||
ggml_tensor * queries = T == 1 ? query : ggml_repeat(ctx, query, ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n, Q, T));
|
||||
ggml_tensor * scores = ggml_soft_max_ext(ctx, ggml_mul_mat(ctx, states, queries), nullptr, 1.0f/sqrtf((float) n), 0.0f);
|
||||
ggml_tensor * out = ggml_mul_mat(ctx, scores, ggml_cont(ctx, ggml_transpose(ctx, states)));
|
||||
ggml_set_name(out, "out");
|
||||
verify.push_back(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
void initialize_tensors(ggml_context * ctx) override {
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
|
||||
init_tensor_uniform(t, -3.0f, 3.0f);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// the loop controller of Inkling 2 as control() builds it: one rms_norm of [cur; msg], the rank r down projection, the gain
|
||||
// and forget projections and (cur - tanh(forget)*cur) + tanh(gain)*msg
|
||||
struct test_loop_ctrl : public test_case {
|
||||
const int64_t n, r, T;
|
||||
|
||||
std::string op_desc(ggml_tensor * t) override {
|
||||
GGML_UNUSED(t);
|
||||
return "LOOP_CTRL";
|
||||
}
|
||||
|
||||
bool run_whole_graph() override { return true; }
|
||||
|
||||
std::string vars() override {
|
||||
return VARS_TO_STR3(n, r, T);
|
||||
}
|
||||
|
||||
test_loop_ctrl(int64_t n = 2304, int64_t r = 64, int64_t T = 1) : n(n), r(r), T(T) {}
|
||||
|
||||
ggml_tensor * build_graph(ggml_context * ctx) override {
|
||||
ggml_tensor * cur = ggml_scale(ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n, T), 1.0f);
|
||||
ggml_tensor * msg = ggml_scale(ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n, T), 1.0f);
|
||||
ggml_tensor * wd = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 2*n, r);
|
||||
ggml_tensor * wg = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, r, n);
|
||||
ggml_tensor * wf = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, r, n);
|
||||
ggml_set_name(cur, "cur");
|
||||
ggml_set_name(msg, "msg");
|
||||
|
||||
ggml_tensor * gate = ggml_concat(ctx, ggml_reshape_3d(ctx, cur, n, 1, T), ggml_reshape_3d(ctx, msg, n, 1, T), 1);
|
||||
gate = ggml_reshape_2d(ctx, ggml_rms_norm(ctx, gate, 1e-6f), 2*n, T);
|
||||
gate = ggml_mul_mat(ctx, wd, gate);
|
||||
|
||||
ggml_tensor * gain = ggml_tanh(ctx, ggml_mul_mat(ctx, wg, gate));
|
||||
ggml_tensor * forget = ggml_tanh(ctx, ggml_mul_mat(ctx, wf, gate));
|
||||
|
||||
ggml_tensor * out = ggml_add(ctx, ggml_sub(ctx, cur, ggml_mul(ctx, forget, cur)), ggml_mul(ctx, gain, msg));
|
||||
ggml_set_name(out, "out");
|
||||
return out;
|
||||
}
|
||||
|
||||
void initialize_tensors(ggml_context * ctx) override {
|
||||
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
|
||||
init_tensor_uniform(t, -0.5f, 0.5f);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
struct test_snake_fuse : public test_case {
|
||||
const ggml_type type;
|
||||
const std::array<int64_t, 4> ne; // [T, C, D2, D3]
|
||||
@@ -10169,11 +10464,13 @@ struct test_flash_attn_ext_indexed_bias : public test_case {
|
||||
const bool kv_rows; // all streams read one K/V cache of 2*kv rows through kv_rows
|
||||
const bool sinks;
|
||||
const ggml_type type_KV;
|
||||
const float logit_softcap;
|
||||
const bool mask_row; // query 0 of each stream sees no key
|
||||
|
||||
std::vector<int32_t> rows;
|
||||
|
||||
std::string vars() override {
|
||||
return VARS_TO_STR10(hs, nh, gqa, kv, nb, n_stream, n_bins, kv_rows, sinks, type_KV);
|
||||
return VARS_TO_STR12(hs, nh, gqa, kv, nb, n_stream, n_bins, kv_rows, sinks, type_KV, logit_softcap, mask_row);
|
||||
}
|
||||
|
||||
double max_nmse_err() override {
|
||||
@@ -10181,8 +10478,10 @@ struct test_flash_attn_ext_indexed_bias : public test_case {
|
||||
}
|
||||
|
||||
test_flash_attn_ext_indexed_bias(int64_t hs = 128, int64_t nh = 2, int64_t gqa = 3, int64_t kv = 768, int64_t nb = 7, int64_t n_stream = 2,
|
||||
int64_t n_bins = 17, bool kv_rows = false, bool sinks = true, ggml_type type_KV = GGML_TYPE_F16)
|
||||
: hs(hs), nh(nh), gqa(gqa), kv(kv), nb(nb), n_stream(n_stream), n_bins(n_bins), kv_rows(kv_rows), sinks(sinks), type_KV(type_KV) {}
|
||||
int64_t n_bins = 17, bool kv_rows = false, bool sinks = true, ggml_type type_KV = GGML_TYPE_F16,
|
||||
float logit_softcap = 0.0f, bool mask_row = false)
|
||||
: hs(hs), nh(nh), gqa(gqa), kv(kv), nb(nb), n_stream(n_stream), n_bins(n_bins), kv_rows(kv_rows), sinks(sinks), type_KV(type_KV),
|
||||
logit_softcap(logit_softcap), mask_row(mask_row) {}
|
||||
|
||||
ggml_tensor * build_graph(ggml_context * ctx) override {
|
||||
ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, hs, nb, nh*gqa, n_stream);
|
||||
@@ -10208,7 +10507,7 @@ struct test_flash_attn_ext_indexed_bias : public test_case {
|
||||
ggml_tensor * indices = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, kv, nb*n_stream);
|
||||
ggml_set_name(indices, "indices");
|
||||
|
||||
ggml_tensor * out = ggml_flash_attn_ext_rows(ctx, q, k, v, m, r, 1.0f/sqrtf(hs), 0.0f, 0.0f);
|
||||
ggml_tensor * out = ggml_flash_attn_ext_rows(ctx, q, k, v, m, r, 1.0f/sqrtf(hs), 0.0f, logit_softcap);
|
||||
if (sinks) {
|
||||
ggml_tensor * s = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nh*gqa);
|
||||
ggml_set_name(s, "s");
|
||||
@@ -10249,7 +10548,7 @@ struct test_flash_attn_ext_indexed_bias : public test_case {
|
||||
for (int64_t j = 0; j < nb; ++j) {
|
||||
for (int64_t i = 0; i < kv; ++i) {
|
||||
const bool pad = kv_rows && rows[s*kv + i] < 0;
|
||||
const bool drop = (i + 3*j + 5*s) % 11 == 0;
|
||||
const bool drop = (i + 3*j + 5*s) % 11 == 0 || (mask_row && j == 0);
|
||||
f[(s*nb + j)*kv + i] = pad || drop ? -INFINITY : dis(gen);
|
||||
}
|
||||
}
|
||||
@@ -11746,6 +12045,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));
|
||||
@@ -14515,10 +14855,16 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
|
||||
}
|
||||
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias( 64, 2, 3, 768, 7, 2, 17, kv_rows, false));
|
||||
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 8, 3, 512, 65, 1, 1025, kv_rows));
|
||||
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, 1, 1, 17, kv_rows, true, GGML_TYPE_F8_E4M3));
|
||||
for (ggml_type type : {GGML_TYPE_Q8_0, GGML_TYPE_Q4_0}) {
|
||||
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, 1, 1, 17, kv_rows, true, type));
|
||||
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, 7, 2, 17, kv_rows, true, type));
|
||||
}
|
||||
for (int64_t nb : {1, 7}) {
|
||||
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 700, nb, 2, 17, kv_rows));
|
||||
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, nb, 2, 17, kv_rows, true, GGML_TYPE_F16, 10.0f));
|
||||
test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, nb, 2, 17, kv_rows, false, GGML_TYPE_F16, 0.0f, true));
|
||||
}
|
||||
}
|
||||
|
||||
// sparse mask with large batch size
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -36,7 +36,7 @@ CASES = [
|
||||
draft=None,
|
||||
n_max=3,
|
||||
min_accept_rate=0.6040,
|
||||
min_accept_len=2.7766,
|
||||
min_accept_len=2.65,
|
||||
),
|
||||
SpecCase(
|
||||
name="dflash",
|
||||
@@ -45,7 +45,7 @@ CASES = [
|
||||
draft="dflash-Qwen3-4B-Q4_K_M.gguf",
|
||||
n_max=7,
|
||||
min_accept_rate=0.1404,
|
||||
min_accept_len=2.1687,
|
||||
min_accept_len=2.10,
|
||||
),
|
||||
SpecCase(
|
||||
name="dspark",
|
||||
@@ -54,7 +54,7 @@ CASES = [
|
||||
draft="dspark-Qwen3-4B-Q4_K_M.gguf",
|
||||
n_max=7,
|
||||
min_accept_rate=0.2767,
|
||||
min_accept_len=3.1246,
|
||||
min_accept_len=3.05,
|
||||
),
|
||||
SpecCase(
|
||||
name="eagle3",
|
||||
@@ -63,7 +63,7 @@ CASES = [
|
||||
draft="eagle3-Qwen3-4B-Q8_0.gguf",
|
||||
n_max=3,
|
||||
min_accept_rate=0.2006,
|
||||
min_accept_len=1.5757,
|
||||
min_accept_len=1.50,
|
||||
),
|
||||
# Nightly floors retain the earlier three-point rate and 0.2 length margins.
|
||||
SpecCase(
|
||||
@@ -73,7 +73,7 @@ CASES = [
|
||||
draft="dflash2-Qwen3.8-27B-Q8_0.gguf",
|
||||
n_max=7,
|
||||
min_accept_rate=0.5180,
|
||||
min_accept_len=4.5414,
|
||||
min_accept_len=4.50,
|
||||
),
|
||||
SpecCase(
|
||||
name="lilicorr",
|
||||
@@ -82,7 +82,7 @@ CASES = [
|
||||
draft="lilicorr-NVIDIA-Nemotron-3.5-Bolt-74B-A9B-24GB-NVFP4.gguf",
|
||||
n_max=7,
|
||||
min_accept_rate=0.6399,
|
||||
min_accept_len=5.4444,
|
||||
min_accept_len=5.40,
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
+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 {
|
||||
|
||||
@@ -64,7 +64,6 @@
|
||||
} from '#lib/types/index.ts';
|
||||
import {
|
||||
buildMentionInsertion,
|
||||
findCommandToken,
|
||||
findMentionToken,
|
||||
getConversationModel,
|
||||
isIMEComposing,
|
||||
@@ -140,6 +139,7 @@
|
||||
let pickersRef: { handleKeydown: (event: KeyboardEvent) => boolean } | undefined =
|
||||
$state(undefined);
|
||||
let inputRef: ChatFormInput | undefined = $state(undefined);
|
||||
let workingDirectoryRef: ChatFormCurrentWorkingDirectory | undefined = $state(undefined);
|
||||
|
||||
// Voice input
|
||||
const recorder: VoiceRecorderLike = untrack(() => voiceRecorder) ?? new VoiceRecorder();
|
||||
@@ -148,8 +148,8 @@
|
||||
/** Why the last start failed (denied, no microphone, busy); the next tap tries again. */
|
||||
let micError = $state<string | null>(null);
|
||||
|
||||
// Invisible anchor the pickers' popovers float above: the form's top edge, or in the
|
||||
// expanded editor the line being written
|
||||
// Invisible anchor the pickers' popovers float above: the line being written, or on a
|
||||
// phone the form's top edge
|
||||
let pickerAnchor: HTMLDivElement | null = $state(null);
|
||||
let pickerAnchorBox = $state({ height: 1, top: 0 });
|
||||
|
||||
@@ -174,6 +174,8 @@
|
||||
conversationsStore.activeConversation ? systemMessage?.content : undefined
|
||||
);
|
||||
|
||||
// a system message is the same whichever model answers: its editor offers no selector
|
||||
let isModelSelectorShown = $derived(showModelSelector && !systemMode);
|
||||
let showWorkingDirectory = $derived(conversationsStore.preferences.hasEnabledCwdTools());
|
||||
// On a desktop the chip under the form shows a directory once one is set, and the + menu
|
||||
// sets one until then. A phone has no chip: a chat shows it in its header (see
|
||||
@@ -185,12 +187,16 @@
|
||||
|
||||
const pickers = useChatFormPickers({
|
||||
canCompact: () => chatStore.canCompact(conversationsStore.activeMessages),
|
||||
canEditSystemMessage: () => !!onSystemPromptClick && !systemMode,
|
||||
// a phone picks in a drawer with its own search field, and a touch screen opens no
|
||||
// typed pickers (see opensOnInput)
|
||||
editsCwdInline: () => !deviceStore.isMobile && !deviceStore.isTouch,
|
||||
focusInput: refocusInput,
|
||||
getCaretOffset: () => inputRef?.getCaretOffset(),
|
||||
getCwd: () => cwd,
|
||||
getPickersRef: () => pickersRef,
|
||||
getServerHome: () => toolsStore.serverHome ?? null,
|
||||
getShowModelSelector: () => showModelSelector,
|
||||
getShowModelSelector: () => isModelSelectorShown,
|
||||
getValue: () => value,
|
||||
hasCwdTools: () => conversationsStore.preferences.hasEnabledCwdTools(),
|
||||
// policy-aware, same rule as the agentic flow: MCP category on and at
|
||||
@@ -205,12 +211,17 @@
|
||||
.some((s) => s.enabled && prefs.isServerToolsEnabled(s.id) && s.url.trim());
|
||||
},
|
||||
onCompact: () => chatStore.compactConversation(),
|
||||
onSystemMessage: () => onSystemPromptClick?.({ files: uploadedFiles, message: value }),
|
||||
openModelSelector: () => chatFormActionsRef?.openModelSelector(),
|
||||
// TODO: no typed pickers with an on-screen keyboard for now: each mobile browser moves
|
||||
// the page its own way as it opens, so a list by the form can not stay clear of the
|
||||
// text. A drawer with its own search field (as the directory picker is) could.
|
||||
opensOnInput: () => !deviceStore.isTouch,
|
||||
setCaretOffset: (offset) => inputRef?.setCaretOffset(offset),
|
||||
setCaretOffset: (offset) => {
|
||||
inputRef?.setCaretOffset(offset);
|
||||
// the caret moved without typing, e.g. onto the `/cwd` line the + menu just added
|
||||
measurePickerAnchor();
|
||||
},
|
||||
setValue: (v) => {
|
||||
value = v;
|
||||
onValueChange?.(v);
|
||||
@@ -237,14 +248,9 @@
|
||||
});
|
||||
|
||||
async function handleWorkingDirectoryChange(newDir: string | null) {
|
||||
// Committing a directory consumes the `/cwd` token; the chip's
|
||||
// clear-X path has no token to consume.
|
||||
const token = findCommandToken(value);
|
||||
|
||||
if (token && token.name === 'cwd') {
|
||||
value = '';
|
||||
onValueChange?.('');
|
||||
}
|
||||
// Committing a directory consumes the `/cwd` line and keeps the message below it; the
|
||||
// chip's clear-X path has no line to consume.
|
||||
pickers.consumeCwdCommand();
|
||||
|
||||
await conversationsStore.preferences.setCwd(newDir);
|
||||
|
||||
@@ -365,18 +371,30 @@
|
||||
isExpanded && deviceStore.isMobile ? (actionsEl ?? null) : pickerAnchor
|
||||
);
|
||||
|
||||
// The anchor covers the caret's line, kept within the form when the line is scrolled out
|
||||
// of the editor's view; on a phone the form's top edge
|
||||
function measurePickerAnchor() {
|
||||
const line = deviceStore.isMobile ? null : inputRef?.getCaretRect();
|
||||
const form = pickerAnchor?.parentElement?.getBoundingClientRect();
|
||||
|
||||
if (!line || !form) {
|
||||
pickerAnchorBox = { height: 1, top: 0 };
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const top = Math.min(Math.max(line.top - form.top, 0), form.height);
|
||||
|
||||
pickerAnchorBox = { height: Math.max(line.bottom - line.top, 1), top };
|
||||
}
|
||||
|
||||
// before the popover is drawn, and again as the query is typed and the line moves
|
||||
$effect.pre(() => {
|
||||
if (!isPickerOpen) return;
|
||||
|
||||
void value;
|
||||
|
||||
const line = isExpanded && !deviceStore.isMobile ? inputRef?.getCaretRect() : null;
|
||||
const formTop = pickerAnchor?.parentElement?.getBoundingClientRect().top ?? 0;
|
||||
|
||||
pickerAnchorBox = line
|
||||
? { height: line.bottom - line.top, top: line.top - formTop }
|
||||
: { height: 1, top: 0 };
|
||||
measurePickerAnchor();
|
||||
});
|
||||
// shown on hover (always on touch screens) while collapsed, always while expanded: on
|
||||
// the phone sheet it keeps the collapsed card's place, below the status bar
|
||||
@@ -447,7 +465,14 @@
|
||||
function handleKeydown(event: KeyboardEvent) {
|
||||
// Pickers consume navigation/escape keys first; when consumed, skip
|
||||
// the enter-to-submit logic below and keep the key from the editor.
|
||||
if (pickers.handleKeydown(event)) {
|
||||
// The directory picker takes the keys typed on its `/cwd` line; in the message below
|
||||
// it only Escape, so Enter and the arrows there stay the message's
|
||||
const isDirectoryKey = pickers.isCaretInCwdCommand() || event.key === KeyboardKey.ESCAPE;
|
||||
|
||||
if (
|
||||
(isDirectoryKey && workingDirectoryRef?.handleKeydown(event)) ||
|
||||
pickers.handleKeydown(event)
|
||||
) {
|
||||
event.preventDefault();
|
||||
|
||||
return;
|
||||
@@ -678,6 +703,13 @@
|
||||
async function submit() {
|
||||
if (!canSubmit || disabled || hasLoadingAttachments || isSendWaiting) return;
|
||||
|
||||
// sending closes the directory picker first, so its `/cwd` command is not sent as text
|
||||
if (pickers.isWorkingDirectoryPickerOpen) {
|
||||
pickers.handleWorkingDirectoryClose();
|
||||
|
||||
if (!canSubmit) return;
|
||||
}
|
||||
|
||||
if (voice.isRefining) {
|
||||
isSendWaiting = true;
|
||||
|
||||
@@ -809,7 +841,9 @@
|
||||
'max-md:border-transparent max-md:focus-within:border-transparent max-md:dark:border-transparent max-md:dark:focus-within:border-transparent',
|
||||
EXPANDED_SHEET_FILL
|
||||
],
|
||||
systemMode && '!border-2 !border-dashed !border-border/50 !bg-muted',
|
||||
// a dashed outline stands in for the card's edge, drawn inside it: the card keeps its size
|
||||
systemMode &&
|
||||
'!bg-muted !outline-2 -outline-offset-2 !outline-dashed !outline-border/50 [--glass-edge-focus:transparent] [--glass-edge:transparent]',
|
||||
disabled && 'cursor-not-allowed opacity-60'
|
||||
]}
|
||||
data-single-row={isSingleRow || undefined}
|
||||
@@ -920,7 +954,7 @@
|
||||
? pickers.handleWorkingDirectoryOpen
|
||||
: undefined}
|
||||
{showAddButton}
|
||||
{showModelSelector}
|
||||
showModelSelector={isModelSelectorShown}
|
||||
voice={{
|
||||
action: voice.label,
|
||||
hint: voice.hint,
|
||||
@@ -952,15 +986,21 @@
|
||||
></div>
|
||||
{/if}
|
||||
|
||||
<div class="flex flex-wrap items-center gap-x-1 self-start">
|
||||
<!-- The chips sit under the card. On a new chat, where the page centres the form, they
|
||||
hang below it and take no room: the card stays where it is as they come and go -->
|
||||
<div
|
||||
class="flex flex-wrap items-center gap-x-1 self-start md:group-data-[chat-form-lifted]/chat-form-host:absolute md:group-data-[chat-form-lifted]/chat-form-host:top-full"
|
||||
>
|
||||
{#if showWorkingDirectory}
|
||||
<!-- opened from the chip, the + menu, a phone chat's header or `/cwd` -->
|
||||
<ChatFormCurrentWorkingDirectory
|
||||
bind:query={pickers.workingDirectoryQuery}
|
||||
bind:this={workingDirectoryRef}
|
||||
class="self-start"
|
||||
customAnchor={activePickerAnchor}
|
||||
directory={cwd}
|
||||
{disabled}
|
||||
inline={pickers.isWorkingDirectoryInline}
|
||||
isOpen={pickers.isWorkingDirectoryPickerOpen}
|
||||
onChange={handleWorkingDirectoryChange}
|
||||
onClose={pickers.handleWorkingDirectoryClose}
|
||||
|
||||
+93
-50
@@ -8,20 +8,23 @@
|
||||
import {
|
||||
CHAT_FORM_CHIP_SPLIT,
|
||||
CHAT_FORM_CHIP_TRANSITION_MS,
|
||||
CHAT_FORM_PATH_PICKER_WIDTH_CLASS,
|
||||
DEFAULT_MOBILE_BREAKPOINT,
|
||||
HOME_TILDE,
|
||||
SEARCH,
|
||||
UI_DATA_ATTRS
|
||||
} from '#lib/constants/index.ts';
|
||||
import { BuiltInTool, GlobSearchType, KeyboardKey, ToolSource } from '#lib/enums/index.ts';
|
||||
import { BuiltInTool, KeyboardKey, ToolSource } from '#lib/enums/index.ts';
|
||||
import { useDebouncedSearch } from '#lib/hooks/use-debounced-search.svelte.ts';
|
||||
import { usePickerNavigation } from '#lib/hooks/use-picker-navigation.svelte.ts';
|
||||
import { useScrollActiveRow } from '#lib/hooks/use-scroll-active-row.svelte.ts';
|
||||
import { ToolsService } from '#lib/services/tools.service.ts';
|
||||
import { conversationsStore, deviceStore, toolsStore } from '#lib/stores/index.ts';
|
||||
import type { GlobSearchChildResult } from '#lib/types/glob.js';
|
||||
import {
|
||||
abbreviateHome,
|
||||
runGlobSearchWithChildren,
|
||||
isIMEComposing,
|
||||
runFolderSearch,
|
||||
toHomeRelativeQuery
|
||||
} from '#lib/utils/index.ts';
|
||||
import { page } from '$app/state';
|
||||
@@ -37,6 +40,9 @@
|
||||
/** Controlled open state; the host owns it so the chip, the + menu and the
|
||||
* `/cwd` slash command open the picker through the same path. */
|
||||
isOpen: boolean;
|
||||
/** The path is typed on the chat input's `/cwd` line: no search field of its own, and
|
||||
* the host forwards the input's keys through `handleKeydown`. */
|
||||
inline?: boolean;
|
||||
/** Two-way bound query, kept in sync with the text after `/cwd `. */
|
||||
query: string;
|
||||
/** Anchor at the form's top edge so the popover floats above the box. */
|
||||
@@ -55,6 +61,7 @@
|
||||
customAnchor = null,
|
||||
directory = null,
|
||||
disabled = false,
|
||||
inline = false,
|
||||
isOpen,
|
||||
onChange,
|
||||
onClose,
|
||||
@@ -109,7 +116,7 @@
|
||||
|
||||
// HTML `autofocus` is unreliable on dynamically shown elements.
|
||||
$effect(() => {
|
||||
if (!isOpen) return;
|
||||
if (!isOpen || inline) return;
|
||||
|
||||
setTimeout(() => searchInputRef?.focus(), FOCUS_DELAY_MS);
|
||||
});
|
||||
@@ -160,32 +167,14 @@
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Generous limit: ranking is client-side, only the top
|
||||
// MAX_RESULTS_SHOWN are shown.
|
||||
// A plain query navigates home as if typed after `~/`; a query
|
||||
// starting from a root or `~` navigates the absolute tree.
|
||||
const res = await runGlobSearchWithChildren(
|
||||
toHomeRelativeQuery(trimmed, homeBase),
|
||||
homeBase ?? HOME_TILDE,
|
||||
SEARCH.MAX_DEPTH,
|
||||
SEARCH.LIMIT,
|
||||
signal,
|
||||
{ type: GlobSearchType.DIR }
|
||||
);
|
||||
|
||||
// Every round of results starts with its first folder highlighted. A stale
|
||||
// search must not touch the list: the next one is already running.
|
||||
const show = (res: GlobSearchChildResult) => {
|
||||
if (!isCurrent()) return;
|
||||
|
||||
if (res.error) {
|
||||
queryResults = [];
|
||||
nav.reset(-1);
|
||||
searchError = res.error;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
searchScope = res.exactDir ?? res.args.path;
|
||||
queryResults = res.entries.map((e) => e.path).slice(0, SEARCH.MAX_RESULTS_SHOWN);
|
||||
searchError = res.error ?? null;
|
||||
|
||||
if (queryResults.length > 0) {
|
||||
nav.reset(0);
|
||||
@@ -193,8 +182,10 @@
|
||||
} else {
|
||||
nav.reset(-1);
|
||||
}
|
||||
};
|
||||
|
||||
searchError = null;
|
||||
try {
|
||||
show(await runFolderSearch(trimmed, homeBase, signal, show));
|
||||
} catch (err) {
|
||||
if (!isCurrent() || signal.aborted) return;
|
||||
|
||||
@@ -261,25 +252,60 @@
|
||||
closePicker();
|
||||
}
|
||||
|
||||
function handleKeydown(event: KeyboardEvent) {
|
||||
if (event.key === KeyboardKey.ENTER) {
|
||||
/** True when the key was the picker's: the chat input then leaves it alone. */
|
||||
function handlePickerKeydown(event: KeyboardEvent): boolean {
|
||||
// a key that confirms or moves within an IME composition belongs to the text
|
||||
if (isIMEComposing(event)) return false;
|
||||
|
||||
// Enter picks a suggestion, never the typed text: before the results arrive it does
|
||||
// nothing. Only without file search, where nothing is suggested, does it take the path
|
||||
// as typed
|
||||
if (event.key === KeyboardKey.ENTER && !event.shiftKey) {
|
||||
event.preventDefault();
|
||||
|
||||
if (nav.hoveredIndex >= 0 && queryResults[nav.hoveredIndex]) {
|
||||
commit(queryResults[nav.hoveredIndex]);
|
||||
} else if (queryResults.length === 0) {
|
||||
} else if (!fileSearchEnabled) {
|
||||
handleSubmit();
|
||||
}
|
||||
} else if (event.key === KeyboardKey.ARROW_DOWN) {
|
||||
if (queryResults.length > 0) {
|
||||
event.preventDefault();
|
||||
nav.move(1);
|
||||
}
|
||||
} else if (event.key === KeyboardKey.ARROW_UP) {
|
||||
if (queryResults.length > 0) {
|
||||
event.preventDefault();
|
||||
nav.move(-1);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (
|
||||
(event.key === KeyboardKey.ARROW_DOWN || event.key === KeyboardKey.ARROW_UP) &&
|
||||
queryResults.length > 0
|
||||
) {
|
||||
event.preventDefault();
|
||||
nav.move(event.key === KeyboardKey.ARROW_DOWN ? 1 : -1);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (inline && event.key === KeyboardKey.ESCAPE) {
|
||||
event.preventDefault();
|
||||
closePicker();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The chat input's keys while the path is typed on its `/cwd` line. */
|
||||
export function handleKeydown(event: KeyboardEvent): boolean {
|
||||
if (!isOpen || !inline) return false;
|
||||
|
||||
return handlePickerKeydown(event);
|
||||
}
|
||||
|
||||
// Inline, the chat input is the picker's field: pressing in the form (to move the caret,
|
||||
// say) keeps the picker open
|
||||
function handleInteractOutside(event: PointerEvent) {
|
||||
const target = event.target;
|
||||
|
||||
if (inline && target instanceof Node && customAnchor?.closest('form')?.contains(target)) {
|
||||
event.preventDefault();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -380,14 +406,27 @@
|
||||
<!-- the drawer's version is roomier: the header's inset, rows spaced for a finger and
|
||||
lined up with the search results, and text sized for a phone -->
|
||||
{#snippet picker(inDrawer: boolean)}
|
||||
<div class={inDrawer ? 'flex flex-col gap-1 px-4' : 'p-2 min-h-22 flex flex-col justify-between'}>
|
||||
<SearchInput
|
||||
bind:ref={searchInputRef}
|
||||
bind:value={query}
|
||||
class="w-full"
|
||||
onClose={closePicker}
|
||||
placeholder="Choose working directory"
|
||||
/>
|
||||
<!-- inline there is no search field to keep room for, only the rows below the line -->
|
||||
<div
|
||||
class={inDrawer
|
||||
? 'flex flex-col gap-1 px-4'
|
||||
: ['flex flex-col justify-between p-2', !inline && 'min-h-22']}
|
||||
>
|
||||
{#if inline}
|
||||
{#if fileSearchEnabled && !query.trim()}
|
||||
<div class="px-2 py-1.5 text-body-sm text-muted-foreground">
|
||||
Type a folder name or path after <span class="font-mono">/cwd</span>
|
||||
</div>
|
||||
{/if}
|
||||
{:else}
|
||||
<SearchInput
|
||||
bind:ref={searchInputRef}
|
||||
bind:value={query}
|
||||
class="w-full"
|
||||
onClose={closePicker}
|
||||
placeholder="Choose working directory"
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if !fileSearchEnabled}
|
||||
<div class="px-2 py-1.5 text-body-sm text-muted-foreground">{searchUnavailableMessage}</div>
|
||||
@@ -460,7 +499,7 @@
|
||||
<!-- a phone picks in a drawer from the screen's bottom; elsewhere a popover above the form -->
|
||||
{#if deviceStore.isMobile}
|
||||
<Drawer.Root onOpenChange={handleOpenChange} open={isOpen}>
|
||||
<Drawer.Content class="gap-0" onkeydown={handleKeydown}>
|
||||
<Drawer.Content class="gap-0" onkeydown={handlePickerKeydown}>
|
||||
<Drawer.Header>
|
||||
<Drawer.Title>Working directory</Drawer.Title>
|
||||
|
||||
@@ -484,16 +523,20 @@
|
||||
<span class="sr-only">Open working directory picker</span>
|
||||
</Popover.Trigger>
|
||||
|
||||
<!-- inline, the focus stays in the chat input, where the path is typed: a trap would
|
||||
pull it into the list as the + menu closes -->
|
||||
<Popover.Content
|
||||
align="start"
|
||||
class="w-[var(--bits-popover-anchor-width)] max-w-none rounded-xl p-0"
|
||||
class={[CHAT_FORM_PATH_PICKER_WIDTH_CLASS, 'rounded-xl p-0']}
|
||||
{customAnchor}
|
||||
onCloseAutoFocus={(event) => event.preventDefault()}
|
||||
onInteractOutside={handleInteractOutside}
|
||||
onOpenAutoFocus={(event) => event.preventDefault()}
|
||||
onkeydown={handleKeydown}
|
||||
onkeydown={handlePickerKeydown}
|
||||
preventScroll={false}
|
||||
side="top"
|
||||
sideOffset={12}
|
||||
trapFocus={!inline}
|
||||
>
|
||||
{@render picker(false)}
|
||||
</Popover.Content>
|
||||
|
||||
+4
-2
@@ -2,7 +2,7 @@
|
||||
import { cn } from '@ggml-org/llama-ui/utils';
|
||||
import { Folder } from '@lucide/svelte';
|
||||
import { UI_DATA_ATTRS } from '#lib/constants/index.ts';
|
||||
import { highlightMatch } from '#lib/utils/index.ts';
|
||||
import { hasPointerMoved, highlightMatch } from '#lib/utils/index.ts';
|
||||
import { fly } from 'svelte/transition';
|
||||
|
||||
// Fly-in transition for the results list.
|
||||
@@ -53,7 +53,9 @@
|
||||
)}
|
||||
data-highlighted={index === hoveredIndex ? '' : undefined}
|
||||
onclick={() => onCommit?.(path)}
|
||||
onmouseenter={() => onHover?.(index)}
|
||||
onmousemove={(event) => {
|
||||
if (hasPointerMoved(event)) onHover?.(index);
|
||||
}}
|
||||
>
|
||||
<Folder class="size-4 shrink-0 text-muted-foreground" />
|
||||
|
||||
|
||||
+7
-3
@@ -1,12 +1,14 @@
|
||||
<script lang="ts">
|
||||
import { UI_DATA_ATTRS } from '#lib/constants/index.ts';
|
||||
import { hasPointerMoved } from '#lib/utils/index.ts';
|
||||
import type { Snippet } from 'svelte';
|
||||
|
||||
interface Props {
|
||||
isSelected?: boolean;
|
||||
disabled?: boolean;
|
||||
onclick: () => void;
|
||||
onmouseenter?: () => void;
|
||||
/** Called when the user moves the pointer over the row, not when the row renders under it. */
|
||||
onhover?: () => void;
|
||||
dataIndex?: number;
|
||||
children: Snippet;
|
||||
class?: string;
|
||||
@@ -19,14 +21,16 @@
|
||||
disabled = false,
|
||||
isSelected = false,
|
||||
onclick,
|
||||
onmouseenter
|
||||
onhover
|
||||
}: Props = $props();
|
||||
</script>
|
||||
|
||||
<button
|
||||
{disabled}
|
||||
{onclick}
|
||||
{onmouseenter}
|
||||
onmousemove={(event) => {
|
||||
if (hasPointerMoved(event)) onhover?.();
|
||||
}}
|
||||
type="button"
|
||||
{...{ [UI_DATA_ATTRS.PICKER_INDEX]: dataIndex }}
|
||||
class="flex w-full cursor-pointer items-start gap-3 rounded-lg px-3 py-2 text-left hover:bg-accent/50 {isSelected
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import * as Popover from '@ggml-org/llama-ui/ui/popover';
|
||||
import { CHAT_FORM_PICKER_WIDTH_CLASS } from '#lib/constants/index.ts';
|
||||
import type { Snippet } from 'svelte';
|
||||
|
||||
interface Props {
|
||||
@@ -42,7 +43,7 @@
|
||||
|
||||
<Popover.Content
|
||||
align="start"
|
||||
class="w-[var(--bits-popover-anchor-width)] max-w-none rounded-xl p-0 {className}"
|
||||
class={[CHAT_FORM_PICKER_WIDTH_CLASS, 'rounded-xl p-0', className]}
|
||||
{customAnchor}
|
||||
onOpenAutoFocus={(event) => event.preventDefault()}
|
||||
onkeydown={onKeydown}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user