diff --git a/.devops/cann.Dockerfile b/.devops/cann.Dockerfile index 83df409506fd..791b583ca6a5 100644 --- a/.devops/cann.Dockerfile +++ b/.devops/cann.Dockerfile @@ -25,9 +25,10 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI from its source next to it +# the app compiles Llama UI and Llama Voice from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ +COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM ${CANN_BASE_IMAGE} AS build diff --git a/.devops/cpu.Dockerfile b/.devops/cpu.Dockerfile index e195b5ac8b53..f63e005ec930 100644 --- a/.devops/cpu.Dockerfile +++ b/.devops/cpu.Dockerfile @@ -15,9 +15,10 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI from its source next to it +# the app compiles Llama UI and Llama Voice from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ +COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/ubuntu:$UBUNTU_VERSION AS build diff --git a/.devops/cuda.Dockerfile b/.devops/cuda.Dockerfile index 20501c1beac2..cf1715d43a4c 100644 --- a/.devops/cuda.Dockerfile +++ b/.devops/cuda.Dockerfile @@ -23,9 +23,10 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI from its source next to it +# the app compiles Llama UI and Llama Voice from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ +COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM ${BASE_CUDA_DEV_CONTAINER} AS build diff --git a/.devops/intel.Dockerfile b/.devops/intel.Dockerfile index 16326ebbdea5..0783ef738c9f 100644 --- a/.devops/intel.Dockerfile +++ b/.devops/intel.Dockerfile @@ -17,9 +17,10 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI from its source next to it +# the app compiles Llama UI and Llama Voice from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ +COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/intel/deep-learning-essentials:$ONEAPI_VERSION AS build diff --git a/.devops/musa.Dockerfile b/.devops/musa.Dockerfile index dbf9e0b41122..3ae62a676e4b 100644 --- a/.devops/musa.Dockerfile +++ b/.devops/musa.Dockerfile @@ -21,9 +21,10 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI from its source next to it +# the app compiles Llama UI and Llama Voice from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ +COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM ${BASE_MUSA_DEV_CONTAINER} AS build diff --git a/.devops/openvino.Dockerfile b/.devops/openvino.Dockerfile index c88cc2bbb5f9..fb8cb4c61f66 100644 --- a/.devops/openvino.Dockerfile +++ b/.devops/openvino.Dockerfile @@ -34,9 +34,10 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI from its source next to it +# the app compiles Llama UI and Llama Voice from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ +COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build ## Build Image diff --git a/.devops/rocm.Dockerfile b/.devops/rocm.Dockerfile index 9e667660f00e..ba9e85a0ed19 100644 --- a/.devops/rocm.Dockerfile +++ b/.devops/rocm.Dockerfile @@ -23,9 +23,10 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI from its source next to it +# the app compiles Llama UI and Llama Voice from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ +COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build ### Build image diff --git a/.devops/vulkan.Dockerfile b/.devops/vulkan.Dockerfile index dc8a87667205..023847628366 100644 --- a/.devops/vulkan.Dockerfile +++ b/.devops/vulkan.Dockerfile @@ -15,9 +15,10 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI from its source next to it +# the app compiles Llama UI and Llama Voice from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ +COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/ubuntu:$UBUNTU_VERSION AS build diff --git a/.devops/zendnn.Dockerfile b/.devops/zendnn.Dockerfile index cbc3696ed643..e49df81ca45f 100644 --- a/.devops/zendnn.Dockerfile +++ b/.devops/zendnn.Dockerfile @@ -15,9 +15,10 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI from its source next to it +# the app compiles Llama UI and Llama Voice from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ +COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/ubuntu:$UBUNTU_VERSION AS build diff --git a/.github/workflows/build-ibm.yml b/.github/workflows/build-ibm.yml index 67ca8b683e40..598b09be775a 100644 --- a/.github/workflows/build-ibm.yml +++ b/.github/workflows/build-ibm.yml @@ -137,8 +137,8 @@ jobs: -DCMAKE_CXX_FLAGS="-march=arch15" time cmake --build build --config Release -j $(nproc) - ubuntu-24-ppc64le: - runs-on: ubuntu-24.04-ppc64le + ubuntu-26-ppc64le: + runs-on: ubuntu-26.04-ppc64le steps: - name: Clone @@ -154,12 +154,6 @@ jobs: libjpeg-dev build-essential libssl-dev \ git-lfs - - name: Toolchain workaround (GCC 14) - run: | - sudo apt-get install -y gcc-14 g++-14 - echo "CC=gcc-14" >> "$GITHUB_ENV" - echo "CXX=g++-14" >> "$GITHUB_ENV" - - name: Python Dependencies id: python_depends run: | diff --git a/.github/workflows/build-openvino.yml b/.github/workflows/build-openvino.yml index 009bde4e48fb..9e092b52be19 100644 --- a/.github/workflows/build-openvino.yml +++ b/.github/workflows/build-openvino.yml @@ -40,61 +40,6 @@ env: CTEST_EXCLUDE: "test-llama-archs|test-llama-context|test-fp8-kv" jobs: - ubuntu-24-openvino: - runs-on: [self-hosted, Linux, Intel, OpenVINO] - - env: - # Sync versions in build-openvino.yml, ci-self-hosted-openvino.yml, release.yml, release-publish.yml, build-cache.yml, .devops/openvino.Dockerfile, docs/backend/OPENVINO.md - OPENVINO_VERSION_MAJOR: "2026.4.1" - OPENVINO_VERSION_FULL: "2026.4.1.22982.07f9c262b05" - - 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 libssl-dev libtbb12 cmake ninja-build python3-pip - sudo apt-get install -y ocl-icd-opencl-dev opencl-headers opencl-clhpp-headers intel-opencl-icd - - - name: Setup OpenVINO Toolkit - uses: ./.github/actions/linux-setup-openvino - with: - path: ./openvino_toolkit - version_major: ${{ env.OPENVINO_VERSION_MAJOR }} - version_full: ${{ env.OPENVINO_VERSION_FULL }} - - - name: Install OpenVINO dependencies - run: | - cd ./openvino_toolkit - chmod +x ./install_dependencies/install_openvino_dependencies.sh - echo "Y" | sudo -E ./install_dependencies/install_openvino_dependencies.sh - - - name: Build - id: cmake_build - run: | - source ./openvino_toolkit/setupvars.sh - cmake -B build/ReleaseOV -G Ninja \ - -DCMAKE_BUILD_TYPE=Release \ - -DGGML_OPENVINO=ON - time cmake --build build/ReleaseOV --config Release --parallel - - - name: Test (CPU) - id: cmake_test_cpu - run: | - cd ${{ github.workspace }} - ctest --test-dir build/ReleaseOV -L main -E "${{ env.CTEST_EXCLUDE }}" --verbose --timeout 3000 - - - name: Test (GPU) - id: cmake_test_gpu - run: | - cd ${{ github.workspace }} - export GGML_OPENVINO_DEVICE=GPU - ctest --test-dir build/ReleaseOV -L main -E "${{ env.CTEST_EXCLUDE }}" --verbose --timeout 3000 - openvino-windows-2022: runs-on: windows-2022 diff --git a/.github/workflows/build-wasm.yml b/.github/workflows/build-wasm.yml index bfe57033e899..b2181271a357 100644 --- a/.github/workflows/build-wasm.yml +++ b/.github/workflows/build-wasm.yml @@ -72,7 +72,7 @@ jobs: - name: Fetch emdawnwebgpu run: | - DAWN_TAG="v20260908.214631" + DAWN_TAG="v20261120.121236" EMDAWN_PKG="emdawnwebgpu_pkg-${DAWN_TAG}.zip" echo "Downloading ${EMDAWN_PKG}" curl -L -o emdawn.zip \ diff --git a/.github/workflows/ci-self-hosted-openvino.yml b/.github/workflows/ci-self-hosted-openvino.yml index ef89f004de32..f2df28a42e8f 100644 --- a/.github/workflows/ci-self-hosted-openvino.yml +++ b/.github/workflows/ci-self-hosted-openvino.yml @@ -21,7 +21,9 @@ on: paths: [ '.github/workflows/ci-self-hosted-openvino.yml', 'ci/run.sh', - '**/CMakeLists.txt', + 'CMakeLists.txt', + 'ggml/CMakeLists.txt', + 'tests/CMakeLists.txt', '**/.cmake', 'ggml/src/*', 'ggml/src/ggml-cpu/**', diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 2272ac35aefa..917f3b97fff0 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -120,6 +120,9 @@ jobs: mv build-matrix.json.tmp build-matrix.json fi + jq 'map(select(.tag != "musa"))' build-matrix.json > build-matrix.json.tmp + mv build-matrix.json.tmp build-matrix.json + BUILD_MATRIX="$(jq -c . build-matrix.json)" MERGE_MATRIX="$(jq -c ' reduce .[] as $entry ({}; .[$entry.tag] |= ( diff --git a/.github/workflows/server-sanitize.yml b/.github/workflows/server-sanitize.yml index 4202c31e7cc1..aececfe2f6d5 100644 --- a/.github/workflows/server-sanitize.yml +++ b/.github/workflows/server-sanitize.yml @@ -42,6 +42,8 @@ env: LLAMA_ARG_LOG_PREFIX: 1 LLAMA_ARG_LOG_TIMESTAMPS: 1 LLAMA_ARG_LOG_VERBOSITY: 10 + # [TAG_MTMD_NO_REALLOC] must match -DGGML_SCHED_NO_REALLOC=ON below, skips tests that are known to realloc + GGML_SCHED_NO_REALLOC: ON concurrency: group: ${{ github.workflow }}-${{ github.ref }}-${{ github.head_ref || github.run_id }} diff --git a/.github/workflows/server-self-hosted.yml b/.github/workflows/server-self-hosted.yml index c5dd86449c5e..e54469964eac 100644 --- a/.github/workflows/server-self-hosted.yml +++ b/.github/workflows/server-self-hosted.yml @@ -39,6 +39,8 @@ env: LLAMA_ARG_LOG_PREFIX: 1 LLAMA_ARG_LOG_TIMESTAMPS: 1 LLAMA_ARG_LOG_VERBOSITY: 10 + # [TAG_MTMD_NO_REALLOC] must match -DGGML_SCHED_NO_REALLOC=ON below, skips tests that are known to realloc + GGML_SCHED_NO_REALLOC: ON concurrency: group: ${{ github.workflow }}-${{ github.ref }}-${{ github.head_ref || github.run_id }} diff --git a/.github/workflows/ui-lib-publish.yml b/.github/workflows/ui-lib-publish.yml index 0faf11c4d6ab..a1258cda4549 100644 --- a/.github/workflows/ui-lib-publish.yml +++ b/.github/workflows/ui-lib-publish.yml @@ -18,6 +18,10 @@ name: UI Lib Publish # ui-lib-publish.yml, and Environment left blank - this job names no environment, since creating # one needs repository admin. Merging this workflow before that exists leaves the publish step # red on master: the release is late rather than wrong, and re-running the job publishes it. +# +# The unscoped llama-ui is an alias: once the scoped package is out, the same build is renamed +# and published again at the same version, so the two never drift. It is a package of its own +# on npm, and needs the same trusted publisher set on it. on: workflow_dispatch: @@ -128,26 +132,29 @@ jobs: npm publish --access public --provenance --ignore-scripts --tag "$TAG" working-directory: ${{ env.LIB_DIR }} - - name: Verify it landed - if: github.ref == 'refs/heads/master' && steps.version.outputs.should_publish == 'true' && inputs.dry_run != true + - name: Rename the build to the unscoped alias + # after the scoped publish, so nothing above sees the changed name. Not on a PR: the + # advisory check there is about the version, which the alias shares. + if: github.event_name != 'pull_request' + run: node scripts/alias-package.mjs + working-directory: ${{ env.LIB_DIR }} + + - name: Compare the alias with npm + id: alias + if: github.event_name != 'pull_request' + run: node scripts/npm-version-check.mjs + working-directory: ${{ env.LIB_DIR }} + + - name: Publish the alias + # its own verdict rather than the scoped one's, so an alias that fell behind catches up + # on the next run instead of waiting for a bump + if: github.ref == 'refs/heads/master' && steps.alias.outputs.should_publish == 'true' && inputs.dry_run != true env: - NAME: ${{ steps.version.outputs.name }} - VERSION: ${{ steps.version.outputs.version }} + TAG: ${{ steps.alias.outputs.tag }} run: | - # the registry can serve a new version some time after publish returns, so retry rather - # than call a release that worked a failure - for try in 1 2 3 4 5 6; do - seen=$(npm view "$NAME@$VERSION" version 2>/dev/null || true) - if [ "$seen" = "$VERSION" ]; then - echo "$NAME@$VERSION is on npm" - npm view "$NAME@$VERSION" dist-tags version dist.integrity - exit 0 - fi - echo "not visible yet (attempt $try of 6)" - sleep 10 - done - echo "::error::$NAME@$VERSION published without error but is not visible on the registry after 6 attempts. The publish did not fail: check the package on npm before publishing again." - exit 1 + test -d dist || { echo "dist/ is missing: nothing was built, so nothing is published"; exit 1; } + npm publish --access public --provenance --ignore-scripts --tag "$TAG" + working-directory: ${{ env.LIB_DIR }} - name: Report if: always() @@ -161,6 +168,11 @@ jobs: NOTE: ${{ steps.version.outputs.note }} SHOULD: ${{ steps.version.outputs.should_publish }} DRY: ${{ inputs.dry_run }} + ALIAS_LATEST: ${{ steps.alias.outputs.latest }} + ALIAS_VERDICT: ${{ steps.alias.outputs.verdict || 'not reached' }} + ALIAS_NOTE: ${{ steps.alias.outputs.note }} + ALIAS_SHOULD: ${{ steps.alias.outputs.should_publish }} + EVENT: ${{ github.event_name }} run: | if [ "$DRY" = "true" ]; then published="no (dry run)" elif [ "$SHOULD" = "true" ]; then published=yes @@ -177,6 +189,23 @@ jobs: echo echo "> $NOTE" } >> "$GITHUB_STEP_SUMMARY" + [ "$EVENT" = "pull_request" ] && exit 0 + if [ "$DRY" = "true" ]; then published="no (dry run)" + elif [ "$ALIAS_SHOULD" = "true" ]; then published=yes + else published=no + fi + { + echo + echo "### llama-ui (alias) $VERSION" + echo + echo "| | |" + echo "| --- | --- |" + echo "| npm latest was | ${ALIAS_LATEST:-nothing published yet} |" + echo "| verdict | \`$ALIAS_VERDICT\` |" + echo "| published | $published |" + echo + echo "> $ALIAS_NOTE" + } >> "$GITHUB_STEP_SUMMARY" - name: Mind the verdict if: always() && github.event_name != 'pull_request' && steps.version.outcome == 'success' diff --git a/.github/workflows/ui-self-hosted.yml b/.github/workflows/ui-self-hosted.yml index 346f1cfb4b12..4967de07ca21 100644 --- a/.github/workflows/ui-self-hosted.yml +++ b/.github/workflows/ui-self-hosted.yml @@ -19,6 +19,7 @@ on: '.github/workflows/ui-build-self-hosted.yml', 'ui/apps/chat/**.*', 'ui/lib/ui/**.*', + 'ui/lib/voice/**.*', 'tools/server/tests/**.*' ] pull_request: @@ -28,6 +29,7 @@ on: '.github/workflows/ui-build-self-hosted.yml', 'ui/apps/chat/**.*', 'ui/lib/ui/**.*', + 'ui/lib/voice/**.*', 'tools/server/tests/**.*' ] diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml index 10d7ed0ed5e4..65e5c36ffdbf 100644 --- a/.github/workflows/ui.yml +++ b/.github/workflows/ui.yml @@ -150,6 +150,37 @@ jobs: run: npm run prepack working-directory: ui/lib/ui + voice-checks: + name: Voice 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/voice + + - name: Run type checking + run: npm run check + working-directory: ui/lib/voice + + - name: Run tests + run: npm test + working-directory: ui/lib/voice + + - name: Build the package + run: npm run prepack + working-directory: ui/lib/voice + e2e-tests: name: E2E Tests needs: ui-build diff --git a/common/arg.cpp b/common/arg.cpp index 192f70607f1e..a638237672bd 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -3420,12 +3420,20 @@ common_params_context common_params_parser_init(common_params & params, llama_ex add_opt(common_arg( {"--ui-mcp-proxy", "--webui-mcp-proxy"}, {"--no-ui-mcp-proxy", "--no-webui-mcp-proxy"}, - "experimental: whether to enable MCP CORS proxy, for Llama Chat to reach public MCP servers without CORS headers; local and private addresses are refused - do not enable in untrusted environments (default: disabled)\n" + "experimental: whether to enable MCP CORS proxy, for Llama Chat to reach public MCP servers without CORS headers; local and private addresses are refused unless --ui-mcp-proxy-allow-private-urls is set - do not enable in untrusted environments (default: disabled)\n" "note: for security reasons, this will limit --cors-origins to localhost by default", [](common_params & params, bool value) { params.ui_mcp_proxy = value; } ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_UI_MCP_PROXY")); + add_opt(common_arg( + {"--ui-mcp-proxy-allow-private-urls"}, + "allow the MCP CORS proxy to reach local or private addresses (e.g. MCP servers on localhost or LAN) - anyone who can reach the proxy can then reach your local network (default: disabled, only public addresses)\n" + "note: only has effect with --ui-mcp-proxy", + [](common_params & params) { + params.ui_mcp_proxy_allow_private_urls = true; + } + ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_UI_MCP_PROXY_ALLOW_PRIVATE_URLS")); add_opt(common_arg( {"--tools"}, "TOOL1,TOOL2,...", "experimental: whether to enable built-in tools for AI agents - do not enable in untrusted environments (default: no tools)\n" diff --git a/common/chat-auto-parser-generator.cpp b/common/chat-auto-parser-generator.cpp index 9b918b366c38..e59a556ad08c 100644 --- a/common/chat-auto-parser-generator.cpp +++ b/common/chat-auto-parser-generator.cpp @@ -69,9 +69,21 @@ common_chat_params peg_generator::generate_parser(const common_chat_template & std::string trigger_marker = !autoparser.tools.format.section_start.empty() ? autoparser.tools.format.section_start : autoparser.tools.format.per_call_start; + // bare JSON calls without a start marker (e.g. Llama 3.x): trigger the lazy grammar on the call's opening instead + std::string trigger_pattern; + { + const auto & fmt = autoparser.tools.format; + bool top_level_name = (fmt.function_field.empty() || fmt.function_field == "function") && + fmt.name_field.find('.') == std::string::npos; + if (trigger_marker.empty() && fmt.mode == tool_format::JSON_NATIVE && !fmt.fun_name_is_key && + !fmt.tools_array_wrapped && top_level_name) { + trigger_pattern = "\\{\\s*\"" + regex_escape(fmt.name_field) + "\"\\s*:"; + } + } + bool has_response_format = !inputs.json_schema.empty() && inputs.json_schema.is_object(); bool include_grammar = has_response_format || (has_tools && - ((inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO && !trigger_marker.empty()) || + ((inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO && (!trigger_marker.empty() || !trigger_pattern.empty())) || inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED)); if (include_grammar) { @@ -82,9 +94,11 @@ common_chat_params peg_generator::generate_parser(const common_chat_template & // Set grammar triggers based on tool section markers (fall back to per-call markers) if (data.grammar_lazy) { - data.grammar_triggers = { - { COMMON_GRAMMAR_TRIGGER_TYPE_WORD, trigger_marker } - }; + if (!trigger_marker.empty()) { + data.grammar_triggers = { { COMMON_GRAMMAR_TRIGGER_TYPE_WORD, trigger_marker } }; + } else { + data.grammar_triggers = { { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, trigger_pattern } }; + } if (autoparser.tools.format.openai_wrapper_trigger) { // model emits the OpenAI function wrapper, trigger on it data.grammar_triggers.push_back({ COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "{\"type\": \"function\"," }); diff --git a/common/common.h b/common/common.h index e16bee7c1629..a8e89ed2dd65 100644 --- a/common/common.h +++ b/common/common.h @@ -702,6 +702,7 @@ struct common_params { // UI configs bool ui = true; bool ui_mcp_proxy = false; + bool ui_mcp_proxy_allow_private_urls = false; // allow the MCP CORS proxy to reach local or private addresses std::string ui_config_json; // "advanced" endpoints are disabled by default for better security diff --git a/common/jinja/caps.cpp b/common/jinja/caps.cpp index cf14c71c56d9..1f967daf6214 100644 --- a/common/jinja/caps.cpp +++ b/common/jinja/caps.cpp @@ -593,7 +593,7 @@ caps caps_get(jinja::program & prog) { if (result.supports_reasoning_effort) { JJ_DEBUG("%s\n", ">>> Running capability check: reasoning effort levels"); - static const std::vector candidates = { "minimal", "low", "medium", "high", "xhigh", "max" }; + static const std::vector candidates = { "none", "minimal", "low", "medium", "high", "xhigh", "max" }; // renders a single user turn with the given effort, nothing when the template raises const auto render = [&](const std::string & effort) { @@ -631,7 +631,10 @@ caps caps_get(jinja::program & prog) { for (const auto & level : candidates) { const auto rendered = render(level); if (!rendered) { - rejected.push_back(level); + // "none" also turns thinking off, so the server does not answer it with an error + if (level != "none") { + rejected.push_back(level); + } continue; } if (rendered == unknown) { diff --git a/conversion/__init__.py b/conversion/__init__.py index 1182c06be3c0..146c309e65a7 100644 --- a/conversion/__init__.py +++ b/conversion/__init__.py @@ -78,6 +78,7 @@ "DistilBertForMaskedLM": "bert", "DistilBertForSequenceClassification": "bert", "DistilBertModel": "bert", + "DomynEdgeForCausalLM": "domynedge", "Dots1ForCausalLM": "dots1", "Dots3NoteForCausalLM": "dots3", "Dots3NoteForConditionalGeneration": "dots3", @@ -147,7 +148,9 @@ "HYV4ForCausalLM": "hy_v4", "IQuestCoderForCausalLM": "llama", "Inkling2ForCausalLM": "inkling2", + "Inkling2LoopForCausalLM": "inkling2", "Inkling2ForConditionalGeneration": "inkling2", + "Inkling2LoopForConditionalGeneration": "inkling2", "InternLM2ForCausalLM": "internlm", "InternLM3ForCausalLM": "internlm", "JAISLMHeadModel": "jais", @@ -283,6 +286,7 @@ "Qwen3NextForCausalLM": "qwen", "Qwen3OmniMoeForConditionalGeneration": "qwen3vl", "PocketTTSModel": "pockettts", + "MoshiModel": "moshi", "KokoroModel": "kokoro", "TinyVocaModel": "tiny_voca", "Zonos3Model": "zonos3", @@ -388,6 +392,7 @@ "HunYuanVLForConditionalGeneration": "hunyuan", "Idefics3ForConditionalGeneration": "smolvlm", "Inkling2ForConditionalGeneration": "inkling2", + "Inkling2LoopForConditionalGeneration": "inkling2", "InternVisionModel": "internvl", "JanusForConditionalGeneration": "januspro", "KimiK25ForConditionalGeneration": "kimivl", @@ -428,6 +433,7 @@ "Qwen3ASRForConditionalGeneration": "qwen3vl", "Qwen3OmniMoeForConditionalGeneration": "qwen3vl", "PocketTTSModel": "pockettts", + "MoshiModel": "moshi", "KokoroModel": "kokoro", "TinyVocaModel": "tiny_voca", "SopranoModel": "soprano", diff --git a/conversion/base.py b/conversion/base.py index 7cfbff321e0d..540a66ba5098 100644 --- a/conversion/base.py +++ b/conversion/base.py @@ -2470,6 +2470,9 @@ def get_vocab_base_pre(self, tokenizer) -> str: if chkhsh == "5635e1c8d621dff7b4825f41f2f97b6ceb39bcf2d5c541db28577080d6efd5e5": # ref: https://huggingface.co/thinkingmachines/Inkling-2-Small res = "inkling2" + if chkhsh == "32d85c31273f8019248f2559fed492d929ea28b17e51d81d3bb36fff23ca72b3": + # ref: https://huggingface.co/domyn/Domyn-Edge-Teacher-IF + res = "domyn-edge" if res is None: logger.warning("\n") diff --git a/conversion/domynedge.py b/conversion/domynedge.py new file mode 100644 index 000000000000..df07add83cbf --- /dev/null +++ b/conversion/domynedge.py @@ -0,0 +1,53 @@ +from .base import TextModel, ModelBase +import gguf + + +@ModelBase.register("DomynEdgeForCausalLM") +@ModelBase.example("domyn/Domyn-Edge-Teacher-IF") +class DomynEdgeModel(TextModel): + model_arch = gguf.MODEL_ARCH.DOMYN_EDGE + + def set_gguf_parameters(self): + super().set_gguf_parameters() + hparams = self.hparams + self.gguf_writer.add_vocab_size(hparams["vocab_size"]) + + position_layers = hparams["position_layers"] # list of "rope"/"nope" strings per layer + head_sizes = hparams["head_sizes"] # list of int head dims per layer + + # Per-layer rope/SWA pattern: True="rope", False="nope" + rope_pattern = [v == "rope" for v in position_layers] + self.gguf_writer.add_rope_pattern(rope_pattern) + self.gguf_writer.add_sliding_window_pattern(rope_pattern) # SWA <-> RoPE in domyn-edge + + # window_sizes entries are flash-attn style [left, right] (current token excluded; -1 = full attention), + # while llama.cpp's n_swa counts the current token, hence the +1 (matches HF's sliding_window=1025) + swa_window = hparams.get("sliding_window") + if swa_window is None: + window_sizes = hparams.get("window_sizes") # list of [size, offset] pairs per layer + if window_sizes is None: + raise KeyError("Neither `sliding_window` nor `window_sizes` found among domyn edge hyperparameters") + left = next((ws[0] for v, ws in zip(position_layers, window_sizes) if v == "rope"), None) + swa_window = left + 1 if left is not None and left > 0 else None + if swa_window is None: + raise ValueError("No sliding window size found among domyn edge hyperparameters") + self.gguf_writer.add_sliding_window(swa_window) + + # Head dims differ between full-attention ("nope") and SWA ("rope") layers + full_head_dims = {h for v, h in zip(position_layers, head_sizes) if v == "nope"} + swa_head_dims = {h for v, h in zip(position_layers, head_sizes) if v == "rope"} + + if len(full_head_dims) != 1: + raise ValueError(f"Expected one head dimension for full attention layers, found {len(full_head_dims)}") + full_head_dim = full_head_dims.pop() + + self.gguf_writer.add_key_length(full_head_dim) + self.gguf_writer.add_value_length(full_head_dim) + + if len(swa_head_dims) != 1: + raise ValueError(f"Expected one head dimension for SWA attention layers, found {len(swa_head_dims)}") + swa_head_dim = swa_head_dims.pop() + + self.gguf_writer.add_key_length_swa(swa_head_dim) + self.gguf_writer.add_value_length_swa(swa_head_dim) + self.gguf_writer.add_rope_dimension_count_swa(swa_head_dim) diff --git a/conversion/drama3.py b/conversion/drama3.py index 68bbb556bfd4..9b490900a44d 100644 --- a/conversion/drama3.py +++ b/conversion/drama3.py @@ -42,6 +42,115 @@ def fold_snake(alpha: Tensor) -> tuple[Tensor, Tensor]: return alpha, 1.0 / (alpha + 1e-9) +# codec encoder strides (encoder_rates of the codec config), the quantizer then downsamples 2x2 +_CODEC_ENC_STRIDES = (2, 4, 8, 8) + +# codec encoder transformers, both 1024 wide with 16 heads of 64 +# generic audio layers a.blk.0..3: last encoder block, a.blk.4..11: quantizer pre_module +_N_ENC_TFM_LAYERS = 4 +_N_PRE_TFM_LAYERS = 8 +_CODEC_HEAD_DIM = 64 + + +def _neox_rows(w: Tensor, head_dim: int) -> Tensor: + # checkpoint uses interleaved RoPE, reorder the rows of each head so NEOX RoPE gives the same result + order = torch.cat([torch.arange(0, head_dim, 2), torch.arange(1, head_dim, 2)]) + return w.reshape(-1, head_dim, *w.shape[1:])[:, order].reshape(w.shape) + + +def codec_encoder_tensors(sd: dict[str, Tensor], num_codebooks: int) -> Iterable[tuple[str, Tensor]]: + T = gguf.MODEL_TENSOR + + def get(name: str) -> Tensor: + return sd[name].float() + + def tn(tensor: gguf.MODEL_TENSOR, bid: int | None = None, xid: int | None = None) -> str: + return gguf.TENSOR_NAMES[tensor].format(bid=bid, xid=xid) + + def fmt(tensor: gguf.MODEL_TENSOR, bid: int | None = None, suffix: str = ".weight") -> str: + return tn(tensor, bid) + suffix + + def conv_wb(tensor: gguf.MODEL_TENSOR, prefix: str, bid: int | None = None, xid: int | None = None, stride: int = 1): + # taps-major [K / stride, OC, stride * IC], see conv() in tools/mtmd/models/fish-s2-spkenc.cpp + w = fold_conv(sd, prefix) + n_out, n_in, k = w.shape + w = w.reshape(n_out, n_in, k // stride, stride).permute(2, 0, 3, 1).reshape(k // stride, n_out, stride * n_in) + yield (tn(tensor, bid, xid) + ".weight", w) + yield (tn(tensor, bid, xid) + ".bias", get(prefix + ".conv.bias")) + + def snake_ab(tensor: gguf.MODEL_TENSOR, name: str, bid: int | None = None, xid: int | None = None): + a, b = fold_snake(get(name)) + yield (tn(tensor, bid, xid) + ".alpha", a) + yield (tn(tensor, bid, xid) + ".beta", b) + + def tfm_layers(prefix: str, n_layer: int, offset: int): + for il in range(n_layer): + p = f"{prefix}layers.{il}." + bid = offset + il + wq, wk, wv = get(p + "attention.wqkv.weight").chunk(3, dim=0) + yield (fmt(T.A_ENC_ATTN_Q, bid), _neox_rows(wq, _CODEC_HEAD_DIM)) + yield (fmt(T.A_ENC_ATTN_K, bid), _neox_rows(wk, _CODEC_HEAD_DIM)) + yield (fmt(T.A_ENC_ATTN_V, bid), wv) + yield (fmt(T.A_ENC_OUTPUT, bid), get(p + "attention.wo.weight")) + yield (fmt(T.A_ENC_INPUT_NORM, bid), get(p + "attention_norm.weight")) + yield (fmt(T.A_ENC_ATTN_SCALE, bid), get(p + "attention_layer_scale.gamma")) + yield (fmt(T.A_ENC_OUTPUT_NORM, bid), get(p + "ffn_norm.weight")) + yield (fmt(T.A_ENC_FFN_GATE, bid), get(p + "feed_forward.w1.weight")) + yield (fmt(T.A_ENC_FFN_UP, bid), get(p + "feed_forward.w3.weight")) + yield (fmt(T.A_ENC_FFN_DOWN, bid), get(p + "feed_forward.w2.weight")) + yield (fmt(T.A_ENC_FFN_SCALE_LS, bid), get(p + "ffn_layer_scale.gamma")) + + # encoder: entry conv, 4x (3 residual units, Snake, strided conv), Snake, post conv + e = "encoder.block." + yield from conv_wb(T.A_CODEC_ENC_ENTRY, e + "0") + for bid, stride in enumerate(_CODEC_ENC_STRIDES): + p = f"{e}{bid + 1}.block." + for xid in range(3): + r = f"{p}{xid}.block." + yield from snake_ab(T.A_CODEC_ENC_RES_ACT1, r + "0.alpha", bid, xid) + yield from conv_wb(T.A_CODEC_ENC_RES_CONV1, r + "1", bid, xid) + yield from snake_ab(T.A_CODEC_ENC_RES_ACT2, r + "2.alpha", bid, xid) + yield from conv_wb(T.A_CODEC_ENC_RES_CONV2, r + "3", bid, xid) + yield from snake_ab(T.A_CODEC_ENC_SNAKE, p + "3.alpha", bid) + yield from conv_wb(T.A_CODEC_ENC_CONV, p + "4", bid, stride=stride) + # the last block ends with a windowed transformer + yield from tfm_layers(f"{e}4.block.5.", _N_ENC_TFM_LAYERS, 0) + yield (fmt(T.A_POST_NORM), get(f"{e}4.block.5.norm.weight")) + yield from snake_ab(T.A_CODEC_ENC_POST_SNAKE, e + "5.alpha") + yield from conv_wb(T.A_CODEC_ENC_POST_CONV, e + "6") + + # quantizer: 2x (strided conv + ConvNeXt), windowed transformer, then semantic + residual VQ + q = "quantizer." + for bid in range(2): + p = f"{q}downsample.{bid}." + yield from conv_wb(T.A_CODEC_DOWN_CONV, p + "0", bid, stride=2) + # depthwise: one [C] row per tap + yield (tn(T.A_CODEC_DOWN_DWCONV, bid) + ".weight", fold_conv(sd, p + "1.dwconv").squeeze(1).T.contiguous()) + yield (tn(T.A_CODEC_DOWN_DWCONV, bid) + ".bias", get(p + "1.dwconv.conv.bias")) + for key, tensor in (("norm", T.A_CODEC_DOWN_NORM), ("pwconv1", T.A_CODEC_DOWN_PW1), ("pwconv2", T.A_CODEC_DOWN_PW2)): + yield (tn(tensor, bid) + ".weight", get(f"{p}1.{key}.weight")) + yield (tn(tensor, bid) + ".bias", get(f"{p}1.{key}.bias")) + yield (tn(T.A_CODEC_DOWN_GAMMA, bid), get(p + "1.gamma")) + yield from tfm_layers(q + "pre_module.", _N_PRE_TFM_LAYERS, _N_ENC_TFM_LAYERS) + yield (fmt(T.A_CODEC_PRE_NORM), get(q + "pre_module.norm.weight")) + + # nearest codebook entry by cosine similarity, see VectorQuantize.decode_latents() + def vq(prefix: str) -> tuple[Tensor, Tensor, Tensor]: + w = fold_wn(sd[prefix + ".in_proj.weight_g"], sd[prefix + ".in_proj.weight_v"]) + cb = torch.nn.functional.normalize(get(prefix + ".codebook.weight"), dim=-1) + return w, get(prefix + ".in_proj.bias"), cb + + w, b, cb = vq(q + "semantic_quantizer.quantizers.0") + yield (fmt(T.A_CODEC_VQ_FIRST_IN, suffix=".weight"), w) + yield (fmt(T.A_CODEC_VQ_FIRST_IN, suffix=".bias"), b) + yield (fmt(T.A_CODEC_VQ_FIRST_CB), cb) + n_rest = num_codebooks - 1 + rest = [vq(f"{q}quantizer.quantizers.{i}") for i in range(n_rest)] + yield (fmt(T.A_CODEC_VQ_REST_IN, suffix=".weight"), torch.stack([r[0] for r in rest])) + yield (fmt(T.A_CODEC_VQ_REST_IN, suffix=".bias"), torch.stack([r[1] for r in rest])) + yield (fmt(T.A_CODEC_VQ_REST_CB), torch.stack([r[2] for r in rest])) + + @ModelBase.register("FishOmniModel") @ModelBase.example("fishaudio/drama-3") class Drama3TextModel(Qwen3_5MoeTextModel): @@ -59,7 +168,7 @@ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Ca @ModelBase.example("fishaudio/drama-3") class Drama3MmprojModel(MmprojModel): has_vision_encoder = False - has_audio_encoder = False + has_audio_encoder = True # codec encoder, for voice cloning gen_projector_type = gguf.VisionProjectorType.DRAMA3_GEN _LAYER_MAP = { @@ -103,6 +212,16 @@ def set_gguf_parameters(self): self.gguf_writer.add_gen_audio_head_count_kv(cfg["n_local_heads"]) self.gguf_writer.add_gen_audio_attention_layernorm_eps(cfg["norm_eps"]) # other tower and codec hparams are hardcoded in tools/mtmd + # codec encoder: raw 44.1 kHz waveform -> backbone input rows, other hparams are hardcoded in tools/mtmd + self.gguf_writer.add_clip_has_audio_encoder(True) + self.gguf_writer.add_clip_audio_projector_type(gguf.VisionProjectorType.FISH_S2_SPKENC) + self.gguf_writer.add_audio_projection_dim(self.n_embd_text) + self.gguf_writer.add_audio_num_mel_bins(1) + self.gguf_writer.add_audio_block_count(_N_ENC_TFM_LAYERS + _N_PRE_TFM_LAYERS) + self.gguf_writer.add_audio_embedding_length(1024) + self.gguf_writer.add_audio_feed_forward_length(3072) + self.gguf_writer.add_audio_head_count(1024 // _CODEC_HEAD_DIM) + self.gguf_writer.add_audio_attention_layernorm_eps(1e-5) @classmethod def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: @@ -112,6 +231,12 @@ def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Ca return None def tensor_force_quant(self, name, new_name, bid, n_dims): + # the VQ picks the nearest codebook entry, small errors in the encoder change the codes + if new_name.startswith("a.codec."): + return gguf.GGMLQuantizationType.F32 + # codec transformers: F16 gives codes closer to the reference than BF16 + if new_name.startswith("a.blk.") and n_dims == 2: + return gguf.GGMLQuantizationType.F16 # conv1d/conv1d_dw kernels must be F16, ggml_conv_1d(_dw) has no BF16 path if new_name.endswith(".weight") and ( new_name in ("a.gen.wav.dac.entry.weight", "a.gen.wav.dac.post_conv.weight") @@ -130,7 +255,7 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter T = gguf.MODEL_TENSOR cfg = self.hparams - if name.startswith("a.gen.wav."): + if name.startswith("a."): yield (name, data_torch) return @@ -177,7 +302,7 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter raise ValueError(f"unexpected tensor {name}") def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]: - # only the DAC decoder, the encoder is for voice cloning (not supported yet) + # Fish DAC decoder, then the shared codec encoder for voice cloning sd = load_codec(self.dir_model) T = gguf.MODEL_TENSOR @@ -262,3 +387,5 @@ def neox_rows(w: Tensor) -> Tensor: yield (self.format_tensor_name(T.A_GEN_WAV_DAC_POST_SNAKE, suffix=".beta"), b) yield (self.format_tensor_name(T.A_GEN_WAV_DAC_POST_CONV, suffix=".weight"), conv(d + "6")) yield (self.format_tensor_name(T.A_GEN_WAV_DAC_POST_CONV, suffix=".bias"), get(d + "6.conv.bias")) + + yield from codec_encoder_tensors(sd, self.hparams["num_codebooks"]) diff --git a/conversion/fish_s2.py b/conversion/fish_s2.py index 4c5aeff13200..563b52b126af 100644 --- a/conversion/fish_s2.py +++ b/conversion/fish_s2.py @@ -3,13 +3,11 @@ from pathlib import Path from typing import Any, Callable, Iterable, TYPE_CHECKING -import torch - if TYPE_CHECKING: from torch import Tensor from .base import ModelBase, gguf -from .drama3 import Drama3MmprojModel, fold_conv, fold_snake, fold_wn, load_codec +from .drama3 import Drama3MmprojModel, _neox_rows from .qwen import Qwen3Model # Fish Audio S2 Pro (dual-AR) @@ -19,15 +17,6 @@ # residual codebook size of codec.pth, the fast AR head is cut to it _N_RESIDUAL_CODES = 1024 -# codec encoder strides (encoder_rates of the codec config), the quantizer then downsamples 2x2 -_CODEC_ENC_STRIDES = (2, 4, 8, 8) - -# codec encoder transformers, both 1024 wide with 16 heads of 64 -# generic audio layers a.blk.0..3: last encoder block, a.blk.4..11: quantizer pre_module -_N_ENC_TFM_LAYERS = 4 -_N_PRE_TFM_LAYERS = 8 -_CODEC_HEAD_DIM = 64 - def _load_hparams(dir_model: Path) -> dict[str, Any]: hparams = ModelBase.load_hparams(dir_model, is_mistral_format=False) @@ -48,12 +37,6 @@ def _load_hparams(dir_model: Path) -> dict[str, Any]: return hparams -def _neox_rows(w: Tensor, head_dim: int) -> Tensor: - # checkpoint uses interleaved RoPE, reorder the rows of each head so NEOX RoPE gives the same result - order = torch.cat([torch.arange(0, head_dim, 2), torch.arange(1, head_dim, 2)]) - return w.reshape(-1, head_dim, *w.shape[1:])[:, order].reshape(w.shape) - - @ModelBase.register("fish_qwen3_omni") @ModelBase.example("fishaudio/s2-pro") class FishS2TextModel(Qwen3Model): @@ -88,7 +71,6 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter @ModelBase.register("fish_qwen3_omni") @ModelBase.example("fishaudio/s2-pro") class FishS2MmprojModel(Drama3MmprojModel): - has_audio_encoder = True # codec encoder, for voice cloning gen_projector_type = gguf.VisionProjectorType.FISH_S2_GEN _FAST_AR_MAP = { @@ -109,28 +91,6 @@ def get_audio_config(self) -> dict[str, Any] | None: cfg["num_hidden_layers"] = cfg["n_layer"] return cfg - def set_gguf_parameters(self): - super().set_gguf_parameters() - # codec encoder: raw 44.1 kHz waveform -> backbone input rows, other hparams are hardcoded in tools/mtmd - self.gguf_writer.add_clip_has_audio_encoder(True) - self.gguf_writer.add_clip_audio_projector_type(gguf.VisionProjectorType.FISH_S2_SPKENC) - self.gguf_writer.add_audio_projection_dim(self.n_embd_text) - self.gguf_writer.add_audio_num_mel_bins(1) - self.gguf_writer.add_audio_block_count(_N_ENC_TFM_LAYERS + _N_PRE_TFM_LAYERS) - self.gguf_writer.add_audio_embedding_length(1024) - self.gguf_writer.add_audio_feed_forward_length(3072) - self.gguf_writer.add_audio_head_count(1024 // _CODEC_HEAD_DIM) - self.gguf_writer.add_audio_attention_layernorm_eps(1e-5) - - def tensor_force_quant(self, name, new_name, bid, n_dims): - # the VQ picks the nearest codebook entry, small errors in the encoder change the codes - if new_name.startswith("a.codec."): - return gguf.GGMLQuantizationType.F32 - # codec transformers: F16 gives codes closer to the reference than BF16 - if new_name.startswith("a.blk.") and n_dims == 2: - return gguf.GGMLQuantizationType.F16 - return super().tensor_force_quant(name, new_name, bid, n_dims) - @classmethod def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None: name = item[0] @@ -182,95 +142,3 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_V, bid), v) return yield (self.format_tensor_name(self._FAST_AR_MAP[key], bid), data_torch) - - def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]: - yield from super().generate_extra_tensors() - - sd = load_codec(self.dir_model) - T = gguf.MODEL_TENSOR - - def get(name: str) -> Tensor: - return sd[name].float() - - def tn(tensor: gguf.MODEL_TENSOR, bid: int | None = None, xid: int | None = None) -> str: - return gguf.TENSOR_NAMES[tensor].format(bid=bid, xid=xid) - - def conv_wb(tensor: gguf.MODEL_TENSOR, prefix: str, bid: int | None = None, xid: int | None = None, stride: int = 1): - # taps-major [K / stride, OC, stride * IC], see conv() in tools/mtmd/models/fish-s2-spkenc.cpp - w = fold_conv(sd, prefix) - n_out, n_in, k = w.shape - w = w.reshape(n_out, n_in, k // stride, stride).permute(2, 0, 3, 1).reshape(k // stride, n_out, stride * n_in) - yield (tn(tensor, bid, xid) + ".weight", w) - yield (tn(tensor, bid, xid) + ".bias", get(prefix + ".conv.bias")) - - def snake_ab(tensor: gguf.MODEL_TENSOR, name: str, bid: int | None = None, xid: int | None = None): - a, b = fold_snake(get(name)) - yield (tn(tensor, bid, xid) + ".alpha", a) - yield (tn(tensor, bid, xid) + ".beta", b) - - def tfm_layers(prefix: str, n_layer: int, offset: int): - for il in range(n_layer): - p = f"{prefix}layers.{il}." - bid = offset + il - wq, wk, wv = get(p + "attention.wqkv.weight").chunk(3, dim=0) - yield (self.format_tensor_name(T.A_ENC_ATTN_Q, bid), _neox_rows(wq, _CODEC_HEAD_DIM)) - yield (self.format_tensor_name(T.A_ENC_ATTN_K, bid), _neox_rows(wk, _CODEC_HEAD_DIM)) - yield (self.format_tensor_name(T.A_ENC_ATTN_V, bid), wv) - yield (self.format_tensor_name(T.A_ENC_OUTPUT, bid), get(p + "attention.wo.weight")) - yield (self.format_tensor_name(T.A_ENC_INPUT_NORM, bid), get(p + "attention_norm.weight")) - yield (self.format_tensor_name(T.A_ENC_ATTN_SCALE, bid), get(p + "attention_layer_scale.gamma")) - yield (self.format_tensor_name(T.A_ENC_OUTPUT_NORM, bid), get(p + "ffn_norm.weight")) - yield (self.format_tensor_name(T.A_ENC_FFN_GATE, bid), get(p + "feed_forward.w1.weight")) - yield (self.format_tensor_name(T.A_ENC_FFN_UP, bid), get(p + "feed_forward.w3.weight")) - yield (self.format_tensor_name(T.A_ENC_FFN_DOWN, bid), get(p + "feed_forward.w2.weight")) - yield (self.format_tensor_name(T.A_ENC_FFN_SCALE_LS, bid), get(p + "ffn_layer_scale.gamma")) - - # encoder: entry conv, 4x (3 residual units, Snake, strided conv), Snake, post conv - e = "encoder.block." - yield from conv_wb(T.A_CODEC_ENC_ENTRY, e + "0") - for bid, stride in enumerate(_CODEC_ENC_STRIDES): - p = f"{e}{bid + 1}.block." - for xid in range(3): - r = f"{p}{xid}.block." - yield from snake_ab(T.A_CODEC_ENC_RES_ACT1, r + "0.alpha", bid, xid) - yield from conv_wb(T.A_CODEC_ENC_RES_CONV1, r + "1", bid, xid) - yield from snake_ab(T.A_CODEC_ENC_RES_ACT2, r + "2.alpha", bid, xid) - yield from conv_wb(T.A_CODEC_ENC_RES_CONV2, r + "3", bid, xid) - yield from snake_ab(T.A_CODEC_ENC_SNAKE, p + "3.alpha", bid) - yield from conv_wb(T.A_CODEC_ENC_CONV, p + "4", bid, stride=stride) - # the last block ends with a windowed transformer - yield from tfm_layers(f"{e}4.block.5.", _N_ENC_TFM_LAYERS, 0) - yield (self.format_tensor_name(T.A_POST_NORM), get(f"{e}4.block.5.norm.weight")) - yield from snake_ab(T.A_CODEC_ENC_POST_SNAKE, e + "5.alpha") - yield from conv_wb(T.A_CODEC_ENC_POST_CONV, e + "6") - - # quantizer: 2x (strided conv + ConvNeXt), windowed transformer, then semantic + residual VQ - q = "quantizer." - for bid in range(2): - p = f"{q}downsample.{bid}." - yield from conv_wb(T.A_CODEC_DOWN_CONV, p + "0", bid, stride=2) - # depthwise: one [C] row per tap - yield (tn(T.A_CODEC_DOWN_DWCONV, bid) + ".weight", fold_conv(sd, p + "1.dwconv").squeeze(1).T.contiguous()) - yield (tn(T.A_CODEC_DOWN_DWCONV, bid) + ".bias", get(p + "1.dwconv.conv.bias")) - for key, tensor in (("norm", T.A_CODEC_DOWN_NORM), ("pwconv1", T.A_CODEC_DOWN_PW1), ("pwconv2", T.A_CODEC_DOWN_PW2)): - yield (tn(tensor, bid) + ".weight", get(f"{p}1.{key}.weight")) - yield (tn(tensor, bid) + ".bias", get(f"{p}1.{key}.bias")) - yield (tn(T.A_CODEC_DOWN_GAMMA, bid), get(p + "1.gamma")) - yield from tfm_layers(q + "pre_module.", _N_PRE_TFM_LAYERS, _N_ENC_TFM_LAYERS) - yield (self.format_tensor_name(T.A_CODEC_PRE_NORM), get(q + "pre_module.norm.weight")) - - # nearest codebook entry by cosine similarity, see VectorQuantize.decode_latents() - def vq(prefix: str) -> tuple[Tensor, Tensor, Tensor]: - w = fold_wn(sd[prefix + ".in_proj.weight_g"], sd[prefix + ".in_proj.weight_v"]) - cb = torch.nn.functional.normalize(get(prefix + ".codebook.weight"), dim=-1) - return w, get(prefix + ".in_proj.bias"), cb - - w, b, cb = vq(q + "semantic_quantizer.quantizers.0") - yield (self.format_tensor_name(T.A_CODEC_VQ_FIRST_IN, suffix=".weight"), w) - yield (self.format_tensor_name(T.A_CODEC_VQ_FIRST_IN, suffix=".bias"), b) - yield (self.format_tensor_name(T.A_CODEC_VQ_FIRST_CB), cb) - n_rest = self.hparams["num_codebooks"] - 1 - rest = [vq(f"{q}quantizer.quantizers.{i}") for i in range(n_rest)] - yield (self.format_tensor_name(T.A_CODEC_VQ_REST_IN, suffix=".weight"), torch.stack([r[0] for r in rest])) - yield (self.format_tensor_name(T.A_CODEC_VQ_REST_IN, suffix=".bias"), torch.stack([r[1] for r in rest])) - yield (self.format_tensor_name(T.A_CODEC_VQ_REST_CB), torch.stack([r[2] for r in rest])) diff --git a/conversion/inkling2.py b/conversion/inkling2.py index a8e8b892ed72..63e73a6d527f 100644 --- a/conversion/inkling2.py +++ b/conversion/inkling2.py @@ -69,7 +69,7 @@ def _is_inkling2(dir_model: Path) -> bool: if not (dir_model / "config.json").is_file(): return False with open(dir_model / "config.json", encoding="utf-8") as f: - return json.load(f).get("model_type") in ("inkling2", "inkling2_text") + return json.load(f).get("model_type") in ("inkling2", "inkling2_text", "inkling2_loop", "inkling2_loop_text") @ModelBase.register_hparams_loader(_is_inkling2) @@ -274,7 +274,62 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter yield from super().modify_tensors(data_torch, name, bid) -@ModelBase.register("Inkling2ForConditionalGeneration") +@ModelBase.register("Inkling2LoopForConditionalGeneration", "Inkling2LoopForCausalLM") +class Inkling2LoopModel(Inkling2Model): + model_arch = gguf.MODEL_ARCH.INKLING2_LOOP + + # raw checkpoint and transformers names of the cross-pass message queries + _query_kinds = { + "model.middle_cycle_cross_pass_queries": "q", + "model.middle_cycle_cross_pass_kv_queries": "kv", + "model.cross_pass_messages.queries": "q", + "model.cross_pass_messages.kv_queries": "kv", + } + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._queries: dict[str, Tensor] = {} + self.loop = self.hparams["loop_config"] + if set(self.loop) != {"core_start", "core_end", "num_passes", "gate_rank", "is_varloop"}: + raise ValueError(f"Inkling2Loop: unsupported loop_config keys {sorted(self.loop)}") + start, end, block = self.loop["core_start"], self.loop["core_end"], self.hparams["n_layers_per_attn_res_block"] + # a fixed loop needs at least 2 passes, a variable loop at least 1 + min_passes = 1 if self.loop["is_varloop"] else 2 + if not 0 < start < end <= self.block_count or start % block or end % block or self.loop["num_passes"] < min_passes or self.loop["gate_rank"] < 1: + raise ValueError(f"Inkling2Loop: invalid loop_config {self.loop}") + + def set_gguf_parameters(self): + super().set_gguf_parameters() + self.gguf_writer.add_loop_start(self.loop["core_start"]) + self.gguf_writer.add_loop_end(self.loop["core_end"]) + self.gguf_writer.add_loop_count(self.loop["num_passes"]) + self.gguf_writer.add_loop_gate_rank(self.loop["gate_rank"]) + self.gguf_writer.add_loop_varying(self.loop["is_varloop"]) + + def tensor_force_quant(self, name: str, new_name: str, bid: int | None, n_dims: int) -> gguf.GGMLQuantizationType | bool: + # the reference does not quantize the loop tensors + if new_name.endswith(("loop_msg_query.weight", "_ctrl_down.weight", "_ctrl_gain.weight", "_ctrl_forget.weight")): + return gguf.GGMLQuantizationType.F32 + return super().tensor_force_quant(name, new_name, bid, n_dims) + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + if name not in self._query_kinds: + yield from super().modify_tensors(data_torch, name, bid) + return + self._queries[self._query_kinds[name]] = data_torch + if len(self._queries) < 2: + return + q, kv = self._queries["q"], self._queries["kv"] + start = self.loop["core_start"] + if q.shape[0] != 2 * (self.loop["core_end"] - start) or kv.shape != q.shape: + raise ValueError(f"Inkling2Loop: cross-pass queries {tuple(q.shape)} and {tuple(kv.shape)} do not match the loop core") + # core layer start + i mixes its q, k, v and mlp messages with these four queries + for i in range(q.shape[0] // 2): + query = torch.stack([q[2 * i], kv[2 * i], kv[2 * i + 1], q[2 * i + 1]]) + yield self.format_tensor_name(gguf.MODEL_TENSOR.LOOP_MSG_QUERY, start + i, ".weight"), query + + +@ModelBase.register("Inkling2ForConditionalGeneration", "Inkling2LoopForConditionalGeneration") class Inkling2VisionModel(MmprojModel): def get_vision_config(self): config = self.global_config.get("vision_config") diff --git a/conversion/moshi.py b/conversion/moshi.py new file mode 100644 index 000000000000..028319385a1c --- /dev/null +++ b/conversion/moshi.py @@ -0,0 +1,378 @@ +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Callable, Iterable, TYPE_CHECKING + +import torch + +if TYPE_CHECKING: + from torch import Tensor + +from .base import ModelBase, MmprojModel, SentencePieceTokenTypes, TextModel, gguf, logger +from .pockettts import mimi_seanet_tensors, mimi_tfm_tensors + +# Moshi family (Kyutai): a backbone over parallel streams (text + generated audio codes + input audio codes), +# one position per 80 ms frame. Only Hibiki (simultaneous speech translation) is supported for now. +# The checkpoint is not in the HF layout: a moshi-style config.json and two safetensors (LM + mimi). +# +# pipeline stage mapping: +# transformer + text_emb/text_linear --> normal libllama text model (arch moshi) +# mimi encoder + RVQ + emb[dep_q:] --> mtmd audio stream (projector moshi), rows of the input audio +# depformer + emb[:dep_q] --> MTMD_GEN_PROCESS_TYPE_GEN_CODE, codes of a frame + their backbone embedding +# RVQ decode + mimi decoder --> MTMD_GEN_PROCESS_TYPE_GEN_WAV +# +# Tricks: +# - the initial text token (text_card) is appended to the vocab as <|text_start|>, the head has no logit for it; +# it only opens the stream, the embeddings of the initial codes of the generated audio are folded into it +# - the condition of Hibiki ("very_good" description, added to every row) is folded into the text embeddings, +# every row has exactly one text embedding +# - Hibiki ignores an early EOS: the reference gives it the embedding of PAD, done here too +# - low-rank depformer embeddings are folded into full tables + +_MIMI_PREFIX = "mimi." +_COND_VALUE = "very_good" + + +def _read_config(dir_model: Path) -> dict[str, Any] | None: + path = dir_model / "config.json" + if not path.is_file(): + return None + with open(path, "r", encoding="utf-8") as f: + config = json.load(f) + return config if isinstance(config, dict) and "moshi_name" in config else None + + +def _tensor_shape(path: Path, name: str) -> tuple[int, ...]: + with gguf.utility.SafetensorsLocal(path) as part: + return tuple(part[name].shape) + + +@ModelBase.register_hparams_loader(lambda dir_model: _read_config(dir_model) is not None) +def _load_hparams(dir_model: Path) -> dict[str, Any]: + config = _read_config(dir_model) + assert config is not None + model_type = config.get("model_type", "moshi") + if model_type != "hibiki": + raise NotImplementedError(f"moshi checkpoint of type {model_type!r} is not supported yet") + logger.info(f"gguf: detected a moshi checkpoint ({model_type})") + + # mtmd has the layout of Hibiki: the acoustic codes lag by 2 frames, the depformer has no positional embedding, + # its steps past the last weight set reuse it, and the initial code is the extra entry after the mimi codebook + n_q = config["dep_q"] + schedule = config.get("depformer_weights_per_step_schedule") or list(range(n_q)) + # text, then the generated and the input codes + if config["delays"] != [0] + ([0] + [2] * (n_q - 1)) * 2: + raise NotImplementedError(f"unsupported delays {config['delays']}") + if schedule != [min(i, max(schedule)) for i in range(n_q)] or config.get("depformer_pos_emb", "none") != "none": + raise NotImplementedError("unsupported depformer layout") + if config["card"] != 2048 or config["n_q"] != 2 * n_q: + raise NotImplementedError("unsupported audio codebooks") + + lm_path = dir_model / config["moshi_name"] + # the gating hidden size is derived from dim_feedforward, read it back from the tensors + n_ff = _tensor_shape(lm_path, "transformer.layers.0.gating.linear_out.weight")[1] + n_ff_dep = _tensor_shape(lm_path, "depformer.layers.0.gating.0.linear_out.weight")[1] + return { + "architectures": ["MoshiModel"], + "model_type": "moshi", + "moshi_config": config, + "num_hidden_layers": config["num_layers"], + "hidden_size": config["dim"], + "intermediate_size": n_ff, + "num_attention_heads": config["num_heads"], + "num_key_value_heads": config["num_heads"], + "max_position_embeddings": config["context"], + "sliding_window": config["context"], + "rope_theta": config["max_period"], + "rms_norm_eps": 1e-8, # rms_norm_f32 + "vocab_size": config["text_card"] + 1, + "audio_config": { + # mimi encoder transformer, constant across the family + "num_hidden_layers": 8, + "hidden_size": 512, + "intermediate_size": 2048, + "num_attention_heads": 8, + }, + "depformer_config": { + "num_hidden_layers": config["depformer_num_layers"], + "hidden_size": config["depformer_dim"], + "intermediate_size": n_ff_dep, + "num_attention_heads": config["depformer_num_heads"], + }, + } + + +# the LM and mimi weights are in two files named by the config, mimi tensors get the "mimi." prefix +def _moshi_config(model: ModelBase) -> dict[str, Any]: + config = model.hparams.get("moshi_config") + if config is None and isinstance(model, MmprojModel): + config = model.global_config["moshi_config"] # the mmproj moves the hparams aside + assert config is not None + return config + + +def _index_moshi_tensors(model: ModelBase) -> dict[str, Callable[[], Tensor]]: + config = _moshi_config(model) + tensors = model.index_local_tensors(Path(config["moshi_name"]).stem) + for name, gen in model.index_local_tensors(Path(config["mimi_name"]).stem).items(): + tensors[_MIMI_PREFIX + name] = gen + return tensors + + +def _low_rank_embd(model: ModelBase, prefix: str) -> Tensor: + embd = model.model_tensors[prefix + ".weight"]().float() + proj = model.model_tensors.get(prefix + ".low_rank.weight") + return embd @ proj().float().T if proj is not None else embd + + +def _condition(model: ModelBase, value: str) -> Tensor: + # LUT conditioner: output_proj(embed[index of value]) + lut = _moshi_config(model)["conditioners"]["description"]["lut"] + prefix = "condition_provider.conditioners.description." + embed = model.model_tensors[prefix + "embed.weight"]().float() + proj = model.model_tensors[prefix + "output_proj.weight"]().float() + return embed[lut["possible_values"].index(value)] @ proj.T + + +@ModelBase.register("MoshiModel") +@ModelBase.example("kyutai/hibiki-1b-pytorch-bf16", "kyutai/hibiki-2b-pytorch-bf16") +class MoshiModel(TextModel): + model_arch = gguf.MODEL_ARCH.MOSHI + + def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]: + assert remote_hf_model_id is None + return _index_moshi_tensors(self) + + def set_vocab(self): + from sentencepiece import SentencePieceProcessor + + config = _moshi_config(self) + sp = SentencePieceProcessor() + sp.LoadFromFile(str(self.dir_model / config["tokenizer_name"])) + assert sp.vocab_size() == config["text_card"] + + tokens: list[bytes] = [] + scores: list[float] = [] + toktypes: list[int] = [] + for i in range(sp.vocab_size()): + toktype = SentencePieceTokenTypes.NORMAL + if sp.IsControl(i) or sp.IsUnknown(i): + # (0) is the end-of-padding marker of the text stream, it has no text + toktype = SentencePieceTokenTypes.CONTROL + elif sp.IsUnused(i): + toktype = SentencePieceTokenTypes.UNUSED + elif sp.IsByte(i): + toktype = SentencePieceTokenTypes.BYTE + tokens.append(sp.IdToPiece(i).encode("utf-8")) + scores.append(sp.GetScore(i)) + toktypes.append(toktype) + + # the initial token of the text stream + tokens.append(b"<|text_start|>") + scores.append(-1000.0) + toktypes.append(SentencePieceTokenTypes.CONTROL) + + self.gguf_writer.add_tokenizer_model("llama") + self.gguf_writer.add_tokenizer_pre("default") + self.gguf_writer.add_token_list(tokens) + self.gguf_writer.add_token_scores(scores) + self.gguf_writer.add_token_types(toktypes) + self.gguf_writer.add_unk_token_id(sp.unk_id()) + self.gguf_writer.add_bos_token_id(sp.bos_id()) + self.gguf_writer.add_eos_token_id(sp.eos_id()) + self.gguf_writer.add_pad_token_id(sp.pad_id()) + self.gguf_writer.add_add_bos_token(False) + self.gguf_writer.add_add_eos_token(False) + + def set_gguf_parameters(self): + super().set_gguf_parameters() + self.gguf_writer.add_sliding_window(self.hparams["sliding_window"]) + + # sampling of the text tokens, the audio codes are sampled by mtmd + gen = _moshi_config(self).get("lm_gen_config", {}) + self.gguf_writer.add_sampling_temp(gen.get("temp_text", 0.7)) + self.gguf_writer.add_sampling_top_k(gen.get("top_k_text", 25)) + self.gguf_writer.add_sampling_top_p(1.0) + self.gguf_writer.add_sampling_min_p(0.0) + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + T = gguf.MODEL_TENSOR + + if name == "text_emb.weight": + config = _moshi_config(self) + embd = data_torch.float().clone() + embd[2] = embd[3] # EOS -> PAD, see get_moshi() of the reference + embd += _condition(self, _COND_VALUE) + assert embd.shape[0] == config["text_card"] + 1 + # <|text_start|> only opens the stream, with the initial codes of the generated audio + for k in range(config["dep_q"]): + embd[-1] += self.model_tensors[f"emb.{k}.weight"]()[config["card"]].float() + yield (self.format_tensor_name(T.TOKEN_EMBD), embd) + return + if name == "text_linear.weight": + yield (self.format_tensor_name(T.OUTPUT), data_torch) + return + if name == "out_norm.alpha": + yield (self.format_tensor_name(T.OUTPUT_NORM), data_torch.reshape(-1)) + return + + if not name.startswith("transformer.layers."): + return # mimi, depformer and the audio embeddings go to the mmproj + assert bid is not None + key = name.split(f"layers.{bid}.", 1)[1] + + if key == "self_attn.in_proj_weight": + q, k, v = data_torch.chunk(3, dim=0) + yield (self.format_tensor_name(T.ATTN_Q, bid), q) + yield (self.format_tensor_name(T.ATTN_K, bid), k) + yield (self.format_tensor_name(T.ATTN_V, bid), v) + elif key == "self_attn.out_proj.weight": + yield (self.format_tensor_name(T.ATTN_OUT, bid), data_torch) + elif key == "norm1.alpha": + yield (self.format_tensor_name(T.ATTN_NORM, bid), data_torch.reshape(-1)) + elif key == "norm2.alpha": + yield (self.format_tensor_name(T.FFN_NORM, bid), data_torch.reshape(-1)) + elif key == "gating.linear_in.weight": + # silu(first half) * second half + gate, up = data_torch.chunk(2, dim=0) + yield (self.format_tensor_name(T.FFN_GATE, bid), gate) + yield (self.format_tensor_name(T.FFN_UP, bid), up) + elif key == "gating.linear_out.weight": + yield (self.format_tensor_name(T.FFN_DOWN, bid), data_torch) + else: + raise ValueError(f"unexpected tensor {name}") + + +@ModelBase.register("MoshiModel") +@ModelBase.example("kyutai/hibiki-1b-pytorch-bf16", "kyutai/hibiki-2b-pytorch-bf16") +class MoshiMmprojModel(MmprojModel): + has_audio_encoder = True + has_vision_encoder = False + + def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]: + assert remote_hf_model_id is None + return _index_moshi_tensors(self) + + def _n_codebooks(self) -> int: + return _moshi_config(self)["dep_q"] + + def set_gguf_parameters(self): + self.gguf_writer.add_file_type(self.ftype) + assert self.hparams_audio is not None + dep = self.global_config["depformer_config"] + + # input audio: mimi encoder + RVQ + embeddings of the input codes + self.gguf_writer.add_clip_has_audio_encoder(True) + self.gguf_writer.add_clip_audio_projector_type(gguf.VisionProjectorType.MOSHI) + self.gguf_writer.add_audio_projection_dim(self.n_embd_text) + self.gguf_writer.add_audio_block_count(self.hparams_audio["num_hidden_layers"]) + self.gguf_writer.add_audio_embedding_length(self.hparams_audio["hidden_size"]) + self.gguf_writer.add_audio_feed_forward_length(self.hparams_audio["intermediate_size"]) + self.gguf_writer.add_audio_head_count(self.hparams_audio["num_attention_heads"]) + self.gguf_writer.add_audio_attention_layernorm_eps(1e-5) + # mimi convolves the waveform directly, it is passed around as a 1-row "mel" + self.gguf_writer.add_audio_num_mel_bins(1) + + # generation: depformer + mimi decoder, the mimi hparams are constant and held by mtmd + self.gguf_writer.add_clip_has_gen_audio_encoder(True) + self.gguf_writer.add_clip_gen_audio_projector_type(gguf.VisionProjectorType.MOSHI_GEN) + self.gguf_writer.add_gen_audio_projection_dim(self.n_embd_text) + self.gguf_writer.add_gen_audio_embedding_length(dep["hidden_size"]) + self.gguf_writer.add_gen_audio_feed_forward_length(dep["intermediate_size"]) + self.gguf_writer.add_gen_audio_block_count(dep["num_hidden_layers"]) + self.gguf_writer.add_gen_audio_head_count(dep["num_attention_heads"]) + self.gguf_writer.add_gen_audio_attention_layernorm_eps(1e-8) + self.gguf_writer.add_gen_audio_model_variant(_moshi_config(self)["model_type"]) + + def tensor_force_quant(self, name, new_name, bid, n_dims): + del name, bid, n_dims + # conv1d/conv1d_dw kernels must be F16, ggml_conv_1d(_dw) has no BF16 path + if ".seanet." in new_name or new_name in ("a.downsample.conv.weight", "a.gen.wav.upsample.weight"): + return gguf.GGMLQuantizationType.F16 + # nearest-code search and RVQ decode stay exact + if ".codebook" in new_name or new_name.startswith("a.codec.vq."): + return gguf.GGMLQuantizationType.F32 + return False + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + del bid + T = gguf.MODEL_TENSOR + if name.startswith(("a.", "mm.a.")): + yield (name, data_torch) # already named by generate_extra_tensors() + return + if not name.startswith(_MIMI_PREFIX): + return # the LM tensors are stacked in generate_extra_tensors() + if name == "mimi.downsample.conv.conv.conv.weight": + yield (self.format_tensor_name(T.A_ENC_DOWNSAMPLE_CONV), data_torch) + elif name == "mimi.upsample.convtr.convtr.convtr.weight": + yield (self.format_tensor_name(T.A_GEN_WAV_UPSAMPLE), data_torch) + elif "_transformer.transformer.layers." in name: + # pocket-tts names it in_proj.weight + yield from mimi_tfm_tensors(self, name.replace(".in_proj_weight", ".in_proj.weight"), data_torch) + elif name.startswith(("mimi.encoder.model.", "mimi.decoder.model.")): + yield from mimi_seanet_tensors(self, name, data_torch, 4) + + def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]: + T = gguf.MODEL_TENSOR + config = _moshi_config(self) + n_q = self._n_codebooks() + + def get(name: str) -> Tensor: + return self.model_tensors[name]() + + def stack(names: Iterable[str]) -> Tensor: + return torch.stack([get(n) for n in names], dim=0) + + # mimi RVQ: one semantic codebook, then n_q - 1 acoustic ones + def codebooks(prefix: str, n: int) -> Tensor: + books = [] + for i in range(n): + embedding_sum = get(f"{prefix}.vq.layers.{i}._codebook.embedding_sum").float() + cluster_usage = get(f"{prefix}.vq.layers.{i}._codebook.cluster_usage").float() + books.append(embedding_sum / cluster_usage.clamp_min(1e-5).unsqueeze(-1)) + return torch.stack(books, dim=0) if n > 1 else books[0] + + q = "mimi.quantizer." + cb_first = codebooks(q + "rvq_first", 1) + cb_rest = codebooks(q + "rvq_rest", n_q - 1) + yield (self.format_tensor_name(T.A_CODEC_VQ_FIRST_IN), get(q + "rvq_first.input_proj.weight").squeeze(-1)) + yield (self.format_tensor_name(T.A_CODEC_VQ_FIRST_CB), cb_first) + yield (self.format_tensor_name(T.A_CODEC_VQ_REST_IN), get(q + "rvq_rest.input_proj.weight").squeeze(-1)) + yield (self.format_tensor_name(T.A_CODEC_VQ_REST_CB), cb_rest) + yield (self.format_tensor_name(T.A_GEN_WAV_QUANT_FIRST_OUT), get(q + "rvq_first.output_proj.weight").squeeze(-1)) + yield (self.format_tensor_name(T.A_GEN_WAV_QUANT_FIRST_CB), cb_first) + yield (self.format_tensor_name(T.A_GEN_WAV_QUANT_REST_OUT), get(q + "rvq_rest.output_proj.weight").squeeze(-1)) + yield (self.format_tensor_name(T.A_GEN_WAV_QUANT_REST_CB), cb_rest) + + # backbone embeddings of the audio codes: the generated stream first, then the input stream + assert config["n_q"] == 2 * n_q + yield (self.format_tensor_name(T.A_GEN_CODE_OUT_EMBD), stack(f"emb.{k}.weight" for k in range(n_q))) + yield (self.format_tensor_name(T.A_MM_CODE_EMBD), stack(f"emb.{k}.weight" for k in range(n_q, 2 * n_q))) + + # depformer: per-step weights are stacked on the last ggml dim, steps past the last weight set reuse it + dep = self.global_config["depformer_config"] + n_dim = dep["hidden_size"] + n_in = sum(1 for name in self.model_tensors if name.startswith("depformer_in.")) + yield (self.format_tensor_name(T.A_GEN_CODE_PROJ_IN), stack(f"depformer_in.{i}.weight" for i in range(n_in))) + yield (self.format_tensor_name(T.A_GEN_CODE_TOK_EMBD), _low_rank_embd(self, "depformer_text_emb")) + yield (self.format_tensor_name(T.A_GEN_CODE_EMBD), + torch.stack([_low_rank_embd(self, f"depformer_emb.{i}") for i in range(n_q - 1)], dim=0)) + yield (self.format_tensor_name(T.A_GEN_CODE_HEAD), stack(f"linears.{k}.weight" for k in range(n_q))) + + for il in range(dep["num_hidden_layers"]): + p = f"depformer.layers.{il}." + n_w = sum(1 for name in self.model_tensors if name.startswith(p + "gating.") and name.endswith(".linear_in.weight")) + assert n_w == n_in, "depformer_in and the per-step weights use the same schedule" + qkv = get(p + "self_attn.in_proj_weight").reshape(n_w, 3, n_dim, n_dim) + yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_Q, il), qkv[:, 0]) + yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_K, il), qkv[:, 1]) + yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_V, il), qkv[:, 2]) + yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_OUT, il), get(p + "self_attn.out_proj.weight").reshape(n_w, n_dim, n_dim)) + gate_up = stack(f"{p}gating.{i}.linear_in.weight" for i in range(n_w)) + gate, up = gate_up.chunk(2, dim=1) + yield (self.format_tensor_name(T.A_GEN_CODE_FFN_GATE, il), gate) + yield (self.format_tensor_name(T.A_GEN_CODE_FFN_UP, il), up) + yield (self.format_tensor_name(T.A_GEN_CODE_FFN_DOWN, il), stack(f"{p}gating.{i}.linear_out.weight" for i in range(n_w))) + yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_NORM, il), get(p + "norm1.alpha").reshape(-1)) + yield (self.format_tensor_name(T.A_GEN_CODE_FFN_NORM, il), get(p + "norm2.alpha").reshape(-1)) diff --git a/conversion/pockettts.py b/conversion/pockettts.py index b0cddc685ca0..4a3d980cd34e 100644 --- a/conversion/pockettts.py +++ b/conversion/pockettts.py @@ -271,26 +271,84 @@ def _embd_table(self, embed: Tensor) -> Tensor: return torch.cat(rows, dim=0) +# mimi tensors (shared with moshi): the transformers of the encoder and the decoder, and the SEANet stacks +MIMI_TFM_MAP = { + "norm1": (gguf.MODEL_TENSOR.A_ENC_INPUT_NORM, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_NORM), + "norm2": (gguf.MODEL_TENSOR.A_ENC_OUTPUT_NORM, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_NORM), + "self_attn.out_proj": (gguf.MODEL_TENSOR.A_ENC_OUTPUT, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_OUT), + "linear1": (gguf.MODEL_TENSOR.A_ENC_FFN_UP, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_UP), + "linear2": (gguf.MODEL_TENSOR.A_ENC_FFN_DOWN, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_DOWN), + "layer_scale_1.scale": (gguf.MODEL_TENSOR.A_ENC_ATTN_SCALE, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_SCALE), + "layer_scale_2.scale": (gguf.MODEL_TENSOR.A_ENC_FFN_SCALE_LS, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_SCALE), +} +MIMI_TFM_QKV = ( + (gguf.MODEL_TENSOR.A_ENC_ATTN_Q, gguf.MODEL_TENSOR.A_ENC_ATTN_K, gguf.MODEL_TENSOR.A_ENC_ATTN_V), + (gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_Q, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_K, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_V), +) + + +def mimi_tfm_tensors(model: MmprojModel, name: str, data_torch: Tensor) -> Iterable[tuple[str, Tensor]]: + is_decoder = name.startswith("mimi.decoder_transformer.") + bid = int(name.split("_transformer.transformer.layers.", 1)[1].split(".")[0]) + key_with_suffix = name.split(f".layers.{bid}.", 1)[1] + + if key_with_suffix == "self_attn.in_proj.weight": + q, k, v = data_torch.chunk(3, dim=0) + names = MIMI_TFM_QKV[1 if is_decoder else 0] + for tensor, part in zip(names, (q, k, v)): + yield (model.format_tensor_name(tensor, bid), part) + return + + key, suffix = key_with_suffix.rsplit(".", 1) + entry = MIMI_TFM_MAP.get(key) or MIMI_TFM_MAP.get(key_with_suffix) + if entry is None: + return + tensor = entry[1 if is_decoder else 0] + suffix = ".weight" if key_with_suffix.endswith(".scale") else "." + suffix + yield (model.format_tensor_name(tensor, bid, suffix=suffix), data_torch) + + +def mimi_seanet_tensors(model: MmprojModel, name: str, data_torch: Tensor, n_stages: int) -> Iterable[tuple[str, Tensor]]: + T = gguf.MODEL_TENSOR + is_decoder = name.startswith("mimi.decoder.") + idx = int(name.split(".model.", 1)[1].split(".")[0]) + suffix = "." + name.rsplit(".", 1)[1] + + conv_in, conv_out, res1, res2, scale = ( + (T.A_GEN_WAV_SEANET_CONV_IN, T.A_GEN_WAV_SEANET_CONV_OUT, T.A_GEN_WAV_SEANET_RES_CONV1, + T.A_GEN_WAV_SEANET_RES_CONV2, T.A_GEN_WAV_SEANET_SCALE_CONV) + if is_decoder else + (T.A_ENC_SEANET_CONV_IN, T.A_ENC_SEANET_CONV_OUT, T.A_ENC_SEANET_RES_CONV1, + T.A_ENC_SEANET_RES_CONV2, T.A_ENC_SEANET_SCALE_CONV) + ) + + if idx == 0: + yield (model.format_tensor_name(conv_in, suffix=suffix), data_torch) + return + if idx == 3 * n_stages + 2: + yield (model.format_tensor_name(conv_out, suffix=suffix), data_torch) + return + + for stage in range(n_stages): + res_idx = _DEC_RES_IDX(stage) if is_decoder else _ENC_RES_IDX(stage) + scale_idx = _DEC_SCALE_IDX(stage) if is_decoder else _ENC_SCALE_IDX(stage) + if idx == scale_idx: + yield (model.format_tensor_name(scale, stage, suffix=suffix), data_torch) + return + if idx == res_idx: + # block.1 is the dilated conv, block.3 the pointwise one (0 and 2 are ELU) + inner = int(name.split(".block.", 1)[1].split(".")[0]) + tensor = res1 if inner == 1 else res2 + yield (model.format_tensor_name(tensor, stage, suffix=suffix), data_torch) + return + + @ModelBase.register("PocketTTSModel") # [TAG_HF_EXAMPLE_MISSING] model is gated, and the checkpoint requires cd to subdir, not supported here class PocketTTSMmprojModel(MmprojModel): has_audio_encoder = True has_vision_encoder = False - _MIMI_TFM_MAP = { - "norm1": (gguf.MODEL_TENSOR.A_ENC_INPUT_NORM, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_NORM), - "norm2": (gguf.MODEL_TENSOR.A_ENC_OUTPUT_NORM, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_NORM), - "self_attn.out_proj": (gguf.MODEL_TENSOR.A_ENC_OUTPUT, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_OUT), - "linear1": (gguf.MODEL_TENSOR.A_ENC_FFN_UP, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_UP), - "linear2": (gguf.MODEL_TENSOR.A_ENC_FFN_DOWN, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_DOWN), - "layer_scale_1.scale": (gguf.MODEL_TENSOR.A_ENC_ATTN_SCALE, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_SCALE), - "layer_scale_2.scale": (gguf.MODEL_TENSOR.A_ENC_FFN_SCALE_LS, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_SCALE), - } - _MIMI_TFM_QKV = ( - (gguf.MODEL_TENSOR.A_ENC_ATTN_Q, gguf.MODEL_TENSOR.A_ENC_ATTN_K, gguf.MODEL_TENSOR.A_ENC_ATTN_V), - (gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_Q, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_K, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_V), - ) - def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.has_audio_encoder = _has_voice_encoder(self.dir_model) @@ -419,11 +477,11 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter return if "_transformer.transformer.layers." in name: - yield from self._mimi_tfm_tensor(name, data_torch) + yield from mimi_tfm_tensors(self, name, data_torch) return if name.startswith("mimi.encoder.model.") or name.startswith("mimi.decoder.model."): - yield from self._seanet_tensor(name, data_torch) + yield from mimi_seanet_tensors(self, name, data_torch, _N_SEANET_STAGES) return return @@ -471,57 +529,3 @@ def _flow_net_tensor(self, name: str, data_torch: Tensor) -> Iterable[tuple[str, if tensor is not None: yield (self.format_tensor_name(tensor, bid, suffix=suffix), data_torch) return - - def _mimi_tfm_tensor(self, name: str, data_torch: Tensor) -> Iterable[tuple[str, Tensor]]: - is_decoder = name.startswith("mimi.decoder_transformer.") - bid = int(name.split("_transformer.transformer.layers.", 1)[1].split(".")[0]) - key_with_suffix = name.split(f".layers.{bid}.", 1)[1] - - if key_with_suffix == "self_attn.in_proj.weight": - q, k, v = data_torch.chunk(3, dim=0) - names = self._MIMI_TFM_QKV[1 if is_decoder else 0] - for tensor, part in zip(names, (q, k, v)): - yield (self.format_tensor_name(tensor, bid), part) - return - - key, suffix = key_with_suffix.rsplit(".", 1) - entry = self._MIMI_TFM_MAP.get(key) or self._MIMI_TFM_MAP.get(key_with_suffix) - if entry is None: - return - tensor = entry[1 if is_decoder else 0] - suffix = ".weight" if key_with_suffix.endswith(".scale") else "." + suffix - yield (self.format_tensor_name(tensor, bid, suffix=suffix), data_torch) - - def _seanet_tensor(self, name: str, data_torch: Tensor) -> Iterable[tuple[str, Tensor]]: - T = gguf.MODEL_TENSOR - is_decoder = name.startswith("mimi.decoder.") - idx = int(name.split(".model.", 1)[1].split(".")[0]) - suffix = "." + name.rsplit(".", 1)[1] - - conv_in, conv_out, res1, res2, scale = ( - (T.A_GEN_WAV_SEANET_CONV_IN, T.A_GEN_WAV_SEANET_CONV_OUT, T.A_GEN_WAV_SEANET_RES_CONV1, - T.A_GEN_WAV_SEANET_RES_CONV2, T.A_GEN_WAV_SEANET_SCALE_CONV) - if is_decoder else - (T.A_ENC_SEANET_CONV_IN, T.A_ENC_SEANET_CONV_OUT, T.A_ENC_SEANET_RES_CONV1, - T.A_ENC_SEANET_RES_CONV2, T.A_ENC_SEANET_SCALE_CONV) - ) - - if idx == 0: - yield (self.format_tensor_name(conv_in, suffix=suffix), data_torch) - return - if idx == 3 * _N_SEANET_STAGES + 2: - yield (self.format_tensor_name(conv_out, suffix=suffix), data_torch) - return - - for stage in range(_N_SEANET_STAGES): - res_idx = _DEC_RES_IDX(stage) if is_decoder else _ENC_RES_IDX(stage) - scale_idx = _DEC_SCALE_IDX(stage) if is_decoder else _ENC_SCALE_IDX(stage) - if idx == scale_idx: - yield (self.format_tensor_name(scale, stage, suffix=suffix), data_torch) - return - if idx == res_idx: - # block.1 is the dilated conv, block.3 the pointwise one (0 and 2 are ELU) - inner = int(name.split(".block.", 1)[1].split(".")[0]) - tensor = res1 if inner == 1 else res2 - yield (self.format_tensor_name(tensor, stage, suffix=suffix), data_torch) - return diff --git a/conversion/qwen3vl.py b/conversion/qwen3vl.py index 9458366b1001..c15959bc4078 100644 --- a/conversion/qwen3vl.py +++ b/conversion/qwen3vl.py @@ -2,6 +2,7 @@ import json +from pathlib import Path from typing import Any, Callable, Iterable, TYPE_CHECKING if TYPE_CHECKING: @@ -393,8 +394,10 @@ def set_gguf_parameters(self): def set_vocab(self): super().set_vocab() - # fix chat template, use correct chatml format - self.gguf_writer.add_chat_template("{% for message in messages %}{{'<|im_start|>' + message['role'] + '\\n' + message['content'] + '<|im_end|>' + '\\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\\n' }}{% endif %}") + # the model outputs "language ", the template renders the language prefix as reasoning_content + # so that the chat parser can separate it from the transcript + template_path = Path(__file__).parent.parent / "models" / "templates" / "Qwen3-ASR.jinja" + self.gguf_writer.add_chat_template(template_path.read_text(encoding="utf-8")) # correct BOS/EOS tokens with open(self.dir_model / "tokenizer_config.json", "r", encoding="utf-8") as f: tokenizer_config = json.load(f) diff --git a/convert_hf_to_gguf_update.py b/convert_hf_to_gguf_update.py index ff5fca4fff89..91fb418a5f2d 100755 --- a/convert_hf_to_gguf_update.py +++ b/convert_hf_to_gguf_update.py @@ -168,6 +168,7 @@ class TOKENIZER_TYPE(IntEnum): {"name": "mmbert", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/jhu-clsp/mmBERT-base", }, {"name": "k2-horizon", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/IFM/K2-Horizon-36B", }, {"name": "inkling2", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/thinkingmachines/Inkling-2-Small", }, + {"name": "domyn-edge", "tokt": TOKENIZER_TYPE.BPE, "repo": "https://huggingface.co/domyn/Domyn-Edge-Teacher-IF", }, ] # some models are known to be broken upstream, so we will skip them as exceptions @@ -227,8 +228,6 @@ def download_model(model): repo = model["repo"] tokt = model["tokt"] - os.makedirs(f"models/tokenizers/{name}", exist_ok=True) - files = ["config.json", "tokenizer.json", "tokenizer_config.json"] if name == "gpt-4o": @@ -243,6 +242,7 @@ def download_model(model): if os.path.isdir(repo): # If repo is a path on the file system, copy the directory + os.makedirs(f"models/tokenizers/{name}", exist_ok=True) for file in files: src_path = os.path.join(repo, file) dst_path = f"models/tokenizers/{name}/{file}" @@ -484,7 +484,7 @@ def get_vocab_base_pre(self, tokenizer) -> str: tokenizer = AutoTokenizer.from_pretrained(f"models/tokenizers/{name}", use_fast=False) else: tokenizer = AutoTokenizer.from_pretrained(f"models/tokenizers/{name}") - except (OSError, TypeError) as e: + except (OSError, TypeError, ValueError) as e: logger.error(f"Failed to load tokenizer for model {name}. Error: {e}") continue # Skip this model and continue with the next one in the loop diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md index 0b5615ca2460..a3a94aa16fb6 100644 --- a/docs/backend/OPENVINO.md +++ b/docs/backend/OPENVINO.md @@ -195,6 +195,7 @@ The models below were tested with `llama-cli` and `Q4_K_M` files on an Intel® C | [bartowski/prism-ml_Bonsai-8B-unpacked-Q4_K_M](https://huggingface.co/bartowski/prism-ml_Bonsai-8B-unpacked-GGUF) | ✓ | ✓ | ✓ | | [LiquidAI/LFM2.5-2.6B-Q4_K_M](https://huggingface.co/LiquidAI/LFM2.5-2.6B-GGUF) | ✓ | ✓ | ✗ | | [bartowski/inclusionAI_Ling-mini-2.0-Q4_K_M](https://huggingface.co/bartowski/inclusionAI_Ling-mini-2.0-GGUF) | ✓ | ✓ | ✗ | +| [tiiuae/Falcon-H1-0.5B-Instruct-Q4_K_M](https://huggingface.co/tiiuae/Falcon-H1-0.5B-Instruct-GGUF) | ✓ | ✓ | ✗ | | | | | | | [Qwen/Qwen3-Embedding-0.6B-Q8_0](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B-GGUF) | ✓ | ✓ | ✗ | | [ggml-org/bge-m3-Q8_0](https://huggingface.co/ggml-org/bge-m3-Q8_0-GGUF) | ✓ | ✓ | ✗ | @@ -990,6 +991,7 @@ build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M. - Multimodal features (audio/image/video) are a work in progress. - Embedding models: reranking models are not validated. - Llama.cpp tool coverage across CPU/GPU/NPU is not uniform. +- Mamba-based models (e.g. Falcon-H1): `llama-perplexity` with several sequences per batch fails; set `-b` to the same value as `-c`. GPU accuracy is slightly lower than CPU. **GPU-specific** @@ -1012,6 +1014,7 @@ build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M. - `llama-perplexity`: requires `-b 512` or smaller. - Flash attention must stay on, which is the default (`-fa auto`). With `-fa off`, the run fails on the NPU. - `llama-embedding` fails on the NPU. +- Mamba-based models (e.g. Falcon-H1) fail on the NPU with `Failed to set tensor` (element type mismatch). - Lunar Lake NPU: decode slows down sharply when the context is large. The context size at which this starts depends on the model. - **Workaround:** Pass the smallest context that fits the use, e.g. `-c 512`, or `-c 256` for larger models. - Panther Lake NPU: the load of a Qwen3.5 model can end with a segmentation fault in the NPU compiler of OpenVINO 2026.4.1. diff --git a/docs/backend/SYCL.md b/docs/backend/SYCL.md index 8649fca0f8a7..4a1d16aad703 100644 --- a/docs/backend/SYCL.md +++ b/docs/backend/SYCL.md @@ -62,7 +62,7 @@ The packages for FP32 and FP16 would have different accuracy and performance on - 2026.04-05 - Optimize mul_mat by reorder feature for data type: Q4_K, Q5_K, Q6_K, Q8_0. - Fused MoE. - - Upgrate CI and built package for oneAPI 2025.3.3, support Ubuntu 24.04 built package. + - Upgrade CI and built package for oneAPI 2025.3.3, support Ubuntu 24.04 built package. - 2026.03 - Support Flash-Attention: less memory usage, performance impact depends on LLM. @@ -131,8 +131,6 @@ SYCL backend supports Intel GPU Family: - Intel Built-in Arc GPU - Intel iGPU in Core CPU (11th Generation Core CPU and newer, refer to [oneAPI supported GPU](https://www.intel.com/content/www/us/en/developer/articles/system-requirements/intel-oneapi-base-toolkit-system-requirements.html#inpage-nav-1-1)). -On older Intel GPUs, you may try [OpenCL](/docs/backend/OPENCL.md) although the performance is not optimal, and some GPUs may not support OpenCL nor have any GPGPU capabilities. - #### Verified devices | Intel GPU | Status | Verified Model | @@ -147,7 +145,7 @@ On older Intel GPUs, you may try [OpenCL](/docs/backend/OPENCL.md) although the *Notes:* - **Memory** - - The device memory is a limitation when running a large model. The loaded model size, *`llm_load_tensors: buffer_size`*, is displayed in the log when running `./bin/llama-completion`. + - The device memory is a limitation when running a large model. The loaded model size is displayed in the log when running `./bin/llama-completion`, for example *`load_tensors: SYCL0 model buffer size = 3577.56 MiB`*. - Please make sure the GPU shared memory from the host is large enough to account for the model's size. For e.g. the *llama-2-7b.Q4_0* requires at least 8.0GB for integrated GPU and 4.0GB for discrete GPU. - **Execution Unit (EU)** @@ -172,12 +170,12 @@ Please refer to [Docker with SYCL](../docker.md#docker-with-sycl) for details. This chapter is for quick development & try with SYCL backend on Intel GPU. -You need to install following sofeware before development: +You need to install following software before development: - Intel GPU driver - oneAPI package - other development tools. -Please refer to [Linux](#linux) or [Windows](#windows-1) for above installation and resolve the trouble in usage. There are the detailed guide. +Please refer to [Linux](#linux) or [Windows](#windows-1) for above installation and resolve the trouble in usage. They have the detailed guide. - Linux @@ -474,7 +472,7 @@ Download the binary package for Windows from: https://github.com/ggml-org/llama. Extract the package to local folder, run the llama tools directly. Refer to [Run the inference](#iii-run-the-inference-1). -Note, the package includes the SYCL running time and all depended dll files, no need to install oneAPI package and activte them. +Note, the package includes the SYCL running time and all depended dll files, no need to install oneAPI package and activate them. ### Option 2: build locally from the source code. @@ -484,7 +482,7 @@ Note, the package includes the SYCL running time and all depended dll files, no If you already have a recent version of Microsoft Visual Studio, you can skip this step. Otherwise, please refer to the official download page for [Microsoft Visual Studio](https://visualstudio.microsoft.com/). -2. Install Intel® oneAPI Base toolkit +2. Install Intel® oneAPI Toolkit SYCL backend depends on: - Intel® oneAPI DPC++/C++ compiler/running-time. @@ -492,11 +490,10 @@ SYCL backend depends on: - Intel® oneAPI Deep Neural Network Library (oneDNN). - Intel® oneAPI Math Kernel Library (oneMKL). -All above are included in both **Intel® oneAPI Base toolkit** and **Intel® Deep Learning Essentials** packages. - -It's recommended to install **Intel® Deep Learning Essentials** which only provides the necessary libraries with less size. +a. Install the toolkit -The **Intel® oneAPI Base toolkit** and **Intel® Deep Learning Essentials** can be obtained from the official [Intel® oneAPI Base Toolkit](https://www.intel.com/content/www/us/en/developer/tools/oneapi/base-toolkit.html) page. +It's recommended to install the [Intel® oneAPI Toolkit](https://www.intel.com/content/www/us/en/developer/tools/oneapi/base-toolkit.html). +Alternatively, users can install **Intel® Deep Learning Essentials** + **oneDNN** to provide the necessary libraries with lesser size. Please follow the instructions for downloading and installing the Toolkit for Windows, and preferably keep the default installation values unchanged, notably the installation path *(`C:\Program Files (x86)\Intel\oneAPI` by default)*. @@ -792,7 +789,7 @@ User can use the device management in [docs/multi-gpu.md](https://github.com/ggm | GGML_SYCL_GRAPH | ON *(default)* \|OFF *(Optional)* | Enable build with [SYCL Graph extension](https://github.com/intel/llvm/blob/sycl/sycl/doc/extensions/experimental/sycl_ext_oneapi_graph.asciidoc). | | GGML_SYCL_DNN | ON *(default)* \|OFF *(Optional)* | Enable build with oneDNN. | | GGML_SYCL_HOST_MEM_FALLBACK | ON *(default)* \|OFF *(Optional)* | Allow host memory fallback when device memory is full during quantized weight reorder. Enables inference to continue at reduced speed (reading over PCIe) instead of failing. Requires Linux kernel 6.8+. | -| GGML_SYCL_SUPPORT_LEVEL_ZERO_API | ON *(default)* \|OFF *(Optional)* | Support to use Level Zero API for device memory allocation. Requires Level Zero headers/library at build time and Intel GPU driver (Level Zero runtime) at run time. Reduces system RAM usage during multi-GPU inference. SYCL backend always runs on Level Zero running time even if it's set as OFF (The SYCL api will be usage for memory allocation).| +| GGML_SYCL_SUPPORT_LEVEL_ZERO_API | ON *(default)* \|OFF *(Optional)* | Support to use Level Zero API for device memory allocation. Requires Level Zero headers/library at build time and Intel GPU driver (Level Zero runtime) at run time. Reduces system RAM usage during multi-GPU inference. SYCL backend always runs on Level Zero running time even if it's set as OFF (the SYCL API is then used for memory allocation).| | CMAKE_C_COMPILER | `icx` *(Linux)*, `icx/cl` *(Windows)* | Set `icx` compiler for SYCL code path. | | CMAKE_CXX_COMPILER | `icpx` *(Linux)*, `icx` *(Windows)* | Set `icpx/icx` compiler for SYCL code path. | @@ -809,11 +806,11 @@ User can use the device management in [docs/multi-gpu.md](https://github.com/ggm | GGML_SYCL_ENABLE_OPT | 0 or 1 (default)| Enable optimize features for Intel GPUs. (Recommended to 0 for Intel devices older than Gen 10) | | GGML_SYCL_ENABLE_GRAPH | 0 (default) or 1 | Enable running computations through SYCL Graphs feature. Disabled by default because SYCL Graph is still in development, performance depends on model and device. [1.](#sycl-graph-footnote) | | GGML_SYCL_GRAPH_EVICTION_TIMEOUT | 10 (default) or positive integer | Seconds a cached SYCL graph can go unused before it is evicted. Checked on a sweep that runs every half of this timeout. | -| GGML_SYCL_ENABLE_HOST_PINNED_MEM | 0 or 1 (default) | Enable host pinned memory to speed up copy data from host to device. When disable it, host memory will common malloc() on CPU. Disable it when use `--load-model mlock`.| +| GGML_SYCL_ENABLE_HOST_PINNED_MEM | 0 or 1 (default) | Enable host pinned memory to speed up copy data from host to device. When disable it, host memory will common malloc() on CPU. Disable it when use `--load-mode mlock`.| | GGML_SYCL_HOST_PINNED_MEM_2G | 0 (default) or 1 | Limit the max memory allocation to be no more than 2GB when enable host pinned memory. USM allocations above 2 GiB take the relaxed/large-allocation path, which serializes H2D copies with compute and prevents copy/compute overlap. It will impact the startup time. Need more test. Depend on `GGML_SYCL_ENABLE_HOST_PINNED_MEM=1`.| | GGML_SYCL_UPLOAD_STAGING_SLOTS | 4 (default) or non-negative integer | Number of 8 MiB pinned host slots used to stage tensor uploads (model loading), so the host copy of one slot overlaps the transfer of the previous one. Set to 0 to use the old path: a malloc'd bounce buffer and a blocking copy per tensor. | | GGML_SYCL_GET_MEM_API | 0 (default) or 1 | Set to get memory info (free, total) by Level Zero or SYCL API:
0 - Level Zero API: support more GPUs, only run on Level Zero running time. When there is an error, fallback to call SYCL API. Depend on GGML_SYCL_SUPPORT_LEVEL_ZERO_API.
1 - SYCL API: legacy, support more running time, it can't get the free size of some GPUs (like Arc770). In such case, return the free size as value of total size.| -| GGML_SYCL_USE_LEVEL_ZERO_API | 1 (default) or 0 | Use Level Zero API for device memory allocation instead of SYCL. Reduces system RAM usage on Intel dGPUs by avoiding DMA-buf/TTM host memory staging. Requires GGML_SYCL_SUPPORT_LEVEL_ZERO_API=ON at build time. SYCL backend always runs on Level Zero running time even if it's set as OFF (The SYCL api will be usage for memory allocation).| +| GGML_SYCL_USE_LEVEL_ZERO_API | 1 (default) or 0 | Use Level Zero API for device memory allocation instead of SYCL. Reduces system RAM usage on Intel dGPUs by avoiding DMA-buf/TTM host memory staging. Requires GGML_SYCL_SUPPORT_LEVEL_ZERO_API=ON at build time. SYCL backend always runs on Level Zero running time even if it's set as OFF (the SYCL API is then used for memory allocation).| | GGML_SYCL_ENABLE_DNN | 0 or 1 (default)| Enable running computations through oneDNN and always use oneMKL. | | GGML_SYCL_FA_ONEDNN | 1 (default) or 0 | Enable the oneDNN fused SDPA (flash-attention) path on supported GPUs. Set to 0 to always use the native SYCL flash-attention kernel. | | GGML_SYCL_FA_ONEDNN_MAX_KV | 0 (default, disabled) or positive integer | By default (0), all sequences are handled by the oneDNN fused SDPA path, regardless of KV length; a positive value caps that length, past which sequences fall back to the native kernel. If GPU driver watchdog resets (DEVICE_LOST) occur during long-context inference, set this near the context depth where they start, e.g. 24576. | @@ -830,6 +827,7 @@ User can use the device management in [docs/multi-gpu.md](https://github.com/ggm | GGML_SYCL_XMX_MAX_COLS | non-negative integer, 80 (default) | Most activation columns (batch size) the `GGML_SYCL_ENABLE_XMX_ESIMD` kernels take; wider batches use the other mat-mul kernels. A larger value keeps XMX for bigger batches (as repeated launches), `0` never uses it. | | GGML_SYCL_XMX_GLU_MAX_COLS | 0 to 16, 16 (default) | Most columns the fused gate and up XMX kernel takes; wider batches run gate and up as separate mat-vecs. 16 is the most the kernel is built for, larger values are clamped to 16 and `0` turns the fused kernel off. | | GGML_SYCL_XMX_GATHER_TYPES | decimal bitmask, all bits set (default) | Weight formats that may use the XMX dequant-GEMM paths, which dequantize weights straight into the XMX tiles. This speeds up prompt processing of MoE models on GPUs with XMX units (Arc A- and B-series, Arc Pro, Data Center GPU Max), for example pp512 of Qwen3-30B-A3B UD-IQ3_XXS by about 50% on an Arc Pro B60. Bits:
* 1: IQ4_NL, 2: IQ3_S, 4: IQ4_XS, 8: IQ3_XXS, 16: IQ2_XXS, 32: IQ2_XS, 64: IQ2_S, 128: IQ1_S, 256: IQ1_M
* 512: Q8_0, 1024: Q4_K, 2048: Q5_K, 4096: Q6_K, 8192: Q2_K, 16384: Q3_K (MoE `MUL_MAT_ID` only)
Add values to combine them, for example `3` for IQ4_NL and IQ3_S; `0` disables the paths. A set bit does not force the path: batches of more than 64 tokens per expert use the library GEMM unless the device schedule width heuristic is overridden with `GGML_SYCL_MMID_SCHED=3`. Row lengths must be a multiple of 256 (32 for IQ4_NL and Q8_0). | +| GGML_SYCL_MMID_ESIMD | 0, 1 (default), 2 | The `MUL_MAT_ID` grouped XMX dequant-GEMM as an ESIMD kernel that dequantizes the weights straight into the `dpas` register operands, with no shared local memory image of them, from either weight layout (the per-expert reorder or the canonical blocks). q8_0, iq4_nl, iq4_xs, iq3_s, iq3_xxs and q2_K to q6_K. It stands in for the 8x16x16 sub-group-16 combination of f16 or bf16 (Xe2, Xe-HPC) and for the 8x8x16 sub-group-8 one (Xe-HPG: Arc A-series, ARL-H; there it works on 16 rows a thread and reads with 1D block loads, since that architecture has half the register file and no 2D block loads); while it is on, a grouped call whose weight type it covers is moved to that combination from any other shape of its type and sub-group size, whatever `GGML_SYCL_XMX_GATHER_SHAPES` allows, because the shape bits choose among `joint_matrix` tiles and the ESIMD kernel tiles on its own. A call it declines runs that combination's `joint_matrix` kernel. 0 uses the `joint_matrix` kernel, 1 the ESIMD one, 2 the ESIMD one summing K in the `joint_matrix` kernel's order (bit-identical output for f16; slower). An AOT build gets its 256-register file through `-ze-opt-enable-auto-large-GRF-mode` (set by the CMake build). Not built with `GGML_SYCL_SUPPORT_XMX=OFF`. | | GGML_SYCL_MMID_SCHED | decimal bitmask, 1 (default) | Build the grouped MoE routing and tile schedule on the GPU, avoiding the expert-ID host readback and CPU sort.
* 1: enable the device schedule.
* 2: override the fallback for models with few routed experts by disabling the performance heuristic that rejects batches averaging more than 64 routed rows per expert. This may reduce performance; type, shape, precision and device capability checks still apply.
Use `3` to enable the device schedule and override this heuristic, or `0` to use the host schedule. Bit 2 alone does not enable the device schedule. Higher bits are ignored. | | GGML_SYCL_XMX_GATHER_SHAPES | decimal bitmask, 255 (default) | XMX `joint_matrix` combinations the paths of `GGML_SYCL_XMX_GATHER_TYPES` may use; the operand type comes from `GGML_SYCL_DYNAMIC_PRECISION` and the best supported combination is picked automatically (logged as `fg_pick_combo`). Bits:
* Xe2, Xe3, Xe-HPC: 1: f16 8x16x16, 2: f16 16x16x16, 4: f16 32x64x16, 8: f16 32x64x32, 32: tf32 8x16x8, 64: bf16 8x16x16
* Xe-HPG (Arc A770, ARL-H): 16: f16 8x8x16, 128: bf16 8x8x16
Clear a bit to exclude a combination, or set a single bit to force one for testing. | | GGML_SYCL_DYNAMIC_PRECISION | `F16` (default with `GGML_SYCL_F16=ON`), `BF16`, `TF32` or `F32` (default otherwise) | Operand type of the XMX dequant-GEMM paths (`GGML_SYCL_XMX_GATHER_TYPES`); accumulation is always f32. `F16` is the fastest, but activations above 65504 overflow. `BF16` keeps the f32 range at a 7-bit mantissa, `TF32` keeps the range and the f16 mantissa but is about 30% slower and needs Xe2, Xe3 or Xe-HPC, and `F32` turns the XMX paths off. Ops that request a higher src1 precision ([TAG_GGML_PREC]) get it regardless of this setting. | @@ -839,7 +837,7 @@ User can use the device management in [docs/multi-gpu.md](https://github.com/ggm | GGML_SYCL_SPARSE_FA_DEBUG | 0 (default) or 1 | Enable to debug for Sparse Flash-attention.| | GGML_SYCL_SPARSE_FA_MARGIN | [0,..] default:256 | Set the margin value for Sparse Flash-attention.| | ZES_ENABLE_SYSMAN | 0 (default) or 1 | Support to get free memory of GPU by sycl::aspect::ext_intel_free_memory.
Recommended to use when --split-mode = layer | -| UR_L0_ENABLE_RELAXED_ALLOCATION_LIMITS | 0 (default) or 1 | Allow SYCL/Unified Runtime Level Zero device allocations larger than 4 GiB. llama.cpp's direct Level Zero allocation path requests the relaxed maximum-size limit itself when GGML_SYCL_ENABLE_LEVEL_ZERO=1. | +| UR_L0_ENABLE_RELAXED_ALLOCATION_LIMITS | 0 (default) or 1 | Allow SYCL/Unified Runtime Level Zero device allocations larger than 4 GiB. llama.cpp's direct Level Zero allocation path requests the relaxed maximum-size limit itself when GGML_SYCL_USE_LEVEL_ZERO_API=1. | | GGML_SYCL_USM_SYSTEM | 0 (default) or 1 | Enable experimental support for [USM system allocations](https://github.khronos.org/SYCL_Reference/iface/usm_basic_concept.html#system-allocations) for large GPU buffers. This requires enough host memory for model weights and caches, an Intel Xe2+ GPU such as BMG or newer and supported on Linux only, with CONFIG_DRM_XE_GPUSVM enabled. | | GGML_SYCL_BMG_VRAM_CHECK | 1 (default) or 0 | Workaround for BMG (Arc B-series) GPUs, where the Level Zero driver accepts device allocations beyond VRAM and moves the overflow to system RAM, which can exhaust host memory when a model does not fit (e.g. `-ngl 999`, see https://github.com/intel/compute-runtime/issues/1047). When enabled, a model or split buffer that does not fit in the device's free memory is refused and the model load fails with an error. Set to 0 to disable. | @@ -950,7 +948,7 @@ Pass these via `CXXFLAGS` or add a one-off `#define` to enable a flag on the spo - `ggml_backend_sycl_buffer_type_alloc_buffer: can't allocate 5000000000 Bytes of memory on device` - With the default `GGML_SYCL_ENABLE_LEVEL_ZERO=1`, llama.cpp requests Level Zero's relaxed maximum-size allocation limit directly. If Level Zero support is disabled at build time or runtime and the allocation goes through SYCL/Unified Runtime instead, enable support for allocations larger than 4 GiB by: + With the default `GGML_SYCL_USE_LEVEL_ZERO_API=1`, llama.cpp requests Level Zero's relaxed maximum-size allocation limit directly. If Level Zero support is disabled at build time or runtime and the allocation goes through SYCL/Unified Runtime instead, enable support for allocations larger than 4 GiB by: ``` export UR_L0_ENABLE_RELAXED_ALLOCATION_LIMITS=1 set UR_L0_ENABLE_RELAXED_ALLOCATION_LIMITS=1 diff --git a/docs/build.md b/docs/build.md index e369aad01f49..759985544cb8 100644 --- a/docs/build.md +++ b/docs/build.md @@ -132,7 +132,10 @@ Full steps, threading notes, and a fallback for older CMake: [AOCL.md](./backend ### Intel oneMKL -Building through oneAPI compilers will make avx_vnni instruction set available for intel processors that do not support avx512 and avx512_vnni. Please note that this build config **does not support Intel GPU**. For Intel GPU support, please refer to [llama.cpp for SYCL](./backend/SYCL.md). +Building through oneAPI compilers will make avx_vnni instruction set available for intel processors that do not support avx512 and avx512_vnni. +> Note: This build config **does not support Intel GPU and NPU**. +> - For Intel GPU support, refer to [OpenVINO](#openvino), [SYCL](#sycl) and [Vulkan](#vulkan) backends. +> - For Intel NPU support, refer to [OpenVINO](#openvino) backend. - Using manual oneAPI installation: By default, `GGML_BLAS_VENDOR` is set to `Generic`, so if you already sourced intel environment script and assign `-DGGML_BLAS=ON` in cmake, the mkl version of Blas will automatically been selected. Otherwise please install oneAPI and follow the below steps: @@ -444,9 +447,9 @@ Launch `w64devkit.exe` and run the following commands to copy Vulkan dependencie ```sh SDK_VERSION=1.3.283.0 cp /VulkanSDK/$SDK_VERSION/Bin/glslc.exe $W64DEVKIT_HOME/bin/ -cp /VulkanSDK/$SDK_VERSION/Lib/vulkan-1.lib $W64DEVKIT_HOME/x86_64-w64-mingw32/lib/ -cp -r /VulkanSDK/$SDK_VERSION/Include/* $W64DEVKIT_HOME/x86_64-w64-mingw32/include/ -cat > $W64DEVKIT_HOME/x86_64-w64-mingw32/lib/pkgconfig/vulkan.pc < $W64DEVKIT_HOME/lib/pkgconfig/vulkan.pc <` to `<|speaker:15|>` in the text give each character its own voice, a text without a tag starts with `<|speaker:0|>` - The language is the one of the text, `--tts-lang` is not used -- Note: `--tts-speaker-file` is not supported yet (voice cloning) +- Voice cloning: `--tts-speaker-file` with the reference clip and `--tts-speaker-text` with its transcript (a transcript without a speaker tag is speaker 0). The clip is encoded by the codec encoder half of `codec.pth` and its codes are put in the prompt as one reference, as the reference does; the clip is truncated to the first 30 s. It needs an mmproj converted with the codec encoder - Note: `--top-k` and `--top-p` are not used, frames are sampled with the settings of the reference (main token: temperature 1.0, top-p 0.9, repetition-aware redraw over the last 16 frames; other codes: temperature 1.0, top-k 30, top-p 0.9) - Each frame is 2048 samples (about 46 ms), generation stops at the end-of-speech token - The codebook tower keeps the whole sequence in its KV cache, the prompt and the generated frames are limited to 4096 positions @@ -192,7 +193,7 @@ llama-tts -m drama3.gguf \ **Note for GGUF conversion:** -The routed experts of the checkpoint are FP8, they are dequantized at conversion. The mmproj holds the codebook tower and the decoder half of `codec.pth`, it is best kept in BF16: +The routed experts of the checkpoint are FP8, they are dequantized at conversion. The mmproj holds the codebook tower and `codec.pth` (the encoder half for voice cloning, the decoder half for the audio), it is best kept in BF16; the codec encoder is always stored in F16/F32: ```sh python convert_hf_to_gguf.py path/to/drama-3 --outtype q8_0 --outfile drama3.gguf @@ -367,6 +368,22 @@ python convert_hf_to_gguf.py MiniMax-Music3 --mmproj --outfile mmproj-minimax-mu The mmproj holds the depth decoder and the DiT layers (in the `--outtype` type), and the condition encoder, the small DiT projections and the DAC decoder, always in F32. +## Hibiki + +Hibiki (Kyutai) translates French speech to English speech in real time. It is a full duplex model: it only runs through the [realtime endpoint](../../tools/server/README.md#full-duplex) of `llama-server`, the audio goes in and comes out every 80 ms. + +The checkpoint is not in the HF layout, the converter reads its `config.json` and the LM and mimi files it names (Hibiki-1B `kyutai/hibiki-1b-pytorch-bf16`, Hibiki-2B `kyutai/hibiki-2b-pytorch-bf16`): + +```sh +python convert_hf_to_gguf.py path/to/hibiki-1b-pytorch-bf16 --outfile hibiki-1b.gguf +python convert_hf_to_gguf.py path/to/hibiki-1b-pytorch-bf16 --mmproj --outfile mmproj-hibiki-1b.gguf + +llama-server -m hibiki-1b.gguf --mmproj mmproj-hibiki-1b.gguf -c 1500 +``` + +- The voice of the output is conditioned like the reference (`very_good`), classifier-free guidance is not supported yet +- The audio codes are sampled with the settings of the checkpoint (temperature 0.8, top-k 250), so is the text (temperature 0.8, top-k 50) unless the server sampling options override it + ## Kokoro Available params: diff --git a/docs/ops.md b/docs/ops.md index bdf64ca0af60..88e92c701d10 100644 --- a/docs/ops.md +++ b/docs/ops.md @@ -24,7 +24,7 @@ Legend: | ARGSORT | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | CEIL | ❌ | ❌ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | CLAMP | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | -| COL2IM_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | +| COL2IM_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | 🟡 | ❌ | ❌ | | CONCAT | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ❌ | ❌ | | CONT | ❌ | 🟡 | ✅ | ✅ | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | ❌ | ❌ | | CONV_1D_DW | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | diff --git a/docs/ops/WebGPU.csv b/docs/ops/WebGPU.csv index 8b5e0c80ed43..2ad8ded659ec 100644 --- a/docs/ops/WebGPU.csv +++ b/docs/ops/WebGPU.csv @@ -5426,39 +5426,44 @@ "WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[3,2,1,1],ne_kernel=[3,2,2,1],s0=1,p0=0,d0=1","support","0","no","WebGPU" "WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[3,2,1,1],ne_kernel=[3,1,2,1],s0=1,p0=0,d0=1","support","0","no","WebGPU" "WebGPU: WebGPU","CONV_TRANSPOSE_1D","ne_input=[2,1,1,1],ne_kernel=[3,1,1,1],s0=1,p0=0,d0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=16,OC=32,T_in=197,s0=8,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=4,OC=3,T_in=7,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=5,T_in=13,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=6,OC=4,T_in=11,s0=3,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=2,OC=3,T_in=9,s0=3,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=5,OC=4,T_in=11,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=8,OC=4,T_in=13,s0=4,p0=2","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=4,OC=3,T_in=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=16,OC=1,T_in=197,s0=8,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=5,T_in=13,s0=3,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f32,K=8,OC=2,T_in=3,s0=2,p0=5","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=16,OC=32,T_in=197,s0=8,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=4,OC=3,T_in=7,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=1,OC=5,T_in=13,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=6,OC=4,T_in=11,s0=3,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=2,OC=3,T_in=9,s0=3,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=5,OC=4,T_in=11,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=8,OC=4,T_in=13,s0=4,p0=2","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=4,OC=3,T_in=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=16,OC=1,T_in=197,s0=8,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=1,OC=5,T_in=13,s0=3,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=f16,K=8,OC=2,T_in=3,s0=2,p0=5","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=16,OC=32,T_in=197,s0=8,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=4,OC=3,T_in=7,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=1,OC=5,T_in=13,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=6,OC=4,T_in=11,s0=3,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=2,OC=3,T_in=9,s0=3,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=5,OC=4,T_in=11,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=8,OC=4,T_in=13,s0=4,p0=2","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=4,OC=3,T_in=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=16,OC=1,T_in=197,s0=8,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=1,OC=5,T_in=13,s0=3,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=8,OC=2,T_in=3,s0=2,p0=5","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=16,OC=32,T_in=197,s0=8,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=4,OC=3,T_in=7,s0=2,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=5,T_in=13,s0=1,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=6,OC=4,T_in=11,s0=3,p0=1,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=2,OC=3,T_in=9,s0=3,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=5,OC=4,T_in=11,s0=2,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=8,OC=4,T_in=13,s0=4,p0=2,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=4,OC=3,T_in=1,s0=2,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=16,OC=1,T_in=197,s0=8,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=5,T_in=13,s0=3,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=8,OC=2,T_in=3,s0=2,p0=5,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=16,OC=32,T_in=197,s0=8,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=4,OC=3,T_in=7,s0=2,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=1,OC=5,T_in=13,s0=1,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=6,OC=4,T_in=11,s0=3,p0=1,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=2,OC=3,T_in=9,s0=3,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=5,OC=4,T_in=11,s0=2,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=8,OC=4,T_in=13,s0=4,p0=2,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=4,OC=3,T_in=1,s0=2,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=16,OC=1,T_in=197,s0=8,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=1,OC=5,T_in=13,s0=3,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f16,K=8,OC=2,T_in=3,s0=2,p0=5,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=16,OC=32,T_in=197,s0=8,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=4,OC=3,T_in=7,s0=2,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=1,OC=5,T_in=13,s0=1,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=6,OC=4,T_in=11,s0=3,p0=1,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=2,OC=3,T_in=9,s0=3,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=5,OC=4,T_in=11,s0=2,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=8,OC=4,T_in=13,s0=4,p0=2,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=4,OC=3,T_in=1,s0=2,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=16,OC=1,T_in=197,s0=8,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=1,OC=5,T_in=13,s0=3,p0=0,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=bf16,K=8,OC=2,T_in=3,s0=2,p0=5,view=0","support","0","no","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=5,OC=3,T_in=17,s0=2,p0=1,view=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=1,T_in=255,s0=1,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=1,T_in=256,s0=1,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=1,T_in=257,s0=1,p0=0,view=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","COL2IM_1D","type=f32,K=1,OC=1,T_in=16777217,s0=1,p0=0,view=0","support","1","yes","WebGPU" "WebGPU: WebGPU","CONV_TRANSPOSE_2D","kernel_type=f32,ne_input=[3,2,3,1],ne_kernel=[2,2,1,3],stride=1","support","0","no","WebGPU" "WebGPU: WebGPU","CONV_TRANSPOSE_2D","kernel_type=f32,ne_input=[10,10,9,1],ne_kernel=[3,3,1,9],stride=2","support","0","no","WebGPU" "WebGPU: WebGPU","CONV_TRANSPOSE_2D","kernel_type=f32,ne_input=[129,63,35,1],ne_kernel=[3,3,48,35],stride=1","support","0","no","WebGPU" diff --git a/ggml/include/ggml-rpc.h b/ggml/include/ggml-rpc.h index da1d4e1f167b..062d5004e8d4 100644 --- a/ggml/include/ggml-rpc.h +++ b/ggml/include/ggml-rpc.h @@ -8,10 +8,10 @@ extern "C" { #define RPC_PROTO_MAJOR_VERSION 10 #define RPC_PROTO_MINOR_VERSION 0 -#define RPC_PROTO_PATCH_VERSION 0 +#define RPC_PROTO_PATCH_VERSION 2 #ifdef __cplusplus -static_assert(GGML_OP_COUNT == 99, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION"); +static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION"); #endif #define GGML_RPC_MAX_SERVERS 16 diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h index 2341fa6c107e..2f466e2e4e46 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -40,8 +40,8 @@ #include #include -#define GGML_FILE_MAGIC 0x67676d6c // "ggml" -#define GGML_FILE_VERSION 2 +#define GGML_FILE_MAGIC 0x67676d6c // "ggml" +#define GGML_FILE_VERSION 2 #define GGML_QNT_VERSION 2 // bump this on quantization format changes #define GGML_QNT_VERSION_FACTOR 1000 // do not change this @@ -214,7 +214,7 @@ extern "C" { struct ggml_context; struct ggml_cgraph; - // NOTE: always add types at the end of the enum to keep backward compatibility + // note: always add types at the end of the enum to keep backward compatibility enum ggml_type { GGML_TYPE_F32 = 0, GGML_TYPE_F16 = 1, @@ -286,6 +286,7 @@ extern "C" { }; // model file types + // [DEPRECATED] will be removed in v2 [TAG_GGML_VERSION_MAJOR_UPDATE] enum ggml_ftype { GGML_FTYPE_UNKNOWN = -1, GGML_FTYPE_ALL_F32 = 0, @@ -319,6 +320,7 @@ extern "C" { }; // available tensor operations: + // note: add new entries at the end of the enum. reorder (if needed) upon major version bumps [TAG_GGML_VERSION_MAJOR_UPDATE] enum ggml_op { GGML_OP_NONE = 0, @@ -429,6 +431,10 @@ extern "C" { GGML_OP_GLU, + GGML_OP_SLEEP, + + GGML_OP_SIGMOID_BACK, + GGML_OP_COUNT, }; @@ -499,7 +505,7 @@ extern "C" { GGML_TRI_TYPE_UPPER_DIAG = 0, GGML_TRI_TYPE_UPPER = 1, GGML_TRI_TYPE_LOWER_DIAG = 2, - GGML_TRI_TYPE_LOWER = 3 + GGML_TRI_TYPE_LOWER = 3, }; struct ggml_init_params { @@ -546,6 +552,8 @@ extern "C" { static const size_t GGML_TENSOR_SIZE = sizeof(struct ggml_tensor); + typedef struct ggml_tensor * ggml_tensor_t; + // Abort callback // If not NULL, called before ggml computation // If it returns true, the computation is aborted @@ -1032,6 +1040,13 @@ extern "C" { struct ggml_tensor * a, struct ggml_tensor * b); + // a - dy + // b - x + GGML_API struct ggml_tensor * ggml_sigmoid_back( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + // hardswish(x) = x * relu6(x + 3) / 6 GGML_API struct ggml_tensor * ggml_hardswish( struct ggml_context * ctx, @@ -1314,12 +1329,6 @@ extern "C" { // indirect matrix multiplication // an id of -1 skips the slot and zeroes the matching row of the result - // - // [TAG_MUL_MAT_ID_DUPLICATE_ID] - // note: this op has undefined behaviour if a given `a` is referenced more than once for a given `b` - // (i.e. duplicate experts per token are not guaranteed to be supported in all backends) - // TODO: add backend support: https://github.com/ggml-org/llama.cpp/pull/29998#issuecomment-6153742533 - // the CPU backend skips negative ids, their rows of the result are zero GGML_API struct ggml_tensor * ggml_mul_mat_id( struct ggml_context * ctx, struct ggml_tensor * as, @@ -2285,12 +2294,12 @@ extern "C" { // TODO: needs to be adapted to ggml_flash_attn_ext GGML_API struct ggml_tensor * ggml_flash_attn_back( - struct ggml_context * ctx, - struct ggml_tensor * q, - struct ggml_tensor * k, - struct ggml_tensor * v, - struct ggml_tensor * d, - bool masked); + struct ggml_context * ctx, + struct ggml_tensor * q, + struct ggml_tensor * k, + struct ggml_tensor * v, + struct ggml_tensor * d, + bool masked); GGML_API struct ggml_tensor * ggml_ssm_conv( struct ggml_context * ctx, @@ -2330,13 +2339,13 @@ extern "C" { GGML_API struct ggml_tensor * ggml_unary( struct ggml_context * ctx, - struct ggml_tensor * a, - enum ggml_unary_op op); + struct ggml_tensor * a, + enum ggml_unary_op op); GGML_API struct ggml_tensor * ggml_unary_inplace( - struct ggml_context * ctx, - struct ggml_tensor * a, - enum ggml_unary_op op); + struct ggml_context * ctx, + struct ggml_tensor * a, + enum ggml_unary_op op); // used in sam GGML_API struct ggml_tensor * ggml_get_rel_pos( @@ -2400,12 +2409,12 @@ extern "C" { * TODO: currently only lower, right, non-unitriangular variant is implemented */ GGML_API struct ggml_tensor * ggml_solve_tri( - struct ggml_context * ctx, - struct ggml_tensor * a, - struct ggml_tensor * b, - bool left, - bool lower, - bool uni); + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + bool left, + bool lower, + bool uni); // TODO: add ggml_gated_delta_net_set_bcast() to be able to configure Q, K broadcast type: tiled vs interleaved [TAG_GGML_GDN_BCAST] // ref: https://github.com/ggml-org/llama.cpp/pull/19468#discussion_r2786394306 @@ -2443,11 +2452,11 @@ extern "C" { // ne3 % ne33 == 0 // GGML_API struct ggml_tensor * ggml_lightning_indexer( - struct ggml_context * ctx, - struct ggml_tensor * q, - struct ggml_tensor * k, - struct ggml_tensor * weights, - struct ggml_tensor * mask); + struct ggml_context * ctx, + struct ggml_tensor * q, + struct ggml_tensor * k, + struct ggml_tensor * weights, + struct ggml_tensor * mask); // DeepSeek V4 hyper-connections (ref. https://arxiv.org/pdf/2512.24880) // In short these operations are replacements for the original residual connection (x = transformer(x) + x) @@ -2528,54 +2537,54 @@ extern "C" { // n_tasks == GGML_N_TASKS_MAX means to use max number of tasks GGML_API struct ggml_tensor * ggml_map_custom1( - struct ggml_context * ctx, - struct ggml_tensor * a, - ggml_custom1_op_t fun, - int n_tasks, - void * userdata); + struct ggml_context * ctx, + struct ggml_tensor * a, + ggml_custom1_op_t fun, + int n_tasks, + void * userdata); GGML_API struct ggml_tensor * ggml_map_custom1_inplace( - struct ggml_context * ctx, - struct ggml_tensor * a, - ggml_custom1_op_t fun, - int n_tasks, - void * userdata); + struct ggml_context * ctx, + struct ggml_tensor * a, + ggml_custom1_op_t fun, + int n_tasks, + void * userdata); GGML_API struct ggml_tensor * ggml_map_custom2( - struct ggml_context * ctx, - struct ggml_tensor * a, - struct ggml_tensor * b, - ggml_custom2_op_t fun, - int n_tasks, - void * userdata); + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + ggml_custom2_op_t fun, + int n_tasks, + void * userdata); GGML_API struct ggml_tensor * ggml_map_custom2_inplace( - struct ggml_context * ctx, - struct ggml_tensor * a, - struct ggml_tensor * b, - ggml_custom2_op_t fun, - int n_tasks, - void * userdata); + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + ggml_custom2_op_t fun, + int n_tasks, + void * userdata); GGML_API struct ggml_tensor * ggml_map_custom3( - struct ggml_context * ctx, - struct ggml_tensor * a, - struct ggml_tensor * b, - struct ggml_tensor * c, - ggml_custom3_op_t fun, - int n_tasks, - void * userdata); + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + struct ggml_tensor * c, + ggml_custom3_op_t fun, + int n_tasks, + void * userdata); GGML_API struct ggml_tensor * ggml_map_custom3_inplace( - struct ggml_context * ctx, - struct ggml_tensor * a, - struct ggml_tensor * b, - struct ggml_tensor * c, - ggml_custom3_op_t fun, - int n_tasks, - void * userdata); + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b, + struct ggml_tensor * c, + ggml_custom3_op_t fun, + int n_tasks, + void * userdata); - typedef void (*ggml_custom_op_t)(struct ggml_tensor * dst , int ith, int nth, void * userdata); + typedef void (*ggml_custom_op_t)(struct ggml_tensor * dst, int ith, int nth, void * userdata); GGML_API struct ggml_tensor * ggml_custom_4d( struct ggml_context * ctx, @@ -2599,6 +2608,12 @@ extern "C" { int n_tasks, void * userdata); + // Busy-wait operator for scheduling and backend testing. + GGML_API struct ggml_tensor * ggml_sleep( + struct ggml_context * ctx, + struct ggml_tensor * a, // wait after this tensor has executed, return value is simply a full view of this tensor + int32_t us); // amount of time to wait in microseconds + // loss function GGML_API struct ggml_tensor * ggml_cross_entropy_loss( @@ -2625,10 +2640,10 @@ extern "C" { // stochastic gradient descent step (with weight decay) GGML_API struct ggml_tensor * ggml_opt_step_sgd( - struct ggml_context * ctx, - struct ggml_tensor * a, - struct ggml_tensor * grad, - struct ggml_tensor * sgd_params); // alpha, weight decay + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * grad, + struct ggml_tensor * sgd_params); // alpha, weight decay // build forward multiple tensors and select one of them for computing // this is useful for creating graphs that have constant topology but compute different things based on the input @@ -2663,19 +2678,19 @@ extern "C" { int idx); GGML_API void ggml_build_forward_expand( - struct ggml_cgraph * cgraph, - struct ggml_tensor * tensor); + struct ggml_cgraph * cgraph, + struct ggml_tensor * tensor); // add the tensor and its parents to the graph without marking them for compute // the flag is set later, when the tensor is reached from a node that computes GGML_API void ggml_build_forward_order( - struct ggml_cgraph * cgraph, - struct ggml_tensor * tensor); + struct ggml_cgraph * cgraph, + struct ggml_tensor * tensor); GGML_API void ggml_build_backward_expand( - struct ggml_context * ctx, // context for gradient computation - struct ggml_cgraph * cgraph, - struct ggml_tensor ** grad_accs); + struct ggml_context * ctx, // context for gradient computation + struct ggml_cgraph * cgraph, + struct ggml_tensor ** grad_accs); // graph allocation in a context GGML_API struct ggml_cgraph * ggml_new_graph (struct ggml_context * ctx); // size = GGML_DEFAULT_GRAPH_SIZE, grads = false diff --git a/ggml/src/ggml-alloc.c b/ggml/src/ggml-alloc.c index 65d2bea27726..90082d8619d9 100644 --- a/ggml/src/ggml-alloc.c +++ b/ggml/src/ggml-alloc.c @@ -35,6 +35,7 @@ bool ggml_op_can_inplace(enum ggml_op op) { case GGML_OP_ROPE: case GGML_OP_ROPE_BACK: case GGML_OP_SILU_BACK: + case GGML_OP_SIGMOID_BACK: case GGML_OP_RMS_NORM: case GGML_OP_RMS_NORM_BACK: case GGML_OP_CLAMP: diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp index 595a5824aafe..54d85b597fda 100644 --- a/ggml/src/ggml-backend-meta.cpp +++ b/ggml/src/ggml-backend-meta.cpp @@ -971,7 +971,8 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state( case GGML_OP_CONCAT: { split_state = handle_concat(src_ss); } break; - case GGML_OP_SILU_BACK: { + case GGML_OP_SILU_BACK: + case GGML_OP_SIGMOID_BACK: { split_state = handle_generic(src_ss, /*scalar_only =*/ false); } break; case GGML_OP_NORM: @@ -2154,8 +2155,28 @@ static enum ggml_status ggml_backend_meta_graph_compute(ggml_backend_t backend, } }; - skip_unrelated(); - if (id + 1 >= cgraph->n_nodes) { + // Chain of MULs with MIRRORED src[1], returns false at the end of the graph + auto absorb_muls = [&]() -> bool { + while (true) { + skip_unrelated(); + if (id + 1 >= cgraph->n_nodes) { + return false; + } + ggml_tensor * next = cgraph->nodes[id+1]; + if (next->op == GGML_OP_MUL && next->src[0] == node && + ggml_backend_meta_get_split_state(next->src[1], false).axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED) { + node = next; + id++; + idr = id; + n_used = ggml_node_get_use_count(cgraph, id); + } else { + return true; + } + } + }; + + // MULs before the PARTIAL bias (e.g. a per-expert weight scale): sum_j(s*p_j + b/n) == s*sum_j(p_j) + b + if (!absorb_muls()) { return idr; } { @@ -2169,22 +2190,8 @@ static enum ggml_status ggml_backend_meta_graph_compute(ggml_backend_t backend, n_used = ggml_node_get_use_count(cgraph, id); } } - // Chain of MULs with MIRRORED src[1] - while (true) { - skip_unrelated(); - if (id + 1 >= cgraph->n_nodes) { - return idr; - } - ggml_tensor * next = cgraph->nodes[id+1]; - if (next->op == GGML_OP_MUL && next->src[0] == node && - ggml_backend_meta_get_split_state(next->src[1], false).axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED) { - node = next; - id++; - idr = id; - n_used = ggml_node_get_use_count(cgraph, id); - } else { - break; - } + if (!absorb_muls()) { + return idr; } if (n_used != node->ne[1] || id + 2*n_used-1 >= cgraph->n_nodes) { diff --git a/ggml/src/ggml-cann/ggml-cann.cpp b/ggml/src/ggml-cann/ggml-cann.cpp index 7e692f1b545f..0adc8680f5a4 100644 --- a/ggml/src/ggml-cann/ggml-cann.cpp +++ b/ggml/src/ggml-cann/ggml-cann.cpp @@ -2501,6 +2501,9 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten break; case GGML_OP_SET_ROWS: { + if (op->src[0]->type == GGML_TYPE_BF16) { + return false; + } switch (op->type) { case GGML_TYPE_F32: case GGML_TYPE_F16: @@ -2553,6 +2556,9 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten if (((const int32_t *) op->op_params)[15] != 0) { return false; // FIXME: support ggml_rope_set_offset } + if (op->src[0]->type != GGML_TYPE_F32 && op->src[0]->type != GGML_TYPE_F16) { + return false; + } if (op->src[0]->ne[0] > 896) { return false; } diff --git a/ggml/src/ggml-cpu/CMakeLists.txt b/ggml/src/ggml-cpu/CMakeLists.txt index 8327c52e6dae..172789bd70fa 100644 --- a/ggml/src/ggml-cpu/CMakeLists.txt +++ b/ggml/src/ggml-cpu/CMakeLists.txt @@ -635,7 +635,7 @@ function(ggml_add_cpu_backend_variant_impl tag_name) set(GGML_CPU_KLEIDIAI_AARCH64 OFF) if (GGML_SYSTEM_ARCH STREQUAL "ARM" AND - (APPLE OR WIN32 OR CMAKE_SYSTEM_NAME MATCHES "^(Linux|Android)$") AND + (APPLE OR WIN32 OR CMAKE_SYSTEM_NAME MATCHES "^(Linux|Android|OHOS)$") AND (CMAKE_SYSTEM_PROCESSOR MATCHES "^(aarch64|arm64|ARM64|arm64-v8a)$" OR CMAKE_OSX_ARCHITECTURES MATCHES "arm64" OR CMAKE_GENERATOR_PLATFORM_LWR STREQUAL "arm64" OR diff --git a/ggml/src/ggml-cpu/ggml-cpu.c b/ggml/src/ggml-cpu/ggml-cpu.c index 30edcdbac0c8..ba075ff8d316 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.c +++ b/ggml/src/ggml-cpu/ggml-cpu.c @@ -1169,6 +1169,28 @@ void ggml_set_f32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, //////////////////////////////////////////////////////////////////////////////// +static inline void ggml_deinterleave_f32( + float * GGML_RESTRICT dst0, + float * GGML_RESTRICT dst1, + const float * GGML_RESTRICT src, + int64_t n, + size_t bs, + int nrc) { + GGML_ASSERT(nrc >= 1 && nrc <= 2); + + if (nrc == 1) { + memcpy(dst0, src, n * sizeof(float)); + return; + } + + for (int64_t i = 0; i < n; ++i) { + dst0[i ] = src[2*i + 0 ]; + dst1[i ] = src[2*i + 1 ]; + dst0[bs + i] = src[2*i + 0 + 16]; + dst1[bs + i] = src[2*i + 1 + 16]; + } +} + // ggml_compute_forward_mul_mat static void ggml_compute_forward_mul_mat_one_chunk( @@ -1218,8 +1240,12 @@ static void ggml_compute_forward_mul_mat_one_chunk( // 16 * 2, accounting for mmla kernels float tmp[32]; + const int64_t nr0_split = (ir0_end - ir0_start) / num_rows_per_vec_dot; // rows per stream + const int64_t ir0_end_split = ir0_start + nr0_split; + const int64_t blck_0_split = blck_0 / num_rows_per_vec_dot; + for (int64_t iir1 = ir1_start; iir1 < ir1_end; iir1 += blck_1) { - for (int64_t iir0 = ir0_start; iir0 < ir0_end; iir0 += blck_0) { + for (int64_t iir0 = ir0_start; iir0 < ir0_end_split; iir0 += blck_0_split) { for (int64_t ir1 = iir1; ir1 < iir1 + blck_1 && ir1 < ir1_end; ir1 += num_rows_per_vec_dot) { const int64_t i13 = (ir1 / (ne12 * ne1)); const int64_t i12 = (ir1 - i13 * ne12 * ne1) / ne1; @@ -1249,13 +1275,13 @@ static void ggml_compute_forward_mul_mat_one_chunk( // vec_dot(ne00, &dst_col[ir0], src0_row + ir0*nb01, src1_col); //} - for (int64_t ir0 = iir0; ir0 < iir0 + blck_0 && ir0 < ir0_end; ir0 += num_rows_per_vec_dot) { - vec_dot(ne00, &tmp[ir0 - iir0], (num_rows_per_vec_dot > 1 ? 16 : 0), src0_row + ir0 * nb01, (num_rows_per_vec_dot > 1 ? nb01 : 0), src1_col, (num_rows_per_vec_dot > 1 ? src1_col_stride : 0), num_rows_per_vec_dot); + for (int64_t ir0 = iir0; ir0 < iir0 + blck_0_split && ir0 < ir0_end_split; ++ir0) { + vec_dot(ne00, &tmp[(ir0 - iir0) * num_rows_per_vec_dot], (num_rows_per_vec_dot > 1 ? 16 : 0), src0_row + ir0 * nb01, (num_rows_per_vec_dot > 1 ? nb01 * nr0_split : 0), src1_col, (num_rows_per_vec_dot > 1 ? src1_col_stride : 0), num_rows_per_vec_dot); } - for (int cn = 0; cn < num_rows_per_vec_dot; ++cn) { - memcpy(&dst_col[iir0 + cn * nb1 / nb0], tmp + (cn * 16), (MIN(iir0 + blck_0, ir0_end) - iir0) * sizeof(float)); - } + const int64_t n = MIN(iir0 + blck_0_split, ir0_end_split) - iir0; + float * dst0 = dst_col + iir0; + ggml_deinterleave_f32(dst0, dst0 + nr0_split, tmp, n, nb1 / nb0, num_rows_per_vec_dot); } } } @@ -1858,6 +1884,10 @@ static void ggml_compute_forward(struct ggml_compute_params * params, struct ggm { ggml_compute_forward_silu_back(params, tensor); } break; + case GGML_OP_SIGMOID_BACK: + { + ggml_compute_forward_sigmoid_back(params, tensor); + } break; case GGML_OP_NORM: { ggml_compute_forward_norm(params, tensor); @@ -2034,6 +2064,10 @@ static void ggml_compute_forward(struct ggml_compute_params * params, struct ggm { ggml_compute_forward_fill(params, tensor); } break; + case GGML_OP_SLEEP: + { + ggml_compute_forward_sleep(params, tensor); + } break; case GGML_OP_FLASH_ATTN_EXT: { ggml_compute_forward_flash_attn_ext(params, tensor); @@ -2306,6 +2340,7 @@ static int ggml_get_n_tasks(struct ggml_tensor * node, int n_threads) { case GGML_OP_REPEAT: case GGML_OP_REPEAT_BACK: case GGML_OP_LEAKY_RELU: + case GGML_OP_SLEEP: { n_tasks = 1; } break; @@ -2361,6 +2396,7 @@ static int ggml_get_n_tasks(struct ggml_tensor * node, int n_threads) { } break; case GGML_OP_SILU_BACK: + case GGML_OP_SIGMOID_BACK: case GGML_OP_MUL: case GGML_OP_DIV: case GGML_OP_NORM: @@ -2928,7 +2964,8 @@ struct ggml_cplan ggml_graph_plan( } break; case GGML_OP_SET_ROWS: { - if (node->src[0]->type == GGML_TYPE_F16 && node->type != GGML_TYPE_F16) { + if ((node->src[0]->type == GGML_TYPE_F16 && node->type != GGML_TYPE_F16) || + (node->src[0]->type == GGML_TYPE_BF16 && node->type != GGML_TYPE_BF16)) { cur = ggml_type_size(GGML_TYPE_F32) * node->src[0]->ne[0] * n_tasks; } } break; diff --git a/ggml/src/ggml-cpu/llamafile/sgemm.cpp b/ggml/src/ggml-cpu/llamafile/sgemm.cpp index 68105f029fbf..36b80051b65e 100644 --- a/ggml/src/ggml-cpu/llamafile/sgemm.cpp +++ b/ggml/src/ggml-cpu/llamafile/sgemm.cpp @@ -1474,6 +1474,282 @@ class tinyBLAS_Q0_VXE { const int32_t ith; const int32_t nth; }; + +template +class tinyBLAS_QK_VXE { + public: + tinyBLAS_QK_VXE(int64_t k, + const TA * A, int64_t lda, + const block_q8_K * B, int64_t ldb, + float * C, int64_t ldc, + int32_t ith, int32_t nth) + : A(A), B(B), C(C), k(k), lda(lda), ldb(ldb), ldc(ldc), ith(ith), nth(nth) { + } + + void matmul(int64_t m, int64_t n) { + const int64_t n4 = n / 4 * 4; + const int64_t n2 = n / 2 * 2; + gemm<4>(m, 0, n4); + gemm<2>(m, n4, n2); + gemm<1>(m, n2, n); + } + + private: + // one block of A is loaded once and used for RN columns of B + template + void gemm(int64_t m, int64_t n0, int64_t n) { + const int64_t tiles = m * ((n - n0) / RN); + const int64_t duty = (tiles + nth - 1) / nth; + const int64_t start = duty * ith; + const int64_t end = MIN(start + duty, tiles); + + for (int64_t job = start; job < end; ++job) { + const int64_t ii = job % m; + const int64_t jj = n0 + RN * (job / m); + float32x4_t v_sum[RN] = {}; + + for (int64_t l = 0; l < k; ++l) { + const TA & x = A[lda * ii + l]; + + int8x16_t v_x[n_group]; + load(x, v_x); + + // scale and minimum of the 16 groups, 8 groups per vector + int16x8_t v_scalel, v_scaleh; + int16x8_t v_minl, v_minh; + load_scale(x, v_scalel, v_scaleh, v_minl, v_minh); + + int16x8_t v_scale[n_group]; + for (int32_t g = 0; g < n_group; ++g) { + v_scale[g] = vec_splats((g < n_group / 2 ? v_scalel : v_scaleh)[g % (n_group / 2)]); + } + + const int8_t * y_qs[RN]; + for (int32_t j = 0; j < RN; ++j) { + y_qs[j] = B[ldb * (jj + j) + l].qs; + } + + // the columns are in the inner loop, so that their sums do not wait for each other + int32x4_t v_dot[RN] = {}; + for (int32_t g = 0; g < n_group; ++g) { + for (int32_t j = 0; j < RN; ++j) { + const int8x16_t v_y = vec_xl(0, y_qs[j] + 16 * g); + const int16x8_t v_xy = vec_meadd(v_x[g], v_y, vec_mulo(v_x[g], v_y)); + v_dot[j] = vec_meadd(v_xy, v_scale[g], vec_moadd(v_xy, v_scale[g], v_dot[j])); + } + } + + const float x_d = unhalf(x.d); + for (int32_t j = 0; j < RN; ++j) { + const block_q8_K & y = B[ldb * (jj + j) + l]; + v_sum[j] = vec_madd(vec_float(v_dot[j]), vec_splats(x_d * y.d), v_sum[j]); + } + + if (has_min) { + const float x_dmin = dmin(x); + + for (int32_t j = 0; j < RN; ++j) { + const block_q8_K & y = B[ldb * (jj + j) + l]; + + const int16_t * y_bsums = y.bsums; + const int16x8_t v_bsumsl = vec_xl(0, y_bsums); + const int16x8_t v_bsumsh = vec_xl(0, y_bsums + n_group / 2); + + const int32x4_t v_minsl = vec_meadd(v_bsumsl, v_minl, vec_mulo(v_bsumsl, v_minl)); + const int32x4_t v_minsh = vec_meadd(v_bsumsh, v_minh, vec_mulo(v_bsumsh, v_minh)); + v_sum[j] = vec_madd(vec_float(v_minsl + v_minsh), vec_splats(-x_dmin * y.d), v_sum[j]); + } + } + } + + for (int32_t j = 0; j < RN; ++j) { + C[ldc * (jj + j) + ii] = hsum(v_sum[j]); + } + } + } + + // a block has 16 groups of 16 weights, Q4_K and Q5_K share one scale and minimum per 2 groups + static constexpr int32_t n_group = QK_K / 16; + + // Q3_K and Q6_K have no minimum, their weights are loaded as signed values. + static constexpr bool has_min = !std::is_same::value && !std::is_same::value; + + static float dmin(const block_q2_K & x) { return unhalf(x.dmin); } + static float dmin(const block_q4_K & x) { return unhalf(x.dmin); } + static float dmin(const block_q5_K & x) { return unhalf(x.dmin); } + template static float dmin(const T &) { return 0.0f; } + + static void load(const block_q2_K & x, int8x16_t * v_x) { + const uint8x16_t v_mask = vec_splats((uint8_t)0x03); + const uint8_t * x_qs = x.qs; + + for (int32_t g = 0; g < n_group; ++g) { + const int32_t qs_offset = 16 * (2 * (g / 8) + g % 2); + const int32_t qs_shift = 2 * (g % 8 / 2); + + const uint8x16_t v_qs = vec_xl(0, x_qs + qs_offset); + v_x[g] = (int8x16_t)vec_and(vec_sr(v_qs, qs_shift), v_mask); + } + } + + static void load(const block_q3_K & x, int8x16_t * v_x) { + const uint8x16_t v_mask = vec_splats((uint8_t)0x03); + const uint8x16_t v_one = vec_splats((uint8_t)0x01); + + const uint8_t * x_qs = x.qs; + const uint8_t * x_hmask = x.hmask; + + for (int32_t g = 0; g < n_group; ++g) { + const int32_t qs_offset = 16 * (2 * (g / 8) + g % 2); + const int32_t qs_shift = 2 * (g % 8 / 2); + const int32_t hmask_offset = 16 * (g % 2); + const int32_t hmask_shift = g / 2; + + const uint8x16_t v_qs = vec_xl(0, x_qs + qs_offset); + const uint8x16_t v_hmask = vec_xl(0, x_hmask + hmask_offset); + const uint8x16_t v_lo = vec_and(vec_sr(v_qs, qs_shift), v_mask); + const uint8x16_t v_hi = vec_sl(vec_and(vec_sr(v_hmask, hmask_shift), v_one), 2); + v_x[g] = (int8x16_t)vec_or(v_lo, v_hi) - vec_splats((int8_t)4); + } + } + + static void load(const block_q4_K & x, int8x16_t * v_x) { + const uint8x16_t v_mask = vec_splats((uint8_t)0x0F); + const uint8_t * x_qs = x.qs; + + for (int32_t g = 0; g < n_group; ++g) { + const int32_t qs_offset = 16 * (2 * (g / 4) + g % 2); + const bool qs_low = g % 4 < 2; + + const uint8x16_t v_qs = vec_xl(0, x_qs + qs_offset); + v_x[g] = (int8x16_t)(qs_low ? vec_and(v_qs, v_mask) : vec_sr(v_qs, 4)); + } + } + + static void load(const block_q5_K & x, int8x16_t * v_x) { + const uint8x16_t v_mask = vec_splats((uint8_t)0x0F); + const uint8x16_t v_one = vec_splats((uint8_t)0x01); + const uint8_t * x_qs = x.qs; + const uint8_t * x_qh = x.qh; + + for (int32_t g = 0; g < n_group; ++g) { + const int32_t qs_offset = 16 * (2 * (g / 4) + g % 2); + const bool qs_low = g % 4 < 2; + const int32_t qh_offset = 16 * (g % 2); + const int32_t qh_shift = g / 2; + + const uint8x16_t v_qs = vec_xl(0, x_qs + qs_offset); + const uint8x16_t v_qh = vec_xl(0, x_qh + qh_offset); + const uint8x16_t v_lo = qs_low ? vec_and(v_qs, v_mask) : vec_sr(v_qs, 4); + const uint8x16_t v_hi = vec_sl(vec_and(vec_sr(v_qh, qh_shift), v_one), 4); + v_x[g] = (int8x16_t)vec_or(v_lo, v_hi); + } + } + + static void load(const block_q6_K & x, int8x16_t * v_x) { + const uint8x16_t v_mask4 = vec_splats((uint8_t)0x0F); + const uint8x16_t v_mask2 = vec_splats((uint8_t)0x03); + const uint8_t * x_ql = x.ql; + const uint8_t * x_qh = x.qh; + + for (int32_t g = 0; g < n_group; ++g) { + const int32_t ql_offset = 16 * (4 * (g / 8) + 2 * (g % 4 / 2) + g % 2); + const bool ql_low = g % 8 < 4; + const int32_t qh_offset = 16 * (2 * (g / 8) + g % 2); + const int32_t qh_shift = 2 * (g % 8 / 2); + + const uint8x16_t v_ql = vec_xl(0, x_ql + ql_offset); + const uint8x16_t v_qh = vec_xl(0, x_qh + qh_offset); + const uint8x16_t v_lo = ql_low ? vec_and(v_ql, v_mask4) : vec_sr(v_ql, 4); + const uint8x16_t v_hi = vec_sl(vec_and(vec_sr(v_qh, qh_shift), v_mask2), 4); + v_x[g] = (int8x16_t)vec_or(v_lo, v_hi) - vec_splats((int8_t)32); + } + } + + static void load_scale(const block_q2_K & x, int16x8_t & v_scalel, int16x8_t & v_scaleh, int16x8_t & v_minl, int16x8_t & v_minh) { + const uint8_t * x_scales = x.scales; + const uint8x16_t v_s = vec_xl(0, x_scales); + const uint8x16_t v_scale = vec_and(v_s, vec_splats((uint8_t)0x0F)); + const uint8x16_t v_min = vec_sr(v_s, 4); + + v_scalel = (int16x8_t)vec_unpackh(v_scale); + v_scaleh = (int16x8_t)vec_unpackl(v_scale); + v_minl = (int16x8_t)vec_unpackh(v_min); + v_minh = (int16x8_t)vec_unpackl(v_min); + } + + static void load_scale(const block_q3_K & x, int16x8_t & v_scalel, int16x8_t & v_scaleh, int16x8_t & v_minl, int16x8_t & v_minh) { + // 6-bit scales: low 4 bits in scales[0..7], high 2 bits in scales[8..11] + const uint8x16_t v_lo_byte = { 4, 5, 6, 7, 8, 9, 10, 11, 4, 5, 6, 7, 8, 9, 10, 11 }; + const uint8x16_t v_lo_shift = { 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4 }; + const uint8x16_t v_hi_byte = { 12, 13, 14, 15, 12, 13, 14, 15, 12, 13, 14, 15, 12, 13, 14, 15 }; + const uint8x16_t v_hi_shift = { 0, 0, 0, 0, 2, 2, 2, 2, 4, 4, 4, 4, 6, 6, 6, 6 }; + + // the load starts 4 bytes before scales, so that it stays inside the block + const uint8_t * x_qs = x.qs; + const uint8x16_t v_s = vec_xl(0, x_qs + sizeof(x.qs) - 4); + const uint8x16_t v_lo = vec_and(vec_sr(vec_perm(v_s, v_s, v_lo_byte), v_lo_shift), vec_splats((uint8_t)0x0F)); + const uint8x16_t v_hi = vec_sl(vec_and(vec_sr(vec_perm(v_s, v_s, v_hi_byte), v_hi_shift), vec_splats((uint8_t)0x03)), 4); + const int8x16_t v_scale = (int8x16_t)vec_or(v_lo, v_hi) - vec_splats((int8_t)32); + + v_scalel = vec_unpackh(v_scale); + v_scaleh = vec_unpackl(v_scale); + v_minl = vec_splats((int16_t)0); + v_minh = vec_splats((int16_t)0); + } + + static void load_scale(const block_q4_K & x, int16x8_t & v_scalel, int16x8_t & v_scaleh, int16x8_t & v_minl, int16x8_t & v_minh) { + load_scale_min_k4(x.scales, v_scalel, v_scaleh, v_minl, v_minh); + } + + static void load_scale(const block_q5_K & x, int16x8_t & v_scalel, int16x8_t & v_scaleh, int16x8_t & v_minl, int16x8_t & v_minh) { + load_scale_min_k4(x.scales, v_scalel, v_scaleh, v_minl, v_minh); + } + + static void load_scale(const block_q6_K & x, int16x8_t & v_scalel, int16x8_t & v_scaleh, int16x8_t & v_minl, int16x8_t & v_minh) { + const int8_t * x_scales = x.scales; + const int8x16_t v_scale = vec_xl(0, x_scales); + + v_scalel = vec_unpackh(v_scale); + v_scaleh = vec_unpackl(v_scale); + v_minl = vec_splats((int16_t)0); + v_minh = vec_splats((int16_t)0); + } + + // 8 scales and 8 minimums of 6 bits, same packing as get_scale_min_k4 in ggml-quants.c + static void load_scale_min_k4(const uint8_t * q, int16x8_t & v_scalel, int16x8_t & v_scaleh, int16x8_t & v_minl, int16x8_t & v_minh) { + // bytes 0..3 and 4..7 have the high 2 bits of scale 4..7 and minimum 4..7, move them to bytes 8..11 + const uint8x16_t v_hi_scale = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0 }; + const uint8x16_t v_hi_min = { 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 0, 0, 0, 0 }; + // each scale and minimum is for 2 groups + const uint8x16_t v_group_scale = { 0, 0, 1, 1, 2, 2, 3, 3, 24, 24, 25, 25, 26, 26, 27, 27 }; + const uint8x16_t v_group_min = { 4, 4, 5, 5, 6, 6, 7, 7, 24, 24, 25, 25, 26, 26, 27, 27 }; + + // the 4 bytes after the 12 scale bytes are in the same block + const uint8x16_t v_s = vec_xl(0, q); + const uint8x16_t v_lo = vec_and(v_s, vec_splats((uint8_t)0x3F)); + const uint8x16_t v_hi = vec_sl(vec_sr(v_s, 6), 4); + const uint8x16_t v_scale_47 = vec_or(vec_and(v_s, vec_splats((uint8_t)0x0F)), vec_perm(v_hi, v_hi, v_hi_scale)); + const uint8x16_t v_min_47 = vec_or(vec_sr(v_s, 4), vec_perm(v_hi, v_hi, v_hi_min)); + const uint8x16_t v_scale = vec_perm(v_lo, v_scale_47, v_group_scale); + const uint8x16_t v_min = vec_perm(v_lo, v_min_47, v_group_min); + + v_scalel = (int16x8_t)vec_unpackh(v_scale); + v_scaleh = (int16x8_t)vec_unpackl(v_scale); + v_minl = (int16x8_t)vec_unpackh(v_min); + v_minh = (int16x8_t)vec_unpackl(v_min); + } + + const TA * const A; + const block_q8_K * const B; + float * const C; + const int64_t k; + const int64_t lda; + const int64_t ldb; + const int64_t ldc; + const int32_t ith; + const int32_t nth; +}; #endif #if defined(__ARM_FEATURE_DOTPROD) @@ -2705,8 +2981,6 @@ class tinyBLAS_Q0_PPC { int64_t n_aligned = 0; if (n % n_chunk == 0) { n_aligned = n; - } else if (n == 4) { - n_aligned = 4; } else if (n < n_chunk) { n_aligned = (n / 8) * 8; } else { @@ -4488,6 +4762,91 @@ bool llamafile_sgemm(const struct ggml_compute_params * params, int64_t m, int64 #endif } + case GGML_TYPE_Q2_K: { + if (Btype != GGML_TYPE_Q8_K) { + return false; + } +#if defined(__VXE__) || defined(__VXE2__) + tinyBLAS_QK_VXE tb{ + k, (const block_q2_K *)A, lda, + (const block_q8_K *)B, ldb, + (float *)C, ldc, + params->ith, params->nth}; + tb.matmul(m, n); + return true; +#else + return false; +#endif + } + + case GGML_TYPE_Q3_K: { + if (Btype != GGML_TYPE_Q8_K) { + return false; + } +#if defined(__VXE__) || defined(__VXE2__) + tinyBLAS_QK_VXE tb{ + k, (const block_q3_K *)A, lda, + (const block_q8_K *)B, ldb, + (float *)C, ldc, + params->ith, params->nth}; + tb.matmul(m, n); + return true; +#else + return false; +#endif + } + + case GGML_TYPE_Q4_K: { + if (Btype != GGML_TYPE_Q8_K) { + return false; + } +#if defined(__VXE__) || defined(__VXE2__) + tinyBLAS_QK_VXE tb{ + k, (const block_q4_K *)A, lda, + (const block_q8_K *)B, ldb, + (float *)C, ldc, + params->ith, params->nth}; + tb.matmul(m, n); + return true; +#else + return false; +#endif + } + + case GGML_TYPE_Q5_K: { + if (Btype != GGML_TYPE_Q8_K) { + return false; + } +#if defined(__VXE__) || defined(__VXE2__) + tinyBLAS_QK_VXE tb{ + k, (const block_q5_K *)A, lda, + (const block_q8_K *)B, ldb, + (float *)C, ldc, + params->ith, params->nth}; + tb.matmul(m, n); + return true; +#else + return false; +#endif + } + + case GGML_TYPE_Q6_K: { + if (Btype != GGML_TYPE_Q8_K) { + return false; + } +#if defined(__VXE__) || defined(__VXE2__) + tinyBLAS_QK_VXE tb{ + k, (const block_q6_K *)A, lda, + (const block_q8_K *)B, ldb, + (float *)C, ldc, + params->ith, params->nth}; + tb.matmul(m, n); + return true; +#else + return false; +#endif + } + case GGML_TYPE_IQ4_NL: { if (Btype != GGML_TYPE_Q8_0) return false; diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index 72efbc6e9fa9..f984f13a6c3c 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -2238,6 +2238,19 @@ void ggml_compute_forward_fill(const ggml_compute_params * params, ggml_tensor * } } +// ggml_compute_forward_sleep + +void ggml_compute_forward_sleep(const ggml_compute_params * params, ggml_tensor * dst) { + if (params->ith != 0) { + return; + } + + // same clock as ggml_time_us() callers; on macOS steady_clock is CLOCK_MONOTONIC_RAW, which can run faster + const int64_t t_end = ggml_time_us() + ggml_get_op_params_i32(dst, 0); + + while (ggml_time_us() < t_end) {} +} + // ggml_compute_tri template @@ -2885,6 +2898,118 @@ void ggml_compute_forward_silu_back( } } + +// ggml_compute_forward_sigmoid_back + +static void ggml_compute_forward_sigmoid_back_f32( + const ggml_compute_params * params, + ggml_tensor * dst) { + + const ggml_tensor * grad = dst->src[0]; + const ggml_tensor * src1 = dst->src[1]; + + GGML_ASSERT(ggml_is_contiguous_1(grad)); + GGML_ASSERT(ggml_is_contiguous_1(src1)); + GGML_ASSERT(ggml_is_contiguous_1(dst)); + GGML_ASSERT(ggml_are_same_shape(src1, dst)); + GGML_ASSERT(ggml_are_same_shape(src1, grad)); + + const int ith = params->ith; + const int nth = params->nth; + + const int nc = src1->ne[0]; + const int nr = ggml_nrows(src1); + + // rows per thread + const int dr = (nr + nth - 1)/nth; + + // row range for this thread + const int ir0 = dr*ith; + const int ir1 = MIN(ir0 + dr, nr); + + for (int i1 = ir0; i1 < ir1; i1++) { + ggml_vec_sigmoid_backward_f32(nc, + (float *) ((char *) dst->data + i1*( dst->nb[1])), + (float *) ((char *) src1->data + i1*(src1->nb[1])), + (float *) ((char *) grad->data + i1*(grad->nb[1]))); + +#ifndef NDEBUG + for (int k = 0; k < nc; k++) { + const float x = ((float *) ((char *) dst->data + i1*( dst->nb[1])))[k]; + GGML_UNUSED(x); + assert(!isnan(x)); + assert(!isinf(x)); + } +#endif // NDEBUG + } +} + +static void ggml_compute_forward_sigmoid_back_f16( + const ggml_compute_params * params, + ggml_tensor * dst) { + + const ggml_tensor * grad = dst->src[0]; + const ggml_tensor * src1 = dst->src[1]; + + GGML_ASSERT(ggml_is_contiguous_1(grad)); + GGML_ASSERT(ggml_is_contiguous_1(src1)); + GGML_ASSERT(ggml_is_contiguous_1(dst)); + GGML_ASSERT(ggml_are_same_shape(src1, dst)); + GGML_ASSERT(ggml_are_same_shape(src1, grad)); + + const int ith = params->ith; + const int nth = params->nth; + + const int nc = src1->ne[0]; + const int nr = ggml_nrows(src1); + + // rows per thread + const int dr = (nr + nth - 1)/nth; + + // row range for this thread + const int ir0 = dr*ith; + const int ir1 = MIN(ir0 + dr, nr); + + for (int i1 = ir0; i1 < ir1; i1++) { + ggml_vec_sigmoid_backward_f16(nc, + (ggml_fp16_t *) ((char *) dst->data + i1*( dst->nb[1])), + (ggml_fp16_t *) ((char *) src1->data + i1*(src1->nb[1])), + (ggml_fp16_t *) ((char *) grad->data + i1*(grad->nb[1]))); + +#ifndef NDEBUG + for (int k = 0; k < nc; k++) { + const float x = ((ggml_fp16_t *) ((char *) dst->data + i1*( dst->nb[1])))[k]; + const float v = GGML_CPU_FP16_TO_FP32(x); + GGML_UNUSED(v); + assert(!isnan(v)); + assert(!isinf(v)); + } +#endif // NDEBUG + } +} + +void ggml_compute_forward_sigmoid_back( + const ggml_compute_params * params, + ggml_tensor * dst) { + + const ggml_tensor * src0 = dst->src[0]; + + switch (src0->type) { + case GGML_TYPE_F32: + { + ggml_compute_forward_sigmoid_back_f32(params, dst); + } break; + case GGML_TYPE_F16: + { + ggml_compute_forward_sigmoid_back_f16(params, dst); + } break; + default: + { + GGML_ABORT("fatal error"); + } + } +} + // ggml_compute_forward_reglu // row loop shared by the BF16 GLU ops @@ -5518,7 +5643,7 @@ static void ggml_compute_forward_set_rows_impl( assert(ne0 == nc); assert(ne2 == ne02); assert(ne3 == ne03); - GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); + GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); assert(ne02 % ne11 == 0); assert(ne03 % ne12 == 0); @@ -5565,6 +5690,20 @@ static void ggml_compute_forward_set_rows_impl( from_float(wdata, ((char *) dst->data + i1*nb1 + i02*nb2 + i03*nb3), nc); } + } else if constexpr (std::is_same_v) { + if (dst->type == GGML_TYPE_BF16) { + memcpy( + ((char *) dst->data + i1*nb1 + i02*nb2 + i03*nb3), + ((char *) src0->data + i*nb01 + i02*nb02 + i03*nb03), + rs); + } else { + float * wdata = (float *) params->wdata + (nc + CACHE_LINE_SIZE_F32) * ith; + ggml_bf16_to_fp32_row( + (const ggml_bf16_t *) ((char *) src0->data + i*nb01 + i02*nb02 + i03*nb03), + wdata, nc); + from_float(wdata, + ((char *) dst->data + i1*nb1 + i02*nb2 + i03*nb3), nc); + } } else { GGML_ABORT("src0->type = %d (%s) not supported", src0->type, ggml_type_name(src0->type)); } @@ -5601,6 +5740,16 @@ void ggml_compute_forward_set_rows( GGML_ABORT("src1->type = %d (%s) not supported", src1->type, ggml_type_name(src1->type)); } } break; + case GGML_TYPE_BF16: + { + if (src1->type == GGML_TYPE_I64) { + ggml_compute_forward_set_rows_impl(params, dst); + } else if (src1->type == GGML_TYPE_I32) { + ggml_compute_forward_set_rows_impl(params, dst); + } else { + GGML_ABORT("src1->type = %d (%s) not supported", src1->type, ggml_type_name(src1->type)); + } + } break; default: { GGML_ABORT("src0->type = %d (%s) not supported", src0->type, ggml_type_name(src0->type)); @@ -6289,7 +6438,7 @@ static void rotate_pairs(const int64_t n, const int64_t n_offset, const float * } } -template //float or ggml_fp16_t +template //float, ggml_fp16_t or ggml_bf16_t static void ggml_compute_forward_rope_flt( const ggml_compute_params * params, ggml_tensor * dst, @@ -6299,7 +6448,7 @@ static void ggml_compute_forward_rope_flt( const ggml_tensor * src1 = dst->src[1]; const ggml_tensor * src2 = dst->src[2]; - GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); + GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); GGML_ASSERT(src1->type == GGML_TYPE_I32); float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow; @@ -6459,6 +6608,10 @@ void ggml_compute_forward_rope( { ggml_compute_forward_rope_flt(params, dst, true); } break; + case GGML_TYPE_BF16: + { + ggml_compute_forward_rope_flt(params, dst, true); + } break; case GGML_TYPE_F32: { ggml_compute_forward_rope_flt(params, dst, true); @@ -6483,6 +6636,10 @@ void ggml_compute_forward_rope_back( { ggml_compute_forward_rope_flt(params, dst, false); } break; + case GGML_TYPE_BF16: + { + ggml_compute_forward_rope_flt(params, dst, false); + } break; case GGML_TYPE_F32: { ggml_compute_forward_rope_flt(params, dst, false); diff --git a/ggml/src/ggml-cpu/ops.h b/ggml/src/ggml-cpu/ops.h index aac527a64c54..22017df7063d 100644 --- a/ggml/src/ggml-cpu/ops.h +++ b/ggml/src/ggml-cpu/ops.h @@ -41,6 +41,7 @@ void ggml_compute_forward_repeat(const struct ggml_compute_params * params, stru void ggml_compute_forward_repeat_back(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_concat(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_silu_back(const struct ggml_compute_params * params, struct ggml_tensor * dst); +void ggml_compute_forward_sigmoid_back(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_norm(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_rms_norm(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_rms_norm_mul_fused(const struct ggml_compute_params * params, struct ggml_tensor * dst_rms_norm, struct ggml_tensor * dst_mul); @@ -84,6 +85,7 @@ void ggml_compute_forward_top_k(const struct ggml_compute_params * params, struc void ggml_compute_forward_leaky_relu(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_tri(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_fill(const struct ggml_compute_params * params, struct ggml_tensor * dst); +void ggml_compute_forward_sleep(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_flash_attn_ext(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_flash_attn_back( const struct ggml_compute_params * params, diff --git a/ggml/src/ggml-cpu/vec.h b/ggml/src/ggml-cpu/vec.h index 4aac5e9666a7..0b8ac5d51e72 100644 --- a/ggml/src/ggml-cpu/vec.h +++ b/ggml/src/ggml-cpu/vec.h @@ -1536,6 +1536,29 @@ inline static void ggml_vec_silu_backward_f16(const int n, ggml_fp16_t * dx, con } } +inline static float ggml_sigmoid_backward_f32(float x, float dy) { + const float s = 1.0f/(1.0f + expf(-x)); + return dy*s*(1.0f - s); +} + +inline static ggml_fp16_t ggml_sigmoid_backward_f16(ggml_fp16_t x, ggml_fp16_t dy) { + const float v = GGML_CPU_FP16_TO_FP32(x); + const float s = 1.0f/(1.0f + expf(-v)); + return GGML_CPU_FP32_TO_FP16(GGML_CPU_FP16_TO_FP32(dy)*s*(1.0f - s)); +} + +inline static void ggml_vec_sigmoid_backward_f32(const int n, float * dx, const float * x, const float * dy) { + for (int i = 0; i < n; ++i) { + dx[i] = ggml_sigmoid_backward_f32(x[i], dy[i]); + } +} + +inline static void ggml_vec_sigmoid_backward_f16(const int n, ggml_fp16_t * dx, const ggml_fp16_t * x, const ggml_fp16_t * dy) { + for (int i = 0; i < n; ++i) { + dx[i] = ggml_sigmoid_backward_f16(x[i], dy[i]); + } +} + inline static void ggml_vec_reglu_f32 (const int n, float * y, const float * x, const float * g) { for (int i = 0; i < n; ++i) { y[i] = (x[i] > 0.f) ? x[i] * g[i] : 0.f; diff --git a/ggml/src/ggml-cuda/batch-get.cu b/ggml/src/ggml-cuda/batch-copy.cu similarity index 63% rename from ggml/src/ggml-cuda/batch-get.cu rename to ggml/src/ggml-cuda/batch-copy.cu index 3f2f6d7121c6..e064fcc09b5e 100644 --- a/ggml/src/ggml-cuda/batch-get.cu +++ b/ggml/src/ggml-cuda/batch-copy.cu @@ -1,18 +1,18 @@ -#include "batch-get.cuh" +#include "batch-copy.cuh" #include "common.cuh" #include "ggml-cpp.h" #include #if !defined(GGML_USE_MUSA) -struct ggml_cuda_batch_get_descriptor { +struct ggml_cuda_batch_copy_descriptor { const unsigned char * src; unsigned char * dst; size_t size; }; #if !defined(GGML_USE_HIP) -static __global__ void ggml_cuda_batch_get_kernel(const ggml_cuda_batch_get_descriptor * copies, size_t count) { +static __global__ void ggml_cuda_batch_copy_kernel(const ggml_cuda_batch_copy_descriptor * copies, size_t count) { // Blocks along y cooperate on each descriptor. const size_t index = blockIdx.x; if (index >= count) { @@ -52,11 +52,11 @@ static __global__ void ggml_cuda_batch_get_kernel(const ggml_cuda_batch_get_desc } #endif // !defined(GGML_USE_HIP) -struct ggml_cuda_batch_get_mapping { +struct ggml_cuda_batch_copy_mapping { void * host = nullptr; unsigned char * device = nullptr; - ggml_cuda_batch_get_mapping(void * host, size_t size) { + ggml_cuda_batch_copy_mapping(void * host, size_t size) { const cudaError_t err = cudaHostRegister(host, size, cudaHostRegisterMapped | cudaHostRegisterPortable); if (err != cudaSuccess) { (void) cudaGetLastError(); @@ -74,10 +74,10 @@ struct ggml_cuda_batch_get_mapping { #endif // !defined(GGML_USE_HIP) } - ggml_cuda_batch_get_mapping(const ggml_cuda_batch_get_mapping &) = delete; - ggml_cuda_batch_get_mapping & operator=(const ggml_cuda_batch_get_mapping &) = delete; + ggml_cuda_batch_copy_mapping(const ggml_cuda_batch_copy_mapping &) = delete; + ggml_cuda_batch_copy_mapping & operator=(const ggml_cuda_batch_copy_mapping &) = delete; - ~ggml_cuda_batch_get_mapping() { + ~ggml_cuda_batch_copy_mapping() { if (host) { // Release only the registration acquired by this object. CUDA_CHECK(cudaHostUnregister(host)); @@ -86,11 +86,12 @@ struct ggml_cuda_batch_get_mapping { }; #endif -bool ggml_cuda_get_tensor_n(int device, - const ggml_tensor * const * tensors, void * const * data, const size_t * offsets, +static bool ggml_cuda_copy_tensor_n(int device, cudaMemcpyKind direction, + const ggml_tensor * const * tensors, const void * const * data, const size_t * offsets, const size_t * sizes, size_t n_tensors) { #if defined(GGML_USE_MUSA) GGML_UNUSED(device); + GGML_UNUSED(direction); GGML_UNUSED(tensors); GGML_UNUSED(data); GGML_UNUSED(offsets); @@ -98,14 +99,17 @@ bool ggml_cuda_get_tensor_n(int device, GGML_UNUSED(n_tensors); return false; #else + const bool to_host = direction == cudaMemcpyDeviceToHost; // Provisional dispatch values based on experiments. constexpr size_t min_batch_reads = 128; - constexpr size_t max_gather_read_bytes = 128 * 1024; - // Collect non-empty CPU destination ranges. + constexpr size_t max_kernel_read_bytes = 128 * 1024; + // Collect destination ranges; repeated sources are allowed. std::vector> ranges; ranges.reserve(n_tensors); size_t payload_bytes = 0; - // Number of non-empty reads whose size is at most max_gather_read_bytes. + uintptr_t begin = UINTPTR_MAX; + uintptr_t end = 0; + // Number of non-empty reads whose size is at most max_kernel_read_bytes. size_t n_reads_small = 0; for (size_t i = 0; i < n_tensors; ++i) { if (sizes[i] == 0) { @@ -115,15 +119,19 @@ bool ggml_cuda_get_tensor_n(int device, GGML_ASSERT(address <= UINTPTR_MAX - sizes[i]); GGML_ASSERT(payload_bytes <= SIZE_MAX - sizes[i]); payload_bytes += sizes[i]; - n_reads_small += sizes[i] <= max_gather_read_bytes; - ranges.emplace_back(address, address + sizes[i]); + n_reads_small += sizes[i] <= max_kernel_read_bytes; + begin = std::min(begin, address); + end = std::max(end, address + sizes[i]); + const uintptr_t destination = to_host ? address : (uintptr_t) tensors[i]->data + offsets[i]; + GGML_ASSERT(destination <= UINTPTR_MAX - sizes[i]); + ranges.emplace_back(destination, destination + sizes[i]); } if (ranges.empty()) { return true; } // Total number of non-empty reads. const size_t n_reads = ranges.size(); - if (n_reads > SIZE_MAX / sizeof(ggml_cuda_batch_get_descriptor) || n_reads > INT_MAX) { + if (n_reads > SIZE_MAX / sizeof(ggml_cuda_batch_copy_descriptor) || n_reads > INT_MAX) { return false; } if (n_reads < 2 || (n_reads < min_batch_reads && n_reads_small == n_reads)) { @@ -131,84 +139,91 @@ bool ggml_cuda_get_tensor_n(int device, } std::sort(ranges.begin(), ranges.end()); for (size_t i = 1; i < ranges.size(); ++i) { - // Preserve the ordered copy path when CPU destinations overlap. + // Preserve the ordered copy path when destinations overlap. if (ranges[i].first < ranges[i - 1].second) { return false; } } - // Find the CPU span to register, including gaps between destinations. - const uintptr_t begin = ranges.front().first; - const uintptr_t end = ranges.back().second; - if (end - begin - payload_bytes > payload_bytes) { + // Limit gaps in the CPU span without underflow when sources overlap. + if (end - begin > payload_bytes && end - begin - payload_bytes > payload_bytes) { return false; } - // Register and map the existing CPU destination so the kernel can write to it directly. - ggml_cuda_batch_get_mapping mapping((void *) begin, end - begin); + // Register and map the CPU span for direct kernel access. + ggml_cuda_batch_copy_mapping mapping((void *) begin, end - begin); if (!mapping.host) { return false; } #if defined(GGML_USE_HIP) - // On HIP the reads use DMA only. Without the registration every copy to pageable memory maps its destination for the transfer. + // On HIP the copies use DMA only. Without the registration every copy to or from pageable memory maps it for the transfer. GGML_UNUSED(device); - const size_t n_reads_gather = 0; + const size_t n_reads_kernel = 0; #else - // Reads selected for gather; zero means all reads use DMA. - size_t n_reads_gather = mapping.device && n_reads_small >= min_batch_reads ? n_reads_small : 0; + // Reads selected for the kernel; zero means all reads use DMA. + size_t n_reads_kernel = mapping.device && n_reads_small >= min_batch_reads ? n_reads_small : 0; // Keep descriptor storage alive until the final stream synchronization. constexpr size_t max_batch_descriptors = 128 * 1024; - const size_t bytes = std::min(n_reads_gather, max_batch_descriptors) * sizeof(ggml_cuda_batch_get_descriptor); - ggml_backend_buffer_ptr descriptors(n_reads_gather ? ggml_backend_buft_alloc_buffer(ggml_backend_cuda_buffer_type(device), bytes) : nullptr); + const size_t bytes = std::min(n_reads_kernel, max_batch_descriptors) * sizeof(ggml_cuda_batch_copy_descriptor); + ggml_backend_buffer_ptr descriptors(n_reads_kernel ? ggml_backend_buft_alloc_buffer(ggml_backend_cuda_buffer_type(device), bytes) : nullptr); if (!descriptors) { - n_reads_gather = 0; + n_reads_kernel = 0; } const auto host_type = ggml_backend_cuda_host_buffer_type(); - ggml_backend_buffer_ptr host_descriptors(n_reads_gather ? ggml_backend_buft_alloc_buffer(host_type, bytes) : nullptr); + ggml_backend_buffer_ptr host_descriptors(n_reads_kernel ? ggml_backend_buft_alloc_buffer(host_type, bytes) : nullptr); if (!host_descriptors || ggml_backend_buffer_get_type(host_descriptors.get()) != host_type) { - n_reads_gather = 0; + n_reads_kernel = 0; } - if (n_reads_gather) { - auto * copies = static_cast(ggml_backend_buffer_get_base(host_descriptors.get())); - auto * device_copies = static_cast(ggml_backend_buffer_get_base(descriptors.get())); + if (n_reads_kernel) { + auto * copies = static_cast(ggml_backend_buffer_get_base(host_descriptors.get())); + auto * device_copies = static_cast(ggml_backend_buffer_get_base(descriptors.get())); const int threads = 256; const size_t nsm = ggml_cuda_info().devices[device].nsm; size_t i = 0; - for (size_t first = 0; first < n_reads_gather; first += max_batch_descriptors) { - const size_t n_batch = std::min(n_reads_gather - first, max_batch_descriptors); + for (size_t first = 0; first < n_reads_kernel; first += max_batch_descriptors) { + const size_t n_batch = std::min(n_reads_kernel - first, max_batch_descriptors); size_t count = 0; for (; i < n_tensors && count < n_batch; ++i) { - if (sizes[i] == 0 || sizes[i] > max_gather_read_bytes) { + if (sizes[i] == 0 || sizes[i] > max_kernel_read_bytes) { continue; } - copies[count++] = {(const unsigned char *) tensors[i]->data + offsets[i], - mapping.device + ((uintptr_t) data[i] - begin), sizes[i]}; + auto * host = mapping.device + ((uintptr_t) data[i] - begin); + auto * tensor = (unsigned char *) tensors[i]->data + offsets[i]; + copies[count++] = {to_host ? tensor : host, to_host ? host : tensor, sizes[i]}; } const size_t blocks_per_copy = std::min(UINT16_MAX, std::max(1, (nsm + n_batch - 1) / n_batch)); const dim3 blocks((unsigned int) n_batch, (unsigned int) blocks_per_copy); // Stream ordering keeps each kernel ahead of the next descriptor overwrite. CUDA_CHECK(cudaMemcpyAsync(device_copies, copies, n_batch * sizeof(copies[0]), cudaMemcpyHostToDevice, cudaStreamPerThread)); - ggml_cuda_batch_get_kernel<<>>(device_copies, n_batch); + ggml_cuda_batch_copy_kernel<<>>(device_copies, n_batch); CUDA_CHECK(cudaGetLastError()); - if (first + n_batch < n_reads_gather) { + if (first + n_batch < n_reads_kernel) { // Wait before refilling the pinned host descriptor buffer. CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread)); } } } #endif // defined(GGML_USE_HIP) - // Keep the destination pinned for DMA too; overlapping destinations already declined above. + // Keep the CPU span pinned for DMA too; overlapping destinations already declined above. for (size_t i = 0; i < n_tensors; ++i) { - if (sizes[i] && (!n_reads_gather || sizes[i] > max_gather_read_bytes)) { - CUDA_CHECK(cudaMemcpyAsync(data[i], (const char *) tensors[i]->data + offsets[i], sizes[i], cudaMemcpyDeviceToHost, cudaStreamPerThread)); + if (sizes[i] && (!n_reads_kernel || sizes[i] > max_kernel_read_bytes)) { + void * host = const_cast(data[i]); + void * tensor = (char *) tensors[i]->data + offsets[i]; + CUDA_CHECK(cudaMemcpyAsync(to_host ? host : tensor, to_host ? tensor : host, sizes[i], direction, cudaStreamPerThread)); } } - // Wait for GPU writes before releasing the CPU mapping and descriptor buffers. + // Wait for transfers before releasing the CPU mapping and descriptor buffers. CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread)); return true; #endif } +bool ggml_cuda_get_tensor_n(int device, + const ggml_tensor * const * tensors, void * const * data, const size_t * offsets, + const size_t * sizes, size_t n_tensors) { + return ggml_cuda_copy_tensor_n(device, cudaMemcpyDeviceToHost, tensors, data, offsets, sizes, n_tensors); +} + bool ggml_cuda_set_tensor_n(int device, - struct ggml_tensor * const * tensors, const void * const * data, const size_t * offsets, + ggml_tensor * const * tensors, const void * const * data, const size_t * offsets, const size_t * sizes, size_t n_tensors) { #if defined(GGML_USE_HIP) // On ROCm every copy from pageable memory maps its source for the transfer, which costs more than the copy for many @@ -237,7 +252,7 @@ bool ggml_cuda_set_tensor_n(int device, } // the registration is released when the mapping goes out of scope, after the stream is synchronized - ggml_cuda_batch_get_mapping mapping((void *) begin, end - begin); + ggml_cuda_batch_copy_mapping mapping((void *) begin, end - begin); if (!mapping.host) { return false; } @@ -250,12 +265,6 @@ bool ggml_cuda_set_tensor_n(int device, CUDA_CHECK(cudaStreamSynchronize(cudaStreamPerThread)); return true; #else - GGML_UNUSED(device); - GGML_UNUSED(tensors); - GGML_UNUSED(data); - GGML_UNUSED(offsets); - GGML_UNUSED(sizes); - GGML_UNUSED(n_tensors); - return false; + return ggml_cuda_copy_tensor_n(device, cudaMemcpyHostToDevice, tensors, data, offsets, sizes, n_tensors); #endif } diff --git a/ggml/src/ggml-cuda/batch-get.cuh b/ggml/src/ggml-cuda/batch-copy.cuh similarity index 59% rename from ggml/src/ggml-cuda/batch-get.cuh rename to ggml/src/ggml-cuda/batch-copy.cuh index 5cba9b6e506b..bb7fca4c02dd 100644 --- a/ggml/src/ggml-cuda/batch-get.cuh +++ b/ggml/src/ggml-cuda/batch-copy.cuh @@ -6,8 +6,6 @@ bool ggml_cuda_get_tensor_n(int device, const ggml_tensor * const * tensors, void * const * data, const size_t * offsets, const size_t * sizes, size_t n_tensors); -// Writes a batch of tensor ranges from host memory, returns false if the caller has to copy them one by one. bool ggml_cuda_set_tensor_n(int device, - struct ggml_tensor * const * tensors, const void * const * data, const size_t * offsets, + ggml_tensor * const * tensors, const void * const * data, const size_t * offsets, const size_t * sizes, size_t n_tensors); - diff --git a/ggml/src/ggml-cuda/common.cuh b/ggml/src/ggml-cuda/common.cuh index 6aeaa888d25e..5be8cdd06b9b 100644 --- a/ggml/src/ggml-cuda/common.cuh +++ b/ggml/src/ggml-cuda/common.cuh @@ -457,6 +457,16 @@ static __device__ __forceinline__ ggml_cuda_thread_mask_t ggml_cuda_ballot(int p return __ballot_sync(mask, predicate); } +static __device__ __forceinline__ int ggml_cuda_popc(ggml_cuda_thread_mask_t x) { + static_assert(sizeof(ggml_cuda_thread_mask_t) == 4 || sizeof(ggml_cuda_thread_mask_t) == 8, "unsupported thread mask type"); + if constexpr (sizeof(ggml_cuda_thread_mask_t) == 4) { + return __popc(x); + } else { + return __popcll(x); + } +} +template static __device__ __forceinline__ int ggml_cuda_popc(T x) = delete; // Makes implicit type casts result in an error. + static __device__ __forceinline__ int ggml_cuda_all(int predicate, ggml_cuda_thread_mask_t mask = GGML_CUDA_FULL_THREAD_MASK) { return __all_sync(mask, predicate); } @@ -906,7 +916,7 @@ static __device__ __forceinline__ float ggml_cuda_ue4m3_to_fp32(uint8_t x) { // but CDNA3 supports only e4m3_fnuz (no inf). const uint32_t bits = x * (x != 0x7F && x != 0xFF); // Convert NaN to 0.0f to match CPU implementation. const __hip_fp8_e4m3_fnuz xf = *reinterpret_cast(&bits); - return static_cast(xf) / 2; + return static_cast(xf); #else #if defined(FP8_AVAILABLE) && !defined(GGML_USE_HIP) const uint32_t bits = x * (x != 0x7F && x != 0xFF); // Convert NaN to 0.0f to match CPU implementation. @@ -1041,6 +1051,12 @@ static const uint3 init_fastdiv_values(uint64_t d_64) { uint32_t L = 0; while (L < 32 && (uint32_t{ 1 } << L) < d) { L++; + if (L == 32) { + // Shifting uint32_t by 32 to the right is undefined behavior. + // On NVIDIA it will produce 0. + // On AMD the value by which is shifted is masked with & 31 so it is shifting by 0 bits. + GGML_ABORT("undefined behavior in fastdiv"); + } } uint32_t mp = (uint32_t) ((uint64_t{ 1 } << 32) * ((uint64_t{ 1 } << L) - d) / d + 1); diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index b27fb6f4cf8c..cd9648341d82 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -17,15 +17,6 @@ static __global__ void flash_attn_mask_to_sparse_indices( constexpr int warp_size = ggml_cuda_get_physical_warp_size(); constexpr int values_per_lane = 8; - using lane_mask_t = std::conditional_t; - constexpr uint64_t ballot_mask = ~(lane_mask_t)0; - const auto popc = [](const lane_mask_t mask) { - if constexpr (warp_size == 64) { - return __popcll(mask); - } else { - return __popc(mask); - } - }; const int tid = threadIdx.x; const int warp = tid / warp_size; const int lane = tid % warp_size; @@ -48,7 +39,7 @@ static __global__ void flash_attn_mask_to_sparse_indices( __syncthreads(); for (int i0 = 0; i0 < ne30; i0 += blockDim.x*values_per_lane) { - lane_mask_t selected_warp[values_per_lane]; + ggml_cuda_thread_mask_t selected_warp[values_per_lane]; int warp_count = 0; #pragma unroll for (int item = 0; item < values_per_lane; ++item) { @@ -60,8 +51,8 @@ static __global__ void flash_attn_mask_to_sparse_indices( selected |= (!oob || q < q1 - q0) && isfinite(__half2float(mask[q*s31 + i])); } } - selected_warp[item] = (lane_mask_t)ggml_cuda_ballot((int) selected, ballot_mask); - warp_count += popc(selected_warp[item]); + selected_warp[item] = ggml_cuda_ballot((int) selected); + warp_count += ggml_cuda_popc(selected_warp[item]); } if (lane == 0) { @@ -81,16 +72,16 @@ static __global__ void flash_attn_mask_to_sparse_indices( } __syncthreads(); - const lane_mask_t lane_mask = lane == 0 ? 0 : ((lane_mask_t)1 << lane) - 1; + const ggml_cuda_thread_mask_t lane_mask = lane == 0 ? 0 : ((ggml_cuda_thread_mask_t)1 << lane) - 1; int warp_item_offset = 0; #pragma unroll for (int item = 0; item < values_per_lane; ++item) { const int i = i0 + (warp*values_per_lane + item)*warp_size + lane; - const int dst = row_count + warp_offsets[warp] + warp_item_offset + popc(selected_warp[item] & lane_mask); - if ((selected_warp[item] & ((lane_mask_t)1 << lane)) && dst < n_kv_max) { + const int dst = row_count + warp_offsets[warp] + warp_item_offset + ggml_cuda_popc(selected_warp[item] & lane_mask); + if ((selected_warp[item] & ((ggml_cuda_thread_mask_t)1 << lane)) && dst < n_kv_max) { indices[dst] = i; } - warp_item_offset += popc(selected_warp[item]); + warp_item_offset += ggml_cuda_popc(selected_warp[item]); } __syncthreads(); diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index badfb14990df..98dace11aacf 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -10,7 +10,7 @@ #include "ggml-cuda/arange.cuh" #include "ggml-cuda/argmax.cuh" #include "ggml-cuda/argsort.cuh" -#include "ggml-cuda/batch-get.cuh" +#include "ggml-cuda/batch-copy.cuh" #include "ggml-cuda/binbcast.cuh" #include "ggml-cuda/clamp.cuh" #include "ggml-cuda/col2im-1d.cuh" @@ -48,6 +48,7 @@ #include "ggml-cuda/rope.cuh" #include "ggml-cuda/roll.cuh" #include "ggml-cuda/scale.cuh" +#include "ggml-cuda/sleep.cuh" #include "ggml-cuda/snake.cuh" #include "ggml-cuda/softcap.cuh" #include "ggml-cuda/softmax.cuh" @@ -2905,7 +2906,8 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * ids_from_sorted_host[i12*n_expert_used + iex] = ids_to_sorted_host.size(); ids_to_sorted_host.push_back(i12*ne11 + iex % ne11); tokens_per_expert[i02]++; - break; + // TODO: removing the break here was done to make duplicate IDs work but this caused a ~10% performance regression, better solution needed. + // break; } } } @@ -2957,6 +2959,7 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * ggml_tensor dst_slice; memset(&dst_slice, 0, sizeof(dst_slice)); memcpy(dst_slice.op_params, dst->op_params, sizeof(dst_slice.op_params)); + dst_slice.op = GGML_OP_MUL_MAT; // ggml_prec_get_acc/ggml_prec_get_src check the op dst_slice.buffer = dst->buffer; dst_slice.type = type_dst_sorted; dst_slice.ne[0] = ne0; @@ -3326,6 +3329,9 @@ static bool ggml_cuda_compute_forward(ggml_backend_cuda_context & ctx, struct gg case GGML_OP_FILL: ggml_cuda_op_fill(ctx, dst); break; + case GGML_OP_SLEEP: + ggml_cuda_op_sleep(ctx, dst); + break; case GGML_OP_LIGHTNING_INDEXER: ggml_cuda_lightning_indexer(ctx, dst); break; @@ -3676,7 +3682,12 @@ static bool ggml_cuda_should_fuse_rope_set_rows(const ggml_tensor * rope, return false; } - if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16) { + if (set_rows->type != GGML_TYPE_F32 && set_rows->type != GGML_TYPE_F16 && set_rows->type != GGML_TYPE_BF16) { + return false; + } + + // BF16 rope fuses into an F16 or BF16 cache, other ropes not into a BF16 cache + if (rope->type == GGML_TYPE_BF16 ? set_rows->type == GGML_TYPE_F32 : set_rows->type == GGML_TYPE_BF16) { return false; } @@ -7097,7 +7108,7 @@ static bool ggml_backend_cuda_device_supports_op(ggml_backend_dev_t dev, const g (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_BF16 || op->type == GGML_TYPE_F8_E4M3 || op->type == GGML_TYPE_Q4_0 || op->type == GGML_TYPE_Q4_1 || op->type == GGML_TYPE_Q5_0 || op->type == GGML_TYPE_Q5_1 || op->type == GGML_TYPE_Q8_0 || op->type == GGML_TYPE_IQ4_NL) && - op->src[0]->type == GGML_TYPE_F32 + (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_BF16) ) || ( op->type == GGML_TYPE_F16 && op->src[0]->type == GGML_TYPE_F16 ) @@ -7318,7 +7329,9 @@ static bool ggml_backend_cuda_device_supports_op(ggml_backend_dev_t dev, const g return false; case GGML_OP_ROPE: case GGML_OP_ROPE_BACK: { - return op->src[0]->nb[0] == ggml_type_size(op->src[0]->type) && ggml_is_contiguous_2(op->src[0]); + return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_BF16) && + op->type == op->src[0]->type && + op->src[0]->nb[0] == ggml_type_size(op->src[0]->type) && ggml_is_contiguous_2(op->src[0]); } case GGML_OP_IM2COL: case GGML_OP_IM2COL_3D: @@ -7376,7 +7389,7 @@ static bool ggml_backend_cuda_device_supports_op(ggml_backend_dev_t dev, const g case GGML_OP_RWKV_WKV7: return true; case GGML_OP_GATED_DELTA_NET: - return true; + return ggml_are_same_stride(op->src[0], op->src[1]); case GGML_OP_DSV4_HC_COMB: return op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->src[2]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32; @@ -7405,6 +7418,12 @@ static bool ggml_backend_cuda_device_supports_op(ggml_backend_dev_t dev, const g return ggml_cuda_lightning_indexer_supported(dev_ctx->device, op); case GGML_OP_TOP_K_MASK: return op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_F32; + case GGML_OP_SLEEP: +#if defined(GGML_USE_HIP) || defined(GGML_USE_MUSA) + return false; +#else + return true; +#endif // defined(GGML_USE_HIP) || defined(GGML_USE_MUSA) default: return false; diff --git a/ggml/src/ggml-cuda/mmf.cu b/ggml/src/ggml-cuda/mmf.cu index 040d390e0cc5..396ad1c1184d 100644 --- a/ggml/src/ggml-cuda/mmf.cu +++ b/ggml/src/ggml-cuda/mmf.cu @@ -43,7 +43,6 @@ void ggml_cuda_mul_mat_f(ggml_backend_cuda_context & ctx, const ggml_tensor * sr const int64_t s13 = src1->nb[3] / ts_src1; const int64_t s3 = dst->nb[3] / ts_dst; - const int64_t ids_s0 = ids ? ids->nb[0] / ggml_type_size(ids->type) : 0; const int64_t ids_s1 = ids ? ids->nb[1] / ggml_type_size(ids->type) : 0; mmf_ids_data ids_info{}; @@ -70,7 +69,7 @@ void ggml_cuda_mul_mat_f(ggml_backend_cuda_context & ctx, const ggml_tensor * sr nchannels_y = ids->ne[0]; } - if (ids && ncols_dst > 16) { + if (ids) { const int64_t n_expert_used = ids->ne[0]; const int64_t n_experts = ne02; const int64_t n_tokens = ne12; @@ -110,7 +109,7 @@ void ggml_cuda_mul_mat_f(ggml_backend_cuda_context & ctx, const ggml_tensor * sr constexpr int vals_per_T = 1; mul_mat_f_switch_rows_per_block( rows_per_block, src0_d, src1_d, ids_d, dst_d, ne00/vals_per_T, ne01, ncols_dst, s01/vals_per_T, stride_col_y/vals_per_T, stride_col_dst, - ids_s0, ids_s1, ne02, nchannels_y, nchannels_dst, s02/vals_per_T, stride_channel_y, stride_channel_dst, + ne02, nchannels_y, nchannels_dst, s02/vals_per_T, stride_channel_y, stride_channel_dst, ne03, ne3, s03/vals_per_T, s13, s3, ctx.stream(), ids_info_ptr); } break; case GGML_TYPE_F16: { @@ -118,7 +117,7 @@ void ggml_cuda_mul_mat_f(ggml_backend_cuda_context & ctx, const ggml_tensor * sr constexpr int vals_per_T = 2; mul_mat_f_switch_rows_per_block( rows_per_block, src0_d, src1_d, ids_d, dst_d, ne00/vals_per_T, ne01, ncols_dst, s01/vals_per_T, stride_col_y/vals_per_T, stride_col_dst, - ids_s0, ids_s1, ne02, nchannels_y, nchannels_dst, s02/vals_per_T, stride_channel_y, stride_channel_dst, + ne02, nchannels_y, nchannels_dst, s02/vals_per_T, stride_channel_y, stride_channel_dst, ne03, ne3, s03/vals_per_T, s13, s3, ctx.stream(), ids_info_ptr); } break; case GGML_TYPE_BF16: { @@ -126,7 +125,7 @@ void ggml_cuda_mul_mat_f(ggml_backend_cuda_context & ctx, const ggml_tensor * sr constexpr int vals_per_T = 2; mul_mat_f_switch_rows_per_block( rows_per_block, src0_d, src1_d, ids_d, dst_d, ne00/vals_per_T, ne01, ncols_dst, s01/vals_per_T, stride_col_y/vals_per_T, stride_col_dst, - ids_s0, ids_s1, ne02, nchannels_y, nchannels_dst, s02/vals_per_T, stride_channel_y, stride_channel_dst, + ne02, nchannels_y, nchannels_dst, s02/vals_per_T, stride_channel_y, stride_channel_dst, ne03, ne3, s03/vals_per_T, s13, s3, ctx.stream(), ids_info_ptr); } break; default: diff --git a/ggml/src/ggml-cuda/mmf.cuh b/ggml/src/ggml-cuda/mmf.cuh index c49f6c47ad1d..46a123a5c3c1 100644 --- a/ggml/src/ggml-cuda/mmf.cuh +++ b/ggml/src/ggml-cuda/mmf.cuh @@ -47,12 +47,11 @@ void ggml_cuda_mul_mat_f(ggml_backend_cuda_context & ctx, const ggml_tensor * sr bool ggml_cuda_should_use_mmf(enum ggml_type type, int cc, int warp_size, const int64_t * scr0_ne, const size_t * src0_nb, const int src1_ncols, bool mul_mat_id); -template +template __launch_bounds__(ggml_cuda_get_physical_warp_size()*nwarps, 1) static __global__ void mul_mat_f( - const T * __restrict__ x, const float * __restrict__ y, const int32_t * __restrict__ ids, float * __restrict__ dst, - const int ncols, const int ncols_dst_total, const int nchannels_dst, const int stride_row, const int stride_col_y, const int stride_col_dst, - const int stride_col_id, const int stride_row_id, + const T * __restrict__ x, const float * __restrict__ y, float * __restrict__ dst, + const int ncols, const int stride_row, const int stride_col_y, const int stride_col_dst, const int channel_ratio, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst, const int sample_ratio, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst) { // TODO: handle this in a consistent and simpler way after AMD MFMA support has been added @@ -90,85 +89,26 @@ static __global__ void mul_mat_f( constexpr int ntA = rows_per_block / tile_A::I; constexpr int ntB = (cols_per_block + tile_B::I - 1) / tile_B::I; - const int row0 = blockIdx.x * rows_per_block; - - int expert_idx = 0; - [[maybe_unused]] int col_base = 0; - - const int channel_dst = has_ids ? 0 : blockIdx.y; - - if constexpr (has_ids) { - // experts + tiles of ncols_dst are packed in the y dimension - int col_tiles = (ncols_dst_total + cols_per_block - 1) / cols_per_block; - const int nchannels_x = gridDim.y / col_tiles; - const int tile_idx = blockIdx.y / nchannels_x; - expert_idx = blockIdx.y - tile_idx * nchannels_x; - col_base = tile_idx * cols_per_block; - } + const int row0 = blockIdx.x * rows_per_block; - const int channel_x = has_ids ? expert_idx : (channel_dst / channel_ratio); + const int channel_dst = blockIdx.y; + const int channel_x = channel_dst / channel_ratio; const int channel_y = channel_dst; const int sample_dst = blockIdx.z; const int sample_x = sample_dst / sample_ratio; const int sample_y = sample_dst; x += int64_t(sample_x) *stride_sample_x + channel_x *stride_channel_x + row0*stride_row ; - y += int64_t(sample_y) *stride_sample_y + (has_ids ? 0 : channel_y *stride_channel_y); - dst += int64_t(sample_dst)*stride_sample_dst + (has_ids ? 0 : channel_dst*stride_channel_dst); - - if constexpr (has_ids) { - constexpr int y_stride_scale = std::is_same_v ? 1 : 2; - const int64_t col_offset = col_base; - y += col_offset * stride_col_y * y_stride_scale; - dst += col_offset * stride_col_dst; - ids += col_offset * stride_row_id; - } + y += int64_t(sample_y) *stride_sample_y + channel_y *stride_channel_y; + dst += int64_t(sample_dst)*stride_sample_dst + channel_dst*stride_channel_dst; [[maybe_unused]] const float2 * y2 = (const float2 *) y; extern __shared__ char data_mmv[]; - char * shmem_base = data_mmv; - [[maybe_unused]] int * slot_map = (int *) shmem_base; - char * compute_base = has_ids ? (shmem_base + GGML_PAD(cols_per_block, 16) * sizeof(int)) : shmem_base; - tile_C C[ntA][ntB]; - T * tile_xy = (T *) compute_base + threadIdx.y*(tile_A::I * tile_k_padded); - - if constexpr (has_ids) { - int found = 0; - - for (int j0 = 0; j0 < cols_per_block; j0 += nwarps) { - const int j = j0 + threadIdx.y; - - if (threadIdx.x == 0) { - slot_map[j] = -1; - } - ggml_cuda_syncwarp(); - - if (col_base + j >= ncols_dst_total) { - continue; - } - - const int32_t * __restrict__ id_row = ids + j*stride_row_id; - - for (int k = threadIdx.x; k < nchannels_dst; k += warp_size) { - int match = id_row[k*stride_col_id] == expert_idx; - - if (match) { - slot_map[j] = k; - found = 1; - break; - } - } - } - - if (!__syncthreads_or(found)) { - return; - } - } - + T * tile_xy = (T *) data_mmv + threadIdx.y*(tile_A::I * tile_k_padded); for (int col = threadIdx.y*warp_size + threadIdx.x; col < ncols; col += nwarps*warp_size) { tile_A A[ntA][warp_size / tile_A::J]; @@ -194,26 +134,15 @@ static __global__ void mul_mat_f( for (int j0 = 0; j0 < tile_B::I; ++j0) { const int j = j0 + itB*tile_B::I; - if constexpr (!has_ids) { - tile_xy[j0*tile_k_padded + threadIdx.x] = j < cols_per_block ? y[j*stride_col_y + col] : 0.0f; - } else { - const bool valid = j < cols_per_block && (col_base + j) < ncols_dst_total && slot_map[j] >= 0; - tile_xy[j0*tile_k_padded + threadIdx.x] = valid ? y[slot_map[j]*stride_channel_y + j*stride_col_y + col] : 0.0f; - } + tile_xy[j0*tile_k_padded + threadIdx.x] = j < cols_per_block ? y[j*stride_col_y + col] : 0.0f; } } else if constexpr (std::is_same_v || std::is_same_v) { #pragma unroll for (int j0 = 0; j0 < tile_B::I; ++j0) { const int j = j0 + itB*tile_B::I; - if constexpr (!has_ids) { - const float2 tmp = j < cols_per_block ? y2[j*stride_col_y + col] : make_float2(0.0f, 0.0f); - tile_xy[j0*tile_k_padded + threadIdx.x] = ggml_cuda_cast(tmp); - } else { - const bool valid = j < cols_per_block && (col_base + j) < ncols_dst_total && slot_map[j] >= 0; - float2 tmp = valid ? *(const float2*) &y[slot_map[j]*stride_channel_y + 2*(j*stride_col_y + col)] : make_float2(0.0f, 0.0f); - tile_xy[j0*tile_k_padded + threadIdx.x] = ggml_cuda_cast(tmp); - } + const float2 tmp = j < cols_per_block ? y2[j*stride_col_y + col] : make_float2(0.0f, 0.0f); + tile_xy[j0*tile_k_padded + threadIdx.x] = ggml_cuda_cast(tmp); } } else { static_assert(std::is_same_v, "unsupported type"); @@ -231,7 +160,7 @@ static __global__ void mul_mat_f( } } - float * buf_iw = (float *) compute_base; + float * buf_iw = (float *) data_mmv; constexpr int kiw = nwarps*rows_per_block + mmf_get_padding(); if (nwarps > 1) { @@ -278,26 +207,15 @@ static __global__ void mul_mat_f( } } - if constexpr (!has_ids) { #pragma unroll - for (int i0 = 0; i0 < sizeof(sum)/sizeof(sum[0]); ++i0) { - dst[j*stride_col_dst + row0 + i0*warp_size + threadIdx.x] = sum[i0]; - } - } else { - const int slot = (j < cols_per_block) ? slot_map[j] : -1; - if (slot >= 0 && (col_base + j) < ncols_dst_total) { -#pragma unroll - for (int i0 = 0; i0 < sizeof(sum)/sizeof(sum[0]); ++i0) { - dst[slot*stride_channel_dst + j*stride_col_dst + row0 + i0*warp_size + threadIdx.x] = sum[i0]; - } - } + for (int i0 = 0; i0 < sizeof(sum)/sizeof(sum[0]); ++i0) { + dst[j*stride_col_dst + row0 + i0*warp_size + threadIdx.x] = sum[i0]; } } } #else - GGML_UNUSED_VARS(x, y, ids, dst, - ncols, ncols_dst_total, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, + GGML_UNUSED_VARS(x, y, dst, + ncols, stride_row, stride_col_y, stride_col_dst, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst); NO_DEVICE_CODE; @@ -588,22 +506,21 @@ static __global__ void mul_mat_f_ids( template static inline void mul_mat_f_switch_ids( - const T * x, const float * y, const int32_t * ids, float * dst, + const T * x, const float * y, float * dst, const int64_t ncols_x, const int64_t ncols_dst, const int64_t nchannels_dst, const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst, - const int64_t stride_col_id, const int64_t stride_row_id, const int64_t channel_ratio, const int64_t stride_channel_x, const int64_t stride_channel_y, const int64_t stride_channel_dst, const int64_t sample_ratio, const int64_t stride_sample_x, const int64_t stride_sample_y, const int64_t stride_sample_dst, const dim3 & block_nums, const dim3 & block_dims, const int nbytes_shared_total, cudaStream_t stream, const mmf_ids_data * ids_data) { + const bool has_ids_data = ids_data && ids_data->ids_src_compact; - // Use the compact-ids kernel only for larger tiles; for small ncols_dst (< 16) - // we prefer the normal mul_mat_f path with has_ids=true. - if (has_ids_data && ncols_dst > 16) { + if (has_ids_data) { if (ids_data->max_tiles == 0) { return; } + GGML_ASSERT(block_nums.z == 1); dim3 block_nums_ids(block_nums.x, ids_data->max_tiles, 1); const uint3 sis1_fd = ids_data->sis1 > 0 ? init_fastdiv_values((uint32_t) ids_data->sis1) : make_uint3(0, 0, 1); @@ -615,19 +532,10 @@ static inline void mul_mat_f_switch_ids( channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, sis1_fd, nch_fd); - } else if (ids) { - const int64_t col_tiles = (ncols_dst + cols_per_block - 1) / cols_per_block; - dim3 block_nums_ids = block_nums; - block_nums_ids.y *= col_tiles; - - mul_mat_f<<>> - (x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst); } else { - mul_mat_f<<>> - (x, y, ids, dst, ncols_x, cols_per_block, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, + mul_mat_f<<>> + (x, y, dst, ncols_x, stride_row, stride_col_y, stride_col_dst, + channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst); } } @@ -637,7 +545,6 @@ void mul_mat_f_cuda( const T * x, const float * y, const int32_t * ids, float * dst, const int64_t ncols_x, const int64_t nrows_x, const int64_t ncols_dst, const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst, - const int64_t stride_col_id, const int64_t stride_row_id, const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst, const int64_t stride_channel_x, const int64_t stride_channel_y, const int64_t stride_channel_dst, const int64_t nsamples_x, const int64_t nsamples_dst, const int64_t stride_sample_x, const int64_t stride_sample_y, const int64_t stride_sample_dst, @@ -673,70 +580,59 @@ void mul_mat_f_cuda( const int nbytes_shared_iter = nwarps_best * (volta_mma_available(cc) ? tile_A_32::I : tile_A_16::I) * (warp_size + mmf_get_padding(cc)) * 4; const int nbytes_cols_per_block_pad = (amd_wmma_available(cc) || amd_mfma_available(cc)) ? tile_B_16::I : tile_B_8::I; const int nbytes_shared_combine = GGML_PAD(cols_per_block, nbytes_cols_per_block_pad) * (nwarps_best*rows_per_block + mmf_get_padding(cc)) * 4; - const int nbytes_shared = std::max(nbytes_shared_iter, nbytes_shared_combine); - const int nbytes_slotmap = ids ? GGML_PAD(cols_per_block, 16) * sizeof(int) : 0; - const int nbytes_shared_total = nbytes_shared + nbytes_slotmap; - const int64_t grid_y = ids ? nchannels_x : nchannels_dst; + const int nbytes_shared_total = std::max(nbytes_shared_iter, nbytes_shared_combine); - const dim3 block_nums(nrows_x/rows_per_block, grid_y, nsamples_dst); + const dim3 block_nums(nrows_x/rows_per_block, nchannels_dst, nsamples_dst); const dim3 block_dims(warp_size, nwarps_best, 1); switch (nwarps_best) { case 1: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 2: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 3: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 4: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 5: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 6: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 7: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; case 8: { mul_mat_f_switch_ids( - x, y, ids, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, channel_ratio, stride_channel_x, stride_channel_y, stride_channel_dst, - sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, block_nums, block_dims, nbytes_shared_total, stream, - ids_data); + x, y, dst, ncols_x, ncols_dst, nchannels_dst, stride_row, stride_col_y, stride_col_dst, channel_ratio, + stride_channel_x, stride_channel_y, stride_channel_dst, sample_ratio, stride_sample_x, stride_sample_y, stride_sample_dst, + block_nums, block_dims, nbytes_shared_total, stream, ids_data); } break; default: GGML_ABORT("fatal error"); @@ -750,95 +646,94 @@ static void mul_mat_f_switch_cols_per_block( const T * x, const float * y, const int32_t * ids, float * dst, const int64_t ncols_x, const int64_t nrows_x, const int64_t ncols_dst, const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst, - const int64_t stride_col_id, const int stride_row_id, const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst, const int64_t stride_channel_x, const int64_t stride_channel_y, const int64_t stride_channel_dst, const int64_t nsamples_x, const int64_t nsamples_dst, const int64_t stride_sample_x, const int64_t stride_sample_y, const int64_t stride_sample_dst, cudaStream_t stream, const mmf_ids_data * ids_data) { - const int ncols_case = (ids && ncols_dst > 16) ? 16 : ncols_dst; + const int ncols_case = ids ? 16 : ncols_dst; GGML_ASSERT(ids || ncols_dst <= 16); switch (ncols_case) { case 1: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 2: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 3: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 4: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 5: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 6: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 7: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 8: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 9: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 10: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 11: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 12: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 13: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 14: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 15: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case 16: { mul_mat_f_cuda(x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; default: @@ -851,7 +746,6 @@ static void mul_mat_f_switch_rows_per_block( const int rows_per_block, const T * x, const float * y, const int32_t * ids, float * dst, const int64_t ncols_x, const int64_t nrows_x, const int64_t ncols_dst, const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst, - const int64_t stride_col_id, const int stride_row_id, const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst, const int64_t stride_channel_x, const int64_t stride_channel_y, const int64_t stride_channel_dst, const int64_t nsamples_x, const int64_t nsamples_dst, const int64_t stride_sample_x, const int64_t stride_sample_y, const int64_t stride_sample_dst, @@ -860,13 +754,13 @@ static void mul_mat_f_switch_rows_per_block( case MMF_ROWS_PER_BLOCK: { mul_mat_f_switch_cols_per_block( x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; case MMF_ROWS_PER_BLOCK_CDNA: { mul_mat_f_switch_cols_per_block( x, y, ids, dst, ncols_x, nrows_x, ncols_dst, stride_row, stride_col_y, stride_col_dst, - stride_col_id, stride_row_id, nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, + nchannels_x, nchannels_y, nchannels_dst, stride_channel_x, stride_channel_y, stride_channel_dst, nsamples_x, nsamples_dst, stride_sample_x, stride_sample_y, stride_sample_dst, stream, ids_data); } break; default: @@ -878,7 +772,6 @@ static void mul_mat_f_switch_rows_per_block( template void mul_mat_f_cuda( \ const T * x, const float * y, const int32_t * ids, float * dst, \ const int64_t ncols_x, const int64_t nrows_x, int64_t ncols_dst_total, const int64_t stride_row, const int64_t stride_col_y, const int64_t stride_col_dst, \ - const int64_t stride_col_id, const int64_t stride_row_id, \ const int64_t nchannels_x, const int64_t nchannels_y, const int64_t nchannels_dst, \ const int64_t stride_channel_x, const int64_t stride_channel_y, const int64_t stride_channel_dst, const int64_t nsamples_x,\ const int64_t nsamples_dst, const int64_t stride_sample_x, const int64_t stride_sample_y, const int64_t stride_sample_dst, \ diff --git a/ggml/src/ggml-cuda/mmid.cu b/ggml/src/ggml-cuda/mmid.cu index 6b425a377244..fe9458763e13 100644 --- a/ggml/src/ggml-cuda/mmid.cu +++ b/ggml/src/ggml-cuda/mmid.cu @@ -24,6 +24,50 @@ template struct mm_ids_pow2 { static constexpr int value = 2*mm_ids_pow2 template <> struct mm_ids_pow2<1> { static constexpr int value = 1; }; template <> struct mm_ids_pow2<0> { static constexpr int value = 1; }; +template +static __device__ __forceinline__ void check_experts( + mm_ids_helper_store * store, int & nex_prev, int & it_compact, + const int expert, const int it, const int iex, const int expert_found) { + if (increment_nex_prev) { + nex_prev += expert_found < expert; + } + + if (write_to_store) { + const ggml_cuda_thread_mask_t iex_used = ggml_cuda_ballot(expert_found == expert); + const ggml_cuda_thread_mask_t mask = (ggml_cuda_thread_mask_t(1) << threadIdx.x) - 1; + const int it_compact_offset = ggml_cuda_popc(iex_used & mask); + + if (expert_found == expert) { + store[it_compact + it_compact_offset] = mm_ids_helper_store(it, iex); + } + + it_compact += ggml_cuda_popc(iex_used); + } +} + +static __device__ __forceinline__ void dump_store( + int32_t * __restrict__ ids_src1, int32_t * __restrict__ ids_dst, + const int n_expert_used, const int nchannels_y, const int sis1, const bool write_inverse, + const mm_ids_helper_store * __restrict__ store, const int nex_prev, int & n_dumped, const int it_compact) { + constexpr int warp_size = ggml_cuda_get_physical_warp_size(); + + for (int itc = threadIdx.x; itc < it_compact; itc += warp_size) { + const mm_ids_helper_store store_it = store[itc]; + const int it = store_it.it(); + const int iex_used = store_it.iex_used(); + ids_dst[nex_prev + n_dumped + itc] = it*n_expert_used + iex_used; + // ids_src1 holds the forward map, or the inverse map (token slot -> compact row) for quant dedup + if (write_inverse) { + ids_src1[it*n_expert_used + iex_used] = nex_prev + n_dumped + itc; + } else { + ids_src1[nex_prev + n_dumped + itc] = it*sis1 + iex_used % nchannels_y; + } + } + n_dumped += it_compact; +} + +constexpr int n_unroll = 4; // Manually unroll this many loop iterations for better performance. + // Helper function for mul_mat_id, converts ids to a more convenient format. // ids_src1 describes how to permute the flattened column indices of src1 in order to get a compact src1 tensor sorted by expert. // ids_dst describes the same mapping but for the dst tensor. @@ -36,85 +80,138 @@ static __global__ void mm_ids_helper( const int32_t * __restrict__ ids, int32_t * __restrict__ ids_src1, int32_t * __restrict__ ids_dst, ggml_cuda_mm_id_tile_spec * __restrict__ tile_spec, const int n_tokens, const int n_expert_used_var, const int nchannels_y, const uint3 tile_width, - const int si1, const int sis1, const bool write_inverse) { + const int si1, const int sis1, const bool write_inverse, const int ne_store) { constexpr int warp_size = ggml_cuda_get_physical_warp_size(); const int n_expert_used = n_expert_used_template == 0 ? n_expert_used_var : n_expert_used_template; - const int expert = blockIdx.x; + + const int expert = blockIdx.x; // The expert this CUDA block handles. extern __shared__ char data_mm_ids_helper[]; mm_ids_helper_store * store = (mm_ids_helper_store *) data_mm_ids_helper; int nex_prev = 0; // Number of columns for experts with a lower index. + int n_dumped = 0; // Number of data values that have been dumped to output buffers. int it_compact = 0; // Running index for the compact slice of this expert. + // Step 1: Iterate over n_tokens, increment nex_prev to determine the output indices, fill up store. + // Step 1.5: If the store does not have enough space to hold all values, iterate over the rest of the tokens just to increment nex_prev. + // Step 2: Dump the stored values using nex_prev to get the correct output indices. + // Step 3: If we were not able to process all values, resume at the index up to which we were able to dump the output and re-do. + if constexpr (n_expert_used_template == 0) { // Generic implementation: - for (int it = 0; it < n_tokens; ++it) { - int iex_used = -1; // The index at which the expert is used, if any. - for (int iex = threadIdx.x; iex < n_expert_used; iex += warp_size) { - const int expert_used = ids[it*si1 + iex]; - nex_prev += expert_used < expert; - if (expert_used == expert) { - iex_used = iex; - } + int it = 0; + for (; it < n_tokens && it_compact + max(warp_size, n_expert_used) <= ne_store; ++it) { + for (int iex0 = 0; iex0 < n_expert_used; iex0 += warp_size) { + const int iex = iex0 + threadIdx.x; + const int expert_found = iex < n_expert_used ? ids[it*si1 + iex] : INT_MAX; + + constexpr bool increment_nex_prev = true; + constexpr bool write_to_store = true; + check_experts + (store, nex_prev, it_compact, expert, it, iex, expert_found); } + } + int it_dumped = it; + for (; it < n_tokens; ++it) { + for (int iex0 = 0; iex0 < n_expert_used; iex0 += warp_size) { + const int iex = iex0 + threadIdx.x; + const int expert_found = iex < n_expert_used ? ids[it*si1 + iex] : INT_MAX; - if (iex_used != -1) { - store[it_compact] = mm_ids_helper_store(it, iex_used); + constexpr bool increment_nex_prev = true; + constexpr bool write_to_store = false; + check_experts + (store, nex_prev, it_compact, expert, it, iex, expert_found); } + } + + nex_prev = warp_reduce_sum(nex_prev); + ggml_cuda_syncwarp(); + dump_store(ids_src1, ids_dst, n_expert_used, nchannels_y, sis1, write_inverse, store, nex_prev, n_dumped, it_compact); + it_compact = 0; - if (warp_reduce_any(iex_used != -1)) { - it_compact++; + for (int it = it_dumped; it < n_tokens; ++it) { + for (int iex0 = 0; iex0 < n_expert_used; iex0 += warp_size) { + const int iex = iex0 + threadIdx.x; + const int expert_found = iex < n_expert_used ? ids[it*si1 + iex] : INT_MAX; + + constexpr bool increment_nex_prev = false; + constexpr bool write_to_store = true; + check_experts + (store, nex_prev, it_compact, expert, it, iex, expert_found); + if (it_compact + max(warp_size, n_expert_used) >= ne_store) { + ggml_cuda_syncwarp(); + dump_store(ids_src1, ids_dst, n_expert_used, nchannels_y, sis1, write_inverse, store, nex_prev, n_dumped, it_compact); + it_compact = 0; + } } } + if (it_compact > 0) { + ggml_cuda_syncwarp(); + dump_store(ids_src1, ids_dst, n_expert_used, nchannels_y, sis1, write_inverse, store, nex_prev, n_dumped, it_compact); + } } else { // Implementation optimized for specific numbers of experts used: // a warp holds a whole number of token slots, so the slot count is padded to a power of 2 constexpr int neu_padded = mm_ids_pow2::value; static_assert(neu_padded <= warp_size && warp_size % neu_padded == 0, "bad n_expert_used"); - for (int it0 = 0; it0 < n_tokens; it0 += warp_size/neu_padded) { - const int it = it0 + threadIdx.x / neu_padded; - - const int iex = threadIdx.x % neu_padded; // The index at which the expert is used, if any. - const int expert_used = (neu_padded == n_expert_used || iex < n_expert_used) && it < n_tokens ? - ids[it*si1 + iex] : INT_MAX; - const int iex_used = expert_used == expert ? iex : -1; - nex_prev += expert_used < expert; - - // Whether the threads at this token position have used the expert: - const int it_compact_add_self = warp_reduce_any(iex_used != -1); + const int iex = threadIdx.x % neu_padded; // The index at which the expert is used, if any. - // Do a scan over threads at lower token positions in warp to get the correct index for writing data: - int it_compact_add_lower = 0; + int it0 = 0; + for (; it0 < n_tokens && it_compact + n_unroll*warp_size <= ne_store; it0 += n_unroll*warp_size/neu_padded) { #pragma unroll - for (int offset = neu_padded; offset < warp_size; offset += neu_padded) { - const int tmp = ggml_cuda_shfl_up(it_compact_add_self, offset, warp_size); - if (threadIdx.x >= static_cast(offset)) { - it_compact_add_lower += tmp; - } - } + for (int it1 = 0; it1 < n_unroll*warp_size/neu_padded; it1 += warp_size/neu_padded) { + const int it = it0 + it1 + threadIdx.x / neu_padded; + const int expert_found = (neu_padded == n_expert_used || iex < n_expert_used) && it < n_tokens ? + ids[it*si1 + iex] : INT_MAX; - if (iex_used != -1) { - store[it_compact + it_compact_add_lower] = mm_ids_helper_store(it, iex_used); + constexpr bool increment_nex_prev = true; + constexpr bool write_to_store = true; + check_experts + (store, nex_prev, it_compact, expert, it, iex, expert_found); } + } + int it0_dumped = it0; + for (; it0 < n_tokens; it0 += n_unroll*warp_size/neu_padded) { +#pragma unroll + for (int it1 = 0; it1 < n_unroll*warp_size/neu_padded; it1 += warp_size/neu_padded) { + const int it = it0 + it1 + threadIdx.x / neu_padded; + const int expert_found = (neu_padded == n_expert_used || iex < n_expert_used) && it < n_tokens ? + ids[it*si1 + iex] : INT_MAX; - // The thread with the highest index in the warp always has the sum over the whole warp, use it to increment all threads: - it_compact += ggml_cuda_shfl(it_compact_add_lower + it_compact_add_self, warp_size - 1, warp_size); + constexpr bool increment_nex_prev = true; + constexpr bool write_to_store = false; + check_experts + (store, nex_prev, it_compact, expert, it, iex, expert_found); + } } - } - nex_prev = warp_reduce_sum(nex_prev); - ggml_cuda_syncwarp(); - for (int itc = threadIdx.x; itc < it_compact; itc += warp_size) { - const mm_ids_helper_store store_it = store[itc]; - const int it = store_it.it(); - const int iex_used = store_it.iex_used(); - ids_dst[nex_prev + itc] = it*n_expert_used + iex_used; - // ids_src1 holds the forward map, or the inverse map (token slot -> compact row) for quant dedup - if (write_inverse) { - ids_src1[it*n_expert_used + iex_used] = nex_prev + itc; - } else { - ids_src1[nex_prev + itc] = it*sis1 + iex_used % nchannels_y; + nex_prev = warp_reduce_sum(nex_prev); + ggml_cuda_syncwarp(); + dump_store(ids_src1, ids_dst, n_expert_used, nchannels_y, sis1, write_inverse, store, nex_prev, n_dumped, it_compact); + it_compact = 0; + + for (it0 = it0_dumped; it0 < n_tokens; it0 += n_unroll*warp_size/neu_padded) { +#pragma unroll + for (int it1 = 0; it1 < n_unroll*warp_size/neu_padded; it1 += warp_size/neu_padded) { + const int it = it0 + it1 + threadIdx.x / neu_padded; + const int expert_found = (neu_padded == n_expert_used || iex < n_expert_used) && it < n_tokens ? + ids[it*si1 + iex] : INT_MAX; + + constexpr bool increment_nex_prev = false; + constexpr bool write_to_store = true; + check_experts + (store, nex_prev, it_compact, expert, it, iex, expert_found); + if (it_compact + warp_size >= ne_store) { + ggml_cuda_syncwarp(); + dump_store(ids_src1, ids_dst, n_expert_used, nchannels_y, sis1, write_inverse, store, nex_prev, n_dumped, it_compact); + it_compact = 0; + } + } + } + if (it_compact > 0) { + ggml_cuda_syncwarp(); + dump_store(ids_src1, ids_dst, n_expert_used, nchannels_y, sis1, write_inverse, store, nex_prev, n_dumped, it_compact); } } @@ -123,7 +220,7 @@ static __global__ void mm_ids_helper( } int col_low = nex_prev; - int col_high = nex_prev + min(int(tile_width.z), it_compact); + int col_high = nex_prev + min(int(tile_width.z), n_dumped); // The while loop covers all tiles at the seams containing the column with % tile_width == 0. while (col_high > fastdiv(col_low + tile_width.z - 1, tile_width) * tile_width.z) { @@ -131,7 +228,7 @@ static __global__ void mm_ids_helper( = {expert, col_low, col_high, /*padding =*/ 0}; col_low = col_high; - col_high = min(col_high + int(tile_width.z), nex_prev + it_compact); + col_high = min(col_high + int(tile_width.z), nex_prev + n_dumped); } // Finally, at most one extra tile_spec between the seams per expert. @@ -157,10 +254,12 @@ static void launch_mm_ids_helper( const dim3 num_blocks(n_experts, 1, 1); const dim3 block_size(warp_size, 1, 1); - const size_t nbytes_shared = n_tokens*sizeof(mm_ids_helper_store); - GGML_ASSERT(nbytes_shared <= smpbo); + const size_t ne_shared_pad = n_expert_used_template == 0 ? std::max(n_expert_used_var, warp_size) : n_unroll*warp_size; + const size_t nbytes_store_core = std::min(smpbo - ne_shared_pad * sizeof(mm_ids_helper_store), n_tokens * sizeof(mm_ids_helper_store)); + const size_t nbytes_shared = nbytes_store_core + ne_shared_pad * sizeof(mm_ids_helper_store); + const size_t ne_store = nbytes_shared / sizeof(mm_ids_helper_store); mm_ids_helper<<>> - (ids, ids_src1, ids_dst, tile_spec, n_tokens, n_expert_used_var, nchannels_y, tile_width_fd, si1, sis1, write_inverse); + (ids, ids_src1, ids_dst, tile_spec, n_tokens, n_expert_used_var, nchannels_y, tile_width_fd, si1, sis1, write_inverse, ne_store); } void ggml_cuda_launch_mm_ids_helper( diff --git a/ggml/src/ggml-cuda/mmvq.cu b/ggml/src/ggml-cuda/mmvq.cu index e4e47457ec6d..458854e81dfd 100644 --- a/ggml/src/ggml-cuda/mmvq.cu +++ b/ggml/src/ggml-cuda/mmvq.cu @@ -93,10 +93,12 @@ enum mmvq_parameter_table_id { MMVQ_PARAMETERS_GENERIC = 0, MMVQ_PARAMETERS_TURING, MMVQ_PARAMETERS_GCN, + MMVQ_PARAMETERS_RDNA1, MMVQ_PARAMETERS_RDNA2, MMVQ_PARAMETERS_RDNA3_0, MMVQ_PARAMETERS_RDNA4, - MMVQ_PARAMETERS_GB10 + MMVQ_PARAMETERS_GB10, + MMVQ_PARAMETERS_ORIN }; // The vdr of a type for a number of dst columns. On RDNA3 (RX 7900 XT) a thread takes wider steps with several @@ -148,6 +150,8 @@ static constexpr __device__ mmvq_parameter_table_id get_device_table_id() { return MMVQ_PARAMETERS_RDNA4; #elif defined(RDNA3_0) return MMVQ_PARAMETERS_RDNA3_0; +#elif defined(RDNA1) + return MMVQ_PARAMETERS_RDNA1; #elif defined(RDNA2) || defined(RDNA3_5) || defined(RDNA4_M) return MMVQ_PARAMETERS_RDNA2; #elif defined(GCN) || defined(CDNA) @@ -156,6 +160,8 @@ static constexpr __device__ mmvq_parameter_table_id get_device_table_id() { return MMVQ_PARAMETERS_TURING; #elif __CUDA_ARCH__ == GGML_CUDA_CC_GB10 return MMVQ_PARAMETERS_GB10; +#elif __CUDA_ARCH__ == GGML_CUDA_CC_ORIN + return MMVQ_PARAMETERS_ORIN; #else return MMVQ_PARAMETERS_GENERIC; #endif @@ -168,6 +174,9 @@ static __host__ mmvq_parameter_table_id get_device_table_id(int cc) { if (GGML_CUDA_CC_IS_RDNA3_0(cc)) { return MMVQ_PARAMETERS_RDNA3_0; } + if (GGML_CUDA_CC_IS_RDNA1(cc)) { + return MMVQ_PARAMETERS_RDNA1; + } if (GGML_CUDA_CC_IS_RDNA2(cc) || GGML_CUDA_CC_IS_RDNA3_5(cc) || GGML_CUDA_CC_IS_RDNA4_M(cc)) { return MMVQ_PARAMETERS_RDNA2; } @@ -180,6 +189,9 @@ static __host__ mmvq_parameter_table_id get_device_table_id(int cc) { if (GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) == GGML_CUDA_CC_GB10) { return MMVQ_PARAMETERS_GB10; } + if (GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) == GGML_CUDA_CC_ORIN) { + return MMVQ_PARAMETERS_ORIN; + } return MMVQ_PARAMETERS_GENERIC; } @@ -596,6 +608,23 @@ static constexpr __host__ __device__ int calc_nwarps(ggml_type type, int ncols_d } return 1; } + if (table_id == MMVQ_PARAMETERS_RDNA1) { + switch (ncols_dst) { + case 1: + return 1; + case 2: + case 3: + case 4: + return 4; + case 5: + case 6: + case 7: + case 8: + return 2; + default: + return 1; + } + } if (table_id == MMVQ_PARAMETERS_TURING) { if (ncols_dst == 1) { switch (type) { @@ -644,6 +673,9 @@ static constexpr __host__ __device__ int calc_nwarps(ggml_type type, int ncols_d } return generic; } + if (table_id == MMVQ_PARAMETERS_ORIN) { + return calc_nwarps(type, ncols_dst, MMVQ_PARAMETERS_GENERIC); + } return 1; } @@ -662,7 +694,7 @@ static constexpr __host__ __device__ bool mmvq_two_rows_ncols1(ggml_type type) { } static constexpr __host__ __device__ int calc_rows_per_block(ggml_type type, int ncols_dst, int table_id, bool small_k = false, int nwarps = 1) { - if (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_GCN || table_id == MMVQ_PARAMETERS_TURING || table_id == MMVQ_PARAMETERS_GB10) { + if (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_GCN || table_id == MMVQ_PARAMETERS_TURING || table_id == MMVQ_PARAMETERS_GB10 || table_id == MMVQ_PARAMETERS_RDNA1) { switch (ncols_dst) { case 1: if (small_k) { @@ -671,7 +703,42 @@ static constexpr __host__ __device__ int calc_rows_per_block(ggml_type type, int if (table_id == MMVQ_PARAMETERS_GB10) { return type == GGML_TYPE_IQ2_S || type == GGML_TYPE_IQ3_S ? 2 : 1; } - return table_id == MMVQ_PARAMETERS_GENERIC && mmvq_two_rows_ncols1(type) ? 2 : 1; + return (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_RDNA1) && mmvq_two_rows_ncols1(type) ? 2 : 1; + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + return 2; + default: + return 1; + } + } + if (table_id == MMVQ_PARAMETERS_ORIN) { + switch (ncols_dst) { + case 1: + if (small_k) { + return nwarps; + } + // One row per warp (more rows per block, more loads in flight) for these types, measured on Jetson Orin Nano. + // Other types are faster in isolated mat-vec too, but gained at most 2 % end to end. + switch (type) { + case GGML_TYPE_Q4_0: + case GGML_TYPE_Q4_1: + case GGML_TYPE_Q5_0: + case GGML_TYPE_Q5_1: + case GGML_TYPE_Q8_0: + case GGML_TYPE_Q4_K: + case GGML_TYPE_Q5_K: + case GGML_TYPE_Q6_K: + case GGML_TYPE_IQ4_NL: + return nwarps; + default: + break; + } + return mmvq_two_rows_ncols1(type) ? 2 : 1; case 2: case 3: case 4: diff --git a/ggml/src/ggml-cuda/rope.cu b/ggml/src/ggml-cuda/rope.cu index a1946f80a98a..e797eef6435a 100644 --- a/ggml/src/ggml-cuda/rope.cu +++ b/ggml/src/ggml-cuda/rope.cu @@ -92,13 +92,16 @@ static __global__ void rope_norm(const T * x, } else if constexpr (std::is_same_v) { half2 v = make_half2(x0, x1); ggml_cuda_memcpy_1<4>(dst + idst, &v); + } else if constexpr (std::is_same_v) { + const __align__(4) nv_bfloat16 v[2] = { ggml_cuda_cast(x0), ggml_cuda_cast(x1) }; + ggml_cuda_memcpy_1(dst + idst, v); } }; if (i0 < n_offs || i0 >= n_offs + n_dims) { if (inplace) { return; } - store_coaelsced(x[ix + 0], x[ix + 1]); + store_coaelsced(ggml_cuda_cast(x[ix + 0]), ggml_cuda_cast(x[ix + 1])); return; } @@ -113,8 +116,8 @@ static __global__ void rope_norm(const T * x, rope_yarn(theta_base/freq_factor, freq_scale, corr_dims, iw, ext_factor, attn_factor, cos_theta, sin_theta); - const float x0 = x[ix + 0]; - const float x1 = x[ix + 1]; + const float x0 = ggml_cuda_cast(x[ix + 0]); + const float x1 = ggml_cuda_cast(x[ix + 1]); store_coaelsced(x0 * cos_theta - x1 * sin_theta, x0 * sin_theta + x1 * cos_theta); } @@ -189,8 +192,8 @@ static __global__ void rope_neox(const T * x, rope_yarn(theta_base/freq_factor, freq_scale, corr_dims, iw, ext_factor, attn_factor, cos_theta, sin_theta); // idst/ix point at channel i0/2; the first channel of the rotated pair is n_offs + iw/2 = i0/2 + n_offs/2 - const float x0 = x[ix + n_offs/2 + 0]; - const float x1 = x[ix + n_offs/2 + n_dims/2]; + const float x0 = ggml_cuda_cast(x[ix + n_offs/2 + 0]); + const float x1 = ggml_cuda_cast(x[ix + n_offs/2 + n_dims/2]); dst[idst + n_offs/2 + 0] = ggml_cuda_cast(x0 * cos_theta - x1 * sin_theta); dst[idst + n_offs/2 + n_dims / 2] = ggml_cuda_cast(x0 * sin_theta + x1 * cos_theta); @@ -293,8 +296,8 @@ static __global__ void rope_multi(const T * x, rope_yarn(theta_base/freq_factor, freq_scale, corr_dims, iw, ext_factor, attn_factor, cos_theta, sin_theta); // idst/ix point at channel i0/2; the first channel of the rotated pair is n_offs + iw/2 = i0/2 + n_offs/2 - const float x0 = x[ix + n_offs/2 + 0]; - const float x1 = x[ix + n_offs/2 + n_dims/2]; + const float x0 = ggml_cuda_cast(x[ix + n_offs/2 + 0]); + const float x1 = ggml_cuda_cast(x[ix + n_offs/2 + n_dims/2]); dst[idst + n_offs/2 + 0] = ggml_cuda_cast(x0*cos_theta - x1*sin_theta); dst[idst + n_offs/2 + n_dims/2] = ggml_cuda_cast(x0*sin_theta + x1*cos_theta); @@ -357,11 +360,11 @@ static __global__ void rope_vision(const T * x, rope_yarn(theta_base/freq_factor, freq_scale, corr_dims, i0, ext_factor, attn_factor, cos_theta, sin_theta); - const float x0 = x[ix + 0]; - const float x1 = x[ix + n_dims]; + const float x0 = ggml_cuda_cast(x[ix + 0]); + const float x1 = ggml_cuda_cast(x[ix + n_dims]); - dst[idst + 0] = x0*cos_theta - x1*sin_theta; - dst[idst + n_dims] = x0*sin_theta + x1*cos_theta; + dst[idst + 0] = ggml_cuda_cast(x0*cos_theta - x1*sin_theta); + dst[idst + n_dims] = ggml_cuda_cast(x0*sin_theta + x1*cos_theta); } template @@ -569,8 +572,8 @@ void ggml_cuda_op_rope_impl(ggml_backend_cuda_context & ctx, } cudaStream_t stream = ctx.stream(); - GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); - GGML_ASSERT( dst->type == GGML_TYPE_F32 || dst->type == GGML_TYPE_F16); + GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); + GGML_ASSERT( dst->type == GGML_TYPE_F32 || dst->type == GGML_TYPE_F16 || dst->type == GGML_TYPE_BF16); // When not fused, src0 and dst types must match // When fused (ROPE+VIEW+SET_ROWS), src0 may be F32 and dst may be F16 GGML_ASSERT(src0->type == dst->type || (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F16)); @@ -655,6 +658,16 @@ void ggml_cuda_op_rope_impl(ggml_backend_cuda_context & ctx, s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, ext_factor, attn_factor, corr_dims, freq_factors, row_indices, set_rows_stride, inplace, stream); + } else if (src0->type == GGML_TYPE_BF16 && dst_type == GGML_TYPE_BF16) { + rope_neox_cuda((const nv_bfloat16 *) src0_d, (nv_bfloat16 *) dst_d, ne00, ne01, ne02, s01, s02, + s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, + ext_factor, attn_factor, corr_dims, freq_factors, row_indices, + set_rows_stride, inplace, stream); + } else if (src0->type == GGML_TYPE_BF16 && dst_type == GGML_TYPE_F16) { + rope_neox_cuda((const nv_bfloat16 *) src0_d, (half *) dst_d, ne00, ne01, ne02, s01, s02, + s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, + ext_factor, attn_factor, corr_dims, freq_factors, row_indices, + set_rows_stride, inplace, stream); } else { GGML_ABORT("fatal error"); } @@ -674,6 +687,16 @@ void ggml_cuda_op_rope_impl(ggml_backend_cuda_context & ctx, s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, ext_factor, attn_factor, corr_dims, freq_factors, sections, is_imrope, row_indices, set_rows_stride, inplace, stream); + } else if (src0->type == GGML_TYPE_BF16 && dst_type == GGML_TYPE_BF16) { + rope_multi_cuda((const nv_bfloat16 *) src0_d, (nv_bfloat16 *) dst_d, ne00, ne01, ne02, s01, s02, + s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, + ext_factor, attn_factor, corr_dims, freq_factors, sections, is_imrope, + row_indices, set_rows_stride, inplace, stream); + } else if (src0->type == GGML_TYPE_BF16 && dst_type == GGML_TYPE_F16) { + rope_multi_cuda((const nv_bfloat16 *) src0_d, (half *) dst_d, ne00, ne01, ne02, s01, s02, + s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, + ext_factor, attn_factor, corr_dims, freq_factors, sections, is_imrope, + row_indices, set_rows_stride, inplace, stream); } else { GGML_ABORT("fatal error"); } @@ -686,6 +709,10 @@ void ggml_cuda_op_rope_impl(ggml_backend_cuda_context & ctx, rope_vision_cuda((const half *) src0_d, (half *) dst_d, ne00, ne01, ne02, s01, s02, s03, s1, s2, s3, n_dims, nr, pos, freq_scale, freq_base, ext_factor, attn_factor, corr_dims, freq_factors, sections, stream); + } else if (src0->type == GGML_TYPE_BF16) { + rope_vision_cuda((const nv_bfloat16 *) src0_d, (nv_bfloat16 *) dst_d, ne00, ne01, ne02, s01, s02, s03, s1, + s2, s3, n_dims, nr, pos, freq_scale, freq_base, ext_factor, attn_factor, + corr_dims, freq_factors, sections, stream); } else { GGML_ABORT("fatal error"); } @@ -705,6 +732,16 @@ void ggml_cuda_op_rope_impl(ggml_backend_cuda_context & ctx, s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, ext_factor, attn_factor, corr_dims, freq_factors, row_indices, set_rows_stride, inplace, stream); + } else if (src0->type == GGML_TYPE_BF16 && dst_type == GGML_TYPE_BF16) { + rope_norm_cuda((const nv_bfloat16 *) src0_d, (nv_bfloat16 *) dst_d, ne00, ne01, ne02, s01, s02, + s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, + ext_factor, attn_factor, corr_dims, freq_factors, row_indices, + set_rows_stride, inplace, stream); + } else if (src0->type == GGML_TYPE_BF16 && dst_type == GGML_TYPE_F16) { + rope_norm_cuda((const nv_bfloat16 *) src0_d, (half *) dst_d, ne00, ne01, ne02, s01, s02, + s03, s1, s2, s3, n_dims, n_offs, nr, pos, freq_scale, freq_base, + ext_factor, attn_factor, corr_dims, freq_factors, row_indices, + set_rows_stride, inplace, stream); } else { GGML_ABORT("fatal error"); } diff --git a/ggml/src/ggml-cuda/set-rows.cu b/ggml/src/ggml-cuda/set-rows.cu index 4be3e649b73b..e4fb51619e66 100644 --- a/ggml/src/ggml-cuda/set-rows.cu +++ b/ggml/src/ggml-cuda/set-rows.cu @@ -4,8 +4,8 @@ typedef void (*set_rows_kernel_t)(const char * src, char * dst); // Generic quantized set_rows kernel template -template -static __global__ void k_set_rows_quant(const float * __restrict__ src0, +template +static __global__ void k_set_rows_quant(const src_t * __restrict__ src0, const idx_t * __restrict__ src1, block_type * __restrict__ dst, const int64_t ne_total, @@ -56,13 +56,23 @@ static __global__ void k_set_rows_quant(const float * __restrict__ src0, ggml_cuda_pdl_sync(); const int64_t dst_row = *(src1 + i10*s10 + i11*s11 + i12*s12); - const float * src0_row = src0 + i01*s01 + i02*s02 + i03*s03; + const src_t * src0_row = src0 + i01*s01 + i02*s02 + i03*s03; block_type * dst_row_ptr = dst + (dst_row*s1 + i02*s2 + i03*s3) / sizeof(block_type); - const float * src_block = src0_row + i00; + const src_t * src_block = src0_row + i00; block_type * dst_block = dst_row_ptr + i00 / qk; - quantize_func(src_block, dst_block); + if constexpr (std::is_same_v) { + quantize_func(src_block, dst_block); + } else { + // the quantize functions take F32 input: widen the block first + float src_block_f32[qk]; +#pragma unroll + for (int j = 0; j < qk; ++j) { + src_block_f32[j] = ggml_cuda_cast(src_block[j]); + } + quantize_func(src_block_f32, dst_block); + } GGML_UNUSED(ne10); GGML_UNUSED(ne11); @@ -71,9 +81,9 @@ static __global__ void k_set_rows_quant(const float * __restrict__ src0, } // Template dispatch function for quantized set_rows -template +template static void set_rows_cuda_quant( - const float * src0_d, const idx_t * src1_d, block_type * dst_d, + const src_t * src0_d, const idx_t * src1_d, block_type * dst_d, const int64_t ne00, const int64_t ne01, const int64_t ne02, const int64_t ne03, const int64_t ne10, const int64_t ne11, const int64_t ne12, const int64_t ne13, const size_t nb01, const size_t nb02, const size_t nb03, @@ -87,9 +97,9 @@ static void set_rows_cuda_quant( const dim3 block_size(CUDA_SET_ROWS_BLOCK_SIZE); const dim3 grid_size(num_blocks); - const int64_t s01 = nb01/sizeof(float); - const int64_t s02 = nb02/sizeof(float); - const int64_t s03 = nb03/sizeof(float); + const int64_t s01 = nb01/sizeof(src_t); + const int64_t s02 = nb02/sizeof(src_t); + const int64_t s03 = nb03/sizeof(src_t); const int64_t s10 = nb10/sizeof(idx_t); const int64_t s11 = nb11/sizeof(idx_t); const int64_t s12 = nb12/sizeof(idx_t); @@ -104,7 +114,7 @@ static void set_rows_cuda_quant( const uint3 ne11_fd = init_fastdiv_values((uint32_t) ne11); const uint3 ne12_fd = init_fastdiv_values((uint32_t) ne12); - k_set_rows_quant<<>>( + k_set_rows_quant<<>>( src0_d, src1_d, dst_d, ne_total, ne10, ne11, ne12, ne13, s01, s02, s03, s10, s11, s12, s1, s2, s3, ne00_fd, ne01_fd, ne02_fd, ne11_fd, ne12_fd); } @@ -268,7 +278,7 @@ static void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_tensor * s stream ); } else if (dst->type == GGML_TYPE_Q4_0) { - set_rows_cuda_quant( + set_rows_cuda_quant( src0_d, src1_d, (block_q4_0*)dst->data, ne00, ne01, ne02, ne03, ne10, ne11, ne12, ne13, @@ -278,7 +288,7 @@ static void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_tensor * s stream ); } else if (dst->type == GGML_TYPE_Q4_1) { - set_rows_cuda_quant( + set_rows_cuda_quant( src0_d, src1_d, (block_q4_1*)dst->data, ne00, ne01, ne02, ne03, ne10, ne11, ne12, ne13, @@ -288,7 +298,7 @@ static void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_tensor * s stream ); } else if (dst->type == GGML_TYPE_Q5_0) { - set_rows_cuda_quant( + set_rows_cuda_quant( src0_d, src1_d, (block_q5_0*)dst->data, ne00, ne01, ne02, ne03, ne10, ne11, ne12, ne13, @@ -298,7 +308,7 @@ static void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_tensor * s stream ); } else if (dst->type == GGML_TYPE_Q5_1) { - set_rows_cuda_quant( + set_rows_cuda_quant( src0_d, src1_d, (block_q5_1*)dst->data, ne00, ne01, ne02, ne03, ne10, ne11, ne12, ne13, @@ -308,7 +318,7 @@ static void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_tensor * s stream ); } else if (dst->type == GGML_TYPE_Q8_0) { - set_rows_cuda_quant( + set_rows_cuda_quant( src0_d, src1_d, (block_q8_0*)dst->data, ne00, ne01, ne02, ne03, ne10, ne11, ne12, ne13, @@ -318,7 +328,7 @@ static void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_tensor * s stream ); } else if (dst->type == GGML_TYPE_IQ4_NL) { - set_rows_cuda_quant( + set_rows_cuda_quant( src0_d, src1_d, (block_iq4_nl*)dst->data, ne00, ne01, ne02, ne03, ne10, ne11, ne12, ne13, @@ -382,12 +392,11 @@ void set_rows_cuda(ggml_backend_cuda_context & ctx, const ggml_te } } - void ggml_cuda_op_set_rows(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { const ggml_tensor * src0 = dst->src[0]; const ggml_tensor * src1 = dst->src[1]; - GGML_ASSERT(src0->type == GGML_TYPE_F32 || (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16)); + GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_BF16 || (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16)); GGML_ASSERT(src1->type == GGML_TYPE_I64 || src1->type == GGML_TYPE_I32); if (src0->type == GGML_TYPE_F32) { @@ -402,6 +411,12 @@ void ggml_cuda_op_set_rows(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { } else { set_rows_cuda(ctx, src0, src1, dst); } + } else if (src0->type == GGML_TYPE_BF16) { + if (src1->type == GGML_TYPE_I64) { + set_rows_cuda(ctx, src0, src1, dst); + } else { + set_rows_cuda(ctx, src0, src1, dst); + } } else { GGML_ABORT("unsupported type %s", ggml_type_name(src0->type)); } diff --git a/ggml/src/ggml-cuda/sleep.cu b/ggml/src/ggml-cuda/sleep.cu new file mode 100644 index 000000000000..e6a40e5f213a --- /dev/null +++ b/ggml/src/ggml-cuda/sleep.cu @@ -0,0 +1,32 @@ +#include "sleep.cuh" + +#if !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) + +// %globaltimer is a nanosecond wall clock, unlike clock64() it is unaffected by the SM clock and by frequency scaling +static __device__ __forceinline__ uint64_t globaltimer_ns() { + uint64_t t; + asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t)); + return t; +} + +// a single thread is enough, the next kernel on the same stream cannot start before this one retires +static __global__ void sleep_ns(const uint64_t ns) { + const uint64_t t0 = globaltimer_ns(); + + while (globaltimer_ns() - t0 < ns) {} +} + +void ggml_cuda_op_sleep(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { + sleep_ns<<<1, 1, 0, ctx.stream()>>>(1000*(uint64_t) ggml_get_op_params_i32(dst, 0)); + CUDA_CHECK(cudaGetLastError()); +} + +#else + +void ggml_cuda_op_sleep(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { + GGML_UNUSED(ctx); + GGML_UNUSED(dst); + GGML_ABORT("GGML_OP_SLEEP requires the %%globaltimer register, which is only available on CUDA"); +} + +#endif // !defined(GGML_USE_HIP) && !defined(GGML_USE_MUSA) diff --git a/ggml/src/ggml-cuda/sleep.cuh b/ggml/src/ggml-cuda/sleep.cuh new file mode 100644 index 000000000000..d62c3178565c --- /dev/null +++ b/ggml/src/ggml-cuda/sleep.cuh @@ -0,0 +1,3 @@ +#include "common.cuh" + +void ggml_cuda_op_sleep(ggml_backend_cuda_context & ctx, ggml_tensor * dst); diff --git a/ggml/src/ggml-cuda/top-k.cu b/ggml/src/ggml-cuda/top-k.cu index 976e26ce0009..1035d1a27217 100644 --- a/ggml/src/ggml-cuda/top-k.cu +++ b/ggml/src/ggml-cuda/top-k.cu @@ -194,13 +194,6 @@ static __global__ void top_k_radix_gather( constexpr int NBINS = 1 << RADIX_BITS; constexpr int warp_size = ggml_cuda_get_physical_warp_size(); constexpr int nwarps = BLOCK_SIZE / warp_size; - const auto popc = [](const ggml_cuda_thread_mask_t mask) { - if constexpr (warp_size == 64) { - return __popcll(mask); - } else { - return __popc(mask); - } - }; __shared__ int warp_ties[nwarps]; const int row = blockIdx.x / blocks_per_row; @@ -257,11 +250,11 @@ static __global__ void top_k_radix_gather( const bool is_tie = col < warp_end && top_k_float_to_ordered(row_src[col]) == threshold; const ggml_cuda_thread_mask_t ties = ggml_cuda_ballot(is_tie); - const int tie_pos = pos + popc(ties & (((ggml_cuda_thread_mask_t) 1 << lane) - 1)); + const int tie_pos = pos + ggml_cuda_popc(ties & (((ggml_cuda_thread_mask_t) 1 << lane) - 1)); if (is_tie && tie_pos < pos_end) { row_dst[k - rank + tie_pos] = col; } - pos += popc(ties); + pos += ggml_cuda_popc(ties); } } diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index 26746d0b3065..2e085453adb9 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1713,7 +1713,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te return has_simdgroup_reduction && op->src[0]->type == GGML_TYPE_F32 && (ggml_is_contiguous_rows(op->src[0])); case GGML_OP_ROPE: case GGML_OP_ROPE_BACK: - return ggml_rope_get_truncate(op); + return ggml_rope_get_truncate(op) && (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16); case GGML_OP_IM2COL: return ggml_is_contiguous(op->src[1]) && op->src[1]->type == GGML_TYPE_F32 && (op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_F32); case GGML_OP_CONV_2D: diff --git a/ggml/src/ggml-metal/ggml-metal-fusion.cpp b/ggml/src/ggml-metal/ggml-metal-fusion.cpp index 6766b4bd998f..7b55a301ea1f 100644 --- a/ggml/src/ggml-metal/ggml-metal-fusion.cpp +++ b/ggml/src/ggml-metal/ggml-metal-fusion.cpp @@ -135,17 +135,15 @@ static bool ggml_metal_fusion_check_norm( } for (int j = 1; j < (int) fusion->ops.size(); j++) { - // the fused MUL/ADD must read the previous node as src0 - if (nodes[j]->src[0] != nodes[j - 1]) { - return false; - } + // MUL/ADD are commutative, the previous node can be either operand + const ggml_tensor * src = nodes[j]->src[0] == nodes[j - 1] ? nodes[j]->src[1] : nodes[j]->src[0]; // the weight/bias must have the same row width as the norm input - if (nodes[j]->src[1]->ne[0] != nodes[0]->ne[0]) { + if (src->ne[0] != nodes[0]->ne[0]) { return false; } - if (!ggml_is_contiguous_rows(nodes[j]->src[1])) { + if (!ggml_is_contiguous_rows(src)) { return false; } diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp index 1ae7f3d5dcf9..a7a1ef61e9cf 100644 --- a/ggml/src/ggml-metal/ggml-metal-ops.cpp +++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp @@ -4698,16 +4698,17 @@ int ggml_metal_op_norm(ggml_metal_op_t ctx, int idx) { for (int i = 1; i < n_fuse; i++) { const ggml_tensor * fn = ctx->node(idx + i); + const ggml_tensor * fs = fn->src[0] == ctx->node(idx + i - 1) ? fn->src[1] : fn->src[0]; - bid_fuse[i - 1] = ggml_metal_get_buffer_id(fn->src[1]); + bid_fuse[i - 1] = ggml_metal_get_buffer_id(fs); - args.nef1[i] = fn->src[1]->ne[1]; - args.nef2[i] = fn->src[1]->ne[2]; - args.nef3[i] = fn->src[1]->ne[3]; + args.nef1[i] = fs->ne[1]; + args.nef2[i] = fs->ne[2]; + args.nef3[i] = fs->ne[3]; - args.nbf1[i] = fn->src[1]->nb[1]; - args.nbf2[i] = fn->src[1]->nb[2]; - args.nbf3[i] = fn->src[1]->nb[3]; + args.nbf1[i] = fs->nb[1]; + args.nbf2[i] = fs->nb[2]; + args.nbf3[i] = fs->nb[3]; } if (debug_fusion > 1) { diff --git a/ggml/src/ggml-opencl/CMakeLists.txt b/ggml/src/ggml-opencl/CMakeLists.txt index cdf4a5d54455..aadf5ddb3321 100644 --- a/ggml/src/ggml-opencl/CMakeLists.txt +++ b/ggml/src/ggml-opencl/CMakeLists.txt @@ -227,6 +227,13 @@ set(GGML_OPENCL_KERNELS gemm_coopk_q4_0_q8_1_dp4a gemm_coopk_q4_k_q8_1_dp4a gemm_coopk_q6_k_q8_1_dp4a + pack_b_f16_coopmat + gemm_noshuffle_q4_0_f32_coopmat + gemm_noshuffle_q5_0_f32_coopmat + gemm_noshuffle_q8_0_f32_coopmat + gemm_noshuffle_q4_k_f32_coopmat + gemm_noshuffle_q5_k_f32_coopmat + gemm_noshuffle_q6_k_f32_coopmat quant_a_q8_1 gemv_moe_q4_k_f32_ns gemm_moe_q5_k_f32_ns @@ -323,6 +330,9 @@ set(GGML_OPENCL_KERNELS mul_mm_f16_f32_kq_kqv mul_mm_f16_f32_kq_p8 mul_mm_q8_f32_kqv + mul_mm_q8_kq_p8 + mul_mm_q8_kq_p8_dk512 + flash_attn_q8_rows conv2d conv2d_f16_f32 conv2_dw diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index 0d9212232871..d35c6d047167 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -781,6 +781,10 @@ struct ggml_backend_opencl_context { ggml_cl_buffer prealloc_fa_pd; ggml_cl_buffer prealloc_fa_bmax; ggml_cl_buffer prealloc_fa_bsum; + ggml_cl_buffer prealloc_fa_k8; + ggml_cl_buffer prealloc_fa_k8_scale; + ggml_cl_buffer prealloc_fa_q8; + ggml_cl_buffer prealloc_fa_q8_scale; #ifdef GGML_OPENCL_USE_ADRENO_KERNELS ggml_cl_buffer prealloc_adreno_xmem_const; @@ -899,6 +903,10 @@ struct ggml_backend_opencl_context { cl_kernel kernel_fa_kqv_direct_f16 = nullptr; cl_kernel kernel_fa_kqv_direct_reduce = nullptr; cl_kernel kernel_fa_v_transpose_q8 = nullptr; + cl_kernel kernel_fa_q8_rows_f16 = nullptr; + cl_kernel kernel_fa_q8_rows_f32 = nullptr; + cl_kernel kernel_mul_mm_q8_kq_p8 = nullptr; + cl_kernel kernel_mul_mm_q8_kq_p8_dk512 = nullptr; ggml_opencl_fa_kernels fa; #ifdef GGML_OPENCL_USE_ADRENO_KERNELS ggml_cl_adreno_xmem_attn_state adreno_xmem_attn; @@ -1487,6 +1495,13 @@ struct ggml_backend_opencl_context { cl_kernel kernel_gemm_noshuffle_iq4_nl_q8_1_dp4a = nullptr; // dp4a (int8) dense IQ4_NL prefill GEMM cl_kernel kernel_gemm_noshuffle_q4_0_q8_1_dp4a = nullptr; // dp4a (int8) dense q4_0 prefill GEMM cl_kernel kernel_gemm_noshuffle_q4_0_q8_1_dp4a_act_vload4 = nullptr; + cl_kernel kernel_pack_b_f16_coopmat = nullptr; + cl_kernel kernel_gemm_noshuffle_q4_0_f32_coopmat = nullptr; + cl_kernel kernel_gemm_noshuffle_q5_0_f32_coopmat = nullptr; + cl_kernel kernel_gemm_noshuffle_q8_0_f32_coopmat = nullptr; + cl_kernel kernel_gemm_noshuffle_q4_k_f32_coopmat = nullptr; + cl_kernel kernel_gemm_noshuffle_q5_k_f32_coopmat = nullptr; + cl_kernel kernel_gemm_noshuffle_q6_k_f32_coopmat = nullptr; cl_kernel kernel_gemm_coopk_q4_0_q8_1_dp4a_c4 = nullptr; cl_kernel kernel_gemm_coopk_q4_0_q8_1_dp4a_c2 = nullptr; int nsg_coopk_dp4a_q4_0 = 8; @@ -1506,7 +1521,18 @@ struct ggml_backend_opencl_context { #endif // GGML_OPENCL_USE_ADRENO_KERNELS ~ggml_backend_opencl_context() { - for (cl_kernel kernel : {kernel_mul_mm_f16_f32_kq_p8, kernel_mul_mm_q8_f32_kqv, kernel_fa_p8_fixup, kernel_fa_v_transpose_q8, kernel_fa_kqv_direct_f16, kernel_fa_kqv_direct_reduce}) { + for (cl_kernel kernel : { + kernel_mul_mm_f16_f32_kq_p8, + kernel_mul_mm_q8_f32_kqv, + kernel_fa_p8_fixup, + kernel_fa_v_transpose_q8, + kernel_fa_kqv_direct_f16, + kernel_fa_kqv_direct_reduce, + kernel_fa_q8_rows_f16, + kernel_fa_q8_rows_f32, + kernel_mul_mm_q8_kq_p8, + kernel_mul_mm_q8_kq_p8_dk512 + }) { if (kernel != nullptr) { CL_CHECK(clReleaseKernel(kernel)); } @@ -1648,7 +1674,7 @@ static cl_program build_program_from_source_ex(cl_context ctx, cl_device_id dev, return NULL; } -static cl_program build_program_from_source(ggml_backend_opencl_context * backend_ctx, const char* program_buffer, const std::string &compile_opts) { +static cl_program build_program_from_source(ggml_backend_opencl_context * backend_ctx, const char* program_buffer, const std::string &compile_opts, bool fatal = true) { cl_context ctx = backend_ctx->context; cl_device_id dev = backend_ctx->device; @@ -1660,7 +1686,7 @@ static cl_program build_program_from_source(ggml_backend_opencl_context * backen return p_cached; } - cl_program p = build_program_from_source_ex(ctx, dev, program_buffer, compile_opts, /*fatal=*/true); + cl_program p = build_program_from_source_ex(ctx, dev, program_buffer, compile_opts, fatal); // Best-effort save of the freshly-built binary (no-op if cache disabled). if (p != nullptr) { @@ -1960,6 +1986,137 @@ static void load_cl_kernels_gemm_coopk(ggml_backend_opencl_context * backend_ctx } } +static void load_cl_kernels_coopmat(ggml_backend_opencl_context * backend_ctx) { + if (backend_ctx->gpu_family != GPU_FAMILY::ADRENO || !strstr(backend_ctx->device_name.c_str(), "850")) { + return; + } + + cl_int err; + const std::string opts = "-cl-std=CL" + std::to_string(backend_ctx->opencl_c_version.major) + "." + + std::to_string(backend_ctx->opencl_c_version.minor) + + (backend_ctx->adreno_use_large_buffer ? " -qcom-enable-large-buffer" : ""); + + // pack_b_f16_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "pack_b_f16_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("pack_b_f16_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (!prog) { + return; + } + CL_CHECK((backend_ctx->kernel_pack_b_f16_coopmat = clCreateKernel(prog, "kernel_pack_b_f16_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q4_0_f32_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q4_0_f32_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q4_0_f32_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (prog) { + CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_0_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_0_f32_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_noshuffle_q5_0_f32_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q5_0_f32_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q5_0_f32_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (prog) { + CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q5_0_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_0_f32_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_noshuffle_q8_0_f32_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q8_0_f32_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q8_0_f32_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (prog) { + CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q8_0_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q8_0_f32_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_noshuffle_q4_k_f32_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q4_k_f32_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q4_k_f32_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (prog) { + CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_k_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_k_f32_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_noshuffle_q5_k_f32_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q5_k_f32_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q5_k_f32_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (prog) { + CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q5_k_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_k_f32_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_noshuffle_q6_k_f32_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q6_k_f32_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q6_k_f32_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (prog) { + CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q6_k_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q6_k_f32_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } +} + #endif static std::string ggml_opencl_make_compile_opts(const ggml_backend_opencl_context * backend_ctx) { @@ -3995,6 +4152,52 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { } #ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (backend_ctx->gpu_family == ADRENO && backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string rows_src { + #include "flash_attn_q8_rows.cl.h" + }; + const std::string kq_src { + #include "mul_mm_q8_kq_p8.cl.h" + }; +#else + const std::string rows_src = read_file("flash_attn_q8_rows.cl"); + const std::string kq_src = read_file("mul_mm_q8_kq_p8.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, rows_src.c_str(), compile_opts, /*fatal=*/false); + if (prog != nullptr) { + CL_CHECK((backend_ctx->kernel_fa_q8_rows_f16 = clCreateKernel(prog, "kernel_fa_q8_rows_f16", &err), err)); + CL_CHECK((backend_ctx->kernel_fa_q8_rows_f32 = clCreateKernel(prog, "kernel_fa_q8_rows_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + } + prog = build_program_from_source(backend_ctx, kq_src.c_str(), compile_opts, /*fatal=*/false); + if (prog != nullptr) { + CL_CHECK((backend_ctx->kernel_mul_mm_q8_kq_p8 = clCreateKernel(prog, "kernel_mul_mm_q8_kq_p8", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + } + GGML_LOG_CONT("."); + } + + // mul_mm_q8_kq_p8_dk512 + if (backend_ctx->gpu_family == ADRENO && backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_q8_kq_p8_dk512.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_q8_kq_p8_dk512.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts, /*fatal=*/false); + if (prog != nullptr) { + cl_kernel kernel = clCreateKernel(prog, "kernel_mul_mm_q8_kq_p8_dk512", &err); + CL_CHECK(clReleaseProgram(prog)); + if (err == CL_SUCCESS) { + backend_ctx->kernel_mul_mm_q8_kq_p8_dk512 = kernel; + } + } + GGML_LOG_CONT("."); + } + // mul_mm_f16_f32_kq_p8 if (backend_ctx->gpu_family == ADRENO && backend_ctx->has_integer_dot) { #ifdef GGML_OPENCL_EMBED_KERNELS @@ -7748,6 +7951,7 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { } } load_cl_kernels_gemm_coopk(backend_ctx); + load_cl_kernels_coopmat(backend_ctx); #endif // GGML_OPENCL_USE_ADRENO_KERNELS GGML_LOG_CONT("\n"); backend_ctx->kernels_loaded = true; @@ -11674,7 +11878,8 @@ inline bool use_q4_0_bin_kernels(const ggml_backend_opencl_context *backend_ctx, #ifdef GGML_OPENCL_USE_ADRENO_KERNELS if (!backend_ctx->kernel_gemv_noshuffle_q4_0_f32_32b_trans || !(backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin || - backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin)) { + backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin || + backend_ctx->kernel_gemm_noshuffle_q4_0_f32_coopmat)) { return false; } @@ -11828,7 +12033,8 @@ inline bool use_q6_k_bin_kernels(const ggml_backend_opencl_context *backend_ctx, #ifdef GGML_OPENCL_USE_ADRENO_KERNELS if (!backend_ctx->kernel_gemv_noshuffle_q6_k_f32_32b_trans || !(backend_ctx->kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a8_bin || - backend_ctx->kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a7_bin)) { + backend_ctx->kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a7_bin || + backend_ctx->kernel_gemm_noshuffle_q6_k_f32_coopmat)) { return false; } // bin kernels require ne2 == 1 and ne3 == 1 for weights @@ -11846,7 +12052,8 @@ inline bool use_q4_k_bin_kernels(const ggml_backend_opencl_context *backend_ctx, #ifdef GGML_OPENCL_USE_ADRENO_KERNELS if (!backend_ctx->kernel_gemv_noshuffle_q4_k_f32_32b_trans || !(backend_ctx->kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a8_bin || - backend_ctx->kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a7_bin)) { + backend_ctx->kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a7_bin || + backend_ctx->kernel_gemm_noshuffle_q4_k_f32_coopmat)) { return false; } // bin kernels require ne2 == 1 and ne3 == 1 for weights @@ -11864,7 +12071,8 @@ inline bool use_q5_k_bin_kernels(const ggml_backend_opencl_context *backend_ctx, #ifdef GGML_OPENCL_USE_ADRENO_KERNELS if (!backend_ctx->kernel_gemv_noshuffle_q5_k_f32_32b_trans || !(backend_ctx->kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a8_bin || - backend_ctx->kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a7_bin)) { + backend_ctx->kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a7_bin || + backend_ctx->kernel_gemm_noshuffle_q5_k_f32_coopmat)) { return false; } return (tensor->ne[0] % 256 == 0) && (tensor->ne[1] % 64 == 0); @@ -12305,7 +12513,7 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te } return false; } - return true; + return op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16; } case GGML_OP_SOLVE_TRI: return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous(op->src[0]); @@ -22922,12 +23130,58 @@ static void ggml_cl_flash_attn_prefill_bin(ggml_backend_t backend, const ggml_te } #endif // GGML_OPENCL_USE_ADRENO_KERNELS +static void ggml_cl_fa_q8_rows( + ggml_backend_t backend, const ggml_tensor * src, const ggml_tensor * dst, + cl_mem values, cl_mem scales, int64_t row0, int nrow +) { + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + auto * extra = (ggml_tensor_extra_cl *) (src->view_src ? src->view_src->extra : src->extra); + const cl_ulong offset = extra->offset + src->view_offs + row0 * src->nb[1]; + const cl_ulong nb1 = src->nb[1]; + const cl_ulong nb2 = src->nb[2]; + const int dk = src->ne[0]; + const int nhead = src->ne[2]; + cl_kernel kernel; + switch (src->type) { + case GGML_TYPE_F16: kernel = backend_ctx->kernel_fa_q8_rows_f16; break; + case GGML_TYPE_F32: kernel = backend_ctx->kernel_fa_q8_rows_f32; break; + default: GGML_ABORT("unsupported int8 KQ input type"); + } + cl_uint a = 0; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &offset)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &values)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &scales)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &dk)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nrow)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nhead)); + const size_t blocks = (size_t) (dk / 32) * nrow * nhead; + size_t gws[3] = {(blocks + 63) / 64 * 64, 1, 1}; + size_t lws[3] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); +} + +static void ggml_cl_fa_kq_int8_prepare(ggml_backend_t backend, const ggml_tensor * dst, int64_t n_q_chunk) { + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * q = dst->src[0]; + const ggml_tensor * k = dst->src[1]; + const size_t k_bytes = (size_t) k->ne[0] * k->ne[1] * k->ne[2]; + const size_t q_bytes = (size_t) q->ne[0] * n_q_chunk * q->ne[2]; + backend_ctx->prealloc_fa_k8.allocate(backend_ctx->context, k_bytes); + backend_ctx->prealloc_fa_k8_scale.allocate(backend_ctx->context, k_bytes / 32 * sizeof(cl_half)); + backend_ctx->prealloc_fa_q8.allocate(backend_ctx->context, q_bytes); + backend_ctx->prealloc_fa_q8_scale.allocate(backend_ctx->context, q_bytes / 32 * sizeof(cl_half)); + ggml_cl_fa_q8_rows(backend, k, dst, backend_ctx->prealloc_fa_k8.buffer, backend_ctx->prealloc_fa_k8_scale.buffer, 0, k->ne[1]); +} + static void ggml_cl_fa_kq_p8_dispatch( ggml_backend_t backend, const ggml_tensor * q, const ggml_tensor * k, const ggml_tensor * mask, const ggml_tensor * sinks, const ggml_tensor * dst, - int64_t q0, int nqc, float scale, float max_bias, int p_pitch + int64_t q0, int nqc, float scale, float max_bias, int p_pitch, bool kq_int8 ) { auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; auto * extra_k = (ggml_tensor_extra_cl *) (k->view_src ? k->view_src->extra : k->extra); @@ -22940,64 +23194,103 @@ static void ggml_cl_fa_kq_p8_dispatch( const int D_A = k->ne[2]; const int D_B = q->ne[2]; - cl_int err; - - cl_buffer_region region = {extra_k->offset + k->view_offs, k->nb[1] * k->ne[1]}; - cl_mem k_sub = clCreateSubBuffer(extra_k->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - cl_image_format fmt = {CL_RGBA, CL_FLOAT}; - cl_image_desc desc = {}; - desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - desc.image_width = region.size / 16; - desc.buffer = k_sub; - cl_mem k_img = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &fmt, &desc, nullptr, &err); - CL_CHECK(err); - - region.origin = extra_q->offset + q->view_offs + q0 * q->nb[1]; - region.size = (size_t) K * N * D_B * sizeof(float); - cl_mem q_sub = clCreateSubBuffer(extra_q->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - const cl_ulong off_mask = extra_m->offset + mask->view_offs + q0 * mask->nb[1]; const cl_ulong mask_nb1 = mask->nb[1]; const int n_head_log2 = 1u << (unsigned) floorf(log2f((float) D_B)); const float m0 = powf(2.0f, -max_bias / n_head_log2); const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2); + cl_kernel kernel; cl_uint a = 0; - cl_kernel kernel = backend_ctx->kernel_mul_mm_f16_f32_kq_p8; - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &k_img)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &q_sub)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pq.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bmax.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bsum.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_m->data_device)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_mask)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &mask_nb1)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &scale)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &max_bias)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m0)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m1)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head_log2)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &M)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &N)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_A)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_B)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &p_pitch)); + if (kq_int8) { + ggml_cl_fa_q8_rows(backend, q, dst, backend_ctx->prealloc_fa_q8.buffer, backend_ctx->prealloc_fa_q8_scale.buffer, q0, nqc); + kernel = K <= 256 ? backend_ctx->kernel_mul_mm_q8_kq_p8 : backend_ctx->kernel_mul_mm_q8_kq_p8_dk512; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_k8.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_k8_scale.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_q8.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_q8_scale.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bmax.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bsum.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_m->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_mask)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &mask_nb1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &max_bias)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m0)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head_log2)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_B)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_A)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &p_pitch)); + size_t gws[3] = {64 * (((size_t) N + 31) / 32) * (D_B / D_A), ((size_t) M + 511) / 512, (size_t) D_A}; + size_t lws[3] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } else { + cl_int err; - const size_t n_tiles = (N + 31) / 32; - size_t gws[3] = {64, n_tiles, (size_t)(M / 64) * D_B}; + cl_buffer_region region = {extra_k->offset + k->view_offs, k->nb[1] * k->ne[1]}; + cl_mem k_sub = clCreateSubBuffer(extra_k->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); - const bool two_tiles = n_tiles % 2 == 0 && backend_ctx->get_kernel_workgroup_size(kernel) >= 128; - size_t lws[3] = {64, two_tiles ? (size_t) 2 : (size_t) 1, 1}; + cl_image_format fmt = {CL_RGBA, CL_FLOAT}; + cl_image_desc desc = {}; + desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + desc.image_width = region.size / 16; + desc.buffer = k_sub; + cl_mem k_img = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &fmt, &desc, nullptr, &err); + CL_CHECK(err); - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - CL_CHECK(clReleaseMemObject(k_img)); - CL_CHECK(clReleaseMemObject(k_sub)); - CL_CHECK(clReleaseMemObject(q_sub)); + region.origin = extra_q->offset + q->view_offs + q0 * q->nb[1]; + region.size = (size_t) K * N * D_B * sizeof(float); + cl_mem q_sub = clCreateSubBuffer(extra_q->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + kernel = backend_ctx->kernel_mul_mm_f16_f32_kq_p8; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &k_img)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &q_sub)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bmax.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bsum.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_m->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_mask)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &mask_nb1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &max_bias)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m0)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head_log2)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_A)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_B)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &p_pitch)); + + // Pack query heads of each KV group into a short batch's tile. + static const bool fold_enabled = [] { + const char * e = getenv("GGML_OPENCL_FA_KQ_P8_FOLD"); + return !e || e[0] != '0'; + }(); + const int gqa = D_B / D_A; + const int fold = fold_enabled && gqa > 1 && N < 32 && gqa <= INT_MAX / N ? gqa : 1; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &fold)); + + const size_t n_tiles = ((size_t) N * fold + 31) / 32; + size_t gws[3] = {64, n_tiles, (size_t)(M / 64) * (fold > 1 ? D_A : D_B)}; + + const bool two_tiles = n_tiles % 2 == 0 && backend_ctx->get_kernel_workgroup_size(kernel) >= 128; + size_t lws[3] = {64, two_tiles ? (size_t) 2 : (size_t) 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + CL_CHECK(clReleaseMemObject(k_img)); + CL_CHECK(clReleaseMemObject(k_sub)); + CL_CHECK(clReleaseMemObject(q_sub)); + } cl_mem sinks_buf = extra_q->data_device; cl_ulong sinks_off = 0; @@ -23261,7 +23554,7 @@ static void ggml_cl_flash_attn_decompose_kq_p8( ggml_backend_t backend, const ggml_tensor * q, const ggml_tensor * k, ggml_tensor * dst, - int64_t n_q_chunk, float scale, float max_bias, bool kqv_direct + int64_t n_q_chunk, float scale, float max_bias, bool kqv_direct, bool kq_int8 ) { auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; const ggml_tensor * v = dst->src[2]; @@ -23345,13 +23638,17 @@ static void ggml_cl_flash_attn_decompose_kq_p8( backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); } + if (kq_int8) { + ggml_cl_fa_kq_int8_prepare(backend, dst, n_q_chunk); + } + ggml_tensor_extra_cl extra_kqv; ggml_tensor kqv; for (int64_t q0 = 0; q0 < n_q; q0 += n_q_chunk) { const int64_t nqc = MIN(n_q_chunk, n_q - q0); - ggml_cl_fa_kq_p8_dispatch(backend, q, k, mask, sinks, dst, q0, nqc, scale, max_bias, kv_pitch); + ggml_cl_fa_kq_p8_dispatch(backend, q, k, mask, sinks, dst, q0, nqc, scale, max_bias, kv_pitch, kq_int8); ggml_cl_fa_decompose_scratch_tensor(kqv, extra_kqv, backend_ctx->prealloc_fa_kqv.buffer, GGML_TYPE_F32, dv, nqc, n_head); @@ -23408,6 +23705,7 @@ static void ggml_cl_flash_attn_decompose_kq_p8( // head size. GGML_OPENCL_FA_DECOMPOSE_MB sets the KQ scratch budget (default 256). // GGML_OPENCL_FA_KQ_P8=0 disables U8 probabilities and int8 KQV. // GGML_OPENCL_FA_KQV_DIRECT=0 disables direct PV for small query batches. +// GGML_OPENCL_FA_KQ_INT8=0 keeps F16 KQ; =1 enables int8 KQ for supported shapes. static bool ggml_cl_flash_attn_decompose_dispatch( ggml_backend_t backend, const ggml_tensor * q, const ggml_tensor * k, ggml_tensor * dst @@ -23537,12 +23835,46 @@ static bool ggml_cl_flash_attn_decompose_dispatch( return false; } + static const int kq_int8_env = [] { + const char * e = getenv("GGML_OPENCL_FA_KQ_INT8"); + return (e && e[0]) ? (e[0] != '0' ? 1 : 0) : -1; + }(); + static const int dk512_env = [] { + const char * e = getenv("GGML_OPENCL_FA_KQ_DK512_F16"); + return (e && e[0]) ? (e[0] != '0' ? 1 : 0) : -1; + }(); + const bool dk512 = dk > 256 && dk <= 512 && n_q >= 32 && + (dk512_env == 1 || (dk512_env < 0 && backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E)); + const bool kq_int8_possible = kq_p8 && (dk <= 256 || dk512) && dk % 32 == 0 && + backend_ctx->kernel_fa_q8_rows_f16 != nullptr && backend_ctx->kernel_fa_q8_rows_f32 != nullptr && + n_head <= INT_MAX && n_head_kv <= INT_MAX && + n_q <= INT_MAX / n_head / (dk / 32) && n_kv <= INT_MAX / n_head_kv / (dk / 32) && + (dst->src[4] == nullptr || dk > 64) && + (kq_int8_env == 1 || (kq_int8_env < 0 && backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && n_kv >= 2048)) && + backend_ctx->get_kernel_workgroup_size(backend_ctx->kernel_fa_q8_rows_f16) >= 64 && + backend_ctx->get_kernel_workgroup_size(backend_ctx->kernel_fa_q8_rows_f32) >= 64; + cl_kernel kq_int8_kernel = nullptr; + if (kq_int8_possible) { + kq_int8_kernel = dk <= 256 ? backend_ctx->kernel_mul_mm_q8_kq_p8 : backend_ctx->kernel_mul_mm_q8_kq_p8_dk512; + } + const bool kq_int8 = kq_int8_kernel != nullptr && backend_ctx->get_kernel_workgroup_size(kq_int8_kernel) >= 64; + + // Fewer query tiles per KV block reduce cache pressure in the int8 KQ kernel. + static const int64_t kq_int8_max_chunk = [] { + const char * e = getenv("GGML_OPENCL_FA_KQ_INT8_MAX_CHUNK"); + const int v = (e && e[0]) ? atoi(e) : 96; + return (int64_t) (v >= 32 ? (v / 32) * 32 : 96); + }(); + if (kq_int8) { + n_q_chunk = MIN(n_q_chunk, kq_int8_max_chunk); + } + // even out the chunks, then align to the 32-wide n-tile const int64_t n_chunks = (n_q + n_q_chunk - 1) / n_q_chunk; n_q_chunk = MIN(n_q_chunk, ((n_q + n_chunks - 1) / n_chunks + 31) & ~(int64_t) 31); if (kq_p8) { - ggml_cl_flash_attn_decompose_kq_p8(backend, q, k, dst, n_q_chunk, scale, max_bias, kqv_direct); + ggml_cl_flash_attn_decompose_kq_p8(backend, q, k, dst, n_q_chunk, scale, max_bias, kqv_direct, kq_int8); } else { ggml_cl_flash_attn_decompose(backend, q, k, dst, n_q_chunk, scale, max_bias); } @@ -25430,6 +25762,48 @@ static void ggml_cl_mul_mat_q2_0_f32_adreno(ggml_backend_t backend, const ggml_t CL_CHECK(clReleaseMemObject(b_sub_buf)); } +static bool ggml_cl_mul_mat_coopmat(ggml_backend_opencl_context * backend_ctx, cl_kernel kernel, + std::initializer_list weights, + const ggml_tensor * src1, ggml_tensor * dst, int K, int M, int N) { + if (kernel == nullptr || M % 64 != 0 || N < 2) { + return false; + } + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int n_tiles = CEIL_DIV(N, 64); + + backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, (size_t)n_tiles * 64 * K * sizeof(cl_half)); + + cl_kernel pk = backend_ctx->kernel_pack_b_f16_coopmat; + CL_CHECK(clSetKernelArg(pk, 0, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(pk, 1, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(pk, 2, sizeof(cl_mem), &backend_ctx->prealloc_act_trans.buffer)); + CL_CHECK(clSetKernelArg(pk, 3, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(pk, 4, sizeof(int), &N)); + size_t p_local[2] = { 64, 4 }; + size_t p_global[2] = { (size_t)n_tiles * 64, (size_t)CEIL_DIV(K, 64) * 4 }; + backend_ctx->enqueue_ndrange_kernel(pk, 2, p_global, p_local, dst); + + cl_uint ka = 0; + for (cl_mem w : weights) { + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(cl_mem), &w)); + } + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(cl_mem), &backend_ctx->prealloc_act_trans.buffer)); + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(int), &N)); + + size_t c_local[3] = { 64, 1, 4 }; + size_t c_global[3] = { 64, (size_t)(M / 64), (size_t)CEIL_DIV(n_tiles, 4) * 4 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, c_global, c_local, dst); + return true; +} + static void ggml_cl_mul_mat_q4_0_f32_adreno_ila(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { GGML_ASSERT(src0); @@ -25745,6 +26119,11 @@ static void ggml_cl_mul_mat_q4_0_f32_adreno(ggml_backend_t backend, const ggml_t const bool use_bin = use_q4_0_bin_kernels(backend_ctx, src0); + if (use_bin && ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q4_0_f32_coopmat, + { extra0_q4_0->q, extra0_q4_0->d }, src1, dst, K, M, N)) { + return; + } + if (use_bin) { if (use_q40_mc3) { static bool warned = false; @@ -26309,6 +26688,11 @@ static void ggml_cl_mul_mat_q5_0_f32_adreno(ggml_backend_t backend, const ggml_t int N = ne1; int K = ne00; + if (ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q5_0_f32_coopmat, + { extra0_q5_0->qs, extra0_q5_0->qh, extra0_q5_0->d }, src1, dst, K, M, N)) { + return; + } + if (ne1 == 1) { cl_mem qs_img = nullptr; cl_mem b_sub_buf = nullptr; @@ -27151,6 +27535,11 @@ static void ggml_cl_mul_mat_q8_0_f32_adreno(ggml_backend_t backend, const ggml_t int N = ne1; int K = ne00; + if (ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q8_0_f32_coopmat, + { extra0_q8_0->q, extra0_q8_0->d }, src1, dst, K, M, N)) { + return; + } + // Multi-column verify GEMV for ne1 2..4, reuses the ne1 == 1 image setup. // Default on for X2E, GGML_OPENCL_Q8_0_MC=0/1 forces it. static const char * q8_mc_env = getenv("GGML_OPENCL_Q8_0_MC"); @@ -28132,6 +28521,11 @@ static void ggml_cl_mul_mat_q4_k_f32_adreno(ggml_backend_t backend, const ggml_t const bool use_bin = use_q4_k_bin_kernels(backend_ctx, src0); + if (use_bin && ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q4_k_f32_coopmat, + { extra0_q4_k->q, extra0_q4_k->s, extra0_q4_k->d, extra0_q4_k->dm }, src1, dst, K, M, N)) { + return; + } + if (use_bin) { if (use_mc3) { static bool warned = false; @@ -29042,6 +29436,11 @@ static void ggml_cl_mul_mat_q6_K_f32_adreno(ggml_backend_t backend, const ggml_t const bool use_bin = use_q6_k_bin_kernels(backend_ctx, src0); + if (use_bin && ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q6_k_f32_coopmat, + { extra0_q6_K->ql, extra0_q6_K->qh, extra0_q6_K->s, extra0_q6_K->d }, src1, dst, ne00, ne01, ne1)) { + return; + } + if (use_bin) { if (use_q6k_mc3 || use_q6k_tiled_mc) { static bool warned = false; @@ -29782,6 +30181,11 @@ static void ggml_cl_mul_mat_q5_K_f32_adreno(ggml_backend_t backend, const ggml_t const bool use_bin = use_q5_k_bin_kernels(backend_ctx, src0); + if (use_bin && ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q5_k_f32_coopmat, + { extra0_q5_k->q, extra0_q5_k->qh, extra0_q5_k->s, extra0_q5_k->d, extra0_q5_k->dm }, src1, dst, K, M, N)) { + return; + } + if (use_bin) { if (use_q5k_mc3) { static bool warned = false; diff --git a/ggml/src/ggml-opencl/kernels/flash_attn_q8_rows.cl b/ggml/src/ggml-opencl/kernels/flash_attn_q8_rows.cl new file mode 100644 index 000000000000..f0eda2539bcd --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/flash_attn_q8_rows.cl @@ -0,0 +1,77 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable + +// Store 32-element blocks as separate int8 values and half scales. + +kernel void kernel_fa_q8_rows_f16( + global const char * src, ulong off_src, ulong nb1, ulong nb2, + global char * dq, global half * dd, + int ne0, int nrow, int nhead +) { + const int nblk = ne0 / 32; + const int gid = get_global_id(0); + if (gid >= nblk*nrow*nhead) { + return; + } + const int b = gid % nblk; + const int r = (gid / nblk) % nrow; + const int h = gid / (nblk*nrow); + + global const half * p = (global const half *)(src + off_src + (ulong)h*nb2 + (ulong)r*nb1) + b*32; + float v[32]; + float amax = 0.0f; + #pragma unroll + for (int i = 0; i < 8; ++i) { + const float4 x = convert_float4(vload4(i, p)); + v[i*4+0] = x.s0; + v[i*4+1] = x.s1; + v[i*4+2] = x.s2; + v[i*4+3] = x.s3; + amax = fmax(amax, fmax(fmax(fabs(x.s0), fabs(x.s1)), fmax(fabs(x.s2), fabs(x.s3)))); + } + const float d = amax / 127.0f; + const float id = amax > 0.0f ? 127.0f / amax : 0.0f; + const size_t row = (size_t)h*nrow + r; + dd[row*nblk + b] = (half)d; + global char * q = dq + row*ne0 + b*32; + #pragma unroll + for (int i = 0; i < 32; ++i) { + q[i] = (char)clamp((int)rint(v[i]*id), -127, 127); + } +} + +kernel void kernel_fa_q8_rows_f32( + global const char * src, ulong off_src, ulong nb1, ulong nb2, + global char * dq, global half * dd, + int ne0, int nrow, int nhead +) { + const int nblk = ne0 / 32; + const int gid = get_global_id(0); + if (gid >= nblk*nrow*nhead) { + return; + } + const int b = gid % nblk; + const int r = (gid / nblk) % nrow; + const int h = gid / (nblk*nrow); + + global const float * p = (global const float *)(src + off_src + (ulong)h*nb2 + (ulong)r*nb1) + b*32; + float v[32]; + float amax = 0.0f; + #pragma unroll + for (int i = 0; i < 8; ++i) { + const float4 x = vload4(i, p); + v[i*4+0] = x.s0; + v[i*4+1] = x.s1; + v[i*4+2] = x.s2; + v[i*4+3] = x.s3; + amax = fmax(amax, fmax(fmax(fabs(x.s0), fabs(x.s1)), fmax(fabs(x.s2), fabs(x.s3)))); + } + const float d = amax / 127.0f; + const float id = amax > 0.0f ? 127.0f / amax : 0.0f; + const size_t row = (size_t)h*nrow + r; + dd[row*nblk + b] = (half)d; + global char * q = dq + row*ne0 + b*32; + #pragma unroll + for (int i = 0; i < 32; ++i) { + q[i] = (char)clamp((int)rint(v[i]*id), -127, 127); + } +} diff --git a/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q4_0_f32_coopmat.cl b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q4_0_f32_coopmat.cl new file mode 100644 index 000000000000..56210a1ad814 --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q4_0_f32_coopmat.cl @@ -0,0 +1,145 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_qcom_kernel_cooperative_matrix : enable + +// Q4_0 x F32 GEMM with cl_qcom_kernel_cooperative_matrix: one 64x64 f16 C tile per wave, +// A dequantized in registers, B packed by kernel_pack_b_f16_coopmat. + +typedef half mat_a_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 16, CLK_COOPERATIVE_MATRIX_A_QCOM))); +typedef half mat_b_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 16, 64, CLK_COOPERATIVE_MATRIX_B_QCOM))); +typedef half mat_c_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 64, CLK_COOPERATIVE_MATRIX_ACCUMULATOR_QCOM))); + +typedef half half1024 __attribute__((ext_vector_type(1024))); +typedef half half4096 __attribute__((ext_vector_type(4096))); + +typedef union { + half1024 v; + half16 h; +} a_row_t; + +typedef union { + half4096 v; + struct { + half16 h0; + half16 h1; + half16 h2; + half16 h3; + } s; +} c_row_t; + +inline half8 dequant8(uint v, half d) { + uint4 t; + t.s0 = ( v & 0x000F) | ((v << 12) & 0x000F0000); + t.s1 = ((v >> 8) & 0x000F) | ((v << 4) & 0x000F0000); + t.s2 = ((v >> 16) & 0x000F) | ((v >> 4) & 0x000F0000); + t.s3 = ((v >> 24) & 0x000F) | ((v >> 12) & 0x000F0000); + t |= (uint4)(0x64006400); + + return (as_half8(t) - (half8)(1032.0h)) * d; +} + +inline void store_c16(global float * p, half16 h, int j0, int nv, int M) { + float16 f = convert_float16(h); + if (j0 + 0 < nv) p[(ulong)(j0 + 0) * M] = f.s0; + if (j0 + 1 < nv) p[(ulong)(j0 + 1) * M] = f.s1; + if (j0 + 2 < nv) p[(ulong)(j0 + 2) * M] = f.s2; + if (j0 + 3 < nv) p[(ulong)(j0 + 3) * M] = f.s3; + if (j0 + 4 < nv) p[(ulong)(j0 + 4) * M] = f.s4; + if (j0 + 5 < nv) p[(ulong)(j0 + 5) * M] = f.s5; + if (j0 + 6 < nv) p[(ulong)(j0 + 6) * M] = f.s6; + if (j0 + 7 < nv) p[(ulong)(j0 + 7) * M] = f.s7; + if (j0 + 8 < nv) p[(ulong)(j0 + 8) * M] = f.s8; + if (j0 + 9 < nv) p[(ulong)(j0 + 9) * M] = f.s9; + if (j0 + 10 < nv) p[(ulong)(j0 + 10) * M] = f.sa; + if (j0 + 11 < nv) p[(ulong)(j0 + 11) * M] = f.sb; + if (j0 + 12 < nv) p[(ulong)(j0 + 12) * M] = f.sc; + if (j0 + 13 < nv) p[(ulong)(j0 + 13) * M] = f.sd; + if (j0 + 14 < nv) p[(ulong)(j0 + 14) * M] = f.se; + if (j0 + 15 < nv) p[(ulong)(j0 + 15) * M] = f.sf; +} + +#define LOAD_Q(qv, dd, o) { \ + qv.s0 = qp[(4 * (o) + 0) * M]; \ + qv.s1 = qp[(4 * (o) + 1) * M]; \ + qv.s2 = qp[(4 * (o) + 2) * M]; \ + qv.s3 = qp[(4 * (o) + 3) * M]; \ + dd = dp[(o) * M]; } + +#define MMA_K32(qv, dd, b) { \ + a_row_t ua0; \ + a_row_t ua1; \ + ua0.h = (half16)(dequant8(qv.s0, dd), dequant8(qv.s1, dd)); \ + ua1.h = (half16)(dequant8(qv.s2, dd), dequant8(qv.s3, dd)); \ + mat_a_t a0 = __builtin_astype(ua0.v, mat_a_t); \ + mat_a_t a1 = __builtin_astype(ua1.v, mat_a_t); \ + mat_b_t b0 = qcom_coop_mat_load((b), CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + mat_b_t b1 = qcom_coop_mat_load((b) + 1024, CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + acc = qcom_coop_mat_mulAdd(a0, b0, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); \ + acc = qcom_coop_mat_mulAdd(a1, b1, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); } + +kernel void kernel_gemm_noshuffle_q4_0_f32_coopmat( + global const uint * src0_q, // A: q4_0 quants, [K/8][M] u32 + global const half * src0_d, // A: q4_0 scales, [K/32][M] f16 + global const half * src1, // B: packed f16 tiles + global char * dst, // C: [N][M] f32 + ulong offsetd, + int K, + int M, + int N +) { + const int lane = get_local_id(0); + const int row = get_global_id(1) * 64; + const int tn = get_global_id(2); + const int n_tiles = (N + 63) / 64; + + if (tn >= n_tiles) { + return; + } + + global const uint * qp = src0_q + row + lane; + global const half * dp = src0_d + row + lane; + global const half * bp = src1 + (ulong)tn * (K / 16) * 1024; + + mat_c_t acc = qcom_coop_mat_init(0.0); + + { + const int odd = (K / 32) & 1; + const int ob = odd ? 0 : 1; + uint4 qa; + uint4 qb; + half da; + half db; + LOAD_Q(qa, da, 0) + LOAD_Q(qb, db, ob) + da = odd ? 0.0h : da; + MMA_K32(qa, da, bp) + MMA_K32(qb, db, bp + ob * 2048) + qp += (ob + 1) * 4 * M; + dp += (ob + 1) * M; + bp += (ob + 1) * 2048; + } + +#pragma unroll 1 + for (int k0 = (K / 32) & 1 ? 32 : 64; k0 < K; k0 += 64) { + uint4 qa; + uint4 qb; + half da; + half db; + LOAD_Q(qa, da, 0) + LOAD_Q(qb, db, 1) + MMA_K32(qa, da, bp) + MMA_K32(qb, db, bp + 2048) + qp += 8 * M; + dp += 2 * M; + bp += 4096; + } + + c_row_t uc; + uc.v = __builtin_astype(acc, half4096); + + global float * p = (global float *)(dst + offsetd) + (ulong)tn * 64 * M + row + lane; + const int nv = N - tn * 64; + store_c16(p, uc.s.h0, 0, nv, M); + store_c16(p, uc.s.h1, 16, nv, M); + store_c16(p, uc.s.h2, 32, nv, M); + store_c16(p, uc.s.h3, 48, nv, M); +} diff --git a/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q4_k_f32_coopmat.cl b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q4_k_f32_coopmat.cl new file mode 100644 index 000000000000..65f29309f8ab --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q4_k_f32_coopmat.cl @@ -0,0 +1,148 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_qcom_kernel_cooperative_matrix : enable + +// Q4_K x F32 GEMM with cl_qcom_kernel_cooperative_matrix: one 64x64 f16 C tile per wave, +// A dequantized in registers, B packed by kernel_pack_b_f16_coopmat. + +#define K_SCALE_SIZE 12 + +typedef half mat_a_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 16, CLK_COOPERATIVE_MATRIX_A_QCOM))); +typedef half mat_b_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 16, 64, CLK_COOPERATIVE_MATRIX_B_QCOM))); +typedef half mat_c_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 64, CLK_COOPERATIVE_MATRIX_ACCUMULATOR_QCOM))); + +typedef half half1024 __attribute__((ext_vector_type(1024))); +typedef half half4096 __attribute__((ext_vector_type(4096))); + +typedef union { + half1024 v; + half16 h; +} a_row_t; + +typedef union { + half4096 v; + struct { + half16 h0; + half16 h1; + half16 h2; + half16 h3; + } s; +} c_row_t; + +inline half8 dequant8(uint v, half scale, half nminv) { + uint4 t; + t.s0 = ( v & 0x000F) | ((v << 12) & 0x000F0000); + t.s1 = ((v >> 8) & 0x000F) | ((v << 4) & 0x000F0000); + t.s2 = ((v >> 16) & 0x000F) | ((v >> 4) & 0x000F0000); + t.s3 = ((v >> 24) & 0x000F) | ((v >> 12) & 0x000F0000); + t |= (uint4)(0x64006400); + + return (as_half8(t) - (half8)(1024.0h)) * scale + nminv; +} + +inline void store_c16(global float * p, half16 h, int j0, int nv, int M) { + float16 f = convert_float16(h); + if (j0 + 0 < nv) p[(ulong)(j0 + 0) * M] = f.s0; + if (j0 + 1 < nv) p[(ulong)(j0 + 1) * M] = f.s1; + if (j0 + 2 < nv) p[(ulong)(j0 + 2) * M] = f.s2; + if (j0 + 3 < nv) p[(ulong)(j0 + 3) * M] = f.s3; + if (j0 + 4 < nv) p[(ulong)(j0 + 4) * M] = f.s4; + if (j0 + 5 < nv) p[(ulong)(j0 + 5) * M] = f.s5; + if (j0 + 6 < nv) p[(ulong)(j0 + 6) * M] = f.s6; + if (j0 + 7 < nv) p[(ulong)(j0 + 7) * M] = f.s7; + if (j0 + 8 < nv) p[(ulong)(j0 + 8) * M] = f.s8; + if (j0 + 9 < nv) p[(ulong)(j0 + 9) * M] = f.s9; + if (j0 + 10 < nv) p[(ulong)(j0 + 10) * M] = f.sa; + if (j0 + 11 < nv) p[(ulong)(j0 + 11) * M] = f.sb; + if (j0 + 12 < nv) p[(ulong)(j0 + 12) * M] = f.sc; + if (j0 + 13 < nv) p[(ulong)(j0 + 13) * M] = f.sd; + if (j0 + 14 < nv) p[(ulong)(j0 + 14) * M] = f.se; + if (j0 + 15 < nv) p[(ulong)(j0 + 15) * M] = f.sf; +} + +#define MMA_K32(q0, q1, q2, q3, sc, nm, b) { \ + a_row_t ua0; \ + a_row_t ua1; \ + ua0.h = (half16)(dequant8(q0, sc, nm), dequant8(q1, sc, nm)); \ + ua1.h = (half16)(dequant8(q2, sc, nm), dequant8(q3, sc, nm)); \ + mat_a_t a0 = __builtin_astype(ua0.v, mat_a_t); \ + mat_a_t a1 = __builtin_astype(ua1.v, mat_a_t); \ + mat_b_t b0 = qcom_coop_mat_load((b), CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + mat_b_t b1 = qcom_coop_mat_load((b) + 1024, CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + acc = qcom_coop_mat_mulAdd(a0, b0, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); \ + acc = qcom_coop_mat_mulAdd(a1, b1, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); } + +#define STEP64(sa, na, sb_, nb_) { \ + uint8 qv; \ + qv.s0 = qp[0]; \ + qv.s1 = qp[M]; \ + qv.s2 = qp[2 * M]; \ + qv.s3 = qp[3 * M]; \ + qv.s4 = qp[4 * M]; \ + qv.s5 = qp[5 * M]; \ + qv.s6 = qp[6 * M]; \ + qv.s7 = qp[7 * M]; \ + qp += 8 * M; \ + MMA_K32(qv.s0, qv.s1, qv.s2, qv.s3, sa, na, bp) \ + MMA_K32(qv.s4, qv.s5, qv.s6, qv.s7, sb_, nb_, bp + 2048) \ + bp += 4096; } + +kernel void kernel_gemm_noshuffle_q4_k_f32_coopmat( + global const uint * src0_q, // A: q4_K quants, [K/8][M] u32 + global const uchar * src0_s, // A: 6-bit scale/min codes, [K/256*12][M] u8 + global const half * src0_d, // A: per-superblock scale, [K/256][M] f16 + global const half * src0_dm, // A: per-superblock min, [K/256][M] f16 + global const half * src1, // B: packed f16 tiles + global char * dst, // C: [N][M] f32 + ulong offsetd, + int K, + int M, + int N +) { + const int lane = get_local_id(0); + const int row = get_global_id(1) * 64; + const int tn = get_global_id(2); + const int n_tiles = (N + 63) / 64; + + if (tn >= n_tiles) { + return; + } + + const int lrow = row + lane; + + global const uint * qp = src0_q + lrow; + global const half * bp = src1 + (ulong)tn * (K / 16) * 1024; + + mat_c_t acc = qcom_coop_mat_init(0.0); + +#pragma unroll 1 + for (int k0 = 0; k0 < K; k0 += 128) { + const int sb = k0 >> 8; + const half dd = src0_d [(ulong)sb * M + lrow]; + const half dmm = src0_dm[(ulong)sb * M + lrow]; + + global const uchar * sp = src0_s + (ulong)(sb * K_SCALE_SIZE) * M + lrow; + const uchar4 c0 = (uchar4)(sp[0], sp[M], sp[2 * M], sp[3 * M]); + const uchar4 c1 = (uchar4)(sp[4 * M], sp[5 * M], sp[6 * M], sp[7 * M]); + const uchar4 c2 = (uchar4)(sp[8 * M], sp[9 * M], sp[10 * M], sp[11 * M]); + const uchar4 sl = c0 & (uchar)0x3F; + const uchar4 ml = c1 & (uchar)0x3F; + const uchar4 sh = (c2 & (uchar)0x0F) | ((c0 >> (uchar)2) & (uchar)0x30); + const uchar4 mh = (c2 >> (uchar)4) | ((c1 >> (uchar)2) & (uchar)0x30); + const int hi = (k0 >> 7) & 1; + const half4 S = dd * convert_half4(hi ? sh : sl); + const half4 Nm = -(dmm * convert_half4(hi ? mh : ml)); + + STEP64(S.s0, Nm.s0, S.s1, Nm.s1) + STEP64(S.s2, Nm.s2, S.s3, Nm.s3) + } + + c_row_t uc; + uc.v = __builtin_astype(acc, half4096); + + global float * p = (global float *)(dst + offsetd) + (ulong)tn * 64 * M + row + lane; + const int nv = N - tn * 64; + store_c16(p, uc.s.h0, 0, nv, M); + store_c16(p, uc.s.h1, 16, nv, M); + store_c16(p, uc.s.h2, 32, nv, M); + store_c16(p, uc.s.h3, 48, nv, M); +} diff --git a/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q5_0_f32_coopmat.cl b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q5_0_f32_coopmat.cl new file mode 100644 index 000000000000..1880a86f0e2c --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q5_0_f32_coopmat.cl @@ -0,0 +1,157 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_qcom_kernel_cooperative_matrix : enable + +// Q5_0 x F32 GEMM with cl_qcom_kernel_cooperative_matrix: one 64x64 f16 C tile per wave, +// A dequantized in registers, B packed by kernel_pack_b_f16_coopmat. + +typedef half mat_a_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 16, CLK_COOPERATIVE_MATRIX_A_QCOM))); +typedef half mat_b_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 16, 64, CLK_COOPERATIVE_MATRIX_B_QCOM))); +typedef half mat_c_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 64, CLK_COOPERATIVE_MATRIX_ACCUMULATOR_QCOM))); + +typedef half half1024 __attribute__((ext_vector_type(1024))); +typedef half half4096 __attribute__((ext_vector_type(4096))); + +typedef union { + half1024 v; + half16 h; +} a_row_t; + +typedef union { + half4096 v; + struct { + half16 h0; + half16 h1; + half16 h2; + half16 h3; + } s; +} c_row_t; + +inline half8 dequant8(uint v, uint h, half d) { + uint4 t; + t.s0 = ( v & 0x000F) | ((v << 12) & 0x000F0000) | ((h << 4) & 0x0010) | ((h << 19) & 0x00100000); + t.s1 = ((v >> 8) & 0x000F) | ((v << 4) & 0x000F0000) | ((h << 2) & 0x0010) | ((h << 17) & 0x00100000); + t.s2 = ((v >> 16) & 0x000F) | ((v >> 4) & 0x000F0000) | ( h & 0x0010) | ((h << 15) & 0x00100000); + t.s3 = ((v >> 24) & 0x000F) | ((v >> 12) & 0x000F0000) | ((h >> 2) & 0x0010) | ((h << 13) & 0x00100000); + t |= (uint4)(0x64006400); + + return (as_half8(t) - (half8)(1040.0h)) * d; +} + +inline void store_c16(global float * p, half16 h, int j0, int nv, int M) { + float16 f = convert_float16(h); + if (j0 + 0 < nv) p[(ulong)(j0 + 0) * M] = f.s0; + if (j0 + 1 < nv) p[(ulong)(j0 + 1) * M] = f.s1; + if (j0 + 2 < nv) p[(ulong)(j0 + 2) * M] = f.s2; + if (j0 + 3 < nv) p[(ulong)(j0 + 3) * M] = f.s3; + if (j0 + 4 < nv) p[(ulong)(j0 + 4) * M] = f.s4; + if (j0 + 5 < nv) p[(ulong)(j0 + 5) * M] = f.s5; + if (j0 + 6 < nv) p[(ulong)(j0 + 6) * M] = f.s6; + if (j0 + 7 < nv) p[(ulong)(j0 + 7) * M] = f.s7; + if (j0 + 8 < nv) p[(ulong)(j0 + 8) * M] = f.s8; + if (j0 + 9 < nv) p[(ulong)(j0 + 9) * M] = f.s9; + if (j0 + 10 < nv) p[(ulong)(j0 + 10) * M] = f.sa; + if (j0 + 11 < nv) p[(ulong)(j0 + 11) * M] = f.sb; + if (j0 + 12 < nv) p[(ulong)(j0 + 12) * M] = f.sc; + if (j0 + 13 < nv) p[(ulong)(j0 + 13) * M] = f.sd; + if (j0 + 14 < nv) p[(ulong)(j0 + 14) * M] = f.se; + if (j0 + 15 < nv) p[(ulong)(j0 + 15) * M] = f.sf; +} + +#define LOAD_Q(qv, hv, dd, o) { \ + qv.s0 = (uint)qp[(8 * (o) + 0) * M] | ((uint)qp[(8 * (o) + 1) * M] << 16); \ + qv.s1 = (uint)qp[(8 * (o) + 2) * M] | ((uint)qp[(8 * (o) + 3) * M] << 16); \ + qv.s2 = (uint)qp[(8 * (o) + 4) * M] | ((uint)qp[(8 * (o) + 5) * M] << 16); \ + qv.s3 = (uint)qp[(8 * (o) + 6) * M] | ((uint)qp[(8 * (o) + 7) * M] << 16); \ + hv.s0 = hp[(4 * (o) + 0) * M]; \ + hv.s1 = hp[(4 * (o) + 1) * M]; \ + hv.s2 = hp[(4 * (o) + 2) * M]; \ + hv.s3 = hp[(4 * (o) + 3) * M]; \ + dd = dp[(o) * M]; } + +#define MMA_K32(qv, hv, dd, b) { \ + a_row_t ua0; \ + a_row_t ua1; \ + ua0.h = (half16)(dequant8(qv.s0, hv.s0, dd), dequant8(qv.s1, hv.s1, dd)); \ + ua1.h = (half16)(dequant8(qv.s2, hv.s2, dd), dequant8(qv.s3, hv.s3, dd)); \ + mat_a_t a0 = __builtin_astype(ua0.v, mat_a_t); \ + mat_a_t a1 = __builtin_astype(ua1.v, mat_a_t); \ + mat_b_t b0 = qcom_coop_mat_load((b), CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + mat_b_t b1 = qcom_coop_mat_load((b) + 1024, CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + acc = qcom_coop_mat_mulAdd(a0, b0, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); \ + acc = qcom_coop_mat_mulAdd(a1, b1, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); } + +kernel void kernel_gemm_noshuffle_q5_0_f32_coopmat( + global const ushort * src0_q, // A: q5_0 quants, [K/4][M] u16 + global const uchar * src0_qh, // A: q5_0 high bits, [K/8][M] u8 + global const half * src0_d, // A: q5_0 scales, [K/32][M] f16 + global const half * src1, // B: packed f16 tiles + global char * dst, // C: [N][M] f32 + ulong offsetd, + int K, + int M, + int N +) { + const int lane = get_local_id(0); + const int row = get_global_id(1) * 64; + const int tn = get_global_id(2); + const int n_tiles = (N + 63) / 64; + + if (tn >= n_tiles) { + return; + } + + global const ushort * qp = src0_q + row + lane; + global const uchar * hp = src0_qh + row + lane; + global const half * dp = src0_d + row + lane; + global const half * bp = src1 + (ulong)tn * (K / 16) * 1024; + + mat_c_t acc = qcom_coop_mat_init(0.0); + + { + const int odd = (K / 32) & 1; + const int ob = odd ? 0 : 1; + uint4 qa; + uint4 qb; + uint4 ha; + uint4 hb; + half da; + half db; + LOAD_Q(qa, ha, da, 0) + LOAD_Q(qb, hb, db, ob) + da = odd ? 0.0h : da; + MMA_K32(qa, ha, da, bp) + MMA_K32(qb, hb, db, bp + ob * 2048) + qp += (ob + 1) * 8 * M; + hp += (ob + 1) * 4 * M; + dp += (ob + 1) * M; + bp += (ob + 1) * 2048; + } + +#pragma unroll 1 + for (int k0 = (K / 32) & 1 ? 32 : 64; k0 < K; k0 += 64) { + uint4 qa; + uint4 qb; + uint4 ha; + uint4 hb; + half da; + half db; + LOAD_Q(qa, ha, da, 0) + LOAD_Q(qb, hb, db, 1) + MMA_K32(qa, ha, da, bp) + MMA_K32(qb, hb, db, bp + 2048) + qp += 16 * M; + hp += 8 * M; + dp += 2 * M; + bp += 4096; + } + + c_row_t uc; + uc.v = __builtin_astype(acc, half4096); + + global float * p = (global float *)(dst + offsetd) + (ulong)tn * 64 * M + row + lane; + const int nv = N - tn * 64; + store_c16(p, uc.s.h0, 0, nv, M); + store_c16(p, uc.s.h1, 16, nv, M); + store_c16(p, uc.s.h2, 32, nv, M); + store_c16(p, uc.s.h3, 48, nv, M); +} diff --git a/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q5_k_f32_coopmat.cl b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q5_k_f32_coopmat.cl new file mode 100644 index 000000000000..2b4f11780a57 --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q5_k_f32_coopmat.cl @@ -0,0 +1,164 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_qcom_kernel_cooperative_matrix : enable + +// Q5_K x F32 GEMM with cl_qcom_kernel_cooperative_matrix: one 64x64 f16 C tile per wave, +// A dequantized in registers, B packed by kernel_pack_b_f16_coopmat. + +#define K_SCALE_SIZE 12 + +typedef half mat_a_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 16, CLK_COOPERATIVE_MATRIX_A_QCOM))); +typedef half mat_b_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 16, 64, CLK_COOPERATIVE_MATRIX_B_QCOM))); +typedef half mat_c_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 64, CLK_COOPERATIVE_MATRIX_ACCUMULATOR_QCOM))); + +typedef half half1024 __attribute__((ext_vector_type(1024))); +typedef half half4096 __attribute__((ext_vector_type(4096))); + +typedef union { + half1024 v; + half16 h; +} a_row_t; + +typedef union { + half4096 v; + struct { + half16 h0; + half16 h1; + half16 h2; + half16 h3; + } s; +} c_row_t; + +inline half8 dequant8(uint v, uint h, half scale, half nminv) { + uint4 t; + t.s0 = ( v & 0x000F) | ((v << 12) & 0x000F0000); + t.s1 = ((v >> 8) & 0x000F) | ((v << 4) & 0x000F0000); + t.s2 = ((v >> 16) & 0x000F) | ((v >> 4) & 0x000F0000); + t.s3 = ((v >> 24) & 0x000F) | ((v >> 12) & 0x000F0000); + t.s0 |= ((h & 0x01u) << 4) | ((h & 0x02u) << 19); + t.s1 |= ((h & 0x04u) << 2) | ((h & 0x08u) << 17); + t.s2 |= ( h & 0x10u ) | ((h & 0x20u) << 15); + t.s3 |= ((h & 0x40u) >> 2) | ((h & 0x80u) << 13); + t |= (uint4)(0x64006400); + + return (as_half8(t) - (half8)(1024.0h)) * scale + nminv; +} + +inline void store_c16(global float * p, half16 h, int j0, int nv, int M) { + float16 f = convert_float16(h); + if (j0 + 0 < nv) p[(ulong)(j0 + 0) * M] = f.s0; + if (j0 + 1 < nv) p[(ulong)(j0 + 1) * M] = f.s1; + if (j0 + 2 < nv) p[(ulong)(j0 + 2) * M] = f.s2; + if (j0 + 3 < nv) p[(ulong)(j0 + 3) * M] = f.s3; + if (j0 + 4 < nv) p[(ulong)(j0 + 4) * M] = f.s4; + if (j0 + 5 < nv) p[(ulong)(j0 + 5) * M] = f.s5; + if (j0 + 6 < nv) p[(ulong)(j0 + 6) * M] = f.s6; + if (j0 + 7 < nv) p[(ulong)(j0 + 7) * M] = f.s7; + if (j0 + 8 < nv) p[(ulong)(j0 + 8) * M] = f.s8; + if (j0 + 9 < nv) p[(ulong)(j0 + 9) * M] = f.s9; + if (j0 + 10 < nv) p[(ulong)(j0 + 10) * M] = f.sa; + if (j0 + 11 < nv) p[(ulong)(j0 + 11) * M] = f.sb; + if (j0 + 12 < nv) p[(ulong)(j0 + 12) * M] = f.sc; + if (j0 + 13 < nv) p[(ulong)(j0 + 13) * M] = f.sd; + if (j0 + 14 < nv) p[(ulong)(j0 + 14) * M] = f.se; + if (j0 + 15 < nv) p[(ulong)(j0 + 15) * M] = f.sf; +} + +#define MMA_K32(q0, q1, q2, q3, h0_, h1_, h2_, h3_, sc, nm, b) { \ + a_row_t ua0; \ + a_row_t ua1; \ + ua0.h = (half16)(dequant8(q0, h0_, sc, nm), dequant8(q1, h1_, sc, nm)); \ + ua1.h = (half16)(dequant8(q2, h2_, sc, nm), dequant8(q3, h3_, sc, nm)); \ + mat_a_t a0 = __builtin_astype(ua0.v, mat_a_t); \ + mat_a_t a1 = __builtin_astype(ua1.v, mat_a_t); \ + mat_b_t b0 = qcom_coop_mat_load((b), CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + mat_b_t b1 = qcom_coop_mat_load((b) + 1024, CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + acc = qcom_coop_mat_mulAdd(a0, b0, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); \ + acc = qcom_coop_mat_mulAdd(a1, b1, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); } + +#define STEP64(sa, na, sb_, nb_) { \ + uint8 qv; \ + qv.s0 = qp[0]; \ + qv.s1 = qp[M]; \ + qv.s2 = qp[2 * M]; \ + qv.s3 = qp[3 * M]; \ + qv.s4 = qp[4 * M]; \ + qv.s5 = qp[5 * M]; \ + qv.s6 = qp[6 * M]; \ + qv.s7 = qp[7 * M]; \ + qp += 8 * M; \ + uint8 hv; \ + hv.s0 = qhp[0]; \ + hv.s1 = qhp[M]; \ + hv.s2 = qhp[2 * M]; \ + hv.s3 = qhp[3 * M]; \ + hv.s4 = qhp[4 * M]; \ + hv.s5 = qhp[5 * M]; \ + hv.s6 = qhp[6 * M]; \ + hv.s7 = qhp[7 * M]; \ + qhp += 8 * M; \ + MMA_K32(qv.s0, qv.s1, qv.s2, qv.s3, hv.s0, hv.s1, hv.s2, hv.s3, sa, na, bp) \ + MMA_K32(qv.s4, qv.s5, qv.s6, qv.s7, hv.s4, hv.s5, hv.s6, hv.s7, sb_, nb_, bp + 2048) \ + bp += 4096; } + +kernel void kernel_gemm_noshuffle_q5_k_f32_coopmat( + global const uint * src0_q, // A: q5_K low nibbles, [K/8][M] u32 + global const uchar * src0_qh, // A: q5_K high bits, [K/8][M] u8 + global const uchar * src0_s, // A: 6-bit scale/min codes, [K/256*12][M] u8 + global const half * src0_d, // A: per-superblock scale, [K/256][M] f16 + global const half * src0_dm, // A: per-superblock min, [K/256][M] f16 + global const half * src1, // B: packed f16 tiles + global char * dst, // C: [N][M] f32 + ulong offsetd, + int K, + int M, + int N +) { + const int lane = get_local_id(0); + const int row = get_global_id(1) * 64; + const int tn = get_global_id(2); + const int n_tiles = (N + 63) / 64; + + if (tn >= n_tiles) { + return; + } + + const int lrow = row + lane; + + global const uint * qp = src0_q + lrow; + global const uchar * qhp = src0_qh + lrow; + global const half * bp = src1 + (ulong)tn * (K / 16) * 1024; + + mat_c_t acc = qcom_coop_mat_init(0.0); + +#pragma unroll 1 + for (int k0 = 0; k0 < K; k0 += 128) { + const int sb = k0 >> 8; + const half dd = src0_d [(ulong)sb * M + lrow]; + const half dmm = src0_dm[(ulong)sb * M + lrow]; + + global const uchar * sp = src0_s + (ulong)(sb * K_SCALE_SIZE) * M + lrow; + const uchar4 c0 = (uchar4)(sp[0], sp[M], sp[2 * M], sp[3 * M]); + const uchar4 c1 = (uchar4)(sp[4 * M], sp[5 * M], sp[6 * M], sp[7 * M]); + const uchar4 c2 = (uchar4)(sp[8 * M], sp[9 * M], sp[10 * M], sp[11 * M]); + const uchar4 sl = c0 & (uchar)0x3F; + const uchar4 ml = c1 & (uchar)0x3F; + const uchar4 sh = (c2 & (uchar)0x0F) | ((c0 >> (uchar)2) & (uchar)0x30); + const uchar4 mh = (c2 >> (uchar)4) | ((c1 >> (uchar)2) & (uchar)0x30); + const int hi = (k0 >> 7) & 1; + const half4 S = dd * convert_half4(hi ? sh : sl); + const half4 Nm = -(dmm * convert_half4(hi ? mh : ml)); + + STEP64(S.s0, Nm.s0, S.s1, Nm.s1) + STEP64(S.s2, Nm.s2, S.s3, Nm.s3) + } + + c_row_t uc; + uc.v = __builtin_astype(acc, half4096); + + global float * p = (global float *)(dst + offsetd) + (ulong)tn * 64 * M + row + lane; + const int nv = N - tn * 64; + store_c16(p, uc.s.h0, 0, nv, M); + store_c16(p, uc.s.h1, 16, nv, M); + store_c16(p, uc.s.h2, 32, nv, M); + store_c16(p, uc.s.h3, 48, nv, M); +} diff --git a/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q6_k_f32_coopmat.cl b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q6_k_f32_coopmat.cl new file mode 100644 index 000000000000..5c517f94db07 --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q6_k_f32_coopmat.cl @@ -0,0 +1,145 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_qcom_kernel_cooperative_matrix : enable + +// Q6_K x F32 GEMM with cl_qcom_kernel_cooperative_matrix: one 64x64 f16 C tile per wave, +// A dequantized in registers, B packed by kernel_pack_b_f16_coopmat. + +typedef half mat_a_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 16, CLK_COOPERATIVE_MATRIX_A_QCOM))); +typedef half mat_b_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 16, 64, CLK_COOPERATIVE_MATRIX_B_QCOM))); +typedef half mat_c_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 64, CLK_COOPERATIVE_MATRIX_ACCUMULATOR_QCOM))); + +typedef half half1024 __attribute__((ext_vector_type(1024))); +typedef half half4096 __attribute__((ext_vector_type(4096))); + +typedef union { + half1024 v; + half16 h; +} a_row_t; + +typedef union { + half4096 v; + struct { + half16 h0; + half16 h1; + half16 h2; + half16 h3; + } s; +} c_row_t; + +inline half8 dequant8(uint v, uint hh, half scale) { + uint4 t; + t.s0 = ( v & 0x000F) | ((v << 12) & 0x000F0000); + t.s1 = ((v >> 8) & 0x000F) | ((v << 4) & 0x000F0000); + t.s2 = ((v >> 16) & 0x000F) | ((v >> 4) & 0x000F0000); + t.s3 = ((v >> 24) & 0x000F) | ((v >> 12) & 0x000F0000); + t.s0 |= ((hh & 0x0003u) << 4) | ((hh & 0x000Cu) << 18); + t.s1 |= ( hh & 0x0030u ) | ((hh & 0x00C0u) << 14); + t.s2 |= ((hh & 0x0300u) >> 4) | ((hh & 0x0C00u) << 10); + t.s3 |= ((hh & 0x3000u) >> 8) | ((hh & 0xC000u) << 6); + t |= (uint4)(0x64006400); + + return (as_half8(t) - (half8)(1056.0h)) * scale; +} + +inline void store_c16(global float * p, half16 h, int j0, int nv, int M) { + float16 f = convert_float16(h); + if (j0 + 0 < nv) p[(ulong)(j0 + 0) * M] = f.s0; + if (j0 + 1 < nv) p[(ulong)(j0 + 1) * M] = f.s1; + if (j0 + 2 < nv) p[(ulong)(j0 + 2) * M] = f.s2; + if (j0 + 3 < nv) p[(ulong)(j0 + 3) * M] = f.s3; + if (j0 + 4 < nv) p[(ulong)(j0 + 4) * M] = f.s4; + if (j0 + 5 < nv) p[(ulong)(j0 + 5) * M] = f.s5; + if (j0 + 6 < nv) p[(ulong)(j0 + 6) * M] = f.s6; + if (j0 + 7 < nv) p[(ulong)(j0 + 7) * M] = f.s7; + if (j0 + 8 < nv) p[(ulong)(j0 + 8) * M] = f.s8; + if (j0 + 9 < nv) p[(ulong)(j0 + 9) * M] = f.s9; + if (j0 + 10 < nv) p[(ulong)(j0 + 10) * M] = f.sa; + if (j0 + 11 < nv) p[(ulong)(j0 + 11) * M] = f.sb; + if (j0 + 12 < nv) p[(ulong)(j0 + 12) * M] = f.sc; + if (j0 + 13 < nv) p[(ulong)(j0 + 13) * M] = f.sd; + if (j0 + 14 < nv) p[(ulong)(j0 + 14) * M] = f.se; + if (j0 + 15 < nv) p[(ulong)(j0 + 15) * M] = f.sf; +} + +#define MMA_K32(q0, q1, q2, q3, hA, hB, sc0, sc1, b) { \ + a_row_t ua0; \ + a_row_t ua1; \ + ua0.h = (half16)(dequant8(q0, (hA), sc0), dequant8(q1, (hA) >> 16, sc0)); \ + ua1.h = (half16)(dequant8(q2, (hB), sc1), dequant8(q3, (hB) >> 16, sc1)); \ + mat_a_t a0 = __builtin_astype(ua0.v, mat_a_t); \ + mat_a_t a1 = __builtin_astype(ua1.v, mat_a_t); \ + mat_b_t b0 = qcom_coop_mat_load((b), CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + mat_b_t b1 = qcom_coop_mat_load((b) + 1024, CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + acc = qcom_coop_mat_mulAdd(a0, b0, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); \ + acc = qcom_coop_mat_mulAdd(a1, b1, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); } + +kernel void kernel_gemm_noshuffle_q6_k_f32_coopmat( + global const uint * src0_ql, // A: q6_K low nibbles, [K/8][M] u32 + global const uint * src0_qh, // A: q6_K high 2-bit, [K/16][M] u32 + global const uint * src0_s, // A: int8 sub-scales, [M][K/16] (4 per u32) + global const half * src0_d, // A: per-superblock scale, [K/256][M] f16 + global const half * src1, // B: packed f16 tiles + global char * dst, // C: [N][M] f32 + ulong offsetd, + int K, + int M, + int N +) { + const int lane = get_local_id(0); + const int row = get_global_id(1) * 64; + const int tn = get_global_id(2); + const int n_tiles = (N + 63) / 64; + + if (tn >= n_tiles) { + return; + } + + const int lrow = row + lane; + + global const uint * qp = src0_ql + lrow; + global const uint * qhp = src0_qh + lrow; + global const half * bp = src1 + (ulong)tn * (K / 16) * 1024; + global const uint * sp = src0_s + (ulong)lrow * (K / 64); + + mat_c_t acc = qcom_coop_mat_init(0.0); + +#pragma unroll 1 + for (int k0 = 0; k0 < K; k0 += 64) { + const half dd = src0_d[(ulong)(k0 >> 8) * M + lrow]; + + const half4 g = convert_half4(as_char4(sp[0])) * dd; + sp += 1; + + uint8 qv; + qv.s0 = qp[0]; + qv.s1 = qp[M]; + qv.s2 = qp[2 * M]; + qv.s3 = qp[3 * M]; + qv.s4 = qp[4 * M]; + qv.s5 = qp[5 * M]; + qv.s6 = qp[6 * M]; + qv.s7 = qp[7 * M]; + qp += 8 * M; + + uint4 hv; + hv.s0 = qhp[0]; + hv.s1 = qhp[M]; + hv.s2 = qhp[2 * M]; + hv.s3 = qhp[3 * M]; + qhp += 4 * M; + + MMA_K32(qv.s0, qv.s1, qv.s2, qv.s3, hv.s0, hv.s1, g.s0, g.s1, bp) + MMA_K32(qv.s4, qv.s5, qv.s6, qv.s7, hv.s2, hv.s3, g.s2, g.s3, bp + 2048) + bp += 4096; + } + + c_row_t uc; + uc.v = __builtin_astype(acc, half4096); + + global float * p = (global float *)(dst + offsetd) + (ulong)tn * 64 * M + row + lane; + const int nv = N - tn * 64; + store_c16(p, uc.s.h0, 0, nv, M); + store_c16(p, uc.s.h1, 16, nv, M); + store_c16(p, uc.s.h2, 32, nv, M); + store_c16(p, uc.s.h3, 48, nv, M); +} diff --git a/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q8_0_f32_coopmat.cl b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q8_0_f32_coopmat.cl new file mode 100644 index 000000000000..e0a86a15fcb3 --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q8_0_f32_coopmat.cl @@ -0,0 +1,157 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_qcom_kernel_cooperative_matrix : enable + +// Q8_0 x F32 GEMM with cl_qcom_kernel_cooperative_matrix: one 64x64 f16 C tile per wave, +// A dequantized in registers, B packed by kernel_pack_b_f16_coopmat. + +typedef half mat_a_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 16, CLK_COOPERATIVE_MATRIX_A_QCOM))); +typedef half mat_b_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 16, 64, CLK_COOPERATIVE_MATRIX_B_QCOM))); +typedef half mat_c_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 64, CLK_COOPERATIVE_MATRIX_ACCUMULATOR_QCOM))); + +typedef half half1024 __attribute__((ext_vector_type(1024))); +typedef half half4096 __attribute__((ext_vector_type(4096))); + +typedef union { + half1024 v; + half16 h; +} a_row_t; + +typedef union { + half4096 v; + struct { + half16 h0; + half16 h1; + half16 h2; + half16 h3; + } s; +} c_row_t; + +inline half4 dequant4(uint v, half d) { + return convert_half4(as_char4(v)) * d; +} + +inline void store_c16(global float * p, half16 h, int j0, int nv, int M) { + float16 f = convert_float16(h); + if (j0 + 0 < nv) p[(ulong)(j0 + 0) * M] = f.s0; + if (j0 + 1 < nv) p[(ulong)(j0 + 1) * M] = f.s1; + if (j0 + 2 < nv) p[(ulong)(j0 + 2) * M] = f.s2; + if (j0 + 3 < nv) p[(ulong)(j0 + 3) * M] = f.s3; + if (j0 + 4 < nv) p[(ulong)(j0 + 4) * M] = f.s4; + if (j0 + 5 < nv) p[(ulong)(j0 + 5) * M] = f.s5; + if (j0 + 6 < nv) p[(ulong)(j0 + 6) * M] = f.s6; + if (j0 + 7 < nv) p[(ulong)(j0 + 7) * M] = f.s7; + if (j0 + 8 < nv) p[(ulong)(j0 + 8) * M] = f.s8; + if (j0 + 9 < nv) p[(ulong)(j0 + 9) * M] = f.s9; + if (j0 + 10 < nv) p[(ulong)(j0 + 10) * M] = f.sa; + if (j0 + 11 < nv) p[(ulong)(j0 + 11) * M] = f.sb; + if (j0 + 12 < nv) p[(ulong)(j0 + 12) * M] = f.sc; + if (j0 + 13 < nv) p[(ulong)(j0 + 13) * M] = f.sd; + if (j0 + 14 < nv) p[(ulong)(j0 + 14) * M] = f.se; + if (j0 + 15 < nv) p[(ulong)(j0 + 15) * M] = f.sf; +} + +#define LOAD_Q(qv, dd) { \ + qv.s0 = qp[0]; \ + qv.s1 = qp[M]; \ + qv.s2 = qp[2 * M]; \ + qv.s3 = qp[3 * M]; \ + qv.s4 = qp[4 * M]; \ + qv.s5 = qp[5 * M]; \ + qv.s6 = qp[6 * M]; \ + qv.s7 = qp[7 * M]; \ + dd = dp[0]; \ + qp += 8 * M; \ + dp += M; } + +#define MMA_K32(qv, dd, b) { \ + a_row_t ua0; \ + a_row_t ua1; \ + ua0.h = (half16)(dequant4(qv.s0, dd), dequant4(qv.s1, dd), dequant4(qv.s2, dd), dequant4(qv.s3, dd)); \ + ua1.h = (half16)(dequant4(qv.s4, dd), dequant4(qv.s5, dd), dequant4(qv.s6, dd), dequant4(qv.s7, dd)); \ + mat_a_t a0 = __builtin_astype(ua0.v, mat_a_t); \ + mat_a_t a1 = __builtin_astype(ua1.v, mat_a_t); \ + mat_b_t b0 = qcom_coop_mat_load((b), CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + mat_b_t b1 = qcom_coop_mat_load((b) + 1024, CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + acc = qcom_coop_mat_mulAdd(a0, b0, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); \ + acc = qcom_coop_mat_mulAdd(a1, b1, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); } + +kernel void kernel_gemm_noshuffle_q8_0_f32_coopmat( + global const uint * src0_q, // A: q8_0 quants, [K/4][M] u32 + global const half * src0_d, // A: q8_0 scales, [K/32][M] f16 + global const half * src1, // B: packed f16 tiles + global char * dst, // C: [N][M] f32 + ulong offsetd, + int K, + int M, + int N +) { + const int lane = get_local_id(0); + const int row = get_global_id(1) * 64; + const int tn = get_global_id(2); + const int n_tiles = (N + 63) / 64; + + if (tn >= n_tiles) { + return; + } + + global const uint * qp = src0_q + row + lane; + global const half * dp = src0_d + row + lane; + global const half * bp = src1 + (ulong)tn * (K / 16) * 1024; + + mat_c_t acc = qcom_coop_mat_init(0.0); + + { + const int odd = (K / 32) & 1; + const int kb = odd ? 0 : 32; + uint8 qa; + uint8 qb; + half da; + half db; + qa.s0 = qp[0]; + qa.s1 = qp[M]; + qa.s2 = qp[2 * M]; + qa.s3 = qp[3 * M]; + qa.s4 = qp[4 * M]; + qa.s5 = qp[5 * M]; + qa.s6 = qp[6 * M]; + qa.s7 = qp[7 * M]; + da = odd ? 0.0h : dp[0]; + qb.s0 = qp[(kb / 4 + 0) * M]; + qb.s1 = qp[(kb / 4 + 1) * M]; + qb.s2 = qp[(kb / 4 + 2) * M]; + qb.s3 = qp[(kb / 4 + 3) * M]; + qb.s4 = qp[(kb / 4 + 4) * M]; + qb.s5 = qp[(kb / 4 + 5) * M]; + qb.s6 = qp[(kb / 4 + 6) * M]; + qb.s7 = qp[(kb / 4 + 7) * M]; + db = dp[(kb / 32) * M]; + MMA_K32(qa, da, bp) + MMA_K32(qb, db, bp + (kb / 16) * 1024) + qp += (kb / 4 + 8) * M; + dp += (kb / 32 + 1) * M; + bp += (kb / 16 + 2) * 1024; + } + +#pragma unroll 1 + for (int k0 = (K / 32) & 1 ? 32 : 64; k0 < K; k0 += 64) { + uint8 qa; + uint8 qb; + half da; + half db; + LOAD_Q(qa, da) + LOAD_Q(qb, db) + MMA_K32(qa, da, bp) + MMA_K32(qb, db, bp + 2048) + bp += 4096; + } + + c_row_t uc; + uc.v = __builtin_astype(acc, half4096); + + global float * p = (global float *)(dst + offsetd) + (ulong)tn * 64 * M + row + lane; + const int nv = N - tn * 64; + store_c16(p, uc.s.h0, 0, nv, M); + store_c16(p, uc.s.h1, 16, nv, M); + store_c16(p, uc.s.h2, 32, nv, M); + store_c16(p, uc.s.h3, 48, nv, M); +} diff --git a/ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_kq_p8.cl b/ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_kq_p8.cl index 2c0a56c855c7..9c4f71a6d910 100644 --- a/ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_kq_p8.cl +++ b/ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_kq_p8.cl @@ -119,7 +119,8 @@ __kernel void mul_mm_f16_f32_kq_p8( int N, int D_A, int D_B, - int p_pitch // bytes per P row, >= M, multiple of 32 + int p_pitch, // bytes per P row, >= M, multiple of 32 + int gqa_fold ) { // Match the n-tile-first grid in ggml_cl_fa_kq_p8_dispatch. @@ -135,7 +136,8 @@ __kernel void mul_mm_f16_f32_kq_p8( const uint col = block_id_m * TILESIZE_M; const uint row = block_id_n * TILESIZE_N; - const uint depth_A = block_id_d / (D_B/D_A); + const uint fold = (uint)gqa_fold; + const uint depth_A = fold > 1 ? block_id_d : block_id_d / (D_B/D_A); const uint depth_B = block_id_d; int line_stride_matrix_A_in_bytes = K * D_A * 2; @@ -158,11 +160,18 @@ __kernel void mul_mm_f16_f32_kq_p8( __local float matrix_B_local[1024]; - // Clamp Q loads in the last tile; columns past N are not stored. - const uint c0 = min(row + b_globalOffsetInWords_xy.y, (uint)N - 1); - const uint c1 = min(row + b_globalOffsetInWords_xy.y + 16, (uint)N - 1); - const uint b_globalOffsetInWords00 = c0*strideBinElements + depth_B*K + b_globalOffsetInWords_xy.x; - const uint b_globalOffsetInWords16 = c1*strideBinElements + depth_B*K + b_globalOffsetInWords_xy.x; + // Folded columns enumerate (query, head within the KV group). + const uint c0 = min(row + b_globalOffsetInWords_xy.y, (uint)N * fold - 1); + const uint c1 = min(row + b_globalOffsetInWords_xy.y + 16, (uint)N * fold - 1); + uint b_globalOffsetInWords00; + uint b_globalOffsetInWords16; + if (fold > 1) { + b_globalOffsetInWords00 = (c0/fold)*strideBinElements + (depth_B*fold + c0%fold)*K + b_globalOffsetInWords_xy.x; + b_globalOffsetInWords16 = (c1/fold)*strideBinElements + (depth_B*fold + c1%fold)*K + b_globalOffsetInWords_xy.x; + } else { + b_globalOffsetInWords00 = c0*strideBinElements + depth_B*K + b_globalOffsetInWords_xy.x; + b_globalOffsetInWords16 = c1*strideBinElements + depth_B*K + b_globalOffsetInWords_xy.x; + } for (uint step=0; step < K; step+=TILESIZE_K) { regA = mm_load_a(matrix_A, subMatrixAStartInElements, line_stride_matrix_A_in_bytes); @@ -199,9 +208,10 @@ __kernel void mul_mm_f16_f32_kq_p8( if (lane < 32) { const int j = lane >> 1; const int b = lane & 1; - const uint n = row + half_*16 + j; - const uint h = depth_B; - if (n < (uint)N) { + const uint c = row + half_*16 + j; + const uint n = c / fold; + const uint h = depth_B*fold + c % fold; + if (c < (uint)N * fold) { float slope = 1.0f; if (max_bias > 0.0f) { const float base = (int)h < n_head_log2 ? m0 : m1; diff --git a/ggml/src/ggml-opencl/kernels/mul_mm_q8_kq_p8.cl b/ggml/src/ggml-opencl/kernels/mul_mm_q8_kq_p8.cl new file mode 100644 index 000000000000..8e04ad393b5b --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/mul_mm_q8_kq_p8.cl @@ -0,0 +1,174 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_khr_subgroups : enable +#ifdef cl_khr_integer_dot_product +#pragma OPENCL EXTENSION cl_khr_integer_dot_product : enable +#endif + +#define KQ_TN 32 +#define KQ_MB 8 +#define KQ_TM 64 +#define KQ_WG 64 +#define KQ_DK_MAX 256 + +__attribute__((qcom_wave_pair_mode(1))) +kernel void kernel_mul_mm_q8_kq_p8( + global const uint * kq, // K int8, [head_kv][n_kv][dk] as packed uints + global const half * kd, // K scales, [head_kv][n_kv][dk/32] + global const uint * qq, // Q int8, [head][n_q][dk] as packed uints + global const half * qd, // Q scales, [head][n_q][dk/32] + global uchar * qp, // u8 P, [head][n_q][p_pitch] + global float * bmax, // per 32-row block max, [head][n_q][p_pitch/32] + global float * bsum, // per block sum of exp(s - bmax), [head][n_q][p_pitch/32] + global const char * mask, // f16 [>=n_kv][n_q] view, row stride mask_nb1 bytes + ulong offset_mask, + ulong mask_nb1, + float scale, + float max_bias, + float m0, + float m1, + int n_head_log2, + int dk, + int n_kv, + int n_q, + int n_head, + int n_head_kv, + int p_pitch // bytes per P row, >= n_kv, multiple of 32 +) { + const int lid = get_local_id(0); + const int gsz = n_head / n_head_kv; + const int g0 = get_group_id(0); + const int head_kv = get_group_id(2); + const int head = head_kv*gsz + (g0 % gsz); + const int qn0 = (g0 / gsz) * KQ_TN; + const int kv0 = get_group_id(1)*KQ_TM*KQ_MB + lid; + + const int nblk = dk / 32; + const int nu = dk / 4; + + __local uint sh_q [KQ_TN][KQ_DK_MAX/4]; + __local half sh_qd[KQ_TN][KQ_DK_MAX/32]; + __local float p8_lds[1024]; + + const size_t qbase = (size_t)head*n_q; + for (int i = lid; i < KQ_TN*(KQ_DK_MAX/16); i += KQ_WG) { + const int t = i / (KQ_DK_MAX/16); + const int u = (i % (KQ_DK_MAX/16)) * 4; + const int qi = qn0 + t; + uint4 v = (uint4)(0u); + if (qi < n_q && u < nu) { + v = vload4(0, &qq[(qbase + qi)*nu + u]); + } + vstore4(v, 0, &sh_q[t][u]); + } + for (int i = lid; i < KQ_TN*(KQ_DK_MAX/32); i += KQ_WG) { + const int t = i / (KQ_DK_MAX/32); + const int b = i % (KQ_DK_MAX/32); + const int qi = qn0 + t; + sh_qd[t][b] = (qi < n_q && b < nblk) ? qd[(qbase + qi)*nblk + b] : (half)0.0f; + } + barrier(CLK_LOCAL_MEM_FENCE); + + float slope = 1.0f; + if (max_bias > 0.0f) { + const float base = head < n_head_log2 ? m0 : m1; + const int ex = head < n_head_log2 ? head + 1 : 2*(head - n_head_log2) + 1; + slope = pow(base, ex); + } + global const half * mrow = (global const half *)(mask + offset_mask); + const uint mstride = (uint)(mask_nb1 / 2); + const int pblk = p_pitch / 32; + + for (int m = 0; m < KQ_MB; ++m) { + const int kv = kv0 + m*KQ_TM; + if (kv - lid >= n_kv) { + break; // uniform across the workgroup + } + + float acc[KQ_TN]; + #pragma unroll + for (int t = 0; t < KQ_TN; ++t) { + acc[t] = 0.0f; + } + + const int kl = min(kv, n_kv - 1); + const size_t kbase = ((size_t)head_kv*n_kv + kl)*nu; + const size_t kdbas = ((size_t)head_kv*n_kv + kl)*nblk; + + for (int b = 0; b < nblk; ++b) { + const uint4 w0 = vload4(0, &kq[kbase + b*8]); + const uint4 w1 = vload4(0, &kq[kbase + b*8 + 4]); + const float dks = (float)kd[kdbas + b]; + + #pragma unroll + for (int t = 0; t < KQ_TN; ++t) { + const uint4 a0 = vload4(0, &sh_q[t][b*8]); + const uint4 a1 = vload4(0, &sh_q[t][b*8 + 4]); + int raw = 0; + raw = dot_acc_sat_4x8packed_ss_int(w0.s0, a0.s0, raw); + raw = dot_acc_sat_4x8packed_ss_int(w0.s1, a0.s1, raw); + raw = dot_acc_sat_4x8packed_ss_int(w0.s2, a0.s2, raw); + raw = dot_acc_sat_4x8packed_ss_int(w0.s3, a0.s3, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s0, a1.s0, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s1, a1.s1, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s2, a1.s2, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s3, a1.s3, raw); + acc[t] += dks * (float)sh_qd[t][b] * (float)raw; + } + } + + // Each lane owns one complete 32-row softmax block after the transpose. + const int kvblk0 = kv - lid; + #pragma unroll + for (int half_ = 0; half_ < 2; ++half_) { + barrier(CLK_LOCAL_MEM_FENCE); + #pragma unroll + for (int j = 0; j < 16; ++j) { + p8_lds[j*64 + lid] = acc[half_*16 + j]; + } + barrier(CLK_LOCAL_MEM_FENCE); + if (lid < 32) { + const int j = lid >> 1; + const int b = lid & 1; + const int n = qn0 + half_*16 + j; + if (n < n_q) { + const int kvb = kvblk0 + b*32; + const __local float * src = p8_lds + j*64 + b*32; + float16 s0 = vload16(0, src); + float16 s1 = vload16(1, src); + const global half * mp = mrow + (size_t)n*mstride + kvb; + const float16 m0v = convert_float16(vload16(0, mp)); + const float16 m1v = convert_float16(vload16(1, mp)); + s0 = s0*scale + slope*m0v; + s1 = s1*scale + slope*m1v; + const float16 mx16 = fmax(s0, s1); + const float8 mx8 = fmax(mx16.lo, mx16.hi); + const float4 mx4 = fmax(mx8.lo, mx8.hi); + const float2 mx2 = fmax(mx4.lo, mx4.hi); + const float amax = fmax(mx2.x, mx2.y); + const size_t prow = qbase + n; + const int blk = kvb >> 5; + float sum = 0.0f; + uchar16 q0 = (uchar16)(0); + uchar16 q1 = (uchar16)(0); + // finite sentinel: the program builds with -cl-finite-math-only + if (amax > -1.0e30f) { + const float16 e0 = exp(s0 - amax); + const float16 e1 = exp(s1 - amax); + const float16 a16 = e0 + e1; + const float8 a8 = a16.lo + a16.hi; + const float4 a4 = a8.lo + a8.hi; + const float2 a2 = a4.lo + a4.hi; + sum = a2.x + a2.y; + q0 = convert_uchar16_sat_rte(e0*255.0f); + q1 = convert_uchar16_sat_rte(e1*255.0f); + } + global uchar * qdst = qp + prow*(size_t)p_pitch + (size_t)kvb; + vstore16(q0, 0, qdst); + vstore16(q1, 1, qdst); + bmax[prow*pblk + blk] = amax; + bsum[prow*pblk + blk] = sum; + } + } + } + } +} diff --git a/ggml/src/ggml-opencl/kernels/mul_mm_q8_kq_p8_dk512.cl b/ggml/src/ggml-opencl/kernels/mul_mm_q8_kq_p8_dk512.cl new file mode 100644 index 000000000000..f6ba2b6c2247 --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/mul_mm_q8_kq_p8_dk512.cl @@ -0,0 +1,170 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_khr_subgroups : enable +#ifdef cl_khr_integer_dot_product +#pragma OPENCL EXTENSION cl_khr_integer_dot_product : enable +#endif + +#define KQ_TN 32 +#define KQ_MB 8 +#define KQ_TM 64 +#define KQ_WG 64 +#define KQ_DKC 256 + +__attribute__((qcom_wave_pair_mode(1))) +kernel void kernel_mul_mm_q8_kq_p8_dk512( + global const uint * kq, // K int8, [head_kv][n_kv][dk] as packed uints + global const half * kd, // K scales, [head_kv][n_kv][dk/32] + global const uint * qq, // Q int8, [head][n_q][dk] as packed uints + global const half * qd, // Q scales, [head][n_q][dk/32] + global uchar * qp, // u8 P, [head][n_q][p_pitch] + global float * bmax, // per 32-row block max, [head][n_q][p_pitch/32] + global float * bsum, // per block sum of exp(s - bmax), [head][n_q][p_pitch/32] + global const char * mask, // f16 [>=n_kv][n_q] view, row stride mask_nb1 bytes + ulong offset_mask, + ulong mask_nb1, + float scale, + float max_bias, + float m0, + float m1, + int n_head_log2, + int dk, + int n_kv, + int n_q, + int n_head, + int n_head_kv, + int p_pitch // bytes per P row, >= n_kv, multiple of 32 +) { + const int lid = get_local_id(0); + const int gsz = n_head / n_head_kv; + const int g0 = get_group_id(0); + const int head_kv = get_group_id(2); + const int head = head_kv*gsz + (g0 % gsz); + const int qn0 = (g0 / gsz) * KQ_TN; + const int kv0 = get_group_id(1)*KQ_TM*KQ_MB + lid; + + const int nblk = dk / 32; + const int nu = dk / 4; + + // Reuse the 256-wide Q slice for the F32 softmax scores after the contraction. + __local uint sh_q [KQ_TN*KQ_DKC/4]; + __local half sh_qd[KQ_TN][KQ_DKC/32]; + __local float * p8_lds = (__local float *)sh_q; + + const size_t qbase = (size_t)head*n_q; + + float slope = 1.0f; + if (max_bias > 0.0f) { + const float base = head < n_head_log2 ? m0 : m1; + const int ex = head < n_head_log2 ? head + 1 : 2*(head - n_head_log2) + 1; + slope = pow(base, ex); + } + global const half * mrow = (global const half *)(mask + offset_mask); + const uint mstride = (uint)(mask_nb1 / 2); + const int pblk = p_pitch / 32; + + for (int m = 0; m < KQ_MB; ++m) { + const int kv = kv0 + m*KQ_TM; + if (kv - lid >= n_kv) { + break; // uniform across the workgroup + } + + float acc[KQ_TN]; + #pragma unroll + for (int t = 0; t < KQ_TN; ++t) { + acc[t] = 0.0f; + } + + const int kl = min(kv, n_kv - 1); + const size_t kbase = ((size_t)head_kv*n_kv + kl)*nu; + const size_t kdbas = ((size_t)head_kv*n_kv + kl)*nblk; + + for (int c0 = 0; c0 < nblk; c0 += KQ_DKC/32) { + const int cb = min(KQ_DKC/32, nblk - c0); + barrier(CLK_LOCAL_MEM_FENCE); + for (int i = lid; i < KQ_TN*(KQ_DKC/16); i += KQ_WG) { + const int t = i / (KQ_DKC/16); + const int u = (i % (KQ_DKC/16)) * 4; + const int qi = qn0 + t; + uint4 v = (uint4)(0u); + if (qi < n_q && u < cb*8) { + v = vload4(0, &qq[(qbase + qi)*nu + c0*8 + u]); + } + vstore4(v, 0, &sh_q[t*(KQ_DKC/4) + u]); + } + for (int i = lid; i < KQ_TN*(KQ_DKC/32); i += KQ_WG) { + const int t = i / (KQ_DKC/32); + const int b = i % (KQ_DKC/32); + const int qi = qn0 + t; + sh_qd[t][b] = (qi < n_q && b < cb) ? qd[(qbase + qi)*nblk + c0 + b] : (half)0.0f; + } + barrier(CLK_LOCAL_MEM_FENCE); + + for (int b = 0; b < cb; ++b) { + const uint4 w0 = vload4(0, &kq[kbase + (c0 + b)*8]); + const uint4 w1 = vload4(0, &kq[kbase + (c0 + b)*8 + 4]); + const float dks = (float)kd[kdbas + c0 + b]; + + #pragma unroll + for (int t = 0; t < KQ_TN; ++t) { + const uint4 a0 = vload4(0, &sh_q[t*(KQ_DKC/4) + b*8]); + const uint4 a1 = vload4(0, &sh_q[t*(KQ_DKC/4) + b*8 + 4]); + int raw = 0; + raw = dot_acc_sat_4x8packed_ss_int(w0.s0, a0.s0, raw); + raw = dot_acc_sat_4x8packed_ss_int(w0.s1, a0.s1, raw); + raw = dot_acc_sat_4x8packed_ss_int(w0.s2, a0.s2, raw); + raw = dot_acc_sat_4x8packed_ss_int(w0.s3, a0.s3, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s0, a1.s0, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s1, a1.s1, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s2, a1.s2, raw); + raw = dot_acc_sat_4x8packed_ss_int(w1.s3, a1.s3, raw); + acc[t] += dks * (float)sh_qd[t][b] * (float)raw; + } + } + } + + // Finish reading the Q slice before writing scores to the same local memory. + const int kvblk0 = kv - lid; + barrier(CLK_LOCAL_MEM_FENCE); + #pragma unroll + for (int t = 0; t < KQ_TN; ++t) { + p8_lds[t*64 + lid] = acc[t]; + } + barrier(CLK_LOCAL_MEM_FENCE); + { + const int j = lid >> 1; + const int b = lid & 1; + const int n = qn0 + j; + if (n < n_q) { + const int kvb = kvblk0 + b*32; + __local float * src = p8_lds + j*64 + b*32; + const global half * mp = mrow + (size_t)n*mstride + kvb; + float4 s = vload4(0, src)*scale + slope*convert_float4(vload4(0, mp)); + vstore4(s, 0, src); + float amax = fmax(fmax(s.x, s.y), fmax(s.z, s.w)); + for (int c = 1; c < 8; ++c) { + s = vload4(c, src)*scale + slope*convert_float4(vload4(c, mp)); + vstore4(s, c, src); + amax = fmax(amax, fmax(fmax(s.x, s.y), fmax(s.z, s.w))); + } + const size_t prow = qbase + n; + const int blk = kvb >> 5; + global uchar * qdst = qp + prow*(size_t)p_pitch + (size_t)kvb; + float sum = 0.0f; + // finite sentinel: the program builds with -cl-finite-math-only + if (amax > -1.0e30f) { + for (int c = 0; c < 8; ++c) { + const float4 e = exp(vload4(c, src) - amax); + sum += (e.x + e.y) + (e.z + e.w); + vstore4(convert_uchar4_sat_rte(e*255.0f), c, qdst); + } + } else { + for (int c = 0; c < 8; ++c) { + vstore4((uchar4)(0), c, qdst); + } + } + bmax[prow*pblk + blk] = amax; + bsum[prow*pblk + blk] = sum; + } + } + } +} diff --git a/ggml/src/ggml-opencl/kernels/pack_b_f16_coopmat.cl b/ggml/src/ggml-opencl/kernels/pack_b_f16_coopmat.cl new file mode 100644 index 000000000000..3f60223b842c --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/pack_b_f16_coopmat.cl @@ -0,0 +1,48 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable + +// Pack B f32 [N][K] into f16 64x16 tiles (column-major, ld 16) at (tn * (K/16) + ks) * 1024. +// Columns >= N are zero. A workgroup (64, 4) packs 64 columns x 64 k. +#define PACK_LDS (64 + 8) + +kernel void kernel_pack_b_f16_coopmat( + global const char * src1, + ulong offset1, + global half * dst, + int K, + int N +) { + local half tile[64 * PACK_LDS]; + + const int l = get_local_id(1) * 64 + get_local_id(0); + const int tn = get_group_id(0); + const int kt = get_group_id(1); + const int k0 = kt * 64; + + global const float * src = (global const float *)(src1 + offset1); + + for (int j = 0; j < 4; j++) { + const int f = j * 256 + l; + const int r = f >> 4; + const int c = (f & 15) * 4; + const int n = tn * 64 + r; + float4 v = (float4)(0.0f); + if (n < N && k0 + c < K) { + v = vload4(0, src + (ulong)n * K + k0 + c); + } + vstore_half4(v, 0, tile + r * PACK_LDS + c); + } + + barrier(CLK_LOCAL_MEM_FENCE); + + global half * out = dst + ((ulong)tn * (K / 16) + kt * 4) * 1024; + for (int j = 0; j < 2; j++) { + const int q = j * 256 + l; + const int ks = q >> 7; + const int n = (q >> 1) & 63; + const int h = q & 1; + if (kt * 4 + ks < K / 16) { + half8 v = vload8(0, tile + n * PACK_LDS + ks * 16 + h * 8); + vstore8(v, 0, out + q * 8); + } + } +} diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 38db895c532f..519c35bc21a1 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -107,7 +107,8 @@ GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph, std::mapn_nodes; ++i) { if ((cgraph->nodes[i]->op == GGML_OP_GATED_DELTA_NET && cgraph->nodes[i]->op_params[0] > 1) || - is_sampling_view(cgraph->nodes[i]) || is_conv_state_snapshot_writeback(cgraph->nodes[i])) { + is_sampling_view(cgraph->nodes[i]) || is_conv_state_snapshot_writeback(cgraph->nodes[i]) || + is_ssm_state_writeback(cgraph->nodes[i])) { std::tie(m_model_params, m_compute_params) = compute_llm_params(cgraph, false); add_extra_inputs(); break; @@ -494,6 +495,10 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { } } else if (node->ne[0] == 1 && src->ne[0] * src->ne[1] * src->ne[2] == node->ne[1]) { op_case = 3; + } else if (node->ne[0] * node->ne[1] == src->ne[0] * src->ne[1] && node->ne[2] == src->ne[2] && + node->ne[3] == src->ne[3]) { + // head regroup, e.g. mamba2's [head_dim, n_head, n_tokens, n_seqs] -> [d_inner/n_group, n_group, n_tokens, n_seqs] + op_case = 1; } else if (name.find("linear_attn_qkv_mixed") == 0 || name.find("alpha") == 0) { op_case = 6; } else if (name.find("linear_attn_out") == 0) { @@ -597,6 +602,10 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { op_case = 3; break; } + if (is_column_set_rows(node)) { + op_case = 4; + break; + } // `-fa off` writes the V cache transposed, through a [1, n] reshape of the cache: one element per row if (node->src[2] != nullptr && node->src[2]->op == GGML_OP_RESHAPE && node->src[2]->ne[0] == 1 && is_kvcache(node->src[2]->src[0], nullptr)) { @@ -797,6 +806,9 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { } else { op_case = 1; } + } else if (is_ssm_state_writeback(node)) { + op_case = 13; + break; } else if (GgmlOvDecoder::is_conv_state_writeback(node)) { op_case = 2; break; @@ -1296,6 +1308,11 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr writeback.snapshot_stride = destination->nb[2] / destination->nb[1]; compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback; } + if (is_ssm_state_writeback(node)) { + ComputeParams::RsWriteback writeback; + writeback.slot_begin = (int64_t) (node->src[1]->view_offs / node->src[1]->nb[1]); + compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback; + } if (is_conv_state_snapshot_writeback(node)) { const auto source = node->src[0]; const auto dest = node->src[2]; @@ -1406,6 +1423,14 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr compute_params.attention_size = ggml_openvino_static_kv_window(compute_params.attention_size, model_params.ctx_per_seq); } + // 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 to a power of two the same way, so that a long context uses a few lengths and not one per + // step. The KQ mask input is padded to this length with -inf (convert_ggml_input_to_ov). + if (!is_static && ggml_openvino_is_gpu() && !ggml_openvino_getenv_int("GGML_OPENVINO_STATEFUL_EXECUTION") && + !compute_params.mask_name.empty() && 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); + } model_params.ctx = model_params.ctx_per_seq * model_params.n_seq; return {model_params, compute_params}; } @@ -1416,6 +1441,15 @@ void GgmlOvDecoder::validate_cgraph() const { } } +bool GgmlOvDecoder::has_inp_embd_leaf_use(const ggml_tensor * tensor) const { + for (int i = 0; i < m_cgraph->n_nodes; i++) { + if (is_inp_embd_leaf(tensor, m_cgraph->nodes[i])) { + return true; + } + } + return false; +} + ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op, const ggml_tensor * input, int dynamic_dim_index) const { @@ -1530,7 +1564,7 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op, // index list has a static length; on CPU/GPU it may change across compiles (defrag). input_shape = m_is_static ? ov::PartialShape{get_shape(input)} : ov::PartialShape{1, 1, 1, -1}; - } else if (input != nullptr && op != nullptr && is_inp_emb(input, op)) { + } else if (input != nullptr && op != nullptr && (is_inp_emb(input, op) || has_inp_embd_leaf_use(input))) { input_shape = ov::PartialShape{get_shape(input)}; if (!m_is_static) { input_shape[2] = -1; @@ -1914,7 +1948,11 @@ void GgmlOvDecoder::compute_model_outputs() { continue; } const bool inactive_top_k = is_sampling_top_k(cur_node) && !(cur_node->flags & GGML_TENSOR_FLAG_COMPUTE); - if ((cur_node->flags & GGML_TENSOR_FLAG_OUTPUT) || inactive_top_k) { + auto cur_node_use_count = m_cgraph->use_counts[ggml_hash_find(&m_cgraph->visited_hash_set, cur_node)]; + // llama flags result_norm in every graph but reads it only with embeddings on, when it has no consumer + // and is kept by the rule below. + const bool unread_embd = strcmp(cur_node->name, "result_norm") == 0 && cur_node_use_count > 0; + if (((cur_node->flags & GGML_TENSOR_FLAG_OUTPUT) && !unread_embd) || inactive_top_k) { const auto name = get_tensor_ov_name(m_cgraph, cur_node); m_model_outputs[name] = cur_node; m_model_output_names.insert(name); @@ -1925,7 +1963,12 @@ void GgmlOvDecoder::compute_model_outputs() { m_model_outputs[name] = cache; m_model_output_names.insert(name); } - auto cur_node_use_count = m_cgraph->use_counts[ggml_hash_find(&m_cgraph->visited_hash_set, cur_node)]; + if (is_ssm_state_writeback(cur_node)) { + auto * cache = cur_node->view_src; + const auto name = get_tensor_ov_name(m_cgraph, cache); + m_model_outputs[name] = cache; + m_model_output_names.insert(name); + } if (cur_node_use_count == 0) { // The output of in-place ops is the view_src tensor, which is updated in place. We should use the view_src name as the output name to make sure it can be correctly matched with the later ops that use the view_src. if (cur_node != nullptr && ::is_inplace_op(cur_node) && @@ -2641,6 +2684,10 @@ bool GgmlOvDecoder::is_direct_gdn_view(const ggml_tensor * node) const { std::vector GgmlOvDecoder::get_output_names(int node_idx) const { auto * node = m_node_info_list[node_idx].node; + if (is_ssm_state_writeback(node)) { + // 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)) { std::string attn_name; std::string state_name; @@ -2669,6 +2716,10 @@ std::vector GgmlOvDecoder::get_output_names(int node_idx) const { std::string GgmlOvDecoder::get_inplace_op_src(int node_idx) const { auto * node = m_node_info_list[node_idx].node; + if (is_ssm_state_writeback(node)) { + // translate_cpy publishes the updated cache as a second named output + return ""; + } // Reset lengths (also in static mode) and dynamic remainder views can become nonempty // after compilation. Keep their alias updates in the translated cache chain. const bool runtime_recurrent_write = !m_naive && is_recurrent_cache(node->view_src) && @@ -2786,7 +2837,7 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { m_node_dynamic_dims[src] = 0; continue; } - if (is_inp_scale_rows(src, node)) { + if (is_inp_scale_rows(src, node) || is_inp_embd_leaf(src, node)) { m_node_dynamic_dims[src] = 1; continue; } @@ -2865,6 +2916,11 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { m_node_dynamic_dims[node] = 2; break; } + if (node->src[0]->op == GGML_OP_SSM_SCAN) { + // y part [head_dim, n_head, n_tokens, n_seqs] at offset 0; the state part is token-independent + m_node_dynamic_dims[node] = node->view_offs == 0 ? 2 : -1; + break; + } // Use stride-based matching: the stride of a VIEW dimension directly // encodes which source dimension it indexes into, so it uniquely // identifies the dynamic dim even when two dims share the same size. @@ -3030,6 +3086,10 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { case GGML_OP_GATED_DELTA_NET: m_node_dynamic_dims[node] = 1; break; + case GGML_OP_SSM_SCAN: + // packed 1-D [y | state]; the y part grows with tokens + m_node_dynamic_dims[node] = 0; + break; case GGML_OP_RMS_NORM: case GGML_OP_L2_NORM: case GGML_OP_NORM: @@ -3080,12 +3140,15 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { case GGML_OP_CPY: case GGML_OP_SUM: case GGML_OP_MEAN: + case GGML_OP_ARANGE: m_node_dynamic_dims[node] = -1; break; case GGML_OP_SET_ROWS: - // a cache write returns the cache; other rows writes keep the shape of their destination - m_node_dynamic_dims[node] = (is_kvcache_write(node) || is_conv_state_snapshot_writeback(node)) ? - -1 : m_node_dynamic_dims[node->src[2]]; + // a cache or column write returns its whole buffer; other rows writes keep the shape of their destination + m_node_dynamic_dims[node] = + (is_kvcache_write(node) || is_conv_state_snapshot_writeback(node) || is_column_set_rows(node)) ? + -1 : + m_node_dynamic_dims[node->src[2]]; break; case GGML_OP_IM2COL: { m_node_dynamic_dims[node] = -1; diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index b7ff4b715f06..12b08cebce4b 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -477,6 +477,21 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { return tensor->op == GGML_OP_GET_ROWS && op->op == GGML_OP_RMS_NORM; } + // Raw float input [n_embd, n_tokens]: DFlash/DSpark/EAGLE3 features into fc, or raw embd batch / EAGLE3 g-embd into RMS_NORM + // MUL_MAT needs a weight leaf as src[0], so inp_mean (src[0] is computed) does not match + static bool is_inp_embd_leaf(const ggml_tensor * tensor, const ggml_tensor * op) { + if (tensor->op != GGML_OP_NONE || !(tensor->flags & GGML_TENSOR_FLAG_INPUT) || tensor->type != GGML_TYPE_F32) { + return false; + } + if (op->op == GGML_OP_MUL_MAT) { + return op->src[1] == tensor && op->src[0] != nullptr && op->src[0]->op == GGML_OP_NONE; + } + return op->op == GGML_OP_RMS_NORM && op->src[0] == tensor; + } + + // true if any node of the current graph uses tensor as a raw embd input (see is_inp_embd_leaf) + bool has_inp_embd_leaf_use(const ggml_tensor * tensor) const; + static bool is_activation_input(const ggml_tensor * tensor, const ggml_tensor * op) { if (tensor == nullptr || op == nullptr || tensor->type != GGML_TYPE_F32 || tensor->ne[2] != 1 || tensor->ne[3] != 1 || (tensor->buffer != nullptr && tensor->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS)) { @@ -578,11 +593,11 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { bool is_direct_gdn_view(const ggml_tensor * node) const; - inline static bool is_cache(const ggml_tensor * tensor, const ggml_tensor * op) { + static bool is_cache(const ggml_tensor * tensor, const ggml_tensor * op) { return is_recurrent_cache(tensor) || is_kvcache(tensor, op); } - inline static bool is_kvcache(const ggml_tensor * tensor, const ggml_tensor * op) { + static bool is_kvcache(const ggml_tensor * tensor, const ggml_tensor * op) { if (tensor == nullptr || is_recurrent_cache(tensor)) { return false; } @@ -590,27 +605,68 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { (op != nullptr && op->op == GGML_OP_SET_ROWS && op->src[2] == tensor); } - inline static bool is_conv_state_writeback(const ggml_tensor * node) { + static bool is_conv_state_writeback(const ggml_tensor * node) { return node->op == GGML_OP_CPY && node->view_src != nullptr && is_recurrent_cache(node->view_src) && node->src[0] != nullptr && node->src[0]->op == GGML_OP_VIEW && node->src[0]->src[0] != nullptr && node->src[0]->src[0]->op == GGML_OP_CONCAT && node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src == node->view_src; } + // The final-state writeback of SSM_SCAN (K == 1): the state tail of the packed [y | state] + // output copied into a slot block of the recurrent cache. + static bool is_ssm_state_writeback(const ggml_tensor * node) { + if (!(node != nullptr && node->op == GGML_OP_CPY && node->view_src != nullptr && node->src[0] != nullptr && + node->src[0]->op == GGML_OP_VIEW && node->src[0]->src[0] != nullptr && + node->src[0]->src[0]->op == GGML_OP_SSM_SCAN && node->src[0]->src[0]->op_params[0] == 1 && + node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW && + node->src[1]->view_src == node->view_src)) { + return false; + } + const auto * scan = node->src[0]->src[0]; + const auto * src = node->src[0]; + const auto * dst = node->src[1]; + if (node->type != GGML_TYPE_F32 || src->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 || + src->ne[2] != 1 || src->ne[3] != 1) { + return false; + } + for (int i = 0; i < GGML_MAX_DIMS; ++i) { + if (src->ne[i] != dst->ne[i]) { + return false; + } + } + return dst->nb[1] > 0 && dst->view_offs % dst->nb[1] == 0 && + src->view_offs == (size_t) ggml_nelements(scan->src[1]) * ggml_type_size(scan->type); + } + // build_conv_state_store writes overlapping [history, window, channel, seq] windows into newest-first rollback planes. // Match this layout separately from general SET_ROWS. static bool is_conv_state_snapshot_writeback(const ggml_tensor * node); + // SET_ROWS into a column range of each row of a plain 2-D buffer, e.g. build_layer_inp_dev(): every enabled layer + // input goes to view_2d(layer_inp_dev, n_embd, n_batch, nb1, col * n_embd * elem) at the batch rows of the ubatch. + // The buffer sits in a regular device buffer, so is_kvcache() matches it: check this first + static bool is_column_set_rows(const ggml_tensor * node) { + if (node == nullptr || node->op != GGML_OP_SET_ROWS || node->src[2] == nullptr || + node->src[2]->op != GGML_OP_VIEW) { + return false; + } + const ggml_tensor * dst = node->src[2]; + const ggml_tensor * buf = dst->view_src; + return buf != nullptr && buf->op == GGML_OP_NONE && !is_recurrent_cache(buf) && buf->ne[2] == 1 && + buf->ne[3] == 1 && dst->ne[2] == 1 && dst->ne[3] == 1 && dst->ne[0] < buf->ne[0] && + dst->nb[0] == buf->nb[0] && dst->nb[1] == buf->nb[1] && dst->ne[1] == buf->ne[1]; + } + // SET_ROWS into a KV cache, directly or through the [1, n] reshape of the transposed V cache with `-fa off`. // Other SET_ROWS write rows of a compute tensor, e.g. the MoE expert-group mask - inline static bool is_kvcache_write(const ggml_tensor * node) { + static bool is_kvcache_write(const ggml_tensor * node) { const ggml_tensor * dst = node->src[2]; return dst != nullptr && is_kvcache(dst->view_src != nullptr ? dst->view_src : dst, nullptr); } // GET_ROWS batched over ggml dims 2 and 3, e.g. the MoE expert-group scores // ggml_get_rows(ggml_reshape_4d(groups, 1, n_exp_per_group, n_groups, n_tokens), top_groups) - inline static bool is_get_rows_batched_4d(const ggml_tensor * node) { + static bool is_get_rows_batched_4d(const ggml_tensor * node) { return node->op == GGML_OP_GET_ROWS && !ggml_is_quantized(node->src[0]->type) && node->src[1]->ne[1] == node->src[0]->ne[2] && node->src[1]->ne[2] == node->src[0]->ne[3] && node->src[1]->ne[3] == 1; diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index c76b423983f3..2537f8af3a31 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -616,6 +616,10 @@ bool ggml_openvino_is_npu() { return ggml_openvino_get_device_config().is_npu; } +bool ggml_openvino_is_static() { + return ggml_openvino_is_npu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC"); +} + bool ggml_openvino_is_gpu() { return has_prefix(ggml_openvino_get_device_name(), "GPU"); } diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h index 5a64c67ef9c5..406ac6d4cb5a 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.h +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h @@ -134,6 +134,9 @@ bool ggml_openvino_release_weights_enabled(); // Check if running on NPU bool ggml_openvino_is_npu(); +// Static graphs: NPU, or any device with GGML_OPENVINO_FORCE_STATIC +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. diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index a7f5d177f527..bd49560d8e1e 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -1504,6 +1504,38 @@ static bool has_strides_on_element_grid(const ggml_tensor * t) { return true; } +// A VIEW that regroups one contiguous span of every row of its contiguous source, e.g. the z/x/B/C +// splits of the fused mamba projections. The strides do not nest on an element grid, but +// process_view_input_new resolves it as a Slice of the source's innermost axis plus a Reshape. +// Keep in sync with the matching branch there; dynamic execution only. +static bool is_row_span_view(const ggml_tensor * t) { + if (ggml_openvino_is_static() || is_stateful_enabled()) { + return false; + } + const ggml_tensor * src = t->op == GGML_OP_VIEW ? t->src[0] : nullptr; + // a RESHAPE source is fine (the translation reads its value); a chained VIEW is not, because + // the view metadata then describes the intermediate view instead of the resolved input + if (src == nullptr || src->op == GGML_OP_VIEW || !ggml_is_contiguous(src) || t->type != src->type) { + return false; + } + const size_t es = ggml_type_size(t->type); + int d = 0; + size_t span = 1; + while (d < GGML_MAX_DIMS && t->nb[d] == span * es) { + span *= t->ne[d]; + d++; + } + if (d < 2) { + return false; + } + for (int s = 1; d < GGML_MAX_DIMS; ++d, ++s) { + if (t->ne[d] != src->ne[s] || t->nb[d] != src->nb[s]) { + return false; + } + } + return t->view_offs % es == 0 && t->view_offs / es + span <= (size_t) src->ne[0]; +} + static bool has_non_contiguous_view_input(const ggml_tensor * op) { for (int i = 0; i < GGML_MAX_SRC; i++) { if (op->src[i] == nullptr) { @@ -1624,7 +1656,7 @@ static bool cpy_output_view_is_supported(const ggml_tensor * op) { } return ggml_nbytes(op) == 0 || ggml_is_contiguous(op) || GgmlOvDecoder::is_conv_state_writeback(op) || - GgmlOvDecoder::is_gdn_snapshot_writeback(op); + GgmlOvDecoder::is_gdn_snapshot_writeback(op) || GgmlOvDecoder::is_ssm_state_writeback(op); } static bool mul_mat_id_requires_large_tmp(const ggml_tensor * op) { @@ -1727,14 +1759,16 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { } case GGML_OP_GET_ROWS: case GGML_OP_SET_ROWS: { - if (GgmlOvDecoder::is_conv_state_snapshot_writeback(op) && - (ggml_openvino_is_npu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC"))) { + if (GgmlOvDecoder::is_conv_state_snapshot_writeback(op) && ggml_openvino_is_static()) { return {false, "convolution snapshots require dynamic execution"}; } if (op->ne[3] != 1 && !GgmlOvDecoder::is_get_rows_batched_4d(op) && !GgmlOvDecoder::is_conv_state_snapshot_writeback(op)) { return {false, "GET_ROWS/SET_ROWS with ne[3] != 1 (ne[3]=" + std::to_string(op->ne[3]) + ") is not supported"}; } + 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->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 @@ -2004,6 +2038,9 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { if (op->view_src != nullptr && !ggml_is_contiguous(op->src[0])) { return {false, "ROPE on VIEW / non-contiguous input is not supported"}; } + if (op->type == GGML_TYPE_BF16) { + return {false, "ROPE with BF16 type is not supported"}; + } break; } case GGML_OP_TRANSPOSE: { @@ -2034,7 +2071,7 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { reason = "GATED_DELTA_NET with kda (per-key-dimension gating) is not supported"; } else if (op->op_params[0] > 1) { - if (ggml_openvino_is_npu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC")) { + if (ggml_openvino_is_static()) { reason = "GATED_DELTA_NET snapshots require dynamic execution"; } } @@ -2053,6 +2090,19 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { // return true; break; } + case GGML_OP_SSM_SCAN: { + // SelectiveSSM implements the Mamba-2 recurrence: scalar decay per head, one final state + if (op->src[3]->ne[0] != 1) { + return {false, "SSM_SCAN with Mamba-1 state-wise decay is not supported"}; + } + if (op->op_params[0] > 1) { + return {false, "SSM_SCAN with rollback snapshots (K > 1) is not supported"}; + } + if (ggml_openvino_is_static()) { + return {false, "SSM_SCAN requires dynamic execution"}; + } + break; + } case GGML_OP_VIEW: { // Skip TOPK_MOE fused tests until it is fully supported. // The argsort_top_k VIEW wrapping ARGSORT is named "selected_experts" in test_topk_moe. @@ -2274,7 +2324,8 @@ static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(gg if (supported_types.find(src->type) == supported_types.end()) { return {false, "src[" + std::to_string(i) + "] type " + std::string(ggml_type_name(src->type)) + " is not supported"}; } - if (!has_strides_on_element_grid(src) && !(i == 1 && GgmlOvDecoder::is_gdn_snapshot_writeback(op)) && + if (!has_strides_on_element_grid(src) && !is_row_span_view(src) && + !(i == 1 && GgmlOvDecoder::is_gdn_snapshot_writeback(op)) && !(i == 2 && GgmlOvDecoder::is_conv_state_snapshot_writeback(op))) { return {false, "src[" + std::to_string(i) + "] strides are not multiples of each other"}; } diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp index 597233d7e6d9..7bfa7ad08b11 100644 --- a/ggml/src/ggml-openvino/model-cache.cpp +++ b/ggml/src/ggml-openvino/model-cache.cpp @@ -197,8 +197,7 @@ void ggml_openvino_model_cache_init() { } return; } - if (cache_only && (ggml_openvino_is_npu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC") || - ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_CACHE") || + if (cache_only && (ggml_openvino_is_static() || ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_CACHE") || ggml_openvino_getenv_int("GGML_OPENVINO_ENABLE_FALLBACK"))) { GGML_ABORT("ggml-openvino: cache-only mode requires dynamic CPU/GPU execution with caching and without fallback"); } @@ -368,7 +367,8 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph, // Version 5 requantizes K-quant MoE experts to Q4_1_64 on GPU by default. // Version 6 clears recurrent-cache slots with Select, so a NaN in a cleared slot does not survive. // Version 7 reads ROPE frequency factors named other than rope_freqs.weight as a Constant, not a Parameter. - h = fnv1a_u64(h, 7); + // Version 8 drops result_norm from the outputs when it has a consumer, and hashes the output flags. + h = fnv1a_u64(h, 8); h = fnv1a(h, graph_signature.data(), graph_signature.size()); for (const char * name : cache_settings) { const char * value = ggml_openvino_getenv_str(name, ""); @@ -391,6 +391,8 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph, const ggml_tensor * node = cgraph->nodes[i]; h = fnv1a_u64(h, static_cast(node->op)); h = fnv1a(h, node->name, strlen(node->name)); + // Each output is a Result of the model; llama_set_embeddings_layer_inp() changes only the flags. + h = fnv1a_u64(h, (node->flags & GGML_TENSOR_FLAG_OUTPUT) ? 1u : 0u); has_gdn = has_gdn || node->op == GGML_OP_GATED_DELTA_NET; } if (has_gdn && ggml_openvino_is_npu()) { diff --git a/ggml/src/ggml-openvino/openvino/op/cpy.cpp b/ggml/src/ggml-openvino/openvino/op/cpy.cpp index 0bb6bd054d15..e0d63ac95179 100644 --- a/ggml/src/ggml-openvino/openvino/op/cpy.cpp +++ b/ggml/src/ggml-openvino/openvino/op/cpy.cpp @@ -75,6 +75,28 @@ OutputVector translate_cpy(const NodeContext & context) { return rename_outputs_with_suffix({result}, context.get_name()); } + if (op_case == 13) { + // SSM_SCAN final-state writeback: output the written state block and the full updated cache + auto src = process_view_input_new(context, 0); + auto base = context.get_input(1); + if (src.get_element_type() != context.get_output_type()) { + src = std::make_shared(src, context.get_output_type()); + } + auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0}); + auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1}); + auto int_max = ov::op::v0::Constant::create(ov::element::i64, {1}, {INT_MAX}); + auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {2}); + auto begin = context.get_input("rs_slot_begin_" + context.get_name()); + auto src_len = std::make_shared( + std::make_shared(src, ov::element::i64), axis, + ov::op::v0::Constant::create(ov::element::i64, {}, {0})); + auto end = std::make_shared(begin, src_len); + auto head_part = std::make_shared(base, zero, begin, one, axis); + auto tail_part = std::make_shared(base, end, int_max, one, axis); + auto updated = std::make_shared(ov::OutputVector{head_part, src, tail_part}, 2); + return rename_outputs_with_suffix({src, updated}, context.get_name()); + } + if (op_case == 4) { auto src = process_view_input_new(context, 0); auto base = context.get_input(1); diff --git a/ggml/src/ggml-openvino/openvino/op/scale.cpp b/ggml/src/ggml-openvino/openvino/op/scale.cpp index f77d8ce58a6e..e0d0ea182c19 100644 --- a/ggml/src/ggml-openvino/openvino/op/scale.cpp +++ b/ggml/src/ggml-openvino/openvino/op/scale.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include @@ -26,15 +27,20 @@ OutputVector translate_scale(const NodeContext & context) { return translate_recurrent_cache_reset(context); } - auto scaled = std::make_shared(process_view_input_new(context, 0), scale_node); - - std::shared_ptr res; + // Multiply and Add need matching types; compute f16 input in f32 and round once, as the CPU backend does. + auto input = process_view_input_new(context, 0); + const auto input_type = input.get_element_type(); + if (input_type != ov::element::f32) { + input = std::make_shared(input, ov::element::f32); + } + ov::Output res = std::make_shared(input, scale_node); if (bias != 0.0f) { auto bias_node = std::make_shared(ov::element::f32, ov::Shape{}, std::vector{bias}); - res = std::make_shared(scaled, bias_node); - } else { - res = scaled; + res = std::make_shared(res, bias_node); + } + if (input_type != ov::element::f32) { + res = std::make_shared(res, input_type); } return rename_outputs_with_suffix({res}, context.get_name()); diff --git a/ggml/src/ggml-openvino/openvino/op/selective_ssm.hpp b/ggml/src/ggml-openvino/openvino/op/selective_ssm.hpp new file mode 100644 index 000000000000..509b43e0005f --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/op/selective_ssm.hpp @@ -0,0 +1,42 @@ +// Copyright (C) 2018-2026 Intel Corporation +// SPDX-License-Identifier: Apache-2.0 +// +// Local mirror of OpenVINO's ov::op::internal::SelectiveSSM declaration +// (src/core/dev_api/openvino/op/selective_ssm.hpp). The implementation comes from the linked +// OpenVINO runtime; the class layout must stay in sync with the runtime's declaration. +#pragma once + +#include "openvino/op/op.hpp" + +namespace ov::op::internal { +/// Mamba2 selective state-space recurrence (arXiv:2405.21060). +/// dA = exp(A * dt), dtB = dt * B; per token t: +/// dBx_t = x_t (x) dtB_t, state_t = state_{t-1} * dA_t + dBx_t, y_t = sum(state_t * C_t). +/// B and C are grouped and shared across heads: head h reads group h / (num_heads / num_groups). +class OPENVINO_API SelectiveSSM : public ov::op::Op { +public: + OPENVINO_OP("SelectiveSSM") + + SelectiveSSM() = default; + /// \param A (Negative) log-decay rates per head [num_heads]. + /// \param dt Per-token, per-head time steps [batch_size, seq_len, num_heads]. + /// \param B Grouped input projection [batch_size, seq_len, num_groups, state_size]. + /// \param x Input hidden states [batch_size, seq_len, num_heads, head_dim]. + /// \param C Grouped output projection [batch_size, seq_len, num_groups, state_size]. + /// \param recurrent_state Initial state [batch_size, num_heads, head_dim, state_size]. + SelectiveSSM(const Output & A, + const Output & dt, + const Output & B, + const Output & x, + const Output & C, + const Output & recurrent_state); + + /// \param args Input tensor vector in order: A, dt, B, x, C, recurrent_state. + explicit SelectiveSSM(const ov::OutputVector & args); + + void validate_and_infer_types() override; + bool visit_attributes(AttributeVisitor & visitor) override; + std::shared_ptr clone_with_new_inputs(const ov::OutputVector & new_args) const override; +}; + +} // namespace ov::op::internal diff --git a/ggml/src/ggml-openvino/openvino/op/set_rows.cpp b/ggml/src/ggml-openvino/openvino/op/set_rows.cpp index 1eae9408b83e..476890911c04 100644 --- a/ggml/src/ggml-openvino/openvino/op/set_rows.cpp +++ b/ggml/src/ggml-openvino/openvino/op/set_rows.cpp @@ -90,12 +90,71 @@ static OutputVector translate_conv_snapshots(const NodeContext & context) { return rename_outputs_with_suffix({result}, name); } +// SET_ROWS into a column range of a plain 2-D buffer (see GgmlOvDecoder::is_column_set_rows). The result is the +// whole buffer: the indexed rows get the new columns, the other columns and rows keep their values, so the next +// write into another column range of the same buffer reads this one. +static OutputVector translate_column_set_rows(const NodeContext & context) { + using namespace ov::op; + auto i64_const = [](const std::vector & values) { + return v0::Constant::create(ov::element::i64, {values.size()}, values); + }; + + const auto view_shape = context.get_view_input_ggml_shape(2, 0); // [1, 1, rows, width] + FRONT_END_OP_CONVERSION_CHECK(view_shape.size() == 4, "SET_ROWS column write needs a 4-D destination view"); + const int64_t width = (int64_t) view_shape[3]; + + auto base = context.get_input(2); + const auto base_shape = base.get_partial_shape(); + FRONT_END_OP_CONVERSION_CHECK(base_shape.rank().is_static() && base_shape[base_shape.size() - 1].is_static(), + "SET_ROWS column write needs a static buffer row size"); + const int64_t row_size = base_shape[base_shape.size() - 1].get_length(); + const size_t elem_size = context.get_output_type().size(); + const int64_t col_begin = (int64_t) (context.get_view_input_offset(2, 0) / elem_size) % row_size; + const int64_t col_end = col_begin + width; + FRONT_END_OP_CONVERSION_CHECK(col_end <= row_size, "SET_ROWS column range is out of bounds"); + + Output data = std::make_shared(process_view_input_new(context, 0), i64_const({1, 1, -1, width}), + false); + if (data.get_element_type() != context.get_output_type()) { + data = std::make_shared(data, context.get_output_type()); + } + Output rows = std::make_shared(process_view_input_new(context, 1), i64_const({-1}), false); + if (rows.get_element_type() != ov::element::i64) { + rows = std::make_shared(rows, ov::element::i64); + } + + auto axis = v0::Constant::create(ov::element::i64, {}, {2}); + auto buffer = std::make_shared(base, i64_const({1, 1, -1, row_size}), false); + Output updates = data; + if (width < row_size) { + auto existing = std::make_shared(buffer, rows, axis); + auto col_axis = i64_const({3}); + OutputVector parts; + if (col_begin > 0) { + parts.push_back(std::make_shared(existing, i64_const({0}), i64_const({col_begin}), + i64_const({1}), col_axis)); + } + parts.push_back(data); + if (col_end < row_size) { + parts.push_back(std::make_shared(existing, i64_const({col_end}), i64_const({row_size}), + i64_const({1}), col_axis)); + } + updates = std::make_shared(parts, 3); + } + auto updated = std::make_shared(buffer, rows, updates, axis); + auto res = std::make_shared(updated, std::make_shared(base, ov::element::i64), false); + return rename_outputs_with_suffix({res}, context.get_name()); +} + OutputVector translate_set_rows(const NodeContext & context) { num_inputs_check(context, 3, 3); if (context.get_op_case() == 3) { return translate_conv_snapshots(context); } + if (context.get_op_case() == 4) { + return translate_column_set_rows(context); + } auto data = process_view_input_new(context, 0); auto indices = process_view_input_new(context, 1); diff --git a/ggml/src/ggml-openvino/openvino/op/ssm_scan.cpp b/ggml/src/ggml-openvino/openvino/op/ssm_scan.cpp new file mode 100644 index 000000000000..fce8e111ed42 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/op/ssm_scan.cpp @@ -0,0 +1,63 @@ +// Copyright (C) 2018-2026 Intel Corporation +// SPDX-License-Identifier: Apache-2.0 +// +// Adapted from OpenVINO's GGUF frontend (src/frontends/gguf/src/op/ssm_scan.cpp). + +#include "../node_context.h" +#include "../op_table.h" +#include "../utils.h" +#include "selective_ssm.hpp" + +#include +#include +#include +#include +#include +#include + +namespace ov { +namespace frontend { +namespace ggml { +namespace op { + +OutputVector translate_ssm_scan(const NodeContext & context) { + num_inputs_check(context, 7, 7); + using namespace ov::op; + + // ggml: s [slots,H,D,S], x [B,T,H,D], dt [1,B,T,H], A [1,1,H,1], + // B/C [B,T,G,S], ids [1,1,1,B]. Only Mamba2 has scalar decay per head. + const auto a_shape = context.get_input_shape(3); + FRONT_END_OP_CONVERSION_CHECK(a_shape.rank() == 4 && a_shape[0] == 1 && a_shape[1] == 1 && a_shape[3] == 1, + "SSM_SCAN: SelectiveSSM requires Mamba2 scalar decay per head; " + "Mamba1 state-wise decay is not supported"); + const auto x = process_view_input_new(context, 1); + const auto flat = v0::Constant::create(element::i64, {1}, {-1}); + const auto axis0 = v0::Constant::create(element::i64, {}, {0}); + const auto ids = std::make_shared(process_view_input_new(context, 6), flat, false); + const auto state = std::make_shared(process_view_input_new(context, 0), ids, axis0); + const auto a = std::make_shared(process_view_input_new(context, 3), flat, false); + const auto dt_shape = std::make_shared(std::make_shared(x), + v0::Constant::create(element::i64, {3}, {0, 1, 2}), + axis0); + const auto dt = + std::make_shared(std::make_shared(process_view_input_new(context, 2), dt_shape, false)); + const auto ssm = std::make_shared(a, + dt, + process_view_input_new(context, 4), + x, + process_view_input_new(context, 5), + state); + // Pack directly in GGML layout so whole-part views can select either Concat input. + const auto packed_shape = v0::Constant::create(element::i64, {4}, {1, 1, 1, -1}); + const auto y = std::make_shared(ssm->output(0), packed_shape, false); + const auto s = std::make_shared(ssm->output(1), packed_shape, false); + const auto result = std::make_shared(OutputVector{y, s}, 3); + result->get_rt_info()[GGML_OV_SSM_SCAN_PACKED] = true; + return rename_outputs_with_suffix({result}, context.get_name()); +} + +} // namespace op +} // namespace ggml +} // namespace frontend +} // namespace ov + diff --git a/ggml/src/ggml-openvino/openvino/op/tri.cpp b/ggml/src/ggml-openvino/openvino/op/tri.cpp index 9b7774a383ec..ba2efdc0bf1f 100644 --- a/ggml/src/ggml-openvino/openvino/op/tri.cpp +++ b/ggml/src/ggml-openvino/openvino/op/tri.cpp @@ -70,7 +70,8 @@ OutputVector translate_tri(const NodeContext & context) { throw std::runtime_error("translate_tri: invalid tri_type " + std::to_string(tri_type)); } - auto zero = ov::op::v0::Constant::create(ov::element::f32, {}, {0.0f}); + // Select needs the zero in the input's type (f32, f16 or bf16). + auto zero = ov::op::v0::Constant::create(x.get_element_type(), {}, {0.0f}); auto res = std::make_shared(mask, x, zero); return rename_outputs_with_suffix({res}, context.get_name()); diff --git a/ggml/src/ggml-openvino/openvino/op_table.cpp b/ggml/src/ggml-openvino/openvino/op_table.cpp index 399c17ac0162..defc428d1d4c 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.cpp +++ b/ggml/src/ggml-openvino/openvino/op_table.cpp @@ -98,6 +98,7 @@ std::unordered_map get_supported_ops() { {"GGML_OP_PAD", op::translate_pad }, {"GGML_OP_TOP_K", op::translate_top_k }, {"GGML_OP_SSM_CONV", op::translate_ssm_conv }, + {"GGML_OP_SSM_SCAN", op::translate_ssm_scan }, {"GGML_OP_GATED_DELTA_NET", op::translate_gated_delta_net }, {"GGML_OP_REPEAT", op::translate_repeat }, {"GGML_OP_CUMSUM", op::translate_cumsum }, diff --git a/ggml/src/ggml-openvino/openvino/op_table.h b/ggml/src/ggml-openvino/openvino/op_table.h index 206966a935ff..54c60c634bf6 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.h +++ b/ggml/src/ggml-openvino/openvino/op_table.h @@ -49,6 +49,7 @@ GGML_OP_CONVERTER(translate_flash_attn_ext); GGML_OP_CONVERTER(translate_clamp); GGML_OP_CONVERTER(translate_pad); GGML_OP_CONVERTER(translate_ssm_conv); +GGML_OP_CONVERTER(translate_ssm_scan); GGML_OP_CONVERTER(translate_gated_delta_net); #ifdef GGML_OPENVINO_HAS_CACHE_UPDATE OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, const OutputVector & cache_inputs); diff --git a/ggml/src/ggml-openvino/openvino/utils.cpp b/ggml/src/ggml-openvino/openvino/utils.cpp index ec7513951c01..e82a6c92fc47 100644 --- a/ggml/src/ggml-openvino/openvino/utils.cpp +++ b/ggml/src/ggml-openvino/openvino/utils.cpp @@ -465,6 +465,25 @@ ov::Output process_view_input_new(const NodeContext & context, int inp return input; } + // A VIEW over the packed SSM_SCAN output selects one whole Concat part: y at offset 0, the + // final state after it. The y length is token-dependent, so a static Slice of the flat + // tensor would bake in the captured token count; return the native part instead. + if (view_input_size == 1 && input.get_node_shared_ptr()->get_rt_info().count(GGML_OV_SSM_SCAN_PACKED)) { + const bool is_y = context.get_view_input_offset(input_index, 0) == 0; + auto part = input.get_node_shared_ptr()->input_value(is_y ? 0 : 1).get_node_shared_ptr()->input_value(0); + if (is_y) { + // y keeps its native [n_seqs, n_tokens, n_head, head_dim] layout + return part; + } + // state [n_seqs, n_head, head_dim, d_state] -> view layout [1, 1, n_seqs, d_state * d_inner] + auto n_seqs = get_dimensions(std::make_shared(part, ov::element::i64), {0}); + auto target = std::make_shared( + ov::OutputVector{ov::op::v0::Constant::create(ov::element::i64, {2}, {1, 1}), n_seqs, + ov::op::v0::Constant::create(ov::element::i64, {1}, {-1})}, + 0); + return std::make_shared(part, target, false); + } + // Integer router views can share these strides when their row count is zero. // Packed projections can store query and gate in separate halves of each head. if (!context.is_static() && view_input_size == 1 && input.get_element_type().is_real()) { @@ -534,6 +553,70 @@ ov::Output process_view_input_new(const NodeContext & context, int inp } } + // A VIEW that regroups one contiguous span of every source row, e.g. the z/x/B/C splits of the + // fused mamba projections: [head_dim, n_head, nt, ns] over [d_in_proj, nt, ns] rows. The span + // dims are packed and the remaining dims carry the source's outer strides, so the view is a + // Slice of the source's innermost axis plus a Reshape. + if (!context.is_static() && view_input_size == 1 && input.get_element_type().is_real()) { + const auto source = context.get_view_input_src_ggml_shape(input_index, 0); + const auto view = context.get_view_input_ggml_shape(input_index, 0); + const auto source_stride = context.get_view_input_src_stride(input_index, 0); + const auto view_stride = context.get_view_input_stride(input_index, 0); + const auto in_rank = input.get_partial_shape().rank(); + const size_t nd = view.size(); + if (nd == 4 && source.size() == nd && view_stride.size() == nd && source_stride.size() == nd && + in_rank.is_static() && in_rank.get_length() == static_cast(nd) && + view_stride[nd - 1] == source_stride[nd - 1] && source_stride[nd - 1] > 0) { + const size_t es = source_stride[nd - 1]; + int j = static_cast(nd) - 1; + size_t span = 1; + while (j >= 0 && view_stride[j] == span * es) { + span *= view[j]; + --j; + } + // at least two packed dims replace the source's innermost dim; a one-dim span keeps the + // source rank and is handled by the generic paths below + const int shift = static_cast(nd) - 2 - j; + bool matches = j >= 0 && shift >= 1; + for (int t = 0; matches && t <= j; ++t) { + matches = view[t] == source[t + shift] && view_stride[t] == source_stride[t + shift]; + } + for (int t = 0; matches && t < shift; ++t) { + matches = source[t] == 1; + } + const size_t offset = context.get_view_input_offset(input_index, 0); + const size_t src_offset = context.get_view_input_src_offset(input_index, 0); + if (matches && offset >= src_offset && (offset - src_offset) % es == 0) { + const int64_t begin = static_cast((offset - src_offset) / es); + if (begin + static_cast(span) <= static_cast(source[nd - 1])) { + auto sliced = std::make_shared( + input, ov::op::v0::Constant::create(ov::element::i64, {1}, {begin}), + ov::op::v0::Constant::create(ov::element::i64, {1}, {begin + static_cast(span)}), + ov::op::v0::Constant::create(ov::element::i64, {1}, {1}), + ov::op::v0::Constant::create(ov::element::i64, {1}, {static_cast(nd) - 1})); + const auto view_ov_shape = context.get_view_input_ov_shape(input_index, 0); + std::vector pattern(nd); + size_t dynamic_dims = 0; + for (size_t i = 0; i < nd; ++i) { + if (view_ov_shape.rank().is_static() && view_ov_shape[i].is_static()) { + pattern[i] = view_ov_shape[i].get_length(); + } else { + pattern[i] = -1; + ++dynamic_dims; + } + } + if (dynamic_dims > 1) { + for (size_t i = 0; i < nd; ++i) { + pattern[i] = static_cast(view[i]); + } + } + return std::make_shared( + sliced, ov::op::v0::Constant::create(ov::element::i64, {nd}, pattern), false); + } + } + } + } + // A row range of a 2D weight (BERT's token type row): slice the rows of the [rows, row_size] Constant if (view_input_size == 1 && input.get_partial_shape().rank().is_static() && input.get_partial_shape().rank().get_length() == 2 && @@ -671,14 +754,17 @@ ov::Output process_view_input_new(const NodeContext & context, int inp exact_chunk = i == static_cast(split_dim) || view_ggml_shape[i] == 1 || view_stride_v[i] == view_src_stride_v[i]; } - // stateful execution drops the leading size-1 axis, so the input can be one rank lower than the - // ggml metadata - const auto input_rank = input.get_partial_shape().rank(); - const int64_t rank_shift = input_rank.is_static() ? - static_cast(ndims) - input_rank.get_length() : - static_cast(ndims); + // num_splits is the captured source size: on a dynamic axis (e.g. the token axis of DSpark's + // result_norm, read one block position at a time) the graph is reused with other sizes, and + // each Split output would then hold several rows or the wrong one + const auto input_shape = input.get_partial_shape(); + const int64_t split_axis = input_shape.rank().is_static() ? + split_dim - (int64_t) ndims + input_shape.rank().get_length() : + -1; + const bool split_axis_static = split_axis >= 0 && input_shape[split_axis].is_static() && + input_shape[split_axis].get_length() == num_splits; if (split_index >= 0 && split_index < num_splits && dynamic_split && exact_chunk && - split_dim >= rank_shift) { + split_axis_static) { // the Split keeps its input alive, so only keep a weak reference to it on the input auto src_node = input.get_node_shared_ptr(); std::string rt_key = @@ -689,8 +775,7 @@ ov::Output process_view_input_new(const NodeContext & context, int inp split_node = rt_info[rt_key].as>().lock(); } if (split_node == nullptr) { - auto axis_const = ov::op::v0::Constant::create( - ov::element::i64, {}, {static_cast(split_dim) - rank_shift}); + auto axis_const = ov::op::v0::Constant::create(ov::element::i64, {}, {split_axis}); split_node = std::make_shared(input, axis_const, static_cast(num_splits)); split_node->set_friendly_name(src_node->get_friendly_name() + "_split"); @@ -722,7 +807,8 @@ ov::Output process_view_input_new(const NodeContext & context, int inp // Lambda function to process a single view operation auto process_single_view = - [](ov::Output current, size_t view_offset, const std::vector & view_stride, + [is_static = context.is_static()]( + ov::Output current, size_t view_offset, const std::vector & view_stride, const ov::Shape & view_ggml_shape, const ov::PartialShape & view_ov_shape, const std::string & view_name, size_t view_src_offset, const std::vector & view_src_stride, const ov::Shape & view_src_ggml_shape, const ov::PartialShape & view_src_ov_shape, const std::string & view_src_name) -> ov::Output { @@ -847,7 +933,12 @@ ov::Output process_view_input_new(const NodeContext & context, int inp ov::op::v0::Constant::create(ov::element::i64, {1}, {1}), ov::op::v0::Constant::create(ov::element::i64, {1}, {slice_dim - axis_shift})); - if (view_ov_shape.is_static()) { + // In a static graph a rank-preserving slice (diff_dims has one entry) already has the view + // shape. Skip the Reshape: its target bakes the static chunk size into the token axis, which + // is wrong after the output-ids GET_ROWS of the last layer (1 token in the prefill graph). + const bool rank_kept = is_static && current_rank.is_static() && + static_cast(current_rank.get_length()) == ndims; + if (view_ov_shape.is_static() && !rank_kept) { auto reshaped = std::make_shared( sliced, ov::op::v0::Constant::create(ov::element::i64, {ndims}, view_ov_shape.to_shape()), diff --git a/ggml/src/ggml-openvino/openvino/utils.h b/ggml/src/ggml-openvino/openvino/utils.h index 10344675b21e..aaee05116445 100644 --- a/ggml/src/ggml-openvino/openvino/utils.h +++ b/ggml/src/ggml-openvino/openvino/utils.h @@ -97,6 +97,9 @@ constexpr const char * GGML_OV_GROUPED_ROWS = "ggml_ov_grouped_rows"; // rt_info key on the stateful V cache read with `-fa off` (permute): V is [.., kv, head_size], not transposed constexpr const char * GGML_OV_V_TOKEN_MAJOR = "ggml_ov_v_token_major"; +// rt_info key on the packed SSM_SCAN output Concat [1, 1, 1, y | state]; whole-part VIEWs select one Concat input +constexpr const char * GGML_OV_SSM_SCAN_PACKED = "ggml_ov_ssm_scan_packed"; + namespace op { template OutputVector translate_1to1_match_2_inputs(const NodeContext & context) { num_inputs_check(context, 2, 2); diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 7c5f6b7567b3..c959ce0d9203 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -657,6 +657,30 @@ ov::Tensor convert_ggml_input_to_ov(const std::shared_ptr & ggml_ return *sliced; } + // KQ mask with fewer columns than the rounded KV length (see compute_llm_params): pad it with -inf + const auto & compute_params = ggml_decoder->get_compute_params(); + if (!ggml_decoder->is_static() && name == compute_params.mask_name && + compute_params.attention_size > ggml_tensor->ne[0] && ggml_is_contiguous(ggml_tensor)) { + const size_t rows = ggml_nrows(ggml_tensor); + const size_t cols = ggml_tensor->ne[0]; + const size_t padded_cols = compute_params.attention_size; + ov::Shape shape = GgmlOvDecoder::get_shape(ggml_tensor); + shape.back() = padded_cols; + ov::Tensor padded(GgmlOvDecoder::get_ov_type(ggml_tensor), shape); + auto pad = [&](auto fill) { + using T = decltype(fill); + auto data = pad_input((const T *) ggml_tensor->data, rows, cols, rows, padded_cols, fill); + std::memcpy(padded.data(), data.data(), padded.get_byte_size()); + }; + if (ggml_tensor->type == GGML_TYPE_F16) { + pad(GGML_FP32_TO_FP16(-INFINITY)); + } else { + GGML_ASSERT(ggml_tensor->type == GGML_TYPE_F32); + pad(-INFINITY); + } + return padded; + } + if (ggml_decoder->is_static() && GgmlOvDecoder::is_kvcache(ggml_tensor, ggml_decoder->get_tensor_used_op(ggml_tensor))) { const auto type = ggml_decoder->get_ov_type(ggml_tensor); @@ -2192,8 +2216,21 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared old_m_params = ggml_decoder->get_model_params(); cache_hit = old_m_params.can_reuse_statically(m_params); if (cache_hit && is_prefill && ggml_openvino_kv_slice_enabled()) { - cache_hit = entry->prefill_attention_size == c_params.attention_size && - entry->prefill_attention_size_swa == c_params.attention_size_swa; + // A larger compiled prefill also serves a smaller attended length: the extra KV rows are masked, as with + // the power-of-two rounding. Without this, a new prompt walks up the sizes again, and since only one + // prefill model is kept, every prompt longer than one chunk recompiles. Head-major KV is bound at the + // storage size, so it keeps the exact match. + // The output count is part of the static prefill shape (more than 1 only for llama-perplexity). + const bool reuse_larger = !ggml_openvino_npu_kv_head_major_enabled(); + cache_hit = entry->prefill_output_len == c_params.output_len && + (reuse_larger ? entry->prefill_attention_size >= c_params.attention_size && + entry->prefill_attention_size_swa >= c_params.attention_size_swa : + entry->prefill_attention_size == c_params.attention_size && + entry->prefill_attention_size_swa == c_params.attention_size_swa); + if (cache_hit) { + c_params.attention_size = entry->prefill_attention_size; + c_params.attention_size_swa = entry->prefill_attention_size_swa; + } prefill_size_changed = !cache_hit; } } @@ -2260,6 +2297,7 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared entry->ptr = ggml_decoder; entry->prefill_attention_size = c_params.attention_size; entry->prefill_attention_size_swa = c_params.attention_size_swa; + entry->prefill_output_len = c_params.output_len; entry->decode_attention_size = compiled.decode_attention_size; entry->shared_key = shared_key; entry->decode_window_requests.clear(); @@ -2274,6 +2312,10 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared r_ctx->ov_output_names_cache_prefill[key] = compiled.prefill_output_names; decoder_end_time = conversion_end_time = compile_end_time = ggml_time_us(); GGML_LOG_DEBUG("ggml-openvino: shared compiled model HIT (static)\n"); + if (prefill_size_changed) { + GGML_LOG_INFO("ggml-openvino: reuse the compiled prefill model of attention size %d\n", + c_params.attention_size); + } } else { auto decode_c_params = c_params; if (ggml_openvino_kv_slice_enabled()) { @@ -2600,6 +2642,7 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared entry->ptr = ggml_decoder; entry->prefill_attention_size = c_params.attention_size; entry->prefill_attention_size_swa = c_params.attention_size_swa; + entry->prefill_output_len = c_params.output_len; entry->decode_attention_size = decode_c_params.attention_size; entry->shared_key = shared_key; entry->decode_window_requests.clear(); @@ -3180,7 +3223,7 @@ enum ggml_status ov_graph_compute(ggml_cgraph * cgraph, ggml_backend_t backend) GgmlOvDecoder::dump_cgraph(cgraph, filename); } - const auto is_static = ggml_openvino_is_npu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC"); + const auto is_static = ggml_openvino_is_static(); GGML_ASSERT(ctx->runtime_context != nullptr); std::shared_ptr r_ctx = std::static_pointer_cast(ctx->runtime_context); diff --git a/ggml/src/ggml-openvino/utils.h b/ggml/src/ggml-openvino/utils.h index 31fa7abc2435..c4450a387748 100644 --- a/ggml/src/ggml-openvino/utils.h +++ b/ggml/src/ggml-openvino/utils.h @@ -42,6 +42,11 @@ struct graph_key { if (GgmlOvDecoder::is_sampling_view(node)) { input_srcs.push_back("sampling_row_" + std::string(node->name) + "#n" + std::to_string(i)); } + // The output set is part of the model (one Result per output). Enabling outputs on an existing graph, + // e.g. llama_set_embeddings_layer_inp() for a DFlash/DSpark drafter, changes only the flags. + if (node->flags & GGML_TENSOR_FLAG_OUTPUT) { + input_srcs.push_back("output_" + std::string(node->name) + "#n" + std::to_string(i)); + } } static const bool full_key = ggml_openvino_getenv_int("GGML_OPENVINO_FULL_GRAPH_KEY") != 0; @@ -95,9 +100,11 @@ struct decoder_runtime_ctx { std::shared_ptr mutex; std::shared_ptr ptr; - // Attention sizes the cached prefill model was built with; decode calls overwrite the decoder's. + // 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; diff --git a/ggml/src/ggml-sycl/CMakeLists.txt b/ggml/src/ggml-sycl/CMakeLists.txt index 8312a83052ca..0a5aede0bfe4 100644 --- a/ggml/src/ggml-sycl/CMakeLists.txt +++ b/ggml/src/ggml-sycl/CMakeLists.txt @@ -218,6 +218,8 @@ endif() if (GGML_SYCL_TARGET STREQUAL "INTEL") add_compile_definitions(GGML_SYCL_WARP_SIZE=16) + # With AOT the option goes to ocloc inside -options (see GGML_SYCL_DEVICE_ARCH below): a bare + # -Xs hands it to ocloc as a command-line flag, which fails the device link. if (NOT GGML_SYCL_DEVICE_ARCH) target_link_options(ggml-sycl PRIVATE -Xs -ze-intel-greater-than-4GB-buffer-required) else() @@ -248,10 +250,18 @@ endif() if (GGML_SYCL_DEVICE_ARCH) message(STATUS "GGML_SYCL_DEVICE_ARCH=${GGML_SYCL_DEVICE_ARCH} (AOT via spir64_gen)") + # AOT (oneAPI 2026.2) ignores the grf_size<256> kernel property on ESIMD kernels and builds them + # with 128 registers, which made the ESIMD MoE GEMM 1.7-3.9x slower than under JIT; SPMD kernels + # keep honouring the property. A module-wide -doubleGRF also moves the ESIMD kernels that ask for + # 128 to 256, and a server built with it hung on its first request, so IGC picks the size per + # kernel from its register pressure instead (ESIMD kernels too; -ze-opt-large-grf-kernel does not + # reach them). + set(GGML_SYCL_AOT_BACKEND_OPTIONS + "-device ${GGML_SYCL_DEVICE_ARCH} -options '-ze-intel-greater-than-4GB-buffer-required -ze-opt-enable-auto-large-GRF-mode'") target_compile_options( ggml-sycl PRIVATE -fsycl-targets=spir64_gen - "SHELL:-Xsycl-target-backend=spir64_gen \"-device ${GGML_SYCL_DEVICE_ARCH} -options -ze-intel-greater-than-4GB-buffer-required\"" + "SHELL:-Xsycl-target-backend=spir64_gen \"${GGML_SYCL_AOT_BACKEND_OPTIONS}\"" ) # Pass through parallel job (process) count for parallelising the @@ -266,7 +276,7 @@ if (GGML_SYCL_DEVICE_ARCH) target_link_options( ggml-sycl PRIVATE -fsycl-targets=spir64_gen - "SHELL:-Xsycl-target-backend=spir64_gen \"-device ${GGML_SYCL_DEVICE_ARCH} -options -ze-intel-greater-than-4GB-buffer-required\"" + "SHELL:-Xsycl-target-backend=spir64_gen \"${GGML_SYCL_AOT_BACKEND_OPTIONS}\"" -fsycl-max-parallel-link-jobs=${GGML_SYCL_MAX_PARALLEL_LINK_JOBS} ) diff --git a/ggml/src/ggml-sycl/common.hpp b/ggml/src/ggml-sycl/common.hpp index 75e783d12095..ae156acca75f 100644 --- a/ggml/src/ggml-sycl/common.hpp +++ b/ggml/src/ggml-sycl/common.hpp @@ -72,6 +72,7 @@ extern int g_ggml_sycl_debug; extern int g_ggml_sycl_enable_optimize; extern int g_ggml_sycl_enable_fusion; extern int g_ggml_sycl_enable_esimd; +extern int g_ggml_sycl_mmid_esimd; extern int g_ggml_sycl_mmvq_wide; extern int g_ggml_sycl_enable_xmx_esimd; extern int g_ggml_sycl_xmx_max_cols; diff --git a/ggml/src/ggml-sycl/conv.cpp b/ggml/src/ggml-sycl/conv.cpp index 475bd34a25d5..5f15c25a2e01 100644 --- a/ggml/src/ggml-sycl/conv.cpp +++ b/ggml/src/ggml-sycl/conv.cpp @@ -28,16 +28,17 @@ static void conv_transpose_1d_kernel( float accumulator = 0; - for (int c = 0; c < src0_ne2; c++) { - int idx = global_index % dst_ne0; + const int idx = global_index % dst_ne0; + + // only inputs with i*s0 <= idx < i*s0 + src0_ne0 contribute + const int i_begin = idx >= src0_ne0 ? (idx - src0_ne0) / s0 + 1 : 0; + const int i_end = sycl::min(src1_ne0, idx / s0 + 1); + for (int c = 0; c < src0_ne2; c++) { int kernel_offset = (src0_ne0 * src0_ne1 * c) + (out_index * src0_ne0); int input_offset = src1_ne0 * c; - for (int i = 0; i < src1_ne0; i++) { - if (!(idx >= i*s0 && idx < i*s0 + src0_ne0)) { - continue; - } + for (int i = i_begin; i < i_end; i++) { int weight_idx = idx - i*s0; float kernel_weight = src0[kernel_offset + weight_idx]; diff --git a/ggml/src/ggml-sycl/convert.cpp b/ggml/src/ggml-sycl/convert.cpp index 1e7edf3b8a82..e991e29e7129 100644 --- a/ggml/src/ggml-sycl/convert.cpp +++ b/ggml/src/ggml-sycl/convert.cpp @@ -516,6 +516,16 @@ static void dequantize_row_iq4_nl_sycl(const void *vx, dst_t *y, const int64_t k } } +template +static void dequantize_row_iq4_sycl_reorder(const void * vx, dst_t * y, const int64_t k, dpct::queue_ptr stream) { + // flat range<1>, four qs bytes (8 outputs) per item + GGML_ASSERT(k % ggml_sycl_reordered::block_q_t::traits::qk == 0); + stream->parallel_for(sycl::range<1>((size_t) (k / 8)), + [=](sycl::id<1> idx) { + dequantize_block_iq4_reorder_wide(vx, y, k, idx); + }); +} + template static void dequantize_row_mxfp4_sycl(const void * vx, dst_t * y, const int64_t k, dpct::queue_ptr stream) { const int nb = (k + QK_K - 1) / QK_K; @@ -743,9 +753,17 @@ static to_t_sycl_t ggml_get_dequant_sycl(ggml_type type, ggml_tensor * ds return dequantize_row_iq3_s_sycl; } case GGML_TYPE_IQ4_XS: - return dequantize_row_iq4_xs_sycl; + if (is_reordered_src0(dst)) { + return dequantize_row_iq4_sycl_reorder; + } else { + return dequantize_row_iq4_xs_sycl; + } case GGML_TYPE_IQ4_NL: - return dequantize_row_iq4_nl_sycl; + if (is_reordered_src0(dst)) { + return dequantize_row_iq4_sycl_reorder; + } else { + return dequantize_row_iq4_nl_sycl; + } case GGML_TYPE_MXFP4: if (is_reordered_src0(dst)) { return dequantize_row_mxfp4_sycl_reorder; diff --git a/ggml/src/ggml-sycl/dequantize.hpp b/ggml/src/ggml-sycl/dequantize.hpp index eb94771d673f..98f1aff6f3b8 100644 --- a/ggml/src/ggml-sycl/dequantize.hpp +++ b/ggml/src/ggml-sycl/dequantize.hpp @@ -15,6 +15,7 @@ #include "common.hpp" #include "convert.hpp" +#include "quants.hpp" typedef void (*dequantize_kernel_t)(const void * vx, const int64_t ib, const int iqs, dfloat2 & v); typedef void (*dequantize_kernel_t_reorder)(const void *d, const int64_t ib, const void *qs, @@ -674,6 +675,15 @@ static __dpct_inline__ void dequantize_iq4_nl(const void *vx, const int64_t ib, v.y() = dequantize_one(iqs + 1); } +static __dpct_inline__ void dequantize_iq4_nl_reorder(const void * d_ptr, const int64_t ib, const void * qs, + const int iqs, dfloat2 & v) { + const float d = (float) ((const sycl::half *) d_ptr)[ib]; + const uint8_t q = ((const uint8_t *) qs)[iqs]; + + v.x() = d * kvalues_iq4nl[q & 0xF]; + v.y() = d * kvalues_iq4nl[q >> 4]; +} + static __dpct_inline__ void dequantize_iq4_xs(const void *vx, const int64_t ib, const int iqs, dfloat2 &v) { #if QK_K == 256 @@ -1758,6 +1768,60 @@ dequantize_block_iq4_xs(const void *__restrict__ vx, dst_t *__restrict__ yy, } } +// reordered IQ4_NL / IQ4_XS: qs bytes iq .. iq + 3 of 32-value group g to y[iq + j] and y[iq + 16 + j], with y the +// group's first output, in two vec stores as for MXFP4; tail is the first byte after all qs +template +static __dpct_inline__ void dequantize_iq4_reorder_quad(const uint8_t * __restrict__ x, + const uint8_t * __restrict__ tail, const int64_t g, + const int iq, dst_t * __restrict__ y) { + const uint8_t * qs = x + 16 * g + iq; + const float d = ggml_sycl_reordered::iq4_group_scale(tail, g); + + sycl::vec lo, hi; +#pragma unroll + for (int j = 0; j < 4; ++j) { + lo[j] = d * kvalues_iq4nl[qs[j] & 0xf]; + hi[j] = d * kvalues_iq4nl[qs[j] >> 4]; + } + *reinterpret_cast *>(y + iq) = lo; + *reinterpret_cast *>(y + iq + 16) = hi; +} + +// flat range over k / 8 items: item i takes group i / 4 from qs byte 4 * (i % 4) +template +static void dequantize_block_iq4_reorder_wide(const void * __restrict__ vx, dst_t * __restrict__ yy, int64_t k, + const sycl::id<1> idx) { + const int64_t i = (int64_t) idx[0]; + const int64_t g = i / 4; + const uint8_t * x = (const uint8_t *) vx; + dequantize_iq4_reorder_quad(x, x + k / 2, g, (int) (4 * (i % 4)), yy + 32 * g); +} + +// item t (0..31) of block ib dequantizes four qs bytes of sub-block t/4 into y, the output of block ib +template +static __dpct_inline__ void dequantize_block_iq4_xs_reorder(const void * __restrict__ vx, dst_t * __restrict__ y, + const int64_t ib, const int t, const int64_t nb) { + const int ib32 = t / 4; + const int iq = 4 * (t % 4); + + const uint8_t * qs = (const uint8_t *) vx + ib * (QK_K / 2) + 16 * ib32 + iq; + const uint8_t * meta = (const uint8_t *) vx + nb * (QK_K / 2) + ib * offsetof(block_iq4_xs, qs); + const uint16_t scales_h = *(const uint16_t *) (meta + offsetof(block_iq4_xs, scales_h)); + const uint8_t scales_l = meta[offsetof(block_iq4_xs, scales_l) + ib32 / 2]; + const float d = (float) *(const ggml_half *) (meta + offsetof(block_iq4_xs, d)) * + ((((scales_l >> (4 * (ib32 % 2))) & 0xf) | (((scales_h >> (2 * ib32)) & 3) << 4)) - 32); + + sycl::vec lo, hi; +#pragma unroll + for (int j = 0; j < 4; ++j) { + lo[j] = d * kvalues_iq4nl[qs[j] & 0xf]; + hi[j] = d * kvalues_iq4nl[qs[j] >> 4]; + } + dst_t * yb = y + 32 * ib32 + iq; + *reinterpret_cast *>(yb) = lo; + *reinterpret_cast *>(yb + 16) = hi; +} + template static void dequantize_block_mxfp4(const void * __restrict__ vx, dst_t * __restrict__ yy, const sycl::nd_item<3> &item_ct1) { diff --git a/ggml/src/ggml-sycl/fused-gemm-esimd.cpp b/ggml/src/ggml-sycl/fused-gemm-esimd.cpp new file mode 100644 index 000000000000..37f87e377819 --- /dev/null +++ b/ggml/src/ggml-sycl/fused-gemm-esimd.cpp @@ -0,0 +1,1160 @@ +#include "fused-gemm-esimd.hpp" + +#include +#include +#include + +// One thread owns MR rows of one expert's weight and one BN-wide tile of the schedule, over the +// whole K. Per k step (32 values) it loads the rows' stored bits, dequantizes them in registers to +// the f16 A operand of dpas (RC = 8 rows x 16 k, row major) and multiplies it with the packed B, +// which is already the dpas VNNI operand: [K/2][Npad][2] halves, NW columns a dpas. +// +// The joint_matrix kernel dequantizes into SLM and reads it back in the same sub-group, which is +// staging, not sharing; dpas takes registers, so that round trip and its barriers are gone here. +// Its K split over GGML_SYCL_GROUPED_GEMM_KSPLIT sub-groups is reproduced as sequential K ranges summed in +// the same ascending order as its tile_c reduction, and every format below rounds A exactly as its +// joint_matrix A stage does, so the output is the same bits. +// +// A weight format is a grouped_gemm_esimd_a with: raw, the stored bits of the MR rows for one k +// step; load(), which fetches them from the expert's slice in either layout (grouped_gemm_esimd::slice); and +// decode(), the f16 A of one row group. +// It reads the same fields as the joint_matrix A stage of its format. +// +// The kernel is built for one grouped_gemm_arch: the dpas width NW (the columns of B one dpas takes, the +// sub-group size of the joint_matrix combination it stands in for), the rows of one thread, and +// whether 2D block loads exist. Xe2 and Xe-HPC: 16 wide, 32 rows, 2D loads. Xe-HPG (Arc A, ARL-H): +// 8 wide, no 2D block messages, and 256 registers of 32 bytes, half of Xe2's file, so 16 rows: its +// 32-row accumulators alone would take half the registers. +static constexpr int GGML_SYCL_GROUPED_GEMM_KSPLIT = FG_KSPLIT; +static constexpr int GGML_SYCL_GROUPED_GEMM_BN = GGML_SYCL_FG_BN; +static constexpr int GROUPED_GEMM_MR = 32; // rows of one thread on Xe2: one 2D load covers them +static constexpr int GROUPED_GEMM_RC = 8; // rows of one dpas +static constexpr int GROUPED_GEMM_QK = 32; // values of one k step + +template struct grouped_gemm_arch { + static constexpr int NW = NW_; + static constexpr int MR = MR_; + static constexpr bool L2D = L2D_; +}; + +using grouped_gemm_xe2 = grouped_gemm_arch<16, GROUPED_GEMM_MR, true>; +using grouped_gemm_xehpg = grouped_gemm_arch<8, 16, false>; + +// An AOT build compiles each kernel only for the targets of its dpas width: GGML_SYCL_XMX_AOT_SG for +// spir64_gen, FG_AOT_SG (fused-gemm.hpp) for intel_gpu_* targets. A build without XMX (GGML_SYCL_SUPPORT_XMX +// off) compiles none of them +template static constexpr bool grouped_gemm_built() { +#if !defined(GGML_SYCL_SUPPORT_XMX) + return false; +#elif defined(GGML_SYCL_XMX_AOT_SG) + return A::NW == GGML_SYCL_XMX_AOT_SG; +#elif defined(FG_AOT_SG) + return A::NW == FG_AOT_SG; +#else + return true; +#endif +} + +namespace grouped_gemm_esimd { +using namespace sycl::ext::intel::esimd; + +// f(std::integral_constant) for I in [0, N): register selects at a runtime offset become +// indirect accesses, so loops whose index picks registers are spelled out at compile time +template struct static_for { + template static ESIMD_INLINE void run(Fn & f) { + if constexpr (I < N) { + f(std::integral_constant{}); + static_for::run(f); + } + } +}; + +// One field of a format's block. In the reorder (SoA) layout it is a stream of its own, `size` bytes +// a block, after `pre` bytes a block of the streams before it; in the canonical (AoS) layout it is +// `aos` bytes into the block. +struct field { + int pre; + int size; + int aos; +}; + +// Where one thread's rows sit in an expert's slice, in either layout. nblocks counts the stored blocks +// of the slice, bpr those of one row, bs is the size of one block. +template struct slice { + const uint8_t * x; + int M; + int bpr; + int nblocks; + int m0; + bool aos; + int bs; + + // per row, the byte offset from x of byte `inner` of field f of block ib + ESIMD_INLINE simd at(const field & f, const int ib, const int inner) const { + const int stride = aos ? bs : f.size; + simd o(0, (uint32_t) (bpr * stride)); + return o + (uint32_t) ((aos ? f.aos : nblocks * f.pre) + (m0 * bpr + ib) * stride + inner); + } + + // a field's bytes at offset `inner` start on a dword in every block (the AoS block and offset + // are multiples of 4); the SoA streams always do + ESIMD_INLINE bool dword_aligned(const field & f, const int inner) const { + return !aos || (bs % 4 == 0 && (f.aos + inner) % 4 == 0); + } + + ESIMD_INLINE simd u16(const field & f, const int ib, const int inner) const { + return gather((const uint16_t *) x, at(f, ib, inner)); + } + + ESIMD_INLINE simd u32(const field & f, const int ib, const int inner) const { + if (dword_aligned(f, inner)) { + return gather((const uint32_t *) x, at(f, ib, inner)); + } + return rows<1>(f, ib, inner); + } + + // W dwords of each of the MR rows from byte `inner` (a multiple of 4) of field f of block ib, as + // [row][W]. SoA with 2D block loads (L2D): one message over the stream. Otherwise the rows' dwords + // are gathered, as [W][row], at offsets rounded down to a dword (every field starts on an even + // byte; the SoA streams are dword aligned), shifted by 16 bits where an AoS row's block starts on + // 2 mod 4, and transposed with strided reads. + template ESIMD_INLINE simd rows(const field & f, const int ib, const int inner) const { + if constexpr (L2D) { + if (!aos) { + const unsigned pitch = (unsigned) (bpr * f.size); + return load_2d((const uint32_t *) (x + (size_t) nblocks * f.pre), pitch - 1, M - 1, + pitch - 1, (ib * f.size + inner) / 4, m0); + } + } + const simd o = at(f, ib, inner); + simd g; + if (dword_aligned(f, inner)) { + g = gather((const uint32_t *) x, o); + } else { + // per row: sh is 16 where the run starts on 2 mod 4, else 0; hm keeps the next dword's low + // half only where it is needed + const simd oa = o & ~3u; + const simd sh = (o & 2u) << 3; + const simd hm = 0u - (sh >> 4); + simd lo = gather((const uint32_t *) x, oa); + // the dword after the run holds its last 2 bytes where a row needs it; a row that does not + // reads its first dword again rather than past the field + const simd tail = gather((const uint32_t *) x, oa + ((4u * W) & hm)); + auto shift = [&](auto vc) SYCL_ESIMD_FUNCTION { + constexpr int v = decltype(vc)::value; + simd a = lo.template select(v * MR); + simd b; + if constexpr (v + 1 < W) { + b = lo.template select((v + 1) * MR); + } else { + b = tail; + } + g.template select(v * MR) = (a >> sh) | ((b << 16) & hm); + }; + static_for<0, W>::run(shift); + } + if constexpr (W == 1) { + return g; + } else { + simd t; + auto row = [&](auto rc) SYCL_ESIMD_FUNCTION { + constexpr int r = decltype(rc)::value; + t.template select(r * W) = g.template select(r); + }; + static_for<0, MR>::run(row); + return t; + } + } +}; + +// A decode returns its row group's A in the order the two dpas of a k step read it, [k half][row][16 +// k]: both iq formats store k and k + 16 in the same byte or grid dword half, so that order needs +// only reads with a stride, while [row][32 k] needed strided writes, which split into SIMD4. +using a_halves = simd; + +// f16 of the f32 product code * scale, each row's scale over its 16 values of a k half: the +// expression the joint_matrix stages evaluate before E::make rounds it +ESIMD_INLINE simd scale_half(simd v, + simd d) { + v *= d.template replicate_vs_w_hs(0); + return v; +} + +// The iq4 codebook by byte, in SLM: entry b holds the values of its low and its high nibble as the +// two 16-bit halves of one dword, as T (half, or int16 for an f32 product). A read-only table every +// lane indexes, which is what SLM is for: register-indirect iselect() over the same lanes cost +// 7.3 of 12.7 ms, a 16-entry SLM table per nibble about 0.4. +template ESIMD_INLINE void iq4_pair_table_to_slm() { + static_assert(sizeof(T) == 2, "two values a dword"); + simd lo; +#pragma unroll + for (int i = 0; i < 16; ++i) { + lo[i] = sycl::bit_cast((T) kvalues_iq4nl[i]); + } +#pragma unroll + for (int hi = 0; hi < 16; ++hi) { + slm_block_store(hi * 64, lo | ((uint32_t) sycl::bit_cast((T) kvalues_iq4nl[hi]) << 16)); + } +} + +// 16 packed bytes a row; byte j holds k = j in its low and k = 16 + j in its high nibble (the order +// of fg_decode_iq4_xs and of the iq4_nl stage). One gather per byte; the low halves are k half 0, +// the high halves k half 1, each [row][16]. +template +ESIMD_INLINE simd iq4_codes(simd q) { + simd off = q.template bit_cast_view(); + simd pr = slm_gather(off * 4); + auto pv = pr.template bit_cast_view(); + simd v; + v.template select(0) = pv.template select(0); + v.template select(GROUPED_GEMM_RC * 16) = pv.template select(1); + return v; +} +// A 2D surface: rows `pitch` bytes apart, 16-byte aligned and at least 64 bytes +constexpr bool surface_ok(const int pitch) { + return pitch % 16 == 0 && pitch >= 64; +} + +// byte i of each lane's dword, i a runtime index: a shift by a scalar, not a register pick +template ESIMD_INLINE simd byte_of(simd w, const int i) { + return (w >> (8 * i)) & 0xffu; +} + +// one of four per-lane dwords by a runtime index, as uniform branches rather than a register pick +template ESIMD_INLINE simd dword_of(simd * w, const int i) { + simd r = w[0]; + if (i == 1) { + r = w[1]; + } else if (i == 2) { + r = w[2]; + } else if (i == 3) { + r = w[3]; + } + return r; +} + +// a row group's 32 k-ordered code bytes a row as f32, in [k half][row][16 k] +ESIMD_INLINE simd byte_codes(simd q) { + auto bm = q.template bit_cast_view(); + simd v; + v.template select(0) = bm.template select(0, 0); + v.template select(GROUPED_GEMM_RC * 16) = + bm.template select(0, 16); + return v; +} + +// f16 of d * code - m in f32, each row's d and m over its 16 values of a k half: the expression of +// the K-quant stages with a min +ESIMD_INLINE simd scale_min_half(simd v, + simd d, + simd m) { + v = v * d.template replicate_vs_w_hs(0) - + m.template replicate_vs_w_hs(0); + return v; +} + +// the two k halves of a row group, the code bytes times one (d, m) per row and half +ESIMD_INLINE a_halves halves_dm(simd q, + simd d0, + simd m0, + simd d1, + simd m1, + const float bias = 0.0f) { + simd c = byte_codes(q); + if (bias != 0.0f) { + c -= bias; + } + a_halves v; + v.template select(0) = + scale_min_half(c.template select(0), d0, m0); + v.template select(GROUPED_GEMM_RC * 16) = + scale_min_half(c.template select(GROUPED_GEMM_RC * 16), d1, m1); + return v; +} + +// a row group's 32 values from grid dwords (byte b of entry e is k = 4e + b) and a sign dword per +// row (bit k negates k), times d: the expression of the iq3 stages +ESIMD_INLINE a_halves grid_signed(simd ge, + simd signs, + simd d) { + auto gm = ge.template bit_cast_view(); + simd sg = signs.template replicate_vs_w_hs(0); + simd k(0, 1); + k &= 15; + a_halves v; +#pragma unroll + for (int h = 0; h < 2; ++h) { + simd eh = gm.template select(0, 4 * h); + simd f = eh.template bit_cast_view(); + f.merge(-f, ((sg >> (k + 16 * h)) & 1) != 0); + v.template select(h * GROUPED_GEMM_RC * 16) = scale_half(f, d); + } + return v; +} +} // namespace grouped_gemm_esimd + +template struct grouped_gemm_esimd_a { + static constexpr bool supported = false; +}; + +// [qs 32][d], one block a k step +template struct grouped_gemm_esimd_a { + static constexpr bool supported = true; + static constexpr int qk = QK8_0; + static constexpr bool whole = true; // decode_all() for the whole tile + static constexpr int slm_bytes = 0; + static ESIMD_INLINE void init_slm() {} + struct raw { + grouped_gemm_esimd::simd q; + grouped_gemm_esimd::simd d; + }; + + static constexpr grouped_gemm_esimd::field QS = { 0, QK8_0, 2 }, D = { QK8_0, 2, 0 }; + static bool ok(const int K, const bool aos) { return K % qk == 0 && (aos || K >= 64); } + struct sb_t {}; + template static ESIMD_INLINE void load_sb(sb_t &, const Sl &, const int) {} + template static ESIMD_INLINE void load(raw & r, sb_t &, const Sl & s, const int kb, const int) { + r.q = s.template rows<8>(QS, kb, 0); + r.d = s.u16(D, kb, 0); + } + // all MR x 32 quants at once: int8 -> half, times the row's scale. q * d needs at most 19 + // significant bits, so the f32 product the joint_matrix stage rounds to half is exact and one + // correctly rounded half multiply gives the same bits. + static ESIMD_INLINE grouped_gemm_esimd::simd decode_all(raw & r) { + using namespace grouped_gemm_esimd; + simd av = r.q.template bit_cast_view(); + simd dh = r.d.template bit_cast_view(); + av *= dh.template replicate_vs_w_hs(0); + return av; + } +}; + +// [qs 16][d], one block a k step +template struct grouped_gemm_esimd_a { + static constexpr bool supported = true; + static constexpr int qk = QK4_NL; + static constexpr bool whole = false; + static constexpr int slm_bytes = 256 * sizeof(uint32_t); + + static ESIMD_INLINE void init_slm() { grouped_gemm_esimd::iq4_pair_table_to_slm(); } + struct raw { + grouped_gemm_esimd::simd q; + grouped_gemm_esimd::simd d; + }; + + static constexpr grouped_gemm_esimd::field QS = { 0, QK4_NL / 2, 2 }, D = { QK4_NL / 2, 2, 0 }; + static bool ok(const int K, const bool aos) { return K % qk == 0 && (aos || K / 2 >= 64); } + struct sb_t {}; + template static ESIMD_INLINE void load_sb(sb_t &, const Sl &, const int) {} + template static ESIMD_INLINE void load(raw & r, sb_t &, const Sl & s, const int kb, const int) { + using namespace grouped_gemm_esimd; + r.q = s.template rows<4>(QS, kb, 0); + simd d = s.u16(D, kb, 0); + r.d = d.template bit_cast_view(); + } + // the codebook values are integers below 128, exact in half, and d * value has at most 18 + // significant bits: one correctly rounded half multiply is the stage's f32 product rounded + template static ESIMD_INLINE grouped_gemm_esimd::a_halves decode(raw & r) { + using namespace grouped_gemm_esimd; + a_halves v = iq4_codes(r.q.template select(g * GROUPED_GEMM_RC * 4)); + simd dg = r.d.template select(g * GROUPED_GEMM_RC); + simd dr = dg.template replicate_vs_w_hs(0); + v.template select(0) *= dr; + v.template select(GROUPED_GEMM_RC * 16) *= dr; + return v; + } +}; + +// [qs 128][d 2][scales_h 2][scales_l 4] per 256 values; k step ib8 of a superblock is sub-block ib8 +template struct grouped_gemm_esimd_a { + static constexpr bool supported = true; + static constexpr int qk = QK_K; + static constexpr bool whole = false; + // int16 table and f32 products: d * (scale - 32) * value can need 24 significant bits, more + // than a half multiply keeps + static constexpr int slm_bytes = 256 * sizeof(uint32_t); + + static ESIMD_INLINE void init_slm() { grouped_gemm_esimd::iq4_pair_table_to_slm(); } + struct raw { + grouped_gemm_esimd::simd q; + grouped_gemm_esimd::simd d; + }; + struct sb_t { + grouped_gemm_esimd::simd d; + grouped_gemm_esimd::simd sh; // scales_h + grouped_gemm_esimd::simd sl; // scales_l, 4 bytes + }; + + static constexpr grouped_gemm_esimd::field QS = { 0, QK_K / 2, 8 }, D = { QK_K / 2, 2, 0 }, + SH = { QK_K / 2 + 2, 2, 2 }, SL = { QK_K / 2 + 4, 4, 4 }; + static bool ok(const int K, const bool) { return K % qk == 0; } + template static ESIMD_INLINE void load_sb(sb_t & sb, const Sl & s, const int ib) { + using namespace grouped_gemm_esimd; + simd dh = s.u16(D, ib, 0); + sb.d = simd(dh.template bit_cast_view()); + sb.sh = s.u16(SH, ib, 0); + sb.sl = s.u32(SL, ib, 0); + } + template static ESIMD_INLINE void load(raw & r, sb_t & sb, const Sl & s, const int kb, const int j) { + using namespace grouped_gemm_esimd; + r.q = s.template rows<4>(QS, kb / 8, 16 * j); + // d * (6-bit scale - 32), in f32 as the stage computes it + simd sc = simd(((sb.sl >> (4 * j)) & 0xf) | (((sb.sh >> (2 * j)) & 3) << 4)) - 32; + r.d = sb.d * simd(sc); + } + + template static ESIMD_INLINE grouped_gemm_esimd::a_halves decode(raw & r) { + using namespace grouped_gemm_esimd; + simd c = + iq4_codes(r.q.template select(g * GROUPED_GEMM_RC * 4)); + simd dg = r.d.template select(g * GROUPED_GEMM_RC); + a_halves v; + v.template select(0) = scale_half(c.template select(0), dg); + v.template select(GROUPED_GEMM_RC * 16) = + scale_half(c.template select(GROUPED_GEMM_RC * 16), dg); + return v; + } +}; + +// [qs 64][qh 8][signs 32][d 2, scales 4] per 256 values. Value k of sub-block ib8 is byte k % 4 of +// grid entry k / 4, the entry index being qs[k / 4] with bit 8 from qh bit k / 4, negated where bit +// k of the sub-block's sign dword is set; times d * (1 + 2 * 4-bit scale) +template struct grouped_gemm_esimd_a { + static constexpr bool supported = true; + static constexpr int qk = QK_K; + static constexpr bool whole = false; + // the 512-entry grid in SLM, read by every lane: the global gather of it cost 2.4x the kernel + static constexpr int slm_bytes = 512 * sizeof(uint32_t); + static ESIMD_INLINE void init_slm() { + using namespace grouped_gemm_esimd; +#pragma unroll + for (int i = 0; i < 512; i += 64) { + slm_block_store(i * 4, block_load(iq3s_grid + i)); + } + } + struct raw { + grouped_gemm_esimd::simd q; // [row][8 qs bytes] + grouped_gemm_esimd::simd qh; // the sub-block's qh byte + grouped_gemm_esimd::simd signs; // the sub-block's 32 sign bits + grouped_gemm_esimd::simd d; + }; + // d and the scale bytes are a block's, kept over its k steps; the sign dword and the qh byte of + // a k step are a 2D load each at that step's column, so no register is picked by a runtime index + struct sb_t { + grouped_gemm_esimd::simd d; + grouped_gemm_esimd::simd sc; // the 4 scale bytes + }; + // the SoA stream {d, scales} is d and scales of the block in AoS, which are not adjacent there: MS + // reads the scales at their SoA offset 2 in the stream, which is AoS offset 2 past 104 + static constexpr int META = QK_K / 4 + QK_K / 32 + QK_K / 8; + static constexpr grouped_gemm_esimd::field QS = { 0, QK_K / 4, 2 }, QH = { QK_K / 4, QK_K / 32, 2 + QK_K / 4 }, + SG = { QK_K / 4 + QK_K / 32, QK_K / 8, 2 + QK_K / 4 + QK_K / 32 }, + MD = { META, 2 + IQ3S_N_SCALE, 0 }, + MS = { META, 2 + IQ3S_N_SCALE, META }; + // the SoA qh and signs streams are 2D surfaces: their row pitches must be 16-byte aligned + static bool ok(const int K, const bool aos) { + return K % qk == 0 && (aos || ((K / QK_K * 8) % 16 == 0 && K / QK_K * 8 >= 64)); + } + template static ESIMD_INLINE void load_sb(sb_t & sb, const Sl & s, const int ib) { + using namespace grouped_gemm_esimd; + simd dh = s.u16(MD, ib, 0); + simd s0 = s.u16(MS, ib, 2); + simd s1 = s.u16(MS, ib, 4); + sb.d = simd(dh.template bit_cast_view()); + sb.sc = s0 | (s1 << 16); + } + template static ESIMD_INLINE void load(raw & r, sb_t & sb, const Sl & s, const int kb, const int j) { + using namespace grouped_gemm_esimd; + const int ib = kb / 8; + r.q = s.template rows<2>(QS, ib, 8 * j); + r.qh = (s.template rows<1>(QH, ib, 4 * (j / 4)) >> (8 * (j % 4))) & 0xffu; + r.signs = s.template rows<1>(SG, ib, 4 * j); + r.d = sb.d * simd(simd(1 + 2 * ((sb.sc >> (4 * j)) & 0xf))); + } + + template static ESIMD_INLINE grouped_gemm_esimd::a_halves decode(raw & r) { + using namespace grouped_gemm_esimd; + // the 8 grid entries of each of the row group's rows + simd qb = + r.q.template select(g * GROUPED_GEMM_RC * 2).template bit_cast_view(); + simd qr = r.qh.template select(g * GROUPED_GEMM_RC); + simd qh = qr.template replicate_vs_w_hs(0); + simd j(0, 1); + j &= 7; + simd idx = simd(qb) | (((qh >> j) & 1) << 8); + simd ge = slm_gather(idx * 4); + return grid_signed(ge, r.signs.template select(g * GROUPED_GEMM_RC), + r.d.template select(g * GROUPED_GEMM_RC)); + } +}; + +// The K-quants and iq3_xxs: a 256-value superblock, k step j its sub-block j. Their value bytes for +// a k step are one rectangle of a stream, in k order after a shift and a mask per dword; scales, +// mins and d are the block's and are loaded once per block. + +// [qs 128][scales 12][dm]: value l of sub-block j is nibble j & 1 of byte 32 (j / 2) + l, times +// dall * scale_j, minus dmin * min_j (6-bit scale and min, get_scale_min_k4) +template struct grouped_gemm_esimd_a { + static constexpr bool supported = true; + static constexpr int qk = QK_K; + static constexpr bool whole = false; + static constexpr int slm_bytes = 0; + static ESIMD_INLINE void init_slm() {} + struct raw { + grouped_gemm_esimd::simd q; + grouped_gemm_esimd::simd d, m; + }; + struct sb_t { + grouped_gemm_esimd::simd sc[3]; // the 12 scale bytes + grouped_gemm_esimd::simd dall, dmin; + }; + + static constexpr grouped_gemm_esimd::field QS = { 0, QK_K / 2, 16 }, SC = { QK_K / 2, K_SCALE_SIZE, 4 }, + DM = { QK_K / 2 + K_SCALE_SIZE, 4, 0 }; + + static bool ok(const int K, const bool aos) { + return K % qk == 0 && (aos || grouped_gemm_esimd::surface_ok(K / 2)); + } + + template + static ESIMD_INLINE void load_sb(sb_t & sb, + const Sl & s, + const int ib, + const grouped_gemm_esimd::field & sc = SC, + const grouped_gemm_esimd::field & dmf = DM) { + using namespace grouped_gemm_esimd; +#pragma unroll + for (int w = 0; w < 3; ++w) { + sb.sc[w] = s.u32(sc, ib, 4 * w); + } + simd dm = s.u32(dmf, ib, 0); + auto dh = dm.template bit_cast_view(); + sb.dall = simd(dh.template select(0)); + sb.dmin = simd(dh.template select(1)); + } + // get_scale_min_k4 for sub-block j over the lanes + static ESIMD_INLINE void scale_min(sb_t & sb, + const int j, + grouped_gemm_esimd::simd & d, + grouped_gemm_esimd::simd & m) { + using namespace grouped_gemm_esimd; + simd sc, mb; + if (j < 4) { + sc = byte_of(sb.sc[0], j) & 63; + mb = byte_of(sb.sc[1], j) & 63; + } else { + sc = (byte_of(sb.sc[2], j - 4) & 0xf) | ((byte_of(sb.sc[0], j - 4) >> 6) << 4); + mb = (byte_of(sb.sc[2], j - 4) >> 4) | ((byte_of(sb.sc[1], j - 4) >> 6) << 4); + } + d = sb.dall * simd(sc); + m = sb.dmin * simd(mb); + } + template static ESIMD_INLINE void load(raw & r, sb_t & sb, const Sl & s, const int kb, const int j) { + using namespace grouped_gemm_esimd; + r.q = (s.template rows<8>(QS, kb / 8, 32 * (j / 2)) >> (4 * (j & 1))) & 0x0F0F0F0Fu; + scale_min(sb, j, r.d, r.m); + } + + template static ESIMD_INLINE grouped_gemm_esimd::a_halves decode(raw & r) { + using namespace grouped_gemm_esimd; + simd d = r.d.template select(g * GROUPED_GEMM_RC), + m = r.m.template select(g * GROUPED_GEMM_RC); + return halves_dm(r.q.template select(g * GROUPED_GEMM_RC * 8), d, m, d, m); + } +}; + +// [qs 128][qh 32][scales 12][dm]: q4_K plus bit j of qh byte l as 16 +template struct grouped_gemm_esimd_a { + using q4 = grouped_gemm_esimd_a; + static constexpr bool supported = true; + static constexpr int qk = QK_K; + static constexpr bool whole = false; + static constexpr int slm_bytes = 0; + static ESIMD_INLINE void init_slm() {} + using raw = typename q4::raw; + using sb_t = typename q4::sb_t; + static constexpr grouped_gemm_esimd::field QS = { 0, QK_K / 2, 48 }, QH = { QK_K / 2, QK_K / 8, 16 }, + SC = { QK_K / 2 + QK_K / 8, K_SCALE_SIZE, 4 }, + DM = { QK_K / 2 + QK_K / 8 + K_SCALE_SIZE, 4, 0 }; + static bool ok(const int K, const bool aos) { + return K % qk == 0 && (aos || (grouped_gemm_esimd::surface_ok(K / 2) && grouped_gemm_esimd::surface_ok(K / 8))); + } + template static ESIMD_INLINE void load_sb(sb_t & sb, const Sl & s, const int ib) { q4::load_sb(sb, s, ib, SC, DM); } + template static ESIMD_INLINE void load(raw & r, sb_t & sb, const Sl & s, const int kb, const int j) { + using namespace grouped_gemm_esimd; + const int ib = kb / 8; + simd qh = s.template rows<8>(QH, ib, 0); + r.q = ((s.template rows<8>(QS, ib, 32 * (j / 2)) >> (4 * (j & 1))) & 0x0F0F0F0Fu) | + (((qh >> j) & 0x01010101u) << 4); + q4::scale_min(sb, j, r.d, r.m); + } + + template static ESIMD_INLINE grouped_gemm_esimd::a_halves decode(raw & r) { + return q4::template decode(r); + } +}; + +// [ql 128][qh 64][scales 16][d]: sub-block j is quarter r = j % 4 of half h = j / 4; value l is +// nibble r >> 1 of ql byte 64h + 32 (r & 1) + l with bits 2r, 2r+1 of qh byte 32h + l above it, +// minus 32, times d * the int8 scale 2j + l / 16 +template struct grouped_gemm_esimd_a { + static constexpr bool supported = true; + static constexpr int qk = QK_K; + static constexpr bool whole = false; + static constexpr int slm_bytes = 0; + static ESIMD_INLINE void init_slm() {} + struct raw { + grouped_gemm_esimd::simd q; + grouped_gemm_esimd::simd d0, d1; // per k half + }; + struct sb_t { + grouped_gemm_esimd::simd sc[4]; // the 16 int8 scales + grouped_gemm_esimd::simd d; + }; + + static constexpr grouped_gemm_esimd::field QL = { 0, QK_K / 2, 0 }, QH = { QK_K / 2, QK_K / 4, QK_K / 2 }, + SC = { QK_K / 2 + QK_K / 4, QK_K / 16, QK_K / 2 + QK_K / 4 }, + D = { QK_K / 2 + QK_K / 4 + QK_K / 16, 2, + QK_K / 2 + QK_K / 4 + QK_K / 16 }; + static bool ok(const int K, const bool aos) { + return K % qk == 0 && (aos || (grouped_gemm_esimd::surface_ok(K / 2) && grouped_gemm_esimd::surface_ok(K / 4))); + } + template static ESIMD_INLINE void load_sb(sb_t & sb, const Sl & s, const int ib) { + using namespace grouped_gemm_esimd; +#pragma unroll + for (int w = 0; w < 4; ++w) { + sb.sc[w] = s.u32(SC, ib, 4 * w); + } + simd dh = s.u16(D, ib, 0); + sb.d = simd(dh.template bit_cast_view()); + } + template static ESIMD_INLINE void load(raw & r, sb_t & sb, const Sl & s, const int kb, const int j) { + using namespace grouped_gemm_esimd; + const int ib = kb / 8, h = j / 4, q = j % 4; + simd ql = s.template rows<8>(QL, ib, 64 * h + 32 * (q & 1)); + simd qh = s.template rows<8>(QH, ib, 32 * h); + r.q = ((ql >> (4 * (q >> 1))) & 0x0F0F0F0Fu) | (((qh >> (2 * q)) & 0x03030303u) << 4); + // scales 2j and 2j + 1: bytes 2 (j % 2) and 2 (j % 2) + 1 of dword j / 2, sign extended + simd w = dword_of(sb.sc, j / 2); + simd s0 = simd(w << (24 - 16 * (j % 2))) >> 24; + simd s1 = simd(w << (16 - 16 * (j % 2))) >> 24; + r.d0 = sb.d * simd(s0); + r.d1 = sb.d * simd(s1); + } + + template static ESIMD_INLINE grouped_gemm_esimd::a_halves decode(raw & r) { + using namespace grouped_gemm_esimd; + simd z = 0.0f; + return halves_dm(r.q.template select(g * GROUPED_GEMM_RC * 8), + r.d0.template select(g * GROUPED_GEMM_RC), z, + r.d1.template select(g * GROUPED_GEMM_RC), z, 32.0f); + } +}; + +// [qs 64][scales 16][dm]: value l of sub-block j is bits 2 (j % 4) of byte 32 (j / 4) + l, times +// d * (scale & 15), minus dmin * (scale >> 4), scale byte 2j + l / 16 +template struct grouped_gemm_esimd_a { + static constexpr bool supported = true; + static constexpr int qk = QK_K; + static constexpr bool whole = false; + static constexpr int slm_bytes = 0; + static ESIMD_INLINE void init_slm() {} + struct raw { + grouped_gemm_esimd::simd q; + grouped_gemm_esimd::simd d0, m0, d1, m1; + }; + struct sb_t { + grouped_gemm_esimd::simd sc[4]; + grouped_gemm_esimd::simd d, dmin; + }; + + static constexpr grouped_gemm_esimd::field QS = { 0, QK_K / 4, QK_K / 16 }, SC = { QK_K / 4, QK_K / 16, 0 }, + DM = { QK_K / 4 + QK_K / 16, 4, QK_K / 4 + QK_K / 16 }; + + static bool ok(const int K, const bool aos) { + return K % qk == 0 && (aos || grouped_gemm_esimd::surface_ok(K / 4)); + } + template static ESIMD_INLINE void load_sb(sb_t & sb, const Sl & s, const int ib) { + using namespace grouped_gemm_esimd; +#pragma unroll + for (int w = 0; w < 4; ++w) { + sb.sc[w] = s.u32(SC, ib, 4 * w); + } + simd dm = s.u32(DM, ib, 0); + auto dh = dm.template bit_cast_view(); + sb.d = simd(dh.template select(0)); + sb.dmin = simd(dh.template select(1)); + } + template static ESIMD_INLINE void load(raw & r, sb_t & sb, const Sl & s, const int kb, const int j) { + using namespace grouped_gemm_esimd; + r.q = (s.template rows<8>(QS, kb / 8, 32 * (j / 4)) >> (2 * (j % 4))) & 0x03030303u; + simd w = dword_of(sb.sc, j / 2); + simd s0 = byte_of(w, 2 * (j % 2)), s1 = byte_of(w, 2 * (j % 2) + 1); + r.d0 = sb.d * simd(s0 & 0xf); + r.m0 = sb.dmin * simd(s0 >> 4); + r.d1 = sb.d * simd(s1 & 0xf); + r.m1 = sb.dmin * simd(s1 >> 4); + } + + template static ESIMD_INLINE grouped_gemm_esimd::a_halves decode(raw & r) { + using namespace grouped_gemm_esimd; + return halves_dm(r.q.template select(g * GROUPED_GEMM_RC * 8), + r.d0.template select(g * GROUPED_GEMM_RC), + r.m0.template select(g * GROUPED_GEMM_RC), + r.d1.template select(g * GROUPED_GEMM_RC), + r.m1.template select(g * GROUPED_GEMM_RC)); + } +}; + +// [qs 64][hmask 32][scales 12][d]: q2_K's 2 bits, minus 4 where bit j of hmask byte l is clear, +// times d * (6-bit scale - 32), scale s = 2j + l / 16 split over bytes s % 8 and 8 + s % 4 +template struct grouped_gemm_esimd_a { + static constexpr bool supported = true; + static constexpr int qk = QK_K; + static constexpr bool whole = false; + static constexpr int slm_bytes = 0; + static ESIMD_INLINE void init_slm() {} + struct raw { + grouped_gemm_esimd::simd q; + grouped_gemm_esimd::simd d0, d1; + }; + struct sb_t { + grouped_gemm_esimd::simd sc[4]; // 12 scale bytes, sc[3] unused + grouped_gemm_esimd::simd d; + }; + + static constexpr grouped_gemm_esimd::field QS = { 0, QK_K / 4, QK_K / 8 }, HM = { QK_K / 4, QK_K / 8, 0 }, + SC = { QK_K / 4 + QK_K / 8, 12, QK_K / 4 + QK_K / 8 }, + D = { QK_K / 4 + QK_K / 8 + 12, 2, QK_K / 4 + QK_K / 8 + 12 }; + static bool ok(const int K, const bool aos) { + return K % qk == 0 && (aos || (grouped_gemm_esimd::surface_ok(K / 4) && grouped_gemm_esimd::surface_ok(K / 8))); + } + template static ESIMD_INLINE void load_sb(sb_t & sb, const Sl & s, const int ib) { + using namespace grouped_gemm_esimd; +#pragma unroll + for (int w = 0; w < 3; ++w) { + sb.sc[w] = s.u32(SC, ib, 4 * w); + } + sb.sc[3] = 0; + simd dh = s.u16(D, ib, 0); + sb.d = simd(dh.template bit_cast_view()); + } + + static ESIMD_INLINE grouped_gemm_esimd::simd scale(sb_t & sb, const int sidx) { + using namespace grouped_gemm_esimd; + simd lo = (byte_of(dword_of(sb.sc, (sidx % 8) / 4), sidx % 4) >> (4 * (sidx / 8))) & 0xf; + simd hi = (byte_of(sb.sc[2], sidx % 4) >> (2 * (sidx / 4))) & 3; + return sb.d * simd(simd(lo | (hi << 4)) - 32); + } + template static ESIMD_INLINE void load(raw & r, sb_t & sb, const Sl & s, const int kb, const int j) { + using namespace grouped_gemm_esimd; + const int ib = kb / 8; + simd hm = s.template rows<8>(HM, ib, 0); + r.q = ((s.template rows<8>(QS, ib, 32 * (j / 4)) >> (2 * (j % 4))) & 0x03030303u) | + (((hm >> j) & 0x01010101u) << 2); + r.d0 = scale(sb, 2 * j); + r.d1 = scale(sb, 2 * j + 1); + } + + template static ESIMD_INLINE grouped_gemm_esimd::a_halves decode(raw & r) { + using namespace grouped_gemm_esimd; + simd z = 0.0f; + return halves_dm(r.q.template select(g * GROUPED_GEMM_RC * 8), + r.d0.template select(g * GROUPED_GEMM_RC), z, + r.d1.template select(g * GROUPED_GEMM_RC), z, 4.0f); + } +}; + +// [qs 96][d]: per sub-block j, 8 grid indices at 8j and an aux dword at 64 + 4j whose 4 x 7 bits +// are sign bytes of ksigns_iq2xs and whose top 4 bits scale d * (0.5 + s) * 0.5. ksigns_iq2xs[i] is +// i with the parity of its 7 bits as bit 7, so the sign bytes are computed, not looked up. +template struct grouped_gemm_esimd_a { + static constexpr bool supported = true; + static constexpr int qk = QK_K; + static constexpr bool whole = false; + // the 256-entry grid, a read-only table in SLM + static constexpr int slm_bytes = 256 * sizeof(uint32_t); + static ESIMD_INLINE void init_slm() { + using namespace grouped_gemm_esimd; +#pragma unroll + for (int i = 0; i < 256; i += 64) { + slm_block_store(i * 4, block_load(iq3xxs_grid + i)); + } + } + struct raw { + grouped_gemm_esimd::simd q; // [row][8 grid indices] + grouped_gemm_esimd::simd aux; + grouped_gemm_esimd::simd d; + }; + struct sb_t { + grouped_gemm_esimd::simd d; + }; + + static constexpr grouped_gemm_esimd::field QS = { 0, 3 * QK_K / 8, 2 }, D = { 3 * QK_K / 8, 2, 0 }; + + static bool ok(const int K, const bool aos) { + return K % qk == 0 && (aos || grouped_gemm_esimd::surface_ok(K / QK_K * 96)); + } + template static ESIMD_INLINE void load_sb(sb_t & sb, const Sl & s, const int ib) { + using namespace grouped_gemm_esimd; + simd dh = s.u16(D, ib, 0); + sb.d = simd(dh.template bit_cast_view()); + } + template static ESIMD_INLINE void load(raw & r, sb_t & sb, const Sl & s, const int kb, const int j) { + using namespace grouped_gemm_esimd; + const int ib = kb / 8; + r.q = s.template rows<2>(QS, ib, 8 * j); + r.aux = s.template rows<1>(QS, ib, 64 + 4 * j); + r.d = sb.d * (0.5f + simd(r.aux >> 28)) * 0.5f; + } + + template static ESIMD_INLINE grouped_gemm_esimd::a_halves decode(raw & r) { + using namespace grouped_gemm_esimd; + simd qb = + r.q.template select(g * GROUPED_GEMM_RC * 2).template bit_cast_view(); + simd ge = slm_gather(qb * 4); + simd ax = r.aux.template select(g * GROUPED_GEMM_RC); + simd sg = 0; +#pragma unroll + for (int il = 0; il < 4; ++il) { + simd si = (ax >> (7 * il)) & 127; + sg |= (si | ((cbit(si) & 1) << 7)) << (8 * il); + } + return grid_signed(ge, sg, r.d.template select(g * GROUPED_GEMM_RC)); + } +}; + +// T is the dpas operand type, sycl::half or bfloat16: the type B is packed in. A is decoded in half +// either way and converted for bf16 (see the double rounding note at the conversion). AOS: the weight +// is in the canonical block layout rather than the reorder (SoA) one. A: the grouped_gemm_arch built for. +template struct grouped_gemm_esimd_kernel { + using F = grouped_gemm_esimd_a; + + const char * src0_dd; + size_t expert_stride; + const ggml_sycl_grouped_gemm_tile * tiles; + const T * packed; + float * dst; + int M; + int Npad; + int K; + ggml_sycl_grouped_gemm_rows dst_rows; + + void operator()(sycl::nd_item<1> it) const SYCL_ESIMD_KERNEL { + if constexpr (grouped_gemm_built()) { + run(it); + } + } + + ESIMD_INLINE void run(sycl::nd_item<1> it) const { + using namespace sycl::ext::intel::esimd; + namespace xmx = sycl::ext::intel::esimd::xmx; + constexpr int MR = A::MR; + constexpr int NW = A::NW; + constexpr int RC = GROUPED_GEMM_RC; + constexpr int RG = MR / RC; // dpas row groups of this thread + constexpr int BN = GGML_SYCL_GROUPED_GEMM_BN; + constexpr int NT = BN / NW; + + if constexpr (F::slm_bytes > 0) { + // the format's lookup table; a work-group is one thread, so nothing else writes it + slm_init(); + F::init_slm(); + } + + const int mblocks = M / MR; + const int gid = it.get_global_id(0); + const int t = gid / mblocks; + const int m0 = (gid % mblocks) * MR; + + const ggml_sycl_grouped_gemm_tile tile = tiles[t]; + if (tile.n1 <= tile.n0) { + return; + } + const int b0 = t * BN; // the tile's packed-B columns + + // the slice of this expert + const int bpr = K / F::qk; + const grouped_gemm_esimd::slice sl = { + (const uint8_t *) src0_dd + (size_t) tile.expert * expert_stride, + M, + bpr, + M * bpr, + m0, + AOS, + (int) sizeof(block_q_t) + }; + const uint32_t * bp = (const uint32_t *) packed; + const unsigned bw = (unsigned) Npad * 4; // bytes of one packed B row + const int nstep = K / GROUPED_GEMM_QK; + + simd acc[RG][NT]; + simd total[KS > 1 ? RG : 1][KS > 1 ? NT : 1]; +#pragma unroll + for (int g = 0; g < RG; ++g) { +#pragma unroll + for (int nt = 0; nt < NT; ++nt) { + acc[g][nt] = 0.0f; + if constexpr (KS > 1) { + total[g][nt] = 0.0f; + } + } + } + + // The tile's route map, gathered once up front; the K loop hides its latency, and the epilogue + // below reads it at compile-time indices. + const int ncols = tile.n1 - tile.n0; + simd_mask cm = simd(0, 1) < ncols; + simd i2 = 0, r1 = 0; // r1: the dst row slot, i1 % ne1 + if (dst_rows.map) { + const int32_t * mp = (const int32_t *) (dst_rows.map + tile.n0); + simd mo(0, sizeof(mmid_row_mapping)); + simd i1 = gather(mp, mo, cm); + i2 = gather(mp + 1, mo, cm); + // once per thread in 32 bits: a 64-bit modulo per column is emulated, and at 20 columns a + // tile it cost more than the whole GEMM (7.2 vs 3.1 ms) + r1 = i1 % simd((int32_t) dst_rows.ne1); + } + + // One k step at a time: the format's stored bits for the MR rows, and the 16 k pairs x NW + // columns of packed B per dpas column tile, one 2D block message each (without 2D loads, one + // block load per packed row, cut into the tiles in registers). A second stage in + // flight spilled 7 KB of the 256 registers and ran 1.6x slower; the other threads of the + // XVE hide the load latency instead. + // A stored block's metadata (its sub-block scales) is loaded once per block. With KS > 1 the + // K split of the joint_matrix kernel is reproduced for bit-identical output (a second set of + // accumulators); KS == 1 sums the whole K in one, which is a different f32 rounding order and + // frees the 4 KB of registers the second set holds. + constexpr int KPB = F::qk / GROUPED_GEMM_QK; // k steps per stored block + int split = 0; + int split_end = KS > 1 ? nstep / KS : nstep; + typename F::sb_t sb; + for (int kb = 0; kb < nstep; ++kb) { + const int j = kb % KPB; + if (j == 0) { + F::load_sb(sb, sl, kb / KPB); + } + typename F::raw r; + F::load(r, sb, sl, kb, j); + simd b[NT]; // [16 k pairs][NW columns] each + if constexpr (A::L2D) { +#pragma unroll + for (int nt = 0; nt < NT; ++nt) { + b[nt] = load_2d(bp, bw - 1, K / 2 - 1, bw - 1, b0 + nt * NW, kb * 16); + } + } else { + simd bm; +#pragma unroll + for (int r = 0; r < 16; ++r) { + bm.template select(r * BN) = + block_load(bp + (size_t) (kb * 16 + r) * Npad + b0, overaligned_tag<16>{}); + } + auto bv = bm.template bit_cast_view(); +#pragma unroll + for (int nt = 0; nt < NT; ++nt) { + b[nt] = bv.template select<16, 1, NW, 1>(0, nt * NW); + } + } + simd all; + if constexpr (F::whole) { + all = F::decode_all(r); + } + // one row group of the thread, g a compile-time constant: with a runtime g the larger + // decodes were left rolled + auto row_group = [&](auto gc) SYCL_ESIMD_FUNCTION { + constexpr int g = decltype(gc)::value; + grouped_gemm_esimd::a_halves av; + if constexpr (F::whole) { + // [row][32 k] of the whole tile to this row group's [k half][row][16 k] + auto am = all.template bit_cast_view(); + av.template select(0) = am.template select(g * RC, 0); + av.template select(RC * 16) = am.template select(g * RC, 16); + } else { + av = F::template decode(r); + } +#pragma unroll + for (int h = 0; h < 2; ++h) { + // A of this k16 half: rows x k [16h, 16h+16), row major + simd ah = av.template select(h * RC * 16); + simd at; + if constexpr (std::is_same_v) { + at = ah; + } else { + // rounded twice (f32 to half in the decode, half to bf16 here), so A's rounding + // error is about twice the joint_matrix bf16 stage's, which rounds f32 once + at = simd(ah); + } +#pragma unroll + for (int nt = 0; nt < NT; ++nt) { + simd bh32 = b[nt].template select<8 * NW, 1>(h * 8 * NW); + simd bh = bh32.template bit_cast_view(); + acc[g][nt] = xmx::dpas<8, RC, float, float>(acc[g][nt], bh, at); + } + } + }; + grouped_gemm_esimd::static_for<0, RG>::run(row_group); + if constexpr (KS > 1) { + // the K split's range ends, in k steps; a range's partial joins the total when it closes + if (kb + 1 == split_end) { +#pragma unroll + for (int g = 0; g < RG; ++g) { +#pragma unroll + for (int nt = 0; nt < NT; ++nt) { + total[g][nt] += acc[g][nt]; + acc[g][nt] = 0.0f; + } + } + ++split; + split_end = ((split + 1) * nstep) / KS; + } + } + } + (void) split; + (void) split_end; + + // column c of the tile: MR consecutive floats of one dst row. Unrolled, so c indexes the + // accumulators at compile time; a runtime index sends them all to private memory. +#pragma unroll + for (int c = 0; c < BN; ++c) { + if (c >= ncols) { + continue; + } + simd col; +#pragma unroll + for (int g = 0; g < RG; ++g) { + if constexpr (KS > 1) { + col.template select(g * RC) = total[g][c / NW].template select(c % NW); + } else { + col.template select(g * RC) = acc[g][c / NW].template select(c % NW); + } + } + const int n = tile.n0 + c; + if (dst_rows.map) { + float * out = (float *) (dst_rows.base + (size_t) r1[c] * dst_rows.nb1 + i2[c] * dst_rows.nb2) + m0; + block_store(out, col, element_aligned_tag{}); + } else { + block_store(dst + (size_t) n * M + m0, col, element_aligned_tag{}); + } + } + } + + auto get(syclexp::properties_tag) const { return syclexp::properties{ sycl::ext::intel::experimental::grf_size<256> }; } +}; + +// the weights' surfaces: 2D block loads (SoA with L2D) want 64-byte aligned bases, the dword gathers 4 +static bool grouped_gemm_esimd_weights_ok(const char * w, const size_t expert_stride, const bool l2d) { + const size_t a = l2d ? 64 : 4; + return (uintptr_t) w % a == 0 && expert_stride % a == 0; +} + +// 0 off, 1 on (default), 2 on with the joint_matrix kernel's K-split order reproduced (bit-identical output) +static int ggml_sycl_grouped_gemm_esimd_mode() { + return g_ggml_sycl_mmid_esimd; +} + +bool ggml_sycl_grouped_gemm_esimd_enabled() { +#if defined(GGML_SYCL_SUPPORT_XMX) + return g_ggml_sycl_enable_esimd && ggml_sycl_grouped_gemm_esimd_mode() != 0; +#else + return false; +#endif +} + +template +static void grouped_gemm_esimd_launch(const char * src0_dd, + size_t expert_stride, + const ggml_sycl_grouped_gemm_tile * tiles, + const T * packed, + float * dst, + int M, + int Npad, + int K, + const ggml_sycl_grouped_gemm_rows & dst_rows, + int64_t n_tiles, + dpct::queue_ptr stream) { + const sycl::nd_range<1> range((size_t) n_tiles * (M / A::MR), 1); + if (ggml_sycl_grouped_gemm_esimd_mode() == 2) { + stream->parallel_for(range, grouped_gemm_esimd_kernel{ + src0_dd, expert_stride, tiles, packed, dst, M, Npad, K, dst_rows }); + } else { + stream->parallel_for(range, grouped_gemm_esimd_kernel{ + src0_dd, expert_stride, tiles, packed, dst, M, Npad, K, dst_rows }); + } +} + +template +static bool grouped_gemm_esimd_run(const char * src0_dd, + size_t expert_stride, + const ggml_sycl_grouped_gemm_tile * tiles, + const T * packed, + float * dst, + int M, + int Npad, + int K, + const ggml_sycl_grouped_gemm_rows & dst_rows, + bool reordered, + int64_t n_tiles, + dpct::queue_ptr stream) { + using F = grouped_gemm_esimd_a; + // whole row groups and stored blocks, every K-split range non-empty (also in mode 1, so both + // modes take the same shapes); B is read with 2D block loads, which want 64-byte aligned + // surfaces and pitches, or with 16-byte aligned block loads of whole tiles + if (M % A::MR != 0 || !F::ok(K, !reordered) || K < GROUPED_GEMM_QK * GGML_SYCL_GROUPED_GEMM_KSPLIT || + !grouped_gemm_esimd_weights_ok(src0_dd, expert_stride, reordered && A::L2D) || ((uintptr_t) packed % 64) != 0 || + Npad % 16 != 0) { + return false; + } + if (reordered) { + grouped_gemm_esimd_launch(src0_dd, expert_stride, tiles, packed, dst, M, Npad, K, + dst_rows, n_tiles, stream); + } else { + grouped_gemm_esimd_launch(src0_dd, expert_stride, tiles, packed, dst, M, Npad, K, + dst_rows, n_tiles, stream); + } + return true; +} + +template +bool ggml_sycl_grouped_gemm_esimd(const char * src0_dd, + size_t expert_stride, + const ggml_sycl_grouped_gemm_tile * tiles, + const T * packed, + float * dst, + int M, + int Npad, + int K, + const ggml_sycl_grouped_gemm_rows & dst_rows, + bool reordered, + int64_t n_tiles, + dpct::queue_ptr stream) { + static_assert(grouped_gemm_esimd_a::supported == ggml_sycl_grouped_gemm_esimd_has, + "the header's format list and the formats implemented here must agree"); + static_assert(NW == 8 || NW == 16, "the dpas widths of Xe-HPG and of Xe2 / Xe-HPC"); + if constexpr (NW == 16) { + return grouped_gemm_esimd_run(src0_dd, expert_stride, tiles, packed, dst, M, + Npad, K, dst_rows, reordered, n_tiles, stream); + } else { + return grouped_gemm_esimd_run(src0_dd, expert_stride, tiles, packed, dst, M, + Npad, K, dst_rows, reordered, n_tiles, stream); + } +} + +#define GROUPED_GEMM_ESIMD_INSTANCE_T(block_q_t, T, NW) \ + template bool ggml_sycl_grouped_gemm_esimd( \ + const char *, size_t, const ggml_sycl_grouped_gemm_tile *, const T *, float *, int, int, int, \ + const ggml_sycl_grouped_gemm_rows &, bool, int64_t, dpct::queue_ptr); +#define GROUPED_GEMM_ESIMD_INSTANCE(block_q_t) \ + GROUPED_GEMM_ESIMD_INSTANCE_T(block_q_t, sycl::half, 16) \ + GROUPED_GEMM_ESIMD_INSTANCE_T(block_q_t, sycl::ext::oneapi::bfloat16, 16) \ + GROUPED_GEMM_ESIMD_INSTANCE_T(block_q_t, sycl::half, 8) \ + GROUPED_GEMM_ESIMD_INSTANCE_T(block_q_t, sycl::ext::oneapi::bfloat16, 8) +GROUPED_GEMM_ESIMD_INSTANCE(block_q8_0) +GROUPED_GEMM_ESIMD_INSTANCE(block_iq4_nl) +GROUPED_GEMM_ESIMD_INSTANCE(block_iq4_xs) +GROUPED_GEMM_ESIMD_INSTANCE(block_iq3_s) +GROUPED_GEMM_ESIMD_INSTANCE(block_iq3_xxs) +GROUPED_GEMM_ESIMD_INSTANCE(block_q3_K) +GROUPED_GEMM_ESIMD_INSTANCE(block_q2_K) +GROUPED_GEMM_ESIMD_INSTANCE(block_q6_K) +GROUPED_GEMM_ESIMD_INSTANCE(block_q5_K) +GROUPED_GEMM_ESIMD_INSTANCE(block_q4_K) diff --git a/ggml/src/ggml-sycl/fused-gemm-esimd.hpp b/ggml/src/ggml-sycl/fused-gemm-esimd.hpp new file mode 100644 index 000000000000..029d19480624 --- /dev/null +++ b/ggml/src/ggml-sycl/fused-gemm-esimd.hpp @@ -0,0 +1,33 @@ +#ifndef GGML_SYCL_FUSED_GEMM_ESIMD_HPP +#define GGML_SYCL_FUSED_GEMM_ESIMD_HPP + +#include "fused-gemm.hpp" + +// The grouped (MUL_MAT_ID) dequant GEMM, written with ESIMD so the dequantized weights go from +// registers straight into the dpas A operand: no SLM, no barrier. Same inputs and outputs as the +// joint_matrix grouped kernel of the 8 x NW x 16 sub-group-NW combination of T (sycl::half or +// bfloat16): NW = 16 on Xe2 and Xe-HPC, 8 on Xe-HPG (Arc A, ARL-H). The schedule's tiles, B packed as +// [K/2][Npad][2] T, and dst through dst_rows. The weight is in the reorder (SoA) layout if +// `reordered`, else in the canonical block layout. Returns false when the shape is not covered. +template +constexpr bool ggml_sycl_grouped_gemm_esimd_has = std::is_same_v || + std::is_same_v || + std::is_same_v || + std::is_same_v || + std::is_same_v || + std::is_same_v || + std::is_same_v || + std::is_same_v || + std::is_same_v || + std::is_same_v; + +template +bool ggml_sycl_grouped_gemm_esimd(const char * src0_dd, size_t expert_stride, const ggml_sycl_grouped_gemm_tile * tiles, + const T * packed, float * dst, int M, int Npad, int K, + const ggml_sycl_grouped_gemm_rows & dst_rows, bool reordered, int64_t n_tiles, + dpct::queue_ptr stream); + +// GGML_SYCL_MMID_ESIMD: 1 (default) takes the ESIMD kernel above where it applies, 0 never does +bool ggml_sycl_grouped_gemm_esimd_enabled(); + +#endif // GGML_SYCL_FUSED_GEMM_ESIMD_HPP diff --git a/ggml/src/ggml-sycl/fused-gemm.cpp b/ggml/src/ggml-sycl/fused-gemm.cpp index 803a994c04bb..89096d561c41 100644 --- a/ggml/src/ggml-sycl/fused-gemm.cpp +++ b/ggml/src/ggml-sycl/fused-gemm.cpp @@ -1,4 +1,6 @@ #include "fused-gemm.hpp" +#include "fused-gemm-esimd.hpp" +#include "quants.hpp" #include @@ -17,7 +19,6 @@ namespace mx = sycl::ext::oneapi::experimental::matrix; // superblock into steps of this width. The sub-groups of a work-group each walk their own K range // and are summed at the end. static constexpr int FG_BK = QK4_NL; -static constexpr int FG_KSPLIT = 4; // Element traits of one joint_matrix operand type. The A stage and the B pack compute in f32 and // convert once, in registers, when they write the element, so any type costs the same one pass. @@ -113,6 +114,15 @@ using fg_half = sycl::half; using fg_bf16 = sycl::ext::oneapi::bfloat16; using fg_tf32 = mx::precision::tf32; +// The combinations the ESIMD grouped GEMM (fused-gemm-esimd.cpp) stands in for: 8 x SG x 16 with f16 +// or bf16 operands, the shape of one dpas, on sub-group 16 (Xe2, Xe-HPC) or 8 (Xe-HPG). Its B is +// packed and tiled as theirs is. +template static constexpr bool fg_esimd_combo() { + return S::TM == 8 && S::TN == S::SG && S::TK == 16 && (S::SG == 16 || S::SG == 8) && + std::is_same_v && + (std::is_same_v || std::is_same_v); +} + // One bit of GGML_SYCL_XMX_GATHER_SHAPES per combination. Only combinations some device lists in // matrix_combinations are built (appendix of sycl_ext_oneapi_matrix and the runtime's own list). template static void fg_visit_combo(int idx, F && f); @@ -152,29 +162,7 @@ template static void fg_visit_combo(int idx, F && f) { // size, since IGC fails on the other ones. A JIT build keeps them all, but each combination lands in // its own device image (joint_matrix is an optional kernel feature) and only a combination the // device reports is launched, so the runtime never asks IGC for the others. -#if defined(__SYCL_DEVICE_ONLY__) -# if __SYCL_TARGET_INTEL_GPU_ACM_G10__ || __SYCL_TARGET_INTEL_GPU_ACM_G11__ || __SYCL_TARGET_INTEL_GPU_ACM_G12__ || \ - __SYCL_TARGET_INTEL_GPU_ARL_H__ -# define FG_AOT_SG 8 -# elif __SYCL_TARGET_INTEL_GPU_PVC__ || __SYCL_TARGET_INTEL_GPU_PVC_VG__ || __SYCL_TARGET_INTEL_GPU_BMG_G21__ || \ - __SYCL_TARGET_INTEL_GPU_BMG_G31__ || __SYCL_TARGET_INTEL_GPU_LNL_M__ || __SYCL_TARGET_INTEL_GPU_PTL_H__ || \ - __SYCL_TARGET_INTEL_GPU_PTL_U__ || __SYCL_TARGET_INTEL_GPU_WCL__ || __SYCL_TARGET_INTEL_GPU_NVL_S__ || \ - __SYCL_TARGET_INTEL_GPU_NVL_U__ || __SYCL_TARGET_INTEL_GPU_NVL_P__ -# define FG_AOT_SG 16 -# elif __SYCL_TARGET_INTEL_GPU_TGLLP__ || __SYCL_TARGET_INTEL_GPU_RKL__ || __SYCL_TARGET_INTEL_GPU_ADL_S__ || \ - __SYCL_TARGET_INTEL_GPU_ADL_P__ || __SYCL_TARGET_INTEL_GPU_ADL_N__ || __SYCL_TARGET_INTEL_GPU_DG1__ || \ - __SYCL_TARGET_INTEL_GPU_MTL_U__ || __SYCL_TARGET_INTEL_GPU_MTL_H__ -# define FG_AOT_SG 0 // no XMX -# endif -#endif - -template static constexpr bool fg_built() { -#if defined(FG_AOT_SG) - return SG == FG_AOT_SG; -#else - return true; -#endif -} +// (FG_AOT_SG is defined in fused-gemm.hpp, which the ESIMD kernels share) // Upper bound on the tile count when total_rows rows are routed to n_as experts: the worst case gives // each expert one row and fills whole tiles with the rest. The bound depends only on the shape, not @@ -434,14 +422,10 @@ static __dpct_inline__ void fg_pack_quarter(const float * __restrict__ t, typena } } +// 32 values from 16 qs bytes, as in IQ4_NL blocks and IQ4_XS sub-blocks: the low nibbles fill the +// first half of the step and the high nibbles the second, so the halves land at a[0..7] and a[8..15] template -static __dpct_inline__ void fg_stage_a(const block_iq4_xs * __restrict__ xrow, const int kb, typename E::pair * a) { - FG_SUPERBLOCK(block_iq4_xs); - // low nibbles fill the first half of the step, high nibbles the second, so the two halves - // land at a[0..7] and a[8..15] and no quarter loop is needed - const float d = (float) blk->d * - ((((blk->scales_l[ib / 2] >> (4 * (ib % 2))) & 0xf) | (((blk->scales_h >> (2 * ib)) & 3) << 4)) - 32); - const uint8_t * q4 = blk->qs + 16 * ib; +static __dpct_inline__ void fg_decode_iq4(const uint8_t * __restrict__ q4, const float d, typename E::pair * a) { #pragma unroll for (int j = 0; j < 8; ++j) { a[j] = E::make(d * kvalues_iq4nl[q4[2 * j] & 0xf], d * kvalues_iq4nl[q4[2 * j + 1] & 0xf]); @@ -449,6 +433,14 @@ static __dpct_inline__ void fg_stage_a(const block_iq4_xs * __restrict__ xrow, c } } +template +static __dpct_inline__ void fg_stage_a(const block_iq4_xs * __restrict__ xrow, const int kb, typename E::pair * a) { + FG_SUPERBLOCK(block_iq4_xs); + const float d = (float) blk->d * + ((((blk->scales_l[ib / 2] >> (4 * (ib % 2))) & 0xf) | (((blk->scales_h >> (2 * ib)) & 3) << 4)) - 32); + fg_decode_iq4(blk->qs + 16 * ib, d, a); +} + template static __dpct_inline__ void fg_stage_a(const block_iq3_xxs * __restrict__ xrow, const int kb, typename E::pair * a) { FG_SUPERBLOCK(block_iq3_xxs); @@ -834,6 +826,22 @@ template <> struct fg_soa { } }; +template struct fg_soa_iq4 { + static constexpr bool supported = true; + // [qs][per-block records]; k step kb is 32-value group kb % groups of block ib + template + static __dpct_inline__ void stage(const uint8_t * x, const size_t nblocks, const size_t ib, const int kb, + typename E::pair * a) { + constexpr int groups = ggml_sycl_reordered::block_q_t::traits::qk / QK4_NL; + const int64_t g = (int64_t) ib * groups + kb % groups; + fg_decode_iq4(x + 16 * g, ggml_sycl_reordered::iq4_group_scale(x + nblocks * groups * 16, g), a); + } +}; + +template <> struct fg_soa : fg_soa_iq4 {}; + +template <> struct fg_soa : fg_soa_iq4 {}; + // one SG_ROWS x BN output tile: B columns [b0, b0 + BN) of packed_b go to dst columns [n0, n1), // n1 - n0 <= BN @@ -991,6 +999,15 @@ static void grouped_dequant_gemm_launch(const char * src0_dd, const size_t exper float * dst, const int M, const int Npad, const int K, const int64_t n_tiles, const int64_t groups_m, dpct::queue_ptr stream, ggml_sycl_grouped_gemm_rows dst_rows = {}) { + if constexpr (fg_esimd_combo() && ggml_sycl_grouped_gemm_esimd_has) { + // the register-operand ESIMD kernel, either weight layout: no SLM A image (GGML_SYCL_MMID_ESIMD) + if (ggml_sycl_grouped_gemm_esimd_enabled() && + ggml_sycl_grouped_gemm_esimd(src0_dd, expert_stride, tiles_ptr, packed, + dst, M, Npad, K, dst_rows, reordered, + n_tiles, stream)) { + return; + } + } stream->submit([&](sycl::handler & cgh) { sycl::local_accessor tile_a(FG_KSPLIT * S::SG_ROWS * FG_BK, cgh); sycl::local_accessor tile_c(FG_KSPLIT * S::SG_ROWS * S::BN, cgh); @@ -1087,6 +1104,45 @@ template static bool fg_visit_type(ggml_type type, bool reordered, } } +// The ESIMD grouped GEMM loads A straight into its dpas operands, so the joint_matrix tile shape +// means nothing to it; it runs on the fg_esimd_combo of the picked operand type and sub-group size. A +// grouped call whose weight it covers is moved there from any other shape of that type and sub-group +// size, if the device lists it, whatever GGML_SYCL_XMX_GATHER_SHAPES allows: the shape bits choose +// among joint_matrix tiles. +// A call the ESIMD kernel then declines (a shape it does not take) runs that combination's joint_matrix +// kernel. +static int fg_esimd_remap(dpct::queue_ptr stream, int combo, ggml_type src0_type, bool reordered) { + if (combo < 0 || !ggml_sycl_grouped_gemm_esimd_enabled()) { + return combo; + } + bool covered = false; + fg_visit_type(src0_type, reordered, [&](auto tag) { + using T = decltype(tag); + covered = ggml_sycl_grouped_gemm_esimd_has; + }); + if (!covered) { + return combo; + } + int target = -1; + fg_visit_combo(combo, [&](auto s) { + using S = decltype(s); + if constexpr (std::is_same_v) { + for (int idx = 0; idx < FG_N_COMBOS; ++idx) { + fg_visit_combo(idx, [&](auto t) { + using U = decltype(t); + if constexpr (fg_esimd_combo() && U::SG == S::SG && std::is_same_v) { + target = idx; + } + }); + } + } + }); + if (target < 0 || target == combo || !(fg_device_combos(stream->get_device()) & (1 << target))) { + return combo; + } + return target; +} + template static bool fg_fused_run(ggml_type src0_type, bool src0_reordered, const void * src0, const void * src1, ggml_type src1_type, float * dst, int64_t M, int64_t N, int64_t K, int64_t ldd, ggml_sycl_pool & pool, @@ -1201,7 +1257,7 @@ bool ggml_sycl_grouped_dequant_gemm(ggml_type src0_type, bool reordered, const v if (!ggml_sycl_grouped_dequant_gemm_shape_ok(src0_type, M, K, total_rows, n_active)) { return false; } - const int combo = fg_pick_combo(stream, GGML_TYPE_F32, src1_prec); + const int combo = fg_esimd_remap(stream, fg_pick_combo(stream, GGML_TYPE_F32, src1_prec), src0_type, reordered); if (combo < 0) { return false; } @@ -1407,7 +1463,7 @@ bool ggml_sycl_grouped_dequant_gemm_device_supported(ggml_type src0_type, bool r if (grouped_gemm_max_tiles(total_rows, n_as, GGML_SYCL_FG_BN) > INT32_MAX / GGML_SYCL_FG_BN) { return false; } - const int combo = fg_pick_combo(stream, GGML_TYPE_F32, src1_prec); + const int combo = fg_esimd_remap(stream, fg_pick_combo(stream, GGML_TYPE_F32, src1_prec), src0_type, reordered); if (combo < 0) { return false; } @@ -1428,7 +1484,7 @@ bool ggml_sycl_grouped_dequant_gemm_device(ggml_type src0_type, bool reordered, n_tokens, M, K, stream)) { return false; } - const int combo = fg_pick_combo(stream, GGML_TYPE_F32, src1_prec); + const int combo = fg_esimd_remap(stream, fg_pick_combo(stream, GGML_TYPE_F32, src1_prec), src0_type, reordered); bool launched = false; fg_visit_combo(combo, [&](auto s) { launched = fg_grouped_device_run(src0_type, reordered, src0_base, expert_stride, src1, dst, diff --git a/ggml/src/ggml-sycl/fused-gemm.hpp b/ggml/src/ggml-sycl/fused-gemm.hpp index 0e807a2c0ab9..e65e98fc8726 100644 --- a/ggml/src/ggml-sycl/fused-gemm.hpp +++ b/ggml/src/ggml-sycl/fused-gemm.hpp @@ -13,7 +13,34 @@ struct ggml_sycl_grouped_gemm_rows { size_t nb2; }; +// AOT: the sub-group size of the XMX combinations of the target, 0 for a target without XMX. +// Undefined in a JIT build, which keeps every combination. +#if defined(__SYCL_DEVICE_ONLY__) +# if __SYCL_TARGET_INTEL_GPU_ACM_G10__ || __SYCL_TARGET_INTEL_GPU_ACM_G11__ || __SYCL_TARGET_INTEL_GPU_ACM_G12__ || \ + __SYCL_TARGET_INTEL_GPU_ARL_H__ +# define FG_AOT_SG 8 +# elif __SYCL_TARGET_INTEL_GPU_PVC__ || __SYCL_TARGET_INTEL_GPU_PVC_VG__ || __SYCL_TARGET_INTEL_GPU_BMG_G21__ || \ + __SYCL_TARGET_INTEL_GPU_BMG_G31__ || __SYCL_TARGET_INTEL_GPU_LNL_M__ || __SYCL_TARGET_INTEL_GPU_PTL_H__ || \ + __SYCL_TARGET_INTEL_GPU_PTL_U__ || __SYCL_TARGET_INTEL_GPU_WCL__ || __SYCL_TARGET_INTEL_GPU_NVL_S__ || \ + __SYCL_TARGET_INTEL_GPU_NVL_U__ || __SYCL_TARGET_INTEL_GPU_NVL_P__ +# define FG_AOT_SG 16 +# elif __SYCL_TARGET_INTEL_GPU_TGLLP__ || __SYCL_TARGET_INTEL_GPU_RKL__ || __SYCL_TARGET_INTEL_GPU_ADL_S__ || \ + __SYCL_TARGET_INTEL_GPU_ADL_P__ || __SYCL_TARGET_INTEL_GPU_ADL_N__ || __SYCL_TARGET_INTEL_GPU_DG1__ || \ + __SYCL_TARGET_INTEL_GPU_MTL_U__ || __SYCL_TARGET_INTEL_GPU_MTL_H__ +# define FG_AOT_SG 0 // no XMX +# endif +#endif + +template static constexpr bool fg_built() { +#if defined(FG_AOT_SG) + return SG == FG_AOT_SG; +#else + return true; +#endif +} + static constexpr int GGML_SYCL_FG_BN = 32; +static constexpr int FG_KSPLIT = 4; static constexpr int64_t GGML_SYCL_MMID_SCHED_MAX_EXPERTS = 4096; // Shape and type gates for the kernels below. Device capability is separate: it needs a queue to ask. diff --git a/ggml/src/ggml-sycl/fusion.cpp b/ggml/src/ggml-sycl/fusion.cpp index 9b553829be6d..9ea6af6b07db 100644 --- a/ggml/src/ggml-sycl/fusion.cpp +++ b/ggml/src/ggml-sycl/fusion.cpp @@ -121,6 +121,28 @@ bool ggml_sycl_can_fuse(const ggml_cgraph * cgraph, int node_idx, std::initializ return ggml_sycl_should_fuse_mul_mat_glu(gate, up, glu); } + // the residual sum stays materialised (a later residual add reads it), so ggml_can_fuse cannot + // express this either: the add and the mul are the subgraph's outputs + if (ops.size() == 3 && ops.begin()[0] == GGML_OP_ADD && ops.begin()[1] == GGML_OP_RMS_NORM && + ops.begin()[2] == GGML_OP_MUL) { + if (!ggml_can_fuse_subgraph(cgraph, node_idx, ops, { node_idx, node_idx + 2 })) { + return false; + } + + const ggml_tensor * add = cgraph->nodes[node_idx]; + if (cgraph->nodes[node_idx + 1]->src[0] != add) { + return false; + } + + // the fused kernel does not broadcast the add + if (add->src[0]->type != GGML_TYPE_F32 || add->src[1]->type != GGML_TYPE_F32 || add->type != GGML_TYPE_F32 || + !ggml_are_same_shape(add->src[0], add) || !ggml_are_same_shape(add->src[1], add)) { + return false; + } + + return ggml_sycl_can_fuse(cgraph, node_idx + 1, { GGML_OP_RMS_NORM, GGML_OP_MUL }, {}); + } + if (!ggml_can_fuse(cgraph, node_idx, ops)) { return false; } diff --git a/ggml/src/ggml-sycl/gated_delta_net.cpp b/ggml/src/ggml-sycl/gated_delta_net.cpp index 8468bbf5bd07..63535a945e61 100644 --- a/ggml/src/ggml-sycl/gated_delta_net.cpp +++ b/ggml/src/ggml-sycl/gated_delta_net.cpp @@ -6,7 +6,13 @@ #include -template +// Warps per work-group. 2 is 13% faster than 4 at 4 columns per warp on Arc Pro B70. +static constexpr int gdn_warps = 2; +// State columns per warp when there are enough heads, see launch_gated_delta_net. +static constexpr int gdn_cols_wide = 4; + +// C is the number of state columns per warp: a token's q/k shard is loaded once and shared by these columns. +template void gated_delta_net_sycl(const float * q, const float * k, const float * v, @@ -34,9 +40,10 @@ void gated_delta_net_sycl(const float * q, auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>(); const uint32_t h_idx = item_ct1.get_group(2); const uint32_t sequence = item_ct1.get_group(1); - // each warp owns one column, using warp-level primitives to reduce across rows + // each warp owns C columns, using warp-level primitives to reduce across rows const int lane = item_ct1.get_local_id(2); - const int col = item_ct1.get_group(0) * item_ct1.get_local_range(1) + item_ct1.get_local_id(1); + const int warp = item_ct1.get_group(0) * item_ct1.get_local_range(1) + item_ct1.get_local_id(1); + const int col0 = warp * C; const uint32_t iq1 = fastmodulo(h_idx, neqk1_magic); const uint32_t iq3 = fastdiv(sequence, rq3_magic); @@ -48,94 +55,145 @@ void gated_delta_net_sycl(const float * q, const int64_t state_in_offset = sequence * H * S_v * S_v + h_idx * S_v * S_v; const int64_t state_out_offset = (sequence * H + h_idx) * S_v * S_v; state += state_out_offset; - curr_state += state_in_offset + col * S_v; + curr_state += state_in_offset; attn_data += (sequence * n_tokens * H + h_idx) * S_v; constexpr int warp_size = ggml_sycl_get_physical_warp_size() < S_v ? ggml_sycl_get_physical_warp_size() : S_v; static_assert(S_v % warp_size == 0, "S_v must be a multiple of warp_size"); + static_assert(S_v % (C * gdn_warps) == 0, "S_v must be a multiple of the columns per work-group"); + static_assert(C <= warp_size, "the attn store puts column c in lane c"); constexpr int rows_per_lane = (S_v + warp_size - 1) / warp_size; - float s_shard[rows_per_lane]; + float s_shard[C][rows_per_lane]; #pragma unroll - for (int r = 0; r < rows_per_lane; r++) { - const int i = r * warp_size + lane; - s_shard[r] = curr_state[i]; + for (int c = 0; c < C; c++) { +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + const int i = r * warp_size + lane; + s_shard[c][r] = curr_state[(col0 + c) * S_v + i]; + } } // snapshot slot mapping: slot 0 = most recent state, slot s = s tokens back. // When n_tokens < K only slots 0..n_tokens-1 are written; older slots are caller-owned. + const float * qp = q + iq3 * sq3 + iq1 * sq1 + lane; + const float * kp = k + iq3 * sq3 + iq1 * sq1 + lane; + const float * vp = v + sequence * sv3 + h_idx * sv1 + col0; + const float * bp = beta + sequence * sb3 + h_idx * sb1; + const float * gp = g + (sequence * sb3 + h_idx * sb1) * (KDA ? S_v : 1); + + // q/k of the next token are loaded one iteration ahead to hide the load latency. + float q_next[rows_per_lane]; + float k_next[rows_per_lane]; +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + q_next[r] = qp[r * warp_size]; + k_next[r] = kp[r * warp_size]; + } + for (int t = 0; t < n_tokens; t++) { - const float * q_t = q + iq3 * sq3 + t * sq2 + iq1 * sq1; - const float * k_t = k + iq3 * sq3 + t * sq2 + iq1 * sq1; - const float * v_t = v + sequence * sv3 + t * sv2 + h_idx * sv1; + const float beta_val = *bp; + const float * g_t = gp; + bp += sb2; + gp += sb2 * (KDA ? S_v : 1); + + float q_reg[rows_per_lane]; + float k_reg[rows_per_lane]; +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + q_reg[r] = q_next[r]; + k_reg[r] = k_next[r]; + } + if (t + 1 < n_tokens) { + qp += sq2; + kp += sq2; + } + // Load outside the branch: the last token reads its own row again. + // A guarded load is 20% slower at 32 heads on Arc Pro B70. +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + q_next[r] = qp[r * warp_size]; + k_next[r] = kp[r * warp_size]; + } - const int64_t gb_offset = sequence * sb3 + t * sb2 + h_idx * sb1; - const float * beta_t = beta + gb_offset; - const float * g_t = g + gb_offset * (KDA ? S_v : 1); + float v_reg[C]; +#pragma unroll + for (int c = 0; c < C; c++) { + v_reg[c] = vp[c]; + } + vp += sv2; - const float beta_val = *beta_t; + // attn[col] = g * (S^T q)[col] + delta[col] * (k . q), so no reduction waits for delta + float kq_shard = 0.0f; +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + kq_shard += k_reg[r] * q_reg[r]; + } + const float kq = warp_reduce_sum(kq_shard); + float out_lane = 0.0f; if constexpr (!KDA) { const float g_val = sycl::native::exp(*g_t); - // kv[col] = (S^T @ k)[col] = sum_i S[i][col] * k[i] - float kv_shard = 0.0f; #pragma unroll - for (int r = 0; r < rows_per_lane; r++) { - const int i = r * warp_size + lane; - kv_shard += s_shard[r] * k_t[i]; - } - float kv_col = warp_reduce_sum(kv_shard); + for (int c = 0; c < C; c++) { + // x: kv[col] = (S^T k)[col], y: (S^T q)[col] + sycl::float2 acc(0.0f, 0.0f); +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + acc.x() += s_shard[c][r] * k_reg[r]; + acc.y() += s_shard[c][r] * q_reg[r]; + } + acc = warp_reduce_sum(acc); - // delta[col] = (v[col] - g * kv[col]) * beta - float delta_col = (v_t[col] - g_val * kv_col) * beta_val; + // delta[col] = (v[col] - g * kv[col]) * beta + const float delta_col = (v_reg[c] - g_val * acc.x()) * beta_val; - // fused: S[i][col] = g * S[i][col] + k[i] * delta[col] - // attn[col] = (S^T @ q)[col] = sum_i S[i][col] * q[i] - float attn_partial = 0.0f; + // S[i][col] = g * S[i][col] + k[i] * delta[col] #pragma unroll - for (int r = 0; r < rows_per_lane; r++) { - const int i = r * warp_size + lane; - s_shard[r] = g_val * s_shard[r] + k_t[i] * delta_col; - attn_partial += s_shard[r] * q_t[i]; - } - - float attn_col = warp_reduce_sum(attn_partial); + for (int r = 0; r < rows_per_lane; r++) { + s_shard[c][r] = g_val * s_shard[c][r] + k_reg[r] * delta_col; + } - if (lane == 0) { - attn_data[col] = attn_col * scale; + // the reductions broadcast, so lane c already holds column c's result + out_lane = (lane == c) ? (g_val * acc.y() + delta_col * kq) * scale : out_lane; } } else { - // kv[col] = sum_i g[i] * S[i][col] * k[i] - float kv_shard = 0.0f; + float g_reg[rows_per_lane]; #pragma unroll for (int r = 0; r < rows_per_lane; r++) { - const int i = r * warp_size + lane; - kv_shard += sycl::native::exp(g_t[i]) * s_shard[r] * k_t[i]; + g_reg[r] = sycl::native::exp(g_t[r * warp_size + lane]); } - float kv_col = warp_reduce_sum(kv_shard); +#pragma unroll + for (int c = 0; c < C; c++) { + // x: kv[col] = sum_i g[i] * S[i][col] * k[i], y: sum_i g[i] * S[i][col] * q[i] + sycl::float2 acc(0.0f, 0.0f); +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + const float gs = g_reg[r] * s_shard[c][r]; + acc.x() += gs * k_reg[r]; + acc.y() += gs * q_reg[r]; + } + acc = warp_reduce_sum(acc); - // delta[col] = (v[col] - kv[col]) * beta - float delta_col = (v_t[col] - kv_col) * beta_val; + // delta[col] = (v[col] - kv[col]) * beta + const float delta_col = (v_reg[c] - acc.x()) * beta_val; - // fused: S[i][col] = g[i] * S[i][col] + k[i] * delta[col] - // attn[col] = (S^T @ q)[col] = sum_i S[i][col] * q[i] - float attn_partial = 0.0f; + // S[i][col] = g[i] * S[i][col] + k[i] * delta[col] #pragma unroll - for (int r = 0; r < rows_per_lane; r++) { - const int i = r * warp_size + lane; - s_shard[r] = sycl::native::exp(g_t[i]) * s_shard[r] + k_t[i] * delta_col; - attn_partial += s_shard[r] * q_t[i]; - } - - float attn_col = warp_reduce_sum(attn_partial); + for (int r = 0; r < rows_per_lane; r++) { + s_shard[c][r] = g_reg[r] * s_shard[c][r] + k_reg[r] * delta_col; + } - if (lane == 0) { - attn_data[col] = attn_col * scale; + out_lane = (lane == c) ? (acc.y() + delta_col * kq) * scale : out_lane; } } + if (lane < C) { + attn_data[col0 + lane] = out_lane; + } + attn_data += S_v * H; @@ -143,21 +201,26 @@ void gated_delta_net_sycl(const float * q, if constexpr (keep_rs_t) { const int target_slot = (int) n_tokens - 1 - t; if (target_slot >= 0 && target_slot < K) { - float * curr_state = state + target_slot * state_slot_stride; + float * slot_col = state + target_slot * state_slot_stride + col0 * S_v + lane; #pragma unroll - for (int r = 0; r < rows_per_lane; r++) { - const int i = r * warp_size + lane; - curr_state[col * S_v + i] = s_shard[r]; + for (int c = 0; c < C; c++) { +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + slot_col[c * S_v + r * warp_size] = s_shard[c][r]; + } } } } } if constexpr (!keep_rs_t) { + float * out_col = state + col0 * S_v + lane; #pragma unroll - for (int r = 0; r < rows_per_lane; r++) { - const int i = r * warp_size + lane; - state[col * S_v + i] = s_shard[r]; + for (int c = 0; c < C; c++) { +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + out_col[c * S_v + r * warp_size] = s_shard[c][r]; + } } } } @@ -193,60 +256,36 @@ static void launch_gated_delta_net(const float * q_d, //TODO: Add chunked kernel for even faster pre-fill const int warp_size = ggml_sycl_info().devices[ggml_sycl_get_device()].warp_size; - const int num_warps = 4; - dpct::dim3 grid_dims(H, n_seqs, (S_v + num_warps - 1) / num_warps); - dpct::dim3 block_dims(warp_size <= S_v ? warp_size : S_v, num_warps, 1); - const sycl::uint3 neqk1_magic = init_fastdiv_values(neqk1); const sycl::uint3 rq3_magic = init_fastdiv_values(rq3); - switch (S_v) { - case 16: - { - constexpr int sv = 16; - stream->parallel_for(sycl::nd_range<3>(grid_dims * block_dims, block_dims), - [=](sycl::nd_item<3> /*item_ct1*/) [[sycl::reqd_sub_group_size(WARP_SIZE)]] { - gated_delta_net_sycl(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, - sq1, sq2, sq3, sv1, sv2, sv3, sb1, sb2, - sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); - }); - } - break; - case 32: - { - constexpr int sv = 32; - stream->parallel_for(sycl::nd_range<3>(grid_dims * block_dims, block_dims), - [=](sycl::nd_item<3> /*item_ct1*/) [[sycl::reqd_sub_group_size(WARP_SIZE)]] { - gated_delta_net_sycl(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, - sq1, sq2, sq3, sv1, sv2, sv3, sb1, sb2, - sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); - }); - } - break; - case 64: { - { - constexpr int sv = 64; - stream->parallel_for(sycl::nd_range<3>(grid_dims * block_dims, block_dims), - [=](sycl::nd_item<3> /*item_ct1*/) [[sycl::reqd_sub_group_size(WARP_SIZE)]] { - gated_delta_net_sycl( - q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, sq1, sq2, - sq3, sv1, sv2, sv3, sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); - }); - } - break; - } - case 128: { - { - constexpr int sv = 128; - stream->parallel_for(sycl::nd_range<3>(grid_dims * block_dims, block_dims), - [=](sycl::nd_item<3> /*item_ct1*/) [[sycl::reqd_sub_group_size(WARP_SIZE)]] { - gated_delta_net_sycl( - q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, sq1, sq2, - sq3, sv1, sv2, sv3, sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); - }); - } - break; + auto launch = [&](auto sv_c, auto c_c) { + constexpr int sv = decltype(sv_c)::value; + constexpr int C = decltype(c_c)::value; + dpct::dim3 grid_dims(H, n_seqs, sv / (C * gdn_warps)); + dpct::dim3 block_dims(warp_size <= sv ? warp_size : sv, gdn_warps, 1); + stream->parallel_for(sycl::nd_range<3>(grid_dims * block_dims, block_dims), + [=](sycl::nd_item<3> /*item_ct1*/) [[sycl::reqd_sub_group_size(WARP_SIZE)]] { + gated_delta_net_sycl( + q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, sq1, sq2, sq3, sv1, sv2, + sv3, sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); + }); + }; + // gdn_cols_wide columns per warp cut the q/k loads but launch fewer warps, so with few heads 1 column is faster. + // The 1024-warp switch point is measured on Arc Pro B70. + auto launch_sv = [&](auto sv_c) { + if (H * n_seqs * S_v / gdn_cols_wide >= 1024) { + launch(sv_c, std::integral_constant{}); + } else { + launch(sv_c, std::integral_constant{}); } + }; + + switch (S_v) { + case 16: launch_sv(std::integral_constant{}); break; + case 32: launch_sv(std::integral_constant{}); break; + case 64: launch_sv(std::integral_constant{}); break; + case 128: launch_sv(std::integral_constant{}); break; default: GGML_ABORT("fatal error"); break; diff --git a/ggml/src/ggml-sycl/getrows.cpp b/ggml/src/ggml-sycl/getrows.cpp index 7b53e3dcca54..4830186d8243 100644 --- a/ggml/src/ggml-sycl/getrows.cpp +++ b/ggml/src/ggml-sycl/getrows.cpp @@ -588,10 +588,24 @@ void ggml_sycl_op_get_rows(ggml_backend_sycl_context & ctx, ggml_tensor * dst) { src1_i32, (float *)dst->data, ctx.stream()); break; case GGML_TYPE_IQ4_NL: + if (src0_reordered) { + get_rows_sycl_reorder(dst->src[0], dst->src[1], dst, dst->src[0]->data, + src1_i32, (float *)dst->data, ctx.stream()); + break; + } get_rows_sycl(ctx, dst->src[0], dst->src[1], dst, (const float *)dst->src[0]->data, src1_i32, (float *)dst->data, ctx.stream()); break; case GGML_TYPE_IQ4_XS: + if (src0_reordered) { + const void * vx = dst->src[0]->data; + get_rows_sycl_reorder_k<1, QK_K / 8, 1>(dst->src[0], dst->src[1], dst, src1_i32, (float *)dst->data, ctx.stream(), + [=](float * y, int64_t ib, uint8_t * scales_local, const sycl::nd_item<1> & item_ct1, int64_t nb) { + dequantize_block_iq4_xs_reorder(vx, y, ib, (int) item_ct1.get_local_id(0), nb); + GGML_UNUSED(scales_local); + }); + break; + } get_rows_sycl(ctx, dst->src[0], dst->src[1], dst, (const float *)dst->src[0]->data, src1_i32, (float *)dst->data, ctx.stream()); break; diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp index 4fc90e543166..7dda19dfd761 100644 --- a/ggml/src/ggml-sycl/ggml-sycl.cpp +++ b/ggml/src/ggml-sycl/ggml-sycl.cpp @@ -111,6 +111,7 @@ int g_ggml_sycl_memtrace_step = 64; int g_ggml_sycl_enable_vmm = 1; int g_ggml_sycl_enable_fusion = 1; int g_ggml_sycl_enable_esimd = 1; +int g_ggml_sycl_mmid_esimd = 1; int g_ggml_sycl_mmvq_wide = 1; int g_ggml_sycl_enable_xmx_esimd = 1; int g_ggml_sycl_xmx_max_cols = GGML_SYCL_XMX_MAX_COLS_DEFAULT; @@ -444,6 +445,7 @@ static void ggml_check_sycl() try { g_ggml_sycl_enable_vmm = ggml_sycl_get_env("GGML_SYCL_ENABLE_VMM", 1); g_ggml_sycl_enable_fusion = ggml_sycl_get_env("GGML_SYCL_ENABLE_FUSION", 1); g_ggml_sycl_enable_esimd = ggml_sycl_get_env("GGML_SYCL_ENABLE_ESIMD", 1); + g_ggml_sycl_mmid_esimd = ggml_sycl_get_env("GGML_SYCL_MMID_ESIMD", 1); g_ggml_sycl_mmvq_wide = ggml_sycl_get_env("GGML_SYCL_MMVQ_WIDE", 1); g_ggml_sycl_enable_xmx_esimd = ggml_sycl_get_env("GGML_SYCL_ENABLE_XMX_ESIMD", 1); g_ggml_sycl_xmx_max_cols = std::max(0, ggml_sycl_get_env("GGML_SYCL_XMX_MAX_COLS", GGML_SYCL_XMX_MAX_COLS_DEFAULT)); @@ -578,6 +580,7 @@ static void ggml_check_sycl() try { GGML_LOG_INFO(" GGML_SYCL_ENABLE_OPT: %d\n", g_ggml_sycl_enable_optimize); GGML_LOG_INFO(" GGML_SYCL_XMX_GATHER_TYPES: %d\n", g_ggml_sycl_xmx_gather_types); GGML_LOG_INFO(" GGML_SYCL_MMID_SCHED: %d\n", g_ggml_sycl_mmid_sched); + GGML_LOG_INFO(" GGML_SYCL_MMID_ESIMD: %d\n", g_ggml_sycl_mmid_esimd); GGML_LOG_INFO(" GGML_SYCL_XMX_GATHER_SHAPES: %d\n", g_ggml_sycl_xmx_gather_shapes); GGML_LOG_INFO(" GGML_SYCL_DYNAMIC_PRECISION: %s\n", ggml_sycl_dynamic_precision_names[g_ggml_sycl_dynamic_precision]); @@ -829,6 +832,8 @@ ggml_backend_sycl_buffer_init_tensor(ggml_backend_buffer_t buffer, case GGML_TYPE_Q6_K: case GGML_TYPE_IQ3_XXS: case GGML_TYPE_IQ3_S: + case GGML_TYPE_IQ4_NL: + case GGML_TYPE_IQ4_XS: case GGML_TYPE_MXFP4:{ ggml_tensor_extra_gpu * extra = new ggml_tensor_extra_gpu{}; tensor->extra = extra; @@ -4383,6 +4388,8 @@ inline bool ggml_sycl_supports_reorder_mmvq(enum ggml_type type) { case GGML_TYPE_Q6_K: case GGML_TYPE_IQ3_XXS: case GGML_TYPE_IQ3_S: + case GGML_TYPE_IQ4_NL: + case GGML_TYPE_IQ4_XS: return true; default: return false; @@ -4972,6 +4979,20 @@ static bool reorder_qw_iq3_xxs(uint8_t * data_device, size_t size, dpct::queue_p }, stream); } +// IQ4_NL / IQ4_XS: the qs go to the front, everything before them (d, plus the IQ4_XS scales) is the block's +// record in the tail +template +static bool reorder_qw_iq4(uint8_t * data_device, size_t size, dpct::queue_ptr stream) { + constexpr size_t record_size = offsetof(block_t, qs); + return reorder_qw_planar(__func__, data_device, size, record_size, sizeof(block_t) - record_size, + [](const block_t & x, int64_t ib, uint8_t * tail, int64_t) { + const uint8_t * record = reinterpret_cast(&x); + for (size_t j = 0; j < record_size; ++j) { + tail[ib * record_size + j] = record[j]; + } + }, stream); +} + static bool reorder_qw(const ggml_tensor * src0, dpct::queue_ptr stream) { uint8_t * data_device = (uint8_t *) src0->data; size_t ncols = src0->ne[0]; @@ -5019,6 +5040,10 @@ static bool reorder_qw(const ggml_tensor * src0, dpct::queue_ptr stream) { return reorder_qw_iq3_xxs(data_device, size, stream); case GGML_TYPE_IQ3_S: return reorder_qw_iq3_s(data_device, size, stream); + case GGML_TYPE_IQ4_NL: + return reorder_qw_iq4(data_device, size, stream); + case GGML_TYPE_IQ4_XS: + return reorder_qw_iq4(data_device, size, stream); default: return false; } @@ -5381,8 +5406,8 @@ static bool ggml_sycl_mul_mat_glu_fused(ggml_backend_sycl_context & ctx, ggml_cg } // gate and up of one type the XMX kernel handles, it needs the reorder layout like the unfused mmvq path - if (wg->type == wu->type && gate->src[1] == act && act->ne[1] >= ggml_sycl_xmx_min_cols(wu->type) && - act->ne[1] <= g_ggml_sycl_xmx_glu_max_cols) { + if (wg->type == wu->type && ggml_sycl_xmx_supports_type(wu->type) && gate->src[1] == act && + act->ne[1] >= ggml_sycl_xmx_min_cols(wu->type) && act->ne[1] <= g_ggml_sycl_xmx_glu_max_cols) { opt_for_reorder(&ctx, wu, act, up, mul_mat_algo::MMVQ); opt_for_reorder(&ctx, wg, act, gate, mul_mat_algo::MMVQ); if (can_use_xmx_batch(ctx.device, wu, act) && can_use_xmx_batch(ctx.device, wg, act) && @@ -6705,6 +6730,12 @@ static void ggml_backend_sycl_graph_compute_impl(ggml_backend_sycl_context * syc continue; } } + if (node->op == GGML_OP_ADD && + ggml_sycl_can_fuse(cgraph, i, { GGML_OP_ADD, GGML_OP_RMS_NORM, GGML_OP_MUL }, {}) && + ggml_sycl_op_add_rms_norm_fused(*sycl_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2])) { + i += 2; + continue; + } if (node->op == GGML_OP_RMS_NORM && ggml_sycl_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ADD }, {})) { ggml_sycl_op_rms_norm_fused_add(*sycl_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2]); @@ -7434,8 +7465,7 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons if (op->type == GGML_TYPE_TQ2_0 || op->type == GGML_TYPE_TQ1_0) { return false; } - auto res = (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || - op->src[0]->type == GGML_TYPE_BF16) && + auto res = (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) && (op->src[1]->type == GGML_TYPE_I64 || op->src[1]->type == GGML_TYPE_I32); return res; } @@ -7624,6 +7654,7 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons } case GGML_OP_ROPE: case GGML_OP_ROPE_BACK: + return op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16; case GGML_OP_IM2COL: case GGML_OP_IM2COL_3D: case GGML_OP_UPSCALE: diff --git a/ggml/src/ggml-sycl/mmvq.cpp b/ggml/src/ggml-sycl/mmvq.cpp index 03464bfaed8f..614b38b2206d 100644 --- a/ggml/src/ggml-sycl/mmvq.cpp +++ b/ggml/src/ggml-sycl/mmvq.cpp @@ -1776,10 +1776,11 @@ static void mul_mat_vec_iq3_xxs_q8_1_sycl(const void *vx, const void *vy, } template -static void reorder_mul_mat_vec_iq3_q8_1_sycl(const void * vx, const void * vy, float * dst, const int ncols, - const int nrows, dpct::queue_ptr stream) { - static_assert(type == GGML_TYPE_IQ3_XXS || type == GGML_TYPE_IQ3_S); - GGML_ASSERT(ncols % QK_K == 0); +static void reorder_mul_mat_vec_iq_q8_1_sycl(const void * vx, const void * vy, float * dst, const int ncols, + const int nrows, dpct::queue_ptr stream) { + static_assert(type == GGML_TYPE_IQ3_XXS || type == GGML_TYPE_IQ3_S || type == GGML_TYPE_IQ4_NL || + type == GGML_TYPE_IQ4_XS); + GGML_ASSERT(ncols % ggml_sycl_reordered::block_q_t::traits::qk == 0); constexpr size_t num_subgroups = WARP_SIZE; const int block_num_y = ceil_div(nrows, GGML_SYCL_MMV_Y * (int) num_subgroups); const sycl::range<3> block_nums(1, 1, block_num_y); @@ -1795,13 +1796,14 @@ static void reorder_mul_mat_vec_iq3_q8_1_sycl(const void * vx, const void * vy, } template -static void reorder_mul_mat_vec_iq3_q8_1_sycl_ncols( +static void reorder_mul_mat_vec_iq_q8_1_sycl_ncols( const void * vx, const void * vy, float * dst, const int ncols, const int nrows, const int stride_col_y_bytes, const int stride_col_dst, dpct::queue_ptr stream) { - static_assert(type == GGML_TYPE_IQ3_XXS || type == GGML_TYPE_IQ3_S); - GGML_ASSERT(ncols % QK_K == 0); + static_assert(type == GGML_TYPE_IQ3_XXS || type == GGML_TYPE_IQ3_S || type == GGML_TYPE_IQ4_NL || + type == GGML_TYPE_IQ4_XS); + GGML_ASSERT(ncols % ggml_sycl_reordered::block_q_t::traits::qk == 0); constexpr size_t num_subgroups = WARP_SIZE; const int block_num_y = ceil_div(nrows, GGML_SYCL_MMV_Y * (int) num_subgroups); const sycl::range<3> block_nums(1, 1, block_num_y); @@ -1818,21 +1820,21 @@ static void reorder_mul_mat_vec_iq3_q8_1_sycl_ncols( } template -static void reorder_mul_mat_vec_iq3_q8_1_sycl_switch_ncols( +static void reorder_mul_mat_vec_iq_q8_1_sycl_switch_ncols( const void * vx, const void * vy, float * dst, const int ncols, const int nrows, const int ncols_dst, const int stride_col_y_bytes, const int stride_col_dst, dpct::queue_ptr stream) { switch (ncols_dst) { - case 1: reorder_mul_mat_vec_iq3_q8_1_sycl(vx, vy, dst, ncols, nrows, stream); break; - case 2: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; - case 3: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; - case 4: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; - case 5: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; - case 6: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; - case 7: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; - case 8: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; - default: GGML_ABORT("unsupported ncols_dst=%d for reordered IQ3 multi-col MMVQ", ncols_dst); + case 1: reorder_mul_mat_vec_iq_q8_1_sycl(vx, vy, dst, ncols, nrows, stream); break; + case 2: reorder_mul_mat_vec_iq_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; + case 3: reorder_mul_mat_vec_iq_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; + case 4: reorder_mul_mat_vec_iq_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; + case 5: reorder_mul_mat_vec_iq_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; + case 6: reorder_mul_mat_vec_iq_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; + case 7: reorder_mul_mat_vec_iq_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; + case 8: reorder_mul_mat_vec_iq_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; + default: GGML_ABORT("unsupported ncols_dst=%d for reordered IQ multi-col MMVQ", ncols_dst); } } @@ -2518,13 +2520,13 @@ void ggml_sycl_op_mul_mat_vec_q(ggml_backend_sycl_context & ctx, const ggml_tens const int stride_col_y_bytes = src1_padded_col_size * q8_1_ts / q8_1_bs; const int stride_col_dst = dst->ne[0]; GGML_SYCL_DEBUG("Calling reordered IQ3_XXS multi-col MMVQ ncols=%d\n", (int) src1_ncols); - reorder_mul_mat_vec_iq3_q8_1_sycl_switch_ncols( + reorder_mul_mat_vec_iq_q8_1_sycl_switch_ncols( src0_dd_i, src1_ddq_i, dst_dd_i, ne00, row_diff, src1_ncols, stride_col_y_bytes, stride_col_dst, stream); return; } else { GGML_SYCL_DEBUG("Calling reordered IQ3_XXS MMVQ\n"); - reorder_mul_mat_vec_iq3_q8_1_sycl( + reorder_mul_mat_vec_iq_q8_1_sycl( src0_dd_i, src1_ddq_i_bs, dst_dd_i_bs, ne00, row_diff, stream); } } else { @@ -2539,13 +2541,13 @@ void ggml_sycl_op_mul_mat_vec_q(ggml_backend_sycl_context & ctx, const ggml_tens const int stride_col_y_bytes = src1_padded_col_size * q8_1_ts / q8_1_bs; const int stride_col_dst = dst->ne[0]; GGML_SYCL_DEBUG("Calling reordered IQ3_S multi-col MMVQ ncols=%d\n", (int) src1_ncols); - reorder_mul_mat_vec_iq3_q8_1_sycl_switch_ncols( + reorder_mul_mat_vec_iq_q8_1_sycl_switch_ncols( src0_dd_i, src1_ddq_i, dst_dd_i, ne00, row_diff, src1_ncols, stride_col_y_bytes, stride_col_dst, stream); return; } else { GGML_SYCL_DEBUG("Calling reordered IQ3_S MMVQ\n"); - reorder_mul_mat_vec_iq3_q8_1_sycl( + reorder_mul_mat_vec_iq_q8_1_sycl( src0_dd_i, src1_ddq_i_bs, dst_dd_i_bs, ne00, row_diff, stream); } } else if (i == 0 && src1_ncols > 1 && src1_ncols <= 8) { @@ -2561,10 +2563,42 @@ void ggml_sycl_op_mul_mat_vec_q(ggml_backend_sycl_context & ctx, const ggml_tens } break; case GGML_TYPE_IQ4_NL: - mul_mat_vec_iq4_nl_q8_1_sycl(src0_dd_i, src1_ddq_i_bs, dst_dd_i_bs, ne00, row_diff, stream); + if ((ggml_tensor_extra_gpu *) dst->src[0]->extra && + ((ggml_tensor_extra_gpu *) dst->src[0]->extra)->optimized_feature.reorder) { + if (i == 0 && src1_ncols > 1 && src1_ncols <= 8) { + const int stride_col_y_bytes = src1_padded_col_size * q8_1_ts / q8_1_bs; + const int stride_col_dst = dst->ne[0]; + GGML_SYCL_DEBUG("Calling reordered IQ4_NL multi-col MMVQ ncols=%d\n", (int) src1_ncols); + reorder_mul_mat_vec_iq_q8_1_sycl_switch_ncols( + src0_dd_i, src1_ddq_i, dst_dd_i, ne00, row_diff, + src1_ncols, stride_col_y_bytes, stride_col_dst, stream); + return; + } else { + GGML_SYCL_DEBUG("Calling reordered IQ4_NL MMVQ\n"); + reorder_mul_mat_vec_iq_q8_1_sycl( + src0_dd_i, src1_ddq_i_bs, dst_dd_i_bs, ne00, row_diff, stream); + } + } else { + mul_mat_vec_iq4_nl_q8_1_sycl(src0_dd_i, src1_ddq_i_bs, dst_dd_i_bs, ne00, row_diff, stream); + } break; case GGML_TYPE_IQ4_XS: - if (i == 0 && src1_ncols > 1 && src1_ncols <= 8) { + if ((ggml_tensor_extra_gpu *) dst->src[0]->extra && + ((ggml_tensor_extra_gpu *) dst->src[0]->extra)->optimized_feature.reorder) { + if (i == 0 && src1_ncols > 1 && src1_ncols <= 8) { + const int stride_col_y_bytes = src1_padded_col_size * q8_1_ts / q8_1_bs; + const int stride_col_dst = dst->ne[0]; + GGML_SYCL_DEBUG("Calling reordered IQ4_XS multi-col MMVQ ncols=%d\n", (int) src1_ncols); + reorder_mul_mat_vec_iq_q8_1_sycl_switch_ncols( + src0_dd_i, src1_ddq_i, dst_dd_i, ne00, row_diff, + src1_ncols, stride_col_y_bytes, stride_col_dst, stream); + return; + } else { + GGML_SYCL_DEBUG("Calling reordered IQ4_XS MMVQ\n"); + reorder_mul_mat_vec_iq_q8_1_sycl( + src0_dd_i, src1_ddq_i_bs, dst_dd_i_bs, ne00, row_diff, stream); + } + } else if (i == 0 && src1_ncols > 1 && src1_ncols <= 8) { const int stride_col_y = src1_padded_col_size / QK8_1; const int stride_col_dst = dst->ne[0]; GGML_SYCL_DEBUG("Calling mul_mat_vec_iq4_xs_q8_1_sycl_switch_ncols ncols=%d\n", (int)src1_ncols); diff --git a/ggml/src/ggml-sycl/norm.cpp b/ggml/src/ggml-sycl/norm.cpp index 36576e9c28c6..0cb30aa3550f 100644 --- a/ggml/src/ggml-sycl/norm.cpp +++ b/ggml/src/ggml-sycl/norm.cpp @@ -1,4 +1,6 @@ #include "norm.hpp" + +#include "fusion.hpp" #include "ggml-sycl/common.hpp" #include "ggml-sycl/presets.hpp" @@ -188,9 +190,28 @@ static void rms_norm_f32(const float* x, float* dst, const int ncols, float tmp = 0.0f; // partial sum for thread in warp - for (int col = tid; col < ncols; col += block_size) { - const float xi = x[col * src_stride_col]; - tmp += xi * xi; + // float4 path for contiguous, 16-byte aligned rows (decode), views and odd lengths stay strided + bool contig = src_stride_col == 1 && dst_stride_col == 1 && ncols % 4 == 0 && (uintptr_t) x % 16 == 0 && + (uintptr_t) dst % 16 == 0; + if constexpr (do_multiply) { + contig = contig && (uintptr_t) mul % 16 == 0; + } + if constexpr (do_add) { + contig = contig && (uintptr_t) add % 16 == 0; + } + const int n4 = ncols / 4; + + if (contig) { + const sycl::float4 * x4 = reinterpret_cast(x); + for (int i = tid; i < n4; i += block_size) { + const sycl::float4 v = x4[i]; + tmp += sycl::dot(v, v); + } + } else { + for (int col = tid; col < ncols; col += block_size) { + const float xi = x[col * src_stride_col]; + tmp += xi * xi; + } } // sum up partial sums @@ -216,17 +237,37 @@ static void rms_norm_f32(const float* x, float* dst, const int ncols, const float mean = tmp / ncols; const float scale = sycl::rsqrt(mean + eps); - for (int col = tid; col < ncols; col += block_size) { - if constexpr (do_multiply && do_add) { - dst[col * dst_stride_col] = scale * x[col * src_stride_col] * mul[col] + add[col]; - } else if constexpr (do_multiply) { - dst[col * dst_stride_col] = scale * x[col * src_stride_col] * mul[col]; - } else { - // folded epilogue of a fused GGML_OP_SCALE consumer (qwen35 GDN l2 norms); - // the explicit temporary keeps the float evaluation order identical to - // running rms_norm and scale as two separate kernels - const float v = scale * x[col * src_stride_col]; - dst[col * dst_stride_col] = v * scale_mul; + if (contig) { + const sycl::float4 * x4 = reinterpret_cast(x); + sycl::float4 * d4 = reinterpret_cast(dst); + const sycl::float4 * m4 = reinterpret_cast(mul); + const sycl::float4 * a4 = reinterpret_cast(add); + for (int i = tid; i < n4; i += block_size) { + const sycl::float4 v = x4[i]; + if constexpr (do_multiply && do_add) { + const sycl::float4 m = m4[i]; + const sycl::float4 a = a4[i]; + d4[i] = scale * v * m + a; + } else if constexpr (do_multiply) { + const sycl::float4 m = m4[i]; + d4[i] = scale * v * m; + } else { + d4[i] = scale * v * scale_mul; + } + } + } else { + for (int col = tid; col < ncols; col += block_size) { + if constexpr (do_multiply && do_add) { + dst[col * dst_stride_col] = scale * x[col * src_stride_col] * mul[col] + add[col]; + } else if constexpr (do_multiply) { + dst[col * dst_stride_col] = scale * x[col * src_stride_col] * mul[col]; + } else { + // folded epilogue of a fused GGML_OP_SCALE consumer (qwen35 GDN l2 norms); + // the explicit temporary keeps the float evaluation order identical to + // running rms_norm and scale as two separate kernels + const float v = scale * x[col * src_stride_col]; + dst[col * dst_stride_col] = v * scale_mul; + } } } } @@ -918,6 +959,127 @@ void ggml_sycl_op_rms_norm_fused_add(ggml_backend_sycl_context & ctx, ggml_tenso add_s01, add_s02, add_s03, add_nrows, add_nchannels, add_nsamples, eps, main_stream, ctx.device); } +// ADD(a, b) -> RMS_NORM -> MUL(w) in one launch. The sum (read by a later residual add) and +// normed * w are written after a barrier, as mul->data may alias a. +static void add_rms_norm_mul_f32(const float * a, + const float * b, + float * sum, + const float * mul, + float * dst, + const int ncols, + const float eps, + const sycl::nd_item<3> & item_ct1, + float * s_sum, + const int block_size) { + const int row = item_ct1.get_group(2); + const size_t off = (size_t) row * ncols; + const int tid = item_ct1.get_local_id(2); + const int n4 = ncols / 4; + + const sycl::float4 * a4 = reinterpret_cast(a + off); + const sycl::float4 * b4 = reinterpret_cast(b + off); + + sycl::float4 v[2]; + float tmp = 0.0f; +#pragma unroll + for (int k = 0; k < 2; ++k) { + const int i = tid + k * block_size; + if (i < n4) { + const sycl::float4 va = a4[i]; + const sycl::float4 vb = b4[i]; + v[k] = va + vb; + tmp += sycl::dot(v[k], v[k]); + } + } + + const int nwarps = block_size / WARP_SIZE; + tmp = warp_reduce_sum(tmp, item_ct1); + if (block_size > WARP_SIZE) { + const auto sub_group = item_ct1.get_sub_group(); + if (sub_group.get_local_linear_id() == 0) { + s_sum[sub_group.get_group_linear_id()] = tmp; + } + item_ct1.barrier(sycl::access::fence_space::local_space); + const size_t nreduce = ceil_div(nwarps, WARP_SIZE); + tmp = 0.0f; + for (size_t i = 0; i < nreduce; i += 1) { + tmp += s_sum[sub_group.get_local_linear_id() + i * WARP_SIZE]; + } + tmp = warp_reduce_sum(tmp, item_ct1); + } + + const float mean = tmp / ncols; + const float scale = sycl::rsqrt(mean + eps); + + sycl::float4 * s4 = reinterpret_cast(sum + off); + sycl::float4 * d4 = reinterpret_cast(dst + off); + const sycl::float4 * m4 = reinterpret_cast(mul); +#pragma unroll + for (int k = 0; k < 2; ++k) { + const int i = tid + k * block_size; + if (i < n4) { + const sycl::float4 m = m4[i]; + const sycl::float4 u = scale * v[k] * m; + s4[i] = v[k]; + d4[i] = u; + } + } +} + +static void add_rms_norm_mul_f32_sycl(const float * a, + const float * b, + float * sum, + const float * mul, + float * dst, + const int ncols, + const int nrows, + const float eps, + queue_ptr stream, + int device) { + const int work_group_size = ggml_sycl_info().max_work_group_sizes[device]; + GGML_ASSERT(work_group_size % (WARP_SIZE * WARP_SIZE) == 0); + const sycl::range<3> global_dims(1, 1, nrows); + const sycl::range<3> block_dims(1, 1, work_group_size); + stream->submit([&](sycl::handler & cgh) { + sycl::local_accessor s_sum(sycl::range<1>(work_group_size / WARP_SIZE), cgh); + cgh.parallel_for(sycl::nd_range<3>(global_dims * block_dims, block_dims), + [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(WARP_SIZE)]] { + add_rms_norm_mul_f32(a, b, sum, mul, dst, ncols, eps, item_ct1, get_pointer(s_sum), + work_group_size); + }); + }); +} + +bool ggml_sycl_op_add_rms_norm_fused(ggml_backend_sycl_context & ctx, + ggml_tensor * add, + ggml_tensor * rms, + ggml_tensor * mul) { + ggml_tensor * a = add->src[0]; + ggml_tensor * b = add->src[1]; + ggml_tensor * w = mul->src[0] == rms ? mul->src[1] : mul->src[0]; + const int64_t ncols = add->ne[0]; + const int wg = ggml_sycl_info().max_work_group_sizes[ctx.device]; + // whole rows of float4, at most two per work-item, from 16-byte aligned contiguous tensors + if (add->ne[2] != 1 || add->ne[3] != 1 || ncols < 1024 || ncols % 4 != 0 || ncols > 8 * (int64_t) wg || + w->ne[1] != 1) { + return false; + } + for (const ggml_tensor * t : { a, b, add, mul, w }) { + if (!ggml_is_contiguous(t) || (uintptr_t) t->data % 16 != 0) { + return false; + } + } + float eps = 0.0f; + memcpy(&eps, rms->op_params, sizeof(float)); + if (!(eps >= 0.0f)) { + return false; + } + add_rms_norm_mul_f32_sycl((const float *) a->data, (const float *) b->data, (float *) add->data, + (const float *) w->data, (float *) mul->data, (int) ncols, (int) add->ne[1], eps, + ctx.stream(), ctx.device); + return true; +} + void ggml_sycl_op_rms_norm_back(ggml_backend_sycl_context & ctx, ggml_tensor * dst) { scope_op_debug_print scope_dbg_print(__func__, dst, /*num_src=*/2); diff --git a/ggml/src/ggml-sycl/norm.hpp b/ggml/src/ggml-sycl/norm.hpp index fb667ac6b6e2..59a9ffd6fef2 100644 --- a/ggml/src/ggml-sycl/norm.hpp +++ b/ggml/src/ggml-sycl/norm.hpp @@ -25,6 +25,11 @@ void ggml_sycl_op_rms_norm_scale_fused(ggml_backend_sycl_context& ctx, ggml_tens void ggml_sycl_op_rms_norm_fused_add(ggml_backend_sycl_context& ctx, ggml_tensor* dst, ggml_tensor* mul_tensor, ggml_tensor* add_tensor); +bool ggml_sycl_op_add_rms_norm_fused(ggml_backend_sycl_context & ctx, + ggml_tensor * add, + ggml_tensor * rms, + ggml_tensor * mul); + void ggml_sycl_op_rms_norm_back(ggml_backend_sycl_context& ctx, ggml_tensor* dst); void ggml_sycl_op_group_norm(ggml_backend_sycl_context& ctx, ggml_tensor* dst); diff --git a/ggml/src/ggml-sycl/quants.hpp b/ggml/src/ggml-sycl/quants.hpp index 9fdcc22f21c6..79b5c8de5d1f 100644 --- a/ggml/src/ggml-sycl/quants.hpp +++ b/ggml/src/ggml-sycl/quants.hpp @@ -14,6 +14,7 @@ #ifndef GGML_SYCL_QUANTS_HPP #define GGML_SYCL_QUANTS_HPP +#include #include #include "ggml-common.h" @@ -225,6 +226,70 @@ template <> struct block_q_t { static constexpr int block_to_q8_1_ratio() { return traits::qk / QK8_1; } }; +template <> struct block_q_t { + struct traits { + static constexpr uint32_t qk = QK4_NL; + static constexpr uint32_t qi = QI4_NL; + static constexpr uint32_t qr = QR4_NL; + static constexpr uint32_t vdr_mmvq = 4; + }; + + // Reordered layout: [qs (QK4_NL/2 per block)][d] + static constexpr int record_size = offsetof(block_iq4_nl, qs); + + static constexpr std::pair get_block_offset(const int block_index, const int /* nblocks */) { + return { block_index * (QK4_NL / 2), 0 }; + } + + static constexpr std::pair get_d_offset(int nrows, int ncols, const int block_index) { + return { (ncols / QR4_NL * nrows) + block_index * sizeof(ggml_half), 0 }; + } + + static float group_scale(const uint8_t * record, const int /* group */) { + return *reinterpret_cast(record); + } + + static constexpr int block_to_q8_1_ratio() { return traits::qk / QK8_1; } +}; + +template <> struct block_q_t { + struct traits { + static constexpr uint32_t qk = QK_K; + static constexpr uint32_t qi = QI4_XS; + static constexpr uint32_t qr = QR4_XS; + static constexpr uint32_t vdr_mmvq = 4; + }; + + // Reordered layout: [qs (QK_K/2 per block)][{d, scales_h, scales_l} per block, as in block_iq4_xs] + static constexpr int record_size = offsetof(block_iq4_xs, qs); + + static constexpr std::pair get_block_offset(const int block_index, const int /* nblocks */) { + return { block_index * (QK_K / 2), 0 }; + } + + static constexpr std::pair get_d_offset(int nrows, int ncols, const int block_index) { + const int nblocks = nrows * (ncols / QK_K); + return { nblocks * (QK_K / 2) + block_index * (int) offsetof(block_iq4_xs, qs), 0 }; + } + + static float group_scale(const uint8_t * record, const int group) { + const uint16_t scales_h = *reinterpret_cast(record + offsetof(block_iq4_xs, scales_h)); + const uint8_t scales_l = record[offsetof(block_iq4_xs, scales_l) + group / 2]; + const int ls = ((scales_l >> (4 * (group % 2))) & 0xf) | (((scales_h >> (2 * group)) & 3) << 4); + return (float) *reinterpret_cast(record + offsetof(block_iq4_xs, d)) * (ls - 32); + } + + static constexpr int block_to_q8_1_ratio() { return traits::qk / QK8_1; } +}; + +// IQ4_NL blocks and IQ4_XS sub-blocks are 32-value groups of 16 qs bytes, so in both layouts the qs of +// group g start at 16 * g; tail is the first byte after all qs, where the per-block records start +template inline float iq4_group_scale(const uint8_t * tail, const int64_t g) { + using block_t = block_q_t; + constexpr int64_t groups = block_t::traits::qk / QK4_NL; + return block_t::group_scale(tail + g / groups * block_t::record_size, (int) (g % groups)); +} + template <> struct block_q_t { struct traits { static constexpr uint32_t qk = QK8_0; // 32 diff --git a/ggml/src/ggml-sycl/vecdotq.hpp b/ggml/src/ggml-sycl/vecdotq.hpp index f547b20e687f..f2f34667a892 100644 --- a/ggml/src/ggml-sycl/vecdotq.hpp +++ b/ggml/src/ggml-sycl/vecdotq.hpp @@ -388,6 +388,14 @@ template <> struct reorder_vec_dot_shared_weights { static constexpr bool value = true; }; +template <> struct reorder_vec_dot_shared_weights { + static constexpr bool value = true; +}; + +template <> struct reorder_vec_dot_shared_weights { + static constexpr bool value = true; +}; + template struct reorder_vec_dot_shared_activations { static constexpr bool value = false; }; @@ -1956,4 +1964,88 @@ vec_dot_iq4_xs_q8_1(const void *__restrict__ vbq, #endif } +// IQ4_NL blocks and IQ4_XS sub-blocks are both 32 values in 16 qs bytes: the low nibbles pair with +// q8_1 ints 0..3 and the high nibbles with ints 4..7. A lane decodes them once for all columns. +struct reorder_vec_dot_iq4_32 { + struct weights { + int v[8]; + float d; + }; + + static __dpct_inline__ weights decode(const uint8_t * qs, const float d) { + const sycl::int4 q4 = *reinterpret_cast(qs); + const uint8_t * values = (const uint8_t *) kvalues_iq4nl; + + weights w; + get_int_from_table_16((uint32_t) q4.x(), values, w.v[0], w.v[4]); + get_int_from_table_16((uint32_t) q4.y(), values, w.v[1], w.v[5]); + get_int_from_table_16((uint32_t) q4.z(), values, w.v[2], w.v[6]); + get_int_from_table_16((uint32_t) q4.w(), values, w.v[3], w.v[7]); + w.d = d; + return w; + } + + static __dpct_inline__ float dot32(const weights & w, const int8_t * q8, const sycl::half2 ds8) { + const int * u = (const int *) q8; + int sumi1 = 0; + int sumi2 = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) { + sumi1 = dpct::dp4a(w.v[j + 0], u[j + 0], sumi1); + sumi2 = dpct::dp4a(w.v[j + 4], u[j + 4], sumi2); + } + return w.d * (float) ds8[0] * (sumi1 + sumi2); + } +}; + +template <> struct reorder_vec_dot_q_sycl : reorder_vec_dot_iq4_32 { + static constexpr ggml_type gtype = GGML_TYPE_IQ4_NL; + + // a lane holds a whole block, so iqs is always 0 + __dpct_inline__ static weights load(const void * __restrict__ vbq, const std::pair ibx_offset, + const std::pair d_offset, const int & /* iqs */) { + const uint8_t * base = static_cast(vbq); + return decode(base + ibx_offset.first, *reinterpret_cast(base + d_offset.first)); + } + + __dpct_inline__ static float dot(const weights & w, const int8_t * q8_1_quant_ptr, const sycl::half2 * q8_1_ds, + const int & /* iqs */) { + return dot32(w, q8_1_quant_ptr, *q8_1_ds); + } + + __dpct_inline__ float operator()(const void * __restrict__ vbq, const std::pair ibx_offset, + const std::pair d_offset, const int8_t * q8_1_quant_ptr, + const sycl::half2 * q8_1_ds, const int & iqs) { + return dot(load(vbq, ibx_offset, d_offset, iqs), q8_1_quant_ptr, q8_1_ds, iqs); + } +}; + +template <> struct reorder_vec_dot_q_sycl : reorder_vec_dot_iq4_32 { + static constexpr ggml_type gtype = GGML_TYPE_IQ4_XS; + + // iqs is the first qs int of the lane's sub-block + __dpct_inline__ static weights load(const void * __restrict__ vbq, const std::pair ibx_offset, + const std::pair d_offset, const int & iqs) { + const uint8_t * base = static_cast(vbq); + const uint8_t * meta = base + d_offset.first; + const int ib32 = iqs / 4; + const uint16_t scales_h = *reinterpret_cast(meta + offsetof(block_iq4_xs, scales_h)); + const uint8_t scales_l = meta[offsetof(block_iq4_xs, scales_l) + ib32 / 2]; + const int ls = ((scales_l >> (4 * (ib32 % 2))) & 0xf) | (((scales_h >> (2 * ib32)) & 3) << 4); + const float d = (float) *reinterpret_cast(meta + offsetof(block_iq4_xs, d)); + return decode(base + ibx_offset.first + sizeof(int) * iqs, d * (ls - 32)); + } + + __dpct_inline__ static float dot(const weights & w, const int8_t * q8_1_quant_ptr, const sycl::half2 * q8_1_ds, + const int & iqs) { + return dot32(w, q8_1_quant_ptr + (iqs / 4) * QK8_1, q8_1_ds[iqs / 4]); + } + + __dpct_inline__ float operator()(const void * __restrict__ vbq, const std::pair ibx_offset, + const std::pair d_offset, const int8_t * q8_1_quant_ptr, + const sycl::half2 * q8_1_ds, const int & iqs) { + return dot(load(vbq, ibx_offset, d_offset, iqs), q8_1_quant_ptr, q8_1_ds, iqs); + } +}; + #endif // GGML_SYCL_VECDOTQ_HPP diff --git a/ggml/src/ggml-version.h.in b/ggml/src/ggml-version.h.in index 37de362977b7..8cfaea5d7707 100644 --- a/ggml/src/ggml-version.h.in +++ b/ggml/src/ggml-version.h.in @@ -2,3 +2,7 @@ #define GGML_VERSION "@GGML_VERSION@" #define GGML_COMMIT "@GGML_BUILD_COMMIT@" + +#define GGML_VERSION_MAJOR (@GGML_VERSION_MAJOR@) +#define GGML_VERSION_MINOR (@GGML_VERSION_MINOR@) +#define GGML_VERSION_PATCH (@GGML_VERSION_PATCH@) diff --git a/ggml/src/ggml-vulkan/CMakeLists.txt b/ggml/src/ggml-vulkan/CMakeLists.txt index 791753a8cf9a..d8fa6ef409bb 100644 --- a/ggml/src/ggml-vulkan/CMakeLists.txt +++ b/ggml/src/ggml-vulkan/CMakeLists.txt @@ -101,6 +101,12 @@ if (Vulkan_FOUND) "GGML_VULKAN_COOPMAT2_DECODE_VECTOR_GLSLC_SUPPORT" ) + test_shader_extension_support( + "GL_EXT_cooperative_matrix_maintenance1" + "${CMAKE_CURRENT_SOURCE_DIR}/vulkan-shaders/feature-tests/coopmat_maintenance1.comp" + "GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT" + ) + test_shader_extension_support( "GL_EXT_integer_dot_product" "${CMAKE_CURRENT_SOURCE_DIR}/vulkan-shaders/feature-tests/integer_dot.comp" diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-buffers.cpp b/ggml/src/ggml-vulkan/ggml-vulkan-buffers.cpp index ed814b59feed..778d012bcb7e 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-buffers.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan-buffers.cpp @@ -809,9 +809,25 @@ void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t siz return; } + // vkCmdFillBuffer requires a 4-byte aligned offset and size, so write the unaligned ends from the matching bytes of c + const size_t end = offset + size; + const size_t begin_aligned = std::min(GGML_PAD(offset, 4), end); + const size_t end_aligned = std::max(end - end % 4, begin_aligned); + + const uint8_t * c_bytes = (const uint8_t *) &c; + if (begin_aligned > offset) { + ggml_vk_buffer_write(dst, offset, c_bytes + offset % 4, begin_aligned - offset); + } + if (end > end_aligned) { + ggml_vk_buffer_write(dst, end_aligned, c_bytes, end - end_aligned); + } + if (end_aligned == begin_aligned) { + return; + } + std::lock_guard guard(dst->device->mutex); vk_context subctx = ggml_vk_begin_sync_ctx(dst->device, dst->device->transfer_queue->cmd_pool); - subctx->s->buffer->buf.fillBuffer(dst->buffer, offset, size, c); + subctx->s->buffer->buf.fillBuffer(dst->buffer, begin_aligned, end_aligned - begin_aligned, c); ggml_vk_submit_sync(dst->device, subctx); } diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp b/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp index 56fa6ada34ae..79258b871145 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp @@ -1043,6 +1043,8 @@ void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph } else if (tensor->op == GGML_OP_FILL) { const float value = ggml_get_op_params_f32(tensor, 0); tensor_clone = ggml_fill(ggml_ctx, src_clone[0], value); + } else if (tensor->op == GGML_OP_SLEEP) { + tensor_clone = ggml_sleep(ggml_ctx, src_clone[0], ggml_get_op_params_i32(tensor, 0)); } else if (tensor->op == GGML_OP_SQR) { tensor_clone = ggml_sqr(ggml_ctx, src_clone[0]); } else if (tensor->op == GGML_OP_SQRT) { diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h index 176dbb72ad21..7a48c08dc3a9 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h @@ -189,6 +189,10 @@ struct vk_op_push_constants { float param4; }; +struct vk_op_sleep_push_constants { + uint32_t ticks; +}; + struct vk_op_fwht_push_constants { uint32_t n_rows; uint32_t src_offset; @@ -691,6 +695,7 @@ struct vk_op_col2im_1d_push_constants { uint32_t K; int32_t stride; int32_t p0; + uint32_t src_offset; }; struct vk_op_conv_transpose_1d_push_constants { @@ -783,6 +788,7 @@ struct vk_op_gated_delta_net_push_constants { uint32_t n_seqs; uint32_t s_off; uint32_t sq1, sq2, sq3; + uint32_t sk1, sk2, sk3; uint32_t sv1, sv2, sv3; uint32_t sb1, sb2, sb3; uint32_t neq1, rq3; @@ -1027,6 +1033,15 @@ template <> inline void init_pushconst_tensor_offsets(ggml_backend_vk_context * GGML_UNUSED(src3); } +template <> inline void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_col2im_1d_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) { + p.src_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type); + GGML_ASSERT(get_misalign_bytes(ctx, dst) == 0); + + GGML_UNUSED(src1); + GGML_UNUSED(src2); + GGML_UNUSED(src3); +} + template <> inline void init_pushconst_tensor_offsets(ggml_backend_vk_context * ctx, vk_op_dsv4_hc_comb_push_constants &p, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, const ggml_tensor * src3, ggml_tensor * dst) { p.m_offset = get_misalign_bytes(ctx, src0) / ggml_type_size(src0->type); p.s_offset = get_misalign_bytes(ctx, src1) / ggml_type_size(src1->type); diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-types.h b/ggml/src/ggml-vulkan/ggml-vulkan-types.h index 6cc76b32307c..211948ee793b 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-types.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-types.h @@ -36,6 +36,21 @@ typedef struct VkPhysicalDeviceCooperativeMatrixDecodeVectorFeaturesNV { } VkPhysicalDeviceCooperativeMatrixDecodeVectorFeaturesNV; #endif +#ifndef VK_EXT_cooperative_matrix_maintenance1 +#define VK_EXT_cooperative_matrix_maintenance1 1 +#define VK_EXT_COOPERATIVE_MATRIX_MAINTENANCE_1_EXTENSION_NAME "VK_EXT_cooperative_matrix_maintenance1" +#define VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_MAINTENANCE_1_FEATURES_EXT ((VkStructureType)1000659000) +typedef struct VkPhysicalDeviceCooperativeMatrixMaintenance1FeaturesEXT { + VkStructureType sType; + void* pNext; + VkBool32 cooperativeMatrixProperties2; + VkBool32 cooperativeMatrixReductions; + VkBool32 cooperativeMatrixConversions; + VkBool32 cooperativeMatrixPerElementOperations; + VkBool32 cooperativeMatrixGetCoordinate; +} VkPhysicalDeviceCooperativeMatrixMaintenance1FeaturesEXT; +#endif + #if __has_include() # include #elif __has_include() @@ -221,6 +236,12 @@ static bool is_pow2(uint32_t x) { return x > 1 && (x & (x-1)) == 0; } #define MAX_FUSED_ADDS (MAX_PARAMETER_COUNT - 3) +#define GGML_VK_GDN_CM_V 64u +#define GGML_VK_GDN_CM2_V 32u +#define GGML_VK_GDN_CM_D 128u +#define GGML_VK_GDN_CM_PAD 8u +#define GGML_VK_GDN_CM_LDP (GGML_VK_GDN_CM_D + GGML_VK_GDN_CM_PAD) + struct vk_pipeline_struct; typedef std::shared_ptr vk_pipeline; @@ -739,6 +760,7 @@ struct vk_device_struct { bool shader_int64; bool buffer_device_address; bool vulkan_memory_model; + bool shader_clock; bool add_rms_fusion; uint32_t partials_binding_alignment; @@ -766,6 +788,12 @@ struct vk_device_struct { bool coopmat_acc_f32_support {}; bool coopmat_acc_f16_support {}; bool coopmat_bf16_support {}; + bool coopmat_bf16_acc_support {}; + bool coopmat_maintenance1 {}; + bool coopmat_m1_reductions {}; + bool coopmat_m1_conversions {}; + bool coopmat_m1_per_element_ops {}; + bool coopmat_m1_get_coordinate {}; bool coopmat_support_16x16x16_f16acc {}; bool coopmat_support_16x16x16_f32acc {}; bool coopmat1_fa_support {}; @@ -780,6 +808,7 @@ struct vk_device_struct { bool coopmat2; bool coopmat2_bf16_support {}; + bool coopmat2_gdn_support {}; bool coopmat2_decode_vector; bool dot2_f16 {}; @@ -923,6 +952,8 @@ struct vk_device_struct { vk_pipeline pipeline_fill_f32; vk_pipeline pipeline_fill_f16; + vk_pipeline pipeline_sleep; + // [src/dst 0=fp32,1=fp16,2=bf16] vk_pipeline pipeline_glu[GGML_GLU_OP_COUNT][3]; @@ -984,6 +1015,9 @@ struct vk_device_struct { vk_pipeline pipeline_lightning_indexer_f32[GGML_TYPE_COUNT]; // [size_idx][kda] where size_idx: 0=d16, 1=d32, 2=d64, 3=d128 vk_pipeline pipeline_gated_delta_net[4][2]; + vk_pipeline pipeline_gated_delta_net_cm; + vk_pipeline pipeline_gated_delta_net_cm_v32; + vk_pipeline pipeline_gated_delta_net_cm_v128; vk_pipeline pipeline_ssm_scan_f32_d128; vk_pipeline pipeline_ssm_scan_f32_d256; vk_pipeline pipeline_ssm_conv_f32; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index 3674579cc4ed..60cebe49445e 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -1323,7 +1323,9 @@ static vk_fa_tuning_params get_fa_tuning_params_coopmat1(const vk_device& device } // Br=32 spills registers, only prefill benefits - result.q_in_regs = result.block_rows == coopmat_block_rows && device->vendor_id == VK_VENDOR_ID_AMD && n_rows >= 64; + // AMD proprietary driver crashes compiling the loop-indexed Qreg array + result.q_in_regs = result.block_rows == coopmat_block_rows && device->vendor_id == VK_VENDOR_ID_AMD && n_rows >= 64 && + device->driver_id != vk::DriverId::eAmdProprietary; // Flipped ownership: each subgroup owns 16 Q rows. // uma, nvidia: K/V tiles staged in separate LDS buffers; discrete AMD GQA: K/V loaded directly from global memory. @@ -1355,6 +1357,9 @@ static vk_fa_tuning_params get_fa_tuning_params_coopmat1(const vk_device& device result.limit_occupancy_shmem = 14 * 1024 / 16; } + // non-flip shader handles at most two row tiles + GGML_ASSERT(result.flip || result.block_rows <= 2 * coopmat_block_rows); + return result; } @@ -1667,6 +1672,22 @@ static uint32_t ggml_vk_mul_mat_vec_max_cols(const vk_device & device) { return device->coopmat2 && !device->disable_narrow_mul_mat ? 4u : mul_mat_vec_max_cols; } +static uint32_t ggml_vk_gated_delta_net_shmem_size(uint32_t v, bool coopmat2) { + const uint32_t C = 16; + const uint32_t LDP = GGML_VK_GDN_CM_LDP; + const uint32_t bf16_size = sizeof(ggml_bf16_t); + const bool gmem_mirror = !coopmat2 && v == 128; + + const uint32_t qk = 4 * C * LDP * bf16_size; + const uint32_t state = gmem_mirror ? 0 : 2 * v * LDP * bf16_size; + const uint32_t p_inv = 4 * C * C * bf16_size; + const uint32_t delta_solved = coopmat2 ? 2 * C * (v + GGML_VK_GDN_CM_PAD) * bf16_size : 4 * C * v * bf16_size; + const uint32_t lower = (coopmat2 ? C * (C - 1) / 2 : C * C) * sizeof(float); + const uint32_t scan = 4 * C * sizeof(float); + + return qk + state + p_inv + delta_solved + lower + scan; +} + static bool ggml_vk_matmul_shmem_support(const vk_device& device, const std::vector& warptile, bool mul_mat_id, ggml_type src0_type) { uint32_t lut_size = 0; @@ -3262,9 +3283,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { rm_stdq = 2; rm_stdq_int = 2; } - // RDNA3/4: above four columns, static 4 rows for all types bench faster than the default const bool is_rdna3_or_4 = device->vendor_id == VK_VENDOR_ID_AMD && (device->architecture == AMD_RDNA3 || device->architecture == AMD_RDNA4); - auto const &rm_int_n = [&](uint32_t rows, uint32_t i) { return (is_rdna3_or_4 && i >= 4) ? 4u : rows; }; // RDNA3/4 and NVIDIA except pre-Turing: use 4 rows for MUL_MAT_ID MMVQ. auto const &rm_id = [&](uint32_t rows) { if (device->vendor_id == VK_VENDOR_ID_NVIDIA && @@ -3375,25 +3394,43 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size; const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q2_0][i], "mul_mat_vec_q2_0_q8_1_f32", arr_dmmv_q2_0_q8_1_f32_len[reduc], arr_dmmv_q2_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(2*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(2*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_q8_1_f32", arr_dmmv_q4_0_q8_1_f32_len[reduc], arr_dmmv_q4_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_q8_1_f32", arr_dmmv_q4_1_q8_1_f32_len[reduc], arr_dmmv_q4_1_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_q8_1_f32", arr_dmmv_q5_0_q8_1_f32_len[reduc], arr_dmmv_q5_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_q8_1_f32", arr_dmmv_q5_1_q8_1_f32_len[reduc], arr_dmmv_q5_1_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_q8_1_f32", arr_dmmv_q8_0_q8_1_f32_len[reduc], arr_dmmv_q8_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_q8_1_f32", arr_dmmv_mxfp4_q8_1_f32_len[reduc], arr_dmmv_mxfp4_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(2*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(2*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_q8_1_f32", arr_dmmv_q2_k_q8_1_f32_len[reduc], arr_dmmv_q2_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(2*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(2*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_q8_1_f32", arr_dmmv_q3_k_q8_1_f32_len[reduc], arr_dmmv_q3_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_q8_1_f32", arr_dmmv_q4_k_q8_1_f32_len[reduc], arr_dmmv_q4_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_q8_1_f32", arr_dmmv_q5_k_q8_1_f32_len[reduc], arr_dmmv_q5_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_q8_1_f32", arr_dmmv_q6_k_q8_1_f32_len[reduc], arr_dmmv_q6_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_q8_1_f32", arr_dmmv_iq1_s_q8_1_f32_len[reduc], arr_dmmv_iq1_s_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_iq_int(i), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_q8_1_f32", arr_dmmv_iq1_m_q8_1_f32_len[reduc], arr_dmmv_iq1_m_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_iq_int(i), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_q8_1_f32", arr_dmmv_iq4_xs_q8_1_f32_len[reduc], arr_dmmv_iq4_xs_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); + const struct { + ggml_type type; + const char * name; + size_t spv_size; + const void * spv_data; + uint32_t default_rows; + } shaders[] = { + {GGML_TYPE_Q2_0, "mul_mat_vec_q2_0_q8_1_f32", arr_dmmv_q2_0_q8_1_f32_len[reduc], arr_dmmv_q2_0_q8_1_f32_data[reduc], 2*rm_kq_int}, + {GGML_TYPE_Q4_0, "mul_mat_vec_q4_0_q8_1_f32", arr_dmmv_q4_0_q8_1_f32_len[reduc], arr_dmmv_q4_0_q8_1_f32_data[reduc], rm_stdq_int}, + {GGML_TYPE_Q4_1, "mul_mat_vec_q4_1_q8_1_f32", arr_dmmv_q4_1_q8_1_f32_len[reduc], arr_dmmv_q4_1_q8_1_f32_data[reduc], rm_stdq_int}, + {GGML_TYPE_Q5_0, "mul_mat_vec_q5_0_q8_1_f32", arr_dmmv_q5_0_q8_1_f32_len[reduc], arr_dmmv_q5_0_q8_1_f32_data[reduc], rm_stdq_int}, + {GGML_TYPE_Q5_1, "mul_mat_vec_q5_1_q8_1_f32", arr_dmmv_q5_1_q8_1_f32_len[reduc], arr_dmmv_q5_1_q8_1_f32_data[reduc], rm_stdq_int}, + {GGML_TYPE_Q8_0, "mul_mat_vec_q8_0_q8_1_f32", arr_dmmv_q8_0_q8_1_f32_len[reduc], arr_dmmv_q8_0_q8_1_f32_data[reduc], rm_stdq_int}, + {GGML_TYPE_MXFP4, "mul_mat_vec_mxfp4_q8_1_f32", arr_dmmv_mxfp4_q8_1_f32_len[reduc], arr_dmmv_mxfp4_q8_1_f32_data[reduc], 2*rm_stdq_int}, + {GGML_TYPE_Q2_K, "mul_mat_vec_q2_k_q8_1_f32", arr_dmmv_q2_k_q8_1_f32_len[reduc], arr_dmmv_q2_k_q8_1_f32_data[reduc], 2*rm_kq_int}, + {GGML_TYPE_Q3_K, "mul_mat_vec_q3_k_q8_1_f32", arr_dmmv_q3_k_q8_1_f32_len[reduc], arr_dmmv_q3_k_q8_1_f32_data[reduc], rm_kq_int}, + {GGML_TYPE_Q4_K, "mul_mat_vec_q4_k_q8_1_f32", arr_dmmv_q4_k_q8_1_f32_len[reduc], arr_dmmv_q4_k_q8_1_f32_data[reduc], rm_kq_int}, + {GGML_TYPE_Q5_K, "mul_mat_vec_q5_k_q8_1_f32", arr_dmmv_q5_k_q8_1_f32_len[reduc], arr_dmmv_q5_k_q8_1_f32_data[reduc], rm_kq_int}, + {GGML_TYPE_Q6_K, "mul_mat_vec_q6_k_q8_1_f32", arr_dmmv_q6_k_q8_1_f32_len[reduc], arr_dmmv_q6_k_q8_1_f32_data[reduc], rm_kq_int}, + {GGML_TYPE_IQ1_S, "mul_mat_vec_iq1_s_q8_1_f32", arr_dmmv_iq1_s_q8_1_f32_len[reduc], arr_dmmv_iq1_s_q8_1_f32_data[reduc], rm_iq_int(i)}, + {GGML_TYPE_IQ1_M, "mul_mat_vec_iq1_m_q8_1_f32", arr_dmmv_iq1_m_q8_1_f32_len[reduc], arr_dmmv_iq1_m_q8_1_f32_data[reduc], rm_iq_int(i)}, + {GGML_TYPE_IQ4_XS, "mul_mat_vec_iq4_xs_q8_1_f32", arr_dmmv_iq4_xs_q8_1_f32_len[reduc], arr_dmmv_iq4_xs_q8_1_f32_data[reduc], rm_stdq_int}, + }; + const bool use_four_rows = is_rdna3_or_4 && i >= 4; + const bool rdna4_amd_prop = device->architecture == AMD_RDNA4 && device->driver_id == vk::DriverId::eAmdProprietary; + for (const auto & shader : shaders) { + // Four rows can be slower for these quants on the AMD proprietary driver. + const bool use_default_rows = rdna4_amd_prop && + (shader.type == GGML_TYPE_Q3_K || shader.type == GGML_TYPE_Q5_K || shader.type == GGML_TYPE_IQ4_XS); + const uint32_t rows = use_four_rows && !use_default_rows ? 4u : shader.default_rows; + + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][shader.type][i], + shader.name, shader.spv_size, shader.spv_data, "main", mul_mat_vec_num_bindings, + sizeof(vk_mat_vec_push_constants), {rows, 1, 1}, {wg_size_subgroup_int, rows, i+1}, + 1, true, use_subgroups, subgroup_size_int); + } } #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT } @@ -3461,7 +3498,6 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { GGML_UNUSED(rm_stdq_int); GGML_UNUSED(rm_kq_int); GGML_UNUSED(is_rdna3_or_4); - GGML_UNUSED(rm_int_n); GGML_UNUSED(rm_id); GGML_UNUSED(rm_iq_int); #endif @@ -3892,6 +3928,10 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { ggml_vk_create_pipeline(device, device->pipeline_fill_f32, "fill_f32", fill_f32_len, fill_f32_data, "main", 1, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); ggml_vk_create_pipeline(device, device->pipeline_fill_f16, "fill_f16", fill_f16_len, fill_f16_data, "main", 1, sizeof(vk_op_push_constants), {512, 1, 1}, {}, 1); + if (device->shader_clock) { + ggml_vk_create_pipeline(device, device->pipeline_sleep, "sleep", sleep_len, sleep_data, "main", 1, sizeof(vk_op_sleep_push_constants), {1, 1, 1}, {}, 1); + } + #define CREATE_GLU(name, op) \ ggml_vk_create_pipeline(device, device->pipeline_glu[GGML_GLU_OP_ ## op][0], #name "_f32", name ## _f32_len, name ## _f32_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \ ggml_vk_create_pipeline(device, device->pipeline_glu[GGML_GLU_OP_ ## op][1], #name "_f16", name ## _f16_len, name ## _f16_data, "main", 3, sizeof(vk_op_glu_push_constants), {512, 1, 1}, {}, 1, true); \ @@ -4120,13 +4160,14 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { device->subgroup_min_size <= 16u && device->subgroup_max_size >= 16u) { gdn_subgroup_size = 16u; } + const bool gdn_packed_rows = S_V == 128u && device->vendor_id == VK_VENDOR_ID_NVIDIA && + gdn_subgroup_size == 32u && device->subgroup_arithmetic && device->subgroup_clustered; uint32_t lanes_per_column; if (device->vendor_id == VK_VENDOR_ID_INTEL) { // Intel Xe: full-width reduction (min rows/lane) ~10x over the COLS_PER_WG=8 rule. lanes_per_column = std::min(gdn_subgroup_size, S_V); } else if (S_V >= 128u && device->subgroup_clustered) { - // COLS_PER_WG=8: measured optimum (Ampere sg32->4, Vega20 sg64->8). - lanes_per_column = std::max(1u, gdn_subgroup_size / 8u); + lanes_per_column = gdn_packed_rows ? 8u : std::max(1u, gdn_subgroup_size / 8u); } else { // Use largest power-of-two that divides both S_V and subgroup_size so that // (1) S_V % lanes_per_column == 0 and (2) S_V % (subgroup_size / lanes_per_column) == 0. @@ -4173,9 +4214,60 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { for (uint32_t kda = 0; kda < 2; kda++) { ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net[si][kda], gdn_names[si][kda], gdn_len, gdn_data, "main", 7, sizeof(vk_op_gated_delta_net_push_constants), - wg_denoms, {S_V, kda, gdn_subgroup_size, lanes_per_column}, 1, true, use_subgroup_ops, gdn_subgroup_size); + wg_denoms, {S_V, kda, gdn_subgroup_size, lanes_per_column, uint32_t(gdn_packed_rows)}, 1, true, use_subgroup_ops, gdn_subgroup_size); + } + } + + // Chunked GDN prefill uses workgroup matrices on CM2 and subgroup matrices on CM1. + const bool gdn_chunked = getenv("GGML_VK_DISABLE_GDN_CHUNKED") == nullptr; + const uint32_t gdn_shmem = device->properties.limits.maxComputeSharedMemorySize; +#if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) + if (gdn_chunked && device->coopmat2 && device->coopmat2_gdn_support) { + ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net_cm, + "gated_delta_net_f32_cm2", gated_delta_net_f32_cm2_len, gated_delta_net_f32_cm2_data, + "main", 7, sizeof(vk_op_gated_delta_net_push_constants), {1, 1, 1}, {}, 1, true, true, 32); + } +#endif +#if defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) && defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) && defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) + // shader needs >= 16 lanes and 16 subgroups per WG; prefer wave64 + auto gdn_sg_ok = [&](uint32_t sg) { + const bool reachable = device->subgroup_size_control ? device->subgroup_min_size <= sg && sg <= device->subgroup_max_size + : device->subgroup_size == sg; + return reachable && 16u * sg <= device->properties.limits.maxComputeWorkGroupInvocations && + 16u * sg <= device->properties.limits.maxComputeWorkGroupSize[0]; + }; + const uint32_t gdn_sg = gdn_sg_ok(64) ? 64u : device->subgroup_size; + if (gdn_chunked && !device->coopmat2 && device->coopmat_support && device->coopmat_bf16_support && device->coopmat_m1_per_element_ops && + gdn_sg >= 16 && gdn_sg_ok(gdn_sg)) { + const bool bf16acc = device->coopmat_bf16_acc_support; + const std::vector gdn_spec = { 16u * gdn_sg }; + // V=64: state mirror in shared, 7 bindings + if (gdn_shmem >= ggml_vk_gated_delta_net_shmem_size(GGML_VK_GDN_CM_V, false)) { + ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net_cm, + bf16acc ? "gated_delta_net_f32_cm1_bf16acc" : "gated_delta_net_f32_cm1", + bf16acc ? gated_delta_net_f32_cm1_bf16acc_len : gated_delta_net_f32_cm1_len, + bf16acc ? (const void *)gated_delta_net_f32_cm1_bf16acc_data : (const void *)gated_delta_net_f32_cm1_data, + "main", 7, sizeof(vk_op_gated_delta_net_push_constants), {1, 1, 1}, gdn_spec, 1, true, true, gdn_sg); + } + if (gdn_shmem >= ggml_vk_gated_delta_net_shmem_size(32u, false)) { + ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net_cm_v32, + bf16acc ? "gated_delta_net_f32_cm1_bf16acc_v32" : "gated_delta_net_f32_cm1_v32", + bf16acc ? gated_delta_net_f32_cm1_bf16acc_v32_len : gated_delta_net_f32_cm1_v32_len, + bf16acc ? (const void *)gated_delta_net_f32_cm1_bf16acc_v32_data : (const void *)gated_delta_net_f32_cm1_v32_data, + "main", 7, sizeof(vk_op_gated_delta_net_push_constants), {1, 1, 1}, gdn_spec, 1, true, true, gdn_sg); + } + // V=128: state mirror in a gmem scratch buffer, 8 bindings + if (gdn_shmem >= ggml_vk_gated_delta_net_shmem_size(128u, false)) { + ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net_cm_v128, + bf16acc ? "gated_delta_net_f32_cm1_bf16acc_v128" : "gated_delta_net_f32_cm1_v128", + bf16acc ? gated_delta_net_f32_cm1_bf16acc_v128_len : gated_delta_net_f32_cm1_v128_len, + bf16acc ? (const void *)gated_delta_net_f32_cm1_bf16acc_v128_data : (const void *)gated_delta_net_f32_cm1_v128_data, + "main", 8, sizeof(vk_op_gated_delta_net_push_constants), {1, 1, 1}, gdn_spec, 1, true, true, gdn_sg); } } +#endif + GGML_UNUSED(gdn_chunked); + GGML_UNUSED(gdn_shmem); } if (device->subgroup_arithmetic && device->subgroup_require_full_support) { @@ -4521,6 +4613,7 @@ vk_device ggml_vk_get_device(size_t idx) { bool ocp_microscaling_extension = false; bool shader_float8_extension = false; bool workgroup_memory_explicit_layout_support = false; + bool shader_clock_support = false; for (const auto& properties : ext_props) { if (strcmp("VK_KHR_maintenance4", properties.extensionName) == 0) { @@ -4549,6 +4642,11 @@ vk_device ggml_vk_get_device(size_t idx) { } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 && !getenv("GGML_VK_DISABLE_COOPMAT2")) { coopmat2_support = true; +#endif +#if defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + } else if (strcmp("VK_EXT_cooperative_matrix_maintenance1", properties.extensionName) == 0 && + !getenv("GGML_VK_DISABLE_COOPMAT_MAINTENANCE1")) { + device->coopmat_maintenance1 = true; #endif } else if (strcmp(VK_NV_COOPERATIVE_MATRIX_DECODE_VECTOR_EXTENSION_NAME, properties.extensionName) == 0 && !getenv("GGML_VK_DISABLE_COOPMAT2_DECODE_VECTOR")) { @@ -4571,6 +4669,9 @@ vk_device ggml_vk_get_device(size_t idx) { } else if (strcmp(VK_EXT_SHADER_FLOAT8_EXTENSION_NAME, properties.extensionName) == 0) { shader_float8_extension = true; #endif + } else if (strcmp("VK_KHR_shader_clock", properties.extensionName) == 0 && + !getenv("GGML_VK_DISABLE_SHADER_CLOCK")) { + shader_clock_support = true; } else if (strcmp("VK_VALVE_shader_mixed_float_dot_product", properties.extensionName) == 0 && !getenv("GGML_VK_DISABLE_DOT2")) { dot2_f16_support = true; @@ -4727,6 +4828,10 @@ vk_device ggml_vk_get_device(size_t idx) { device->subgroup_arithmetic = false; } #endif + // Workaround for subgroupAdd() returning wrong sums on Adreno after divergent code + if (device->driver_id == vk::DriverId::eQualcommProprietary) { + device->subgroup_arithmetic = false; + } device->subgroup_shuffle = (vk11_props.subgroupSupportedStages & vk::ShaderStageFlagBits::eCompute) && (vk11_props.subgroupSupportedOperations & vk::SubgroupFeatureFlagBits::eShuffle); #ifdef __APPLE__ @@ -4868,6 +4973,15 @@ vk_device ggml_vk_get_device(size_t idx) { } #endif +#if defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + VkPhysicalDeviceCooperativeMatrixMaintenance1FeaturesEXT coopmat_m1_features {}; + coopmat_m1_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_MAINTENANCE_1_FEATURES_EXT; + if (device->coopmat_support && device->coopmat_maintenance1) { + last_struct->pNext = (VkBaseOutStructure *)&coopmat_m1_features; + last_struct = (VkBaseOutStructure *)&coopmat_m1_features; + } +#endif + VkPhysicalDeviceCooperativeMatrixDecodeVectorFeaturesNV coopmat2_decode_vector_features {}; coopmat2_decode_vector_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_DECODE_VECTOR_FEATURES_NV; if (coopmat2_decode_vector_support) { @@ -4919,6 +5033,14 @@ vk_device ggml_vk_get_device(size_t idx) { device_extensions.push_back("VK_KHR_shader_integer_dot_product"); } + VkPhysicalDeviceShaderClockFeaturesKHR shader_clock_features {}; + shader_clock_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR; + if (shader_clock_support) { + last_struct->pNext = (VkBaseOutStructure *)&shader_clock_features; + last_struct = (VkBaseOutStructure *)&shader_clock_features; + device_extensions.push_back("VK_KHR_shader_clock"); + } + VkPhysicalDeviceShaderMixedFloatDotProductFeaturesVALVE dot2_features {}; dot2_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_MIXED_FLOAT_DOT_PRODUCT_FEATURES_VALVE; if (dot2_f16_support) { @@ -5025,6 +5147,7 @@ vk_device ggml_vk_get_device(size_t idx) { device->shader_int64 = device_features2.features.shaderInt64; device->buffer_device_address = vk12_features.bufferDeviceAddress; device->vulkan_memory_model = vk12_features.vulkanMemoryModel; + device->shader_clock = shader_clock_support && shader_clock_features.shaderDeviceClock; if (device->subgroup_size_control) { device->subgroup_min_size = subgroup_size_control_props.minSubgroupSize; @@ -5043,6 +5166,17 @@ vk_device ggml_vk_get_device(size_t idx) { device->coopmat1_fa_support = device->coopmat_support && device->subgroup_require_full_support; #endif +#if defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + device->coopmat_maintenance1 = device->coopmat_support && device->coopmat_maintenance1; + if (device->coopmat_maintenance1) { + device->coopmat_m1_reductions = coopmat_m1_features.cooperativeMatrixReductions; + device->coopmat_m1_conversions = coopmat_m1_features.cooperativeMatrixConversions; + device->coopmat_m1_per_element_ops = coopmat_m1_features.cooperativeMatrixPerElementOperations; + device->coopmat_m1_get_coordinate = coopmat_m1_features.cooperativeMatrixGetCoordinate; + device_extensions.push_back(VK_EXT_COOPERATIVE_MATRIX_MAINTENANCE_1_EXTENSION_NAME); + } +#endif + if (coopmat2_support) { #if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) if (coopmat2_features.cooperativeMatrixWorkgroupScope && @@ -5126,6 +5260,13 @@ vk_device ggml_vk_get_device(size_t idx) { prop.KGranularity <= 16) { found_bf16_128 = true; } + // GDN uses M=32, with N/K dimensions that are multiples of 16. + if (prop.workgroupInvocations == 128 && + prop.MGranularity != 0 && 32 % prop.MGranularity == 0 && + prop.NGranularity != 0 && 16 % prop.NGranularity == 0 && + prop.KGranularity != 0 && 16 % prop.KGranularity == 0) { + device->coopmat2_gdn_support = true; + } if (prop.workgroupInvocations == 256 && prop.MGranularity <= 32 && prop.NGranularity <= 32 && @@ -5136,6 +5277,12 @@ vk_device ggml_vk_get_device(size_t idx) { #endif } } + device->coopmat2_gdn_support = device->coopmat2_gdn_support && + coopmat2_props.cooperativeMatrixWorkgroupScopeMaxWorkgroupSize >= 128 && + device->properties.limits.maxComputeWorkGroupInvocations >= 128 && + device->properties.limits.maxComputeWorkGroupSize[0] >= 128 && + uint64_t(ggml_vk_gated_delta_net_shmem_size(GGML_VK_GDN_CM2_V, true)) + coopmat2_props.cooperativeMatrixWorkgroupScopeReservedSharedMemory <= + device->properties.limits.maxComputeSharedMemorySize; if (found_fp16_128 && found_fp16_256 && found_fp32_128 && found_fp32_256 && coopmat2_props.cooperativeMatrixFlexibleDimensionsMaxDimension >= 512) { @@ -5253,6 +5400,18 @@ vk_device ggml_vk_get_device(size_t idx) { device->coopmat_bf16_support = true; } } + // bf16 accumulator (bf16/bf16/bf16/bf16) at the shader's fixed 16x16x16 + // shape lets the GDN coopmat1 path keep the hi/lo split as accumulators. + if (bfloat16_support && + prop.AType == VK_COMPONENT_TYPE_BFLOAT16_KHR && + prop.BType == VK_COMPONENT_TYPE_BFLOAT16_KHR && + prop.CType == VK_COMPONENT_TYPE_BFLOAT16_KHR && + prop.ResultType == VK_COMPONENT_TYPE_BFLOAT16_KHR && + (vk::ScopeKHR)prop.scope == vk::ScopeKHR::eSubgroup && + prop.MSize == 16 && prop.NSize == 16 && prop.KSize == 16 + ) { + device->coopmat_bf16_acc_support = true; + } #endif } @@ -5468,6 +5627,7 @@ static void ggml_vk_print_gpu_info(size_t idx) { bool coopmat_support = false; bool coopmat2_support = false; bool coopmat2_decode_vector_support = false; + bool coopmat_maintenance1_support = false; bool integer_dot_product = false; bool bfloat16_support = false; bool dot2_f16_support = false; @@ -5488,6 +5648,11 @@ static void ggml_vk_print_gpu_info(size_t idx) { } else if (strcmp("VK_NV_cooperative_matrix2", properties.extensionName) == 0 && !getenv("GGML_VK_DISABLE_COOPMAT2")) { coopmat2_support = true; +#endif +#if defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + } else if (strcmp("VK_EXT_cooperative_matrix_maintenance1", properties.extensionName) == 0 && + !getenv("GGML_VK_DISABLE_COOPMAT_MAINTENANCE1")) { + coopmat_maintenance1_support = true; #endif } else if (strcmp(VK_NV_COOPERATIVE_MATRIX_DECODE_VECTOR_EXTENSION_NAME, properties.extensionName) == 0 && !getenv("GGML_VK_DISABLE_COOPMAT2_DECODE_VECTOR")) { @@ -5571,6 +5736,15 @@ static void ggml_vk_print_gpu_info(size_t idx) { } #endif +#if defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + VkPhysicalDeviceCooperativeMatrixMaintenance1FeaturesEXT coopmat_m1_features {}; + coopmat_m1_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COOPERATIVE_MATRIX_MAINTENANCE_1_FEATURES_EXT; + if (coopmat_support && coopmat_maintenance1_support) { + last_struct->pNext = (VkBaseOutStructure *)&coopmat_m1_features; + last_struct = (VkBaseOutStructure *)&coopmat_m1_features; + } +#endif + VkPhysicalDeviceShaderIntegerDotProductFeaturesKHR shader_integer_dot_product_features {}; shader_integer_dot_product_features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_DOT_PRODUCT_FEATURES_KHR; if (integer_dot_product) { @@ -5664,13 +5838,17 @@ static void ggml_vk_print_gpu_info(size_t idx) { coopmat2_support = false; #endif +#if defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + coopmat_maintenance1_support = coopmat_maintenance1_support && coopmat_m1_features.cooperativeMatrixPerElementOperations; +#endif + coopmat2_decode_vector_support = coopmat2_decode_vector_support && coopmat2_decode_vector_features.cooperativeMatrixDecodeVector; #if !defined(GGML_VULKAN_COOPMAT2_DECODE_VECTOR_GLSLC_SUPPORT) coopmat2_decode_vector_support = false; #endif std::string matrix_cores = coopmat2_support ? (coopmat2_decode_vector_support ? "NV_coopmat2v" : "NV_coopmat2") - : coopmat_support ? "KHR_coopmat" + : coopmat_support ? (coopmat_maintenance1_support ? "KHR_coopmat_m1" : "KHR_coopmat") : "none"; bool dot2_f16 = dot2_f16_support && dot2_features.shaderMixedFloatDotProductFloat16AccFloat32; @@ -10235,6 +10413,8 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const return ctx->device->pipeline_arange_f32; } return nullptr; + case GGML_OP_SLEEP: + return ctx->device->pipeline_sleep; case GGML_OP_FILL: if (dst->type == GGML_TYPE_F32) { return ctx->device->pipeline_fill_f32; @@ -10450,6 +10630,12 @@ static void ggml_vk_op_f32(ggml_backend_vk_context * ctx, vk_context& subctx, co case GGML_OP_COL2IM_1D: { elements = { uint32_t(dst->ne[0]), uint32_t(dst->ne[1]), 1 }; + const uint32_t groups_x = CEIL_DIV(elements[0], pipeline->wg_denoms[0]); + const uint32_t max_groups_x = ctx->device->properties.limits.maxComputeWorkGroupCount[0]; + if (groups_x > max_groups_x) { + elements[2] = CEIL_DIV(groups_x, max_groups_x); + elements[0] = CEIL_DIV(groups_x, elements[2]) * pipeline->wg_denoms[0]; + } } break; case GGML_OP_POOL_1D: { @@ -11149,6 +11335,7 @@ void ggml_vk_lightning_indexer(ggml_backend_vk_context * ctx, vk_context& subctx void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { const ggml_tensor * src_q = dst->src[0]; + const ggml_tensor * src_k = dst->src[1]; const ggml_tensor * src_v = dst->src[2]; const ggml_tensor * src_beta = dst->src[4]; @@ -11164,7 +11351,39 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, const uint32_t s_off = S_v * H * n_tokens * n_seqs; - vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op); + const ggml_tensor * src_g = dst->src[3]; + // RDNA3: the scan is faster below ~4k tokens + const uint32_t cm_min_tokens = ctx->device->architecture == AMD_RDNA3 ? 4096u : 64u; + const bool use_cm = (ctx->device->pipeline_gated_delta_net_cm != nullptr || + ctx->device->pipeline_gated_delta_net_cm_v32 != nullptr || + ctx->device->pipeline_gated_delta_net_cm_v128 != nullptr) && + src_g->ne[0] == 1 && S_v == 128 && dst->src[0]->ne[0] == 128 && K == 1 && n_tokens >= cm_min_tokens; + + const bool use_cm2 = use_cm && ctx->device->coopmat2; + const bool have_v64 = ctx->device->pipeline_gated_delta_net_cm != nullptr; + bool use_v32 = use_cm && !use_cm2 && !have_v64 && ctx->device->pipeline_gated_delta_net_cm_v32 != nullptr; + bool use_v128 = use_cm && !use_cm2 && !have_v64 && !use_v32; + const uint32_t nsm = ctx->device->shader_core_count; + if (use_cm && !use_cm2 && have_v64 && nsm != 0) { + const uint32_t wg64 = 2u * H * n_seqs; + // V=32 only pays off while V=64 leaves at least half the cores idle + use_v32 = ctx->device->pipeline_gated_delta_net_cm_v32 != nullptr && 2u * wg64 <= nsm; + if (!use_v32 && ctx->device->pipeline_gated_delta_net_cm_v128 != nullptr) { + const uint32_t wg128 = H * n_seqs; + const uint32_t waves64 = (wg64 + nsm - 1) / nsm; + const uint32_t waves128 = (wg128 + nsm - 1) / nsm; + // prefer v128 when occupancy (wgs / (waves * nsm)) is at least as good + use_v128 = (uint64_t)wg128 * waves64 >= (uint64_t)wg64 * waves128; + } + } + + const uint32_t cm_V = use_cm2 ? GGML_VK_GDN_CM2_V : (use_v128 ? 128u : (use_v32 ? 32u : GGML_VK_GDN_CM_V)); + + vk_pipeline pipeline = use_v128 + ? ctx->device->pipeline_gated_delta_net_cm_v128 + : use_v32 ? ctx->device->pipeline_gated_delta_net_cm_v32 + : (use_cm ? ctx->device->pipeline_gated_delta_net_cm + : ggml_vk_op_get_pipeline(ctx, dst->src[0], dst->src[1], dst->src[2], dst, dst->op)); GGML_ASSERT(pipeline != nullptr); ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); @@ -11175,9 +11394,27 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]); } + vk_subbuffer mirror_buf{}; + if (use_v128) { + const uint32_t LDP = GGML_VK_GDN_CM_LDP; + const uint32_t blocks = (S_v / cm_V) * n_seqs * H; + const size_t scratch_size = (size_t)blocks * LDP * cm_V * 2u * sizeof(uint16_t); + if (ctx->prealloc_size_x < scratch_size) { + ctx->prealloc_size_x = scratch_size; + ggml_vk_preallocate_buffers(ctx, subctx); + } + if (ctx->prealloc_x_need_sync) { + ggml_vk_sync_buffers(ctx, subctx); + } + mirror_buf = vk_subbuffer{ ctx->prealloc_x, 0, ctx->prealloc_x->size }; + } + const uint32_t sq1 = (uint32_t)(src_q->nb[1] / sizeof(float)); const uint32_t sq2 = (uint32_t)(src_q->nb[2] / sizeof(float)); const uint32_t sq3 = (uint32_t)(src_q->nb[3] / sizeof(float)); + const uint32_t sk1 = (uint32_t)(src_k->nb[1] / sizeof(float)); + const uint32_t sk2 = (uint32_t)(src_k->nb[2] / sizeof(float)); + const uint32_t sk3 = (uint32_t)(src_k->nb[3] / sizeof(float)); const uint32_t sv1 = (uint32_t)(src_v->nb[1] / sizeof(float)); const uint32_t sv2 = (uint32_t)(src_v->nb[2] / sizeof(float)); const uint32_t sv3 = (uint32_t)(src_v->nb[3] / sizeof(float)); @@ -11192,6 +11429,7 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, const vk_op_gated_delta_net_push_constants pc = { H, n_tokens, n_seqs, s_off, sq1, sq2, sq3, + sk1, sk2, sk3, sv1, sv2, sv3, sb1, sb2, sb3, neq1, rq3, @@ -11199,9 +11437,16 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, K }; - ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, - {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf}, - pc, { H, n_seqs, S_v }); + if (use_v128) { + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf, mirror_buf}, + pc, std::array{ S_v / cm_V, n_seqs, H }); + ctx->prealloc_x_need_sync = true; + } else { + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf}, + pc, use_cm ? std::array{ S_v / cm_V, n_seqs, H } : std::array{ H, n_seqs, S_v }); + } } void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { @@ -11471,6 +11716,31 @@ void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements); } +static void ggml_vk_sleep(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) { + VK_LOG_DEBUG("ggml_vk_sleep(dst=" << dst << ", us=" << ggml_get_op_params_i32(dst, 0) << ")"); + + // Vulkan does not specify the period of the shader realtime clock this assumes it matches the timestamp counter. + // A driver where this does not hold could sleep too short or too long by that ratio + const float ns_per_tick = ctx->device->properties.limits.timestampPeriod; + const uint64_t ns = 1000 * (uint64_t) ggml_get_op_params_i32(dst, 0); + const uint64_t ticks = std::min(ns_per_tick > 0.0f ? (uint64_t)(ns / ns_per_tick) : ns, std::numeric_limits::max()); + + vk_op_sleep_push_constants pc = { + (uint32_t) ticks, + }; + + vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, nullptr, nullptr, nullptr, dst, GGML_OP_SLEEP); + GGML_ASSERT(pipeline != nullptr); + + ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); + vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst); + + // a single invocation spins, the buffer is bound only to keep the spin from being optimized out + std::array elements = { 1, 1, 1 }; + + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements); +} + void ggml_vk_sin(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, ggml_tensor * dst) { ggml_vk_op_f32(ctx, subctx, src0, nullptr, nullptr, nullptr, dst, GGML_OP_SIN, vk_op_unary_push_constants_init(src0, dst)); } @@ -13317,6 +13587,10 @@ bool ggml_vk_build_graph(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph, in case GGML_OP_FILL: ggml_vk_fill(ctx, compute_ctx, node); + break; + case GGML_OP_SLEEP: + ggml_vk_sleep(ctx, compute_ctx, node); + break; case GGML_OP_SCALE: if (ctx->fused_hc_post_gate) { @@ -14005,7 +14279,9 @@ bool ggml_backend_vk_buffer_cpy_tensor_n(ggml_backend_buffer_t buffer, const ggm void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) { ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context; - ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size); + // set all bytes of a u32 to the same 1 byte value + uint32_t val32 = (uint32_t)value * 0x01010101; + ggml_vk_buffer_memset(ctx->dev_buffer, 0, val32, buffer->size); } const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) { @@ -16681,8 +16957,9 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm case GGML_OP_REPEAT_BACK: return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32; case GGML_OP_ROPE: - return ggml_is_contiguous_rows(op) && ggml_is_contiguous_rows(op->src[0]); + return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) && ggml_is_contiguous_rows(op) && ggml_is_contiguous_rows(op->src[0]); case GGML_OP_ROPE_BACK: + return op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16; case GGML_OP_NONE: case GGML_OP_RESHAPE: case GGML_OP_VIEW: @@ -16768,8 +17045,10 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm return op->type == GGML_TYPE_F32; case GGML_OP_FILL: return op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16; + case GGML_OP_SLEEP: + return device->shader_clock; case GGML_OP_SCALE: - return ggml_is_contiguous(op->src[0]) && ggml_vk_is_float_elementwise(op); + return ggml_vk_is_float_elementwise(op); case GGML_OP_PAD: case GGML_OP_PAD_REFLECT_1D: case GGML_OP_ROLL: diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/CMakeLists.txt b/ggml/src/ggml-vulkan/vulkan-shaders/CMakeLists.txt index cbe7a68bf372..273a80233e61 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/CMakeLists.txt +++ b/ggml/src/ggml-vulkan/vulkan-shaders/CMakeLists.txt @@ -15,6 +15,10 @@ if (GGML_VULKAN_COOPMAT2_DECODE_VECTOR_GLSLC_SUPPORT) add_compile_definitions(GGML_VULKAN_COOPMAT2_DECODE_VECTOR_GLSLC_SUPPORT) message(STATUS "Enabling coopmat2 decode_vector glslc support") endif() +if (GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + add_compile_definitions(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + message(STATUS "Enabling coopmat maintenance1 glslc support") +endif() if (GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) add_compile_definitions(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT) message(STATUS "Enabling dot glslc support") diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/col2im_1d.comp b/ggml/src/ggml-vulkan/vulkan-shaders/col2im_1d.comp index a23de380f071..ba50544859e7 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/col2im_1d.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/col2im_1d.comp @@ -15,10 +15,12 @@ layout (push_constant) uniform parameter { uint32_t K; int32_t stride; int32_t p0; + uint32_t src_offset; } p; // Load A_TYPE to float float load_col(uint32_t idx) { + idx += p.src_offset; #if defined(DATA_A_BF16) return bf16_to_fp32(uint32_t(data_a[idx])); #else @@ -36,7 +38,7 @@ void store_dst(uint32_t idx, float v) { } void main() { - const uint32_t t_out = gl_GlobalInvocationID.x; + const uint32_t t_out = gl_GlobalInvocationID.x + gl_GlobalInvocationID.z * gl_NumWorkGroups.x * gl_WorkGroupSize.x; const uint32_t oc = gl_GlobalInvocationID.y; if (t_out >= p.T_out || oc >= p.OC) return; diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/feature-tests/coopmat_maintenance1.comp b/ggml/src/ggml-vulkan/vulkan-shaders/feature-tests/coopmat_maintenance1.comp new file mode 100644 index 000000000000..049ca2867393 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/feature-tests/coopmat_maintenance1.comp @@ -0,0 +1,8 @@ +#version 460 + +#extension GL_KHR_cooperative_matrix : require +#extension GL_EXT_cooperative_matrix_maintenance1 : require + +void main() +{ +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1.comp index bb9755ab8ac9..ea945ed075dc 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1.comp @@ -25,6 +25,7 @@ // These need to be supported N,M values for a MatBc x MatBr x 16 coopmatmuladd const uint32_t MatBr = 16; const uint32_t MatBc = 16; +const uint32_t q_tiles = Br / MatBr; const uint32_t rows_per_thread = Br / row_split; const uint32_t cols_per_iter = gl_WorkGroupSize.x / row_split; @@ -64,15 +65,14 @@ shared FLOAT_TYPEV4 kvsh[(kvsh_stride >= vsh_stride) ? (Bc * kvsh_stride) : (Bc shared ACC_TYPE slope[Br]; // row-tiled builds stage the PV result through sfsh -const bool PV_IN_SFSH = Br > MatBr; const uint32_t osh_stride = row_split * MatBr / 4; -shared O_TYPEV4 pvsh[PV_IN_SFSH ? 2 : Br * osh_stride]; +shared O_TYPEV4 pvsh[q_tiles > 1 ? 2 : Br * osh_stride]; shared vec4 occupancy_limiter[LIMIT_OCCUPANCY_SHMEM > 0 ? LIMIT_OCCUPANCY_SHMEM : 1]; #if defined(FLOAT16) && !defined(ACC_TYPE_MAX) const uint32_t pv_per_acc = 2; O_TYPEV4 pvsh_load(const uint32_t i) { - if (!PV_IN_SFSH) { + if (q_tiles == 1) { return pvsh[i]; } const uvec2 u = floatBitsToUint(vec2(sfsh[i / 2][(i % 2) * 2], sfsh[i / 2][(i % 2) * 2 + 1])); @@ -81,7 +81,7 @@ O_TYPEV4 pvsh_load(const uint32_t i) { #else const uint32_t pv_per_acc = 1; O_TYPEV4 pvsh_load(const uint32_t i) { - if (!PV_IN_SFSH) { + if (q_tiles == 1) { return pvsh[i]; } return O_TYPEV4(sfsh[i]); @@ -117,7 +117,6 @@ void main() { #define tile_row(r) (row_tid * rows_per_thread + (r)) - const uint32_t q_tiles = Br / MatBr; const uint32_t d_tiles = HSK_pad / 16; uint32_t q_offset = gqa_iq1*p.nb01 + (iq2*p.nb02+iq3*p.nb03) / 4; @@ -329,10 +328,9 @@ void main() { // K * Q^T -> S^T: Bc x HSK_pad * HSK_pad x Br -> Bc x Br // Bc split across workgroup (four subgroups), loop over HSK in chunks of 16: 16 x 16 * 16 x 16 -> 16 x 16 // This is written transposed in order to allow for N being 8 if implementations need it - coopmat SfMat[q_tiles]; - [[unroll]] for (uint32_t q = 0; q < q_tiles; ++q) { - SfMat[q] = coopmat(0); - } + // No coopmat arrays: AMD's Windows compiler crashes on loop-indexed ones. q_tiles <= 2. + coopmat SfMat0 = coopmat(0); + coopmat SfMat1 = coopmat(0); coopmat KMat; coopmat QMat; @@ -386,19 +384,24 @@ void main() { coopMatLoad(KMat, kvsh, coord, kvsh_stride, gl_CooperativeMatrixLayoutRowMajor); } - [[unroll]] for (uint32_t q = 0; q < q_tiles; ++q) { - if (Q_IN_REGS) { - SfMat[q] = coopMatMulAdd(KMat, Qreg[d * q_tiles + q], SfMat[q]); - } else { - coopMatLoad(QMat, Qf, d * 16 / 4 + q * MatBr * qstride, qstride, gl_CooperativeMatrixLayoutColumnMajor); - SfMat[q] = coopMatMulAdd(KMat, QMat, SfMat[q]); + if (Q_IN_REGS) { + SfMat0 = coopMatMulAdd(KMat, Qreg[d * q_tiles], SfMat0); + if (q_tiles > 1) { + SfMat1 = coopMatMulAdd(KMat, Qreg[d * q_tiles + 1], SfMat1); + } + } else { + coopMatLoad(QMat, Qf, d * 16 / 4, qstride, gl_CooperativeMatrixLayoutColumnMajor); + SfMat0 = coopMatMulAdd(KMat, QMat, SfMat0); + if (q_tiles > 1) { + coopMatLoad(QMat, Qf, d * 16 / 4 + MatBr * qstride, qstride, gl_CooperativeMatrixLayoutColumnMajor); + SfMat1 = coopMatMulAdd(KMat, QMat, SfMat1); } } } - [[unroll]] for (uint32_t q = 0; q < q_tiles; ++q) { - uint coord = gl_SubgroupID * MatBc * sfshstride + q * (MatBr / 4); - coopMatStore(SfMat[q], sfsh, coord, sfshstride, gl_CooperativeMatrixLayoutRowMajor); + coopMatStore(SfMat0, sfsh, gl_SubgroupID * MatBc * sfshstride, sfshstride, gl_CooperativeMatrixLayoutRowMajor); + if (q_tiles > 1) { + coopMatStore(SfMat1, sfsh, gl_SubgroupID * MatBc * sfshstride + MatBr / 4, sfshstride, gl_CooperativeMatrixLayoutRowMajor); } barrier(); @@ -516,10 +519,8 @@ void main() { [[unroll]] for (uint32_t hsv_tile = 0; hsv_tile < num_hsv_tiles; ++hsv_tile) { const uint hsv_offset = (hsv_tile * row_split + gl_SubgroupID) * 16; - coopmat PVMat[q_tiles]; - [[unroll]] for (uint32_t q = 0; q < q_tiles; ++q) { - PVMat[q] = coopmat(0); - } + coopmat PVMat0 = coopmat(0); + coopmat PVMat1 = coopmat(0); // Preload V tiles for [Bc, 16 * num subgroups] const uint v_rows = Bc; @@ -584,18 +585,19 @@ void main() { coopMatLoad(QMat, kvsh, v_tile_offset, kvsh_stride, gl_CooperativeMatrixLayoutRowMajor); } - [[unroll]] for (uint32_t q = 0; q < q_tiles; ++q) { - coopMatLoad(KMat, Psh, bc_chunk * MatBc * psh_stride + q * (MatBc / 4), psh_stride, gl_CooperativeMatrixLayoutColumnMajor); - PVMat[q] = coopMatMulAdd(KMat, QMat, PVMat[q]); + coopMatLoad(KMat, Psh, bc_chunk * MatBc * psh_stride, psh_stride, gl_CooperativeMatrixLayoutColumnMajor); + PVMat0 = coopMatMulAdd(KMat, QMat, PVMat0); + if (q_tiles > 1) { + coopMatLoad(KMat, Psh, bc_chunk * MatBc * psh_stride + MatBc / 4, psh_stride, gl_CooperativeMatrixLayoutColumnMajor); + PVMat1 = coopMatMulAdd(KMat, QMat, PVMat1); } } - [[unroll]] for (uint32_t q = 0; q < q_tiles; ++q) { - if (PV_IN_SFSH) { - coopMatStore(PVMat[q], sfsh, (o_offset + q * MatBc * osh_stride) / pv_per_acc, osh_stride / pv_per_acc, gl_CooperativeMatrixLayoutRowMajor); - } else { - coopMatStore(PVMat[q], pvsh, o_offset + q * MatBc * osh_stride, osh_stride, gl_CooperativeMatrixLayoutRowMajor); - } + if (q_tiles > 1) { + coopMatStore(PVMat0, sfsh, o_offset / pv_per_acc, osh_stride / pv_per_acc, gl_CooperativeMatrixLayoutRowMajor); + coopMatStore(PVMat1, sfsh, (o_offset + MatBc * osh_stride) / pv_per_acc, osh_stride / pv_per_acc, gl_CooperativeMatrixLayoutRowMajor); + } else { + coopMatStore(PVMat0, pvsh, o_offset, osh_stride, gl_CooperativeMatrixLayoutRowMajor); } } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp index 0e384330b9b9..ad2ced78aa39 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp @@ -15,10 +15,19 @@ layout(constant_id = 0) const uint S_V = 128; layout(constant_id = 1) const uint KDA = 0; layout(constant_id = 2) const uint SUBGROUP_SIZE = 32; layout(constant_id = 3) const uint LANES_PER_COLUMN = 32; +layout(constant_id = 4) const bool PACKED_ROWS = false; const uint COLS_PER_WG = SUBGROUP_SIZE / LANES_PER_COLUMN; const uint ROWS_PER_LANE = S_V / LANES_PER_COLUMN; +uint row_index(uint r, uint lane) { + // Keep four adjacent rows together in each lane. + if (PACKED_ROWS) { + return (r / 4u * LANES_PER_COLUMN + lane) * 4u + r % 4u; + } + return r * LANES_PER_COLUMN + lane; +} + layout(local_size_x_id = 2, local_size_y = 1, local_size_z = 1) in; layout(push_constant) uniform Parameters { @@ -27,6 +36,7 @@ layout(push_constant) uniform Parameters { uint n_seqs; uint s_off; uint sq1, sq2, sq3; + uint sk1, sk2, sk3; uint sv1, sv2, sv3; uint sb1, sb2, sb3; uint neq1, rq3; @@ -110,7 +120,7 @@ void main() { FLOAT_TYPE s_shard[ROWS_PER_LANE]; [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - s_shard[r] = FLOAT_TYPE(data_state[state_in_base + col * S_V + r * LANES_PER_COLUMN + lane]); + s_shard[r] = FLOAT_TYPE(data_state[state_in_base + col * S_V + row_index(r, lane)]); } // snapshot slot mapping: slot 0 = most recent state, slot s = s tokens back. @@ -120,7 +130,7 @@ void main() { for (uint t = 0; t < n_tokens; t++) { const uint q_off = iq3 * sq3 + t * sq2 + iq1 * sq1; - const uint k_off = q_off; + const uint k_off = iq3 * sk3 + t * sk2 + iq1 * sk1; const uint v_off = seq_id * sv3 + t * sv2 + head_id * sv1; const uint gb_off = seq_id * sb3 + t * sb2 + head_id * sb1; const FLOAT_TYPE beta_val = FLOAT_TYPE(data_beta[gb_off]); @@ -128,7 +138,7 @@ void main() { FLOAT_TYPE k_reg[ROWS_PER_LANE]; FLOAT_TYPE q_reg[ROWS_PER_LANE]; [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - const uint i = r * LANES_PER_COLUMN + lane; + const uint i = row_index(r, lane); k_reg[r] = FLOAT_TYPE(data_k[k_off + i]); q_reg[r] = FLOAT_TYPE(data_q[q_off + i]); } @@ -142,7 +152,7 @@ void main() { } else { const uint g_base = gb_off * S_V; [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - const uint i = r * LANES_PER_COLUMN + lane; + const uint i = row_index(r, lane); g_exp[r] = exp(FLOAT_TYPE(data_g[g_base + i])); } } @@ -175,7 +185,7 @@ void main() { if (target_slot >= 0 && target_slot < int(K)) { const uint slot_base = s_off + uint(target_slot) * state_size_per_snap + state_out_base; [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - data_dst[slot_base + col * S_V + r * LANES_PER_COLUMN + lane] = s_shard[r]; + data_dst[slot_base + col * S_V + row_index(r, lane)] = s_shard[r]; } } } @@ -183,7 +193,7 @@ void main() { if (K == 1u) { [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { - data_dst[s_off + state_out_base + col * S_V + r * LANES_PER_COLUMN + lane] = s_shard[r]; + data_dst[s_off + state_out_base + col * S_V + row_index(r, lane)] = s_shard[r]; } } } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net_cm.comp b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net_cm.comp new file mode 100644 index 000000000000..c5b4e4084faf --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net_cm.comp @@ -0,0 +1,437 @@ +#version 450 + +#extension GL_EXT_control_flow_attributes : enable +#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require +#extension GL_EXT_shader_explicit_arithmetic_types_int32 : require +#extension GL_EXT_bfloat16 : require +#extension GL_KHR_memory_scope_semantics : enable +#extension GL_KHR_shader_subgroup_basic : enable +#extension GL_KHR_shader_subgroup_arithmetic : enable +#extension GL_KHR_shader_subgroup_shuffle : enable +#extension GL_KHR_cooperative_matrix : enable +#extension GL_EXT_cooperative_matrix_maintenance1 : enable + +// Chunked gated-delta-net prefill (non-KDA, S_v == D == 128, K == 1), port of CUDA PR 29353. +// State in register tiles, mirrored ([D x V]) for the projections. +// bf16 hi/lo 3x products for ~fp32 accuracy. +#define OPD bfloat16_t + +#define C 16 // chunk size (tokens per step) +#define D 128 // head dim / value dim +#define TM 16 // tile rows +#define TN 16 // tile cols (bf16 cm has only m16n16k16; n8 would pad) +#ifndef V +#define V 64 // value columns per workgroup block (V=128 = whole head) +#endif +#define NSUB 16 // subgroups per workgroup +layout(constant_id = 0) const uint WGS = NSUB * 32; // NSUB * subgroup size +#define KT 16 // K-tile width for deep (K=D) matmuls (bf16 cm: m16n16k16 only) +#define PAD 8 // shared padding to break COL-load bank conflicts (keep LDP*2 a multiple of 16B) +#define LDP (D + PAD) + +// GMEM_MIRROR: state mirror in a gmem scratch buffer (too big for shared) + +#define STATE_TILES ((D / TM) * (V / TN)) +#define PER_WARP (STATE_TILES / NSUB) +#define VT (V / TN) // value tiles +#define CT (C / TN) // C-column tiles (gram/pmat halves) +const uint NQK = C * D / WGS; + +#define TILE_R(ti) (((ti) / VT) * TM) +#define TILE_C(ti) (((ti) % VT) * TN) + +layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in; + +layout(push_constant) uniform Parameters { + uint H; + uint n_tokens; + uint n_seqs; + uint s_off; + uint sq1, sq2, sq3; + uint sk1, sk2, sk3; + uint sv1, sv2, sv3; + uint sb1, sb2, sb3; + uint neq1, rq3; + float scale; + uint K; +} p; + +layout(binding = 0) readonly buffer QBuf { float data_q[]; }; +layout(binding = 1) readonly buffer KBuf { float data_k[]; }; +layout(binding = 2) readonly buffer VBuf { float data_v[]; }; +layout(binding = 3) readonly buffer GBuf { float data_g[]; }; +layout(binding = 4) readonly buffer BetaBuf { float data_beta[]; }; +layout(binding = 5) readonly buffer StateBuf { float data_state[]; }; +layout(binding = 6) buffer DstBuf { float data_dst[]; }; +#ifdef GMEM_MIRROR +layout(binding = 7) coherent buffer MirrorBuf { OPD data_mirror[]; }; +#endif + +shared OPD sh_qh[C * LDP], sh_ql[C * LDP]; // q*scale hi/lo (D padded) +shared OPD sh_kh[C * LDP], sh_kl[C * LDP]; // k hi/lo (D padded) +#ifndef GMEM_MIRROR +shared OPD sh_sh[LDP * V], sh_sl[LDP * V]; // state mirror [D x V] column-major (D padded) +#endif +shared OPD sh_dh[C * V], sh_dl[C * V]; // delta (pre-inv) / delta2 [C x V] row-major +shared OPD sh_soh[C * V], sh_sol[C * V]; // solved [C x V] row-major +shared OPD sh_ph[C * C], sh_pl[C * C]; // decayed P +shared OPD sh_ih[C * C], sh_il[C * C]; // (I + L)^-1 +shared float sh_lower[C * C]; // strictly-lower decayed L + +shared float sh_prefix[C], sh_beta[C], sh_ep[C], sh_carry[C]; + +#define SG gl_ScopeSubgroup +#define MUA gl_MatrixUseA +#define MUB gl_MatrixUseB +#define MACC gl_MatrixUseAccumulator +#define ROW gl_CooperativeMatrixLayoutRowMajor +#define COL gl_CooperativeMatrixLayoutColumnMajor + + +// 3x bf16 product accumulated into acc (hi/lo split for ~fp32 accuracy). +#define PRODUCT(acc, ah, al, bh, bl) \ + acc = coopMatMulAdd(al, bh, acc); \ + acc = coopMatMulAdd(ah, bl, acc); \ + acc = coopMatMulAdd(ah, bh, acc); + +void split(const float x, out OPD h, out OPD l) { + h = OPD(x); + l = OPD(x - float(h)); +} + +#ifdef BF16ACC +// split through a bf16 accumulator +#define SPLIT_STORE(m, arr_h, off_h, arr_l, off_l, ld, layout) { \ + const coopmat h_ = coopmat(m); \ + const coopmat l_ = coopmat(m - coopmat(h_)); \ + coopMatStore(h_, arr_h, off_h, ld, layout); \ + coopMatStore(l_, arr_l, off_l, ld, layout); \ +} + +#ifdef GMEM_MIRROR +#define STORE_MIRROR(m, off) SPLIT_STORE(m, data_mirror, mir_h + off, data_mirror, mir_l + off, LDP, COL) +#else +#define STORE_MIRROR(m, off) SPLIT_STORE(m, sh_sh, off, sh_sl, off, LDP, COL) +#endif +#define STORE_DELTA(m, off) SPLIT_STORE(m, sh_dh, off, sh_dl, off, V, ROW) +#define STORE_SOLVED(m, off) SPLIT_STORE(m, sh_soh, off, sh_sol, off, V, ROW) +#else +// split per element +#ifdef GMEM_MIRROR +float SplitColS(const in uint32_t r, const in uint32_t c, const in float elem, const in uint32_t off) { + const uint idx = off + c * LDP + r; + split(elem, data_mirror[idx], data_mirror[idx + LDP * V]); + return elem; +} +#define STORE_MIRROR(m, off) coopMatPerElementEXT(m, m, SplitColS, mir_h + off) +#else +float SplitColS(const in uint32_t r, const in uint32_t c, const in float elem, const in uint32_t off) { + const uint idx = off + c * LDP + r; + split(elem, sh_sh[idx], sh_sl[idx]); + return elem; +} +#define STORE_MIRROR(m, off) coopMatPerElementEXT(m, m, SplitColS, off) +#endif + +float SplitRowD(const in uint32_t r, const in uint32_t c, const in float elem, const in uint32_t off) { + const uint idx = off + r * V + c; + split(elem, sh_dh[idx], sh_dl[idx]); + return elem; +} + +float SplitRowSO(const in uint32_t r, const in uint32_t c, const in float elem, const in uint32_t off) { + const uint idx = off + r * V + c; + split(elem, sh_soh[idx], sh_sol[idx]); + return elem; +} + +#define STORE_DELTA(m, off) coopMatPerElementEXT(m, m, SplitRowD, off) +#define STORE_SOLVED(m, off) coopMatPerElementEXT(m, m, SplitRowSO, off) +#endif + +#ifdef GMEM_MIRROR +#define LOAD_S(h, l, off) \ + coopMatLoad(h, data_mirror, mir_h + off, LDP, COL); \ + coopMatLoad(l, data_mirror, mir_l + off, LDP, COL); +// mirror is workgroup-private +#define MIRROR_BARRIER() controlBarrier(gl_ScopeWorkgroup, gl_ScopeWorkgroup, \ + gl_StorageSemanticsBuffer | gl_StorageSemanticsShared, \ + gl_SemanticsAcquireRelease) +#else +#define LOAD_S(h, l, off) \ + coopMatLoad(h, sh_sh, off, LDP, COL); \ + coopMatLoad(l, sh_sl, off, LDP, COL); +#define MIRROR_BARRIER() barrier() +#endif + +float StoreOut(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t out_base, const in uint32_t valid) { + if (r < valid) { + data_dst[out_base + r * (D * p.H) + c] = elem; + } + return elem; +} + +float StoreState(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t base) { + data_dst[base + c * D + r] = elem; + return elem; +} + +float LoadV(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t v_base, const in uint32_t sv2, const in uint32_t valid) { + return r < valid ? data_v[v_base + r * sv2 + c] : 0.0; +} + +// sh_beta[r] == 0 for r >= valid +float ComputeDeltaV(const in uint32_t r, const in uint32_t c, const in float ks, + const in float vv) { + return sh_beta[r] * (vv - sh_ep[r] * ks); +} + +float ApplyExpPrefix(const in uint32_t r, const in uint32_t c, const in float qs) { + return sh_ep[r] * qs; +} + +float StoreLower(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t c_o) { + const uint cc = c_o + c; + if (cc < r) { + sh_lower[r * C + cc] = elem * exp(sh_prefix[r] - sh_prefix[cc]) * sh_beta[r]; + } + return elem; +} + +float StorePmat(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t c_o) { + const uint cc = c_o + c; + float v = 0.0; + if (cc <= r) { + v = elem * exp(sh_prefix[r] - sh_prefix[cc]); + } + split(v, sh_ph[r * C + cc], sh_pl[r * C + cc]); + return elem; +} + +void prefetch(const uint t0, const uint iq1, const uint iq3, const uint seq_id, const uint head_id, + out float q[NQK], out float k[NQK], out float g, out float b) { + const uint n = t0 < p.n_tokens ? min(C, p.n_tokens - t0) : 0u; + [[unroll]] for (uint j = 0; j < NQK; j++) { + const uint i = gl_LocalInvocationID.x + j * WGS; + const uint t = i / D; + q[j] = 0.0; + k[j] = 0.0; + if (t < n) { + const uint q_off = iq3 * p.sq3 + (t0 + t) * p.sq2 + iq1 * p.sq1 + i % D; + const uint k_off = iq3 * p.sk3 + (t0 + t) * p.sk2 + iq1 * p.sk1 + i % D; + q[j] = data_q[q_off] * p.scale; + k[j] = data_k[k_off]; + } + } + g = 0.0; + b = 0.0; + const uint t = gl_SubgroupInvocationID; + if (gl_SubgroupID == 0 && t < n) { + const uint gb = seq_id * p.sb3 + (t0 + t) * p.sb2 + head_id * p.sb1; + g = data_g[gb]; + b = data_beta[gb]; + } +} + +// sg0: gram K@K^T -> L, sg1: pmat Q@K^T -> P +void gram_pmat(const uint sg) { + const bool gram = sg < CT; + const uint c_o = (sg % CT) * TN; + coopmat x = coopmat(0); + [[unroll]] for (uint kk = 0; kk < D; kk += KT) { + coopmat ah, al; + if (gram) { + coopMatLoad(ah, sh_kh, kk, LDP, ROW); + coopMatLoad(al, sh_kl, kk, LDP, ROW); + } else { + coopMatLoad(ah, sh_qh, kk, LDP, ROW); + coopMatLoad(al, sh_ql, kk, LDP, ROW); + } + coopmat bh, bl; + coopMatLoad(bh, sh_kh, c_o * LDP + kk, LDP, COL); + coopMatLoad(bl, sh_kl, c_o * LDP + kk, LDP, COL); + PRODUCT(x, ah, al, bh, bl); + } + if (gram) { + coopMatPerElementEXT(x, x, StoreLower, c_o); + } else { + coopMatPerElementEXT(x, x, StorePmat, c_o); + } +} + +// (I + L)^-1, forward substitution: subgroup per row, lane per column +void invert(const uint sg) { + const uint col = gl_SubgroupInvocationID; + [[unroll]] for (uint row = sg; row < C; row += NSUB) { + float x = col < C ? (col == row ? 1.0 : (col < row ? -sh_lower[row * C + col] : 0.0)) : 0.0; + for (int pivot = int(row) - 1; pivot > 0; pivot--) { + const float xp = subgroupShuffle(x, uint(pivot)); + if (col < uint(pivot)) { + x -= xp * sh_lower[uint(pivot) * C + col]; + } + } + if (col < C) { + split(x, sh_ih[row * C + col], sh_il[row * C + col]); + } + } +} + +float carry_decay(const uint valid) { + const float plast = sh_prefix[valid - 1]; + if (gl_LocalInvocationID.x < C) { + sh_carry[gl_LocalInvocationID.x] = exp(plast - sh_prefix[gl_LocalInvocationID.x]); + } + return exp(plast); +} + +void main() { + const uint head_id = gl_WorkGroupID.z; + const uint seq_id = gl_WorkGroupID.y; + const uint sg = gl_SubgroupID; + const uint tid = gl_LocalInvocationID.x; + const uint v0 = gl_WorkGroupID.x * V; + + const uint iq1 = head_id % p.neq1; + const uint iq3 = seq_id / p.rq3; + + const uint state_base = (seq_id * p.H + head_id) * (D * D); + +#ifdef GMEM_MIRROR + const uint mir_stride = uint(LDP) * V; + const uint mir_block = (head_id * p.n_seqs + seq_id) * gl_NumWorkGroups.x + gl_WorkGroupID.x; + const uint mir_h = mir_block * mir_stride * 2u; + const uint mir_l = mir_h + mir_stride; +#endif + + coopmat state[PER_WARP]; + [[unroll]] for (uint j = 0; j < PER_WARP; j++) { + const uint ti = sg + j * NSUB; + coopMatLoad(state[j], data_state, state_base + (v0 + TILE_C(ti)) * D + TILE_R(ti), D, COL); + } + + float qreg[NQK], kreg[NQK], greg, breg; + prefetch(0u, iq1, iq3, seq_id, head_id, qreg, kreg, greg, breg); + + for (uint t0 = 0; t0 < p.n_tokens; t0 += C) { + const uint valid = min(C, p.n_tokens - t0); + + barrier(); + if (sg == 0) { + const uint t = gl_SubgroupInvocationID; + const float acc = subgroupInclusiveAdd(greg); + if (t < C) { + sh_prefix[t] = acc; + sh_ep[t] = exp(acc); + sh_beta[t] = breg; + } + } + [[unroll]] for (uint j = 0; j < NQK; j++) { + const uint i = tid + j * WGS; + const uint pi = (i / D) * LDP + (i % D); + split(qreg[j], sh_qh[pi], sh_ql[pi]); + split(kreg[j], sh_kh[pi], sh_kl[pi]); + } + + [[unroll]] for (uint j = 0; j < PER_WARP; j++) { + const uint ti = sg + j * NSUB; + STORE_MIRROR(state[j], TILE_C(ti) * LDP + TILE_R(ti)); + } + MIRROR_BARRIER(); + + prefetch(t0 + C, iq1, iq3, seq_id, head_id, qreg, kreg, greg, breg); + const float cdecay = carry_decay(valid); + + // qs -> base_r and ks -> delta on sg2..2+VT-1 + coopmat base_r = coopmat(0); + if (sg < 2 * CT) { + gram_pmat(sg); + } else if (sg - 2 * CT < VT) { + const uint c_o = (sg - 2 * CT) * TN; + const uint v_base = seq_id * p.sv3 + head_id * p.sv1 + v0 + c_o + t0 * p.sv2; + coopmat vmat = coopmat(0); + coopMatPerElementEXT(vmat, vmat, LoadV, v_base, p.sv2, valid); + coopmat qs = coopmat(0); + coopmat ks = coopmat(0); + [[unroll]] for (uint kk = 0; kk < D; kk += KT) { + coopmat qh, ql, kh, kl; + coopMatLoad(qh, sh_qh, kk, LDP, ROW); + coopMatLoad(ql, sh_ql, kk, LDP, ROW); + coopMatLoad(kh, sh_kh, kk, LDP, ROW); + coopMatLoad(kl, sh_kl, kk, LDP, ROW); + coopmat sbh, sbl; + LOAD_S(sbh, sbl, c_o * LDP + kk); + PRODUCT(qs, qh, ql, sbh, sbl); + PRODUCT(ks, kh, kl, sbh, sbl); + } + coopMatPerElementEXT(base_r, qs, ApplyExpPrefix); + coopmat delta; + coopMatPerElementEXT(delta, ks, ComputeDeltaV, vmat); + STORE_DELTA(delta, c_o); + } + barrier(); + + invert(sg); + barrier(); + + // solved = (I+L)^-1 @ delta (sg0..VT-1) + if (sg < VT) { + const uint c_o = sg * TN; + coopmat solved = coopmat(0); + coopmat ih, il; + coopMatLoad(ih, sh_ih, 0, C, ROW); + coopMatLoad(il, sh_il, 0, C, ROW); + coopmat dh, dl; + coopMatLoad(dh, sh_dh, c_o, V, ROW); + coopMatLoad(dl, sh_dl, c_o, V, ROW); + PRODUCT(solved, ih, il, dh, dl); + STORE_SOLVED(solved, c_o); + } + barrier(); + + // out = base + P@solved (sg2..2+VT-1) + if (sg >= 2 * CT && sg - 2 * CT < VT) { + const uint c_o = (sg - 2 * CT) * TN; + coopmat O = base_r; + coopmat ph, pl; + coopMatLoad(ph, sh_ph, 0, C, ROW); + coopMatLoad(pl, sh_pl, 0, C, ROW); + coopmat svh, svl; + coopMatLoad(svh, sh_soh, c_o, V, ROW); + coopMatLoad(svl, sh_sol, c_o, V, ROW); + PRODUCT(O, ph, pl, svh, svl); + const uint out_base = (seq_id * p.n_tokens * p.H + head_id) * D + v0 + c_o + t0 * (D * p.H); + coopMatPerElementEXT(O, O, StoreOut, out_base, valid); + } + // delta2 = solved * carry -> sh_dh/dl (all threads) + for (uint i = tid; i < C * V; i += WGS) { + const float sv = float(sh_soh[i]) + float(sh_sol[i]); + split(sv * sh_carry[i / V], sh_dh[i], sh_dl[i]); + } + barrier(); + + // state = cdecay*state + K^T @ delta2 + [[unroll]] for (uint j = 0; j < PER_WARP; j++) { + const uint ti = sg + j * NSUB; + coopmat kth, ktl; + coopMatLoad(kth, sh_kh, TILE_R(ti), LDP, COL); + coopMatLoad(ktl, sh_kl, TILE_R(ti), LDP, COL); + coopmat dh, dl; + coopMatLoad(dh, sh_dh, TILE_C(ti), V, ROW); + coopMatLoad(dl, sh_dl, TILE_C(ti), V, ROW); + state[j] = state[j] * cdecay; + PRODUCT(state[j], kth, ktl, dh, dl); + } + // no end-of-chunk barrier: covered by the chunk-top barrier + } + + [[unroll]] for (uint j = 0; j < PER_WARP; j++) { + const uint ti = sg + j * NSUB; + coopMatPerElementEXT(state[j], state[j], StoreState, + p.s_off + state_base + (v0 + TILE_C(ti)) * D + TILE_R(ti)); + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net_cm2.comp b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net_cm2.comp new file mode 100644 index 000000000000..270ef35db3a5 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net_cm2.comp @@ -0,0 +1,320 @@ +#version 450 + +#extension GL_EXT_control_flow_attributes : require +#extension GL_EXT_shader_explicit_arithmetic_types_int32 : require +#extension GL_EXT_bfloat16 : require +#extension GL_KHR_memory_scope_semantics : require +#extension GL_KHR_shader_subgroup_basic : require +#extension GL_KHR_shader_subgroup_arithmetic : require +#extension GL_KHR_shader_subgroup_shuffle : require +#extension GL_KHR_shader_subgroup_shuffle_relative : require +#extension GL_KHR_cooperative_matrix : require +#extension GL_NV_cooperative_matrix2 : require + +// Chunked gated-delta-net prefill (non-KDA, S_v == D == 128, K == 1). +// BF16 hi/lo products use FP32 accumulators. +#define OPD bfloat16_t + +#define C 16 // chunk size (tokens per step) +#define D 128 // head dim / value dim +#define V 32 // value columns per workgroup block +#define WGS 128 +#define NSUB (WGS / 32) +#define KT 32 // K-tile width for deep (K=D) matmuls +#define PAD 8 +#define LDP (D + PAD) +#define LDV (V + PAD) +#define KQ_ROWS (2 * C) +#define NQK (C * D / WGS) + +layout(local_size_x = WGS, local_size_y = 1, local_size_z = 1) in; + +layout(push_constant) uniform Parameters { + uint H; + uint n_tokens; + uint n_seqs; + uint s_off; + uint sq1, sq2, sq3; + uint sk1, sk2, sk3; + uint sv1, sv2, sv3; + uint sb1, sb2, sb3; + uint neq1, rq3; + float scale; + uint K; +} p; + +layout(binding = 0) readonly buffer QBuf { float data_q[]; }; +layout(binding = 1) readonly buffer KBuf { float data_k[]; }; +layout(binding = 2) readonly buffer VBuf { float data_v[]; }; +layout(binding = 3) readonly buffer GBuf { float data_g[]; }; +layout(binding = 4) readonly buffer BetaBuf { float data_beta[]; }; +layout(binding = 5) readonly buffer StateBuf { float data_state[]; }; +layout(binding = 6) buffer DstBuf { float data_dst[]; }; + +// K and scaled Q occupy the two row blocks of one 32-row operand. +shared OPD sh_kqh[2 * C * LDP], sh_kql[2 * C * LDP]; +shared OPD sh_sh[V * LDP], sh_sl[V * LDP]; // state mirror [V x D] row-major (D padded) +shared OPD sh_ph[C * C], sh_pl[C * C]; +shared OPD sh_ih[C * C], sh_il[C * C]; +shared OPD sh_dh[C * LDV], sh_dl[C * LDV]; // delta / solved [C x V] row-major (V padded) +shared float sh_lower[C * (C - 1) / 2]; // packed strictly-lower Gram entries +shared float sh_prefix[C], sh_ep[C], sh_beta[C], sh_carry[C]; + +#define WG gl_ScopeWorkgroup +#define MUA gl_MatrixUseA +#define MUB gl_MatrixUseB +#define MACC gl_MatrixUseAccumulator +#define ROW gl_CooperativeMatrixLayoutRowMajor +#define COL gl_CooperativeMatrixLayoutColumnMajor + +#define PRODUCT(acc, ah, al, bh, bl) \ + acc = coopMatMulAdd(ah, bh, acc); \ + acc = coopMatMulAdd(al, bh, acc); \ + acc = coopMatMulAdd(ah, bl, acc); + +void split(const float x, out OPD h, out OPD l) { + h = OPD(x); + l = OPD(x - float(h)); +} + +float StoreGramPmat(const in uint32_t r, const in uint32_t c, const in float elem) { + if (r < C) { + if (c < r) { + sh_lower[r * (r - 1) / 2 + c] = elem * exp(sh_prefix[r] - sh_prefix[c]) * sh_beta[r]; + } + } else { + const uint row = r - C; + const float y = c <= row ? elem * exp(sh_prefix[row] - sh_prefix[c]) : 0.0; + split(y, sh_ph[row * C + c], sh_pl[row * C + c]); + } + return elem; +} + +float SplitRowS(const in uint32_t r, const in uint32_t c, const in float elem) { + const uint i = r * LDP + c; + split(elem, sh_sh[i], sh_sl[i]); + return elem; +} + +float ApplyExpPrefix(const in uint32_t r, const in uint32_t c, const in float qs) { + return sh_ep[c] * qs; +} + +float LoadV(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t v_base, const in uint32_t sv2, const in uint32_t valid) { + return c < valid ? data_v[v_base + c * sv2 + r] : 0.0; +} + +float StoreDeltaV(const in uint32_t r, const in uint32_t c, const in float ks, const in float vv) { + const float x = sh_beta[c] * (vv - sh_ep[c] * ks); + const uint i = c * LDV + r; + split(x, sh_dh[i], sh_dl[i]); + return ks; +} + +float StoreSolved(const in uint32_t r, const in uint32_t c, const in float elem) { + const uint i = c * LDV + r; + split(elem, sh_dh[i], sh_dl[i]); + // The state mirror is no longer needed after KS/QS. + const uint j = r * LDP + c; + split(sh_carry[c] * elem, sh_sh[j], sh_sl[j]); + return elem; +} + +float StoreOut(const in uint32_t r, const in uint32_t c, const in float elem, + const in uint32_t out_base, const in uint32_t valid) { + if (c < valid) { + data_dst[out_base + c * (p.H * D) + r] = elem; + } + return elem; +} + +void prefetch(const uint t0, const uint q_base, const uint k_base, const uint gb_base, + out float q[NQK], out float k[NQK], out float g, out float b) { + const uint valid = t0 < p.n_tokens ? min(C, p.n_tokens - t0) : 0u; + const uint r = gl_SubgroupInvocationID; + g = 0.0; + b = 0.0; + if (gl_SubgroupID == 0 && r < valid) { + const uint off = gb_base + (t0 + r) * p.sb2; + g = data_g[off]; + b = data_beta[off]; + } + [[unroll]] for (uint j = 0; j < NQK; ++j) { + const uint i = gl_LocalInvocationID.x + j * WGS; + const uint token = i / D; + q[j] = 0.0; + k[j] = 0.0; + if (token < valid) { + const uint q_off = q_base + (t0 + token) * p.sq2 + i % D; + const uint k_off = k_base + (t0 + token) * p.sk2 + i % D; + q[j] = data_q[q_off]; + k[j] = data_k[k_off]; + } + } +} + +void stage_inputs(const in float q[NQK], const in float k[NQK]) { + [[unroll]] for (uint j = 0; j < NQK; ++j) { + const uint i = gl_LocalInvocationID.x + j * WGS; + const uint token = i / D; + const uint key = i % D; + const uint ki = token * LDP + key; + const uint qi = (C + token) * LDP + key; + split(k[j], sh_kqh[ki], sh_kql[ki]); + split(p.scale * q[j], sh_kqh[qi], sh_kql[qi]); + } +} + +// [K; Q] * K^T computes Gram and P in one 32-row matrix. +void gram_pmat() { + coopmat x = coopmat(0.0); + [[unroll]] for (uint kk = 0; kk < D; kk += KT) { + coopmat ah, al; + coopmat bh, bl; + coopMatLoad(ah, sh_kqh, kk, LDP, ROW); + coopMatLoad(al, sh_kql, kk, LDP, ROW); + coopMatLoad(bh, sh_kqh, kk, LDP, COL); + coopMatLoad(bl, sh_kql, kk, LDP, COL); + PRODUCT(x, ah, al, bh, bl); + } + coopMatPerElementNV(x, x, StoreGramPmat); +} + +void invert() { + const uint col = gl_SubgroupInvocationID % C; + // Each half-subgroup covers all columns of its assigned rows. + const uint section = gl_SubgroupInvocationID / C; + const uint row_base = (gl_SubgroupID * 2u + section) * (C / (2 * NSUB)); + // Keep the diagonal zero so pivots at or above the row do nothing. + float x[C / (2 * NSUB)]; + [[unroll]] for (uint j = 0; j < C / (2 * NSUB); ++j) { + const uint row = row_base + j; + x[j] = col < row ? -sh_lower[row * (row - 1) / 2 + col] : 0.0; + } + [[dont_unroll]] for (int pivot = C - 2; pivot > 0; --pivot) { + const float lower = col < uint(pivot) ? sh_lower[uint(pivot) * uint(pivot - 1) / 2 + col] : 0.0; + [[unroll]] for (uint j = 0; j < C / (2 * NSUB); ++j) { + const float xp = subgroupShuffle(x[j], uint(pivot) + section * C); + x[j] -= xp * lower; + } + } + [[unroll]] for (uint j = 0; j < C / (2 * NSUB); ++j) { + const uint row = row_base + j; + split(col == row ? 1.0 : x[j], sh_ih[row * C + col], sh_il[row * C + col]); + } +} + +void main() { + const uint head_id = gl_WorkGroupID.z; + const uint seq_id = gl_WorkGroupID.y; + const uint v0 = gl_WorkGroupID.x * V; + const uint iq1 = head_id % p.neq1; + const uint iq3 = seq_id / p.rq3; + const uint q_base = iq3 * p.sq3 + iq1 * p.sq1; + const uint k_base = iq3 * p.sk3 + iq1 * p.sk1; + const uint v_base = seq_id * p.sv3 + head_id * p.sv1 + v0; + const uint gb_base = seq_id * p.sb3 + head_id * p.sb1; + const uint state_base = (seq_id * p.H + head_id) * (D * D) + v0 * D; + const uint out_base = (seq_id * p.n_tokens * p.H + head_id) * D + v0; + + // Transposing the state-side products gives them V=32 rows with C=16 columns. + coopmat state; + coopMatLoad(state, data_state, state_base, D, ROW); + + float qreg[NQK], kreg[NQK], greg, breg; + prefetch(0u, q_base, k_base, gb_base, qreg, kreg, greg, breg); + + [[dont_unroll]] for (uint t0 = 0; t0 < p.n_tokens; t0 += C) { + const uint valid = min(C, p.n_tokens - t0); + barrier(); + if (gl_SubgroupID == 0) { + const uint r = gl_SubgroupInvocationID; + // shuffle scan instead of subgroupInclusiveAdd: works around an NVIDIA r620 shader compiler crash + float sum = greg; + [[unroll]] for (uint d = 1; d < C; d <<= 1) { + const float t = subgroupShuffleUp(sum, d); + if (r >= d) { + sum += t; + } + } + const float last = subgroupShuffle(sum, valid - 1); + if (r < C) { + sh_prefix[r] = sum; + sh_ep[r] = exp(sum); + sh_beta[r] = breg; + sh_carry[r] = exp(last - sum); + } + } + stage_inputs(qreg, kreg); + coopmat vmat; + if (valid == C && (v_base % 4u) == 0 && (p.sv2 % 4u) == 0) { + coopMatLoad(vmat, data_v, v_base + t0 * p.sv2, p.sv2, COL); + } else { + vmat = coopmat(0.0); + coopMatPerElementNV(vmat, vmat, LoadV, v_base + t0 * p.sv2, p.sv2, valid); + } + barrier(); + // Current inputs are in shared memory; keep the next chunk in registers. + prefetch(t0 + C, q_base, k_base, gb_base, qreg, kreg, greg, breg); + + gram_pmat(); + barrier(); + invert(); + coopMatPerElementNV(state, state, SplitRowS); + barrier(); + + coopmat ks = coopmat(0.0), base_r = coopmat(0.0); + [[unroll]] for (uint kk = 0; kk < D; kk += KT) { + coopmat ah, al; + coopmat kh, kl, qh, ql; + coopMatLoad(ah, sh_sh, kk, LDP, ROW); + coopMatLoad(al, sh_sl, kk, LDP, ROW); + coopMatLoad(kh, sh_kqh, kk, LDP, COL); + coopMatLoad(kl, sh_kql, kk, LDP, COL); + coopMatLoad(qh, sh_kqh, C * LDP + kk, LDP, COL); + coopMatLoad(ql, sh_kql, C * LDP + kk, LDP, COL); + PRODUCT(ks, ah, al, kh, kl); + PRODUCT(base_r, ah, al, qh, ql); + } + coopMatPerElementNV(base_r, base_r, ApplyExpPrefix); + coopMatPerElementNV(ks, ks, StoreDeltaV, vmat); + barrier(); + + coopmat solved = coopmat(0.0); + { + coopmat rh, rl; + coopmat ih, il; + coopMatLoad(rh, sh_dh, 0, LDV, COL); + coopMatLoad(rl, sh_dl, 0, LDV, COL); + coopMatLoad(ih, sh_ih, 0, C, COL); + coopMatLoad(il, sh_il, 0, C, COL); + PRODUCT(solved, rh, rl, ih, il); + } + barrier(); + coopMatPerElementNV(solved, solved, StoreSolved); + barrier(); + + { + coopmat xh, xl; + coopmat ph, pl; + coopMatLoad(xh, sh_dh, 0, LDV, COL); + coopMatLoad(xl, sh_dl, 0, LDV, COL); + coopMatLoad(ph, sh_ph, 0, C, COL); + coopMatLoad(pl, sh_pl, 0, C, COL); + PRODUCT(base_r, xh, xl, ph, pl); + } + coopMatPerElementNV(base_r, base_r, StoreOut, out_base + t0 * (p.H * D), valid); + + coopmat xh, xl; + coopmat kh, kl; + coopMatLoad(xh, sh_sh, 0, LDP, ROW); + coopMatLoad(xl, sh_sl, 0, LDP, ROW); + coopMatLoad(kh, sh_kqh, 0, LDP, ROW); + coopMatLoad(kl, sh_kql, 0, LDP, ROW); + state *= sh_ep[valid - 1]; + PRODUCT(state, xh, xl, kh, kl); + } + + coopMatStore(state, data_dst, p.s_off + state_base, D, ROW); +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm.comp b/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm.comp index b9f0a1841b51..b73fdeca48fd 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/rms_norm.comp @@ -87,6 +87,12 @@ void rms_norm(uint num_iters) { #endif FLOAT_TYPE sum = FLOAT_TYPE(0.0f); // partial sum for thread in warp +#if RMS_NORM_ROPE_FUSION + for (uint col = tid; col < ncols; col += BLOCK_SIZE) { + const FLOAT_TYPE xi = FLOAT_TYPE(data_a[a_offset + col]); + sum += xi * xi; + } +#else [[unroll]] for (uint col = tid, idx = 0; idx < num_iters; col += BLOCK_SIZE, ++idx) { FLOAT_TYPE xi = FLOAT_TYPE(0); if (col < ncols) { @@ -94,6 +100,7 @@ void rms_norm(uint num_iters) { } sum += xi * xi; } +#endif #if USE_SUBGROUP_ADD sum = subgroupAdd(sum); @@ -131,6 +138,15 @@ void rms_norm(uint num_iters) { const FLOAT_TYPE mean = sum / FLOAT_TYPE(ncols); const FLOAT_TYPE scale = inversesqrt(mean + FLOAT_TYPE(p.param1)); +#if RMS_NORM_ROPE_FUSION + for (uint col = tid; col < ncols; col += BLOCK_SIZE) { + FLOAT_TYPE value = scale * FLOAT_TYPE(data_a[a_offset + col]); + if (do_multiply) { + value *= FLOAT_TYPE(data_b[b_offset + fastmod(col, p.ne10)]); + } + data_d[d_offset + col] = D_TYPE(value); + } +#else if (do_multiply) { if (ncols > p.ne10) { [[unroll]] for (uint col = tid, idx = 0; idx < num_iters; col += BLOCK_SIZE, ++idx) { @@ -169,6 +185,7 @@ void rms_norm(uint num_iters) { data_d[d_offset + col] = FLOAT_TO_D(scale * FLOAT_TYPE(A_TO_FLOAT(data_a[a_offset + col]))); } } +#endif #if RMS_NORM_ROPE_FUSION barrier(); rope_params rp = p.rope; @@ -185,6 +202,10 @@ void rms_norm(uint num_iters) { } void main() { +#if RMS_NORM_ROPE_FUSION + const uint num_blocks = (p.ne00 + BLOCK_SIZE - 1) / BLOCK_SIZE; + rms_norm(num_blocks); +#else // instantiate the rms_norm function for several different // dimensions, to allow loop unrolling uint num_blocks = (p.ne00 + BLOCK_SIZE - 1) / BLOCK_SIZE; @@ -209,4 +230,5 @@ void main() { } else if (num_blocks == 1) { rms_norm(1); } +#endif } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/scale.comp b/ggml/src/ggml-vulkan/vulkan-shaders/scale.comp index 83ee31a72960..0313f2fed90a 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/scale.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/scale.comp @@ -18,7 +18,7 @@ void main() { continue; } - data_d[get_doffset() + idx] = FLOAT_TO_D(A_TO_FLOAT(data_a[get_aoffset() + idx]) * FLOAT_TYPE(p.param1) + FLOAT_TYPE(p.param2)); + data_d[get_doffset() + dst_idx(idx)] = FLOAT_TO_D(A_TO_FLOAT(data_a[get_aoffset() + src0_idx(idx)]) * FLOAT_TYPE(p.param1) + FLOAT_TYPE(p.param2)); idx += num_threads; } } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/sleep.comp b/ggml/src/ggml-vulkan/vulkan-shaders/sleep.comp new file mode 100644 index 000000000000..07f6cafc9715 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/sleep.comp @@ -0,0 +1,37 @@ +#version 450 + +#extension GL_EXT_shader_realtime_clock : require + +layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in; + +// never written, it only anchors the spin below so the compiler cannot drop it +layout (binding = 0) writeonly buffer D {uint data_d[];}; + +layout (push_constant) uniform parameter { + uint ticks; +} p; + +// bounds the spin in case the clock does not advance, turning a hang into a too-short sleep +const uint MAX_ITER = 1u << 27; + +void main() { + const uvec2 t0 = clockRealtime2x32EXT(); + + uvec2 t = t0; + + for (uint iter = 0; iter < MAX_ITER; ++iter) { + t = clockRealtime2x32EXT(); + + const uint lo = t.x - t0.x; + const uint hi = t.y - t0.y - (t.x < t0.x ? 1u : 0u); + + if (hi != 0u || lo >= p.ticks) { + break; + } + } + + // the store never runs, but the compiler cannot prove it and has to keep the spin + if (t.x == 0xFFFFFFFFu && t.y == 0xFFFFFFFFu) { + data_d[0] = t.x; + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp index 2a07746960af..e20c94758900 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp @@ -348,7 +348,10 @@ compile_count_guard acquire_compile_slot() { } void string_to_spv_func(std::string name, std::string in_path, std::string out_path, std::map defines, bool coopmat, bool dep_file, compile_count_guard slot) { - std::string target_env = (name.find("_cm2") != std::string::npos) ? "--target-env=vulkan1.3" : "--target-env=vulkan1.2"; + // coopmat2 and the maintenance1 GDN coopmat1 variants need SPIR-V 1.6 (vulkan1.3) + const bool needs_spv16 = name.find("_cm2") != std::string::npos || + name.find("gated_delta_net_f32_cm1") != std::string::npos; + std::string target_env = needs_spv16 ? "--target-env=vulkan1.3" : "--target-env=vulkan1.2"; #ifdef _WIN32 std::vector cmd = {GLSLC, "-fshader-stage=compute", target_env, "\"" + in_path + "\"", "-o", "\"" + out_path + "\""}; @@ -1028,6 +1031,7 @@ void process_shaders() { string_to_spv("arange_f32", "arange.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}}); string_to_spv("fill_f32", "fill.comp", {{"D_TYPE", "float"}, {"FLOAT_TYPE", "float"}}); string_to_spv("fill_f16", "fill.comp", {{"D_TYPE", "float16_t"}, {"FLOAT_TYPE", "float"}}); + string_to_spv("sleep", "sleep.comp", {}); string_to_spv("silu_back_f32", "silu_back.comp", {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}}); @@ -1127,6 +1131,20 @@ void process_shaders() { string_to_spv("gated_delta_net_f32_nocluster", "gated_delta_net.comp", merge_maps(base_dict, {{"FLOAT_TYPE", "float"}, {"USE_SUBGROUP_ADD", "1"}, {"USE_SUBGROUP_CLUSTERED", "0"}})); string_to_spv("gated_delta_net_f32_shmem", "gated_delta_net.comp", merge_maps(base_dict, {{"FLOAT_TYPE", "float"}, {"USE_SUBGROUP_ADD", "0"}, {"USE_SUBGROUP_CLUSTERED", "0"}})); +#if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT) + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm2.comp", base_dict, true, false, true); +#endif +#if defined(GGML_VULKAN_BFLOAT16_GLSLC_SUPPORT) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT) && defined(GGML_VULKAN_COOPMAT_MAINTENANCE1_GLSLC_SUPPORT) + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm.comp", merge_maps(base_dict, {{"BF16ACC", "1"}}), true, true, false, false, "_bf16acc"); + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm.comp", base_dict, true, true); + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm.comp", merge_maps(base_dict, {{"BF16ACC", "1"}, {"V", "32"}}), true, true, false, false, "_bf16acc_v32"); + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm.comp", merge_maps(base_dict, {{"V", "32"}}), true, true, false, false, "_v32"); + // whole-head V=128 variant: state mirror in a gmem scratch buffer (won't fit LDS). + // For head counts that tail the CU grid at V=64 (e.g. 48-head 27B on 64 CUs). + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm.comp", merge_maps(base_dict, {{"BF16ACC", "1"}, {"GMEM_MIRROR", "1"}, {"V", "128"}}), true, true, false, false, "_bf16acc_v128"); + string_to_spv("gated_delta_net_f32", "gated_delta_net_cm.comp", merge_maps(base_dict, {{"GMEM_MIRROR", "1"}, {"V", "128"}}), true, true, false, false, "_v128"); +#endif + string_to_spv("opt_step_adamw_f32", "opt_step_adamw.comp", merge_maps(base_dict, {{"A_TYPE", "float"}})); string_to_spv("opt_step_sgd_f32", "opt_step_sgd.comp", merge_maps(base_dict, {{"A_TYPE", "float"}})); diff --git a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp index 52b1bcc88ca3..cc7f660ef8e4 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp @@ -1269,6 +1269,7 @@ class ggml_webgpu_shader_lib { std::unordered_map argsort_pipelines; // key is order std::unordered_map argsort_merge_pipelines; // key is order std::unordered_map cumsum_pipelines; // key is fixed, no variants yet + std::unordered_map col2im_1d_pipelines; // key is fixed, no variants yet std::unordered_map arange_pipelines; // key is fixed, no variants yet std::unordered_map count_equal_pipelines; // key is src_overlap std::unordered_map timestep_embedding_pipelines; // key is fixed, no variants yet @@ -2096,6 +2097,23 @@ class ggml_webgpu_shader_lib { return pool2d_pipelines[key]; } + webgpu_pipeline get_col2im_1d_pipeline(const ggml_webgpu_shader_lib_context & context) { + auto it = col2im_1d_pipelines.find(1); + if (it != col2im_1d_pipelines.end()) { + return it->second; + } + + const uint32_t wg_size = std::min(256u, context.max_wg_size); + std::vector defines = { "WG_SIZE=" + std::to_string(wg_size) }; + auto processed = preprocessor.preprocess(wgsl_col2im_1d, defines); + auto decisions = std::make_shared(); + decisions->wg_size = wg_size; + webgpu_pipeline pipeline = ggml_webgpu_create_pipeline(device, processed, "col2im_1d"); + pipeline.context = decisions; + col2im_1d_pipelines[1] = pipeline; + return pipeline; + } + webgpu_pipeline get_pad_pipeline(const ggml_webgpu_shader_lib_context & context) { ggml_webgpu_pad_pipeline_key key = {}; key.reflect = context.dst->op == GGML_OP_PAD_REFLECT_1D; diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp index 6aa0cc92a32b..886760849796 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp @@ -908,6 +908,32 @@ static webgpu_encoded_op ggml_webgpu_arange(webgpu_context & ctx, ggml_tensor * return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y); } +static webgpu_encoded_op ggml_webgpu_col2im_1d(webgpu_context & ctx, ggml_tensor * src, ggml_tensor * dst) { + ggml_webgpu_shader_lib_context shader_lib_ctx = {}; + shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup; + webgpu_pipeline pipeline = ctx->shader_lib->get_col2im_1d_pipeline(shader_lib_ctx); + auto * decisions = static_cast(pipeline.context.get()); + + std::vector params = { + (uint32_t) ggml_nelements(dst), + (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src) / sizeof(float)), + (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / sizeof(float)), + (uint32_t) src->ne[0], + (uint32_t) src->ne[1], + (uint32_t) dst->ne[0], + (uint32_t) (src->ne[0] / dst->ne[1]), + (uint32_t) ggml_get_op_params_i32(dst, 0), + (uint32_t) ggml_get_op_params_i32(dst, 2), + }; + std::vector entries = { ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src), + ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst) }; + uint32_t wg_x; + uint32_t wg_y; + const uint32_t total_wg = CEIL_DIV(ggml_nelements(dst), decisions->wg_size); + compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y); + return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y); +} + static webgpu_encoded_op ggml_webgpu_pad(webgpu_context & ctx, ggml_tensor * src, ggml_tensor * dst) { ggml_webgpu_shader_lib_context shader_lib_ctx = {}; shader_lib_ctx.src0 = src; @@ -3712,6 +3738,8 @@ static std::optional ggml_webgpu_encode(webgpu_context ctx, return ggml_webgpu_arange(ctx, node); case GGML_OP_POOL_2D: return ggml_webgpu_pool2d(ctx, src0, node); + case GGML_OP_COL2IM_1D: + return ggml_webgpu_col2im_1d(ctx, src0, node); case GGML_OP_PAD_REFLECT_1D: case GGML_OP_PAD: return ggml_webgpu_pad(ctx, src0, node); @@ -4038,7 +4066,7 @@ static void ggml_backend_webgpu_buffer_memset_tensor(ggml_backend_buffer_t buffe size_t total_offset = ggml_webgpu_tensor_offset(tensor) + offset; - // This is a trick to set all bytes of a u32 to the same 1 byte value. + // set all bytes of a u32 to the same 1 byte value uint32_t val32 = (uint32_t) value * 0x01010101; ggml_backend_webgpu_buffer_memset(buf_ctx->global_ctx, buf_ctx->buffer, val32, total_offset, size); WEBGPU_CPU_PROFILE_TOTAL_END(memset_tensor, buf_ctx->global_ctx); @@ -4378,7 +4406,10 @@ static void ggml_backend_webgpu_buffer_clear(ggml_backend_buffer_t buffer, uint8 WEBGPU_LOG_DEBUG("ggml_backend_webgpu_buffer_clear(" << buffer << ", " << (uint32_t) value << ")"); WEBGPU_CPU_PROFILE_TOTAL_START(clear); ggml_backend_webgpu_buffer_context * buf_ctx = (ggml_backend_webgpu_buffer_context *) buffer->context; - ggml_backend_webgpu_buffer_memset(buf_ctx->global_ctx, buf_ctx->buffer, value, 0, buffer->size); + + // set all bytes of a u32 to the same 1 byte value + uint32_t val32 = (uint32_t) value * 0x01010101; + ggml_backend_webgpu_buffer_memset(buf_ctx->global_ctx, buf_ctx->buffer, val32, 0, buffer->size); WEBGPU_CPU_PROFILE_TOTAL_END(clear, buf_ctx->global_ctx); } @@ -5234,7 +5265,8 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && src2->type == GGML_TYPE_F32 && op->src[3]->type == GGML_TYPE_F32 && op->src[4]->type == GGML_TYPE_F32 && op->src[5]->type == GGML_TYPE_F32 && - s_v <= ctx->webgpu_global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup; + s_v <= ctx->webgpu_global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup && + ggml_are_same_stride(src0, src1); } break; case GGML_OP_CLAMP: @@ -5292,6 +5324,10 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const supports_op = src0->type == GGML_TYPE_I32 && src1->type == GGML_TYPE_I32 && ggml_is_contiguous(src0) && ggml_is_contiguous(src1); break; + case GGML_OP_COL2IM_1D: + supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32 && ggml_is_contiguous(src0) && + ggml_is_contiguous(op); + break; case GGML_OP_SUM_ROWS: case GGML_OP_MEAN: supports_op = op->type == GGML_TYPE_F32 && src0->type == op->type && ggml_is_contiguous_rows(src0); diff --git a/ggml/src/ggml-webgpu/wgsl-shaders/col2im_1d.wgsl b/ggml/src/ggml-webgpu/wgsl-shaders/col2im_1d.wgsl new file mode 100644 index 000000000000..f89528f2476d --- /dev/null +++ b/ggml/src/ggml-webgpu/wgsl-shaders/col2im_1d.wgsl @@ -0,0 +1,45 @@ +@group(0) @binding(0) +var src: array; + +@group(0) @binding(1) +var dst: array; + +struct Params { + ne: u32, + offset_src: u32, + offset_dst: u32, + src_ne0: u32, + t_in: u32, + t_out: u32, + kernel: u32, + stride: u32, + padding: u32, +}; + +@group(0) @binding(2) +var params: Params; + +@compute @workgroup_size(WG_SIZE) +fn main(@builtin(num_workgroups) num_wg: vec3, + @builtin(global_invocation_id) gid: vec3) { + let idx = gid.x + num_wg.x * WG_SIZE * gid.y; + if (idx >= params.ne) { + return; + } + + let channel = idx / params.t_out; + let t_abs = idx % params.t_out + params.padding; + var first: u32 = 0; + if (t_abs >= params.kernel) { + first = (t_abs - params.kernel) / params.stride + 1; + } + let last = min(t_abs / params.stride, params.t_in - 1); + + // Gather overlapping columns in the same order as the CPU reference. + var sum: f32 = 0.0; + for (var t = first; t <= last; t++) { + let k = t_abs - t * params.stride; + sum += src[params.offset_src + t * params.src_ne0 + channel * params.kernel + k]; + } + dst[params.offset_dst + idx] = sum; +} diff --git a/ggml/src/ggml-webgpu/wgsl-shaders/cpy.wgsl b/ggml/src/ggml-webgpu/wgsl-shaders/cpy.wgsl index 0d0d81ab650f..2466b2f0b7ca 100644 --- a/ggml/src/ggml-webgpu/wgsl-shaders/cpy.wgsl +++ b/ggml/src/ggml-webgpu/wgsl-shaders/cpy.wgsl @@ -53,12 +53,14 @@ var params: Params; @compute @workgroup_size(WG_SIZE) fn main( @builtin(global_invocation_id) gid: vec3, + @builtin(num_workgroups) num_wg: vec3, ) { - if (gid.x >= params.ne) { + let idx = gid.x + num_wg.x * WG_SIZE * gid.y; + if (idx >= params.ne) { return; } - var i = gid.x; + var i = idx; let i3 = i / (params.src_ne2 * params.src_ne1 * params.src_ne0); i = i % (params.src_ne2 * params.src_ne1 * params.src_ne0); let i2 = i / (params.src_ne1 * params.src_ne0); @@ -66,7 +68,7 @@ fn main( let i1 = i / params.src_ne0; let i0 = i % params.src_ne0; - var j = gid.x; + var j = idx; let j3 = j / (params.dst_ne2 * params.dst_ne1 * params.dst_ne0); j = j % (params.dst_ne2 * params.dst_ne1 * params.dst_ne0); let j2 = j / (params.dst_ne1 * params.dst_ne0); diff --git a/ggml/src/ggml-zdnn/common.hpp b/ggml/src/ggml-zdnn/common.hpp index e28e7608b6a2..3ab3b4b277b4 100644 --- a/ggml/src/ggml-zdnn/common.hpp +++ b/ggml/src/ggml-zdnn/common.hpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -50,6 +51,8 @@ struct ggml_backend_zdnn_buffer { std::vector scales; // per-row scales for quantized weights std::vector channel_scales; // per-input-channel scales for quantized weights, applied to the inputs + std::mutex mutex; + char name[GGML_MAX_NAME]; }; diff --git a/ggml/src/ggml-zdnn/mmf.cpp b/ggml/src/ggml-zdnn/mmf.cpp index acd443e5be59..0efb4821eb01 100644 --- a/ggml/src/ggml-zdnn/mmf.cpp +++ b/ggml/src/ggml-zdnn/mmf.cpp @@ -61,9 +61,7 @@ void ggml_zdnn_mul_mat_f( GGML_ASSERT(weights_extra->pre_tfm_desc.dim2 == weights->ne[1] && "weights_extra->pre_tfm_desc.dim2 must match weights->ne[1]"); // weights read straight into a host buffer skip set_tensor, so transform them on first use - if (!weights_extra->ztensor.is_transformed) { - ggml_zdnn_load_tensor(weights_extra->ztensor, weights->data); - } + ggml_zdnn_load_weights(weights_extra, weights); // the inputs can be in any host buffer or be a view, so transform them from their data on every call { diff --git a/ggml/src/ggml-zdnn/mmq.cpp b/ggml/src/ggml-zdnn/mmq.cpp index 285479b4184e..50acddb25c5d 100644 --- a/ggml/src/ggml-zdnn/mmq.cpp +++ b/ggml/src/ggml-zdnn/mmq.cpp @@ -190,9 +190,7 @@ void ggml_zdnn_mul_mat_q( ggml_backend_zdnn_buffer * weights_extra = (ggml_backend_zdnn_buffer *)weights->extra; // weights read straight into a host buffer skip set_tensor, so transform them on first use - if (!weights_extra->ztensor.is_transformed) { - ggml_zdnn_load_tensor_q(weights_extra, weights); - } + ggml_zdnn_load_weights(weights_extra, weights); // starting threads costs more than it saves for small inputs, e.g. during token generation const int32_t n_threads = ne10*ne11 >= 65536 ? ctx->n_threads : 1; diff --git a/ggml/src/ggml-zdnn/utils.cpp b/ggml/src/ggml-zdnn/utils.cpp index 18e9879d0906..d59ed4001f67 100644 --- a/ggml/src/ggml-zdnn/utils.cpp +++ b/ggml/src/ggml-zdnn/utils.cpp @@ -144,6 +144,20 @@ void ggml_zdnn_load_tensor_q(ggml_backend_zdnn_buffer * buffer, const ggml_tenso ZDNN_CHECK(zdnn_transform_quantized_ztensor(&buffer->ztensor, false, -127, 127, q.data())); } +void ggml_zdnn_load_weights(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor) { + std::lock_guard lock(buffer->mutex); + + if (buffer->ztensor.is_transformed) { + return; + } + + if (ggml_is_quantized(tensor->type)) { + ggml_zdnn_load_tensor_q(buffer, tensor); + } else { + ggml_zdnn_load_tensor(buffer->ztensor, tensor->data); + } +} + void ggml_zdnn_init_tensor(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor) { if (ggml_is_quantized(tensor->type)) { GGML_ASSERT(ggml_is_matrix(tensor)); diff --git a/ggml/src/ggml-zdnn/utils.hpp b/ggml/src/ggml-zdnn/utils.hpp index 20f5be5b4828..f610c216f5ef 100644 --- a/ggml/src/ggml-zdnn/utils.hpp +++ b/ggml/src/ggml-zdnn/utils.hpp @@ -18,6 +18,8 @@ int64_t ggml_zdnn_q_group_size(const ggml_tensor * tensor); void ggml_zdnn_load_tensor_q(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor); +void ggml_zdnn_load_weights(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor); + void ggml_zdnn_init_tensor(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor); #endif // GGML_ZDNN_UTILITIES_HPP diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index 7132abc51f3b..3389dcd63d7c 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -54,6 +54,8 @@ #define UNUSED GGML_UNUSED +static_assert(GGML_VERSION_MAJOR == 1, "major version update requires attending to all [TAG_GGML_VERSION_MAJOR_UPDATE] tags"); + uint64_t ggml_graph_next_uid(void) { #ifdef _MSC_VER #if defined(_WIN32) @@ -1112,9 +1114,13 @@ static const char * GGML_OP_NAME[GGML_OP_COUNT] = { "OPT_STEP_SGD", "GLU", + + "SLEEP", + + "SIGMOID_BACK", }; -static_assert(GGML_OP_COUNT == 99, "GGML_OP_COUNT != 99"); +static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT != 101"); static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "none", @@ -1225,9 +1231,13 @@ static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "sgd(x)", "glu(x)", + + "sleep(x)", + + "sigmoid_back(x)", }; -static_assert(GGML_OP_COUNT == 99, "GGML_OP_COUNT != 99"); +static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT != 101"); static_assert(GGML_OP_POOL_COUNT == 2, "GGML_OP_POOL_COUNT != 2"); @@ -2860,6 +2870,21 @@ struct ggml_tensor * ggml_silu_back( return result; } +// ggml_sigmoid_back + +struct ggml_tensor * ggml_sigmoid_back( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b) { + struct ggml_tensor * result = ggml_dup_tensor(ctx, a); + + result->op = GGML_OP_SIGMOID_BACK; + result->src[0] = a; + result->src[1] = b; + + return result; +} + // ggml hardswish struct ggml_tensor * ggml_hardswish( @@ -4015,7 +4040,7 @@ struct ggml_tensor * ggml_set_rows( GGML_ASSERT(b->ne[2] % c->ne[1] == 0); GGML_ASSERT(b->ne[3] % c->ne[2] == 0); GGML_ASSERT(c->ne[3] == 1); - GGML_ASSERT(b->type == GGML_TYPE_F32 || b->type == GGML_TYPE_F16); + GGML_ASSERT(b->type == GGML_TYPE_F32 || b->type == GGML_TYPE_F16 || b->type == GGML_TYPE_BF16); GGML_ASSERT(c->type == GGML_TYPE_I64 || c->type == GGML_TYPE_I32); GGML_ASSERT(ggml_is_contiguous_rows(a)); @@ -6176,6 +6201,27 @@ struct ggml_tensor * ggml_custom_inplace( return result; } + +// ggml_sleep + +// the result aliases a, the op only delays and never touches the data +struct ggml_tensor * ggml_sleep( + struct ggml_context * ctx, + struct ggml_tensor * a, + int32_t us) { + GGML_ASSERT(us >= 0); + + struct ggml_tensor * result = ggml_view_tensor(ctx, a); + ggml_format_name(result, "%s (sleep)", a->name); + + ggml_set_op_params_i32(result, 0, us); + + result->op = GGML_OP_SLEEP; + result->src[0] = a; + + return result; +} + // ggml_cross_entropy_loss struct ggml_tensor * ggml_cross_entropy_loss( @@ -7121,6 +7167,11 @@ static void ggml_compute_backward( ggml_add_or_set(ctx, cgraph, isrc0, ggml_silu_back(ctx, grad, src0)); } } break; + case GGML_UNARY_OP_SIGMOID: { + if (src0_needs_grads) { + ggml_add_or_set(ctx, cgraph, isrc0, ggml_sigmoid_back(ctx, grad, src0)); + } + } break; case GGML_UNARY_OP_EXP: { if (src0_needs_grads) { ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, tensor, grad)); diff --git a/ggml/src/gguf.cpp b/ggml/src/gguf.cpp index c80b682185ce..1a57b608e972 100644 --- a/ggml/src/gguf.cpp +++ b/ggml/src/gguf.cpp @@ -322,24 +322,6 @@ struct gguf_reader { return true; } - bool read(enum ggml_type & dst) const { - int32_t tmp = -1; - if (!read(tmp)) { - return false; - } - dst = ggml_type(tmp); - return true; - } - - bool read(enum gguf_type & dst) const { - int32_t tmp = -1; - if (!read(tmp)) { - return false; - } - dst = gguf_type(tmp); - return true; - } - bool read(std::string & dst) const { uint64_t size = 0; if (!read(size)) { @@ -555,7 +537,7 @@ static struct gguf_context * gguf_init_from_reader(const struct gguf_reader & gr for (int64_t i = 0; ok && i < n_kv; ++i) { std::string key; - gguf_type type = gguf_type(-1); + int32_t type = -1; bool is_array = false; uint64_t n = 1; @@ -724,15 +706,20 @@ static struct gguf_context * gguf_init_from_reader(const struct gguf_reader & gr // tensor type { - ok = ok && gr.read(info.t.type); + int32_t type = -1; + ok = ok && gr.read(type); + if (!ok) { + break; + } // check that tensor type is within defined range - if (info.t.type < 0 || info.t.type >= GGML_TYPE_COUNT) { + if (type < 0 || type >= GGML_TYPE_COUNT) { GGML_LOG_ERROR("%s: tensor '%s' has invalid ggml type %d. should be in [0, %d)\n", - __func__, info.t.name, info.t.type, GGML_TYPE_COUNT); + __func__, info.t.name, type, GGML_TYPE_COUNT); ok = false; break; } + info.t.type = ggml_type(type); const size_t type_size = ggml_type_size(info.t.type); const int64_t blck_size = ggml_blck_size(info.t.type); diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py index e07ea2f4b7c2..0592f5e016f5 100644 --- a/gguf-py/gguf/constants.py +++ b/gguf-py/gguf/constants.py @@ -326,6 +326,13 @@ class HRM: L_CYCLES = "{arch}.hrm.l_cycles" PREFIX_LM = "{arch}.hrm.prefix_lm" + class Loop: + START = "{arch}.loop.start" + END = "{arch}.loop.end" + COUNT = "{arch}.loop.count" + GATE_RANK = "{arch}.loop.gate_rank" + VARYING = "{arch}.loop.varying" + class Metis: PASS_COUNT = "{arch}.metis.pass_count" MEMORY_LENGTH = "{arch}.metis.memory_length" @@ -771,6 +778,7 @@ class MODEL_ARCH(IntEnum): NANBEIGE = auto() QWEN3TTS = auto() POCKETTTS = auto() + MOSHI = auto() ZONOS3 = auto() KOKORO = auto() TINY_VOCA = auto() @@ -778,6 +786,8 @@ class MODEL_ARCH(IntEnum): KOLIBRI1 = auto() LIMITE = auto() INKLING2 = auto() + INKLING2_LOOP = auto() + DOMYN_EDGE = auto() class VISION_PROJECTOR_TYPE(IntEnum): @@ -879,6 +889,19 @@ class MODEL_TENSOR(IntEnum): MOE_LATENT_UP = auto() # nemotron 3 super FFN_POST_CONV = auto() FFN_RES_QUERY = auto() + LOOP_MSG_QUERY = auto() + LOOP_Q_CTRL_DOWN = auto() + LOOP_Q_CTRL_GAIN = auto() + LOOP_Q_CTRL_FORGET = auto() + LOOP_K_CTRL_DOWN = auto() + LOOP_K_CTRL_GAIN = auto() + LOOP_K_CTRL_FORGET = auto() + LOOP_V_CTRL_DOWN = auto() + LOOP_V_CTRL_GAIN = auto() + LOOP_V_CTRL_FORGET = auto() + LOOP_FFN_CTRL_DOWN = auto() + LOOP_FFN_CTRL_GAIN = auto() + LOOP_FFN_CTRL_FORGET = auto() STREAM_EMBD = auto() DEPTH_MEM_STATE_WRITE = auto() DEPTH_MEM_META_WRITE = auto() @@ -1771,6 +1794,7 @@ class MODEL_TENSOR(IntEnum): MODEL_ARCH.NANBEIGE: "nanbeige", MODEL_ARCH.QWEN3TTS: "qwen3tts", MODEL_ARCH.POCKETTTS: "pockettts", + MODEL_ARCH.MOSHI: "moshi", MODEL_ARCH.ZONOS3: "zonos3", MODEL_ARCH.KOKORO: "kokoro", MODEL_ARCH.TINY_VOCA: "tiny-voca", @@ -1778,6 +1802,8 @@ class MODEL_TENSOR(IntEnum): MODEL_ARCH.KOLIBRI1: "kolibri1", MODEL_ARCH.LIMITE: "limite", MODEL_ARCH.INKLING2: "inkling2", + MODEL_ARCH.INKLING2_LOOP: "inkling2_loop", + MODEL_ARCH.DOMYN_EDGE: "domynedge", } VISION_PROJECTOR_TYPE_NAMES: dict[VISION_PROJECTOR_TYPE, str] = { @@ -1879,6 +1905,19 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.MOE_LATENT_UP: "blk.{bid}.ffn_latent_up", # nemotron 3 super MODEL_TENSOR.FFN_POST_CONV: "blk.{bid}.ffn_post_conv", MODEL_TENSOR.FFN_RES_QUERY: "blk.{bid}.ffn_res_query", + MODEL_TENSOR.LOOP_MSG_QUERY: "blk.{bid}.loop_msg_query", + MODEL_TENSOR.LOOP_Q_CTRL_DOWN: "blk.{bid}.loop_q_ctrl_down", + MODEL_TENSOR.LOOP_Q_CTRL_GAIN: "blk.{bid}.loop_q_ctrl_gain", + MODEL_TENSOR.LOOP_Q_CTRL_FORGET: "blk.{bid}.loop_q_ctrl_forget", + MODEL_TENSOR.LOOP_K_CTRL_DOWN: "blk.{bid}.loop_k_ctrl_down", + MODEL_TENSOR.LOOP_K_CTRL_GAIN: "blk.{bid}.loop_k_ctrl_gain", + MODEL_TENSOR.LOOP_K_CTRL_FORGET: "blk.{bid}.loop_k_ctrl_forget", + MODEL_TENSOR.LOOP_V_CTRL_DOWN: "blk.{bid}.loop_v_ctrl_down", + MODEL_TENSOR.LOOP_V_CTRL_GAIN: "blk.{bid}.loop_v_ctrl_gain", + MODEL_TENSOR.LOOP_V_CTRL_FORGET: "blk.{bid}.loop_v_ctrl_forget", + MODEL_TENSOR.LOOP_FFN_CTRL_DOWN: "blk.{bid}.loop_ffn_ctrl_down", + MODEL_TENSOR.LOOP_FFN_CTRL_GAIN: "blk.{bid}.loop_ffn_ctrl_gain", + MODEL_TENSOR.LOOP_FFN_CTRL_FORGET: "blk.{bid}.loop_ffn_ctrl_forget", MODEL_TENSOR.STREAM_EMBD: "stream_embd", MODEL_TENSOR.DEPTH_MEM_STATE_WRITE: "depth_mem_state_write", MODEL_TENSOR.DEPTH_MEM_META_WRITE: "depth_mem_meta_write", @@ -6920,6 +6959,20 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.FFN_DOWN, MODEL_TENSOR.FFN_UP, ], + MODEL_ARCH.MOSHI: [ + MODEL_TENSOR.TOKEN_EMBD, + MODEL_TENSOR.OUTPUT_NORM, + MODEL_TENSOR.OUTPUT, + MODEL_TENSOR.ATTN_NORM, + MODEL_TENSOR.ATTN_Q, + MODEL_TENSOR.ATTN_K, + MODEL_TENSOR.ATTN_V, + MODEL_TENSOR.ATTN_OUT, + MODEL_TENSOR.FFN_NORM, + MODEL_TENSOR.FFN_GATE, + MODEL_TENSOR.FFN_DOWN, + MODEL_TENSOR.FFN_UP, + ], MODEL_ARCH.TINY_VOCA: [ MODEL_TENSOR.TOKEN_EMBD, MODEL_TENSOR.OUTPUT_NORM, @@ -7085,6 +7138,71 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.FFN_POST_CONV, MODEL_TENSOR.FFN_RES_QUERY, ], + MODEL_ARCH.INKLING2_LOOP: [ + MODEL_TENSOR.TOKEN_EMBD, + MODEL_TENSOR.TOKEN_EMBD_NORM, + MODEL_TENSOR.OUTPUT, + MODEL_TENSOR.OUTPUT_NORM, + MODEL_TENSOR.OUTPUT_RES_QUERY, + MODEL_TENSOR.ATTN_NORM, + MODEL_TENSOR.ATTN_Q, + MODEL_TENSOR.ATTN_K, + MODEL_TENSOR.ATTN_V, + MODEL_TENSOR.ATTN_OUT, + MODEL_TENSOR.ATTN_GATE, + MODEL_TENSOR.ATTN_REL, + MODEL_TENSOR.ATTN_REL_BIAS, + MODEL_TENSOR.ATTN_Q_CLIP, + MODEL_TENSOR.ATTN_REL_CLIP, + MODEL_TENSOR.ATTN_SINK_PROJ, + MODEL_TENSOR.ATTN_Q_INP_NORM, + MODEL_TENSOR.ATTN_K_INP_NORM, + MODEL_TENSOR.ATTN_V_INP_NORM, + MODEL_TENSOR.ATTN_K_CONV, + MODEL_TENSOR.ATTN_V_CONV, + MODEL_TENSOR.ATTN_K_CONV_PROJ, + MODEL_TENSOR.ATTN_V_CONV_PROJ, + MODEL_TENSOR.ATTN_POST_CONV, + MODEL_TENSOR.ATTN_RES_QUERY, + MODEL_TENSOR.FFN_NORM, + MODEL_TENSOR.FFN_GATE_INP, + MODEL_TENSOR.FFN_EXP_PROBS_B, + MODEL_TENSOR.FFN_GATE_EXP, + MODEL_TENSOR.FFN_UP_EXP, + MODEL_TENSOR.FFN_GATE_UP_EXP, + MODEL_TENSOR.FFN_DOWN_EXP, + MODEL_TENSOR.FFN_POST_CONV, + MODEL_TENSOR.FFN_RES_QUERY, + MODEL_TENSOR.LOOP_MSG_QUERY, + MODEL_TENSOR.LOOP_Q_CTRL_DOWN, + MODEL_TENSOR.LOOP_Q_CTRL_GAIN, + MODEL_TENSOR.LOOP_Q_CTRL_FORGET, + MODEL_TENSOR.LOOP_K_CTRL_DOWN, + MODEL_TENSOR.LOOP_K_CTRL_GAIN, + MODEL_TENSOR.LOOP_K_CTRL_FORGET, + MODEL_TENSOR.LOOP_V_CTRL_DOWN, + MODEL_TENSOR.LOOP_V_CTRL_GAIN, + MODEL_TENSOR.LOOP_V_CTRL_FORGET, + MODEL_TENSOR.LOOP_FFN_CTRL_DOWN, + MODEL_TENSOR.LOOP_FFN_CTRL_GAIN, + MODEL_TENSOR.LOOP_FFN_CTRL_FORGET, + ], + MODEL_ARCH.DOMYN_EDGE: [ + MODEL_TENSOR.TOKEN_EMBD, + MODEL_TENSOR.ATTN_Q, + MODEL_TENSOR.ATTN_K, + MODEL_TENSOR.ATTN_V, + MODEL_TENSOR.ATTN_OUT, + MODEL_TENSOR.ATTN_K_NORM, + MODEL_TENSOR.ATTN_NORM, + MODEL_TENSOR.ATTN_POST_NORM, + MODEL_TENSOR.FFN_PRE_NORM, + MODEL_TENSOR.FFN_POST_NORM, + MODEL_TENSOR.FFN_DOWN, + MODEL_TENSOR.FFN_UP, + MODEL_TENSOR.FFN_GATE, + MODEL_TENSOR.OUTPUT_NORM, + ], } # tensors that will not be serialized @@ -7412,6 +7530,8 @@ class VisionProjectorType: QWEN3TTS_GEN = "qwen3tts_gen" # audio generation: code_predictor POCKETTTS_SPKENC = "pockettts_spkenc" # audio: mimi encoder as voice-prompt encoder POCKETTTS_GEN = "pockettts_gen" # audio generation: flow-matching decoder + mimi decoder + MOSHI = "moshi" # audio: streaming mimi encoder, input audio codes -> backbone rows + MOSHI_GEN = "moshi_gen" # audio generation: depformer + mimi decoder CHATTERBOX_SPKENC = "chatterbox_spkenc" # audio: CAMPPlus speaker encoder CHATTERBOX = "chatterbox" # audio generation: s3gen flow matching + HiFT vocoder SOPRANO = "soprano" # audio generation: Vocos decoder diff --git a/gguf-py/gguf/gguf_writer.py b/gguf-py/gguf/gguf_writer.py index eb0bd91d0049..08c8d2f33c15 100644 --- a/gguf-py/gguf/gguf_writer.py +++ b/gguf-py/gguf/gguf_writer.py @@ -990,6 +990,21 @@ def add_hrm_l_cycles(self, value: int) -> None: def add_hrm_prefix_lm(self, value: bool) -> None: self.add_bool(Keys.HRM.PREFIX_LM.format(arch=self.arch), value) + def add_loop_start(self, value: int) -> None: + self.add_uint32(Keys.Loop.START.format(arch=self.arch), value) + + def add_loop_end(self, value: int) -> None: + self.add_uint32(Keys.Loop.END.format(arch=self.arch), value) + + def add_loop_count(self, value: int) -> None: + self.add_uint32(Keys.Loop.COUNT.format(arch=self.arch), value) + + def add_loop_gate_rank(self, value: int) -> None: + self.add_uint32(Keys.Loop.GATE_RANK.format(arch=self.arch), value) + + def add_loop_varying(self, value: bool) -> None: + self.add_bool(Keys.Loop.VARYING.format(arch=self.arch), value) + def add_metis_pass_count(self, value: int) -> None: self.add_uint32(Keys.Metis.PASS_COUNT.format(arch=self.arch), value) diff --git a/gguf-py/gguf/tensor_mapping.py b/gguf-py/gguf/tensor_mapping.py index c844a9322b12..c0bbfde2298d 100644 --- a/gguf-py/gguf/tensor_mapping.py +++ b/gguf-py/gguf/tensor_mapping.py @@ -272,6 +272,7 @@ class TensorNameMap: "model.layers.{bid}.pre_attention_layernorm", # kormo "head.layers.{bid}.norm1", # laya "model.layers.{bid}.attn_norm", # inkling2 + "model.layers.{bid}.pre_attention_norm", # domynedge ), # Attention norm 2 @@ -440,6 +441,7 @@ class TensorNameMap: "model.layers.{bid}.post_attn_norm", # kolibri1 "model.layers.layers.{bid}.post_mixer_norm.weight", # plamo2 "model.layers.{bid}.post_operator_norm", # lfm3 + "model.layers.{bid}.post_attention_norm", # domynedge ), # Rotary embeddings @@ -541,6 +543,66 @@ class TensorNameMap: "model.layers.{bid}.attention_input.query", # inkling2 ), + MODEL_TENSOR.LOOP_Q_CTRL_DOWN: ( + "model.layers.{bid}.q_controller.down_proj", # inkling2_loop + "model.layers.{bid}.controllers.attn.down_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_Q_CTRL_GAIN: ( + "model.layers.{bid}.q_controller.gain_proj", # inkling2_loop + "model.layers.{bid}.controllers.attn.gain_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_Q_CTRL_FORGET: ( + "model.layers.{bid}.q_controller.forget_proj", # inkling2_loop + "model.layers.{bid}.controllers.attn.forget_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_K_CTRL_DOWN: ( + "model.layers.{bid}.k_controller.down_proj", # inkling2_loop + "model.layers.{bid}.controllers.k.down_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_K_CTRL_GAIN: ( + "model.layers.{bid}.k_controller.gain_proj", # inkling2_loop + "model.layers.{bid}.controllers.k.gain_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_K_CTRL_FORGET: ( + "model.layers.{bid}.k_controller.forget_proj", # inkling2_loop + "model.layers.{bid}.controllers.k.forget_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_V_CTRL_DOWN: ( + "model.layers.{bid}.v_controller.down_proj", # inkling2_loop + "model.layers.{bid}.controllers.v.down_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_V_CTRL_GAIN: ( + "model.layers.{bid}.v_controller.gain_proj", # inkling2_loop + "model.layers.{bid}.controllers.v.gain_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_V_CTRL_FORGET: ( + "model.layers.{bid}.v_controller.forget_proj", # inkling2_loop + "model.layers.{bid}.controllers.v.forget_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_FFN_CTRL_DOWN: ( + "model.layers.{bid}.mlp_controller.down_proj", # inkling2_loop + "model.layers.{bid}.controllers.mlp.down_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_FFN_CTRL_GAIN: ( + "model.layers.{bid}.mlp_controller.gain_proj", # inkling2_loop + "model.layers.{bid}.controllers.mlp.gain_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_FFN_CTRL_FORGET: ( + "model.layers.{bid}.mlp_controller.forget_proj", # inkling2_loop + "model.layers.{bid}.controllers.mlp.forget_weight", # inkling2_loop + ), + # Feed-forward norm MODEL_TENSOR.FFN_NORM: ( "layers.{bid}.moe_connection.norm", # metis16 @@ -579,6 +641,7 @@ class TensorNameMap: "layers.{bid}.pre_feedforward_layernorm", # embeddinggemma "model.layers.{bid}.pre_ff_layernorm.weight", "model.layers.{bid}.pre_mlp_layernorm", # afmoe + "model.layers.{bid}.pre_feedforward_norm", # domynedge ), MODEL_TENSOR.FFN_PRE_NORM_2: ( @@ -603,6 +666,7 @@ class TensorNameMap: "model.layers.{bid}.feed_forward.up_proj", "model.layers.{bid}.post_moe_norm", # grok-2 "model.layers.{bid}.post_ffn_norm", # lfm3 + "model.layers.{bid}.post_feedforward_norm", # domynedge ), MODEL_TENSOR.FFN_POST_NORM_1: ( @@ -692,6 +756,7 @@ class TensorNameMap: "encoder.layers.{bid}.mlp.dense_h_to_4h", # chatglm "transformer.h.{bid}.mlp.c_fc_1", # exaone "model.layers.{bid}.feed_forward.up_proj", # llama4 jamba granite-hybrid + "model.layers.{bid}.feedforward.up_proj", # domynedge "transformer_encoder.{bid}.ffn.w12", # neobert "model.layers.{bid}.block_sparse_moe.up", # smallthinker "model.transformer.blocks.{bid}.up_proj", # llada @@ -755,6 +820,7 @@ class TensorNameMap: "layers.{bid}.mlp.gate_proj", # qwen3-embedding "model.layers.{bid}.mlp.language_mlp.gate_proj", # cogvlm "model.blocks.{bid}.mlp.mlp_gate", # talkie + "model.layers.{bid}.feedforward.gate_proj", # domynedge ), MODEL_TENSOR.FFN_GATE_EXP: ( @@ -923,6 +989,7 @@ class TensorNameMap: "encoder.layers.{bid}.mlp.dense_4h_to_h", # chatglm "model.layers.h.{bid}.mlp.c_proj", # exaone "model.layers.{bid}.feed_forward.down_proj", # llama4 jamba granite-hybrid + "model.layers.{bid}.feedforward.down_proj", # domynedge "transformer_encoder.{bid}.ffn.w3", # neobert "model.layers.{bid}.block_sparse_moe.down", # smallthinker "model.transformer.blocks.{bid}.ff_out", # llada @@ -997,6 +1064,7 @@ class TensorNameMap: "layers.{bid}.self_attn.k_norm", # qwen3-embedding "model.layers.{bid}.self_attn.k_rope_only_layernorm", # dots3note "model.layers.{bid}.attention.key_layernorm", # apertus + "model.layers.{bid}.attention.k_norm", # domynedge ), MODEL_TENSOR.ROPE_FREQS: ( diff --git a/models/templates/Qwen3-ASR.jinja b/models/templates/Qwen3-ASR.jinja new file mode 100644 index 000000000000..0342d9e7e8f4 --- /dev/null +++ b/models/templates/Qwen3-ASR.jinja @@ -0,0 +1,8 @@ +{%- for message in messages -%} +{{- '<|im_start|>' + message.role + '\n' -}} +{%- if message.role == 'assistant' and message.reasoning_content is defined and message.reasoning_content -%} +{{- message.reasoning_content + '' -}} +{%- endif -%} +{{- message.content + '<|im_end|>\n' -}} +{%- endfor -%} +{%- if add_generation_prompt -%}{{- '<|im_start|>assistant\n' -}}{%- endif -%} diff --git a/scripts/server-bench.py b/scripts/server-bench.py index f0984026c862..dca157302213 100755 --- a/scripts/server-bench.py +++ b/scripts/server-bench.py @@ -264,7 +264,7 @@ def benchmark( bin_max = np.ceil(token_t_last) + 1 plt.figure() - plt.hist(token_t, np.linspace(0, bin_max, bin_max, endpoint=False).tolist()) + plt.hist(token_t, np.linspace(0, bin_max, int(bin_max), endpoint=False).tolist()) plt.xlim(0, bin_max + 1) plt.title(name or "") plt.xlabel("Time [s]") diff --git a/scripts/ui-assets.cmake b/scripts/ui-assets.cmake index 90d0bdf338b8..a3b4f16d7b68 100644 --- a/scripts/ui-assets.cmake +++ b/scripts/ui-assets.cmake @@ -20,10 +20,12 @@ set(LLAMA_UI_GZIP "" CACHE STRING "Apply gzip compress to assets to save ban set(DIST_DIR "${UI_BINARY_DIR}/dist") set(SRC_DIST_DIR "${UI_SOURCE_DIR}/dist") # The stage keeps the layout of ui/: the app in apps/chat, with the sources of -# Llama UI that it compiles next to it in lib/ui (see ui/apps/chat/scripts/llama-ui.js). +# Llama UI that it compiles next to it in lib/ui (see ui/apps/chat/scripts/llama-ui.js), +# and those of Llama Voice in lib/voice (see ui/apps/chat/vite.config.ts). set(STAGE_DIR "${UI_BINARY_DIR}/ui-src") set(WORK_DIR "${STAGE_DIR}/apps/chat") set(UI_LIB_DIR "${UI_SOURCE_DIR}/../../lib/ui") +set(UI_VOICE_DIR "${UI_SOURCE_DIR}/../../lib/voice") set(STAMP_FILE "${UI_BINARY_DIR}/.ui-stamp") set(EMBED_STAMP "${UI_BINARY_DIR}/.ui-embed.sha256") set(UI_CPP "${UI_BINARY_DIR}/ui.cpp") @@ -356,6 +358,12 @@ function(stage_sources) DESTINATION "${STAGE_DIR}/lib/ui/src" NO_SOURCE_PERMISSIONS ) + + # and of Llama Voice, its sources only: they import nothing from outside them + file(COPY "${UI_VOICE_DIR}/src" + DESTINATION "${STAGE_DIR}/lib/voice" + NO_SOURCE_PERMISSIONS + ) endfunction() function(npm_build out_var) diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index c50e9f98a200..cdb1f3794fe1 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -176,6 +176,7 @@ static const std::map LLM_ARCH_NAMES = { { LLM_ARCH_NANBEIGE, "nanbeige" }, { LLM_ARCH_QWEN3TTS, "qwen3tts" }, { LLM_ARCH_POCKETTTS, "pockettts" }, + { LLM_ARCH_MOSHI, "moshi" }, { LLM_ARCH_ZONOS3, "zonos3" }, { LLM_ARCH_KOKORO, "kokoro" }, { LLM_ARCH_TINY_VOCA, "tiny-voca" }, @@ -184,6 +185,8 @@ static const std::map LLM_ARCH_NAMES = { { LLM_ARCH_KOLIBRI1, "kolibri1" }, { LLM_ARCH_RICURSIVE, "ricursive" }, { LLM_ARCH_INKLING2, "inkling2" }, + { LLM_ARCH_INKLING2_LOOP, "inkling2_loop" }, + { LLM_ARCH_DOMYN_EDGE, "domynedge" }, { LLM_ARCH_UNKNOWN, "(unknown)" }, }; @@ -284,6 +287,11 @@ static const std::map LLM_KV_NAMES = { { LLM_KV_HRM_H_CYCLES, "%s.hrm.h_cycles" }, { LLM_KV_HRM_L_CYCLES, "%s.hrm.l_cycles" }, { LLM_KV_HRM_PREFIX_LM, "%s.hrm.prefix_lm" }, + { LLM_KV_LOOP_START, "%s.loop.start" }, + { LLM_KV_LOOP_END, "%s.loop.end" }, + { LLM_KV_LOOP_COUNT, "%s.loop.count" }, + { LLM_KV_LOOP_GATE_RANK, "%s.loop.gate_rank" }, + { LLM_KV_LOOP_VARYING, "%s.loop.varying" }, { LLM_KV_METIS_PASS_COUNT, "%s.metis.pass_count" }, { LLM_KV_METIS_MEMORY_LENGTH, "%s.metis.memory_length" }, { LLM_KV_METIS_ROUTE_LENGTH, "%s.metis.route_length" }, @@ -590,6 +598,19 @@ static const std::map LLM_TENSOR_NAMES = { { LLM_TENSOR_FFN_LATENT_UP, "blk.%d.ffn_latent_up" }, { LLM_TENSOR_FFN_POST_CONV, "blk.%d.ffn_post_conv" }, { LLM_TENSOR_FFN_RES_QUERY, "blk.%d.ffn_res_query" }, + { LLM_TENSOR_LOOP_MSG_QUERY, "blk.%d.loop_msg_query" }, + { LLM_TENSOR_LOOP_Q_CTRL_DOWN, "blk.%d.loop_q_ctrl_down" }, + { LLM_TENSOR_LOOP_Q_CTRL_GAIN, "blk.%d.loop_q_ctrl_gain" }, + { LLM_TENSOR_LOOP_Q_CTRL_FORGET, "blk.%d.loop_q_ctrl_forget" }, + { LLM_TENSOR_LOOP_K_CTRL_DOWN, "blk.%d.loop_k_ctrl_down" }, + { LLM_TENSOR_LOOP_K_CTRL_GAIN, "blk.%d.loop_k_ctrl_gain" }, + { LLM_TENSOR_LOOP_K_CTRL_FORGET, "blk.%d.loop_k_ctrl_forget" }, + { LLM_TENSOR_LOOP_V_CTRL_DOWN, "blk.%d.loop_v_ctrl_down" }, + { LLM_TENSOR_LOOP_V_CTRL_GAIN, "blk.%d.loop_v_ctrl_gain" }, + { LLM_TENSOR_LOOP_V_CTRL_FORGET, "blk.%d.loop_v_ctrl_forget" }, + { LLM_TENSOR_LOOP_FFN_CTRL_DOWN, "blk.%d.loop_ffn_ctrl_down" }, + { LLM_TENSOR_LOOP_FFN_CTRL_GAIN, "blk.%d.loop_ffn_ctrl_gain" }, + { LLM_TENSOR_LOOP_FFN_CTRL_FORGET, "blk.%d.loop_ffn_ctrl_forget" }, { LLM_TENSOR_STREAM_EMBD, "stream_embd" }, { LLM_TENSOR_DEPTH_MEM_STATE_WRITE, "depth_mem_state_write" }, { LLM_TENSOR_DEPTH_MEM_META_WRITE, "depth_mem_meta_write" }, @@ -1261,6 +1282,19 @@ static const std::map LLM_TENSOR_INFOS = { {LLM_TENSOR_FFN_LATENT_UP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_FFN_POST_CONV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_SSM_CONV}}, {LLM_TENSOR_FFN_RES_QUERY, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_MSG_QUERY, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_Q_CTRL_DOWN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_Q_CTRL_GAIN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_Q_CTRL_FORGET, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_K_CTRL_DOWN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_K_CTRL_GAIN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_K_CTRL_FORGET, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_V_CTRL_DOWN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_V_CTRL_GAIN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_V_CTRL_FORGET, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_FFN_CTRL_DOWN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_FFN_CTRL_GAIN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_FFN_CTRL_FORGET, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_STREAM_EMBD, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_ADD}}, {LLM_TENSOR_DEPTH_MEM_STATE_WRITE, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, {LLM_TENSOR_DEPTH_MEM_META_WRITE, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, @@ -1447,6 +1481,7 @@ bool llm_arch_is_hybrid(const llm_arch & arch) { case LLM_ARCH_MINIMAX_01: case LLM_ARCH_ZONOS3: case LLM_ARCH_INKLING2: + case LLM_ARCH_INKLING2_LOOP: return true; default: return false; @@ -1483,6 +1518,7 @@ bool llm_arch_supports_rs_rollback(const llm_arch & arch) { case LLM_ARCH_LFM3: case LLM_ARCH_BAILINGMOE3: case LLM_ARCH_INKLING2: + case LLM_ARCH_INKLING2_LOOP: return true; default: return false; @@ -1501,6 +1537,7 @@ bool llm_arch_supports_mixed_batch(const llm_arch & arch) { case LLM_ARCH_GEMMA4_ASSISTANT: case LLM_ARCH_LIMITE: case LLM_ARCH_INKLING2: + case LLM_ARCH_INKLING2_LOOP: return false; default: return true; @@ -1521,6 +1558,7 @@ bool llm_arch_supports_sm_tensor(const llm_arch & arch) { case LLM_ARCH_JAMBA: case LLM_ARCH_FALCON_H1: case LLM_ARCH_INKLING2: + case LLM_ARCH_INKLING2_LOOP: case LLM_ARCH_OLMO2: case LLM_ARCH_OLMOE: case LLM_ARCH_DEEPSEEK2: @@ -1563,6 +1601,7 @@ bool llama_arch_supports_save(llm_arch arch) { case LLM_ARCH_APERTUS: case LLM_ARCH_STEP35: case LLM_ARCH_CLEF: // the head tensors are not saved + case LLM_ARCH_INKLING2_LOOP: // the loop tensors are not saved and the cache slots are expanded at load case LLM_ARCH_VLLM_DECISION2: return false; default: diff --git a/src/llama-arch.h b/src/llama-arch.h index 9c517a9fe15d..6517a3ea7ea9 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -177,6 +177,7 @@ enum llm_arch { LLM_ARCH_NANBEIGE, LLM_ARCH_QWEN3TTS, LLM_ARCH_POCKETTTS, + LLM_ARCH_MOSHI, LLM_ARCH_ZONOS3, LLM_ARCH_KOKORO, LLM_ARCH_TINY_VOCA, @@ -188,6 +189,8 @@ enum llm_arch { LLM_ARCH_LIMITE, LLM_ARCH_RICURSIVE, LLM_ARCH_INKLING2, + LLM_ARCH_INKLING2_LOOP, + LLM_ARCH_DOMYN_EDGE, LLM_ARCH_UNKNOWN, }; @@ -288,6 +291,11 @@ enum llm_kv { LLM_KV_HRM_H_CYCLES, LLM_KV_HRM_L_CYCLES, LLM_KV_HRM_PREFIX_LM, + LLM_KV_LOOP_START, + LLM_KV_LOOP_END, + LLM_KV_LOOP_COUNT, + LLM_KV_LOOP_GATE_RANK, + LLM_KV_LOOP_VARYING, LLM_KV_METIS_PASS_COUNT, LLM_KV_METIS_MEMORY_LENGTH, LLM_KV_METIS_ROUTE_LENGTH, @@ -609,6 +617,19 @@ enum llm_tensor { LLM_TENSOR_FFN_LATENT_UP, LLM_TENSOR_FFN_POST_CONV, LLM_TENSOR_FFN_RES_QUERY, + LLM_TENSOR_LOOP_MSG_QUERY, + LLM_TENSOR_LOOP_Q_CTRL_DOWN, + LLM_TENSOR_LOOP_Q_CTRL_GAIN, + LLM_TENSOR_LOOP_Q_CTRL_FORGET, + LLM_TENSOR_LOOP_K_CTRL_DOWN, + LLM_TENSOR_LOOP_K_CTRL_GAIN, + LLM_TENSOR_LOOP_K_CTRL_FORGET, + LLM_TENSOR_LOOP_V_CTRL_DOWN, + LLM_TENSOR_LOOP_V_CTRL_GAIN, + LLM_TENSOR_LOOP_V_CTRL_FORGET, + LLM_TENSOR_LOOP_FFN_CTRL_DOWN, + LLM_TENSOR_LOOP_FFN_CTRL_GAIN, + LLM_TENSOR_LOOP_FFN_CTRL_FORGET, LLM_TENSOR_STREAM_EMBD, LLM_TENSOR_DEPTH_MEM_STATE_WRITE, LLM_TENSOR_DEPTH_MEM_META_WRITE, diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 971a34499ca2..6b5e2efb2334 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -136,12 +136,6 @@ static const llm_fused_op_probe llm_fused_op_flash_attn_kv_rows_probe = { /*.n_tokens_per_seq =*/ 1, }; -static const llm_fused_op_probe llm_fused_op_lid_probe = { - /*.op =*/ LLM_FUSED_OP_LIGHTNING_INDEXER, - /*.name =*/ "Lightning Indexer", - /*.n_tokens_per_seq =*/ 1, -}; - static const llm_fused_op_probe llm_fused_op_dsv4_hc_pre_probe = { /*.op =*/ LLM_FUSED_OP_DSV4_HC_PRE, /*.name =*/ "fused DeepSeek V4 HC pre", @@ -334,9 +328,6 @@ llama_context::llama_context( cparams.auto_fa = false; } - cparams.fused_lid = true; - cparams.auto_flid = false; - cparams.fused_dsv4_hc_pre = true; cparams.fused_dsv4_hc_comb = true; cparams.fused_dsv4_hc_post = true; @@ -729,12 +720,6 @@ void llama_context::resolve_fused_ops(const llama_memory_context_i * mctx, uint3 cparams.auto_fkvr = false; } - if (cparams.auto_flid) { - LLAMA_LOG_INFO("%s: resolving fused Lightning Indexer support:\n", func); - resolve(llm_fused_op_lid_probe, cparams.fused_lid); - cparams.auto_flid = false; - } - if (cparams.auto_fhc) { LLAMA_LOG_INFO("%s: resolving fused DeepSeek V4 HC support:\n", func); resolve(llm_fused_op_dsv4_hc_pre_probe, cparams.fused_dsv4_hc_pre); @@ -2968,42 +2953,15 @@ void llama_context::output_reorder() { // uint32_t llama_context::graph_max_nodes() const { - uint32_t res; - if (model.arch == LLM_ARCH_KIMI_K3 || model.arch == LLM_ARCH_KIMI_K31 || model.arch == LLM_ARCH_GLM5_NEXT || - model.arch == LLM_ARCH_HRM_TEXT) { - res = std::max(1024u, 64u * model.n_tensors()); - } else if (model.arch == LLM_ARCH_QWEN3NEXT || - model.arch == LLM_ARCH_KIMI_LINEAR || - model.arch == LLM_ARCH_METIS16 || - model.arch == LLM_ARCH_BAILINGMOE3 || - model.arch == LLM_ARCH_QWEN35 || - model.arch == LLM_ARCH_QWEN35MOE || - model.arch == LLM_ARCH_ZONOS3 || - model.arch == LLM_ARCH_CLEF || - model.arch == LLM_ARCH_CLOVER_MOE || - model.arch == LLM_ARCH_QWEN4EXP || - model.arch == LLM_ARCH_DEEPSEEK4 || - model.arch == LLM_ARCH_DEEPSEEK41 || - model.arch == LLM_ARCH_XING4_0 || - (model.arch == LLM_ARCH_DFLASH && model.hparams.dsv4_hc_mult > 0) || - model.arch == LLM_ARCH_NANBEIGE || - model.arch == LLM_ARCH_MINIMAX_01 || - model.arch == LLM_ARCH_MINIMAX_M3 || - model.arch == LLM_ARCH_HY_V4 || - model.arch == LLM_ARCH_INKLING2) { - res = std::max(1024u, 32u * model.n_tensors()); - } else if (model.arch == LLM_ARCH_DFLASH && model.hparams.dflash_selector_rank > 0) { - // DFlash2's convolutions and selector are shape work rather than matmuls, - // so they cost ~8.6 nodes per tensor against ~5.9 for a plain DFlash draft. - // The selector lattice scales with the draft block size; 12u was calibrated - // on block-8 drafters, so scale the budget for larger blocks (e.g. Ripple's 16). - const uint32_t block_scale = std::max(1u, model.hparams.dflash_block_size/8u); - res = std::max(1024u, 12u*block_scale*model.n_tensors()); - } else { - res = std::max(1024u, 8u*model.n_tensors()); - for (const auto & lora : model.loras) { - res += lora->get_n_nodes(); - } + uint32_t res = std::max(1024u, model.graph_nodes_per_tensor()*model.n_tensors()); + for (const auto & lora : model.loras) { + res += lora->get_n_nodes(); + } + + // the MoE cache adds a lookup to each MoE layer, and a second expert path with a CPU share (up to ~16 tensors per layer), + // which the per-tensor estimates above do not cover for models with few tensors per layer + if (cparams.moe_cache_size > 0) { + res += 32u*model.hparams.n_layer_all; } // every sampler builds n_outputs_max_per_seq chains, see llm_graph_context::build_sampling diff --git a/src/llama-cparams.h b/src/llama-cparams.h index 1f890d6fa9c4..c93494fafeb1 100644 --- a/src/llama-cparams.h +++ b/src/llama-cparams.h @@ -39,8 +39,6 @@ struct llama_cparams { bool offload_kqv; bool flash_attn; bool auto_fa; - bool fused_lid; // use fused lightning indexer - bool auto_flid; bool fused_dsv4_hc_pre; bool fused_dsv4_hc_comb; bool fused_dsv4_hc_post; diff --git a/src/llama-grammar.cpp b/src/llama-grammar.cpp index bb853b1e5bea..9a0de14307e5 100644 --- a/src/llama-grammar.cpp +++ b/src/llama-grammar.cpp @@ -668,6 +668,9 @@ const char * llama_grammar_parser::parse_sequence( if (max_times != UINT64_MAX && max_times > MAX_REPETITION_THRESHOLD) { max_times = UINT64_MAX; } + if (max_times < min_times) { + throw std::runtime_error(std::string("incorrect number of repetitions")); + } handle_repetitions(min_times, max_times); } else { break; diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 0cfbee73b3b5..86ecc13dc4bb 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -34,13 +34,14 @@ static ggml_tensor * build_attn_inp_kq_mask( ggml_context * ctx, const llama_kv_cache_context * mctx, const llama_ubatch & ubatch, - const llama_cparams & cparams) { + const llama_cparams & cparams, + bool force_f16 = false) { const auto n_kv = mctx->get_n_kv(); const auto n_tokens = ubatch.n_tokens; const auto n_stream = cparams.kv_unified ? 1 : ubatch.n_seqs_unq; - // flash attention requires an f16 mask - const auto type = cparams.flash_attn ? GGML_TYPE_F16 : GGML_TYPE_F32; + // flash attention and the lightning indexer require an f16 mask + const auto type = (cparams.flash_attn || force_f16) ? GGML_TYPE_F16 : GGML_TYPE_F32; ggml_tensor * res = ggml_new_tensor_4d(ctx, type, n_kv, n_tokens/n_stream, 1, n_stream); ggml_set_input(res); @@ -1150,7 +1151,7 @@ static void dsv4_build_comp_inputs( GGML_ASSERT(n_stream > 0); GGML_ASSERT(n_tokens%n_stream == 0); - inp.kq_mask = ggml_new_tensor_4d(ctx, (strcmp(name, "lid") != 0 && cparams.flash_attn) || (strcmp(name, "lid") == 0 && cparams.fused_lid) ? GGML_TYPE_F16 : GGML_TYPE_F32, plan.n_kv, n_tokens/n_stream, 1, n_stream); + inp.kq_mask = ggml_new_tensor_4d(ctx, (strcmp(name, "lid") == 0 || cparams.flash_attn) ? GGML_TYPE_F16 : GGML_TYPE_F32, plan.n_kv, n_tokens/n_stream, 1, n_stream); ggml_set_input(inp.kq_mask); ggml_set_name(inp.kq_mask, (std::string("dsv4_") + name + "_kq_mask").c_str()); } @@ -1407,6 +1408,91 @@ bool llm_graph_input_mem_hybrid_iswa::can_reuse(const llm_graph_params & params) return res; } +void llm_graph_input_mem_hybrid_iswa_rel::set_input(const llama_ubatch * ubatch) { + const auto * attn_ctx = mctx->get_attn(); + + // base tensors may not be allocated if there are no non-SWA attention layers + if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { + attn_ctx->get_base()->set_input_k_idxs(inp_attn->self_k_idxs, ubatch); + attn_ctx->get_base()->set_input_v_idxs(inp_attn->self_v_idxs, ubatch); + } + + if (inp_attn->self_attn_mask.raw && inp_attn->self_attn_mask.raw->buffer) { + attn_ctx->get_base()->set_input_attn_mask(inp_attn->self_attn_mask, ubatch, cparams.causal_attn); + } + + if (self_rel_pos->buffer) { + attn_ctx->get_base()->set_input_relative_pos(self_rel_pos, ubatch, extent); + } + + // swa tensors may not be allocated if there are no SWA attention layers + if (inp_attn->self_k_idxs_swa && inp_attn->self_k_idxs_swa->buffer) { + attn_ctx->get_swa()->set_input_k_idxs(inp_attn->self_k_idxs_swa, ubatch); + attn_ctx->get_swa()->set_input_v_idxs(inp_attn->self_v_idxs_swa, ubatch); + } + + if (inp_attn->self_attn_mask_swa.raw && inp_attn->self_attn_mask_swa.raw->buffer) { + attn_ctx->get_swa()->set_input_attn_mask(inp_attn->self_attn_mask_swa, ubatch, cparams.causal_attn); + } + + if (self_rel_pos_swa->buffer) { + attn_ctx->get_swa()->set_input_relative_pos(self_rel_pos_swa, ubatch, extent_swa); + } + + const int64_t n_rs = mctx->get_recr()->get_n_rs(); + + if (inp_rs->s_copy) { + GGML_ASSERT(ggml_backend_buffer_is_host(inp_rs->s_copy->buffer)); + int32_t * data = (int32_t *) inp_rs->s_copy->data; + + // assuming copy destinations ALWAYS happen ONLY on the cells between head and head+n + for (uint32_t i = 0; i < n_rs; ++i) { + data[i] = mctx->get_recr()->s_copy(i); + } + } +} + +bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & params) { + const auto * mctx = static_cast(params.mctx); + + this->mctx = mctx; + + bool res = true; + + const auto * attn_ctx = mctx->get_attn(); + + // the masks are always dense, see build_inp_mem_hybrid_iswa_rel() + + // base tensors may not be allocated if there are no non-SWA attention layers + if (inp_attn->self_k_idxs && inp_attn->self_k_idxs->buffer) { + res &= inp_attn->self_k_idxs->ne[0] == params.ubatch.n_tokens; + } + + res &= can_reuse_kq_mask(inp_attn->self_attn_mask.raw, attn_ctx->get_base(), params.ubatch, params.cparams); + + res &= self_rel_pos->ne[0] == attn_ctx->get_base()->get_n_kv(); + res &= self_rel_pos->ne[1] == params.ubatch.n_tokens; + + // swa tensors may not be allocated if there are no SWA attention layers + if (inp_attn->self_k_idxs_swa && inp_attn->self_k_idxs_swa->buffer) { + res &= inp_attn->self_k_idxs_swa->ne[0] == params.ubatch.n_tokens; + } + + res &= can_reuse_kq_mask(inp_attn->self_attn_mask_swa.raw, attn_ctx->get_swa(), params.ubatch, params.cparams); + + res &= self_rel_pos_swa->ne[0] == attn_ctx->get_swa()->get_n_kv(); + res &= self_rel_pos_swa->ne[1] == params.ubatch.n_tokens; + + res &= inp_rs->s_copy->ne[0] == mctx->get_recr()->get_n_rs(); + + res &= inp_rs->s_copy_main->ne[0] == params.ubatch.n_seqs; + + res &= inp_rs->head == mctx->get_recr()->get_head(); + res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z(); + + return res; +} + void llm_graph_input_sampling::set_input(const llama_ubatch * ubatch) { // set the inputs only for the active samplers in the current ubatch std::unordered_set active_samplers; @@ -1731,16 +1817,21 @@ ggml_tensor * llm_graph_context::build_lora_mm( ggml_tensor * w, ggml_tensor * cur, ggml_tensor * w_s) const { + if (!w_s) { + w_s = model.get_w_scale(w); + } + // a Hadamard-folded weight reads the transformed input; a LoRA delta lives in the primal basis and reads `cur` ggml_tensor * cur_mm = build_hadamard_input(w, cur); ggml_tensor * res = ggml_mul_mat(ctx0, w, cur_mm); - prec_policy.apply(res); - if (w->type == GGML_TYPE_NVFP4) { ggml_prec_set_acc(res, GGML_PREC_BF16); } + + prec_policy.apply(res); + if (w_s) { res = ggml_mul(ctx0, res, w_s); } @@ -1807,9 +1898,10 @@ ggml_tensor * llm_graph_context::build_lora_mm_id( ggml_tensor * w, // ggml_tensor * as ggml_tensor * cur, // ggml_tensor * b ggml_tensor * ids, - ggml_tensor * w_s, ggml_tensor * slots, bool cached) const { + ggml_tensor * w_s = model.get_w_scale(w); + // as in build_lora_mm: the folded weight reads the transformed input, the LoRA delta reads `cur` ggml_tensor * cur_mm = build_hadamard_input(w, cur); // the experts in the MoE cache are selected by their slots @@ -1817,12 +1909,13 @@ ggml_tensor * llm_graph_context::build_lora_mm_id( ggml_mul_mat_id(ctx0, w, cur_mm, ids) : ggml_mul_mat_id(ctx0, cached ? moe_cache->get_experts(w) : w, cur_mm, slots); - prec_policy.apply(res); - if (w->type == GGML_TYPE_NVFP4) { ggml_prec_set_acc(res, GGML_PREC_BF16); } + // after the NVFP4 default, so that the policy can request a higher precision + prec_policy.apply(res); + if (w_s) { const int64_t n_expert = w_s->ne[0]; const int64_t n_tokens = cur->ne[2]; @@ -2036,34 +2129,7 @@ ggml_tensor * llm_graph_context::build_ffn( int il) const { const llm_arch arch = model.arch; - // NVFP4 support is currently restricted to - // 1) LORA absence (*_s would be applied after LORA residual, which is incorrect) - // 2) bias absense (*_s would be applied after bias addition, which is incorrect) - // TODO: disambiguate LLM-architectural scales (which use *_s) from NVFP4 scale_2 (which also uses *_s currently) - auto has_lora = [this](ggml_tensor * w) { - if (!w) { - return false; - } - for (const auto & lora : *loras) { - if (lora.first->get_weight(w) != nullptr) { - return true; - } - } - return false; - }; - - auto is_scaled_low_precision = [](ggml_tensor * w) { - return w && (w->type == GGML_TYPE_NVFP4 || w->type == GGML_TYPE_F8_E4M3); - }; - - GGML_ASSERT(!up_s || !up_b || !is_scaled_low_precision(up)); - GGML_ASSERT(!gate_s || !gate_b || !is_scaled_low_precision(gate)); - GGML_ASSERT(!down_s || !down_b || !is_scaled_low_precision(down)); - GGML_ASSERT(!up_s || !is_scaled_low_precision(up) || !has_lora(up)); - GGML_ASSERT(!gate_s || !is_scaled_low_precision(gate) || !has_lora(gate)); - GGML_ASSERT(!down_s || !is_scaled_low_precision(down) || !has_lora(down)); - - ggml_tensor * tmp = up ? build_lora_mm(up, cur) : cur; + ggml_tensor * tmp = up ? build_lora_mm(up, cur, up_s) : cur; cb(tmp, "ffn_up", il); if (up_b) { @@ -2071,21 +2137,16 @@ ggml_tensor * llm_graph_context::build_ffn( cb(tmp, "ffn_up_b", il); } - if (up_s) { - tmp = ggml_mul(ctx0, tmp, up_s); - cb(tmp, "ffn_up_s", il); - } - if (gate) { switch (type_gate) { case LLM_FFN_SEQ: { - cur = build_lora_mm(gate, tmp); + cur = build_lora_mm(gate, tmp, gate_s); cb(cur, "ffn_gate", il); } break; case LLM_FFN_PAR: { - cur = build_lora_mm(gate, cur); + cur = build_lora_mm(gate, cur, gate_s); cb(cur, "ffn_gate", il); } break; } @@ -2095,11 +2156,6 @@ ggml_tensor * llm_graph_context::build_ffn( cb(cur, "ffn_gate_b", il); } - if (gate_s) { - cur = ggml_mul(ctx0, cur, gate_s); - cb(cur, "ffn_gate_s", il); - } - } else { cur = tmp; } @@ -2221,11 +2277,7 @@ ggml_tensor * llm_graph_context::build_ffn( } if (down) { - cur = build_lora_mm(down, cur); - if (arch == LLM_ARCH_GLM4 || arch == LLM_ARCH_GLM4_MOE || arch == LLM_ARCH_JAIS2) { - // GLM4, GLM4_MOE, and JAIS2 have numerical issues with F16 accumulators - ggml_prec_set_acc(cur, GGML_PREC_BF16); - } + cur = build_lora_mm(down, cur, down_s); } if (down_b) { @@ -2236,11 +2288,6 @@ ggml_tensor * llm_graph_context::build_ffn( cur = ggml_add(ctx0, cur, down_b); } - if (down_s) { - cur = ggml_mul(ctx0, cur, down_s); - cb(cur, "ffn_down_s", il); - } - return cur; } @@ -2260,9 +2307,6 @@ ggml_tensor * llm_graph_context::build_moe_ffn( int il, ggml_tensor * probs_in, ggml_tensor * gate_up_exps, - ggml_tensor * up_exps_s, - ggml_tensor * gate_exps_s, - ggml_tensor * down_exps_s, ggml_tensor * selected_experts_in, ggml_tensor * post_exp_norm, float post_exp_norm_eps) const { @@ -2283,9 +2327,6 @@ ggml_tensor * llm_graph_context::build_moe_ffn( probs_in, gate_up_exps, /* gate_up_exps_b */ nullptr, - up_exps_s, - gate_exps_s, - down_exps_s, selected_experts_in, post_exp_norm, post_exp_norm_eps @@ -2313,9 +2354,6 @@ ggml_tensor * llm_graph_context::build_moe_ffn( ggml_tensor * probs_in, ggml_tensor * gate_up_exps, ggml_tensor * gate_up_exps_b, - ggml_tensor * up_exps_s, - ggml_tensor * gate_exps_s, - ggml_tensor * down_exps_s, ggml_tensor * selected_experts_in, ggml_tensor * post_exp_norm, float post_exp_norm_eps) const { @@ -2328,10 +2366,6 @@ ggml_tensor * llm_graph_context::build_moe_ffn( if (probs_in == nullptr) { logits = build_lora_mm(gate_inp, cur); // [n_expert, n_tokens] - if (gating_op == LLAMA_EXPERT_GATING_FUNC_TYPE_SQRT_SOFTPLUS || hparams.expert_router_f32) { - // the reference computes the router in F32: https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash/blob/60d8d70770c6776ff598c94bb586a859a38244f1/inference/model.py#L565 - ggml_prec_set_acc(logits, GGML_PREC_F32); - } cb(logits, "ffn_moe_logits", il); } else { logits = probs_in; @@ -2504,13 +2538,9 @@ ggml_tensor * llm_graph_context::build_moe_ffn( if (gate_up_exps) { // merged gate_up path: one mul_mat_id, then split into gate and up views - ggml_tensor * gate_up = build_lora_mm_id(gate_up_exps, cur, ids, up_exps_s, mm_ids, cached); // [n_ff*2, n_expert_used, n_tokens] + ggml_tensor * gate_up = build_lora_mm_id(gate_up_exps, cur, ids, mm_ids, cached); // [n_ff*2, n_expert_used, n_tokens] cb(gate_up, "ffn_moe_gate_up", il); - if (up_exps_s) { - cb(gate_up, "ffn_moe_gate_up_scaled", il); - } - if (gate_up_exps_b) { gate_up = ggml_add_id(ctx0, gate_up, gate_up_exps_b, ids); cb(gate_up, "ffn_moe_gate_up_biased", il); @@ -2523,29 +2553,21 @@ ggml_tensor * llm_graph_context::build_moe_ffn( cb(up, "ffn_moe_up", il); } else { // separate gate and up path - up = build_lora_mm_id(up_exps, cur, ids, up_exps_s, mm_ids, cached); // [n_ff, n_expert_used, n_tokens] + up = build_lora_mm_id(up_exps, cur, ids, mm_ids, cached); // [n_ff, n_expert_used, n_tokens] cb(up, "ffn_moe_up", il); - if (up_exps_s) { - cb(up, "ffn_moe_up_scaled", il); - } - if (up_exps_b) { up = ggml_add_id(ctx0, up, up_exps_b, ids); cb(up, "ffn_moe_up_biased", il); } if (gate_exps) { - cur = build_lora_mm_id(gate_exps, cur, ids, gate_exps_s, mm_ids, cached); // [n_ff, n_expert_used, n_tokens] + cur = build_lora_mm_id(gate_exps, cur, ids, mm_ids, cached); // [n_ff, n_expert_used, n_tokens] cb(cur, "ffn_moe_gate", il); } else { cur = up; } - if (gate_exps_s) { - cb(cur, "ffn_moe_gate_scaled", il); - } - if (gate_exps_b) { cur = ggml_add_id(ctx0, cur, gate_exps_b, ids); cb(cur, "ffn_moe_gate_biased", il); @@ -2648,7 +2670,7 @@ ggml_tensor * llm_graph_context::build_moe_ffn( cur = amax_src1.res; } - ggml_tensor * experts = build_lora_mm_id(down_exps, cur, ids, down_exps_s, mm_ids, cached); // [n_embd, n_expert_used, n_tokens] + ggml_tensor * experts = build_lora_mm_id(down_exps, cur, ids, mm_ids, cached); // [n_embd, n_expert_used, n_tokens] //ggml_prec_set_src(experts, GGML_PREC_BF16, 1); // (see TODO above) cb(experts, "ffn_moe_down", il); @@ -2666,10 +2688,6 @@ ggml_tensor * llm_graph_context::build_moe_ffn( return (*static_cast(user_data))(cur, ids, mm_ids, cached); }, &build_experts); - if (down_exps_s) { - cb(experts, "ffn_moe_down_scaled", il); - } - if (down_exps_b) { experts = ggml_add_id(ctx0, experts, down_exps_b, selected_experts); cb(experts, "ffn_moe_down_biased", il); @@ -3120,7 +3138,7 @@ ggml_tensor * llm_graph_context::build_attn_mha( ggml_tensor * cur; - const bool use_flash_attn = cparams.flash_attn && kq_b == nullptr && (!sinks || ggml_is_vector(sinks)); + const bool use_flash_attn = cparams.flash_attn && kq_b == nullptr; GGML_ASSERT(use_flash_attn || kv_rows == nullptr); if (use_flash_attn) { GGML_ASSERT(kq_b == nullptr && "Flash attention does not support KQ bias yet"); @@ -3203,16 +3221,8 @@ ggml_tensor * llm_graph_context::build_attn_mha( cb(kq, "kq_plus_kq_b", il); } - if (sinks && !ggml_is_vector(sinks)) { - // Per-query sinks are extra logits with zero values. - const int64_t n_kv = kq->ne[0]; - kq = ggml_add(ctx0, ggml_scale(ctx0, kq, kq_scale), ggml_cast(ctx0, kq_mask, GGML_TYPE_F32)); - kq = ggml_soft_max(ctx0, ggml_concat(ctx0, kq, sinks, 0)); - kq = ggml_cont(ctx0, ggml_view_4d(ctx0, kq, n_kv, kq->ne[1], kq->ne[2], kq->ne[3], kq->nb[1], kq->nb[2], kq->nb[3], 0)); - } else { - kq = ggml_soft_max_ext(ctx0, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias); - ggml_soft_max_add_sinks(kq, sinks); - } + kq = ggml_soft_max_ext(ctx0, kq, kq_mask, kq_scale, hparams.f_max_alibi_bias); + ggml_soft_max_add_sinks(kq, sinks); cb(kq, "kq_soft_max", il); if (!v_trans) { @@ -3414,8 +3424,6 @@ ggml_tensor * llm_graph_context::build_attn( ggml_tensor * v_mla, // TODO: remove float kq_scale, int il) const { - const llm_arch arch = model.arch; - GGML_ASSERT(v_mla == nullptr); if (inp->self_k_rot[il]) { @@ -3472,16 +3480,7 @@ ggml_tensor * llm_graph_context::build_attn( } if (wo) { - if (arch == LLM_ARCH_GLM4 || arch == LLM_ARCH_GLM4_MOE || arch == LLM_ARCH_JAIS2) { - // GLM4, GLM4_MOE, and JAIS2 have numerical issues with F16 accumulators - cur = build_lora_mm(wo, cur); - ggml_prec_set_acc(cur, GGML_PREC_BF16); - if (wo_s) { - cur = ggml_mul(ctx0, cur, wo_s); - } - } else { - cur = build_lora_mm(wo, cur, wo_s); - } + cur = build_lora_mm(wo, cur, wo_s); } if (wo_b) { @@ -3532,8 +3531,6 @@ ggml_tensor * llm_graph_context::build_attn( ggml_tensor * v_mla, float kq_scale, int il) const { - const llm_arch arch = model.arch; - // these nodes are added to the graph together so that they are not reordered // by doing so, the number of splits in the graph is reduced // expand k later to enable rope fusion which directly writes into k-v cache @@ -3561,16 +3558,7 @@ ggml_tensor * llm_graph_context::build_attn( cb(cur, "kqv_out", il); if (wo) { - if (arch == LLM_ARCH_GLM4 || arch == LLM_ARCH_GLM4_MOE) { - // GLM4 and GLM4_MOE have numerical issues with F16 accumulators - cur = build_lora_mm(wo, cur); - ggml_prec_set_acc(cur, GGML_PREC_BF16); - if (wo_s) { - cur = ggml_mul(ctx0, cur, wo_s); - } - } else { - cur = build_lora_mm(wo, cur, wo_s); - } + cur = build_lora_mm(wo, cur, wo_s); } if (wo_b) { @@ -3694,7 +3682,9 @@ ggml_tensor * llm_graph_context::build_attn( return cur; } -ggml_tensor * llm_graph_context::build_attn( +// the iswa build_attn with the KQ mask and kv_rows given by the caller, which has to keep them in sync +static ggml_tensor * build_attn_iswa_impl( + const llm_graph_context & gctx, llm_graph_input_attn_kv_iswa * inp, ggml_tensor * wo, ggml_tensor * wo_b, @@ -3703,11 +3693,18 @@ ggml_tensor * llm_graph_context::build_attn( ggml_tensor * k_cur, ggml_tensor * v_cur, ggml_tensor * kq_b, + ggml_tensor * kq_mask, + ggml_tensor * kv_rows, ggml_tensor * sinks, ggml_tensor * v_mla, float kq_scale, - int il, - ggml_tensor * kq_mask) const { + int il) { + ggml_context * ctx0 = gctx.ctx0; + ggml_cgraph * gf = gctx.gf; + + const auto & hparams = gctx.hparams; + const auto & cparams = gctx.cparams; + const bool is_swa = hparams.is_swa(il); auto * k_rot = is_swa ? inp->self_k_rot_swa[il] : inp->self_k_rot[il]; @@ -3746,7 +3743,7 @@ ggml_tensor * llm_graph_context::build_attn( // whole seq fits into batch in training mode const bool use_kv_cur = cparams.training && k_cur && v_cur; if (use_kv_cur) { - GGML_ASSERT(mctx_cur->get_n_kv() == n_tokens); + GGML_ASSERT(mctx_cur->get_n_kv() == gctx.n_tokens); } const bool store_kv = !use_kv_cur || hparams.n_layer_kv_from_start >= 0; @@ -3764,25 +3761,20 @@ ggml_tensor * llm_graph_context::build_attn( ggml_build_forward_expand(gf, mctx_cur->cpy_v(ctx0, v_cur, v_idxs, il)); } - if (!kq_mask) { - kq_mask = is_swa ? inp->self_attn_mask_swa.raw : inp->self_attn_mask.raw; - } - const auto & kv_rows = is_swa ? inp->self_attn_mask_swa.rows : inp->self_attn_mask.rows; - ggml_tensor * q = q_cur; ggml_tensor * k = use_kv_cur ? k_cur : mctx_cur->get_k(ctx0, il); ggml_tensor * v = use_kv_cur ? v_cur : mctx_cur->get_v(ctx0, il); - ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il); + ggml_tensor * cur = gctx.build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il); cur = build_attn_scale_kv_output(ctx0, mctx_cur, cur, il); - cb(cur, "kqv_out", il); + gctx.cb(cur, "kqv_out", il); if (v_rot) { cur = llama_mul_mat_hadamard(ctx0, cur, v_rot); } if (wo) { - cur = build_lora_mm(wo, cur, wo_s); + cur = gctx.build_lora_mm(wo, cur, wo_s); } if (wo_b) { @@ -3796,6 +3788,27 @@ ggml_tensor * llm_graph_context::build_attn( return cur; } +ggml_tensor * llm_graph_context::build_attn( + llm_graph_input_attn_kv_iswa * inp, + ggml_tensor * wo, + ggml_tensor * wo_b, + ggml_tensor * wo_s, + ggml_tensor * q_cur, + ggml_tensor * k_cur, + ggml_tensor * v_cur, + ggml_tensor * kq_b, + ggml_tensor * sinks, + ggml_tensor * v_mla, + float kq_scale, + int il) const { + const bool is_swa = hparams.is_swa(il); + + const auto & kq_mask = is_swa ? inp->self_attn_mask_swa.raw : inp->self_attn_mask.raw; + const auto & kv_rows = is_swa ? inp->self_attn_mask_swa.rows : inp->self_attn_mask.rows; + + return build_attn_iswa_impl(*this, inp, wo, wo_b, wo_s, q_cur, k_cur, v_cur, kq_b, kq_mask, kv_rows, sinks, v_mla, kq_scale, il); +} + ggml_tensor * llm_graph_context::build_attn( llm_graph_input_attn_k_iswa * inp, ggml_tensor * wo, @@ -3940,11 +3953,7 @@ static std::unique_ptr build_attn_inp_k_dsa_impl( { inp->self_k_idxs_lid = mctx_cur->get_lid()->build_input_k_idxs(ctx0, ubatch); - // ensure that mask type matches fused lightning indexer use (requires f16 mask) - auto cparams_copy = cparams; - cparams_copy.flash_attn = cparams.fused_lid; - - inp->self_attn_mask_lid.raw = build_attn_inp_kq_mask(ctx0, mctx_cur->get_lid(), ubatch, cparams_copy); + inp->self_attn_mask_lid.raw = build_attn_inp_kq_mask(ctx0, mctx_cur->get_lid(), ubatch, cparams, true); inp->self_k_rot_lid = mctx_cur->get_lid()->get_k_rot(); } @@ -4348,14 +4357,14 @@ llm_graph_input_mem_hybrid_iswa * llm_graph_context::build_inp_mem_hybrid_iswa() inp_attn->self_k_idxs = attn_ctx->get_base()->build_input_k_idxs(ctx0, ubatch); inp_attn->self_v_idxs = attn_ctx->get_base()->build_input_v_idxs(ctx0, ubatch); - inp_attn->self_attn_mask.raw = build_attn_inp_kq_mask(ctx0, attn_ctx->get_base(), ubatch, cparams); + inp_attn->self_attn_mask = build_attn_inp_attn_mask(ctx0, attn_ctx->get_base(), ubatch, cparams); } { inp_attn->self_k_idxs_swa = attn_ctx->get_swa()->build_input_k_idxs(ctx0, ubatch); inp_attn->self_v_idxs_swa = attn_ctx->get_swa()->build_input_v_idxs(ctx0, ubatch); - inp_attn->self_attn_mask_swa.raw = build_attn_inp_kq_mask(ctx0, attn_ctx->get_swa(), ubatch, cparams); + inp_attn->self_attn_mask_swa = build_attn_inp_attn_mask(ctx0, attn_ctx->get_swa(), ubatch, cparams); } inp_attn->self_k_rot = attn_ctx->get_base()->get_k_rot(); @@ -4369,6 +4378,87 @@ llm_graph_input_mem_hybrid_iswa * llm_graph_context::build_inp_mem_hybrid_iswa() return (llm_graph_input_mem_hybrid_iswa *) res->add_input(std::move(inp)); } +llm_graph_input_mem_hybrid_iswa_rel * llm_graph_context::build_inp_mem_hybrid_iswa_rel( + uint32_t extent, + uint32_t extent_swa) const { + const auto * mctx_cur = static_cast(mctx); + + auto inp_rs = build_rs_inp_impl(ctx0, ubatch, mctx_cur->get_recr()); + + const auto * attn_ctx = mctx_cur->get_attn(); + + auto inp_attn = std::make_unique(hparams, cparams, attn_ctx); + + // dense masks: the bias is gathered by the distance to each cell of the K/V view + { + inp_attn->self_k_idxs = attn_ctx->get_base()->build_input_k_idxs(ctx0, ubatch); + inp_attn->self_v_idxs = attn_ctx->get_base()->build_input_v_idxs(ctx0, ubatch); + + inp_attn->self_attn_mask.raw = build_attn_inp_kq_mask(ctx0, attn_ctx->get_base(), ubatch, cparams); + } + + { + inp_attn->self_k_idxs_swa = attn_ctx->get_swa()->build_input_k_idxs(ctx0, ubatch); + inp_attn->self_v_idxs_swa = attn_ctx->get_swa()->build_input_v_idxs(ctx0, ubatch); + + inp_attn->self_attn_mask_swa.raw = build_attn_inp_kq_mask(ctx0, attn_ctx->get_swa(), ubatch, cparams); + } + + inp_attn->self_k_rot = attn_ctx->get_base()->get_k_rot(); + inp_attn->self_v_rot = attn_ctx->get_base()->get_v_rot(); + + inp_attn->self_k_rot_swa = attn_ctx->get_swa()->get_k_rot(); + inp_attn->self_v_rot_swa = attn_ctx->get_swa()->get_v_rot(); + + auto inp = std::make_unique(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur, extent, extent_swa); + + inp->self_rel_pos = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, attn_ctx->get_base()->get_n_kv(), ubatch.n_tokens); + ggml_set_input(inp->self_rel_pos); + ggml_set_name(inp->self_rel_pos, "attn_inp_rel_pos"); + + inp->self_rel_pos_swa = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, attn_ctx->get_swa()->get_n_kv(), ubatch.n_tokens); + ggml_set_input(inp->self_rel_pos_swa); + ggml_set_name(inp->self_rel_pos_swa, "attn_inp_rel_pos_swa"); + + return (llm_graph_input_mem_hybrid_iswa_rel *) res->add_input(std::move(inp)); +} + +ggml_tensor * llm_graph_context::build_attn( + llm_graph_input_mem_hybrid_iswa_rel * inp, + ggml_tensor * wo, + ggml_tensor * wo_b, + ggml_tensor * wo_s, + ggml_tensor * q_cur, + ggml_tensor * k_cur, + ggml_tensor * v_cur, + ggml_tensor * kq_b, + ggml_tensor * sinks, + float kq_scale, + int il) const { + const bool is_swa = hparams.is_swa(il); + + auto * inp_attn = inp->get_attn(); + + const auto & attn_mask = is_swa ? inp_attn->self_attn_mask_swa : inp_attn->self_attn_mask; + + // TODO: support kv_rows - fill the distances over the kv_rows cell lists and pass the rows to build_attn_mha, + // needs a kv_rows flash attention with a per-head mask (CUDA has none) + GGML_ASSERT(attn_mask.rows == nullptr); + + // a mask per head, in the dense layout of the input mask, which flash attention takes in F16 + ggml_tensor * kq_mask = attn_mask.raw; + if (kq_mask->type != GGML_TYPE_F32) { + kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F32); + } + kq_mask = ggml_add(ctx0, kq_b, kq_mask); + if (cparams.flash_attn) { + kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F16); + } + cb(kq_mask, "kq_mask_rel_pos", il); + + return build_attn_iswa_impl(*this, inp_attn, wo, wo_b, wo_s, q_cur, k_cur, v_cur, nullptr, kq_mask, nullptr, sinks, nullptr, kq_scale, il); +} + void llm_graph_context::build_dense_out( ggml_tensor * dense_2, ggml_tensor * dense_2_b, diff --git a/src/llama-graph.h b/src/llama-graph.h index 86b9e1d94727..56a323733c8f 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -49,7 +49,6 @@ enum llm_graph_type { enum llm_fused_op { LLM_FUSED_OP_FLASH_ATTN, LLM_FUSED_OP_FLASH_ATTN_KV_ROWS, - LLM_FUSED_OP_LIGHTNING_INDEXER, LLM_FUSED_OP_DSV4_HC_PRE, LLM_FUSED_OP_DSV4_HC_COMB, LLM_FUSED_OP_DSV4_HC_POST, @@ -781,6 +780,48 @@ class llm_graph_input_mem_hybrid_iswa : public llm_graph_input_i { const llama_memory_hybrid_iswa_context * mctx; }; +// hybrid iswa memory with a per-head attention bias that depends on the distance from the query to the cell (Inkling) +// the KQ masks are always dense (rows == nullptr) and are filled from the same cells as the distances, so that the bias +// gathered by distance lines up with the mask +class llm_graph_input_mem_hybrid_iswa_rel : public llm_graph_input_i { +public: + llm_graph_input_mem_hybrid_iswa_rel( + const llama_cparams & cparams, + std::unique_ptr inp_attn, + std::unique_ptr inp_rs, + const llama_memory_hybrid_iswa_context * mctx, + uint32_t extent, + uint32_t extent_swa) : + inp_attn(std::move(inp_attn)), + inp_rs(std::move(inp_rs)), + extent(extent), + extent_swa(extent_swa), + cparams(cparams), + mctx(mctx) { } + virtual ~llm_graph_input_mem_hybrid_iswa_rel() = default; + + void set_input(const llama_ubatch * ubatch) override; + + bool can_reuse(const llm_graph_params & params) override; + + std::unique_ptr inp_attn; + std::unique_ptr inp_rs; + + llm_graph_input_attn_kv_iswa * get_attn() const { return inp_attn.get(); } + llm_graph_input_rs * get_recr() const { return inp_rs.get(); } + + // distance from the token to the cell, extent for the empty, future and more distant cells + ggml_tensor * self_rel_pos = nullptr; // I32 [n_kv, n_batch] + ggml_tensor * self_rel_pos_swa = nullptr; // I32 [n_kv_swa, n_batch] + + const uint32_t extent; + const uint32_t extent_swa; + + const llama_cparams cparams; + + const llama_memory_hybrid_iswa_context * mctx; +}; + class llm_graph_input_sampling : public llm_graph_input_i { public: llm_graph_input_sampling(std::map samplers) : @@ -1148,6 +1189,7 @@ struct llm_graph_context { ggml_tensor * cur) const; // do mat_mul, while optionally apply lora and per-tensor scale + // w_s defaults to the weight scale of w ggml_tensor * build_lora_mm( ggml_tensor * w, ggml_tensor * cur, @@ -1159,7 +1201,6 @@ struct llm_graph_context { ggml_tensor * w, // ggml_tensor * as ggml_tensor * cur, // ggml_tensor * b ggml_tensor * ids, - ggml_tensor * w_s = nullptr, ggml_tensor * slots = nullptr, bool cached = true) const; @@ -1232,9 +1273,6 @@ struct llm_graph_context { int il, ggml_tensor * probs_in = nullptr, ggml_tensor * gate_up_exps = nullptr, - ggml_tensor * up_exps_s = nullptr, - ggml_tensor * gate_exps_s = nullptr, - ggml_tensor * down_exps_s = nullptr, ggml_tensor * selected_experts_in = nullptr, ggml_tensor * post_exp_norm = nullptr, float post_exp_norm_eps = 1e-5f) const; @@ -1260,9 +1298,6 @@ struct llm_graph_context { ggml_tensor * probs_in = nullptr, ggml_tensor * gate_up_exps = nullptr, ggml_tensor * gate_up_exps_b = nullptr, - ggml_tensor * up_exps_s = nullptr, - ggml_tensor * gate_exps_s = nullptr, - ggml_tensor * down_exps_s = nullptr, ggml_tensor * selected_experts_in = nullptr, ggml_tensor * post_exp_norm = nullptr, float post_exp_norm_eps = 1e-5f) const; @@ -1411,8 +1446,7 @@ struct llm_graph_context { ggml_tensor * sinks, // [n_head_q] ggml_tensor * v_mla, // [n_embd_head_v_mla, n_embd_head_v, n_head_v] float kq_scale, - int il, - ggml_tensor * kq_mask = nullptr) const; + int il) const; llm_graph_input_attn_k_iswa * build_attn_inp_k_iswa() const; @@ -1512,6 +1546,25 @@ struct llm_graph_context { llm_graph_input_mem_hybrid_iswa * build_inp_mem_hybrid_iswa() const; + // extent, extent_swa: the distance that the bias tables of the full and the SWA layers stop at + llm_graph_input_mem_hybrid_iswa_rel * build_inp_mem_hybrid_iswa_rel( + uint32_t extent, + uint32_t extent_swa) const; + + // kq_b is added to the KQ mask, after the KQ scale + ggml_tensor * build_attn( + llm_graph_input_mem_hybrid_iswa_rel * inp, + ggml_tensor * wo, + ggml_tensor * wo_b, + ggml_tensor * wo_s, + ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens] + ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens] + ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens] + ggml_tensor * kq_b, // [n_kv, n_tokens/n_stream, n_head_q, n_stream] + ggml_tensor * sinks, // [n_head_q] + float kq_scale, + int il) const; + // // pooling // diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index 74d6e276e93f..19d4d72e9d48 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -314,11 +314,8 @@ llama_kv_cache::llama_kv_cache( ggml_is_quantized(type_k) && hparams.n_embd_head_k() % 64 == 0; - // always create Hadamard rotation tensors for DeepSeek lightning indexers - if ((model.arch == LLM_ARCH_DEEPSEEK32 || model.arch == LLM_ARCH_DEEPSEEK4 || - model.arch == LLM_ARCH_GLM_DSA || model.arch == LLM_ARCH_DOTS3NOTE || - model.arch == LLM_ARCH_MISTRAL_LARGE4) && - hparams.n_embd_head_k_full == hparams.indexer_head_size) { + // always create Hadamard rotation tensors for lightning indexer keys + if (model.lid_k_hdmd() && hparams.n_embd_head_k_full == hparams.indexer_head_size) { attn_rot_k = true; } diff --git a/src/llama-memory-hybrid-idx.cpp b/src/llama-memory-hybrid-idx.cpp index 2e19576f19fe..0199c734e341 100644 --- a/src/llama-memory-hybrid-idx.cpp +++ b/src/llama-memory-hybrid-idx.cpp @@ -353,6 +353,7 @@ struct llama_memory_hybrid_idx_context::kpool_state { uint32_t generation = 0; uint32_t n_pool_real = 0; + uint32_t n_pool_ub = 0; // pools of the ubatch's sequences, the only ones the indexer scores uint32_t n_new = 0; uint32_t n_new_g = 1; // graph size of the new pool list, stable across decode steps }; @@ -496,6 +497,7 @@ llama_memory_hybrid_idx_context::llama_memory_hybrid_idx_context(llama_memory_hy const uint64_t n_pool_max = uint64_t(idx->get_size() / mem->get_kpool()) * idx->get_n_seq_max(); GGML_ASSERT(n_pool_max <= UINT32_MAX - 64); st.n_pool_real = std::max(st.n_pool_real, uint32_t(n_pool_max)); + st.n_pool_ub = st.n_pool_real; st.n_new = st.n_pool_real; st.n_new_g = std::max(st.n_new, 1u); kpool_st = std::make_unique(std::move(st)); @@ -687,6 +689,12 @@ void llama_memory_hybrid_idx_context::kpool_build_state(const llama_ubatch & uba } GGML_ASSERT(ip == st.is_new.size()); + // the indexer scores only the pools of the ubatch's sequences + st.n_pool_ub = 0; + for (uint32_t i = 0; i < ubatch.n_seqs_unq; ++i) { + st.n_pool_ub += (uint32_t) lay.seqs[ubatch.seq_id_unq[i]].pools.size(); + } + // in order mode a token's cell gives its rank, and the rank its pool: positions cannot, as an image shares one const bool by_order = mem->get_kpool_by_order(); const auto * sinfo = by_order ? &sinfos_kpool[i_cur] : nullptr; @@ -731,7 +739,7 @@ const llama_memory_hybrid_idx_context::kpool_state & llama_memory_hybrid_idx_con } uint32_t llama_memory_hybrid_idx_context::get_n_kpool() const { - return kpool_pad(kpool_cur().n_pool_real); + return kpool_pad(kpool_cur().n_pool_ub); } uint32_t llama_memory_hybrid_idx_context::get_n_kpool_new() const { @@ -761,7 +769,7 @@ void llama_memory_hybrid_idx_context::set_input_kpool(ggml_tensor * pool_cells, const bool by_order = mem->get_kpool_by_order(); - GGML_ASSERT(n_pool == kpool_pad(st.n_pool_real)); + GGML_ASSERT(n_pool == kpool_pad(st.n_pool_ub)); GGML_ASSERT(st.is_new.size() == st.n_pool_real); GGML_ASSERT(pool_mask->ne[0] == (int64_t) n_pool && pool_mask->ne[1] == (int64_t) n_tokens); GGML_ASSERT(tail_idxs->ne[0] == (int64_t) kpool - 1 && tail_idxs->ne[1] == (int64_t) n_tokens); @@ -783,7 +791,7 @@ void llama_memory_hybrid_idx_context::set_input_kpool(ggml_tensor * pool_cells, return (int64_t) sq.strm*kv_size + cell; }; - // Sequences present in this ubatch, pools of absent sequences must fall on the scatter sentinel row. + // Sequences present in this ubatch, only their pools are scored. std::vector seq_in_ub(LLAMA_MAX_SEQ, 0); for (uint32_t i = 0; i < n_tokens; ++i) { for (int32_t k = 0; k < ubatch->n_seq_id[i]; ++k) { @@ -846,27 +854,26 @@ void llama_memory_hybrid_idx_context::set_input_kpool(ggml_tensor * pool_cells, std::fill(npos, npos + 4*n_new_g, 0); } - uint32_t i_new = 0; + // the reps of all pools, the padded new entries must not write them + const int64_t n_cells = (int64_t) kv_size*n_stream_kv; + std::vector is_rep(n_new_g > n_new ? n_cells : 0, 0); + + uint32_t i_new = 0; + uint32_t ip_all = 0; for (llama_seq_id s = 0; s < LLAMA_MAX_SEQ; ++s) { const auto & sq = lay.seqs[s]; seq_pool_start[s] = (uint32_t) pool_end.size(); - const bool inert = n_stream_kv > 1 && !seq_in_ub[s]; - - for (size_t pi = 0; pi < sq.pools.size(); ++pi) { - const uint32_t j = sq.pools[pi]; - const uint32_t ip = (uint32_t) pool_end.size(); - GGML_ASSERT(ip + 1 < n_pool); + for (size_t pi = 0; pi < sq.pools.size(); ++pi, ++ip_all) { + const uint32_t j = sq.pools[pi]; // The pooled key lives in the last member's row. const uint32_t rep = sq.cells[j + kpool - 1].second; - pcell[ip] = (int32_t) gcell(sq, rep); - - for (uint32_t k = 0; k < kpool; ++k) { - pidx[(size_t) ip*kpool + k] = inert ? sentinel : (int32_t) sq.cells[j + k].second; + if (!is_rep.empty()) { + is_rep[gcell(sq, rep)] = 1; } - if (st.is_new[ip] == st.generation) { + if (st.is_new[ip_all] == st.generation) { GGML_ASSERT(i_new < n_new); for (uint32_t k = 0; k < kpool; ++k) { nidx[(size_t) i_new*kpool + k] = (int32_t) gcell(sq, sq.cells[j + k].second); @@ -884,23 +891,33 @@ void llama_memory_hybrid_idx_context::set_input_kpool(ggml_tensor * pool_cells, ++i_new; } + if (!seq_in_ub[s]) { + continue; + } + + const uint32_t ip = (uint32_t) pool_end.size(); + GGML_ASSERT(ip + 1 < n_pool); + + pcell[ip] = (int32_t) gcell(sq, rep); + for (uint32_t k = 0; k < kpool; ++k) { + pidx[(size_t) ip*kpool + k] = (int32_t) sq.cells[j + k].second; + } + pool_end.push_back(sq.cells[j + kpool - 1].first); } } GGML_ASSERT(i_new == n_new); + GGML_ASSERT(ip_all == st.n_pool_real && pool_end.size() == st.n_pool_ub); // Padded entries re-pool cells whose pooled slot is never read: only the reps of complete pools are read. // Each entry takes its own cell, entries sharing one would write it from several threads in the scatter. if (n_new_g > n_new) { - std::vector reps(pcell, pcell + pool_end.size()); - std::sort(reps.begin(), reps.end()); - int64_t pad_cell = 0; for (uint32_t i = n_new; i < n_new_g; ++i, ++pad_cell) { - while (std::binary_search(reps.begin(), reps.end(), pad_cell)) { + while (pad_cell < n_cells && is_rep[pad_cell]) { ++pad_cell; } - GGML_ASSERT(pad_cell < (int64_t) kv_size*n_stream_kv); + GGML_ASSERT(pad_cell < n_cells); for (uint32_t k = 0; k < kpool; ++k) { nidx[(size_t) i*kpool + k] = (int32_t) pad_cell; } diff --git a/src/llama-model.cpp b/src/llama-model.cpp index ac5266a42d2a..06eb7c929281 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -126,6 +126,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params return new llama_model_qwen3tts(params); case LLM_ARCH_POCKETTTS: return new llama_model_pockettts(params); + case LLM_ARCH_MOSHI: + return new llama_model_moshi(params); case LLM_ARCH_ZONOS3: return new llama_model_zonos3(params); case LLM_ARCH_KOKORO: @@ -326,6 +328,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params return new llama_model_falcon_h1(params); case LLM_ARCH_INKLING2: return new llama_model_inkling2(params); + case LLM_ARCH_INKLING2_LOOP: + return new llama_model_inkling2_loop(params); case LLM_ARCH_LFM2: return new llama_model_lfm2(params); case LLM_ARCH_LFM2MOE: @@ -394,6 +398,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params return new llama_model_k2_horizon(params); case LLM_ARCH_KOLIBRI1: return new llama_model_kolibri1(params); + case LLM_ARCH_DOMYN_EDGE: + return new llama_model_domyn_edge(params); default: throw std::runtime_error(std::string("unsupported model architecture: '") + llm_arch_name(arch) + "'"); } @@ -1404,12 +1410,19 @@ bool llama_prec_policy::apply(ggml_tensor * res) const { return false; } - const auto it = prec_src1.find(res->src[0]); - if (it == prec_src1.end()) { - return false; + bool applied = false; + + const auto it_acc = prec_acc.find(res->src[0]); + if (it_acc != prec_acc.end()) { + applied |= ggml_prec_set_acc(res, it_acc->second); } - return ggml_prec_set_src(res, it->second, 1); + const auto it_src1 = prec_src1.find(res->src[0]); + if (it_src1 != prec_src1.end()) { + applied |= ggml_prec_set_src(res, it_src1->second, 1); + } + + return applied; } void llama_prec_policy::load(llama_model_loader & ml, const llama_model & model) { @@ -1909,6 +1922,12 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) { } if (!layer.ffn_up_exps_s && layer.ffn_up_exps) { layer.ffn_up_exps_s = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "scale", i), {n_expert}, TENSOR_NOT_REQUIRED); + if (layer.ffn_up_exps_s && layer.ffn_gate_up_exps) { + throw std::runtime_error(format("ffn_up_exps.scale and ffn_gate_up_exps.weight both exist for layer %d", i)); + } + } + if (!layer.ffn_up_exps_s && layer.ffn_gate_up_exps) { + layer.ffn_up_exps_s = create_tensor(tn(LLM_TENSOR_FFN_GATE_UP_EXPS, "scale", i), {n_expert}, TENSOR_NOT_REQUIRED); } // recurrent / linear-attention weight scales (per-tensor, shape {1}) @@ -2009,6 +2028,7 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) { output_in_s = create_tensor(tn(LLM_TENSOR_OUTPUT, "input_scale"), {1}, TENSOR_NOT_REQUIRED); } } + post_arch_tensors(ml); } ml.done_getting_tensors(); @@ -2031,6 +2051,42 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) { } } + // map each weight to its ".scale" tensor: shape {1} for a 2D weight, {n_expert} for a 3D weight + { + auto ends_with = [](const std::string & str, const std::string & suffix) { + return str.size() >= suffix.size() && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0; + }; + std::unordered_map weights; + for (const auto & [name, cur] : tensors_by_name) { + if (ends_with(name, ".weight")) { + weights.emplace(name.substr(0, name.size() - 7), cur); + } + } + for (const auto & [name, s] : tensors_by_name) { + if (!ends_with(name, ".scale")) { + continue; + } + const auto it = weights.find(name.substr(0, name.size() - 6)); + if (it == weights.end()) { + continue; + } + ggml_tensor * w = it->second; + const bool ok = w->ne[3] == 1 && ggml_nelements(s) == w->ne[2] && s->ne[0] == w->ne[2]; + if (ok) { + w_scales.emplace(w, s); + } else { + LLAMA_LOG_DEBUG("%s: '%s' is not a weight scale for '%s', skipping\n", __func__, name.c_str(), w->name); + } + } + } + + // the reference computes the router in F32: https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash/blob/60d8d70770c6776ff598c94bb586a859a38244f1/inference/model.py#L565 + if (hparams.expert_gating_func == LLAMA_EXPERT_GATING_FUNC_TYPE_SQRT_SOFTPLUS || hparams.expert_router_f32) { + for (const auto & layer : layers) { + prec_policy.set_acc(layer.ffn_gate_inp, GGML_PREC_F32); + } + } + // per-tensor activation precision policy prec_policy.load(ml, *this); @@ -2562,6 +2618,11 @@ size_t llama_model::size() const { return pimpl->n_bytes; } +ggml_tensor * llama_model::get_w_scale(const ggml_tensor * w) const { + const auto it = w_scales.find(w); + return it == w_scales.end() ? nullptr : it->second; +} + size_t llama_model::n_tensors() const { return tensors_by_name.size(); } @@ -3143,6 +3204,27 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, /* filter_recr */ std::move(filter_recr), /* filter_idx */ std::move(filter_idx)); } break; + case LLM_ARCH_MOSHI: + { + // every layer attends to the same sliding window: one cache that masks it, the cells past the window are reused + res = new llama_kv_cache( + *this, + params.no_alloc, + hparams, + params.type_k, + params.type_v, + !cparams.flash_attn, + cparams.offload_kqv, + cparams.kv_unified, + cparams.n_ctx_seq, + cparams.n_seq_max, + hparams.n_swa, + LLAMA_SWA_TYPE_STANDARD, + nullptr, + nullptr, + nullptr, + nullptr); + } break; case LLM_ARCH_HY_V4: { if (hparams.indexer_top_k == 0) { @@ -3351,7 +3433,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, filter_idx = [&](uint32_t il) { return il < hparams.n_layer() && !hparams.is_recr(il) && hparams.is_indexer_full(il); }; - } else if (arch == LLM_ARCH_FALCON_H1 || arch == LLM_ARCH_INKLING2 || arch == LLM_ARCH_ZAYA1) { + } else if (arch == LLM_ARCH_FALCON_H1 || arch == LLM_ARCH_INKLING2 || arch == LLM_ARCH_INKLING2_LOOP || arch == LLM_ARCH_ZAYA1) { filter_attn = [&](uint32_t) { return true; }; filter_recr = [&](uint32_t) { return true; }; } else if (arch == LLM_ARCH_NEMOTRON_H || arch == LLM_ARCH_NEMOTRON_H_MOE) { @@ -3727,6 +3809,7 @@ llama_rope_type llama_model_rope_type(const llama_model * model) { case LLM_ARCH_GLM5_NEXT: case LLM_ARCH_STARCODER: case LLM_ARCH_INKLING2: + case LLM_ARCH_INKLING2_LOOP: case LLM_ARCH_KOKORO: return LLAMA_ROPE_TYPE_NONE; @@ -3777,6 +3860,7 @@ llama_rope_type llama_model_rope_type(const llama_model * model) { case LLM_ARCH_DOTS3NOTE: case LLM_ARCH_NANBEIGE: case LLM_ARCH_POCKETTTS: + case LLM_ARCH_MOSHI: case LLM_ARCH_ZONOS3: case LLM_ARCH_LIMITE: case LLM_ARCH_TINY_VOCA: @@ -3873,6 +3957,7 @@ llama_rope_type llama_model_rope_type(const llama_model * model) { case LLM_ARCH_HRM_TEXT: case LLM_ARCH_BEAM: case LLM_ARCH_KOLIBRI1: + case LLM_ARCH_DOMYN_EDGE: return LLAMA_ROPE_TYPE_NEOX; case LLM_ARCH_DFLASH: diff --git a/src/llama-model.h b/src/llama-model.h index 8d2f5629efae..eae5c68486ab 100644 --- a/src/llama-model.h +++ b/src/llama-model.h @@ -737,8 +737,7 @@ struct llama_meta_device_get_split_state_userdata { struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const struct ggml_tensor * tensor, void * userdata); struct llama_prec_policy { - // the key is the weight tensor `res->src[0]`, stores the recommended accumulation type of the op (unused for now) - // TODO: migrate ad-hoc ggml_prec_set_acc() calls to this container + update apply() to use it + // the key is the weight tensor `res->src[0]`, stores the recommended accumulation type of the op std::unordered_map prec_acc; // the key is the weight tensor `res->src[0]`, stores the recommended activation precision type @@ -746,6 +745,12 @@ struct llama_prec_policy { bool apply(ggml_tensor * res) const; + void set_acc(const ggml_tensor * w, ggml_prec prec) { + if (w) { + prec_acc[w] = prec; + } + } + void load(llama_model_loader & ml, const llama_model & model); }; @@ -818,6 +823,11 @@ struct llama_model { llama_hadamard hdmd; + // weight -> ".scale" tensor (e.g. NVFP4 scale2), applied by build_lora_mm and build_lora_mm_id + std::unordered_map w_scales; + + ggml_tensor * get_w_scale(const ggml_tensor * w) const; + // see llama_model_set_attn_rot bool attn_rot = true; @@ -1052,6 +1062,12 @@ struct llama_model { llama_memory_i * create_memory(const llama_memory_params & params, const llama_cparams & cparams) const; + // graph size budget: max graph nodes per model tensor + virtual uint32_t graph_nodes_per_tensor() const { return 8; } + + // apply Hadamard transform to the lightning indexer keys + virtual bool lid_k_hdmd() const { return false; } + ggml_cgraph * build_graph(const llm_graph_params & params) const; virtual void load_stats (llama_model_loader & ml) = 0; @@ -1064,6 +1080,9 @@ struct llama_model { virtual void load_arch_tensors(llama_model_loader & ml) = 0; virtual std::unique_ptr build_arch_graph(const llm_graph_params & params) const = 0; + // optional, runs after the scale pass + virtual void post_arch_tensors(llama_model_loader &) {} + protected: llama_model_params params; diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp index 79d964972831..0515756dcee9 100644 --- a/src/llama-quant.cpp +++ b/src/llama-quant.cpp @@ -340,12 +340,13 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param quantize &= name.find("mudd_") == std::string::npos; } - // inkling2: short conv kernels, clip scales, residual mix queries and the relative bias projection - if (arch == LLM_ARCH_INKLING2) { + // inkling2: short conv kernels, clip scales, residual mix queries, the relative bias projection and the loop tensors + if (arch == LLM_ARCH_INKLING2 || arch == LLM_ARCH_INKLING2_LOOP) { quantize &= name.find("_conv.weight") == std::string::npos; quantize &= name.find("_clip.weight") == std::string::npos; quantize &= name.find("_res_query.weight") == std::string::npos; quantize &= name.find("attn_rel_bias.weight") == std::string::npos; + quantize &= name.find(".loop_") == std::string::npos; } // zaya1: the top-1 router and the grouped conv kernels stay F32 diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp index 3aecacb516bc..f3e1d0192414 100644 --- a/src/llama-vocab.cpp +++ b/src/llama-vocab.cpp @@ -2566,7 +2566,8 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { tokenizer_pre == "qwen2" || tokenizer_pre == "deepseek-r1-qwen" || tokenizer_pre == "kormo" || - tokenizer_pre == "f2llmv2") { + tokenizer_pre == "f2llmv2" || + tokenizer_pre == "domyn-edge") { pre_type = LLAMA_VOCAB_PRE_TYPE_QWEN2; clean_spaces = false; } else if ( diff --git a/src/models/clef.cpp b/src/models/clef.cpp index 86fed4e874a8..c41c93cb138c 100644 --- a/src/models/clef.cpp +++ b/src/models/clef.cpp @@ -173,22 +173,35 @@ static clef_spans clef_get_spans(const llama_ubatch & ubatch) { return res; } +// the head always has the max number of spans, so its graph depends only on n_tokens +// each span has 1 token or more and each question has an option, so there is always a spare question for the padding options +static size_t clef_n_questions(int64_t n_tokens) { return n_tokens / 2 + 1; } +static size_t clef_n_options (int64_t n_tokens) { return std::max(n_tokens - 1, 1); } + // pooling matrices and indices computed from the spans class llama_model_clef::input_decision : public llm_graph_input_i { public: - input_decision(const llama_ubatch & ubatch) : n_tokens(ubatch.n_tokens) { - const auto spans = clef_get_spans(ubatch); - n_questions = spans.questions.size(); - n_options = spans.options.size(); - } + input_decision(const llama_ubatch & ubatch) : + n_tokens(ubatch.n_tokens), n_questions(clef_n_questions(n_tokens)), n_options(clef_n_options(n_tokens)) {} void set_input(const llama_ubatch * ubatch) override { // a batch of embeddings has no token ids, and no usable spans const std::vector no_tokens(ubatch->token ? 0 : n_tokens, 0); ggml_backend_tensor_set(tokens, ubatch->token ? ubatch->token : no_tokens.data(), 0, n_tokens * sizeof(llama_token)); - const auto spans = clef_get_spans(*ubatch); - GGML_ASSERT(spans.questions.size() == n_questions && spans.options.size() == n_options); + auto spans = clef_get_spans(*ubatch); + const int32_t n_q_used = spans.questions.size(); + GGML_ASSERT((size_t) n_q_used < n_questions && spans.options.size() <= n_options); + + // the padding options belong to the first padding question, the questions do not read the padding questions + spans.questions.resize(n_questions, { 0, 0, 0 }); + spans.options.resize(n_options, { n_q_used, 0, 0 }); + + std::vector q_mask(n_questions * n_questions, 0.0f); + for (size_t i = 0; i < n_questions; i++) { + std::fill(q_mask.begin() + i * n_questions + n_q_used, q_mask.begin() + (i + 1) * n_questions, -INFINITY); + } + ggml_backend_tensor_set(question_mask, q_mask.data(), 0, ggml_nbytes(question_mask)); // the scores are NaN if the batch has a decision order that cannot be used const float status_data = spans.valid || ubatch->decision_order == nullptr ? 0.0f : NAN; @@ -215,6 +228,8 @@ class llama_model_clef::input_decision : public llm_graph_input_i { owner[i] = o.question; mask[o.question * n_options + i] = 0.0f; } + // a padding question reads all options, a row of -inf gives NaN + std::fill(mask.begin() + n_q_used * n_options, mask.end(), 0.0f); ggml_backend_tensor_set(pool_q, pool_q_data.data(), 0, ggml_nbytes(pool_q)); ggml_backend_tensor_set(pool_o, pool_o_data.data(), 0, ggml_nbytes(pool_o)); @@ -225,8 +240,7 @@ class llama_model_clef::input_decision : public llm_graph_input_i { bool can_reuse(const llm_graph_params & params) override { // the values are computed again in set_input(), only the shapes must match - const auto spans = clef_get_spans(params.ubatch); - return spans.questions.size() == n_questions && spans.options.size() == n_options; + return params.ubatch.n_tokens == (uint32_t) n_tokens; } ggml_tensor * tokens = nullptr; // I32 [n_tokens] @@ -235,11 +249,12 @@ class llama_model_clef::input_decision : public llm_graph_input_i { ggml_tensor * question_type = nullptr; // I32 [n_questions] ggml_tensor * option_question = nullptr; // I32 [n_options] ggml_tensor * option_mask = nullptr; // F32 [n_options, n_questions], 0 if the option belongs to the question, else -inf + ggml_tensor * question_mask = nullptr; // F32 [n_questions, n_questions], -inf for the padding questions ggml_tensor * status = nullptr; // F32 [1], added to the scores: 0, or NaN on invalid input const int64_t n_tokens; - size_t n_questions; - size_t n_options; + const size_t n_questions; + const size_t n_options; }; // the backbone is copied from llama_model_qwen35::graph, without the memory module @@ -479,8 +494,8 @@ ggml_tensor * llama_model_clef::graph::build_head_norm(ggml_tensor * cur, const return build_norm(cur, n.w, n.b, LLM_NORM, -1); } -// q: [n_embd_h, n_q], kv: [n_embd_h, n_kv], no mask -ggml_tensor * llama_model_clef::graph::build_head_attn(ggml_tensor * q, ggml_tensor * kv, const attn & a) { +// q: [n_embd_h, n_q], kv: [n_embd_h, n_kv], kq_mask: [n_kv, n_q] or null +ggml_tensor * llama_model_clef::graph::build_head_attn(ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask) { const int64_t n_embd_h = q->ne[0]; const int64_t n_head_h = model.n_head_decision; const int64_t d_head = n_embd_h / n_head_h; @@ -497,7 +512,7 @@ ggml_tensor * llama_model_clef::graph::build_head_attn(ggml_tensor * q, ggml_ten Vcur = ggml_cont(ctx0, Vcur); ggml_tensor * kq = ggml_mul_mat(ctx0, Kcur, Qcur); // [n_kv, n_q, n_head] - kq = ggml_soft_max_ext(ctx0, kq, nullptr, 1.0f / sqrtf(float(d_head)), 0.0f); + kq = ggml_soft_max_ext(ctx0, kq, kq_mask, 1.0f / sqrtf(float(d_head)), 0.0f); ggml_tensor * cur = ggml_mul_mat(ctx0, Vcur, kq); // [d_head, n_q, n_head] cur = ggml_cont_2d(ctx0, ggml_permute(ctx0, cur, 0, 2, 1, 3), n_embd_h, n_q); @@ -523,8 +538,9 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de inp->question_type = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_questions); inp->option_question = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_options); inp->option_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_options, n_questions); + inp->question_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_questions, n_questions); inp->status = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1); - for (ggml_tensor * t : { inp->tokens, inp->pool_q, inp->pool_o, inp->question_type, inp->option_question, inp->option_mask, inp->status }) { + for (ggml_tensor * t : { inp->tokens, inp->pool_q, inp->pool_o, inp->question_type, inp->option_question, inp->option_mask, inp->question_mask, inp->status }) { ggml_set_input(t); } @@ -584,7 +600,7 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de const auto & layer = model.head_layers[il]; ggml_tensor * cur = build_head_norm(fields, layer.self_norm); - fields = ggml_add(ctx0, fields, build_head_attn(cur, cur, layer.self_attn)); + fields = ggml_add(ctx0, fields, build_head_attn(cur, cur, layer.self_attn, inp->question_mask)); cur = build_head_norm(fields, layer.cross_norm); fields = ggml_add(ctx0, fields, build_head_attn(cur, memory, layer.cross_attn)); diff --git a/src/models/clover-moe.cpp b/src/models/clover-moe.cpp index e51242616fe8..83d98ebbf3e4 100644 --- a/src/models/clover-moe.cpp +++ b/src/models/clover-moe.cpp @@ -384,10 +384,7 @@ ggml_tensor * llama_model_clover_moe::graph::build_layer_ffn(ggml_tensor * cur, LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, il, - nullptr, model.layers[il].ffn_gate_up_exps, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + nullptr, model.layers[il].ffn_gate_up_exps); cb(moe_out, "ffn_moe_out", il); if (model.layers[il].ffn_up_shexp != nullptr) { diff --git a/src/models/cohere2moe.cpp b/src/models/cohere2moe.cpp index 52b959672dfa..c4d778e5050d 100644 --- a/src/models/cohere2moe.cpp +++ b/src/models/cohere2moe.cpp @@ -226,10 +226,7 @@ llama_model_cohere2moe::graph::graph(const llm_graph_params & params) : llm_grap hparams.expert_weights_scale, (llama_expert_gating_func_type) hparams.expert_gating_func, il, - nullptr, layer.ffn_gate_up_exps, - layer.ffn_up_exps_s, - layer.ffn_gate_exps_s, - layer.ffn_down_exps_s); + nullptr, layer.ffn_gate_up_exps); cb(cur, "ffn_moe_out", il); if (layer.ffn_up_shexp) { @@ -371,10 +368,7 @@ llama_model_cohere2moe::graph_mtp::graph_mtp(const llm_graph_params & params) : hparams.expert_weights_scale, (llama_expert_gating_func_type) hparams.expert_gating_func, il, - nullptr, layer.ffn_gate_up_exps, - layer.ffn_up_exps_s, - layer.ffn_gate_exps_s, - layer.ffn_down_exps_s); + nullptr, layer.ffn_gate_up_exps); cb(cur, "mtp_ffn_moe_out", il); if (layer.ffn_up_shexp) { diff --git a/src/models/deepseek32.cpp b/src/models/deepseek32.cpp index fc6207f8b3d0..8f6f34790df3 100644 --- a/src/models/deepseek32.cpp +++ b/src/models/deepseek32.cpp @@ -265,46 +265,8 @@ llama_model_deepseek32::graph::graph(const llm_graph_params & params) : indexer_weights = ggml_scale(ctx0, indexer_weights, 1.0f / sqrtf(float(n_embd_indexer_head * n_indexer_head))); cb(indexer_weights, "indexer_weights", il); - ggml_tensor * indexer_score = nullptr; - if (cparams.fused_lid) { - indexer_score = ggml_lightning_indexer(ctx0, indexer_q, indexer_k, indexer_weights, inp_attn_dsa->self_attn_mask_lid.raw); - cb(indexer_score, "indexer_score", il); - res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, indexer_score, il}); - } else { - // calculate indexer kq - indexer_q = ggml_permute(ctx0, indexer_q, 0, 2, 1, 3); - cb(indexer_q, "indexer_q", il); - indexer_k = ggml_permute(ctx0, indexer_k, 0, 2, 1, 3); - cb(indexer_k, "indexer_k", il); - - ggml_tensor * indexer_kq = ggml_mul_mat(ctx0, indexer_k, indexer_q); - cb(indexer_kq, "indexer_kq", il); - - // ReLU requires contiguous tensors - indexer_kq = ggml_cont(ctx0, ggml_permute(ctx0, indexer_kq, 2, 1, 0, 3)); - cb(indexer_kq, "indexer_kq", il); - - // apply ReLU - indexer_score = ggml_relu(ctx0, indexer_kq); - cb(indexer_score, "indexer_score", il); - - // multiply scores by indexer weights - indexer_score = ggml_mul(ctx0, indexer_score, indexer_weights); - cb(indexer_score, "indexer_score", il); - - // sum by q n_indexer_head dimension - indexer_score = ggml_sum_rows(ctx0, indexer_score); - cb(indexer_score, "indexer_score", il); - - // permute result to match KQ mask - indexer_score = ggml_cont(ctx0, ggml_permute(ctx0, indexer_score, 2, 1, 0, 3)); - cb(indexer_score, "indexer_score", il); - - // mask indexer scores - ggml_tensor * indexer_kq_mask = inp_attn_dsa->self_attn_mask_lid.raw; - indexer_score = ggml_add(ctx0, indexer_score, indexer_kq_mask); - cb(indexer_score, "indexer_score", il); - } + ggml_tensor * indexer_score = ggml_lightning_indexer(ctx0, indexer_q, indexer_k, indexer_weights, inp_attn_dsa->self_attn_mask_lid.raw); + cb(indexer_score, "indexer_score", il); // get indices of top k indexer scores uint32_t n_top_k = indexer_score->ne[0] < n_indexer_top_k ? indexer_score->ne[0] : n_indexer_top_k; @@ -421,10 +383,7 @@ llama_model_deepseek32::graph::graph(const llm_graph_params & params) : (llama_expert_gating_func_type) hparams.expert_gating_func, il, nullptr, - model.layers[il].ffn_gate_up_exps, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + model.layers[il].ffn_gate_up_exps); cb(moe_out, "ffn_moe_out", il); // FFN shared expert @@ -662,10 +621,7 @@ llama_model_deepseek32::graph_mtp::graph_mtp(const llm_graph_params & params) (llama_expert_gating_func_type) hparams.expert_gating_func, il, nullptr, - layer.ffn_gate_up_exps, - layer.ffn_up_exps_s, - layer.ffn_gate_exps_s, - layer.ffn_down_exps_s); + layer.ffn_gate_up_exps); cb(moe_out, "mtp_ffn_moe_out", il); // FFN shared expert diff --git a/src/models/deepseek4.cpp b/src/models/deepseek4.cpp index 69ebe5a603ec..f4269e0430e4 100644 --- a/src/models/deepseek4.cpp +++ b/src/models/deepseek4.cpp @@ -642,32 +642,8 @@ ggml_tensor * llama_model_deepseek4::graph::build_lid_top_k( indexer_weights->ne[0], indexer_weights->ne[1]/n_stream, indexer_weights->ne[2], n_stream, indexer_weights->nb[1], indexer_weights->nb[2]/n_stream, indexer_weights->nb[3]/n_stream, 0); - ggml_tensor * indexer_score = nullptr; - if (cparams.fused_lid) { - indexer_score = ggml_lightning_indexer(ctx0, indexer_q, indexer_k, indexer_weights, inp_lid.kq_mask); - cb(indexer_score, "lid_score_masked", il); - res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, indexer_score, il}); - } else { - indexer_q = ggml_permute(ctx0, indexer_q, 0, 2, 1, 3); - cb(indexer_q, "lid_q", il); - indexer_k = ggml_permute(ctx0, indexer_k, 0, 2, 1, 3); - cb(indexer_k, "lid_k", il); - - ggml_tensor * indexer_kq = ggml_mul_mat(ctx0, indexer_k, indexer_q); - cb(indexer_kq, "lid_kq", il); - - indexer_kq = ggml_cont(ctx0, ggml_permute(ctx0, indexer_kq, 2, 1, 0, 3)); - cb(indexer_kq, "lid_kq", il); - - indexer_score = ggml_relu(ctx0, indexer_kq); - indexer_score = ggml_mul(ctx0, indexer_score, indexer_weights); - indexer_score = ggml_sum_rows(ctx0, indexer_score); - indexer_score = ggml_cont(ctx0, ggml_permute(ctx0, indexer_score, 2, 1, 0, 3)); - cb(indexer_score, "lid_score", il); - - indexer_score = ggml_add(ctx0, indexer_score, inp_lid.kq_mask); - cb(indexer_score, "lid_score_masked", il); - } + ggml_tensor * indexer_score = ggml_lightning_indexer(ctx0, indexer_q, indexer_k, indexer_weights, inp_lid.kq_mask); + cb(indexer_score, "lid_score_masked", il); const uint32_t n_top_k = indexer_score->ne[0] < hparams.indexer_top_k ? indexer_score->ne[0] : hparams.indexer_top_k; ggml_tensor * top_k = ggml_cont(ctx0, ggml_top_k(ctx0, indexer_score, n_top_k)); @@ -1308,9 +1284,6 @@ llama_model_deepseek4::graph::graph(const llm_graph_params & params) : il, nullptr, nullptr, - nullptr, - nullptr, - nullptr, selected_experts); cb(moe_out, "ffn_moe_out", il); diff --git a/src/models/deepseek41.cpp b/src/models/deepseek41.cpp index 96de9041270c..e481cbd1de10 100644 --- a/src/models/deepseek41.cpp +++ b/src/models/deepseek41.cpp @@ -203,6 +203,8 @@ void llama_model_deepseek41::load_arch_tensors(llama_model_loader & ml) { } layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0); + // the reference computes the router in F32: https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash-1017/blob/1bae0e1088993b9b82de08f59de5be5a34e42170/inference/model.py#L813 + prec_policy.set_acc(layer.ffn_gate_inp, GGML_PREC_F32); layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, 0); layer.ffn_exp_probs_b_vl = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B_VL, "bias", i), {n_expert}, TENSOR_NOT_REQUIRED); layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0); @@ -533,7 +535,7 @@ ggml_tensor * llama_model_deepseek41::graph::build_attention41( ggml_tensor * ik = ggml_view_4d(ctx0, comp_all, n_idx_embd, 1, n_comp, n_stream, comp_all->nb[1], comp_all->nb[2], comp_all->nb[3], ggml_row_size(comp_all->type, n_embd_head)); // the fused indexer reads the strided view in place, the unfused path needs it contiguous; CUDA has no same-type copy of quantized views, so dequantize them - const bool fused_idx = sparse && cparams.fused_lid && ci.kq_mask->type == GGML_TYPE_F16; + const bool fused_idx = sparse && ci.kq_mask->type == GGML_TYPE_F16; if (ggml_is_quantized(ik->type)) { ik = ggml_cast(ctx0, ik, GGML_TYPE_F32); } else if (!fused_idx) { @@ -572,7 +574,6 @@ ggml_tensor * llama_model_deepseek41::graph::build_attention41( ggml_tensor * score = nullptr; if (fused_idx) { score = ggml_lightning_indexer(ctx0, iq, ik, iw, ci.kq_mask); - res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, score, il}); } else { ggml_tensor * iqc = ggml_view_4d(ctx0, iq, iq->ne[0], iq->ne[1], nc, n_stream, iq->nb[1], iq->nb[2], iq->nb[3], t0*iq->nb[2]); @@ -875,9 +876,7 @@ llama_model_deepseek41::graph::graph(const llm_graph_params & params) : cur = build_norm(cur, layer.ffn_norm, nullptr, LLM_NORM_RMS, il); cb(cur, "ffn_norm", il); - // the reference computes the router in F32: https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash-1017/blob/1bae0e1088993b9b82de08f59de5be5a34e42170/inference/model.py#L813 ggml_tensor * logits = build_lora_mm(layer.ffn_gate_inp, cur); - ggml_prec_set_acc(logits, GGML_PREC_F32); cb(logits, "ffn_moe_logits", il); // image (embedding) tokens use the vision router bias, as DeepSeek-V4 diff --git a/src/models/dflash.cpp b/src/models/dflash.cpp index 000222f4c0d1..98a8d1d9acec 100644 --- a/src/models/dflash.cpp +++ b/src/models/dflash.cpp @@ -125,6 +125,20 @@ void llama_model_dflash::load_arch_tensors(llama_model_loader &) { } } +uint32_t llama_model_dflash::graph_nodes_per_tensor() const { + if (hparams.dsv4_hc_mult > 0) { + return 32; + } + if (hparams.dflash_selector_rank > 0) { + // DFlash2's convolutions and selector are shape work rather than matmuls, + // so they cost ~8.6 nodes per tensor against ~5.9 for a plain DFlash draft. + // The selector lattice scales with the draft block size; 12u was calibrated + // on block-8 drafters, so scale the budget for larger blocks (e.g. Ripple's 16). + return 12u*std::max(1u, hparams.dflash_block_size/8u); + } + return llama_model_base::graph_nodes_per_tensor(); +} + void llama_model_dflash::load_tensors_layers_base() { LLAMA_LOAD_LOCALS; diff --git a/src/models/domyn-edge.cpp b/src/models/domyn-edge.cpp new file mode 100644 index 000000000000..6452894d34be --- /dev/null +++ b/src/models/domyn-edge.cpp @@ -0,0 +1,164 @@ +#include "models.h" + +void llama_model_domyn_edge::load_arch_hparams(llama_model_loader & ml) { + ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); + ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa); + // required: the base loader defaults it to n_rot_full if the key is not found + ml.get_key(LLM_KV_ROPE_DIMENSION_COUNT_SWA, hparams.n_rot_swa); + // RoPE cannot rotate more dims than the SWA head has: CPU aborts, GPU backends read past the row + if (hparams.n_rot_swa > hparams.n_embd_head_k_swa) { + throw std::runtime_error(format("invalid n_rot_swa: %u, max %u", hparams.n_rot_swa, hparams.n_embd_head_k_swa)); + } + + hparams.swa_type = LLAMA_SWA_TYPE_STANDARD; + + ml.get_arr(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, hparams.is_swa_impl); + ml.get_arr(LLM_KV_ATTENTION_ROPE_PATTERN, hparams.rope_pattern); + + // only for print_info / saver; get_rope_params uses cparams + hparams.rope_freq_base_train_swa = hparams.rope_freq_base_train; + hparams.rope_freq_scale_train_swa = hparams.rope_freq_scale_train; + + switch (hparams.n_layer()) { + case 36: type = LLM_TYPE_4B; break; + default: type = LLM_TYPE_UNKNOWN; + } +} + +void llama_model_domyn_edge::load_arch_tensors(llama_model_loader &) { + LLAMA_LOAD_LOCALS; + + tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0); + output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0); + output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED); + + // if output is NULL, init from the input tok embed + if (output == NULL) { + output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED); + } + + for (int i = 0; i < n_layer; ++i) { + auto & layer = layers[i]; + const int64_t n_embd_head_i = hparams.n_embd_head_k(i); + const int64_t n_embd_k_i = hparams.n_embd_k_gqa(i); + const int64_t n_embd_v_i = hparams.n_embd_v_gqa(i); + + layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0); + layer.attn_post_norm = create_tensor(tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), {n_embd}, 0); + + const int64_t n_embd_q_i = n_embd_head_i * n_head; + create_tensor_qkv(layer, i, n_embd, n_embd_q_i, n_embd_k_i, n_embd_v_i, 0); + layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head_i * n_head, n_embd}, 0); + + // K-norm has a learnable weight; Q-norm does not + layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head_i}, 0); + + layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0); + layer.ffn_post_norm = create_tensor(tn(LLM_TENSOR_FFN_POST_NORM, "weight", i), {n_embd}, 0); + + layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0); + layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0); + layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0); + } +} + +llama_rope_params llama_model_domyn_edge::get_rope_params(const llama_cparams & cparams, int il) const { + auto res = llama_model::get_rope_params(cparams, il); + + // the SWA layers use the global base and scale + res.freq_base = cparams.rope_freq_base; + res.freq_scale = cparams.rope_freq_scale; + + return res; +} + +llama_model_domyn_edge::graph::graph(const llm_graph_params & params) + : llm_graph_context(params) { + ggml_tensor * cur; + ggml_tensor * inpL = build_inp_embd(model.tok_embd); + ggml_tensor * inp_pos = build_inp_pos(); + + auto * inp_attn = build_attn_inp_kv_iswa(); + + ggml_tensor * inp_out_ids = build_inp_out_ids(); + + for (int il = 0; il < n_layer; ++il) { + const auto & layer = model.layers[il]; + const int64_t n_embd_head = hparams.n_embd_head_k(il); + const int64_t n_head_il = hparams.n_head(il); + const int64_t n_head_kv_il = hparams.n_head_kv(il); + const float kq_scale = 1.0f / sqrtf((float)n_embd_head); + + ggml_tensor * residual = inpL; + + // pre-attention norm + cur = build_norm(inpL, layer.attn_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "attn_norm", il); + + auto [Qcur, Kcur, Vcur] = build_qkv(layer, cur, n_embd_head, n_head_il, n_head_kv_il, il); + + // Q-norm: RMSNorm without learnable weight (elementwise_affine=False) + Qcur = build_norm(Qcur, NULL, NULL, LLM_NORM_RMS, il); + cb(Qcur, "Qcur_normed", il); + + // K-norm: RMSNorm with learnable weight + Kcur = build_norm(Kcur, layer.attn_k_norm, NULL, LLM_NORM_RMS, il); + cb(Kcur, "Kcur_normed", il); + + // build_rope already applies RoPE only if the current layer is a RoPE layer + Qcur = build_rope(Qcur, inp_pos, il); + cb(Qcur, "Qcur_rope", il); + + Kcur = build_rope(Kcur, inp_pos, il); + cb(Kcur, "Kcur_rope", il); + + cur = build_attn(inp_attn, + layer.wo, NULL, layer.wo_s, + Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il); + cb(cur, "attn_out", il); + + // post-attention norm applied to attn output before residual add + cur = build_norm(cur, layer.attn_post_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "attn_post_norm", il); + + if (il == n_layer - 1 && inp_out_ids) { + cur = ggml_get_rows(ctx0, cur, inp_out_ids); + residual = ggml_get_rows(ctx0, residual, inp_out_ids); + } + + ggml_tensor * ffn_inp = ggml_add(ctx0, cur, residual); + cb(ffn_inp, "ffn_inp", il); + + // pre-FFN norm + cur = build_norm(ffn_inp, layer.ffn_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "ffn_norm", il); + + // SwiGLU FFN + cur = build_ffn(cur, + layer.ffn_up, NULL, NULL, + layer.ffn_gate, NULL, NULL, + layer.ffn_down, NULL, NULL, NULL, + LLM_FFN_SILU, LLM_FFN_PAR, il); + cb(cur, "ffn_out", il); + + // post-FFN norm applied to ffn output before residual add + cur = build_norm(cur, layer.ffn_post_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "ffn_post_norm", il); + + cur = ggml_add(ctx0, cur, ffn_inp); + inpL = build_cvec(cur, il); + cb(inpL, "l_out", il); + } + + cur = build_norm(inpL, model.output_norm, NULL, LLM_NORM_RMS, -1); + cb(cur, "result_norm", -1); + res->t_embd = cur; + + cur = build_lora_mm(model.output, cur, model.output_s); + cb(cur, "result_output", -1); + res->t_logits = cur; +} + +std::unique_ptr llama_model_domyn_edge::build_arch_graph(const llm_graph_params & params) const { + return std::make_unique(params); +} diff --git a/src/models/dots3note.cpp b/src/models/dots3note.cpp index a6fccd58f1d6..2a2d5500b992 100644 --- a/src/models/dots3note.cpp +++ b/src/models/dots3note.cpp @@ -257,42 +257,8 @@ llama_model_dots3note::graph::graph(const llm_graph_params & params) : indexer_weights = ggml_scale(ctx0, indexer_weights, 1.0f / sqrtf(float(n_embd_indexer_head * n_indexer_head))); cb(indexer_weights, "indexer_weights", il); - ggml_tensor * indexer_score = nullptr; - if (cparams.fused_lid) { - indexer_score = ggml_lightning_indexer(ctx0, indexer_q, indexer_k, indexer_weights, inp_attn->get_dsa()->self_attn_mask_lid.raw); - cb(indexer_score, "indexer_score", il); - res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, indexer_score, il}); - } else { - indexer_q = ggml_permute(ctx0, indexer_q, 0, 2, 1, 3); - cb(indexer_q, "indexer_q", il); - indexer_k = ggml_permute(ctx0, indexer_k, 0, 2, 1, 3); - cb(indexer_k, "indexer_k", il); - - ggml_tensor * indexer_kq = ggml_mul_mat(ctx0, indexer_k, indexer_q); - cb(indexer_kq, "indexer_kq", il); - - // ReLU requires contiguous tensors - indexer_kq = ggml_cont(ctx0, ggml_permute(ctx0, indexer_kq, 2, 1, 0, 3)); - cb(indexer_kq, "indexer_kq", il); - - indexer_score = ggml_relu(ctx0, indexer_kq); - cb(indexer_score, "indexer_score", il); - - indexer_score = ggml_mul(ctx0, indexer_score, indexer_weights); - cb(indexer_score, "indexer_score", il); - - // sum by q n_indexer_head dimension - indexer_score = ggml_sum_rows(ctx0, indexer_score); - cb(indexer_score, "indexer_score", il); - - // permute result to match KQ mask - indexer_score = ggml_cont(ctx0, ggml_permute(ctx0, indexer_score, 2, 1, 0, 3)); - cb(indexer_score, "indexer_score", il); - - ggml_tensor * indexer_kq_mask = inp_attn->get_dsa()->self_attn_mask_lid.raw; - indexer_score = ggml_add(ctx0, indexer_score, indexer_kq_mask); - cb(indexer_score, "indexer_score", il); - } + ggml_tensor * indexer_score = ggml_lightning_indexer(ctx0, indexer_q, indexer_k, indexer_weights, inp_attn->get_dsa()->self_attn_mask_lid.raw); + cb(indexer_score, "indexer_score", il); // get indices of top k indexer scores uint32_t n_top_k = indexer_score->ne[0] < n_indexer_top_k ? indexer_score->ne[0] : n_indexer_top_k; @@ -435,10 +401,7 @@ llama_model_dots3note::graph::graph(const llm_graph_params & params) : (llama_expert_gating_func_type) hparams.expert_gating_func, il, nullptr, - model.layers[il].ffn_gate_up_exps, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + model.layers[il].ffn_gate_up_exps); cb(moe_out, "ffn_moe_out", il); ggml_tensor * ffn_shexp = diff --git a/src/models/flint.cpp b/src/models/flint.cpp index 520334ce656f..173278b6f34c 100644 --- a/src/models/flint.cpp +++ b/src/models/flint.cpp @@ -158,10 +158,7 @@ llama_model_flint::graph::graph(const llm_graph_params & params) : LLM_FFN_SILU, hparams.expert_weights_norm, hparams.expert_weights_scale, (llama_expert_gating_func_type) hparams.expert_gating_func, - il, nullptr, nullptr, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + il); cb(moe_out, "ffn_moe_out", il); { diff --git a/src/models/gemma4.cpp b/src/models/gemma4.cpp index 3bd85895e7b9..bdb22f83faef 100644 --- a/src/models/gemma4.cpp +++ b/src/models/gemma4.cpp @@ -157,6 +157,29 @@ static ggml_tensor * gemma4_view_2d_slice(ggml_context * ctx0, ggml_tensor * x, return ggml_view_2d(ctx0, x, x->ne[0], x->ne[1], x->nb[1], idx * x->nb[2]); } +class llm_graph_input_gemma4_prune : public llm_graph_input_i { + int64_t n_slices; + int64_t n_slice_tokens; + int64_t n_slice_outputs; +public: + ggml_tensor * full_mask = nullptr; + ggml_tensor * full_mask_swa = nullptr; + ggml_tensor * out_mask = nullptr; + ggml_tensor * out_mask_swa = nullptr; + ggml_tensor * inp_prune_ids = nullptr; + ggml_tensor * inp_prune_keep = nullptr; + llm_graph_input_gemma4_prune(int64_t n_slices, int64_t n_slice_tokens, int64_t n_slice_outputs) + : n_slices(n_slices), n_slice_tokens(n_slice_tokens), n_slice_outputs(n_slice_outputs) {} + + void set_input(const llama_ubatch * ubatch) override; + + bool can_reuse(const llm_graph_params & params) override; + + static int64_t max_outputs_per_slice( + const llama_ubatch & ubatch, int64_t n_slices, int64_t n_slice_tokens + ); +}; + llama_model_gemma4::graph::graph(const llm_graph_params & params) : llm_graph_context(params), n_embd_per_layer(model.hparams.n_embd_per_layer) { @@ -181,11 +204,8 @@ llama_model_gemma4::graph::graph(const llm_graph_params & params) : // TODO: is causal == true correct? might need some changes auto * inp_attn = build_attn_inp_kv_iswa(); - auto inp_attn_full = *inp_attn; auto inp_attn_prune = *inp_attn; - ggml_tensor * inp_out_ids = build_inp_out_ids(); - if (model.per_layer_tok_embd) { // fold per_layer_input_scale (1/sqrt(2)) from project_per_layer_inputs() into tok_embd_scale const float tok_embd_scale = sqrtf((float) n_embd_per_layer) / sqrtf(2.0f); @@ -197,34 +217,57 @@ llama_model_gemma4::graph::graph(const llm_graph_params & params) : inp_per_layer = project_per_layer_inputs(inpL, inp_per_layer); } + const bool needs_unmasked_nextn = + cparams.embeddings_nextn && !cparams.embeddings_nextn_masked; + // KV-shared layers do not write to the KV cache, so prune non-output token rows before the first KV-shared layer - bool prune_shared = crop_before_nextn(inp_out_ids) && + bool prune_shared = !needs_unmasked_nextn && hparams.n_layer_kv_from_start > 0 && hparams.n_layer_kv_from_start < n_layer && - !cparams.embeddings && cparams.n_seq_max == 1; + !cparams.embeddings; for (int il = (int) hparams.n_layer_kv_from_start; prune_shared && il <= n_layer; ++il) { prune_shared = !cparams.embeddings_layer_inp[il]; } int64_t n_rows = n_tokens; + ggml_tensor * inp_prune_ids = nullptr; + ggml_tensor * inp_prune_keep = nullptr; + ggml_tensor * inp_out_ids = prune_shared ? nullptr : build_inp_out_ids(); + for (int il = 0; il < n_layer; ++il) { if (prune_shared && il == (int) hparams.n_layer_kv_from_start) { - inpL = ggml_get_rows(ctx0, inpL, inp_out_ids); - inp_pos = ggml_reshape_1d(ctx0, ggml_get_rows(ctx0, ggml_reshape_2d(ctx0, inp_pos, 1, n_tokens), inp_out_ids), n_outputs); + ggml_tensor * full = inp_attn->self_attn_mask.raw; + ggml_tensor * full_swa = inp_attn->self_attn_mask_swa.raw; - // TODO: instead of doing get_rows here, extend llm_attn_mask to have a `out` mask that - // is construted during set_input to contain just the pruned output cells - // this can be used to enable pruning with more than 1 sequence, both with unified and split KV cache - // ref: https://github.com/ggml-org/llama.cpp/pull/31356#discussion_r4455286628 - inp_attn_prune.self_attn_mask.raw = ggml_get_rows(ctx0, inp_attn_full.self_attn_mask.raw, inp_out_ids); - inp_attn_prune.self_attn_mask_swa.raw = ggml_get_rows(ctx0, inp_attn_full.self_attn_mask_swa.raw, inp_out_ids); + const int64_t n_slices = full->ne[3], n_slice_tokens = full->ne[1]; + const int64_t n_slice_outputs = llm_graph_input_gemma4_prune::max_outputs_per_slice(ubatch, n_slices, n_slice_tokens); - inp_attn_prune.self_attn_mask.raw = ggml_cast(ctx0, inp_attn_prune.self_attn_mask.raw, GGML_TYPE_F16); - inp_attn_prune.self_attn_mask_swa.raw = ggml_cast(ctx0, inp_attn_prune.self_attn_mask_swa.raw, GGML_TYPE_F16); + n_rows = n_slices * n_slice_outputs; - n_rows = n_outputs; + auto prune_input = std::make_unique(n_slices, n_slice_tokens, n_slice_outputs); + prune_input->full_mask = full; + prune_input->full_mask_swa = full_swa; + prune_input->out_mask = ggml_new_tensor_4d(ctx0, full->type, full->ne[0], n_slice_outputs, 1, n_slices); + prune_input->out_mask_swa = ggml_new_tensor_4d(ctx0, full_swa->type, full_swa->ne[0], n_slice_outputs, 1, n_slices); + prune_input->inp_prune_ids = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_rows); + prune_input->inp_prune_keep = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_outputs); + ggml_set_input(prune_input->out_mask); + ggml_set_input(prune_input->out_mask_swa); + ggml_set_input(prune_input->inp_prune_ids); + ggml_set_input(prune_input->inp_prune_keep); + + inp_prune_ids = prune_input->inp_prune_ids; + inp_prune_keep = prune_input->inp_prune_keep; + + inpL = ggml_get_rows(ctx0, inpL, inp_prune_ids); + inp_pos = ggml_reshape_1d(ctx0, ggml_get_rows(ctx0, ggml_reshape_2d(ctx0, inp_pos, 1, n_tokens), inp_prune_ids), n_rows); + + inp_attn_prune.self_attn_mask.raw = prune_input->out_mask; + inp_attn_prune.self_attn_mask_swa.raw = prune_input->out_mask_swa; inp_attn = &inp_attn_prune; + + res->add_input(std::move(prune_input)); } const int64_t n_embd_head = hparams.n_embd_head_k(il); @@ -363,10 +406,7 @@ llama_model_gemma4::graph::graph(const llm_graph_params & params) : 1.0f, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, il, logits, - model.layers[il].ffn_gate_up_exps, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + model.layers[il].ffn_gate_up_exps); cur_moe = build_norm(cur_moe, model.layers[il].ffn_post_norm_2, nullptr, LLM_NORM_RMS, il); @@ -406,7 +446,9 @@ llama_model_gemma4::graph::graph(const llm_graph_params & params) : ggml_tensor * inp_this_layer = gemma4_view_2d_slice(ctx0, inp_per_layer, il); // [n_embd_per_layer, n_tokens] - if ((prune_shared && !hparams.has_kv(il)) || (il == n_layer - 1 && crop_before_nextn(inp_out_ids))) { + if (prune_shared && !hparams.has_kv(il)) { + inp_this_layer = ggml_get_rows(ctx0, inp_this_layer, inp_prune_ids); + } else if (il == n_layer - 1 && crop_before_nextn(inp_out_ids)) { inp_this_layer = ggml_get_rows(ctx0, inp_this_layer, inp_out_ids); } @@ -433,6 +475,9 @@ llama_model_gemma4::graph::graph(const llm_graph_params & params) : inpL = cur; } cur = inpL; + if (prune_shared) { + cur = ggml_get_rows(ctx0, cur, inp_prune_keep); + } cur = build_norm(cur, model.output_norm, nullptr, @@ -559,3 +604,89 @@ ggml_tensor * llama_model_gemma4::graph::project_per_layer_inputs(ggml_tensor * // permute to shape: [n_embd_per_layer, n_tokens, n_layer] return ggml_permute(ctx0, inp_per_layer, 0, 2, 1, 3); } + +void llm_graph_input_gemma4_prune::set_input(const llama_ubatch * ubatch) { + std::vector> selected(n_slices); + + for (int32_t s = 0; s < n_slices; ++s) { + for (int32_t t = 0; t < n_slice_tokens; ++t) { + const int32_t i = s * n_slice_tokens + t; + if (ubatch->output[i]) { + selected[s].push_back(i); + } + } + } + + std::vector take, keep; + for (int32_t s = 0; s < n_slices; ++s) { + const auto & ids = selected[s]; + + for (int32_t j = 0; j < int32_t(ids.size()); ++j) { + keep.push_back(s * n_slice_outputs + j); + } + + take.insert(take.end(), ids.begin(), ids.end()); + const int32_t dummy = ids.empty() ? s * n_slice_tokens : ids.back(); + take.insert(take.end(), n_slice_outputs - ids.size(), dummy); + } + + GGML_ASSERT(take.size() == size_t(inp_prune_ids->ne[0])); + if (!take.empty()) { + ggml_backend_tensor_set(inp_prune_ids, take.data(), 0, + take.size() * sizeof(int32_t)); + } + + auto copy_mask = [&](const ggml_tensor * full, ggml_tensor * out) { + if (take.empty() || !out->buffer) { + return; + } + + GGML_ASSERT(full->buffer && ggml_backend_buffer_is_host(full->buffer)); + const size_t row_bytes = full->ne[0] * ggml_element_size(full); + const auto * src = static_cast(full->data); + std::vector packed(take.size() * row_bytes); + + for (size_t j = 0; j < take.size(); ++j) { + memcpy(packed.data() + j * row_bytes, + src + take[j] * row_bytes, + row_bytes); + } + + ggml_backend_tensor_set(out, packed.data(), 0, packed.size()); + }; + + copy_mask(full_mask, out_mask); + copy_mask(full_mask_swa, out_mask_swa); + + if (!keep.empty()) { + ggml_backend_tensor_set( + inp_prune_keep, keep.data(), 0, + keep.size() * sizeof(int32_t)); + } +} + +bool llm_graph_input_gemma4_prune::can_reuse(const llm_graph_params & params) { + const auto & ubatch = params.ubatch; + + if (ubatch.n_tokens != n_slices * n_slice_tokens || !ubatch.output) { + return false; + } + + return max_outputs_per_slice(ubatch, n_slices, n_slice_tokens) == n_slice_outputs; +} + +int64_t llm_graph_input_gemma4_prune::max_outputs_per_slice(const llama_ubatch & ubatch, int64_t n_slices, int64_t n_slice_tokens) { + int64_t res = 0; + + for (int32_t s = 0; s < n_slices; ++s) { + int64_t m = 0; + for (int32_t t = 0; t < n_slice_tokens; ++t) { + const int32_t i = s * n_slice_tokens + t; + if (ubatch.output[i]) { + m++; + } + } + res = std::max(res, m); + } + return res; +} diff --git a/src/models/glm-dsa.cpp b/src/models/glm-dsa.cpp index 7007f427faeb..c0ff62e4a3ac 100644 --- a/src/models/glm-dsa.cpp +++ b/src/models/glm-dsa.cpp @@ -307,46 +307,8 @@ llama_model_glm_dsa::graph::graph(const llm_graph_params & params) : indexer_weights = ggml_scale(ctx0, indexer_weights, 1.0f / sqrtf(float(n_embd_indexer_head * n_indexer_head))); cb(indexer_weights, "indexer_weights", il); - ggml_tensor * indexer_score = nullptr; - if (cparams.fused_lid) { - indexer_score = ggml_lightning_indexer(ctx0, indexer_q, indexer_k, indexer_weights, inp_attn_dsa->self_attn_mask_lid.raw); - cb(indexer_score, "indexer_score", il); - res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, indexer_score, il}); - } else { - // calculate indexer kq - indexer_q = ggml_permute(ctx0, indexer_q, 0, 2, 1, 3); - cb(indexer_q, "indexer_q", il); - indexer_k = ggml_permute(ctx0, indexer_k, 0, 2, 1, 3); - cb(indexer_k, "indexer_k", il); - - ggml_tensor * indexer_kq = ggml_mul_mat(ctx0, indexer_k, indexer_q); - cb(indexer_kq, "indexer_kq", il); - - // ReLU requires contiguous tensors - indexer_kq = ggml_cont(ctx0, ggml_permute(ctx0, indexer_kq, 2, 1, 0, 3)); - cb(indexer_kq, "indexer_kq", il); - - // apply ReLU - indexer_score = ggml_relu(ctx0, indexer_kq); - cb(indexer_score, "indexer_score", il); - - // multiply scores by indexer weights - indexer_score = ggml_mul(ctx0, indexer_score, indexer_weights); - cb(indexer_score, "indexer_score", il); - - // sum by q n_indexer_head dimension - indexer_score = ggml_sum_rows(ctx0, indexer_score); - cb(indexer_score, "indexer_score", il); - - // permute result to match KQ mask - indexer_score = ggml_cont(ctx0, ggml_permute(ctx0, indexer_score, 2, 1, 0, 3)); - cb(indexer_score, "indexer_score", il); - - // mask indexer scores - ggml_tensor * indexer_kq_mask = inp_attn_dsa->self_attn_mask_lid.raw; - indexer_score = ggml_add(ctx0, indexer_score, indexer_kq_mask); - cb(indexer_score, "indexer_score", il); - } + ggml_tensor * indexer_score = ggml_lightning_indexer(ctx0, indexer_q, indexer_k, indexer_weights, inp_attn_dsa->self_attn_mask_lid.raw); + cb(indexer_score, "indexer_score", il); // get indices of top k indexer scores uint32_t n_top_k = indexer_score->ne[0] < n_indexer_top_k ? indexer_score->ne[0] : n_indexer_top_k; @@ -469,10 +431,7 @@ llama_model_glm_dsa::graph::graph(const llm_graph_params & params) : (llama_expert_gating_func_type) hparams.expert_gating_func, il, nullptr, - model.layers[il].ffn_gate_up_exps, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + model.layers[il].ffn_gate_up_exps); cb(moe_out, "ffn_moe_out", il); // FFN shared expert @@ -710,10 +669,7 @@ llama_model_glm_dsa::graph_mtp::graph_mtp(const llm_graph_params & params) (llama_expert_gating_func_type) hparams.expert_gating_func, il, nullptr, - layer.ffn_gate_up_exps, - layer.ffn_up_exps_s, - layer.ffn_gate_exps_s, - layer.ffn_down_exps_s); + layer.ffn_gate_up_exps); cb(moe_out, "mtp_ffn_moe_out", il); // FFN shared expert diff --git a/src/models/glm4-moe.cpp b/src/models/glm4-moe.cpp index 9560fd3d0429..a3e2fa46e4ef 100644 --- a/src/models/glm4-moe.cpp +++ b/src/models/glm4-moe.cpp @@ -113,6 +113,11 @@ void llama_model_glm4_moe::load_arch_tensors(llama_model_loader & ml) { layer.nextn.shared_head_head = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD, "weight", i), { n_embd, n_vocab }, TENSOR_NOT_REQUIRED | flags); layer.nextn.shared_head_norm = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, "weight", i), { n_embd }, TENSOR_NOT_REQUIRED | flags); } + + // numerical issues with F16 accumulators + prec_policy.set_acc(layer.wo, GGML_PREC_BF16); + prec_policy.set_acc(layer.ffn_down, GGML_PREC_BF16); + prec_policy.set_acc(layer.ffn_down_shexp, GGML_PREC_BF16); } } diff --git a/src/models/glm4.cpp b/src/models/glm4.cpp index e57c51cbe78e..5c50b2f055d2 100644 --- a/src/models/glm4.cpp +++ b/src/models/glm4.cpp @@ -58,6 +58,10 @@ void llama_model_glm4::load_arch_tensors(llama_model_loader &) { layer.nextn.shared_head_head = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD, "weight", i), { n_embd, n_vocab }, flags | TENSOR_NOT_REQUIRED); layer.nextn.shared_head_norm = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, "weight", i), { n_embd }, flags | TENSOR_NOT_REQUIRED); } + + // numerical issues with F16 accumulators + prec_policy.set_acc(layer.wo, GGML_PREC_BF16); + prec_policy.set_acc(layer.ffn_down, GGML_PREC_BF16); } } diff --git a/src/models/glm5-next.cpp b/src/models/glm5-next.cpp index 844a327b3dd2..51a26df3deaf 100644 --- a/src/models/glm5-next.cpp +++ b/src/models/glm5-next.cpp @@ -280,15 +280,12 @@ llama_model_glm5_next::llm_graph_input_kpool * llama_model_glm5_next::graph::bui // change shape every kpool tokens const uint32_t n_new = std::max(mctx_hyb->get_n_kpool_new(), 1u); - // the fused lightning indexer wants an f16 mask - const auto type_mask = cparams.fused_lid ? GGML_TYPE_F16 : GGML_TYPE_F32; - auto inp = std::make_unique(mctx_hyb, kpool); inp->k_idxs = mctx_idx->build_input_k_idxs(ctx0, ubatch); inp->pool_cells = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_pool); inp->pool_idxs = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, kpool, n_pool); - inp->pool_mask = ggml_new_tensor_2d(ctx0, type_mask, n_pool, n_tokens); + inp->pool_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F16, n_pool, n_tokens); inp->tail_idxs = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, kpool - 1, n_tokens); ggml_set_input(inp->pool_cells); ggml_set_input(inp->pool_idxs); @@ -934,22 +931,7 @@ ggml_tensor * llama_model_glm5_next::graph::build_kpool_select( weights = ggml_scale(ctx0, weights, 1.0f / sqrtf(float(n_embd_indexer * n_indexer_head))); cb(weights, "indexer_weights", il); - ggml_tensor * score = nullptr; - if (cparams.fused_lid) { - score = ggml_lightning_indexer(ctx0, iq, pooled, weights, inp_kpool->pool_mask); - res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, score, il}); - } else { - ggml_tensor * q_p = ggml_permute(ctx0, iq, 0, 2, 1, 3); // [head_dim, n_tokens, n_head] - ggml_tensor * k_p = ggml_permute(ctx0, pooled, 0, 2, 1, 3); // [head_dim, n_pool, 1] - - ggml_tensor * kq = ggml_mul_mat(ctx0, k_p, q_p); // [n_pool, n_tokens, n_head] - kq = ggml_cont(ctx0, ggml_permute(ctx0, kq, 2, 1, 0, 3)); // [n_head, n_tokens, n_pool] - score = ggml_relu(ctx0, kq); - score = ggml_mul(ctx0, score, weights); - score = ggml_sum_rows(ctx0, score); // [1, n_tokens, n_pool] - score = ggml_cont(ctx0, ggml_permute(ctx0, score, 2, 1, 0, 3)); // [n_pool, n_tokens, 1] - score = ggml_add(ctx0, score, inp_kpool->pool_mask); - } + ggml_tensor * score = ggml_lightning_indexer(ctx0, iq, pooled, weights, inp_kpool->pool_mask); cb(score, "indexer_score", il); const int64_t n_top_pool = std::min(n_pool, hparams.indexer_top_k / kpool); diff --git a/src/models/granite-hybrid.cpp b/src/models/granite-hybrid.cpp index be352dfd770d..d638663afd44 100644 --- a/src/models/granite-hybrid.cpp +++ b/src/models/granite-hybrid.cpp @@ -260,11 +260,7 @@ ggml_tensor * llama_model_granite_hybrid::graph::build_layer_ffn(ggml_tensor * LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, - il, - nullptr, nullptr, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + il); cb(moe_out, "ffn_moe_out", il); // For Granite MoE Shared diff --git a/src/models/granite-swa.cpp b/src/models/granite-swa.cpp index be9e5577856d..2e2609f52c83 100644 --- a/src/models/granite-swa.cpp +++ b/src/models/granite-swa.cpp @@ -277,10 +277,7 @@ ggml_tensor * llama_model_granite_swa::graph::build_layer_ffn( hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, il, - nullptr, model.layers[il].ffn_gate_up_exps, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + nullptr, model.layers[il].ffn_gate_up_exps); cb(moe_out, "ffn_moe_out", il); // For Granite MoE Shared - gate+up kept fused in ffn_up_shexp diff --git a/src/models/granite.cpp b/src/models/granite.cpp index 0ab9084dae8a..0a5dd78eafb6 100644 --- a/src/models/granite.cpp +++ b/src/models/granite.cpp @@ -269,11 +269,7 @@ ggml_tensor * llama_model_granite::graph::build_layer_ffn( LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, - il, - nullptr, nullptr, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + il); cb(moe_out, "ffn_moe_out", il); // For Granite MoE Shared diff --git a/src/models/hrm-text.cpp b/src/models/hrm-text.cpp index 8e3b34c57580..1a800ee5b382 100644 --- a/src/models/hrm-text.cpp +++ b/src/models/hrm-text.cpp @@ -1,5 +1,7 @@ #include "models.h" +#include + // HRM-Text: alternating low/high transformer stacks over the same token stream. // Reference: HrmTextModel in transformers, DFM Mimir 1B. @@ -19,8 +21,15 @@ void llama_model_hrm_text::load_arch_hparams(llama_model_loader & ml) { GGML_ASSERT(hparams.n_hrm_l_cycles > 0); // the GGUF block count is the expanded cache-slot count - const uint32_t n_slot = hparams.n_hrm_layers_per_stack * hparams.n_hrm_h_cycles * (hparams.n_hrm_l_cycles + 1); - GGML_ASSERT(hparams.n_layer() == n_slot); + // 64-bit: a 32-bit product can wrap and match n_layer(), then load_arch_tensors() indexes past model.layers + const uint64_t n_slot = (uint64_t) hparams.n_hrm_layers_per_stack * hparams.n_hrm_h_cycles * (hparams.n_hrm_l_cycles + 1); + if (hparams.n_hrm_layers_per_stack >= hparams.n_layer() || hparams.n_hrm_h_cycles > LLAMA_MAX_LAYERS/2 || hparams.n_hrm_l_cycles >= LLAMA_MAX_LAYERS || n_slot != hparams.n_layer()) { + throw std::runtime_error(format( + "hrm: cache-slot count %" PRIu64 " (layers_per_stack %u, h_cycles %u, l_cycles %u) " + "does not match block_count %u", + n_slot, hparams.n_hrm_layers_per_stack, hparams.n_hrm_h_cycles, + hparams.n_hrm_l_cycles, hparams.n_layer())); + } switch (hparams.n_embd) { case 1536: diff --git a/src/models/hy-v3.cpp b/src/models/hy-v3.cpp index c47c373f89ea..f53d94827ee7 100644 --- a/src/models/hy-v3.cpp +++ b/src/models/hy-v3.cpp @@ -168,10 +168,7 @@ llama_model_hy_v3::graph::graph(const llm_graph_params & params) : llm_graph_con hparams.expert_weights_scale, (llama_expert_gating_func_type) hparams.expert_gating_func, il, - nullptr, model.layers[il].ffn_gate_up_exps, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + nullptr, model.layers[il].ffn_gate_up_exps); cb(moe_out, "ffn_moe_out", il); // shared expert (always active, no gate) @@ -323,10 +320,7 @@ llama_model_hy_v3::graph_mtp::graph_mtp(const llm_graph_params & params) hparams.expert_weights_scale, (llama_expert_gating_func_type) hparams.expert_gating_func, il, - nullptr, layer.ffn_gate_up_exps, - layer.ffn_up_exps_s, - layer.ffn_gate_exps_s, - layer.ffn_down_exps_s); + nullptr, layer.ffn_gate_up_exps); cb(moe_out, "mtp_ffn_moe_out", il); ggml_tensor * sh_out = build_ffn(cur, diff --git a/src/models/hy-v4.cpp b/src/models/hy-v4.cpp index 386d504bcde7..de7d87cd03ee 100644 --- a/src/models/hy-v4.cpp +++ b/src/models/hy-v4.cpp @@ -393,24 +393,8 @@ ggml_tensor * llama_model_hy_v4::graph::build_indexer_top_k( // fold both reference scale factors into the weights before the big score tensor iw = ggml_scale(ctx0, iw, 1.0f / sqrtf(float(n_embd_indexer * n_indexer_head))); - ggml_tensor * score = nullptr; - if (cparams.fused_lid) { - score = ggml_lightning_indexer(ctx0, iq, ik, iw, inp_attn_dsa->self_attn_mask_lid.raw); - cb(score, "indexer_score", il); - res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, score, il}); - } else { - iq = ggml_permute(ctx0, iq, 0, 2, 1, 3); - ik = ggml_permute(ctx0, ik, 0, 2, 1, 3); - - score = ggml_mul_mat(ctx0, ik, iq); - score = ggml_cont(ctx0, ggml_permute(ctx0, score, 2, 1, 0, 3)); - score = ggml_relu(ctx0, score); - score = ggml_mul(ctx0, score, iw); - score = ggml_sum_rows(ctx0, score); - score = ggml_cont(ctx0, ggml_permute(ctx0, score, 2, 1, 0, 3)); - score = ggml_add(ctx0, score, inp_attn_dsa->self_attn_mask_lid.raw); - cb(score, "indexer_score", il); - } + ggml_tensor * score = ggml_lightning_indexer(ctx0, iq, ik, iw, inp_attn_dsa->self_attn_mask_lid.raw); + cb(score, "indexer_score", il); const uint32_t n_top_k = score->ne[0] < (int64_t) hparams.indexer_top_k ? score->ne[0] : hparams.indexer_top_k; diff --git a/src/models/inkling2-loop.cpp b/src/models/inkling2-loop.cpp new file mode 100644 index 000000000000..8366a1191f25 --- /dev/null +++ b/src/models/inkling2-loop.cpp @@ -0,0 +1,115 @@ +#include "models.h" + +int llama_model_inkling2_loop::layer_phys(int il) const { + return il < n_phys ? il : core_start + (il - n_phys) % (core_end - core_start); +} + +void llama_model_inkling2_loop::load_arch_hparams(llama_model_loader & ml) { + llama_model_inkling2::load_arch_hparams(ml); + + ml.get_key(LLM_KV_LOOP_START, core_start); + ml.get_key(LLM_KV_LOOP_END, core_end); + ml.get_key(LLM_KV_LOOP_COUNT, n_passes); + ml.get_key(LLM_KV_LOOP_GATE_RANK, gate_rank); + ml.get_key(LLM_KV_LOOP_VARYING, varying, false); + + n_phys = hparams.n_layer(); + const uint32_t block = hparams.attn_res_block_size; + // a fixed loop needs at least 2 passes, a variable loop at least 1 + if (n_passes < (varying ? 1u : 2u) || !gate_rank || !core_start || core_start >= core_end || core_end > (uint32_t) n_phys || + core_start % block || core_end % block || hparams.n_layer_nextn) { + throw std::runtime_error(format("inkling2_loop: invalid loop core [%u, %u) with block size %u, %u passes or gate rank %u for %d layers", + core_start, core_end, block, n_passes, gate_rank, n_phys)); + } + const size_t n_slot = n_phys + (size_t) (n_passes - 1)*(core_end - core_start); + if (n_slot > LLAMA_MAX_LAYERS) { + throw std::runtime_error(format("inkling2_loop: %zu cache slots exceed the maximum of %d", n_slot, LLAMA_MAX_LAYERS)); + } + + // expand to the cache slots before load_tensors() allocates the layers and the memory + hparams.n_layer_all = n_slot; + for (int il = n_phys; il < (int) n_slot; ++il) { + const int p = layer_phys(il); + hparams.n_head_arr[il] = hparams.n_head_arr[p]; + hparams.n_head_kv_arr[il] = hparams.n_head_kv_arr[p]; + hparams.n_ff_arr[il] = hparams.n_ff_arr[p]; + hparams.n_ff_exp_arr[il] = hparams.n_ff_exp_arr[p]; + hparams.n_expert_used_arr[il] = hparams.n_expert_used_arr[p]; + hparams.is_swa_impl[il] = hparams.is_swa_impl[p]; + hparams.is_recr_impl[il] = hparams.is_recr_impl[p]; + } +} + +void llama_model_inkling2_loop::load_arch_tensors(llama_model_loader & ml) { + llama_model_inkling2::load_arch_tensors(ml); + + const int64_t n_embd = hparams.n_embd; + const int64_t rank = gate_rank; + const llm_tensor down[LOOP_CTRL_COUNT] = { LLM_TENSOR_LOOP_Q_CTRL_DOWN, LLM_TENSOR_LOOP_K_CTRL_DOWN, LLM_TENSOR_LOOP_V_CTRL_DOWN, LLM_TENSOR_LOOP_FFN_CTRL_DOWN }; + const llm_tensor gain[LOOP_CTRL_COUNT] = { LLM_TENSOR_LOOP_Q_CTRL_GAIN, LLM_TENSOR_LOOP_K_CTRL_GAIN, LLM_TENSOR_LOOP_V_CTRL_GAIN, LLM_TENSOR_LOOP_FFN_CTRL_GAIN }; + const llm_tensor forget[LOOP_CTRL_COUNT] = { LLM_TENSOR_LOOP_Q_CTRL_FORGET, LLM_TENSOR_LOOP_K_CTRL_FORGET, LLM_TENSOR_LOOP_V_CTRL_FORGET, LLM_TENSOR_LOOP_FFN_CTRL_FORGET }; + + loop_layers.resize(core_end - core_start); + for (uint32_t il = core_start; il < core_end; ++il) { + auto & l = loop_layers[il - core_start]; + // the q, k, v and ffn message queries + l.msg_query = create_tensor(tn(LLM_TENSOR_LOOP_MSG_QUERY, "weight", il), {n_embd, LOOP_CTRL_COUNT}, 0); + for (int c = 0; c < LOOP_CTRL_COUNT; ++c) { + l.ctrl_down[c] = create_tensor(tn(down[c], "weight", il), {2*n_embd, rank}, 0); + l.ctrl_gain[c] = create_tensor(tn(gain[c], "weight", il), {rank, n_embd}, 0); + l.ctrl_forget[c] = create_tensor(tn(forget[c], "weight", il), {rank, n_embd}, 0); + } + } +} + +void llama_model_inkling2_loop::post_arch_tensors(llama_model_loader &) { + // share the physical weights, each cache slot keeps its own KV and conv state + for (int il = n_phys; il < (int) hparams.n_layer(); ++il) { + layers[il] = layers[layer_phys(il)]; + } +} + +std::unique_ptr llama_model_inkling2_loop::build_arch_graph(const llm_graph_params & params) const { + return std::make_unique(params); +} + +llama_model_inkling2_loop::graph::graph(const llm_graph_params & params) : llama_model_inkling2::graph(params, no_build{}) { + const auto & m = static_cast(model); + const int start = m.core_start; + const int end = m.core_end; + + auto * cur = build_inputs(); + std::vector blocks; + for (int il = 0; il < start; ++il) { + cur = build_layer(il, il, cur, blocks); + } + + // every pass starts from the prelude output + auto * prelude = cur; + const auto prelude_blocks = blocks; + for (uint32_t pass = 0; pass < m.n_passes; ++pass) { + // the bank of the previous pass: its blocks after the first core block, and its output + std::vector bank; + ggml_tensor * bank_out = nullptr; + if (pass > 0) { + bank.assign(blocks.begin() + prelude_blocks.size() + 1, blocks.end()); + bank_out = cur; + cur = prelude; + blocks = prelude_blocks; + } + for (int ip = start; ip < end; ++ip) { + const int il = pass == 0 ? ip : m.n_phys + (pass - 1)*(end - start) + (ip - start); + if (pass == 0) { + cur = build_layer(il, ip, cur, blocks); + continue; + } + const auto & loop = m.loop_layers[ip - start]; + cur = build_layer(il, ip, cur, blocks, mix(bank, bank_out, loop.msg_query), &loop); + } + } + + for (int il = end; il < m.n_phys; ++il) { + cur = build_layer(il, il, cur, blocks); + } + build_output(cur, blocks); +} diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 41eebd1908df..45477a69e35e 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -2,111 +2,158 @@ #include "../llama-memory-hybrid-iswa.h" void llama_model_inkling2::load_arch_hparams(llama_model_loader & ml) { - ml.get_key_or_arr(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp_arr, hparams.n_layer_all); ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); + ml.get_key(LLM_KV_ATTENTION_QK_CLIP, hparams.f_qk_clip); + ml.get_key(LLM_KV_ATTN_RES_BLOCK_SIZE, hparams.attn_res_block_size); + ml.get_key(LLM_KV_SHORTCONV_L_CACHE, hparams.n_shortconv_l_cache); + + // relative-position bias, and the log-scaled positions of the full-attention layers ml.get_key(LLM_KV_ATTENTION_RELATIVE_LENGTH, hparams.n_relative); ml.get_key(LLM_KV_ATTENTION_RELATIVE_EXTENT, hparams.n_relative_extent); - ml.get_key(LLM_KV_ATTENTION_QK_CLIP, hparams.f_qk_clip); - ml.get_key(LLM_KV_ATTENTION_RELATIVE_CLIP, hparams.f_relative_clip); + ml.get_key(LLM_KV_ATTENTION_RELATIVE_CLIP, hparams.f_relative_clip); ml.get_key(LLM_KV_ATTENTION_LOG_SCALE_FLOOR, hparams.n_log_scale_floor); ml.get_key(LLM_KV_ATTENTION_LOG_SCALE_ALPHA, hparams.f_log_scale_alpha); - ml.get_key(LLM_KV_ATTN_RES_BLOCK_SIZE, hparams.attn_res_block_size); - ml.get_key(LLM_KV_SHORTCONV_L_CACHE, hparams.n_shortconv_l_cache); - ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab_padded); + + // the embedding and output tensors are padded past the vocabulary + ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab_padded); ml.get_key(LLM_KV_VOCAB_SIZE_UNPADDED, hparams.n_vocab_unpadded); - ml.get_key(LLM_KV_ACTIVATION_SITU_BETA, hparams.situ_beta); + + // MoE + ml.get_key_or_arr(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp_arr, hparams.n_layer_all); + + ml.get_key(LLM_KV_ACTIVATION_SITU_BETA, hparams.situ_beta); ml.get_key(LLM_KV_ACTIVATION_SITU_LINEAR_BETA, hparams.situ_linear_beta); - ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale); - ml.get_key(LLM_KV_FINAL_LOGIT_SOFTCAPPING, hparams.f_final_logit_softcapping); - ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa); + ml.get_key(LLM_KV_EXPERT_WEIGHTS_SCALE, hparams.expert_weights_scale, false); + + hparams.f_final_logit_softcapping = 0.0f; + ml.get_key(LLM_KV_FINAL_LOGIT_SOFTCAPPING, hparams.f_final_logit_softcapping, false); + + // sliding window + ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa); ml.get_arr(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, hparams.is_swa_impl); + uint32_t n_pattern = 0; ml.get_arr_n(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, n_pattern); + if (n_pattern != hparams.n_layer() || !hparams.n_relative || !hparams.n_relative_extent || !hparams.n_swa || !hparams.attn_res_block_size || !hparams.n_log_scale_floor || hparams.n_shortconv_l_cache < 2 || hparams.n_shortconv_l_cache > 64 || hparams.n_relative_extent > INT32_MAX || hparams.n_swa > INT32_MAX || !hparams.n_vocab_unpadded || hparams.n_vocab_unpadded > hparams.n_vocab_padded) { throw std::runtime_error("inkling2: invalid dimensions, vocabulary, or layer pattern"); } - for (float value : {hparams.f_norm_rms_eps, hparams.f_qk_clip, hparams.f_relative_clip, hparams.situ_beta, - hparams.situ_linear_beta, hparams.expert_weights_scale, hparams.f_final_logit_softcapping}) { + + for (float value : {hparams.f_norm_rms_eps, hparams.f_qk_clip, hparams.f_relative_clip, hparams.situ_beta, hparams.situ_linear_beta}) { if (!std::isfinite(value) || value <= 0.0f) { throw std::runtime_error("inkling2: normalization, clipping and scaling parameters must be finite and positive"); } } + if (!std::isfinite(hparams.f_log_scale_alpha) || hparams.f_log_scale_alpha < 0.0f) { throw std::runtime_error("inkling2: invalid logarithmic scale"); } - hparams.swa_type = LLAMA_SWA_TYPE_STANDARD; - hparams.expert_router_f32 = true; + + hparams.swa_type = LLAMA_SWA_TYPE_STANDARD; + hparams.expert_router_f32 = true; hparams.expert_weights_norm_eps = 1e-20f; + + // no RoPE, the relative-position bias carries the positions hparams.rope_pattern.fill(false); - uint64_t max_channels = 0; + + // the convolution state keeps K, V, the attention output and the FFN output of the widest layer + uint64_t n_channels_max = 0; + for (uint32_t il = 0; il < hparams.n_layer(); ++il) { if (!hparams.n_head_kv(il) || hparams.n_head(il) % hparams.n_head_kv(il) || hparams.n_embd_head_k(il) != hparams.n_embd_head_v(il) || !hparams.n_expert_used(il) || hparams.n_expert_used(il) > hparams.n_expert || !hparams.n_ff_exp(il)) { throw std::runtime_error("inkling2: invalid attention or expert dimensions"); } - max_channels = std::max(max_channels, 2ull * hparams.n_embd_k_gqa(il) + 2ull * hparams.n_embd); + + n_channels_max = std::max(n_channels_max, 2ull * hparams.n_embd_k_gqa(il) + 2ull * hparams.n_embd); } - if (max_channels * (hparams.n_shortconv_l_cache - 1) > UINT32_MAX) { + + if (n_channels_max * (hparams.n_shortconv_l_cache - 1) > UINT32_MAX) { throw std::runtime_error("inkling2: convolution state is too large"); } - hparams.n_sconv_channels = max_channels; + + hparams.n_sconv_channels = n_channels_max; + type = LLM_TYPE_UNKNOWN; } void llama_model_inkling2::load_arch_tensors(llama_model_loader &) { LLAMA_LOAD_LOCALS; + if (hparams.n_vocab_unpadded != vocab.n_tokens()) { throw std::runtime_error("inkling2: tokenizer size must equal the unpadded vocabulary size"); } - tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, hparams.n_vocab_padded}, 0); + + const int64_t n_vocab_padded = hparams.n_vocab_padded; + const int64_t n_rel = hparams.n_relative; + const int64_t n_conv = hparams.n_shortconv_l_cache; + + tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab_padded}, 0); tok_norm = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD_NORM, "weight", 0), {n_embd}, 0); - output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, hparams.n_vocab_padded}, 0); - output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0); + + // output + output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab_padded}, 0); + prec_policy.set_acc(output, GGML_PREC_F32); + output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0); output_res_query = create_tensor(tn(LLM_TENSOR_OUTPUT_RES_QUERY, "weight"), {n_embd}, 0); - for (int i = 0; i < n_layer; ++i) { - auto & l = layers[i]; - const int64_t nh = hparams.n_head(i); - const int64_t nk = hparams.n_head_kv(i); - const int64_t hd = hparams.n_embd_head_k(i); - const int64_t nr = hparams.n_relative; - const int64_t kernel = hparams.n_shortconv_l_cache; - const int64_t extent = hparams.is_swa(i) ? hparams.n_swa : hparams.n_relative_extent; - l.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, nh*hd}, 0); - l.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, nk*hd}, 0); - l.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, nk*hd}, 0); - l.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {nh*hd, n_embd}, 0); - l.wqkv_gate = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "weight", i), {n_embd, nh*hd}, 0); - l.attn_rel = create_tensor(tn(LLM_TENSOR_ATTN_REL, "weight", i), {n_embd, nh*nr}, 0); - l.attn_rel_bias = create_tensor(tn(LLM_TENSOR_ATTN_REL_BIAS, "weight", i), {nr, extent}, 0); - l.attn_q_clip = create_tensor(tn(LLM_TENSOR_ATTN_Q_CLIP, "weight", i), {hd, nh}, 0); - l.attn_rel_clip = create_tensor(tn(LLM_TENSOR_ATTN_REL_CLIP, "weight", i), {nr, nh}, 0); - l.attn_sink_proj = create_tensor(tn(LLM_TENSOR_ATTN_SINK_PROJ, "weight", i), {n_embd, nh}, 0); - l.attn_k_conv = create_tensor(tn(LLM_TENSOR_ATTN_K_CONV, "weight", i), {kernel, nk*hd}, 0); - l.attn_v_conv = create_tensor(tn(LLM_TENSOR_ATTN_V_CONV, "weight", i), {kernel, nk*hd}, 0); - l.attn_post_conv = create_tensor(tn(LLM_TENSOR_ATTN_POST_CONV, "weight", i), {kernel, n_embd}, 0); - l.ffn_post_conv = create_tensor(tn(LLM_TENSOR_FFN_POST_CONV, "weight", i), {kernel, n_embd}, 0); + + for (int i = 0; i < n_layer_phys(); ++i) { + auto & layer = layers[i]; + + const int64_t n_head = hparams.n_head(i); + const int64_t n_head_kv = hparams.n_head_kv(i); + const int64_t n_embd_head = hparams.n_embd_head_k(i); + const int64_t n_ff_exp = hparams.n_ff_exp(i); + const int64_t n_extent = hparams.is_swa(i) ? hparams.n_swa : hparams.n_relative_extent; + + // attention + layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head*n_head}, 0); + layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_head*n_head_kv}, 0); + layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_head*n_head_kv}, 0); + layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head*n_head, n_embd}, 0); + layer.wqkv_gate = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "weight", i), {n_embd, n_embd_head*n_head}, 0); + + layer.attn_q_clip = create_tensor(tn(LLM_TENSOR_ATTN_Q_CLIP, "weight", i), {n_embd_head, n_head}, 0); + layer.attn_sink_proj = create_tensor(tn(LLM_TENSOR_ATTN_SINK_PROJ, "weight", i), {n_embd, n_head}, 0); + + // relative-position bias + layer.attn_rel = create_tensor(tn(LLM_TENSOR_ATTN_REL, "weight", i), {n_embd, n_rel*n_head}, 0); + layer.attn_rel_bias = create_tensor(tn(LLM_TENSOR_ATTN_REL_BIAS, "weight", i), {n_rel, n_extent}, 0); + layer.attn_rel_clip = create_tensor(tn(LLM_TENSOR_ATTN_REL_CLIP, "weight", i), {n_rel, n_head}, 0); + + // short convolutions + layer.attn_k_conv = create_tensor(tn(LLM_TENSOR_ATTN_K_CONV, "weight", i), {n_conv, n_embd_head*n_head_kv}, 0); + layer.attn_v_conv = create_tensor(tn(LLM_TENSOR_ATTN_V_CONV, "weight", i), {n_conv, n_embd_head*n_head_kv}, 0); + layer.attn_post_conv = create_tensor(tn(LLM_TENSOR_ATTN_POST_CONV, "weight", i), {n_conv, n_embd}, 0); + layer.ffn_post_conv = create_tensor(tn(LLM_TENSOR_FFN_POST_CONV, "weight", i), {n_conv, n_embd}, 0); + if (hparams.is_swa(i)) { - l.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0); + layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0); } else { - l.attn_q_inp_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_INP_NORM, "weight", i), {n_embd}, 0); - l.attn_k_inp_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_INP_NORM, "weight", i), {n_embd}, 0); - l.attn_v_inp_norm = create_tensor(tn(LLM_TENSOR_ATTN_V_INP_NORM, "weight", i), {n_embd}, 0); - l.attn_k_conv_proj = create_tensor(tn(LLM_TENSOR_ATTN_K_CONV_PROJ, "weight", i), {n_embd, kernel*nk}, 0); - l.attn_v_conv_proj = create_tensor(tn(LLM_TENSOR_ATTN_V_CONV_PROJ, "weight", i), {n_embd, kernel*nk}, 0); + // full-attention layers: separate Q, K and V input norms, and input-dependent taps for the K and V convolutions + layer.attn_q_inp_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_INP_NORM, "weight", i), {n_embd}, 0); + layer.attn_k_inp_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_INP_NORM, "weight", i), {n_embd}, 0); + layer.attn_v_inp_norm = create_tensor(tn(LLM_TENSOR_ATTN_V_INP_NORM, "weight", i), {n_embd}, 0); + layer.attn_k_conv_proj = create_tensor(tn(LLM_TENSOR_ATTN_K_CONV_PROJ, "weight", i), {n_embd, n_conv*n_head_kv}, 0); + layer.attn_v_conv_proj = create_tensor(tn(LLM_TENSOR_ATTN_V_CONV_PROJ, "weight", i), {n_embd, n_conv*n_head_kv}, 0); } + + // block attention residuals if (i > 0) { - l.attn_res_query = create_tensor(tn(LLM_TENSOR_ATTN_RES_QUERY, "weight", i), {n_embd, hparams.is_swa(i) ? 1 : 3}, 0); + layer.attn_res_query = create_tensor(tn(LLM_TENSOR_ATTN_RES_QUERY, "weight", i), {n_embd, hparams.is_swa(i) ? 1 : 3}, 0); } - l.ffn_res_query = create_tensor(tn(LLM_TENSOR_FFN_RES_QUERY, "weight", i), {n_embd}, 0); - l.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0); - l.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0); - l.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, TENSOR_NOT_REQUIRED); - l.ffn_gate_up_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_UP_EXPS, "weight", i), {n_embd, 2*hparams.n_ff_exp(i), n_expert}, 0); - l.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {hparams.n_ff_exp(i), n_embd, n_expert}, 0); + layer.ffn_res_query = create_tensor(tn(LLM_TENSOR_FFN_RES_QUERY, "weight", i), {n_embd}, 0); + + // MoE + layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0); + layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0); + layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, TENSOR_NOT_REQUIRED); + layer.ffn_gate_up_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_UP_EXPS, "weight", i), {n_embd, 2*n_ff_exp, n_expert}, 0); + layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert}, 0); } } @@ -114,202 +161,297 @@ std::unique_ptr llama_model_inkling2::build_arch_graph(const return std::make_unique(params); } -class llm_graph_input_inkling2_pos : public llm_graph_input_i { -public: - const llama_kv_cache_context * cache[2]; - ggml_tensor * distance[2]; - uint32_t extent[2]; - - bool can_reuse(const llm_graph_params & params) override { - const auto * memory = static_cast(params.mctx); - cache[0] = memory->get_attn()->get_base(); - cache[1] = memory->get_attn()->get_swa(); - for (int i = 0; i < 2; ++i) { - if (distance[i]->ne[0] != cache[i]->get_n_kv() || distance[i]->ne[1] != params.ubatch.n_tokens) { - return false; - } - } - return true; - } - - void set_input(const llama_ubatch * ubatch) override { - for (int i = 0; i < 2; ++i) { - if (distance[i]->buffer) { - cache[i]->set_input_relative_pos(distance[i], ubatch, extent[i]); - } - } - } -}; - +// scale each row down to an L2 norm of at most threshold, after the optional per-channel scale ggml_tensor * llama_model_inkling2::graph::clip(ggml_tensor * cur, ggml_tensor * scale, float threshold) { if (scale) { cur = ggml_mul(ctx0, cur, scale); } - auto * norm = ggml_sqrt(ctx0, ggml_sum_rows(ctx0, ggml_sqr(ctx0, cur))); + + ggml_tensor * norm = ggml_sqrt(ctx0, ggml_sum_rows(ctx0, ggml_sqr(ctx0, cur))); norm = ggml_scale_bias(ctx0, norm, 1.0f, 1e-6f); - auto * factor = ggml_div(ctx0, ggml_fill(ctx0, norm, threshold), norm); + + ggml_tensor * factor = ggml_div(ctx0, ggml_fill(ctx0, norm, threshold), norm); + return ggml_mul(ctx0, cur, ggml_clamp(ctx0, factor, 0.0f, 1.0f)); } +// attention over the depth: mix the earlier block outputs and cur with learned queries ggml_tensor * llama_model_inkling2::graph::mix(const std::vector & blocks, ggml_tensor * cur, ggml_tensor * query) { - auto * states = ggml_reshape_3d(ctx0, cur, n_embd, 1, n_tokens); - for (auto * block : blocks) { + ggml_tensor * states = ggml_reshape_3d(ctx0, cur, n_embd, 1, n_tokens); + for (ggml_tensor * block : blocks) { states = ggml_concat(ctx0, ggml_reshape_3d(ctx0, block, n_embd, 1, n_tokens), states, 1); } states = ggml_rms_norm(ctx0, states, 1e-6f); - auto * queries = ggml_repeat(ctx0, query, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd, query->ne[1], n_tokens)); - auto * scores = ggml_mul_mat(ctx0, states, queries); + + ggml_tensor * queries = ggml_repeat(ctx0, query, ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd, query->ne[1], n_tokens)); + + ggml_tensor * scores = ggml_mul_mat(ctx0, states, queries); scores = ggml_soft_max_ext(ctx0, scores, nullptr, 1.0f/sqrtf(n_embd), 0.0f); + return ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, states)), scores); } -ggml_tensor * llama_model_inkling2::graph::convolve(ggml_tensor * cur, ggml_tensor * weight, ggml_tensor * dynamic, - ggml_tensor * state, ggml_tensor * history, llm_graph_input_rs * inp, int64_t offset) { - const int64_t kernel = hparams.n_shortconv_l_cache; - const int64_t channels = cur->ne[0]; - const int64_t nt = ubatch.n_seq_tokens; - const int64_t ns = ubatch.n_seqs; - auto * past = ggml_view_3d(ctx0, history, kernel - 1, channels, ns, history->nb[1], history->nb[2], offset*history->nb[1]); - auto * x = ggml_transpose(ctx0, ggml_reshape_3d(ctx0, cur, channels, nt, ns)); +// causal short convolution with a residual; dynamic adds input-dependent taps per head +// the last n_conv - 1 inputs of each sequence live in the recurrent state at channel offset `offset` +ggml_tensor * llama_model_inkling2::graph::convolve( + ggml_tensor * cur, + ggml_tensor * weight, + ggml_tensor * dynamic, + ggml_tensor * state, + ggml_tensor * history, + llm_graph_input_rs * inp, + int64_t offset) { + const int64_t n_conv = hparams.n_shortconv_l_cache; + const int64_t n_channels = cur->ne[0]; + const int64_t n_seq_tokens = ubatch.n_seq_tokens; + const int64_t n_seqs = ubatch.n_seqs; + + 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)); x = ggml_concat(ctx0, past, x, 0); - build_conv_state_store(inp, state, x, kernel - 1, offset*(kernel - 1)*ggml_element_size(state)); - auto * out = ggml_ssm_conv(ctx0, x, weight); - out = ggml_reshape_2d(ctx0, out, channels, n_tokens); + + build_conv_state_store(inp, state, x, n_conv - 1, offset*(n_conv - 1)*ggml_element_size(state)); + + ggml_tensor * out = ggml_ssm_conv(ctx0, x, weight); + out = ggml_reshape_2d(ctx0, out, n_channels, n_tokens); + if (dynamic) { - const int64_t heads = dynamic->ne[0]/kernel; - dynamic = ggml_reshape_3d(ctx0, dynamic, kernel, heads, n_tokens); - for (int64_t lag = 0; lag < kernel; ++lag) { - auto * tap = ggml_view_3d(ctx0, dynamic, 1, heads, n_tokens, dynamic->nb[1], dynamic->nb[2], lag*dynamic->nb[0]); - auto * window = ggml_view_3d(ctx0, x, nt, channels, ns, x->nb[1], x->nb[2], (kernel - 1 - lag)*x->nb[0]); + const int64_t n_heads = dynamic->ne[0]/n_conv; + + dynamic = ggml_reshape_3d(ctx0, dynamic, n_conv, n_heads, n_tokens); + + for (int64_t lag = 0; lag < n_conv; ++lag) { + ggml_tensor * tap = ggml_view_3d(ctx0, dynamic, 1, n_heads, n_tokens, dynamic->nb[1], dynamic->nb[2], lag*dynamic->nb[0]); + ggml_tensor * window = ggml_view_3d(ctx0, x, n_seq_tokens, n_channels, n_seqs, x->nb[1], x->nb[2], (n_conv - 1 - lag)*x->nb[0]); + window = ggml_cont(ctx0, ggml_transpose(ctx0, window)); - window = ggml_reshape_3d(ctx0, window, channels/heads, heads, n_tokens); - auto * term = ggml_reshape_2d(ctx0, ggml_mul(ctx0, window, tap), channels, n_tokens); + window = ggml_reshape_3d(ctx0, window, n_channels/n_heads, n_heads, n_tokens); + + ggml_tensor * term = ggml_reshape_2d(ctx0, ggml_mul(ctx0, window, tap), n_channels, n_tokens); + out = ggml_add(ctx0, out, term); } } - return ggml_scale(ctx0, ggml_add(ctx0, cur, out), 1.0f/sqrtf((dynamic ? 2 : 1)*kernel + 1)); + + return ggml_scale(ctx0, ggml_add(ctx0, cur, out), 1.0f/sqrtf((dynamic ? 2 : 1)*n_conv + 1)); } -llama_model_inkling2::graph::graph(const llm_graph_params & params) : llm_graph_context(params) { - auto * inp = build_inp_mem_hybrid_iswa(); - auto * attn = inp->get_attn(); - auto * recr = inp->get_recr(); - auto * positions = build_inp_pos(); - auto * out_ids = build_inp_out_ids(); - auto rel = std::make_unique(); - rel->cache[0] = attn->mctx->get_base(); - rel->cache[1] = attn->mctx->get_swa(); - rel->extent[0] = hparams.n_relative_extent; - rel->extent[1] = hparams.n_swa; - ggml_tensor * distances[2]; - for (int i = 0; i < 2; ++i) { - distances[i] = rel->distance[i] = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, rel->cache[i]->get_n_kv(), n_tokens); - ggml_set_input(distances[i]); - } - res->add_input(std::move(rel)); - auto * tau = ggml_scale_bias(ctx0, ggml_cast(ctx0, positions, GGML_TYPE_F32), 1.0f, 1.0f); +// mix a cross-pass message into a looped layer input: (1 - forget)*cur + gain*message, both gated on cur and message +ggml_tensor * llama_model_inkling2::graph::control(ggml_tensor * cur, ggml_tensor * message, const loop_layer & loop, int ctrl) { + ggml_tensor * gate = ggml_concat(ctx0, ggml_rms_norm(ctx0, cur, 1e-6f), ggml_rms_norm(ctx0, message, 1e-6f), 0); + gate = build_lora_mm(loop.ctrl_down[ctrl], gate); + + ggml_tensor * gain = ggml_tanh(ctx0, build_lora_mm(loop.ctrl_gain[ctrl], gate)); + ggml_tensor * forget = ggml_tanh(ctx0, build_lora_mm(loop.ctrl_forget[ctrl], gate)); + + return ggml_add(ctx0, ggml_sub(ctx0, cur, ggml_mul(ctx0, forget, cur)), ggml_mul(ctx0, gain, message)); +} + +ggml_tensor * llama_model_inkling2::graph::build_inputs() { + inp = build_inp_mem_hybrid_iswa_rel(hparams.n_relative_extent, hparams.n_swa); + attn = inp->get_attn(); + recr = inp->get_recr(); + + ggml_tensor * inp_pos = build_inp_pos(); + inp_out_ids = build_inp_out_ids(); + + // log-scaled positions: 1 + alpha*log(max(1, (pos + 1)/floor)), multiplies q and r of the full-attention layers + 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); - auto * cur = build_inp_embd(model.tok_embd); + + ggml_tensor * cur = build_inp_embd(model.tok_embd); + // important: do not normalize raw embeddings input (i.e. encoded image embeddings) if (ubatch.token) { cur = build_norm(cur, model.tok_norm, nullptr, LLM_NORM_RMS, -1); } - std::vector blocks; - for (int il = 0; il < n_layer; ++il) { - const auto & l = model.layers[il]; - const bool swa = hparams.is_swa(il); - const int64_t nh = hparams.n_head(il); - const int64_t nk = hparams.n_head_kv(il); - const int64_t hd = hparams.n_embd_head_k(il); - const int64_t kv = nk*hd; - auto * state = recr->mctx->get_r_l(il); - auto * history = build_rs(recr, state, hparams.n_embd_r(), ubatch.n_seqs); - history = ggml_reshape_3d(ctx0, history, hparams.n_shortconv_l_cache - 1, hparams.n_sconv_channels, ubatch.n_seqs); - auto * residual = cur; - ggml_tensor * inputs[3] = {cur, cur, cur}; - if (l.attn_res_query) { - auto * mixed = mix(blocks, cur, l.attn_res_query); - for (int j = 0; j < 3; ++j) { - inputs[j] = ggml_cont(ctx0, ggml_view_2d(ctx0, mixed, n_embd, n_tokens, mixed->nb[2], (swa ? 0 : j)*mixed->nb[1])); - } + + return cur; +} + +ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tensor * cur, std::vector & blocks, + ggml_tensor * messages, const loop_layer * loop) { + GGML_ASSERT(!messages == !loop); + + const auto & layer = model.layers[il]; + + const bool is_swa = hparams.is_swa(il); + const int64_t n_head = hparams.n_head(il); + const int64_t n_head_kv = hparams.n_head_kv(il); + const int64_t n_embd_head = hparams.n_embd_head_k(il); + const int64_t n_embd_k_gqa = n_embd_head*n_head_kv; + + // the message of controller ctrl, [n_embd, n_tokens] + auto message = [&](int ctrl) { + return ggml_cont(ctx0, ggml_view_2d(ctx0, messages, n_embd, n_tokens, messages->nb[2], ctrl*messages->nb[1])); + }; + + ggml_tensor * state = recr->mctx->get_r_l(il); + ggml_tensor * history = build_rs(recr, state, hparams.n_embd_r(), ubatch.n_seqs); + history = ggml_reshape_3d(ctx0, history, hparams.n_shortconv_l_cache - 1, hparams.n_sconv_channels, ubatch.n_seqs); + + ggml_tensor * inpSA = cur; + + // attention inputs: SWA layers mix one, full-attention layers one each for Q, K and V + ggml_tensor * inputs[3] = {cur, cur, cur}; + if (layer.attn_res_query) { + ggml_tensor * mixed = mix(blocks, cur, layer.attn_res_query); + for (int j = 0; j < 3; ++j) { + inputs[j] = ggml_cont(ctx0, ggml_view_2d(ctx0, mixed, n_embd, n_tokens, mixed->nb[2], (is_swa ? 0 : j)*mixed->nb[1])); } - if (swa) { - inputs[0] = build_norm(inputs[0], l.attn_norm, nullptr, LLM_NORM_RMS, il); - inputs[1] = inputs[2] = inputs[0]; - } else { - inputs[0] = build_norm(inputs[0], l.attn_q_inp_norm, nullptr, LLM_NORM_RMS, il); - inputs[1] = build_norm(inputs[1], l.attn_k_inp_norm, nullptr, LLM_NORM_RMS, il); - inputs[2] = build_norm(inputs[2], l.attn_v_inp_norm, nullptr, LLM_NORM_RMS, il); + } + + if (messages) { + // the messages make the Q, K and V inputs of a SWA layer differ + for (int j = 0; j < 3; ++j) { + inputs[j] = control(inputs[j], message(LOOP_CTRL_Q + j), *loop, LOOP_CTRL_Q + j); } - auto * q = build_lora_mm(l.wq, inputs[0]); - auto * k = convolve(build_lora_mm(l.wk, inputs[1]), l.attn_k_conv, - swa ? nullptr : build_lora_mm(l.attn_k_conv_proj, inputs[1]), state, history, recr, 0); - auto * v = convolve(build_lora_mm(l.wv, inputs[2]), l.attn_v_conv, - swa ? nullptr : build_lora_mm(l.attn_v_conv_proj, inputs[2]), state, history, recr, kv); - auto * r = build_lora_mm(l.attn_rel, inputs[0]); - q = clip(ggml_reshape_3d(ctx0, q, hd, nh, n_tokens), l.attn_q_clip, hparams.f_qk_clip); - k = clip(ggml_reshape_3d(ctx0, k, hd, nk, n_tokens), nullptr, hparams.f_qk_clip); - v = ggml_rms_norm(ctx0, ggml_reshape_3d(ctx0, v, hd, nk, n_tokens), hparams.f_norm_rms_eps); - r = clip(ggml_reshape_3d(ctx0, r, hparams.n_relative, nh, n_tokens), l.attn_rel_clip, hparams.f_relative_clip); - if (!swa) { - q = ggml_mul(ctx0, q, tau); - r = ggml_mul(ctx0, r, tau); + } + + if (is_swa && messages) { + for (int j = 0; j < 3; ++j) { + inputs[j] = build_norm(inputs[j], layer.attn_norm, nullptr, LLM_NORM_RMS, il); } - auto * mask = swa ? attn->self_attn_mask_swa.raw : attn->self_attn_mask.raw; - const int64_t streams = mask->ne[3]; - const int64_t n_kv = distances[swa]->ne[0]; - auto * sinks = build_lora_mm(l.attn_sink_proj, inputs[0]); - // project r on the bias table first, then gather by distance: only the gathered bias is n_kv x n_tokens x nh - auto * table = ggml_mul_mat(ctx0, ggml_pad(ctx0, l.attn_rel_bias, 0, 1, 0, 0), r); - if (cparams.flash_attn) { - // exp(s - t)/(1 + sum(exp(s - t))) = exp(s)/(exp(t) + sum(exp(s))). - table = ggml_sub(ctx0, table, ggml_reshape_3d(ctx0, sinks, 1, nh, n_tokens)); - } else { - // build_attn scales the bias along with QK; FA adds the mask after scaling QK. - table = ggml_scale(ctx0, table, sqrtf(hd)); + } else if (is_swa) { + inputs[0] = build_norm(inputs[0], layer.attn_norm, nullptr, LLM_NORM_RMS, il); + inputs[1] = inputs[2] = inputs[0]; + } else { + inputs[0] = build_norm(inputs[0], layer.attn_q_inp_norm, nullptr, LLM_NORM_RMS, il); + inputs[1] = build_norm(inputs[1], layer.attn_k_inp_norm, nullptr, LLM_NORM_RMS, il); + inputs[2] = build_norm(inputs[2], layer.attn_v_inp_norm, nullptr, LLM_NORM_RMS, il); + } + + // self-attention + { + ggml_tensor * Qcur = build_lora_mm(layer.wq, inputs[0]); + ggml_tensor * Kcur = convolve(build_lora_mm(layer.wk, inputs[1]), layer.attn_k_conv, + is_swa ? nullptr : build_lora_mm(layer.attn_k_conv_proj, inputs[1]), state, history, recr, 0); + ggml_tensor * Vcur = convolve(build_lora_mm(layer.wv, inputs[2]), layer.attn_v_conv, + is_swa ? nullptr : build_lora_mm(layer.attn_v_conv_proj, inputs[2]), state, history, recr, n_embd_k_gqa); + ggml_tensor * Rcur = build_lora_mm(layer.attn_rel, inputs[0]); + + Qcur = clip(ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), layer.attn_q_clip, hparams.f_qk_clip); + Kcur = clip(ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), nullptr, hparams.f_qk_clip); + Vcur = ggml_rms_norm(ctx0, ggml_reshape_3d(ctx0, Vcur, n_embd_head, n_head_kv, n_tokens), hparams.f_norm_rms_eps); + Rcur = clip(ggml_reshape_3d(ctx0, Rcur, hparams.n_relative, n_head, n_tokens), layer.attn_rel_clip, hparams.f_relative_clip); + + if (!is_swa) { + Qcur = ggml_mul(ctx0, Qcur, tau); + Rcur = ggml_mul(ctx0, Rcur, tau); } + + cb(Qcur, "Qcur", il); + cb(Kcur, "Kcur", il); + cb(Vcur, "Vcur", il); + cb(Rcur, "Rcur", il); + + ggml_tensor * rel_pos = is_swa ? inp->self_rel_pos_swa : inp->self_rel_pos; + + const int64_t n_stream = (is_swa ? attn->self_attn_mask_swa.raw : attn->self_attn_mask.raw)->ne[3]; + const int64_t n_kv = rel_pos->ne[0]; + + ggml_tensor * sinks = build_lora_mm(layer.attn_sink_proj, inputs[0]); + + // project r on the bias table first, then gather by distance: only the gathered bias is n_kv x n_tokens x n_head + ggml_tensor * table = ggml_mul_mat(ctx0, ggml_pad(ctx0, layer.attn_rel_bias, 0, 1, 0, 0), Rcur); + + // the sink logit t is per query: exp(s - t)/(1 + sum(exp(s - t))) = exp(s)/(exp(t) + sum(exp(s))), with a zero sink + table = ggml_sub(ctx0, table, ggml_reshape_3d(ctx0, sinks, 1, n_head, n_tokens)); table = ggml_cont(ctx0, ggml_permute(ctx0, table, 1, 0, 2, 3)); - auto * bias = ggml_get_rows(ctx0, table, distances[swa]); - bias = ggml_cont(ctx0, ggml_permute(ctx0, ggml_reshape_4d(ctx0, bias, nh, n_kv, n_tokens/streams, streams), 2, 0, 1, 3)); - ggml_tensor * fa_mask = nullptr; - if (cparams.flash_attn) { - fa_mask = ggml_cast(ctx0, ggml_add(ctx0, bias, ggml_cast(ctx0, mask, GGML_TYPE_F32)), GGML_TYPE_F16); - sinks = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, nh), 0.0f); - bias = nullptr; - } else { - sinks = ggml_reshape_4d(ctx0, ggml_cont(ctx0, ggml_permute(ctx0, - ggml_reshape_3d(ctx0, sinks, nh, n_tokens/streams, streams), 1, 0, 2, 3)), 1, n_tokens/streams, nh, streams); - } - cur = build_attn(attn, nullptr, nullptr, nullptr, q, k, v, bias, sinks, nullptr, 1.0f/sqrtf(hd), il, fa_mask); - cur = ggml_mul(ctx0, cur, ggml_sigmoid(ctx0, build_lora_mm(l.wqkv_gate, inputs[0]))); - cur = convolve(build_lora_mm(l.wo, cur), l.attn_post_conv, nullptr, state, history, recr, 2*kv); - if (il % hparams.attn_res_block_size == 0) { - blocks.push_back(residual); - } else { - cur = ggml_add(ctx0, residual, cur); - } - residual = cur; - cur = ggml_reshape_2d(ctx0, mix(blocks, cur, l.ffn_res_query), n_embd, n_tokens); - cur = build_norm(cur, l.ffn_norm, nullptr, LLM_NORM_RMS, il); - cur = build_moe_ffn(cur, l.ffn_gate_inp, nullptr, nullptr, l.ffn_down_exps, l.ffn_exp_probs_b, - hparams.n_expert, hparams.n_expert_used(il), LLM_FFN_SITU, true, hparams.expert_weights_scale, - LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID, il, nullptr, l.ffn_gate_up_exps); - cur = convolve(cur, l.ffn_post_conv, nullptr, state, history, recr, 2*kv + n_embd); - cur = ggml_add(ctx0, residual, cur); - cb(cur, "l_out", il); + + ggml_tensor * kq_b = ggml_get_rows(ctx0, table, rel_pos); + kq_b = ggml_reshape_4d(ctx0, kq_b, n_head, n_kv, n_tokens/n_stream, n_stream); + kq_b = ggml_cont(ctx0, ggml_permute(ctx0, kq_b, 2, 0, 1, 3)); + cb(kq_b, "kq_b", il); + + sinks = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f); + + cur = build_attn(inp, + nullptr, nullptr, nullptr, + Qcur, Kcur, Vcur, kq_b, sinks, 1.0f/sqrtf(n_embd_head), il); + + cur = ggml_mul(ctx0, cur, ggml_sigmoid(ctx0, build_lora_mm(layer.wqkv_gate, inputs[0]))); + cur = convolve(build_lora_mm(layer.wo, cur), layer.attn_post_conv, nullptr, state, history, recr, 2*n_embd_k_gqa); + cb(cur, "attn_out", il); + } + + // the first layer of each block starts a new residual stream, the earlier one joins the mixed blocks + if (ip % hparams.attn_res_block_size == 0) { + blocks.push_back(inpSA); + } else { + cur = ggml_add(ctx0, inpSA, cur); + } + + ggml_tensor * ffn_inp = cur; + cb(ffn_inp, "ffn_inp", il); + + // MoE + cur = ggml_reshape_2d(ctx0, mix(blocks, cur, layer.ffn_res_query), n_embd, n_tokens); + if (messages) { + cur = control(cur, message(LOOP_CTRL_FFN), *loop, LOOP_CTRL_FFN); } + cur = build_norm(cur, layer.ffn_norm, nullptr, LLM_NORM_RMS, il); + + cur = build_moe_ffn(cur, + layer.ffn_gate_inp, + nullptr, + nullptr, + layer.ffn_down_exps, + layer.ffn_exp_probs_b, + hparams.n_expert, + hparams.n_expert_used(il), + LLM_FFN_SITU, true, + hparams.expert_weights_scale, + LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID, + il, + nullptr, + layer.ffn_gate_up_exps); + + cur = convolve(cur, layer.ffn_post_conv, nullptr, state, history, recr, 2*n_embd_k_gqa + n_embd); + cb(cur, "ffn_out", il); + + cur = ggml_add(ctx0, ffn_inp, cur); + cb(cur, "l_out", il); + + return cur; +} + +void llama_model_inkling2::graph::build_output(ggml_tensor * cur, const std::vector & blocks) { cur = ggml_reshape_2d(ctx0, mix(blocks, cur, model.output_res_query), n_embd, n_tokens); cur = build_norm(cur, model.output_norm, nullptr, LLM_NORM_RMS, -1); - if (out_ids) { - cur = ggml_get_rows(ctx0, cur, out_ids); + + if (inp_out_ids) { + cur = ggml_get_rows(ctx0, cur, inp_out_ids); } + + cb(cur, "result_norm", -1); res->t_embd = cur; + + // lm_head cur = build_lora_mm(model.output, cur); - ggml_prec_set_acc(cur, GGML_PREC_F32); - const float cap = hparams.f_final_logit_softcapping; - cur = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, cur, 1.0f/cap)), cap); + + if (hparams.f_final_logit_softcapping != 0.0f) { + const float cap = hparams.f_final_logit_softcapping; + + cur = ggml_scale(ctx0, ggml_tanh(ctx0, ggml_scale(ctx0, cur, 1.0f/cap)), cap); + } + + // drop the padded vocabulary cur = ggml_cont(ctx0, ggml_view_2d(ctx0, cur, hparams.n_vocab_unpadded, cur->ne[1], cur->nb[1], 0)); - res->t_logits = cur; + cb(cur, "result_output", -1); + res->t_logits = cur; +} + +llama_model_inkling2::graph::graph(const llm_graph_params & params) : llm_graph_context(params) { + ggml_tensor * cur = build_inputs(); + + std::vector blocks; + for (int il = 0; il < n_layer; ++il) { + cur = build_layer(il, il, cur, blocks); + } + + build_output(cur, blocks); } diff --git a/src/models/jais2.cpp b/src/models/jais2.cpp index 8376423ea5fd..1f077fd8699b 100644 --- a/src/models/jais2.cpp +++ b/src/models/jais2.cpp @@ -42,6 +42,10 @@ void llama_model_jais2::load_arch_tensors(llama_model_loader &) { layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0); layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0); layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0); + + // numerical issues with F16 accumulators + prec_policy.set_acc(layer.wo, GGML_PREC_BF16); + prec_policy.set_acc(layer.ffn_down, GGML_PREC_BF16); } } diff --git a/src/models/kimi-k31.cpp b/src/models/kimi-k31.cpp index 0c0ca2af259d..3f99eca4a183 100644 --- a/src/models/kimi-k31.cpp +++ b/src/models/kimi-k31.cpp @@ -581,28 +581,11 @@ llama_model_kimi_k31::graph::build_dsa_layer( iw->nb[1], iw->nb[2]/n_stream, iw->nb[2]/n_stream, 0); ggml_tensor * kq_mask_lid = inp_attn->self_attn_mask.raw; - if (cparams.fused_lid && kq_mask_lid->type != GGML_TYPE_F16) { + if (kq_mask_lid->type != GGML_TYPE_F16) { kq_mask_lid = ggml_cast(ctx0, kq_mask_lid, GGML_TYPE_F16); } - ggml_tensor * score; - if (cparams.fused_lid) { - score = ggml_lightning_indexer(ctx0, iq, ik, iw, kq_mask_lid); - res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, score, il}); - } else { - ggml_tensor * q_p = ggml_permute(ctx0, iq, 0, 2, 1, 3); // [n_idx_dim, n_tokens, n_idx_head] - ggml_tensor * k_p = ggml_permute(ctx0, ik, 0, 2, 1, 3); // [n_idx_dim, n_kv, 1] - - ggml_tensor * kq = ggml_mul_mat(ctx0, k_p, q_p); // [n_kv, n_tokens, n_idx_head] - kq = ggml_cont(ctx0, ggml_permute(ctx0, kq, 2, 1, 0, 3)); // [n_idx_head, n_tokens, n_kv] - - score = ggml_relu(ctx0, kq); - score = ggml_mul(ctx0, score, iw); - score = ggml_sum_rows(ctx0, score); // [1, n_tokens, n_kv] - score = ggml_cont(ctx0, ggml_permute(ctx0, score, 2, 1, 0, 3)); // [n_kv, n_tokens, 1] - - score = ggml_add(ctx0, score, kq_mask_lid); - } + ggml_tensor * score = ggml_lightning_indexer(ctx0, iq, ik, iw, kq_mask_lid); cb(score, "indexer_score", il); const int64_t n_top_k = std::min(score->ne[0], hparams.indexer_top_k); diff --git a/src/models/kolibri1.cpp b/src/models/kolibri1.cpp index c4d8eca1bed4..64182d186061 100644 --- a/src/models/kolibri1.cpp +++ b/src/models/kolibri1.cpp @@ -142,7 +142,7 @@ llama_model_kolibri1::graph::graph(const llm_graph_params & params) (llama_expert_gating_func_type) hparams.expert_gating_func, il, logits, - nullptr, nullptr, nullptr, nullptr, selected); + nullptr, selected); cb(moe_out, "ffn_moe_out", il); ggml_tensor * shared = build_ffn(cur, diff --git a/src/models/lfm-base.cpp b/src/models/lfm-base.cpp index 40b259fe6ee1..b2740ffee463 100644 --- a/src/models/lfm-base.cpp +++ b/src/models/lfm-base.cpp @@ -116,10 +116,5 @@ ggml_tensor * llm_build_lfm_base::build_lfm_moe_ffn(ggml_tensor * cur, LLM_FFN_SILU, true, hparams.expert_weights_scale, static_cast(hparams.expert_gating_func), - il, - nullptr, - nullptr, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + il); } diff --git a/src/models/llama.cpp b/src/models/llama.cpp index 26d54968cabd..3925699f4188 100644 --- a/src/models/llama.cpp +++ b/src/models/llama.cpp @@ -198,11 +198,7 @@ llama_model_llama::graph::graph(const llm_graph_params & params) : llm_gr LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, - il, - nullptr, nullptr, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + il); cb(cur, "ffn_moe_out", il); } cur = ggml_add(ctx0, cur, ffn_inp); diff --git a/src/models/mellum.cpp b/src/models/mellum.cpp index 57dd5b79a28e..d0b3609b1e08 100644 --- a/src/models/mellum.cpp +++ b/src/models/mellum.cpp @@ -199,11 +199,7 @@ llama_model_mellum::graph::graph(const llm_graph_params & params) : llm_gr LLM_FFN_SILU, hparams.expert_weights_norm, hparams.expert_weights_scale, (llama_expert_gating_func_type) hparams.expert_gating_func, - il, - nullptr, nullptr, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + il); cb(moe_out, "ffn_moe_out", il); cur = moe_out; @@ -351,11 +347,7 @@ llama_model_mellum::graph_mtp::graph_mtp(const llm_graph_params & params) LLM_FFN_SILU, hparams.expert_weights_norm, hparams.expert_weights_scale, (llama_expert_gating_func_type) hparams.expert_gating_func, - il, - nullptr, nullptr, - layer.ffn_up_exps_s, - layer.ffn_gate_exps_s, - layer.ffn_down_exps_s); + il); cb(cur, "mtp_ffn_moe_out", il); cur = ggml_add(ctx0, cur, ffn_inp); diff --git a/src/models/metis16.cpp b/src/models/metis16.cpp index 8a433f3cc0bb..0a57a6ab0b0e 100644 --- a/src/models/metis16.cpp +++ b/src/models/metis16.cpp @@ -329,7 +329,7 @@ llama_model_metis16::graph::graph(const llm_graph_params & params) : ggml_tensor * moe_out = build_moe_ffn(latent, nullptr, nullptr, nullptr, layer.ffn_down_exps, nullptr, n_exp, n_used, LLM_FFN_SILU, false, 0.0f, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX_WEIGHT, il_p, - logits, layer.ffn_gate_up_exps, nullptr, nullptr, nullptr, selected); + logits, layer.ffn_gate_up_exps, selected); ggml_tensor * shexp = build_ffn(latent, layer.ffn_up_shexp, NULL, NULL, layer.ffn_gate_shexp, NULL, NULL, diff --git a/src/models/minimax-m3.cpp b/src/models/minimax-m3.cpp index 4f1184590f82..8560c710aff3 100644 --- a/src/models/minimax-m3.cpp +++ b/src/models/minimax-m3.cpp @@ -572,10 +572,7 @@ llama_model_minimax_m3::graph::graph(const llm_graph_params & params) : llm_grap LLM_FFN_SWIGLU_OAI_MOE, hparams.expert_weights_norm, hparams.expert_weights_scale, (llama_expert_gating_func_type) hparams.expert_gating_func, - il, nullptr, nullptr, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + il); cb(moe_out, "ffn_moe_out", il); // shared expert (swigluoai) diff --git a/src/models/mistral-large4.cpp b/src/models/mistral-large4.cpp index a4315a9919e3..aab49df9d8a4 100644 --- a/src/models/mistral-large4.cpp +++ b/src/models/mistral-large4.cpp @@ -290,46 +290,8 @@ llama_model_mistral_large4::graph::graph(const llm_graph_params & params) : indexer_weights = ggml_scale(ctx0, indexer_weights, 1.0f / sqrtf(float(n_embd_indexer_head * n_indexer_head))); cb(indexer_weights, "indexer_weights", il); - ggml_tensor * indexer_score = nullptr; - if (cparams.fused_lid) { - indexer_score = ggml_lightning_indexer(ctx0, indexer_q, indexer_k, indexer_weights, inp_attn_dsa->self_attn_mask_lid.raw); - cb(indexer_score, "indexer_score", il); - res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, indexer_score, il}); - } else { - // calculate indexer kq - indexer_q = ggml_permute(ctx0, indexer_q, 0, 2, 1, 3); - cb(indexer_q, "indexer_q", il); - indexer_k = ggml_permute(ctx0, indexer_k, 0, 2, 1, 3); - cb(indexer_k, "indexer_k", il); - - ggml_tensor * indexer_kq = ggml_mul_mat(ctx0, indexer_k, indexer_q); - cb(indexer_kq, "indexer_kq", il); - - // ReLU requires contiguous tensors - indexer_kq = ggml_cont(ctx0, ggml_permute(ctx0, indexer_kq, 2, 1, 0, 3)); - cb(indexer_kq, "indexer_kq", il); - - // apply ReLU - indexer_score = ggml_relu(ctx0, indexer_kq); - cb(indexer_score, "indexer_score", il); - - // multiply scores by indexer weights - indexer_score = ggml_mul(ctx0, indexer_score, indexer_weights); - cb(indexer_score, "indexer_score", il); - - // sum by q n_indexer_head dimension - indexer_score = ggml_sum_rows(ctx0, indexer_score); - cb(indexer_score, "indexer_score", il); - - // permute result to match KQ mask - indexer_score = ggml_cont(ctx0, ggml_permute(ctx0, indexer_score, 2, 1, 0, 3)); - cb(indexer_score, "indexer_score", il); - - // mask indexer scores - ggml_tensor * indexer_kq_mask = inp_attn_dsa->self_attn_mask_lid.raw; - indexer_score = ggml_add(ctx0, indexer_score, indexer_kq_mask); - cb(indexer_score, "indexer_score", il); - } + ggml_tensor * indexer_score = ggml_lightning_indexer(ctx0, indexer_q, indexer_k, indexer_weights, inp_attn_dsa->self_attn_mask_lid.raw); + cb(indexer_score, "indexer_score", il); // get indices of top k indexer scores uint32_t n_top_k = indexer_score->ne[0] < n_indexer_top_k ? indexer_score->ne[0] : n_indexer_top_k; @@ -458,10 +420,7 @@ llama_model_mistral_large4::graph::graph(const llm_graph_params & params) : (llama_expert_gating_func_type) hparams.expert_gating_func, il, nullptr, - layer.ffn_gate_up_exps, - layer.ffn_up_exps_s, - layer.ffn_gate_exps_s, - layer.ffn_down_exps_s); + layer.ffn_gate_up_exps); cb(moe_out, "ffn_moe_out", il); ggml_tensor * ffn_shexp = build_ffn(cur, diff --git a/src/models/mistral3.cpp b/src/models/mistral3.cpp index ab81218635da..e1e6981bb0db 100644 --- a/src/models/mistral3.cpp +++ b/src/models/mistral3.cpp @@ -248,11 +248,7 @@ llama_model_mistral3::graph::graph(const llm_graph_params & params) : llm_graph_ LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, - il, - nullptr, nullptr, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + il); cb(cur, "ffn_moe_out", il); } cur = ggml_add(ctx0, cur, ffn_inp); diff --git a/src/models/models.h b/src/models/models.h index 9c79d99f3fdd..21c1581bd640 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -456,6 +456,7 @@ struct llama_model_nanbeige : public llama_model_base { llama_model_nanbeige(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } int n_loops = 1; int n_layer_phys = 0; @@ -783,6 +784,18 @@ struct llama_model_pockettts : public llama_model_base { std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; }; +struct llama_model_moshi : public llama_model_base { + llama_model_moshi(const struct llama_model_params & params) : llama_model_base(params) {} + void load_arch_hparams(llama_model_loader & ml) override; + void load_arch_tensors(llama_model_loader & ml) override; + + struct graph : public llm_graph_context { + graph(const llm_graph_params & params); + }; + + std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; +}; + struct llama_model_kokoro : public llama_model_base { llama_model_kokoro(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; @@ -815,6 +828,7 @@ struct llama_model_zonos3 : public llama_model_base { llama_model_zonos3(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -1258,6 +1272,7 @@ struct llama_model_deepseek32 : public llama_model_base { llama_model_deepseek32(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + bool lid_k_hdmd() const override { return true; } struct graph : public llm_graph_context { graph(const llm_graph_params & params); @@ -1274,6 +1289,7 @@ struct llama_model_dots3note : public llama_model_base { llama_model_dots3note(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + bool lid_k_hdmd() const override { return true; } struct graph : public llm_graph_context { graph(const llm_graph_params & params); @@ -1296,6 +1312,8 @@ struct llama_model_deepseek4 : public llama_model_base { llama_model_deepseek4(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } + bool lid_k_hdmd() const override { return true; } struct graph : public llm_graph_context { struct no_build {}; @@ -1453,6 +1471,7 @@ struct llama_model_xing4_0 : public llama_model_base { llama_model_xing4_0(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_graph_context { graph(const llama_model & model, const llm_graph_params & params); @@ -1495,6 +1514,7 @@ struct llama_model_deepseek41 : public llama_model_deepseek4 { llama_model_deepseek41(const struct llama_model_params & params) : llama_model_deepseek4(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + bool lid_k_hdmd() const override { return false; } // Engram: the hash constants are hparams.ple_* (one module per Engram layer), hashed on the host (ggml has no int64 mul/xor/mod) int engram_index(int il) const; @@ -1553,6 +1573,7 @@ struct llama_model_glm_dsa : public llama_model_base { llama_model_glm_dsa(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + bool lid_k_hdmd() const override { return true; } struct graph : public llm_graph_context { graph(const llm_graph_params & params); @@ -1585,6 +1606,7 @@ struct llama_model_dflash : public llama_model_base { llama_model_dflash(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override; enum variant_type { VARIANT_DFLASH, @@ -1686,6 +1708,7 @@ struct llama_model_mistral_large4 : public llama_model_base { llama_model_mistral_large4(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + bool lid_k_hdmd() const override { return true; } struct graph : public llm_graph_context { graph(const llm_graph_params & params); @@ -1847,6 +1870,7 @@ struct llama_model_metis16 : public llama_model_base { llama_model_metis16(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } uint32_t n_pass = 1; uint32_t n_stream = 1; @@ -2148,6 +2172,7 @@ struct llama_model_hrm_text : public llama_model_base { llama_model_hrm_text(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 64; } struct graph : public llm_graph_context { graph(const llm_graph_params & params); @@ -2190,6 +2215,7 @@ struct llama_model_bailingmoe3 : public llama_model_base { llama_model_bailingmoe3(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -2360,6 +2386,7 @@ struct llama_model_hy_v4 : public llama_model_base { llama_model_hy_v4(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_graph_context { graph(const llm_graph_params & params); @@ -2489,12 +2516,80 @@ struct llama_model_inkling2 : public llama_model_base { llama_model_inkling2(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } + + // the layers stored in the file + virtual int n_layer_phys() const { return hparams.n_layer(); } + + // message controllers of the q, k, v and ffn inputs of a looped layer (inkling2_loop) + enum { LOOP_CTRL_Q, LOOP_CTRL_K, LOOP_CTRL_V, LOOP_CTRL_FFN, LOOP_CTRL_COUNT }; + + struct loop_layer { + ggml_tensor * msg_query = nullptr; + ggml_tensor * ctrl_down[LOOP_CTRL_COUNT] = {}; + ggml_tensor * ctrl_gain[LOOP_CTRL_COUNT] = {}; + ggml_tensor * ctrl_forget[LOOP_CTRL_COUNT] = {}; + }; struct graph : public llm_graph_context { graph(const llm_graph_params & params); ggml_tensor * mix(const std::vector & blocks, ggml_tensor * cur, ggml_tensor * query); ggml_tensor * clip(ggml_tensor * cur, ggml_tensor * scale, float threshold); - ggml_tensor * convolve(ggml_tensor * cur, ggml_tensor * weight, ggml_tensor * dynamic, ggml_tensor * state, ggml_tensor * history, llm_graph_input_rs * inp, int64_t offset); + ggml_tensor * convolve( + ggml_tensor * cur, + ggml_tensor * weight, + ggml_tensor * dynamic, + ggml_tensor * state, + ggml_tensor * history, + llm_graph_input_rs * inp, + int64_t offset); + ggml_tensor * control(ggml_tensor * cur, ggml_tensor * message, const loop_layer & loop, int ctrl); + + protected: + // the helpers alone, a derived graph builds its own body + struct no_build {}; + graph(const llm_graph_params & params, no_build) : llm_graph_context(params) {} + + // the inputs and the token embeddings + ggml_tensor * build_inputs(); + // cache slot il of physical layer ip; messages [n_embd, LOOP_CTRL_COUNT, n_tokens] are mixed into its inputs + ggml_tensor * build_layer(int il, int ip, ggml_tensor * cur, std::vector & blocks, + ggml_tensor * messages = nullptr, const loop_layer * loop = nullptr); + void build_output(ggml_tensor * cur, const std::vector & blocks); + + llm_graph_input_mem_hybrid_iswa_rel * inp = nullptr; + llm_graph_input_attn_kv_iswa * attn = nullptr; + llm_graph_input_rs * recr = nullptr; + + ggml_tensor * inp_out_ids = nullptr; + ggml_tensor * tau = nullptr; // log-scaled positions + }; + + std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; +}; + +// the cache slots after the physical layers repeat the core [core_start, core_end) for each later pass +struct llama_model_inkling2_loop : public llama_model_inkling2 { + llama_model_inkling2_loop(const struct llama_model_params & params) : llama_model_inkling2(params) {} + void load_arch_hparams(llama_model_loader & ml) override; + void load_arch_tensors(llama_model_loader & ml) override; + void post_arch_tensors(llama_model_loader & ml) override; + + int n_layer_phys() const override { return n_phys; } + int layer_phys(int il) const; + + int n_phys = 0; + uint32_t core_start = 0; + uint32_t core_end = 0; + uint32_t n_passes = 0; + uint32_t gate_rank = 0; + bool varying = false; // trained for a varying number of passes + + // indexed by physical layer - core_start + std::vector loop_layers; + + struct graph : public llama_model_inkling2::graph { + graph(const llm_graph_params & params); }; std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; @@ -2606,6 +2701,7 @@ struct llama_model_minimax_01 : public llama_model_base { llama_model_minimax_01(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_graph_context { graph(const llm_graph_params & params); @@ -2636,6 +2732,7 @@ struct llama_model_minimax_m3 : public llama_model_base { llama_model_minimax_m3(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } msa_params msa_p; struct graph : public llm_graph_context { graph(const llm_graph_params & params); @@ -2680,6 +2777,7 @@ struct llama_model_qwen3next : public llama_model_base { llama_model_qwen3next(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -2722,6 +2820,7 @@ struct llama_model_qwen35 : public llama_model_base { llama_model_qwen35(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -2842,7 +2941,7 @@ struct llama_model_clef : public llama_model_qwen35 { input_decision * inp); ggml_tensor * build_head_norm(ggml_tensor * cur, const norm & n); - ggml_tensor * build_head_attn(ggml_tensor * q, ggml_tensor * kv, const attn & a); + ggml_tensor * build_head_attn(ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask = nullptr); ggml_tensor * build_head_ffn (ggml_tensor * cur, const head_layer & layer); const llama_model_clef & model; @@ -2858,6 +2957,7 @@ struct llama_model_qwen4exp : public llama_model_base { void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -2972,6 +3072,7 @@ struct llama_model_qwen35moe : public llama_model_base { llama_model_qwen35moe(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -3014,6 +3115,7 @@ struct llama_model_clover_moe : public llama_model_base { llama_model_clover_moe(const llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -3062,6 +3164,7 @@ struct llama_model_kimi_k3 : public llama_model_base { llama_model_kimi_k3(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 64; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -3102,6 +3205,7 @@ struct llama_model_kimi_k31 : public llama_model_base { llama_model_kimi_k31(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 64; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -3148,6 +3252,7 @@ struct llama_model_glm5_next : public llama_model_base { llama_model_glm5_next(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 64; } // k-pool indexer inputs on top of the generic hybrid input class llm_graph_input_kpool; @@ -3232,6 +3337,7 @@ struct llama_model_kimi_linear : public llama_model_base { llama_model_kimi_linear(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + uint32_t graph_nodes_per_tensor() const override { return 32; } struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); @@ -3315,3 +3421,16 @@ struct llama_model_kolibri1 : public llama_model_base { std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; }; + +struct llama_model_domyn_edge : public llama_model_base { + llama_model_domyn_edge(const struct llama_model_params & params) : llama_model_base(params) {} + void load_arch_hparams(llama_model_loader & ml) override; + void load_arch_tensors(llama_model_loader & ml) override; + llama_rope_params get_rope_params(const llama_cparams & cparams, int il) const override; + + struct graph : public llm_graph_context { + graph(const llm_graph_params & params); + }; + + std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; +}; diff --git a/src/models/moshi.cpp b/src/models/moshi.cpp new file mode 100644 index 000000000000..5cb63cd7e855 --- /dev/null +++ b/src/models/moshi.cpp @@ -0,0 +1,132 @@ +#include "models.h" + +// backbone of the Moshi family (e.g. Hibiki): one position per audio frame, the input rows (text + audio codes) +// are built by mtmd, the head predicts the next text token. Every layer attends to the same sliding window, see create_memory(). + +void llama_model_moshi::load_arch_hparams(llama_model_loader & ml) { + ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); + + // the window of every layer, it is applied by the KV cache, see create_memory() + ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa); + + switch (hparams.n_layer()) { + case 16: type = LLM_TYPE_1B; break; // Hibiki-M + case 24: type = LLM_TYPE_2B; break; // Hibiki + default: type = LLM_TYPE_UNKNOWN; + } +} + +void llama_model_moshi::load_arch_tensors(llama_model_loader & ml) { + LLAMA_LOAD_LOCALS; + + // the last vocab entries are input-only (e.g. the initial text token), the head has no logits for them + // a model built from metadata only has no tensor to read it from + const ggml_tensor * meta = ml.get_tensor_meta(tn(LLM_TENSOR_OUTPUT, "weight").str().c_str()); + const int64_t n_vocab_out = meta ? meta->ne[1] : n_vocab; + if (n_vocab_out < 1 || n_vocab_out > n_vocab) { + throw std::runtime_error(format("tensor 'output.weight' has invalid head size %lld (vocab size %lld)", (long long) n_vocab_out, (long long) n_vocab)); + } + + tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0); + + output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0); + output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab_out}, 0); + + for (int i = 0; i < n_layer; ++i) { + auto & layer = layers[i]; + + layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0); + + create_tensor_qkv(layer, i, n_embd, n_embd, n_embd_gqa, n_embd_gqa, 0); + layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0); + + layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0); + layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0); + layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0); + layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0); + } +} + +std::unique_ptr llama_model_moshi::build_arch_graph(const llm_graph_params & params) const { + return std::make_unique(params); +} + +llama_model_moshi::graph::graph(const llm_graph_params & params) : llm_graph_context(params) { + const int64_t n_embd_head = hparams.n_embd_head_v(); + + GGML_ASSERT(n_embd_head == hparams.n_embd_head_k()); + GGML_ASSERT(n_embd_head == n_rot); + + ggml_tensor * cur; + ggml_tensor * inpL = build_inp_embd(model.tok_embd); + + ggml_tensor * inp_pos = build_inp_pos(); + + auto * inp_attn = build_attn_inp_kv(); + + ggml_tensor * inp_out_ids = build_inp_out_ids(); + + for (int il = 0; il < n_layer; ++il) { + cur = build_norm(inpL, model.layers[il].attn_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "attn_norm", il); + + { + auto [Qcur, Kcur, Vcur] = build_qkv(model.layers[il], cur, n_embd_head, n_head, n_head_kv, il); + + Qcur = build_rope(Qcur, inp_pos, il); + Kcur = build_rope(Kcur, inp_pos, il); + + cb(Qcur, "Qcur", il); + cb(Kcur, "Kcur", il); + cb(Vcur, "Vcur", il); + + cur = build_attn(inp_attn, + model.layers[il].wo, NULL, model.layers[il].wo_s, + Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f/sqrtf(float(n_embd_head)), il); + } + + if (il == n_layer - 1 && inp_out_ids) { + cur = ggml_get_rows(ctx0, cur, inp_out_ids); + inpL = ggml_get_rows(ctx0, inpL, inp_out_ids); + } + + ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL); + cb(ffn_inp, "ffn_inp", il); + + cur = build_norm(ffn_inp, model.layers[il].ffn_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "ffn_norm", il); + + cur = build_ffn(cur, + model.layers[il].ffn_up, NULL, NULL, + model.layers[il].ffn_gate, NULL, NULL, + model.layers[il].ffn_down, NULL, NULL, + NULL, + LLM_FFN_SILU, LLM_FFN_PAR, il); + cb(cur, "ffn_out", il); + + cur = ggml_add(ctx0, cur, ffn_inp); + + cur = build_cvec(cur, il); + cb(cur, "l_out", il); + + inpL = cur; + } + + cur = build_norm(inpL, model.output_norm, NULL, LLM_NORM_RMS, -1); + + cb(cur, "result_norm", -1); + res->t_embd = cur; + + cur = build_lora_mm(model.output, cur, model.output_s); + + // pad the logits of the input-only tokens with -inf + const int64_t pad = model.tok_embd->ne[1] - model.output->ne[1]; + if (pad > 0) { + ggml_tensor * neg_inf = ggml_scale_bias(ctx0, ggml_view_1d(ctx0, model.output_norm, 1, 0), 0.0f, -INFINITY); + neg_inf = ggml_repeat_4d(ctx0, neg_inf, pad, cur->ne[1], 1, 1); + cur = ggml_concat(ctx0, cur, neg_inf, 0); + } + + cb(cur, "result_output", -1); + res->t_logits = cur; +} diff --git a/src/models/muse-spark.cpp b/src/models/muse-spark.cpp index ea6ab84abd94..10de4676e12f 100644 --- a/src/models/muse-spark.cpp +++ b/src/models/muse-spark.cpp @@ -180,7 +180,7 @@ llama_model_muse_spark::graph::graph(const llm_graph_params & params) (llama_expert_gating_func_type) hparams.expert_gating_func, il, router_logits, - nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, model.layers[il].ffn_post_exp_norm, hparams.f_post_norm_eps); cb(moe_out, "ffn_moe_out", il); diff --git a/src/models/nemotron-h-moe.cpp b/src/models/nemotron-h-moe.cpp index 4753558327d1..3aa385379d6d 100644 --- a/src/models/nemotron-h-moe.cpp +++ b/src/models/nemotron-h-moe.cpp @@ -118,10 +118,7 @@ llama_model_nemotron_h_moe::graph_mtp::graph_mtp(const llm_graph_params & params hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID, il, - router_logits, nullptr, - layer.ffn_up_exps_s, - nullptr, // no gate - layer.ffn_down_exps_s); + router_logits); cb(moe_out, "mtp_ffn_moe_out", il); if (layer.ffn_latent_up) { diff --git a/src/models/nemotron-h.cpp b/src/models/nemotron-h.cpp index 313f42f1c7a0..18e45320a317 100644 --- a/src/models/nemotron-h.cpp +++ b/src/models/nemotron-h.cpp @@ -322,10 +322,7 @@ ggml_tensor * llama_model_nemotron_h::graph::build_ffn_layer(ggml_tensor * cur, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID, il, - router_logits, nullptr, - model.layers[il].ffn_up_exps_s, - nullptr, // no gate - model.layers[il].ffn_down_exps_s); + router_logits); cb(moe_out, "ffn_moe_out", il); if (model.layers[il].ffn_latent_up) { diff --git a/src/models/qwen35moe.cpp b/src/models/qwen35moe.cpp index affe13dc97ed..89d425367ec4 100644 --- a/src/models/qwen35moe.cpp +++ b/src/models/qwen35moe.cpp @@ -466,10 +466,7 @@ ggml_tensor * llama_model_qwen35moe::graph::build_layer_ffn(ggml_tensor * cur, c LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, il, - nullptr, model.layers[il].ffn_gate_up_exps, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + nullptr, model.layers[il].ffn_gate_up_exps); cb(moe_out, "ffn_moe_out", il); // Add shared experts if present - following Qwen3Next reference implementation @@ -638,10 +635,7 @@ llama_model_qwen35moe::graph_mtp::graph_mtp(const llm_graph_params & params) LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, il, - nullptr, layer.ffn_gate_up_exps, - layer.ffn_up_exps_s, - layer.ffn_gate_exps_s, - layer.ffn_down_exps_s); + nullptr, layer.ffn_gate_up_exps); cb(moe_out, "mtp_ffn_moe_out", il); if (layer.ffn_up_shexp != nullptr) { diff --git a/src/models/qwen3moe.cpp b/src/models/qwen3moe.cpp index ce7144a229b3..fc57928f598b 100644 --- a/src/models/qwen3moe.cpp +++ b/src/models/qwen3moe.cpp @@ -136,11 +136,7 @@ llama_model_qwen3moe::graph::graph(const llm_graph_params & params) : llm_graph_ LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, - il, - nullptr, nullptr, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + il); cb(moe_out, "ffn_moe_out", il); cur = moe_out; diff --git a/src/models/qwen3next.cpp b/src/models/qwen3next.cpp index a26361cb3b94..6bf89ae93613 100644 --- a/src/models/qwen3next.cpp +++ b/src/models/qwen3next.cpp @@ -562,10 +562,7 @@ ggml_tensor * llama_model_qwen3next::graph::build_layer_ffn(ggml_tensor * cur, c LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, il, - nullptr, model.layers[il].ffn_gate_up_exps, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + nullptr, model.layers[il].ffn_gate_up_exps); cb(moe_out, "ffn_moe_out", il); // Add shared experts if present - following Qwen3Next reference implementation @@ -749,10 +746,7 @@ llama_model_qwen3next::graph_mtp::graph_mtp(const llm_graph_params & params) LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, il, - nullptr, layer.ffn_gate_up_exps, - layer.ffn_up_exps_s, - layer.ffn_gate_exps_s, - layer.ffn_down_exps_s); + nullptr, layer.ffn_gate_up_exps); cb(moe_out, "mtp_ffn_moe_out", il); if (layer.ffn_up_shexp != nullptr) { diff --git a/src/models/qwen4exp.cpp b/src/models/qwen4exp.cpp index 7bf9b3fee8c9..106530490fd7 100644 --- a/src/models/qwen4exp.cpp +++ b/src/models/qwen4exp.cpp @@ -872,7 +872,6 @@ ggml_tensor * llama_model_qwen4exp::graph::build_qsa_sel( // which is the lightning indexer with every head weight set to that scale ggml_tensor * weights = ggml_fill(ctx0, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_idx_h, n_tokens), 1.0f/sqrtf((float) idx_dim)); ggml_tensor * score = ggml_lightning_indexer(ctx0, q, pooled, weights, inp_kpool->pool_mask); // [n_pool, n_tokens] - res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, score, il}); cb(score, "indexer_score", il); const int64_t n_top_pool = std::min(n_pool, hparams.indexer_top_k / kpool); @@ -1231,10 +1230,7 @@ ggml_tensor * llama_model_qwen4exp::graph::build_layer_ffn(ggml_tensor * cur, co LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, il, - nullptr, model.layers[il].ffn_gate_up_exps, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + nullptr, model.layers[il].ffn_gate_up_exps); cb(moe_out, "ffn_moe_out", il); // shared experts, as in the Qwen3Next reference diff --git a/src/models/vllm-decision2.cpp b/src/models/vllm-decision2.cpp index 2a3b9595c72d..6925344257a5 100644 --- a/src/models/vllm-decision2.cpp +++ b/src/models/vllm-decision2.cpp @@ -99,13 +99,19 @@ static decision2_rows decision2_get_rows(const llama_ubatch & ubatch) { return res; } +// no decision order (e.g. reserve): use the max number of options +static size_t decision2_n_options(const llama_ubatch & ubatch, uint32_t n_outputs) { + return ubatch.decision_order ? decision2_get_rows(ubatch).options.size() : std::max(n_outputs, 1); +} + class llama_model_vllm_decision2::input_decision : public llm_graph_input_i { public: - input_decision(const llama_ubatch & ubatch) : n_options(decision2_get_rows(ubatch).options.size()) {} + input_decision(const llama_ubatch & ubatch, uint32_t n_outputs) : n_options(decision2_n_options(ubatch, n_outputs)) {} void set_input(const llama_ubatch * ubatch) override { - const auto rows = decision2_get_rows(*ubatch); - GGML_ASSERT(rows.options.size() == n_options); + auto rows = decision2_get_rows(*ubatch); + GGML_ASSERT(rows.options.size() <= n_options); + rows.options.resize(n_options, 0); // the scores are NaN if the batch has a decision order that cannot be used const float status_data = rows.valid || ubatch->decision_order == nullptr ? 0.0f : NAN; @@ -117,7 +123,7 @@ class llama_model_vllm_decision2::input_decision : public llm_graph_input_i { bool can_reuse(const llm_graph_params & params) override { // the values are computed again in set_input(), only the shapes must match - return decision2_get_rows(params.ubatch).options.size() == n_options; + return decision2_n_options(params.ubatch, params.n_outputs) == n_options; } ggml_tensor * options = nullptr; // I32 [n_options] @@ -129,7 +135,7 @@ class llama_model_vllm_decision2::input_decision : public llm_graph_input_i { llama_model_vllm_decision2::graph::graph(const llm_graph_params & params) : llama_model_qwen3::graph(params, no_build()), model(static_cast(*params.model)) { - auto inp_decision_ptr = std::make_unique(ubatch); + auto inp_decision_ptr = std::make_unique(ubatch, n_outputs); auto * inp_decision = inp_decision_ptr.get(); res->add_input(std::move(inp_decision_ptr)); diff --git a/src/models/zaya1.cpp b/src/models/zaya1.cpp index 2763500f4001..013658c73448 100644 --- a/src/models/zaya1.cpp +++ b/src/models/zaya1.cpp @@ -277,9 +277,6 @@ ggml_tensor * llama_model_zaya1::graph::build_router_moe(const llama_model & mod il, logits, layer.ffn_gate_up_exps, - nullptr, - nullptr, - nullptr, expert); return ggml_mul(ctx0, moe, keep); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 7103ce29219f..0e322b24883c 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -371,6 +371,8 @@ llama_build(test-backend-ops.cpp LINK ggml Threads::Threads) llama_build(test-fattn-masked.cpp LINK ggml Threads::Threads) llama_build_and_test(test-backend-tensor.cpp LINK ggml) +llama_build_and_test(test-sleep.cpp LINK ggml) +llama_build_and_test(test-backend-sched.cpp LINK ggml) if (BUILD_SHARED_LIBS) llama_build_and_test(test-llama-mmap.cpp ${PROJECT_SOURCE_DIR}/src/llama-impl.cpp ${PROJECT_SOURCE_DIR}/src/llama-mmap.cpp LABEL behavior) diff --git a/tests/fusion/MTL.csv b/tests/fusion/MTL.csv index 310934e31725..2a4f4b36192c 100644 --- a/tests/fusion/MTL.csv +++ b/tests/fusion/MTL.csv @@ -41,6 +41,7 @@ cohere2 ,0 ,any ,NORM+MUL , 3 cohere2moe ,1 ,any ,ADD+ADD , 2 cohere2moe ,1 ,any ,MUL+ADD , 2 cohere2moe ,1 ,any ,RMS_NORM+MUL , 3 +command-r ,0 ,any ,ADD+ADD , 2 command-r ,0 ,any ,NORM+MUL , 3 dbrx ,0 ,any ,MUL+ADD , 4 dbrx ,0 ,any ,NORM+MUL , 5 @@ -63,8 +64,10 @@ deepseek4 ,0 ,any ,MUL+ADD , 8 deepseek4 ,0 ,any ,RMS_NORM+MUL , 20 deepseek4 ,0 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 4 deepseek41 ,0 ,any ,MUL+ADD , 12 -deepseek41 ,0 ,any ,RMS_NORM+MUL , 29 +deepseek41 ,0 ,any ,RMS_NORM+MUL , 31 deepseek41 ,0 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV, 6 +domynedge ,0 ,any ,RMS_NORM+MUL , 8 +domynedge ,0 ,any ,RMS_NORM+MUL+ADD , 3 dots1 ,0 ,any ,ADD+ADD , 1 dots1 ,0 ,any ,MUL+ADD , 2 dots1 ,0 ,any ,RMS_NORM+MUL , 9 @@ -99,8 +102,8 @@ gemma2 ,0 ,any ,RMS_NORM+MUL , 5 gemma2 ,0 ,any ,RMS_NORM+MUL+ADD , 4 gemma3 ,0 ,any ,RMS_NORM+MUL , 9 gemma3 ,0 ,any ,RMS_NORM+MUL+ADD , 4 -gemma4 ,0 ,any ,RMS_NORM+MUL , 47 -gemma4 ,0 ,any ,RMS_NORM+MUL+ADD , 20 +gemma4 ,0 ,any ,RMS_NORM+MUL , 37 +gemma4 ,0 ,any ,RMS_NORM+MUL+ADD , 30 glm-dsa ,0 ,any ,ADD+ADD , 1 glm-dsa ,0 ,any ,MUL+ADD , 2 glm-dsa ,0 ,any ,NORM+MUL+ADD , 2 @@ -205,6 +208,7 @@ llama ,0 ,any ,MUL+ADD , 4 llama ,0 ,any ,RMS_NORM+MUL , 5 llama ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 llama4 ,0 ,any ,ADD+ADD , 2 +llama4 ,0 ,any ,MUL+ADD , 4 llama4 ,0 ,any ,RMS_NORM+MUL , 9 maincoder ,0 ,any ,RMS_NORM+MUL , 9 maion-coder ,0 ,any ,MUL+ADD , 4 @@ -251,12 +255,13 @@ mistral4 ,0 ,any ,ADD+ADD , 1 mistral4 ,0 ,any ,MUL+ADD , 2 mistral4 ,0 ,any ,RMS_NORM+MUL , 9 mistral4 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 +moshi ,0 ,any ,RMS_NORM+MUL , 5 mpt ,0 ,any ,NORM+MUL+ADD , 5 muse-glimmer ,0 ,any ,RMS_NORM+MUL , 10 muse-glimmer ,0 ,any ,RMS_NORM+MUL+ADD , 3 -muse-spark ,0 ,prefill ,MUL+ADD , 2 -muse-spark ,0 ,decode ,MUL+ADD , 4 -muse-spark ,0 ,any ,RMS_NORM+MUL , 14 +muse-spark ,0 ,any ,MUL+ADD , 4 +muse-spark ,0 ,any ,RMS_NORM+MUL , 11 +muse-spark ,0 ,any ,RMS_NORM+MUL+ADD , 3 muse-spark ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 nanbeige ,0 ,any ,RMS_NORM+MUL , 5 nemotron ,0 ,any ,NORM+MUL+ADD , 5 diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 5ddb9ea0e28e..fdbd3152f7eb 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -2176,7 +2176,7 @@ struct test_unary : public test_case { ggml_tensor * build_graph(ggml_context * ctx) override { const bool grad_supported = op == GGML_UNARY_OP_ABS || op == GGML_UNARY_OP_SGN || op == GGML_UNARY_OP_NEG || op == GGML_UNARY_OP_STEP || op == GGML_UNARY_OP_RELU || op == GGML_UNARY_OP_SILU || - op == GGML_UNARY_OP_EXPM1 || op == GGML_UNARY_OP_SOFTPLUS; + op == GGML_UNARY_OP_EXPM1 || op == GGML_UNARY_OP_SOFTPLUS || op == GGML_UNARY_OP_SIGMOID; ggml_tensor * a; if (v & 1) { @@ -2218,6 +2218,12 @@ struct test_unary : public test_case { max = 10.f; } + // saturated sigmoid inputs give zero analytic and numeric gradients, which the grad check cannot compare + if (mode == MODE_GRAD && op == GGML_UNARY_OP_SIGMOID) { + min = -2.f; + max = 2.f; + } + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { // test extended range of values to check for NaNs in GELU init_tensor_uniform(t, min, max); @@ -2225,7 +2231,16 @@ struct test_unary : public test_case { } float grad_eps() override { - return 15.0f; + return op == GGML_UNARY_OP_SIGMOID ? 0.25f : 15.0f; + } + + bool grad_precise() override { + return op == GGML_UNARY_OP_SIGMOID; + } + + // f32 rounding of a large summed loss exceeds the tolerance, so only the small sigmoid case is grad checked + int64_t grad_nmax() override { + return op == GGML_UNARY_OP_SIGMOID ? 64 : test_case::grad_nmax(); } std::vector grad_expect() override { @@ -2830,6 +2845,12 @@ struct test_set_rows : public test_case { if (type_src == GGML_TYPE_F16) { err_estimate *= 16.0f; } + if (type_src == GGML_TYPE_BF16) { + // BF16 values have 8 significant bits, so many of them land exactly on a rounding tie, + // and backends break ties differently (e.g. the CPU q8_0 rounds half to even, CUDA half away from zero). + // Allow 1 in 32 values to be off by one instead of one value in total. + return err_estimate / (0.25f*32.0f); + } err_estimate /= 0.25f*float(ne[0] * r * ne[2]*nr23[0] * ne[3]*nr23[1]); return err_estimate; } @@ -2860,10 +2881,15 @@ struct test_rope_set_rows : public test_case { const int n_dims; const bool yarn; const bool truncate; + const ggml_type type_a; // type of the rope input const int n_ctx{512}; std::string vars() override { - return VARS_TO_STR7(type, type_idx, ne_a, mode, n_dims, yarn, truncate); + std::string s = VARS_TO_STR7(type, type_idx, ne_a, mode, n_dims, yarn, truncate); + if (type_a != GGML_TYPE_F32) { + s += "," + VAR_TO_STR(type_a); + } + return s; } std::string op_desc(ggml_tensor * t) override { @@ -2871,17 +2897,27 @@ struct test_rope_set_rows : public test_case { return "ROPE_SET_ROWS"; } + double max_nmse_err() override { + if (type_a != GGML_TYPE_BF16) { + return 1e-7; + } + // into F16 the reference rounds the BF16 rope result to BF16 first, the fused rope + set_rows does not + // otherwise the limit of a BF16 test_rope: the angle error n_ctx*FLT_EPSILON can flip a BF16 rounding + return type == GGML_TYPE_F16 ? 1e-5 : n_ctx * FLT_EPSILON / 128.0; + } + bool run_whole_graph() override { return true; } test_rope_set_rows(ggml_type type, ggml_type type_idx, std::array ne_a, int mode, - int n_dims = 128, bool yarn = false, bool truncate = true) - : type(type), type_idx(type_idx), ne_a(ne_a), mode(mode), n_dims(n_dims), yarn(yarn), truncate(truncate) {} + int n_dims = 128, bool yarn = false, bool truncate = true, + ggml_type type_a = GGML_TYPE_F32) + : type(type), type_idx(type_idx), ne_a(ne_a), mode(mode), n_dims(n_dims), yarn(yarn), truncate(truncate), type_a(type_a) {} ggml_tensor * build_graph(ggml_context * ctx) override { - ggml_tensor * a = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, ne_a[0], ne_a[1], ne_a[2], 1); + ggml_tensor * a = ggml_new_tensor_4d(ctx, type_a, ne_a[0], ne_a[1], ne_a[2], 1); ggml_set_name(a, "a"); const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE; @@ -3877,6 +3913,37 @@ struct test_silu_back : public test_case { } }; +// GGML_OP_SIGMOID_BACK +struct test_sigmoid_back : public test_case { + const ggml_type type; + const std::array ne; + + std::string vars() override { + return VARS_TO_STR2(type, ne); + } + + test_sigmoid_back(ggml_type type = GGML_TYPE_F32, + std::array ne = {64, 5, 4, 3}) + : type(type), ne(ne) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data()); + ggml_set_name(a, "a"); + + ggml_tensor * grad = ggml_new_tensor(ctx, type, 4, ne.data()); + ggml_set_name(grad, "grad"); + + ggml_tensor * out = ggml_sigmoid_back(ctx, a, grad); + ggml_set_name(out, "out"); + + return out; + } + + bool grad_precise() override { + return true; + } +}; + // GGML_OP_NORM struct test_norm : public test_case { const ggml_type type; @@ -4114,6 +4181,7 @@ struct test_rms_norm_mul_add : public test_case { const bool weight_broadcast; const ggml_type type_w; // type of b and d, GGML_TYPE_COUNT -> same as a const ggml_type type_add; // type of c, GGML_TYPE_COUNT -> same as b + const bool swap; // the norm chain is the second operand of MUL and ADD std::string op_desc(ggml_tensor * t) override { GGML_UNUSED(t); @@ -4130,6 +4198,9 @@ struct test_rms_norm_mul_add : public test_case { if (type_add != GGML_TYPE_COUNT) { s += "," + VAR_TO_STR(type_add); } + if (swap) { + s += "," + VAR_TO_STR(swap); + } return s; } @@ -4137,9 +4208,10 @@ struct test_rms_norm_mul_add : public test_case { std::array ne = {64, 5, 4, 3}, float eps = 1e-6f, bool broadcast = false, bool multi_add = false, bool post_mul = false, bool alias_rms_input = false, bool weight_broadcast = false, ggml_type type_w = GGML_TYPE_COUNT, - ggml_type type_add = GGML_TYPE_COUNT) + ggml_type type_add = GGML_TYPE_COUNT, bool swap = false) : type(type), ne(ne), eps(eps), broadcast(broadcast), multi_add(multi_add), post_mul(post_mul), - alias_rms_input(alias_rms_input), weight_broadcast(weight_broadcast), type_w(type_w), type_add(type_add) {} + alias_rms_input(alias_rms_input), weight_broadcast(weight_broadcast), type_w(type_w), type_add(type_add), + swap(swap) {} ggml_tensor * build_graph(ggml_context * ctx) override { std::array broadcast_dims = {ne[0]*2, ne[1]*3, ne[2]*3, ne[3]*4}; @@ -4170,8 +4242,9 @@ struct test_rms_norm_mul_add : public test_case { if (multi_add) { a = ggml_add(ctx, ggml_add(ctx, a, b), c); } - ggml_tensor * mul = ggml_mul(ctx, ggml_rms_norm(ctx, a, eps), b); - ggml_tensor * out = alias_rms_input ? ggml_add_inplace(ctx, a, mul) : ggml_add(ctx, mul, c); + ggml_tensor * norm = ggml_rms_norm(ctx, a, eps); + ggml_tensor * mul = swap ? ggml_mul(ctx, b, norm) : ggml_mul(ctx, norm, b); + ggml_tensor * out = alias_rms_input ? ggml_add_inplace(ctx, a, mul) : swap ? ggml_add(ctx, c, mul) : ggml_add(ctx, mul, c); if (post_mul) { out = ggml_mul(ctx, out, d); } @@ -4324,6 +4397,52 @@ struct test_add_rms_norm : public test_case { } }; +// GGML_OP_ADD + GGML_OP_RMS_NORM + GGML_OP_MUL (fused operation) +struct test_add_rms_norm_mul : public test_case { + const std::array ne; + const float eps; + + ggml_tensor * sum = nullptr; + ggml_tensor * out = nullptr; + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "ADD_RMS_NORM_MUL"; + } + + bool run_whole_graph() override { return true; } + + std::vector fusion_test_nodes() override { return { sum, out }; } + + std::string vars() override { return VARS_TO_STR2(ne, eps); } + + test_add_rms_norm_mul(std::array ne = { 4096, 1, 1, 1 }, float eps = 1e-6f) : ne(ne), eps(eps) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * a = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne.data()); + ggml_tensor * b = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne.data()); + ggml_tensor * w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, ne[0]); + ggml_set_name(a, "a"); + ggml_set_name(b, "b"); + ggml_set_name(w, "w"); + + sum = ggml_add(ctx, a, b); + ggml_set_name(sum, "sum"); + ggml_tensor * normed = ggml_mul(ctx, ggml_rms_norm(ctx, sum, eps), w); + ggml_set_name(normed, "normed"); + + out = ggml_add(ctx, normed, sum); + 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, -10.f, 10.f); + } + } +}; + // GGML_OP_UNARY(RELU) + GGML_OP_SQR (fused operation) struct test_relu_sqr : public test_case { const ggml_type type; @@ -5394,16 +5513,26 @@ struct test_gated_delta_net : public test_case { const bool permuted; const bool kda; const int64_t K; // snapshot slot count: 1 = final-only, >1 = last K states + const bool correlated; + const bool padded_v; + const bool padded_q; + const bool permuted_k; + // lower bound of the log-gate; a mild gate keeps the state alive over the whole sequence + const float g_min; std::string vars() override { - return VARS_TO_STR9(type, head_count, head_size, n_seq_tokens, n_seqs, v_repeat, permuted, kda, K); + std::string s = VARS_TO_STR13(type, head_count, head_size, n_seq_tokens, n_seqs, v_repeat, permuted, kda, K, correlated, padded_v, padded_q, permuted_k); + if (g_min != -20.0f) { + s += "," + VAR_TO_STR(g_min); + } + return s; } test_gated_delta_net(ggml_type type = GGML_TYPE_F32, int64_t head_count = 4, int64_t head_size = 16, int64_t n_seq_tokens = 1, int64_t n_seqs = 1, - int v_repeat = 1, bool permuted = false, bool kda = false, int64_t K = 1) + int v_repeat = 1, bool permuted = false, bool kda = false, int64_t K = 1, bool correlated = false, bool padded_v = false, bool padded_q = false, bool permuted_k = false, float g_min = -20.0f) : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), - v_repeat(v_repeat), permuted(permuted), kda(kda), K(K) {} + v_repeat(v_repeat), permuted(permuted), kda(kda), K(K), correlated(correlated), padded_v(padded_v), padded_q(padded_q), permuted_k(permuted_k), g_min(g_min) {} ggml_tensor * build_graph(ggml_context * ctx) override { ggml_tensor * q; @@ -5413,11 +5542,15 @@ struct test_gated_delta_net : public test_case { // create with dims 1 and 2 swapped, then permute back to get non-contiguous layout q = ggml_permute(ctx, ggml_new_tensor_4d(ctx, type, head_size, n_seq_tokens, head_count, n_seqs), 0, 2, 1, 3); k = ggml_permute(ctx, ggml_new_tensor_4d(ctx, type, head_size, n_seq_tokens, head_count, n_seqs), 0, 2, 1, 3); - v = ggml_permute(ctx, ggml_new_tensor_4d(ctx, type, head_size, n_seq_tokens, head_count * v_repeat, n_seqs), 0, 2, 1, 3); + v = ggml_permute(ctx, ggml_new_tensor_4d(ctx, type, head_size + padded_v, n_seq_tokens, head_count * v_repeat, n_seqs), 0, 2, 1, 3); } else { q = ggml_new_tensor_4d(ctx, type, head_size, head_count, n_seq_tokens, n_seqs); k = ggml_new_tensor_4d(ctx, type, head_size, head_count, n_seq_tokens, n_seqs); - v = ggml_new_tensor_4d(ctx, type, head_size, head_count * v_repeat, n_seq_tokens, n_seqs); + v = ggml_new_tensor_4d(ctx, type, head_size + padded_v, head_count * v_repeat, n_seq_tokens, n_seqs); + } + if (padded_v) { + ggml_set_name(v, "v"); + v = ggml_view_4d(ctx, v, head_size, head_count * v_repeat, n_seq_tokens, n_seqs, v->nb[1], v->nb[2], v->nb[3], 0); } ggml_set_name(q, "q"); ggml_set_name(k, "k"); @@ -5432,6 +5565,17 @@ struct test_gated_delta_net : public test_case { // q/k are L2-normalised in qwen35/kimi-linear before delta_net q = ggml_l2_norm(ctx, q, 1e-6f); k = ggml_l2_norm(ctx, k, 1e-6f); + // Set layouts after normalization, which produces contiguous tensors. + if (padded_q) { + ggml_tensor * q_padded = ggml_new_tensor_4d(ctx, type, head_size + 1, head_count, n_seq_tokens, n_seqs); + q_padded = ggml_view_4d(ctx, q_padded, head_size, head_count, n_seq_tokens, n_seqs, q_padded->nb[1], q_padded->nb[2], q_padded->nb[3], 0); + q = ggml_cpy(ctx, q, q_padded); + } + if (permuted_k) { + ggml_tensor * k_permuted = ggml_new_tensor_4d(ctx, type, head_size, n_seq_tokens, head_count, n_seqs); + k_permuted = ggml_permute(ctx, k_permuted, 0, 2, 1, 3); + k = ggml_cpy(ctx, k, k_permuted); + } ggml_tensor * out = ggml_gated_delta_net(ctx, q, k, v, g, beta, state, K); return out; } @@ -5440,9 +5584,17 @@ struct test_gated_delta_net : public test_case { for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) { if (ggml_is_view_op(t->op)) { continue; } if (strcmp(t->name, "g") == 0) { - init_tensor_uniform(t, -20.0f, -1e-4f); + init_tensor_uniform(t, correlated ? -1e-4f : g_min, -1e-4f); } else if (strcmp(t->name, "beta") == 0) { - init_tensor_uniform(t, 0.0f, 1.0f); + init_tensor_uniform(t, correlated ? 0.9f : 0.0f, correlated ? 0.9f : 1.0f); + } else if (correlated && strcmp(t->name, "k") == 0) { + // Identical unit keys and weak decay stress cancellation in the triangular solve. + GGML_ASSERT(t->type == GGML_TYPE_F32); + std::vector data(ggml_nelements(t), 0.0f); + for (size_t i = 0; i < data.size(); i += size_t(t->ne[0])) { + data[i] = 1.0f; + } + ggml_backend_tensor_set(t, data.data(), 0, data.size() * sizeof(float)); } else if (strcmp(t->name, "v") == 0) { init_tensor_uniform(t, -0.3f, 5.0f); } else { @@ -7157,6 +7309,10 @@ struct test_rope : public test_case { // the f32 rotation angle of a position below n_ctx carries a rounding error of up to n_ctx*FLT_EPSILON radians // backends compute the angle with different rounding sequences, so their agreement is bounded by that error const double eps_theta = n_ctx * FLT_EPSILON; + if (type == GGML_TYPE_BF16) { + // with BF16 output that error can also change the rounding: a step of 2^-7 with a chance of about eps_theta/2^-7 + return std::max(test_case::max_nmse_err(), eps_theta / 128.0); + } return std::max(test_case::max_nmse_err(), eps_theta * eps_theta); } @@ -7279,9 +7435,10 @@ struct test_col2im_1d : public test_case { const int64_t T_in; // input length (number of columns) const int s0; // stride const int p0; // padding cropped from both sides + const bool view; std::string vars() override { - return VARS_TO_STR6(type, K, OC, T_in, s0, p0); + return VARS_TO_STR7(type, K, OC, T_in, s0, p0, view); } double max_nmse_err() override { @@ -7290,11 +7447,17 @@ struct test_col2im_1d : public test_case { test_col2im_1d(ggml_type type = GGML_TYPE_F32, int64_t K = 4, int64_t OC = 3, int64_t T_in = 7, - int s0 = 2, int p0 = 0) - : type(type), K(K), OC(OC), T_in(T_in), s0(s0), p0(p0) {} + int s0 = 2, int p0 = 0, bool view = false) + : type(type), K(K), OC(OC), T_in(T_in), s0(s0), p0(p0), view(view) {} ggml_tensor * build_graph(ggml_context * ctx) override { - ggml_tensor * cols = ggml_new_tensor_2d(ctx, type, K*OC, T_in); + ggml_tensor * cols; + if (view) { + ggml_tensor * base = ggml_new_tensor_1d(ctx, type, K * OC * T_in + 1); + cols = ggml_view_2d(ctx, base, K * OC, T_in, K * OC * ggml_type_size(type), ggml_type_size(type)); + } else { + cols = ggml_new_tensor_2d(ctx, type, K * OC, T_in); + } ggml_set_name(cols, "cols"); ggml_tensor * out = ggml_col2im_1d(ctx, cols, s0, (int) OC, p0); @@ -10384,6 +10547,33 @@ struct test_fill : public test_case { } }; +// GGML_OP_SLEEP (for scheduler testing only) +struct test_sleep : public test_case { + const ggml_type type; + const std::array ne; + const int32_t us; + + std::string vars() override { return VARS_TO_STR3(type, ne, us); } + + // the op only delays, the output aliases the input and must match it exactly + double max_nmse_err() override { return 0.0; } + + test_sleep(int32_t us = 100, ggml_type type = GGML_TYPE_F32, + std::array ne = { 10, 10, 4, 3 }) + : type(type), ne(ne), us(us) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * a = ggml_new_tensor_4d(ctx, type, ne[0], ne[1], ne[2], ne[3]); + ggml_set_name(a, "a"); + + ggml_tensor * out = ggml_sleep(ctx, a, us); + + ggml_set_name(out, "out"); + + return out; + } +}; + // GGML_OP_SOLVE_TRI struct test_solve_tri : public test_case { const ggml_type type; @@ -11364,6 +11554,7 @@ static std::vector> make_test_cases_eval() { } } } + test_cases.emplace_back(new test_unary(GGML_UNARY_OP_SIGMOID, GGML_TYPE_F32, { 16, 4, 1, 1 })); // fused relu + sqr (squared ReLU) for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32}) { @@ -11543,10 +11734,10 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_get_rows(GGML_TYPE_F32, 1, 8, 2, 1, 1, false)); for (ggml_type type : {GGML_TYPE_Q4_0, GGML_TYPE_Q8_0, GGML_TYPE_Q2_K, GGML_TYPE_Q3_K, GGML_TYPE_Q4_K, GGML_TYPE_Q5_K, GGML_TYPE_Q6_K, - GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ3_S}) { + GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_NL, GGML_TYPE_IQ4_XS}) { test_cases.emplace_back(new test_get_rows_after_mul_mat(type)); } - for (ggml_type type : {GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ3_S}) { + for (ggml_type type : {GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_NL, GGML_TYPE_IQ4_XS}) { test_cases.emplace_back(new test_mul_mat_reorder_then_big_batch(type)); } for (int n : {1, 3, 257}) { @@ -11554,6 +11745,10 @@ static std::vector> make_test_cases_eval() { } // many rows of a wide table, as a per-layer embedding lookup does test_cases.emplace_back(new test_get_rows(GGML_TYPE_F8_E4M3, 160, 100000, 32768, 1, 1, false)); + // past the fused dequant GEMM's column limit the reordered weight goes through the conversion kernels + for (ggml_type type : {GGML_TYPE_IQ4_NL, GGML_TYPE_IQ4_XS}) { + test_cases.emplace_back(new test_mul_mat_reorder_then_big_batch(type, 128)); + } for (ggml_type type : all_types) { for (int b : {1, 7}) { for (bool v : {false, true}) { @@ -11607,6 +11802,12 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_set_rows(GGML_TYPE_F16, GGML_TYPE_F16, GGML_TYPE_I32, { 1, 8, 1, 3 }, { 1, 1 }, 2, false)); test_cases.emplace_back(new test_set_rows(GGML_TYPE_F16, GGML_TYPE_F16, GGML_TYPE_I64, { 1, 8, 1, 3 }, { 1, 1 }, 2, true)); test_cases.emplace_back(new test_set_rows(GGML_TYPE_F16, GGML_TYPE_F16, GGML_TYPE_I32, { 1, 8, 1, 3 }, { 1, 1 }, 2, true)); + // BF16 source: one case per type covers batch dims, broadcast indices and gaps between rows + for (ggml_type type : all_types) { + test_cases.emplace_back(new test_set_rows(GGML_TYPE_BF16, type, GGML_TYPE_I64, { 256, 11, 1, 1 }, { 2, 3, }, 7, true)); + } + test_cases.emplace_back(new test_set_rows(GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_I32, { 256, 5, 1, 3 }, { 1, 1, }, 1, false)); + test_cases.emplace_back(new test_set_rows(GGML_TYPE_BF16, GGML_TYPE_F16, GGML_TYPE_I64, { 1, 8, 1, 3 }, { 1, 1 }, 2, false)); for (int mode : { GGML_ROPE_TYPE_NORMAL, GGML_ROPE_TYPE_NEOX, GGML_ROPE_TYPE_MROPE, GGML_ROPE_TYPE_VISION, GGML_ROPE_TYPE_IMROPE }) { for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32}) { @@ -11617,11 +11818,19 @@ static std::vector> make_test_cases_eval() { } } test_cases.emplace_back(new test_rope_set_rows(GGML_TYPE_F32, GGML_TYPE_I32, { 128, 32, 8, 1 }, GGML_ROPE_TYPE_IMROPE)); + for (int mode : { GGML_ROPE_TYPE_NORMAL, GGML_ROPE_TYPE_NEOX, GGML_ROPE_TYPE_MROPE, GGML_ROPE_TYPE_VISION, GGML_ROPE_TYPE_IMROPE }) { + for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_BF16}) { + for (int ne2 : {1, 8, 512}) { + test_cases.emplace_back(new test_rope_set_rows(type, GGML_TYPE_I64, { 128, 32, ne2, 1 }, mode, 128, false, true, GGML_TYPE_BF16)); + } + } + } // partial rotation for (int mode : { GGML_ROPE_TYPE_NORMAL, GGML_ROPE_TYPE_NEOX, GGML_ROPE_TYPE_MROPE, GGML_ROPE_TYPE_IMROPE }) { for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32}) { test_cases.emplace_back(new test_rope_set_rows(type, GGML_TYPE_I64, { 256, 4, 8, 1 }, mode, 64)); } + test_cases.emplace_back(new test_rope_set_rows(GGML_TYPE_F16, GGML_TYPE_I64, { 256, 4, 8, 1 }, mode, 64, false, true, GGML_TYPE_BF16)); } for (int mode : {GGML_ROPE_TYPE_NORMAL, GGML_ROPE_TYPE_NEOX}) { @@ -12014,6 +12223,11 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_col2im_1d(type, 8, 2, 3, 2, 5)); // cropping eats most of the signal, T_out = 2 } + test_cases.emplace_back(new test_col2im_1d(GGML_TYPE_F32, 5, 3, 17, 2, 1, true)); + for (int64_t n : {255, 256, 257, 16777217}) { + test_cases.emplace_back(new test_col2im_1d(GGML_TYPE_F32, 1, 1, n, 1, 0)); + } + for (ggml_type kernel_type : {GGML_TYPE_F32, GGML_TYPE_F16}) { test_cases.emplace_back(new test_conv_transpose_2d({3, 2, 3, 1}, {2, 2, 1, 3}, 1, kernel_type)); test_cases.emplace_back(new test_conv_transpose_2d({10, 10, 9, 1}, {3, 3, 1, 9}, 2, kernel_type)); @@ -12141,7 +12355,7 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_cpy(GGML_TYPE_F16, GGML_TYPE_F16, {128, 2, 3, 1}, {128, 2, 3, 1}, {0, 0, 0, 0}, {0, 0, 0, 0}, false, {128, 4, 3, 1})); // strided dst test_cases.emplace_back(new test_cpy(GGML_TYPE_F32, GGML_TYPE_F32, {64, 16, 1, 1}, {1, 64, 16, 1}, {1, 2, 0, 3}, {0, 0, 0, 0}, false, {32, 64, 16, 1})); // permuted src, strided dst test_cases.emplace_back(new test_cpy(GGML_TYPE_F16, GGML_TYPE_F16, {64, 16, 1, 1}, {1, 64, 16, 1}, {1, 2, 0, 3}, {0, 0, 0, 0}, false, {32, 64, 16, 1})); // permuted src, strided dst - + test_cases.emplace_back(new test_cpy(GGML_TYPE_F32, GGML_TYPE_F32, {2, 2, 524281, 1}, {-1,-1,-1,-1}, {1, 0, 2, 3})); // CPY - different src/dst shapes (reshaping via CPY) // Use permutations of {3, 5, 7, 32}. Total elements: 3*5*7*32 = 3360. // Each src permutation is tested against canonical sorted and reverse dst (skip self). @@ -12330,8 +12544,10 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_scale(GGML_TYPE_F32, {10, 10, 10, 10}, 2.0f, 1.0f, false, 1)); // view test test_cases.emplace_back(new test_scale(GGML_TYPE_F32, {10, 10, 10, 10}, 2.0f, 1.0f, true, 1)); // view test, inplace test_cases.emplace_back(new test_scale(GGML_TYPE_BF16, {10, 10, 10, 10}, 2.0f, 1.0f, true, 1)); // view test, inplace + test_cases.emplace_back(new test_scale(GGML_TYPE_F16, {10, 10, 10, 10}, 2.0f, 1.0f, false, 1)); // view test test_cases.emplace_back(new test_softcap(GGML_TYPE_F32, {10, 10, 10, 10}, 50.0f)); test_cases.emplace_back(new test_silu_back()); + test_cases.emplace_back(new test_sigmoid_back()); for (float eps : { 0.0f, 1e-6f, 1e-4f, 1e-1f, 10.f }) { for (uint32_t n : { 64, 1025 }) { @@ -12416,6 +12632,7 @@ static std::vector> make_test_cases_eval() { for (uint32_t n : { 64, 1025 }) { test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, false)); test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, true)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, false, false, false, false, false, GGML_TYPE_COUNT, GGML_TYPE_COUNT, true)); test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { n, 5, 4, 3 }, eps, false, false, false, false, false, GGML_TYPE_F32)); test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { n, 5, 4, 3 }, eps, true, false, false, false, false, GGML_TYPE_F32)); test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { n, 5, 4, 3 }, eps, true, false, false, false, false, GGML_TYPE_F32, GGML_TYPE_BF16)); @@ -12439,6 +12656,13 @@ static std::vector> make_test_cases_eval() { } } + // decode-shaped residual rows: below, at and above the fused path's limits, odd row counts, batches + for (int64_t n : { 1020, 1024, 4096, 5120, 8192, 8196, 16384 }) { + for (int64_t rows : { 1, 3, 4 }) { + test_cases.emplace_back(new test_add_rms_norm_mul({ n, rows, 1, 1 }, 1e-6f)); + } + test_cases.emplace_back(new test_add_rms_norm_mul({ n, 2, 3, 1 }, 1e-6f)); + } for (uint32_t n : {64, 1025}) { test_cases.emplace_back(new test_add_add(GGML_TYPE_F32, GGML_TYPE_F32, { n, 5, 4, 3 }, false, false)); test_cases.emplace_back(new test_add_add(GGML_TYPE_F32, GGML_TYPE_F32, { n, 5, 4, 3 }, true, false)); @@ -12751,8 +12975,8 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_mul_mat(type_a, GGML_TYPE_F32, 16, 8, 16*256, { 1, 1}, {1, 1})); } - // Multi-column MMVQ coverage for the Q4_K weight-reuse path and a Q5_K control. - for (ggml_type type_a : { GGML_TYPE_Q4_K, GGML_TYPE_Q5_K }) { + // Multi-column MMVQ coverage for the Q4_K and IQ4 weight-reuse paths and a Q5_K control. + for (ggml_type type_a : { GGML_TYPE_Q4_K, GGML_TYPE_Q5_K, GGML_TYPE_IQ4_NL, GGML_TYPE_IQ4_XS }) { for (int n = 1; n <= 8; ++n) { test_cases.emplace_back(new test_mul_mat(type_a, GGML_TYPE_F32, 4096, n, 1024, { 1, 1 }, { 1, 1 })); test_cases.emplace_back(new test_mul_mat(type_a, GGML_TYPE_F32, 1023, n, 4096, { 1, 1 }, { 1, 1 })); @@ -13254,6 +13478,9 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_BF16, GGML_TYPE_F32, 16, 16, b, 50, 200, 64)); } + // One very large one to trigger a code path in CUDA requiring >1 pass over expert IDs due to shared memory limits: + test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_Q8_0, GGML_TYPE_F32, 16, 16, false, 32, 65536, 256)); + // For issue 27873 test_cases.emplace_back(new test_mul_mat_id(GGML_TYPE_IQ2_XXS, GGML_TYPE_F32, 1, 1, false, 1, 8192, 4096)); @@ -13314,8 +13541,6 @@ static std::vector> make_test_cases_eval() { } } - // TODO: disabled until CUDA backend support is added [TAG_MUL_MAT_ID_DUPLICATE_ID] -#if 0 // repeated expert ids within a row for (ggml_type ta : {GGML_TYPE_F16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0}) { for (int n : {9, 16, 33, 64}) { @@ -13327,7 +13552,6 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_mul_mat_id_dup(ta, GGML_TYPE_F32, 1025, 10, false, 64, 33, 256, 0, true)); test_cases.emplace_back(new test_mul_mat_id_dup(ta, GGML_TYPE_F32, 2050, 10, true, 64, 33, 256)); } -#endif for (ggml_type type_a : all_types) { test_cases.emplace_back(new test_mul_mat_id(type_a, GGML_TYPE_F32, 4, 2, false, 64, 16, 3*ggml_blck_size(type_a))); @@ -13628,8 +13852,17 @@ static std::vector> make_test_cases_eval() { } } + // BF16: each mode forward on a strided view and backward on an offset view, with and without freq factors, and one in place + for (int mode : {GGML_ROPE_TYPE_NORMAL, GGML_ROPE_TYPE_NEOX, GGML_ROPE_TYPE_MROPE, GGML_ROPE_TYPE_IMROPE, GGML_ROPE_TYPE_VISION}) { + for (bool ff : {false, true}) { + test_cases.emplace_back(new test_rope(GGML_TYPE_BF16, {128, 32, 2, 1}, 128, mode, 512, 1.4245f, 0.7465f, 1.4245f, ff, 1, true)); + test_cases.emplace_back(new test_rope(GGML_TYPE_BF16, {128, 32, 2, 1}, 128, mode, 512, 1.4245f, 0.7465f, 1.4245f, ff, 2, false)); + } + test_cases.emplace_back(new test_rope(GGML_TYPE_BF16, {128, 32, 2, 1}, 128, mode, 512, 1.4245f, 0.7465f, 1.4245f, false, 0, true, true)); + } + // rotated dims window at an offset (ggml_rope_set_offset), not supported for vision mode - for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16}) { + for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16}) { for (bool fw : {true, false}) { // fw == forward for (bool ff : {false, true}) { test_cases.emplace_back(new test_rope(type, {128, 32, 2, 1}, 32, GGML_ROPE_TYPE_NORMAL, 512, 1.4245f, 0.7465f, 1.4245f, ff, 0, fw, false, 32)); @@ -13935,6 +14168,10 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_fill(-152.0f, GGML_TYPE_F16, { 800, 600, 4, 4 })); test_cases.emplace_back(new test_fill(3.5f, GGML_TYPE_F16, { 2048, 512, 2, 2 })); + test_cases.emplace_back(new test_sleep(0)); + test_cases.emplace_back(new test_sleep(10, GGML_TYPE_F16, { 128, 4, 2, 2 })); + test_cases.emplace_back(new test_sleep(10, GGML_TYPE_F32, { 128, 4, 2, 2 })); + for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16}) { test_cases.emplace_back(new test_diag(type)); test_cases.emplace_back(new test_diag(type, { 79, 1, 19, 13 })); @@ -14517,6 +14754,15 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 33, 1, 1, false, true)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 100, 1, 1, false, true)); + // KDA at D=128: decode, prefill, tails, strides, and snapshots. + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 1, 1, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 64, 1, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 65, 2, 2, true, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 1, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 65, 1, 1, false, true, 1, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 1, 1, true, true, 1, true, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 4, 2, 2, false, true, 4)); + // MMA-eligible GDN shapes: whole heads, value slices, tails, and the HIP prefill threshold. test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 65, 1, 1)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 65, 3, 4)); @@ -14528,6 +14774,43 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 2048, 1, 2)); // Keep the WebGPU dispatch below 65535 workgroups (32 per token for this shape). test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 2047, 2, 3)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 4097, 1, 2)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 127, 2)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 256, 1, 2)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 256, 1, 3)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 513, 1, 2)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 512, 2, 2)); + + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 2, 2, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 129, 1, 1, false, false, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 4095, 1, 2)); + + // Correlated keys, high beta, and weak decay stress the chunked triangular solve. + for (int64_t n_tokens : {64, 65, 257}) { + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, n_tokens, 1, 1, false, false, 1, true)); + } + + // Odd V strides require element loads instead of aligned matrix loads. + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 65, 1, 1, false, false, 1, false, true)); + + // Q and K can have different strides in both scalar and chunked paths. + for (int64_t n_tokens : {4, 65}) { + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, 1, false, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, 1, false, false, false, true)); + } + // mild decay keeps the state alive across the sequence; qwen35 prefill layout with K=5 snapshots + for (int64_t n : { 5, 300, 2048 }) { + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, n, 1, 3, false, false, /*K=*/5, false, false, false, false, /*g_min=*/-0.05f)); + } + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 300, 2, 2, true, false, /*K=*/1, false, false, false, false, /*g_min=*/-0.05f)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 200, 1, 1, false, false, /*K=*/5, false, false, false, false, /*g_min=*/-0.05f)); + // a backend may pick its kernel by head count: few and many heads, per head size, plain and KDA + for (int64_t s : { 16, 32, 64, 128 }) { + for (int64_t h : { 4 * 128 / s, 64 * 128 / s }) { + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, h, s, 37, 1, 1, false, false, /*K=*/4, false, false, false, false, /*g_min=*/-0.05f)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, h, s, 37, 1, 1, false, true, /*K=*/1, false, false, false, false, /*g_min=*/-0.05f)); + } + } // K > 1: output keeps the last min(n_tokens, K) per-token snapshots, ordered most-recent-first // (slot 0 = final state, slot s = state s tokens back). @@ -14549,6 +14832,7 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 64, 4, 1, 2)); test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 4, 1, 4)); test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 8, 32, 4, 2, 4)); + test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 128, 64, 4, 1, 4)); test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 8, 1, 4)); #if 0 @@ -15091,7 +15375,7 @@ static std::vector> make_test_cases_perf() { } for (bool fw : {true, false}) { // fw == forward - for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16}) { + for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16}) { for (bool ff : {false, true}) { // freq_factors for (float v : { 0, 1 }) { test_cases.emplace_back(new test_rope(type, {128, 32, 512, 1}, 128, GGML_ROPE_TYPE_NORMAL, 512, 1.0f, 0.0f, 1.0f, ff, v, fw)); // llama 7B @@ -15128,6 +15412,12 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_argsort(GGML_TYPE_F32, {200000, 1, 1, 1})); test_cases.emplace_back(new test_argsort(GGML_TYPE_F32, {200000, 16, 1, 1})); + // Independent perf cases using upsampling layer shapes from the Drama 3 audio codec decoder. + test_cases.emplace_back(new test_conv_transpose_1d({16, 1536, 1, 1}, {16, 768, 1536, 1}, 8, 0, 1)); + test_cases.emplace_back(new test_conv_transpose_1d({128, 768, 1, 1}, {16, 384, 768, 1}, 8, 0, 1)); + test_cases.emplace_back(new test_conv_transpose_1d({1024, 384, 1, 1}, {8, 192, 384, 1}, 4, 0, 1)); + test_cases.emplace_back(new test_conv_transpose_1d({4096, 192, 1, 1}, {4, 96, 192, 1}, 2, 0, 1)); + test_cases.emplace_back(new test_top_k(GGML_TYPE_F32, {2, 1, 1, 1}, 1)); // widths around the tiling threshold for (auto cols : {4096, 8192, 12288, 16384, 24576, 32768, 65536, 131072}) { @@ -15219,12 +15509,35 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 256, 1)); // PP-256 test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 512, 1)); // PP-512 test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 1024, 1)); // PP-1024 + // MMA-eligible prefill sweep (16 heads, d=128, K=1): Vulkan cm2 vs CUDA MMA + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 64, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 128, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 256, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 512, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 1024, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 2048, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 4096, 1)); // Small model configs (fewer heads = less GPU occupancy for autoregressive) test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 64, 1)); // 4h PP-64 test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 256, 1)); // 4h PP-256 test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 512, 1)); // 4h PP-512 test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 1024, 1)); // 4h PP-1024 test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 64, 1, 1, false, true)); // KDA PP-64 + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 64, 1, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 256, 1, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 1024, 1, 1, false, true)); + // GDN model shapes: 35B (v_repeat=2), 27B (v_repeat=3), batch sweep + for (int T : { 2048, 4096, 8192, 16384, 32768 }) { + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, T, 1, 2)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, T, 1, 3)); + } + + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 2048, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 4096, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 8192, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 20, 128, 1536, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 20, 128, 2048, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 2048, 1, 3, false, false, 5)); // qwen35 PP-2048, K=5 // lightning_indexer for (int kv : { 256, 4096, 65536 }) { diff --git a/tests/test-backend-sched.cpp b/tests/test-backend-sched.cpp new file mode 100644 index 000000000000..8afdcc7caadd --- /dev/null +++ b/tests/test-backend-sched.cpp @@ -0,0 +1,1084 @@ +// Test suite for scheduler and backend behavior + +// Towards formalized scheduling behavior: +// - a single inference pass can run on several backends. The subset of nodes running on a single backend is a split +// - synchronous backends: +// - explicit synchronization (ggml_backend_synchronize()) is required between each operation +// - asynchronous backends: +// - Activations from one split can be copied asynchronously to the next (output of split N -> input of split N+1) +// - Several scheduling patterns must be supported by async backends. The scheduler may: +// - not explicitly synchronize between CPU->backend memcpy and graph execution on backend +// - dispatch several parallel memcpys to the same backend at once +// - schedule splits without inputs at any point in the graph + +#include "ggml.h" +#include "ggml-alloc.h" +#include "ggml-backend.h" +#include "ggml-cpp.h" + +#include +#include +#include +#include +#include +#include +#include + + + +enum test_result { + TEST_FAIL = 0, + TEST_OK = 1, + TEST_SKIP = 2, // in case a backend does not support a required OP (e.g. OP_SLEEP) +}; + +// global counters for pass/fail/skip +static int n_ok = 0; +static int n_skip = 0; +static int n_test = 0; + +// default silent on success; --verbose / -v prints progress +static bool print_log = false; + +GGML_ATTRIBUTE_FORMAT(1, 2) +static void log_maybe(const char * fmt, ...) { + if (!print_log) { + return; + } + + va_list args; + va_start(args, fmt); + vprintf(fmt, args); + va_end(args); +} + +// pretty-print helpers start +static constexpr int status_column = 82; // for ok/fail column alignment +static int case_len = 0; +static char case_label[256]; // max length of a case label + +static void case_end(test_result res) { + n_ok += res == TEST_OK; + n_skip += res == TEST_SKIP; + n_test++; + + if (res != TEST_FAIL && !print_log) { + case_len = 0; + return; + } + + if (case_len == 0) { + case_len = printf(" %s", case_label); + } + + const char * status = "FAIL"; + if (res == TEST_OK) { + status = "OK"; + } else if (res == TEST_SKIP) { + status = "SKIP"; + } + + printf("%*s%s\n", std::max(1, status_column - case_len), "", status); + case_len = 0; +} + +static void vnote(const char * fmt, va_list args) { + if (case_len != 0) { + printf("\n"); + } + printf(" "); + vprintf(fmt, args); + printf("\n"); + + case_len = 0; +} + +GGML_ATTRIBUTE_FORMAT(1, 2) +static void note(const char * fmt, ...) { + if (!print_log) { + return; + } + + va_list args; + va_start(args, fmt); + vnote(fmt, args); + va_end(args); +} + +GGML_ATTRIBUTE_FORMAT(1, 2) +static test_result fail(const char * fmt, ...) { + if (case_len == 0) { + case_len = printf(" %s", case_label); + } + + va_list args; + va_start(args, fmt); + vnote(fmt, args); + va_end(args); + + return TEST_FAIL; +} + +GGML_ATTRIBUTE_FORMAT(1, 2) +static test_result skip(const char * fmt, ...) { + if (print_log) { + va_list args; + va_start(args, fmt); + vnote(fmt, args); + va_end(args); + } + + return TEST_SKIP; +} + +GGML_ATTRIBUTE_FORMAT(1, 2) +static void case_begin(const char * fmt, ...) { + va_list args; + va_start(args, fmt); + vsnprintf(case_label, sizeof(case_label), fmt, args); + va_end(args); + + if (print_log) { + case_len = printf(" %s", case_label); + fflush(stdout); + } else { + case_len = 0; + } +} +// pretty-print helpers end + + +// NB: the last backend passed has to be the CPU backend (cf. ggml_backend_sched_new) +static ggml_backend_sched_ptr create_test_scheduler(std::vector backends, size_t graph_size, + bool use_device_host_buft, bool parallel = false) { + + std::vector bufts(backends.size()); + for (size_t b = 0; b < backends.size(); b++) { + bufts[b] = ggml_backend_get_default_buffer_type(backends[b]); + } + + // pinned memory for the CPU backend (always required to be the last backend) enables async copies to other devices + // the host buffer type comes from the first backend, (cf. llama_context::llama_context()) + if (use_device_host_buft) { + ggml_backend_buffer_type_t host = ggml_backend_dev_host_buffer_type(ggml_backend_get_device(backends[0])); + if (host != nullptr) { + bufts.back() = host; + } + } + + return ggml_backend_sched_ptr(ggml_backend_sched_new(backends.data(), bufts.data(), (int) backends.size(), + graph_size, parallel, /*op_offload =*/ false)); +} + +// the nodes of the graph together with the backend each of them is assigned to +struct helper_graph { + ggml_cgraph * gf; + std::vector nodes; + std::vector backend_id; + + helper_graph(ggml_context * ctx, size_t graph_size) : gf(ggml_new_graph_custom(ctx, graph_size, /*grads =*/ false)) {} + + ggml_tensor * add(ggml_tensor * node, int backend) { + nodes.push_back(node); + backend_id.push_back(backend); + ggml_build_forward_expand(gf, node); + + return node; + } +}; + +struct helper_check { + ggml_tensor * tensor; // Tensor for which to check the data. + float expected; // The expected value that the tensor data should have after graph execution. +}; + +// asks whether the backend implements the op, independent of where the sources of this node currently live. +static bool backend_supports_op(ggml_backend_t backend, const ggml_tensor * node) { + ggml_init_params params = { + /*.mem_size =*/ GGML_MAX_SRC*ggml_tensor_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx(ggml_init(params)); + + ggml_tensor probe = *node; + probe.buffer = nullptr; + probe.view_src = nullptr; + probe.data = nullptr; + + for (ggml_tensor *& src : probe.src) { + if (src != nullptr) { + src = ggml_dup_tensor(ctx.get(), src); + } + } + + return ggml_backend_supports_op(backend, &probe); +} + +// executes the graph, then checks the number of splits and the results +static test_result run_and_check(ggml_backend_sched_t sched, const helper_graph & g, + const std::vector & backends, const std::vector & checks, int64_t ne) { + + // ggml_backend_sched_set_tensor_backend does not validate the op, an unsupported one would abort inside the backend + for (size_t i = 0; i < g.nodes.size(); i++) { + ggml_backend_t backend = backends[g.backend_id[i]]; + if (!backend_supports_op(backend, g.nodes[i])) { + return skip("%s does not support %s", ggml_backend_name(backend), ggml_op_name(g.nodes[i]->op)); + } + } + + // to later check if any further graph logic alters the number of splits + int n_splits_expected = g.nodes.empty() ? 0 : 1; + for (size_t i = 1; i < g.backend_id.size(); i++) { + n_splits_expected += g.backend_id[i] != g.backend_id[i - 1]; + } + + ggml_backend_sched_reset(sched); + for (size_t i = 0; i < g.nodes.size(); i++) { + ggml_backend_sched_set_tensor_backend(sched, g.nodes[i], backends[g.backend_id[i]]); + } + + if (!ggml_backend_sched_alloc_graph(sched, g.gf)) { + return fail("failed to allocate the graph"); + } + + if (ggml_backend_sched_graph_compute(sched, g.gf) != GGML_STATUS_SUCCESS) { + return fail("failed to compute the graph"); + } + + const int n_splits = ggml_backend_sched_get_n_splits(sched); + if (n_splits != n_splits_expected) { + return fail("n_splits = %d, expected %d, each split consisting of just a single node", n_splits, n_splits_expected); + } + + std::vector data(ne); + for (const helper_check & c : checks) { + ggml_backend_tensor_get(c.tensor, data.data(), 0, ggml_nbytes(c.tensor)); + for (int64_t i = 0; i < ne; i++) { + if (data[i] != c.expected) { + return fail("%s[%" PRId64 "] = %f, expected %f", ggml_get_name(c.tensor), i, data[i], c.expected); + } + } + } + + return TEST_OK; +} + +// helper struct for inputless splits, and constants like 0 and 1 +struct backend_consts { + // the buffers are declared after the contexts, so that they are released first + std::vector ctxs; + std::vector bufs; + std::vector zero; + std::vector one; + + backend_consts(const std::vector & backends, int64_t ne) { + std::vector data(ne); + + for (size_t b = 0; b < backends.size(); b++) { + ggml_init_params params = { + /*.mem_size =*/ 2*ggml_tensor_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context * ctx = ggml_init(params); + + ggml_tensor * z = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, ne); + ggml_format_name(z, "zero_%s", ggml_backend_name(backends[b])); + + ggml_tensor * o = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, ne); + ggml_format_name(o, "one_%s", ggml_backend_name(backends[b])); + + ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors(ctx, backends[b]); + GGML_ASSERT(buf != nullptr); + + std::fill(data.begin(), data.end(), 0.0f); + ggml_backend_tensor_set(z, data.data(), 0, ggml_nbytes(z)); + + std::fill(data.begin(), data.end(), 1.0f); + ggml_backend_tensor_set(o, data.data(), 0, ggml_nbytes(o)); + + ctxs.emplace_back(ctx); + bufs.emplace_back(buf); + zero.push_back(z); + one.push_back(o); + } + } +}; + +// TODO add tests for the auto-assign logic of nodes to backends of the scheduler. Possible tests: +// - test of CPU backend with any other backend. Expectation is that GEMM-nodes (usually the first accelerated components) are assigned to the non-CPU backend +// - test of the property that tensor location influences backend assignment. +// - test of neighbor propagation logic? 3 nodes, with the middle one initially on CPU, moved to the other backend? + + +// stress test: a tensor is incremented and sent back and forth between the backends in a ping-pong pattern. +// One pass pairs every backend a with every other backend b via nested loops. +// The counter is brought to a, then bounced to b and back for every partner in turn. +// So one pass copies an activation across every ordered pair of backends. +// Every lap runs two passes: one where the nodes add the constant 1, one where they add a user input +// from the CPU backend, so that every transition is tested with and without an input next to the activation. +// The input values come from a fixed seed. +static test_result stress_test_linked_list(const std::vector & backends, int n_laps, + int64_t tensor_len, bool use_device_host_buft) { + const int n_backends = (int) backends.size(); + + // per pass and backend a: one node to bring the counter to a, then two per partner for the ping-pong + const int n_nodes_pass = n_backends*(2*n_backends - 1); + const int n_nodes = 2*n_laps*n_nodes_pass; + const int n_inputs = n_laps*n_nodes_pass; // one per node of the pass that takes user inputs + + // initial pseudo-random value draw so that the expected result is known before graph execution + std::mt19937 rng(42); + std::uniform_int_distribution draw_value(1, 10000); + + std::vector input_value(n_inputs); // random values store + int64_t sum_inputs = 0; + + for (int i = 0; i < n_inputs; i++) { + input_value[i] = draw_value(rng); + sum_inputs += input_value[i]; + } + + // see sched->hash_set FIXME, the set has to hold the nodes and the leafs: two constants per backend + // plus the user inputs + const size_t graph_size = n_nodes + 2*n_backends + n_inputs; + + backend_consts consts(backends, tensor_len); + + ggml_backend_sched_ptr sched = create_test_scheduler(backends, graph_size, use_device_host_buft); + + // the user inputs all live on the CPU backend, with the same buffer type the scheduler uses for it + ggml_init_params params_input = { + /*.mem_size =*/ n_inputs*ggml_tensor_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_input(ggml_init(params_input)); + ggml_backend_buffer_ptr buf_input; + + std::vector input(n_inputs); + for (int i = 0; i < n_inputs; i++) { + input[i] = ggml_new_tensor_1d(ctx_input.get(), GGML_TYPE_F32, tensor_len); + ggml_format_name(input[i], "input%d", i); + ggml_set_input(input[i]); + } + + // the inputs follow the buffer type the scheduler uses for the CPU backend (cf. create_test_scheduler) + ggml_backend_buffer_type_t buft = ggml_backend_get_default_buffer_type(backends.back()); + if (use_device_host_buft) { + ggml_backend_buffer_type_t host = ggml_backend_dev_host_buffer_type(ggml_backend_get_device(backends[0])); + if (host != nullptr) { + buft = host; + } + } + + buf_input.reset(ggml_backend_alloc_ctx_tensors_from_buft(ctx_input.get(), buft)); + GGML_ASSERT(buf_input != nullptr); + + // write inputs before graph execution + std::vector data(tensor_len); + for (int i = 0; i < n_inputs; i++) { + std::fill(data.begin(), data.end(), float(input_value[i])); + ggml_backend_tensor_set(input[i], data.data(), 0, ggml_nbytes(input[i])); + } + + ggml_init_params params_compute = { + /*.mem_size =*/ (n_nodes + 2)*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + + helper_graph g(ctx_compute.get(), graph_size); + + int64_t sum = 0; + ggml_tensor * out = nullptr; + + int i = 0; // next user input to consume + + // increments the counter on backend b, which makes the scheduler copy it there from the previous backend + auto step = [&](int b, bool with_input) { + ggml_tensor * src = out == nullptr ? consts.zero[b] : out; + + if (with_input) { + out = g.add(ggml_add(ctx_compute.get(), src, input[i]), b); + i++; + } else { + out = g.add(ggml_add(ctx_compute.get(), src, consts.one[b]), b); + sum += 1; + } + }; + + for (int lap = 0; lap < n_laps; lap++) { + for (bool with_input : { false, true }) { // test each transition with and without input + for (int a = 0; a < n_backends; a++) { + step(a, with_input); + + for (int b = 0; b < n_backends; b++) { + if (b == a) { + continue; + } + + step(b, with_input); + step(a, with_input); + } + } + } + } + ggml_set_name(out, "out"); + ggml_set_output(out); + + // every node adds either the constant 1 or its drawn user input + const int64_t expected = sum + sum_inputs; + + note("%d of %d nodes take a user input, they contribute %" PRId64 " of %" PRId64, n_inputs, n_nodes, sum_inputs, expected); + + test_result ok; + if (expected >= (1 << 24)) { // the counter has to stay exact in f32 + ok = fail("expected result %" PRId64 " does not fit into the f32 mantissa, lower n_laps", expected); + } else { + ok = run_and_check(sched.get(), g, backends, {{ out, float(expected) }}, tensor_len); + } + + return ok; +} + +// Same idea as stress_test_linked_list, but with the compute graph being a directed acyclic graph (DAG). +// n_lanes independent counters run through rounds of four shapes, so that one graph covers: +// - lanes with different histories, so a misrouted copy shows up as a wrong count in a single lane +// - one split producing two values followed by two splits that each consume one of them and do not depend on each other +// - splits with no inputs at all, from lanes re-seeded out of constants that already live on the split's backend +// - splits taking one activation per lane from the previous split, one of them from an older split instead +static test_result stress_test_dag(const std::vector & backends, int n_lanes, int n_rounds, + int64_t tensor_len, bool use_device_host_buft) { + + const int n_backends = (int) backends.size(); + + GGML_ASSERT(n_lanes % 2 == 0); + + // sized for the worst case + const size_t graph_size = n_lanes*(2*n_rounds + 1) + 2*n_backends; + + backend_consts consts(backends, tensor_len); + + ggml_backend_sched_ptr sched = create_test_scheduler(backends, graph_size, use_device_host_buft); + + ggml_init_params params_compute = { + /*.mem_size =*/ (graph_size + 8)*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + + helper_graph g(ctx_compute.get(), graph_size); + + std::vector lane(n_lanes); + std::vector value(n_lanes); + std::vector checks; + + // every lane starts at a different value, so that a misrouted copy changes a sum instead of going unnoticed + auto seed = [&](int b, const char * prefix) { + for (int l = 0; l < n_lanes; l++) { + lane[l] = g.add(ggml_add(ctx_compute.get(), l == 0 ? consts.zero[b] : lane[l - 1], consts.one[b]), b); + value[l] = l + 1; + ggml_format_name(lane[l], "%s%d", prefix, l); + } + }; + + auto check_lanes = [&]() { + for (int l = 0; l < n_lanes; l++) { + ggml_set_output(lane[l]); + checks.push_back({ lane[l], float(value[l]) }); + } + }; + + seed(0, "seed"); + + std::vector older = lane; + std::vector value_older = value; + + for (int round = 0; round < n_rounds; round++) { + // a backend the previous node did not use, so that the round is not absorbed into the split before it + const int b = (g.backend_id.back() + 1) % n_backends; + + const std::vector prev = lane; + const std::vector value_prev = value; + + switch (round % 5) { + case 0: + for (int p = 0; p < n_lanes/2; p++) { + const int la = 2*p; + const int lb = 2*p + 1; + const int prod = (b + p) % n_backends; + const int cons = (prod + 1) % n_backends; + + // one split producing two values ... + for (int l : { la, lb }) { + lane[l] = g.add(ggml_add(ctx_compute.get(), lane[l], consts.one[prod]), prod); + value[l]++; + ggml_format_name(lane[l], "r%d_prod%d", round, l); + } + + // ... and two splits that each consume one of them, with no dependency on each other + lane[la] = g.add(ggml_add(ctx_compute.get(), lane[la], consts.one[cons]), cons); + value[la]++; + ggml_format_name(lane[la], "r%d_cons%d", round, la); + + lane[lb] = g.add(ggml_add(ctx_compute.get(), lane[lb], consts.one[prod]), prod); + value[lb]++; + ggml_format_name(lane[lb], "r%d_cons%d", round, lb); + } + break; + case 1: + check_lanes(); + seed(b, "restart"); + break; + case 2: + case 3: + for (int l = 0; l < n_lanes; l++) { + const int partner = (l + 1 + round) % n_lanes; + const bool reach_back = round >= 2 && l == round % n_lanes; + + ggml_tensor * a = reach_back ? older[l] : prev[l]; + const int64_t va = reach_back ? value_older[l] : value_prev[l]; + + lane[l] = g.add(ggml_add(ctx_compute.get(), a, prev[partner]), b); + value[l] = va + value_prev[partner]; + ggml_format_name(lane[l], "r%d_lane%d", round, l); + } + break; + case 4: + lane[0] = g.add(ggml_add(ctx_compute.get(), prev[0], consts.one[b]), b); + value[0] = value_prev[0] + 1; + ggml_format_name(lane[0], "r%d_single", round); + break; + default: + GGML_ABORT("unexpected round %d", round); + } + + older = prev; + value_older = value_prev; + } + + check_lanes(); + + test_result ok = TEST_OK; + for (const helper_check & c : checks) { + if (c.expected >= float(1 << 24)) { // the counts have to stay exact in f32 + ok = fail("expected result %.0f does not fit into the f32 mantissa, lower n_rounds", c.expected); + break; + } + } + + if (ok == TEST_OK) { + ok = run_and_check(sched.get(), g, backends, checks, tensor_len); + } + + return ok; +} + +// Created in response to https://github.com/ggml-org/llama.cpp/issues/23321 +// Currently, input copies to splits synchronize split execution. +// CPU split N+1 could overwrite output of split N if this was not copied to backend in time. +// Mechanism to test: GPU split with long sleep to clog CUDA stream / vk command queue, +// followed by CPU splits without input, provoking a race condition in the current setup. +// GPU: 100ms sleep to clog stream/queue +// CPU: produce {55} +// GPU: request copy of {55} in CUDA stream, ADD {44}; Output should be {99} +// CPU: produce {66} +// GPU: increment both {99} and {66} -> {100} and {67} +// Correct result is thus {100}, incorrect output is {111} when {55} was overwritten by {66} before the copy started. +// Note: currently only reproducible on async H2D copy (=pinned memory). +static test_result test_inputless_splits_scheduling(ggml_backend_t gpu, ggml_backend_t cpu, int64_t tensor_len, int32_t sleep_us, bool use_device_host_buft) { + + const int GPU = 0; + const int CPU = 1; + + const std::vector backends = { gpu, cpu }; + + const size_t graph_size = 64; + + ggml_backend_sched_ptr sched = create_test_scheduler(backends, graph_size, use_device_host_buft); + + ggml_init_params params_static = { + /*.mem_size =*/ 4*ggml_tensor_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + + ggml_context_ptr ctx_cpu(ggml_init(params_static)); + + ggml_tensor * zero_cpu = ggml_new_tensor_1d(ctx_cpu.get(), GGML_TYPE_F32, tensor_len); + ggml_set_name(zero_cpu, "zero_cpu"); + + ggml_tensor * val55_cpu = ggml_new_tensor_1d(ctx_cpu.get(), GGML_TYPE_F32, tensor_len); + ggml_set_name(val55_cpu, "val55_cpu"); + + ggml_tensor * val66_cpu = ggml_new_tensor_1d(ctx_cpu.get(), GGML_TYPE_F32, tensor_len); + ggml_set_name(val66_cpu, "val66_cpu"); + + ggml_backend_buffer_ptr buf_cpu(ggml_backend_alloc_ctx_tensors(ctx_cpu.get(), cpu)); + GGML_ASSERT(buf_cpu != nullptr); + + ggml_context_ptr ctx_gpu(ggml_init(params_static)); + + ggml_tensor * zero_gpu = ggml_new_tensor_1d(ctx_gpu.get(), GGML_TYPE_F32, tensor_len); + ggml_set_name(zero_gpu, "zero_gpu"); + + ggml_tensor * one_gpu = ggml_new_tensor_1d(ctx_gpu.get(), GGML_TYPE_F32, tensor_len); + ggml_set_name(one_gpu, "one_gpu"); + + ggml_tensor * val44_gpu = ggml_new_tensor_1d(ctx_gpu.get(), GGML_TYPE_F32, tensor_len); + ggml_set_name(val44_gpu, "val44_gpu"); + + ggml_backend_buffer_ptr buf_gpu(ggml_backend_alloc_ctx_tensors(ctx_gpu.get(), gpu)); + GGML_ASSERT(buf_gpu != nullptr); + + std::vector data(tensor_len); + + std::fill(data.begin(), data.end(), 0.0f); + ggml_backend_tensor_set(zero_cpu, data.data(), 0, ggml_nbytes(zero_cpu)); + ggml_backend_tensor_set(zero_gpu, data.data(), 0, ggml_nbytes(zero_gpu)); + + std::fill(data.begin(), data.end(), 1.0f); + ggml_backend_tensor_set(one_gpu, data.data(), 0, ggml_nbytes(one_gpu)); + + std::fill(data.begin(), data.end(), 44.0f); + ggml_backend_tensor_set(val44_gpu, data.data(), 0, ggml_nbytes(val44_gpu)); + + std::fill(data.begin(), data.end(), 55.0f); + ggml_backend_tensor_set(val55_cpu, data.data(), 0, ggml_nbytes(val55_cpu)); + + std::fill(data.begin(), data.end(), 66.0f); + ggml_backend_tensor_set(val66_cpu, data.data(), 0, ggml_nbytes(val66_cpu)); + + ggml_init_params params_compute = { + /*.mem_size =*/ (graph_size + 8)*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + + helper_graph g(ctx_compute.get(), graph_size); + + // GPU: add then sleep - occupies the GPU while later splits run + ggml_tensor * delayed = g.add(ggml_add(ctx_compute.get(), zero_gpu, one_gpu), GPU); + ggml_set_name(delayed, "to_delay"); + delayed = g.add(ggml_sleep(ctx_compute.get(), delayed, sleep_us), GPU); + ggml_set_name(delayed, "delayed"); + + // CPU: 0 + 55 -> 55 + ggml_tensor * v55 = g.add(ggml_add(ctx_compute.get(), zero_cpu, val55_cpu), CPU); + ggml_set_name(v55, "v55"); + + // GPU: 55 + 44 -> 99 + ggml_tensor * v99 = g.add(ggml_add(ctx_compute.get(), v55, val44_gpu), GPU); + ggml_set_name(v99, "v99"); + + // CPU: 0 + 66 -> 66 + ggml_tensor * v66 = g.add(ggml_add(ctx_compute.get(), zero_cpu, val66_cpu), CPU); + ggml_set_name(v66, "v66"); + + // GPU: increment both of the previous split outputs + ggml_tensor * out99 = g.add(ggml_add(ctx_compute.get(), v99, one_gpu), GPU); + ggml_set_name(out99, "out99"); + + ggml_tensor * out66 = g.add(ggml_add(ctx_compute.get(), v66, one_gpu), GPU); + ggml_set_name(out66, "out66"); + + ggml_set_output(delayed); + ggml_set_output(out99); + ggml_set_output(out66); + + const test_result ok = run_and_check(sched.get(), g, backends, { + { delayed, 1.0f }, + { out99, 100.0f }, + { out66, 67.0f }, + }, tensor_len); + + // the race needs the allocator to reuse the memory of the first CPU split for the second one + note("v55 and v66 %s (v55=%p v66=%p)", v55->data == v66->data ? "alias" : "do not alias", v55->data, v66->data); + + return ok; +} + +// Test that all async backends transmit their activations to the following async backend correctly. No user inputs tested. +static test_result test_chain_all_backends(const std::vector & backends, int64_t tensor_len, int32_t sleep_us, + bool use_device_host_buft) { + + const int n_backends = (int) backends.size(); + + std::vector seq; + + auto push = [&](int b) { + if (seq.empty() || seq.back() != b) { + seq.push_back(b); + } + }; + + for (int i = 0; i < n_backends; i++) { + for (int j = 0; j < n_backends; j++) { + if (i != j) { + push(i); + push(j); + } + } + } + + const size_t n_nodes = seq.size(); + const size_t n_sleeps = sleep_us > 0 ? n_nodes : 0; // one sleep per split + const size_t graph_size = n_nodes + n_sleeps + n_backends + 1; // see sched->hash_set FIXME, one "one" per backend plus the "zero" that starts the chain + + backend_consts consts(backends, tensor_len); + + ggml_backend_sched_ptr sched = create_test_scheduler(backends, graph_size, use_device_host_buft); + + ggml_init_params params_compute = { + /*.mem_size =*/ (graph_size + 8)*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + + helper_graph g(ctx_compute.get(), graph_size); + + ggml_tensor * out = nullptr; + for (size_t k = 0; k < n_nodes; k++) { + const int b = seq[k]; + + out = g.add(ggml_add(ctx_compute.get(), k == 0 ? consts.zero[b] : out, consts.one[b]), b); + + // the sleep keeps the backend busy, so that the next one has to wait for this split + if (sleep_us > 0) { + out = g.add(ggml_sleep(ctx_compute.get(), out, sleep_us), b); + } + } + ggml_set_name(out, "out"); + ggml_set_output(out); + + const test_result ok = run_and_check(sched.get(), g, backends, {{ out, float(n_nodes) }}, tensor_len); + + return ok; +} + +// Tests data transfer between all combinations of backend pairs +// The receiving split takes one activation from the sender plus n_inputs user inputs +static test_result test_pair_user_inputs(const std::vector & backends, int b_send, int b_recv, int64_t tensor_len, + int n_inputs, bool inputs_on_sender, bool parallel, bool use_device_host_buft) { + + const size_t graph_size = 64; + + backend_consts consts(backends, tensor_len); + + ggml_backend_sched_ptr sched = create_test_scheduler(backends, graph_size, use_device_host_buft, parallel); + + // placing the inputs on the sender makes the receiving split copy all of them, placing them on the + // receiver leaves the activation as its only input + const int b_inputs = inputs_on_sender ? b_send : b_recv; + + ggml_init_params params_inputs = { + /*.mem_size =*/ n_inputs*ggml_tensor_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_inputs(ggml_init(params_inputs)); + + std::vector inputs; + for (int k = 0; k < n_inputs; k++) { + ggml_tensor * in = ggml_new_tensor_1d(ctx_inputs.get(), GGML_TYPE_F32, tensor_len); + ggml_format_name(in, "in%d", k); + ggml_set_input(in); + inputs.push_back(in); + } + + ggml_backend_buffer_ptr buf_inputs(ggml_backend_alloc_ctx_tensors(ctx_inputs.get(), backends[b_inputs])); + GGML_ASSERT(buf_inputs != nullptr); + + std::vector data(tensor_len); + std::fill(data.begin(), data.end(), 1.0f); + for (ggml_tensor * in : inputs) { + ggml_backend_tensor_set(in, data.data(), 0, ggml_nbytes(in)); + } + + ggml_init_params params_compute = { + /*.mem_size =*/ (graph_size + 8)*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + + helper_graph g(ctx_compute.get(), graph_size); + + ggml_tensor * out = g.add(ggml_add(ctx_compute.get(), consts.zero[b_send], consts.one[b_send]), b_send); + + for (ggml_tensor * in : inputs) { + out = g.add(ggml_add(ctx_compute.get(), out, in), b_recv); + } + ggml_set_name(out, "out"); + ggml_set_output(out); + + test_result ok = run_and_check(sched.get(), g, backends, {{ out, float(1 + n_inputs) }}, tensor_len); + + for (ggml_tensor * in : inputs) { + if (ok != TEST_OK) { + break; + } + ggml_backend_tensor_get(in, data.data(), 0, ggml_nbytes(in)); + for (int64_t i = 0; i < tensor_len; i++) { + if (data[i] != 1.0f) { + ok = fail("%s[%" PRId64 "] = %f after compute, expected 1.000000 - the input was modified", ggml_get_name(in), i, data[i]); + break; + } + } + } + + return ok; +} + +// Tests Y-shaped scheduling: two parallel lanes merging into 1. Lane A and B, merging into a single split. +// The lanes join in a final split on backend_a that receives one activation from each of the two backend_b splits. +static test_result test_y_shaped_graph(const std::vector & backends, int backend_a, int backend_b, int64_t tensor_len, + int32_t sleep_us, bool use_device_host_buft) { + + const size_t graph_size = 64; + + backend_consts consts(backends, tensor_len); + + ggml_backend_sched_ptr sched = create_test_scheduler(backends, graph_size, use_device_host_buft); + + ggml_init_params params_compute = { + /*.mem_size =*/ (graph_size + 8)*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + + helper_graph g(ctx_compute.get(), graph_size); + + ggml_tensor * seed_a = g.add(ggml_add(ctx_compute.get(), consts.zero[backend_a], consts.one[backend_a]), backend_a); + ggml_set_name(seed_a, "seed_a"); + + // only lane a sleeps, so that lane b is scheduled while it is still running + if (sleep_us > 0) { + seed_a = g.add(ggml_sleep(ctx_compute.get(), seed_a, sleep_us), backend_a); + ggml_set_name(seed_a, "seed_a_delayed"); + } + + ggml_tensor * lane_a = g.add(ggml_add(ctx_compute.get(), seed_a, consts.one[backend_b]), backend_b); + ggml_set_name(lane_a, "lane_a"); + + if (sleep_us > 0) { + lane_a = g.add(ggml_sleep(ctx_compute.get(), lane_a, sleep_us), backend_b); + ggml_set_name(lane_a, "lane_a_delayed"); + } + + ggml_tensor * seed_b = g.add(ggml_add(ctx_compute.get(), consts.zero[backend_a], consts.one[backend_a]), backend_a); + ggml_set_name(seed_b, "seed_b"); + + ggml_tensor * lane_b = g.add(ggml_add(ctx_compute.get(), seed_b, consts.one[backend_b]), backend_b); + ggml_set_name(lane_b, "lane_b"); + + // neither lane ends on backend_a, so both activations are inputs of the last split + ggml_tensor * out = g.add(ggml_add(ctx_compute.get(), lane_a, lane_b), backend_a); + ggml_set_name(out, "out"); + ggml_set_output(out); + + const test_result ok = run_and_check(sched.get(), g, backends, {{ out, 4.0f }}, tensor_len); + + return ok; +} + +static const char * dev_type_name(enum ggml_backend_dev_type type) { + switch (type) { + case GGML_BACKEND_DEVICE_TYPE_CPU: return "CPU"; + case GGML_BACKEND_DEVICE_TYPE_GPU: return "GPU"; + case GGML_BACKEND_DEVICE_TYPE_IGPU: return "IGPU"; + case GGML_BACKEND_DEVICE_TYPE_ACCEL: return "ACCEL"; + case GGML_BACKEND_DEVICE_TYPE_META: return "META"; + } + return "UNKNOWN"; +} + +static bool initialize_backends(std::vector & backends) { + + // cf. GGML_SCHED_MAX_BACKENDS + const size_t max_backends = 16; + + for (size_t i = 0; i < ggml_backend_dev_count() && backends.size() + 1 < max_backends; i++) { + ggml_backend_dev_t dev = ggml_backend_dev_get(i); + log_maybe("device %2zu: %-10s %-5s (%s)\n", i, ggml_backend_dev_name(dev), + dev_type_name(ggml_backend_dev_type(dev)), ggml_backend_dev_description(dev)); + + const enum ggml_backend_dev_type type = ggml_backend_dev_type(dev); + // Exclude ACCEL devices as they run in tandem with the CPU backend and only implement matmul, the tests here require ADD + if (type == GGML_BACKEND_DEVICE_TYPE_CPU || type == GGML_BACKEND_DEVICE_TYPE_ACCEL) { + continue; + } + + ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr); + if (backend == nullptr) { + printf("failed to initialize %s, skipping it\n", ggml_backend_dev_name(dev)); + continue; + } + + backends.emplace_back(backend); + } + + if (backends.empty()) { + printf("no non-CPU backend found, skipping\n"); + return false; + } + + // ggml_backend_sched_new requires the CPU backend to be the last one + backends.emplace_back(ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr)); + GGML_ASSERT(backends.back() != nullptr); + + for (const ggml_backend_ptr & backend : backends) { + ggml_backend_dev_t dev = ggml_backend_get_device(backend.get()); + + log_maybe("backend: %-10s host_buft = %d (%s)\n", ggml_backend_name(backend.get()), + ggml_backend_dev_host_buffer_type(dev) != nullptr, ggml_backend_dev_description(dev)); + } + log_maybe("\n"); + return true; +} + + +int main(int argc, char ** argv) { + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) { + print_log = true; + } else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { + printf("Usage: %s [-v|--verbose]\n", argv[0]); + return 0; + } else { + fprintf(stderr, "unknown argument: %s\n", argv[i]); + fprintf(stderr, "Usage: %s [-v|--verbose]\n", argv[0]); + return 1; + } + } + + ggml_backend_load_all(); + + std::vector backends; + + // nothing to test with synchronous CPU backend only + if (!initialize_backends(backends)) { + return 0; + } + + // the tests only borrow the backends, the ownership stays with this vector + std::vector backend_ptrs; + for (const ggml_backend_ptr & backend : backends) { + backend_ptrs.push_back(backend.get()); + } + + ggml_backend_t cpu = backend_ptrs.back(); + const size_t n_non_cpu_backends = backend_ptrs.size() - 1; + + // Test cases for single backends against CPU backend + for (size_t b_id = 0; b_id < n_non_cpu_backends; b_id++) { + ggml_backend_t backend = backend_ptrs[b_id]; + const char * name_backend = ggml_backend_name(backend); + + for (bool use_device_host_buft : { false, true }) { + // without a host buffer type this case is a duplicate of the pageable one + if (use_device_host_buft && ggml_backend_dev_host_buffer_type(ggml_backend_get_device(backend)) == nullptr) { + continue; + } + + log_maybe("=== Backend: %s, CPU sched buft: %s ===\n\n", name_backend, use_device_host_buft ? "device_host" : "pageable"); + + for (int32_t sleep_us : {50, 60, 70, 80, 400, 500, 600, 700, 1000, 10000}) { + for (int tensor_len : { 2, 2048, 4096, 8192, 1600}) { + case_begin("test_inputless_splits_scheduling %-8s sleep_us = %6d, tensor_len = %4d", name_backend, sleep_us, tensor_len); + case_end(test_inputless_splits_scheduling(backend, cpu, tensor_len, sleep_us, use_device_host_buft)); + } + } + + log_maybe("\n"); + } + } + + // Test cases for all present backend subsets + for (bool use_device_host_buft : { false, true }) { + // create_test_scheduler takes the host buffer type from the first backend + if (use_device_host_buft && ggml_backend_dev_host_buffer_type(ggml_backend_get_device(backend_ptrs[0])) == nullptr) { + continue; + } + + log_maybe("=== all backends, CPU sched buft: %s ===\n\n", use_device_host_buft ? "device_host" : "pageable"); + + for (int n_lanes : { 8, 16 }) { + for (int n_rounds : { 5, 13, 64 }) { + for (int tensor_len : { 2, 4096 }) { + case_begin("stress_test_dag n_lanes = %2d, n_rounds = %2d, tensor_len = %4d", n_lanes, n_rounds, tensor_len); + case_end(stress_test_dag(backend_ptrs, n_lanes, n_rounds, tensor_len, use_device_host_buft)); + } + } + } + + log_maybe("\n"); + + for (int tensor_len : { 2, 4096 }) { + for (int32_t sleep_us : { 0, 80 }) { + case_begin("test_chain_all_backends sleep_us = %4d, tensor_len = %4d", sleep_us, tensor_len); + case_end(test_chain_all_backends(backend_ptrs, tensor_len, sleep_us, use_device_host_buft)); + } + } + + log_maybe("\n"); + + for (int n_laps : { 1, 4, 64 }) { + for (int tensor_len : { 2, 4096 }) { + case_begin("stress_test_linked_list n_laps = %3d, tensor_len = %4d", n_laps, tensor_len); + case_end(stress_test_linked_list(backend_ptrs, n_laps, tensor_len, use_device_host_buft)); + } + } + + log_maybe("\n"); + + // every ordered pair of backends is the sender and the receiver of a copy + for (size_t backend_a = 0; backend_a < backend_ptrs.size(); backend_a++) { + for (size_t backend_b = 0; backend_b < backend_ptrs.size(); backend_b++) { + if (backend_a == backend_b) { + continue; + } + + const char * name_a = ggml_backend_name(backend_ptrs[backend_a]); + const char * name_b = ggml_backend_name(backend_ptrs[backend_b]); + + for (bool inputs_on_sender : { false, true }) { + for (bool parallel : { false, true }) { + for (int tensor_len : { 1, 4096 }) { + case_begin("test_pair_user_inputs %-8s -> %-8s inputs on %-8s parallel = %d, tensor_len = %4d", + name_a, name_b, inputs_on_sender ? "sender" : "receiver", parallel, tensor_len); + case_end(test_pair_user_inputs(backend_ptrs, (int) backend_a, (int) backend_b, tensor_len, + /*n_inputs =*/ 4, inputs_on_sender, parallel, use_device_host_buft)); + } + } + } + + for (int tensor_len : { 1, 4096 }) { + for (int32_t sleep_us : { 0, 80 }) { + case_begin("test_y_shaped %-8s -> %-8s sleep_us = %4d, tensor_len = %4d", name_a, name_b, sleep_us, tensor_len); + case_end(test_y_shaped_graph(backend_ptrs, (int) backend_a, (int) backend_b, tensor_len, sleep_us, use_device_host_buft)); + } + } + } + } + + log_maybe("\n"); + } + + if (print_log || n_ok + n_skip != n_test) { + printf("%d/%d tests passed", n_ok, n_test); + if (n_skip > 0) { + printf(", %d skipped", n_skip); + } + printf("\n"); + } + + return n_ok + n_skip == n_test ? 0 : 1; +} diff --git a/tests/test-backend-tensor.cpp b/tests/test-backend-tensor.cpp index 9685bc277789..84c4dc2bd30f 100644 --- a/tests/test-backend-tensor.cpp +++ b/tests/test-backend-tensor.cpp @@ -170,6 +170,72 @@ static bool test_tensor_n(ggml_backend_buffer_type_t buft) { } } + { + uint8_t expected[24], out[24] = {}; + memset(expected, 0x11, sizeof(expected)); + ggml_backend_tensor_set(t_big, expected, 0, sizeof(expected)); + + // Verify memset of unaligned ranges, such as single F16 elements. + const size_t ranges[][2] = { { 2, 2 }, { 1, 1 }, { 5, 2 }, { 9, 13 }, { 22, 2 } }; + for (const auto & range : ranges) { + const uint8_t value = (uint8_t) (0xA0 + range[0]); + memset(expected + range[0], value, range[1]); + ggml_backend_tensor_memset(t_big, value, range[0], range[1]); + } + + ggml_backend_tensor_get(t_big, out, 0, sizeof(out)); + if (memcmp(out, expected, sizeof(out)) != 0) { + return false; + } + } + + { + std::vector batch; + ggml_backend_buffer_ptr scatter_buf = alloc_tensors(ctx.get(), buft, { 64 }, batch); + if (!scatter_buf) { + return false; + } + batch.resize(128, batch[0]); + uint8_t input[32], expected[256], out[256]; + for (size_t i = 0; i < sizeof(input); i++) { + input[i] = (uint8_t) (i + 1); + } + std::vector offsets(batch.size()), sizes(batch.size(), 1), data_offsets(batch.size()); + for (bool overlap : { false, true }) { + memset(expected, 0, sizeof(expected)); + ggml_backend_tensor_set(batch[0], expected, 0, sizeof(expected)); + for (size_t i = 0; i < batch.size(); i++) { + offsets[i] = 2*((i*5) % batch.size()) + 1; + data_offsets[i] = i % sizeof(input); + } + // Repeated sources are valid; overlapping destinations must retain copy order. + if (overlap) { + offsets.back() = offsets.front(); + } + for (size_t i = 0; i < batch.size(); i++) { + expected[offsets[i]] = input[data_offsets[i]]; + } + ggml_backend_tensor_set_n(batch.data(), input, offsets.data(), sizes.data(), data_offsets.data(), batch.size()); + ggml_backend_tensor_get(batch[0], out, 0, sizeof(out)); + if (memcmp(out, expected, sizeof(out)) != 0) { + return false; + } + } + } + + { + uint8_t expected[24], out[24] = {}; + memset(expected, 0x5A, sizeof(expected)); + + // Verify that clear fills every byte with a nonzero value. + ggml_backend_buffer_clear(buf.get(), 0x5A); + + ggml_backend_tensor_get(t_big, out, 0, sizeof(out)); + if (memcmp(out, expected, sizeof(out)) != 0) { + return false; + } + } + return true; } diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp index efffae530d83..7b70e7bcc853 100644 --- a/tests/test-chat.cpp +++ b/tests/test-chat.cpp @@ -1118,6 +1118,7 @@ struct peg_test_case { common_chat_msg expect; bool is_partial = false; bool expect_reconstruction = false; + bool expect_grammar = false; std::vector expect_rules; }; @@ -1191,6 +1192,10 @@ static void test_peg_parser(common_chat_templates * tmpls, } } + if (tc.expect_grammar && session.grammar().empty()) { + throw std::runtime_error("expected a grammar constraining the tool calls, but none was produced"); + } + common_chat_msg msg_accum; common_chat_msg msg_prev; msg_accum.role = msg_prev.role = "assistant"; @@ -1614,6 +1619,11 @@ class peg_test_builder { return *this; } + peg_test_builder & expect_grammar() { + tc_.expect_grammar = true; + return *this; + } + peg_test_builder & tool_choice(common_chat_tool_choice choice) { tc_.params.tool_choice = choice; return *this; @@ -7006,6 +7016,28 @@ static void test_template_output_peg_parsers(bool detailed_debug) { .run(); } + // Qwen3-ASR: "language ", the language prefix is delimiter-style reasoning + { + auto tst = peg_tester("models/templates/Qwen3-ASR.jinja", detailed_debug); + + tst.test("language EnglishAnd so, my fellow Americans, ask not.") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .expect(simple_assist_msg("And so, my fellow Americans, ask not.", "language English")) + .expect_reconstruction() + .run(); + + tst.test("language None") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .expect(simple_assist_msg("", "language None")) + .run(); + + // reasoning_format none keeps the raw output + tst.test("language EnglishHello") + .reasoning_format(COMMON_REASONING_FORMAT_NONE) + .expect_content("language EnglishHello") + .run(); + } + // Mistral Small 3.2 - FUNC_BRACKET_TAG format: [TOOL_CALLS]func_name[CALL_ID]id[ARGS]{...} { auto tst = peg_tester("models/templates/Mistral-Small-3.2-24B-Instruct-2506.jinja", detailed_debug); @@ -7086,6 +7118,19 @@ static void test_template_output_peg_parsers(bool detailed_debug) { auto tst = peg_tester("models/templates/meta-llama-Llama-3.2-3B-Instruct.jinja", detailed_debug); tst.test("Hello, world!\nWhat's up?").tools({ special_function_tool }).expect(message_assist).expect_reconstruction().expect_rules({ "tool-0" }).run(); + // bare JSON calls have no start marker, auto mode must still produce a lazy grammar + tst.test("{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}") + .tools({ special_function_tool }) + .expect(message_assist_call) + .expect_grammar() + .run(); + // same without spaces + tst.test("{\"name\":\"special_function\",\"parameters\":{\"arg1\":1}}") + .tools({ special_function_tool }) + .expect(message_assist_call) + .expect_grammar() + .run(); + // Continuation tests tst.test("world!\nWhat's up?") .messages({ message_user, message_assist_prefill_content }) @@ -8698,7 +8743,7 @@ static void test_reasoning_effort_caps() { assert_equals(json(expected).dump(), common_chat_templates_get_caps(tmpls.get()).at("reasoning_effort_levels").dump()); }; - const std::vector all_levels = { "minimal", "low", "medium", "high", "xhigh", "max" }; + const std::vector all_levels = { "none", "minimal", "low", "medium", "high", "xhigh", "max" }; assert_effort_levels("models/templates/deepseek-ai-DeepSeek-V4.jinja", { "max" }); assert_effort_levels("models/templates/deepseek-ai-DeepSeek-V4-Flash-0731.jinja", { "high", "max" }); @@ -8708,7 +8753,8 @@ static void test_reasoning_effort_caps() { assert_effort_levels("models/templates/upstage-Solar-Open-100B.jinja", { "low" }); assert_effort_levels("models/templates/muse-glimmer.jinja", all_levels); assert_effort_levels("models/templates/openai-gpt-oss-120b.jinja", all_levels); - assert_effort_levels("models/templates/Cohere2MoE.jinja", {}); + assert_effort_levels("models/templates/Cohere2MoE.jinja", { "none" }); + assert_effort_levels("models/templates/thinkingmachines-Inkling-2-Small.jinja", { "none", "minimal", "low", "medium", "high", "max" }); assert_effort_levels("models/templates/Qwen-Qwen3-0.6B.jinja", {}); auto assert_effort_rejected = [](const std::string & path, const std::vector & expected) { diff --git a/tests/test-llama-archs.cpp b/tests/test-llama-archs.cpp index f10404e8c28a..6faa8843decd 100644 --- a/tests/test-llama-archs.cpp +++ b/tests/test-llama-archs.cpp @@ -326,7 +326,7 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const n_vocab = 3072; // TODO: should be 4096, but user code cannot get `n_vocab_out` yet [TAG_LLAMA_N_VOCAB_OUT] } else if (arch == LLM_ARCH_HRM_TEXT) { n_layer = 6; // 1 layer per stack x 2 h-cycles x (2 l-cycles + 1) cache slots - } else if (arch == LLM_ARCH_INKLING2) { + } else if (arch == LLM_ARCH_INKLING2 || arch == LLM_ARCH_INKLING2_LOOP) { n_embd = 128; n_head = 4; n_ff = 24; @@ -496,16 +496,22 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, pattern); } else if (arch == LLM_ARCH_COHERE2MOE || arch == LLM_ARCH_MIMO2 || arch == LLM_ARCH_STEP35 || arch == LLM_ARCH_SPARK2_5 || arch == LLM_ARCH_MUSE_GLIMMER || arch == LLM_ARCH_MUSE_SPARK || arch == LLM_ARCH_GRANITE_SWA || arch == LLM_ARCH_DOTS3NOTE || - arch == LLM_ARCH_KOLIBRI1 || arch == LLM_ARCH_MAPLE || arch == LLM_ARCH_FLINT || arch == LLM_ARCH_BEAM || arch == LLM_ARCH_RICURSIVE) { + arch == LLM_ARCH_KOLIBRI1 || arch == LLM_ARCH_MAPLE || arch == LLM_ARCH_FLINT || arch == LLM_ARCH_BEAM || arch == LLM_ARCH_RICURSIVE || arch == LLM_ARCH_DOMYN_EDGE) { std::vector pattern; pattern.reserve(n_layer); for (uint32_t il = 0; il < n_layer; il++) { pattern.push_back(il % 2); } ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, pattern); - if (arch == LLM_ARCH_FLINT) { + if (arch == LLM_ARCH_FLINT || arch == LLM_ARCH_DOMYN_EDGE) { ms.add_kv(LLM_KV_ATTENTION_ROPE_PATTERN, pattern); } + if (arch == LLM_ARCH_DOMYN_EDGE) { + // SWA (rope) layers use a smaller head dim than the full-attention (nope) layers + ms.add_kv(LLM_KV_ATTENTION_KEY_LENGTH_SWA, n_embd_head/2); + ms.add_kv(LLM_KV_ATTENTION_VALUE_LENGTH_SWA, n_embd_head/2); + ms.add_kv(LLM_KV_ROPE_DIMENSION_COUNT_SWA, n_embd_head/2); + } } else if (arch == LLM_ARCH_LFM3) { ms.add_kv(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, std::vector({0, 0, 1})); ms.add_kv(LLM_KV_ROPE_FREQ_BASE_SWA, 10000.0f); @@ -697,7 +703,8 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const ms.add_kv(LLM_KV_MUDD_TAP_INDICES, std::vector({-1, -1, -1, -1, 0, 2, 1, 3})); } - if (arch == LLM_ARCH_INKLING2) { + if (arch == LLM_ARCH_INKLING2 || arch == LLM_ARCH_INKLING2_LOOP) { + const bool loop = arch == LLM_ARCH_INKLING2_LOOP; ms.add_kv(LLM_KV_ATTENTION_RELATIVE_LENGTH, uint32_t(4)); ms.add_kv(LLM_KV_ATTENTION_RELATIVE_EXTENT, uint32_t(16)); ms.add_kv(LLM_KV_ATTENTION_QK_CLIP, 0.25f); @@ -705,6 +712,14 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const ms.add_kv(LLM_KV_ATTENTION_LOG_SCALE_FLOOR, uint32_t(4)); ms.add_kv(LLM_KV_ATTENTION_LOG_SCALE_ALPHA, 0.1f); ms.add_kv(LLM_KV_ATTN_RES_BLOCK_SIZE, uint32_t(2)); + if (loop) { + // prelude 0, core 1, coda 2; the loader adds slot 3 for the second pass over the core + ms.add_kv(LLM_KV_LOOP_START, uint32_t(1)); + ms.add_kv(LLM_KV_LOOP_END, uint32_t(2)); + ms.add_kv(LLM_KV_LOOP_COUNT, uint32_t(2)); + ms.add_kv(LLM_KV_LOOP_GATE_RANK, uint32_t(8)); + ms.add_kv(LLM_KV_LOOP_VARYING, false); + } ms.add_kv(LLM_KV_SHORTCONV_L_CACHE, uint32_t(4)); ms.add_kv(LLM_KV_VOCAB_SIZE, n_vocab + 2); ms.add_kv(LLM_KV_VOCAB_SIZE_UNPADDED, n_vocab); @@ -821,7 +836,8 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const ms.add_kv(LLM_KV_WKV_HEAD_SIZE, n_embd/n_head); ms.add_kv(LLM_KV_SHORTCONV_L_CACHE, uint32_t(3)); ms.add_kv(LLM_KV_RESIDUAL_SCALE, 3.5565588200778455f); - ms.add_kv(LLM_KV_ATTN_RES_BLOCK_SIZE, uint32_t(12)); + // the inkling2_loop core boundaries must be multiples of the block size + ms.add_kv(LLM_KV_ATTN_RES_BLOCK_SIZE, uint32_t(arch == LLM_ARCH_INKLING2_LOOP ? 1 : 12)); ms.add_kv(LLM_KV_ACTIVATION_SITU_BETA, 4.0f); ms.add_kv(LLM_KV_ACTIVATION_SITU_LINEAR_BETA, 25.0f); ms.add_kv(LLM_KV_KDA_GATE_LOWER_BOUND, -5.0f); @@ -1139,6 +1155,7 @@ static bool moe_mandatory(const llm_arch arch) { case LLM_ARCH_METIS16: case LLM_ARCH_ZONOS3: case LLM_ARCH_INKLING2: + case LLM_ARCH_INKLING2_LOOP: return true; default: return false; diff --git a/tests/test-server-component.cpp b/tests/test-server-component.cpp index bef83e1ebff5..bb531860c063 100644 --- a/tests/test-server-component.cpp +++ b/tests/test-server-component.cpp @@ -699,7 +699,7 @@ static void test_decision_ocr_jev_validation(testing & t) { const auto reject_questions = [&](const char * name, const json & body, const std::string & expected) { std::string error; try { - ctx.parse_questions(body); + ctx.parse_questions(body, false); } catch (const std::invalid_argument & e) { error = e.what(); } diff --git a/tests/test-sleep.cpp b/tests/test-sleep.cpp new file mode 100644 index 000000000000..bd836c33870a --- /dev/null +++ b/tests/test-sleep.cpp @@ -0,0 +1,154 @@ +// Tests for GGML_OP_SLEEP, on every backend that supports it. Three properties are checked: +// - the op only delays: input = output +// - the op does not return early: a chain of n sleeps must take at least n*us +// Only a lower bound is asserted for the duration. A busy-wait cannot finish early, so that bound is +// deterministic, whereas an upper bound would be flaky on a loaded machine. +// Known limitation: Vulkan does not specify the tick rate of the shader clock, see ggml_vk_sleep. A driver +// whose clock runs slower than assumed could undershoot the request and fail this bound. + +#include "ggml.h" +#include "ggml-alloc.h" +#include "ggml-backend.h" +#include "ggml-cpp.h" + +#include +#include +#include +#include +#include + +enum test_result { + TEST_OK, + TEST_FAIL, + TEST_SKIP, +}; + +static test_result test_sleep(ggml_backend_t backend, ggml_type type, int64_t ne, int32_t us, int n_nodes) { + const size_t graph_size = n_nodes + 16; + + ggml_init_params params_static = { + /*.mem_size =*/ ggml_tensor_overhead(), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_static(ggml_init(params_static)); + + ggml_tensor * x = ggml_new_tensor_1d(ctx_static.get(), type, ne); + ggml_set_name(x, "x"); + ggml_set_input(x); + + ggml_init_params params_compute = { + /*.mem_size =*/ n_nodes*ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), + /*.mem_buffer =*/ nullptr, + /*.no_alloc =*/ true, + }; + ggml_context_ptr ctx_compute(ggml_init(params_compute)); + ggml_cgraph * gf = ggml_new_graph_custom(ctx_compute.get(), graph_size, false); + + ggml_tensor * out = x; + for (int i = 0; i < n_nodes; i++) { + out = ggml_sleep(ctx_compute.get(), out, us); + } + ggml_set_name(out, "out"); + ggml_build_forward_expand(gf, out); + + // the backends log to stdout while computing, so the result line is only printed once it is complete + char desc[128]; + snprintf(desc, sizeof(desc), " %-6s %-4s ne=%-9" PRId64 " us=%-7d n_nodes=%d ", + ggml_backend_name(backend), ggml_type_name(type), ne, us, n_nodes); + + test_result result = TEST_OK; + + if (!ggml_backend_supports_op(backend, out)) { + printf("%snot supported\n", desc); + result = TEST_SKIP; + } else { + ggml_backend_buffer_ptr buf_static(ggml_backend_alloc_ctx_tensors(ctx_static.get(), backend)); + + // random bytes rather than random floats, so that bit patterns a value-wise copy could + // mangle, such as NaNs and denormals, are covered as well + std::vector data_in(ggml_nbytes(x)); + std::mt19937 rng(1234); + for (size_t i = 0; i < data_in.size(); i++) { + data_in[i] = rng() & 0xFF; + } + ggml_backend_tensor_set(x, data_in.data(), 0, data_in.size()); + + ggml_gallocr_ptr galloc(ggml_gallocr_new(ggml_backend_get_default_buffer_type(backend))); + ggml_gallocr_alloc_graph(galloc.get(), gf); + + // warm up, so that one-time costs such as lazy CUDA module loading are not timed + ggml_backend_graph_compute(backend, gf); + + const int64_t t_start_us = ggml_time_us(); + const ggml_status status = ggml_backend_graph_compute(backend, gf); + const int64_t t_us = ggml_time_us() - t_start_us; + + std::vector data_out(ggml_nbytes(out)); + ggml_backend_tensor_get(out, data_out.data(), 0, data_out.size()); + + const int64_t t_min_us = (int64_t) n_nodes * us; + + const bool ok_status = status == GGML_STATUS_SUCCESS; + const bool ok_alias = out->data == x->data; + const bool ok_data = memcmp(data_in.data(), data_out.data(), data_in.size()) == 0; + const bool ok_time = t_us >= t_min_us; + + printf("%selapsed=%7" PRId64 " us (>= %6" PRId64 ") alias: %-4s data: %-4s time: %s\n", + desc, t_us, t_min_us, ok_alias ? "OK" : "FAIL", ok_data ? "OK" : "FAIL", ok_time ? "OK" : "FAIL"); + + if (!ok_status) { + printf(" compute failed: %s\n", ggml_status_to_string(status)); + } + + result = ok_status && ok_alias && ok_data && ok_time ? TEST_OK : TEST_FAIL; + } + + return result; +} + +int main() { + ggml_time_init(); + ggml_backend_load_all(); + + int n_ok = 0; + int n_fail = 0; + int n_skip = 0; + + for (size_t i = 0; i < ggml_backend_dev_count(); i++) { + ggml_backend_dev_t dev = ggml_backend_dev_get(i); + + ggml_backend_ptr backend(ggml_backend_dev_init(dev, nullptr)); + if (backend == nullptr) { + printf(" failed to initialize %s\n", ggml_backend_dev_name(dev)); + n_fail++; + continue; + } + + // a zero duration must still be a valid no-op, longer ones are checked against the clock, + // and the last case verifies that a chain of sleeps accumulates instead of collapsing into one + const struct { + ggml_type type; + int64_t ne; + int32_t us; + int n_nodes; + } cases[] = { + { GGML_TYPE_F32, 1, 0, 1 }, + { GGML_TYPE_F32, 4096, 10000, 1 }, + { GGML_TYPE_F16, 1024, 10000, 1 }, + { GGML_TYPE_F32, 1 << 20, 5000, 4 }, + }; + + for (const auto & c : cases) { + switch (test_sleep(backend.get(), c.type, c.ne, c.us, c.n_nodes)) { + case TEST_OK: n_ok++; break; + case TEST_FAIL: n_fail++; break; + case TEST_SKIP: n_skip++; break; + } + } + } + + printf("%d passed, %d failed, %d skipped\n", n_ok, n_fail, n_skip); + + return n_fail > 0; +} diff --git a/tests/test-tokenizer-random.py b/tests/test-tokenizer-random.py index 7f5ea3f45684..4b4fbdf75510 100644 --- a/tests/test-tokenizer-random.py +++ b/tests/test-tokenizer-random.py @@ -80,6 +80,7 @@ def __init__(self, libllama: LibLlama, path_model: str, mparams={}, cparams={}): raise RuntimeError("error: failed to load model '%s'" % path_model) if isinstance(cparams, dict): cparams = libllama.context_default_params(**cparams) + self.vocab = self.lib.llama_model_get_vocab(self.model) self.ctx = self.lib.llama_init_from_model(self.model, cparams) if not self.ctx: raise RuntimeError("error: failed to create context for model '%s'" % path_model) @@ -98,10 +99,10 @@ def free(self): def tokenize(self, text: str, add_special: bool = False, parse_special: bool = False) -> list[int]: encoded_text: bytes = text.encode("utf-8") - num = self.lib.llama_tokenize(self.model, encoded_text, len(encoded_text), self.token_ids, len(self.token_ids), add_special, parse_special) + num = self.lib.llama_tokenize(self.vocab, encoded_text, len(encoded_text), self.token_ids, len(self.token_ids), add_special, parse_special) while num < 0 and len(self.token_ids) < (16 << 20): self.token_ids = self.ffi.new("llama_token[]", -2 * num) - num = self.lib.llama_tokenize(self.model, encoded_text, len(encoded_text), self.token_ids, len(self.token_ids), add_special, parse_special) + num = self.lib.llama_tokenize(self.vocab, encoded_text, len(encoded_text), self.token_ids, len(self.token_ids), add_special, parse_special) return list(self.token_ids[0:num]) def detokenize(self, ids: list[int], remove_special: bool = False, unparse_special: bool = False) -> str: @@ -109,10 +110,10 @@ def detokenize(self, ids: list[int], remove_special: bool = False, unparse_speci self.token_ids = self.ffi.new("llama_token[]", 2 * len(ids)) for i, id in enumerate(ids): self.token_ids[i] = id - num = self.lib.llama_detokenize(self.model, self.token_ids, len(ids), self.text_buff, len(self.text_buff), remove_special, unparse_special) + num = self.lib.llama_detokenize(self.vocab, self.token_ids, len(ids), self.text_buff, len(self.text_buff), remove_special, unparse_special) while num < 0 and len(self.text_buff) < (16 << 20): self.text_buff = self.ffi.new("uint8_t[]", -2 * num) - num = self.lib.llama_detokenize(self.model, self.token_ids, len(ids), self.text_buff, len(self.text_buff), remove_special, unparse_special) + num = self.lib.llama_detokenize(self.vocab, self.token_ids, len(ids), self.text_buff, len(self.text_buff), remove_special, unparse_special) return str(self.ffi.buffer(self.text_buff, num), encoding="utf-8", errors="replace") # replace errors with '\uFFFD' # pyright: ignore[reportArgumentType] diff --git a/tools/mtmd/CMakeLists.txt b/tools/mtmd/CMakeLists.txt index 9c37d60ed0a9..cd9810e6d714 100644 --- a/tools/mtmd/CMakeLists.txt +++ b/tools/mtmd/CMakeLists.txt @@ -96,6 +96,7 @@ add_library(mtmd models/pockettts-seanet.cpp models/pockettts-spkenc.cpp models/pockettts-gen.cpp + models/moshi.cpp models/soprano.cpp models/kokoro.cpp models/tiny-voca.cpp diff --git a/tools/mtmd/models/drama3-gen.cpp b/tools/mtmd/models/drama3-gen.cpp index e77fcf540daf..41d8c22b1032 100644 --- a/tools/mtmd/models/drama3-gen.cpp +++ b/tools/mtmd/models/drama3-gen.cpp @@ -130,9 +130,19 @@ ggml_cgraph * mtmd_graph_drama3_gen::build_tower() { ggml_set_name(inp_pos, "inp_pos"); ggml_set_input(inp_pos); - ggml_tensor * inp_rand = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_heads); - ggml_set_name(inp_rand, "inp_rand"); - ggml_set_input(inp_rand); + // teacher forcing (reference rows of a voice clone): codes 1.. of the frame are given, nothing is sampled + const bool forced = n_frames == 2; + ggml_tensor * inp_rand = nullptr; + ggml_tensor * inp_force = nullptr; + if (forced) { + inp_force = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_heads); + ggml_set_name(inp_force, "inp_force"); + ggml_set_input(inp_force); + } else { + inp_rand = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_heads); + ggml_set_name(inp_rand, "inp_rand"); + ggml_set_input(inp_rand); + } ggml_tensor * mask = ggml_view_1d(ctx0, inp_scale, 1, 0); ggml_tensor * extra_on = ggml_view_1d(ctx0, inp_scale, 1, sizeof(float)); @@ -152,6 +162,11 @@ ggml_cgraph * mtmd_graph_drama3_gen::build_tower() { continue; } const int ih = il - n_shared; + if (forced) { + code = ggml_view_1d(ctx0, inp_force, 1, (size_t) ih * sizeof(int32_t)); + out_codes = cg.cache_set(out_codes, ih + 1, code); + continue; + } ggml_tensor * head = ggml_view_2d(ctx0, model.gen_code_head_w, model.gen_code_head_w->ne[0], model.gen_code_head_w->ne[1], model.gen_code_head_w->nb[1], (size_t) ih * model.gen_code_head_w->nb[2]); ggml_tensor * logits = ggml_mul_mat(ctx0, head, x); diff --git a/tools/mtmd/models/fish-s2-spkenc.cpp b/tools/mtmd/models/fish-s2-spkenc.cpp index a9c51d9cda7a..fe2eb28ef68f 100644 --- a/tools/mtmd/models/fish-s2-spkenc.cpp +++ b/tools/mtmd/models/fish-s2-spkenc.cpp @@ -2,6 +2,7 @@ #include #include +#include // reference clip -> codec frames -> backbone input rows, see DAC.encode() and DownsampleResidualVectorQuantize.encode() // activations are [C, T]; a conv is a sum of matmuls over tap-shifted views: exact in F32, no im2col buffer @@ -117,17 +118,35 @@ ggml_cgraph * mtmd_graph_fish_s2_spkenc::build() { return ggml_view_2d(ctx0, t, t->ne[0], t->ne[1], t->nb[1], (size_t) g * t->nb[2]); }; - // backbone row: (E_lm[semantic] + sum of E_cb[g][code g]) / sqrt(n_cb + 1), same as fish_s2_gen const int64_t n_cb = model.gen_code_embd_w->ne[2]; - ggml_tensor * idx = vq(c2w.quant_first_in_w, c2w.quant_first_in_b, c2w.quant_first_cb_norm_w, c2w.quant_first_cb_w); - ggml_tensor * out = ggml_add(ctx0, ggml_get_rows(ctx0, model.gen_code_out_embd_w, idx), - ggml_get_rows(ctx0, page(model.gen_code_embd_w, 0), idx)); + std::vector idx(n_cb); + idx[0] = vq(c2w.quant_first_in_w, c2w.quant_first_in_b, c2w.quant_first_cb_norm_w, c2w.quant_first_cb_w); for (int64_t g = 1; g < n_cb; g++) { ggml_tensor * in_b = ggml_view_1d(ctx0, c2w.quant_rest_in_b, c2w.quant_rest_in_b->ne[0], (size_t) (g - 1) * c2w.quant_rest_in_b->nb[1]); - idx = vq(page(c2w.quant_rest_in_w, g - 1), in_b, page(c2w.quant_rest_cb_norm_w, g - 1), page(c2w.quant_rest_cb_w, g - 1)); - out = ggml_add(ctx0, out, ggml_get_rows(ctx0, page(model.gen_code_embd_w, g), idx)); + idx[g] = vq(page(c2w.quant_rest_in_w, g - 1), in_b, page(c2w.quant_rest_cb_norm_w, g - 1), page(c2w.quant_rest_cb_w, g - 1)); + } + // codes of the clip, read back as the gen-side reference + for (int64_t g = 0; g < n_cb; g++) { + ggml_set_name(idx[g], ("out_ref_code_" + std::to_string(g)).c_str()); + ggml_set_output(idx[g]); + ggml_build_forward_expand(gf, idx[g]); + } + + ggml_tensor * out = nullptr; + if (hparams.spkenc_drama3_rows) { + // drama3 backbone row: (E_lm[semantic] + E_cb[1][code 1]) / sqrt(2), see mtmd_graph_drama3_gen::build_tower() + out = ggml_add(ctx0, ggml_get_rows(ctx0, model.gen_code_out_embd_w, idx[0]), + ggml_get_rows(ctx0, page(model.gen_code_embd_w, 1), idx[1])); + out = ggml_scale(ctx0, out, 1.0f / sqrtf(2.0f)); + } else { + // backbone row: (E_lm[semantic] + sum of E_cb[g][code g]) / sqrt(n_cb + 1), same as fish_s2_gen + out = ggml_add(ctx0, ggml_get_rows(ctx0, model.gen_code_out_embd_w, idx[0]), + ggml_get_rows(ctx0, page(model.gen_code_embd_w, 0), idx[0])); + for (int64_t g = 1; g < n_cb; g++) { + out = ggml_add(ctx0, out, ggml_get_rows(ctx0, page(model.gen_code_embd_w, g), idx[g])); + } + out = ggml_scale(ctx0, out, 1.0f / sqrtf((float) (n_cb + 1))); } - out = ggml_scale(ctx0, out, 1.0f / sqrtf((float) (n_cb + 1))); cb(out, "spk_rows", -1); ggml_build_forward_expand(gf, out); diff --git a/tools/mtmd/models/models.h b/tools/mtmd/models/models.h index 64f7bf70d4f0..278fcdb27eb3 100644 --- a/tools/mtmd/models/models.h +++ b/tools/mtmd/models/models.h @@ -433,7 +433,11 @@ struct mtmd_graph_qwen3tts_gen : mtmd_graph { // MTMD_SUBCTX_GEN_PROCESS_TOKENIZE: reference clip -> codes and their talker input rows ggml_cgraph * build_ref_encoder(); - ggml_tensor * nearest_code(ggml_tensor * x, ggml_tensor * codebook) const; + static ggml_tensor * nearest_code(ggml_context * ctx0, ggml_tensor * x, ggml_tensor * codebook); + // split RVQ (mimi): the first codebook on x_first, the residual ones on x_rest, cb_rest is stacked on dim 2 + // x_first, x_rest: [dim, T] -> one [T] code tensor per codebook; also used by the moshi encoder + static std::vector rvq_encode(ggml_context * ctx0, ggml_tensor * x_first, ggml_tensor * cb_first, + ggml_tensor * x_rest, ggml_tensor * cb_rest); // reference encoder transformer, see encoder_config in speech_tokenizer/config.json static constexpr int ref_enc_n_head = 8; @@ -529,6 +533,8 @@ struct mtmd_graph_qwen3tts_gen : mtmd_graph { // pocket-tts: SEANet convolution stack, shared by the voice encoder and the mimi decoder. // stateless unless state_in is populated: convs then pad instead of carrying left-context. // +struct c2w_state_slot; + struct mtmd_graph_pockettts_seanet : mtmd_graph { mtmd_graph_pockettts_seanet(const mtmd_graph & parent) : mtmd_graph(parent) {} ggml_cgraph * build() override { GGML_ABORT("call encode()/decode() instead"); } @@ -542,6 +548,10 @@ struct mtmd_graph_pockettts_seanet : mtmd_graph { std::map state_in; mutable std::vector> state_out; + // the "state_in_" inputs of the slots, then the "state_out_" outputs written by the graph + void state_inputs(const std::vector & slots); + void state_outputs(ggml_cgraph * graph) const; + ggml_tensor * conv1d(ggml_tensor * x, ggml_tensor * w, ggml_tensor * b, int stride, int dilation, bool pad_replicate = false, const std::string & state_name = "") const; ggml_tensor * conv_transpose1d(ggml_tensor * x, ggml_tensor * w, ggml_tensor * b, int stride, @@ -549,10 +559,15 @@ struct mtmd_graph_pockettts_seanet : mtmd_graph { ggml_tensor * res_unit(ggml_tensor * x, const mtmd_seanet::stage & stage, int dilation, const std::string & state_prefix = "") const; - // x: [T, C] -> [T / hop, dim] + // x: [T, C] -> [T / hop, dim], streams when state_in is populated ggml_tensor * encode(ggml_tensor * x) const; // x: [T, dim] -> [T * hop, 1], streams when state_in is populated ggml_tensor * decode(ggml_tensor * x) const; + + // mimi transformer, always streams (see list_pockettts_state_slots): x: [dim, n_pos] -> [dim, n_pos] + ggml_tensor * transformer(ggml_tensor * x, const std::vector & layers, int n_head, float eps) const; + // mimi decoder: upsample, transformer, SEANet decoder; x: [dim, n_frames] -> [n_samples, 1] + ggml_tensor * mimi_decode(ggml_tensor * x, int n_head, float eps) const; }; // mimi encoder + speaker_proj: reference waveform -> voice conditioning rows @@ -594,6 +609,43 @@ struct mtmd_graph_pockettts_gen : mtmd_graph { ggml_tensor * flow_forward(ggml_tensor * cond, ggml_tensor * x, float s, float t) const; }; +// +// moshi family (e.g. Hibiki): streaming mimi encoder + RVQ, rows of the input audio codes +// output: [n_embd, n_q * (n_frames + 1)], the embedding of each code of each frame, then of the initial codes +// +struct mtmd_graph_moshi : mtmd_graph { + mtmd_graph_moshi(mtmd_subcontext * ctx, const mtmd_image_f32 & img) : mtmd_graph(ctx, img) {} + ggml_cgraph * build() override; + + static constexpr int n_samples_per_frame = 1920; // 80 ms at 24 kHz +}; + +// +// moshi generation: +// GEN_CODE = depformer, the codes of one frame + their backbone embedding; with all codes known, only the embedding +// GEN_WAV = RVQ decode + mimi decoder +// +struct mtmd_graph_moshi_gen : mtmd_graph { + mtmd_graph_moshi_gen(mtmd_subcontext * ctx, const mtmd_image_f32 & img, mtmd_subctx_gen_process gen_process, bool fb_only, + int n_frames, int top_k, float temp) + : mtmd_graph(ctx, img), gen_process(gen_process), fb_only(fb_only), n_frames(n_frames), top_k(top_k), temp(temp) {} + ggml_cgraph * build() override; + + static constexpr int mimi_n_layer = 8; + static constexpr int mimi_n_head = 8; + static constexpr float mimi_eps = 1e-5f; + static constexpr int n_q_max = 32; + + mtmd_subctx_gen_process gen_process; + bool fb_only; + int n_frames; + int top_k; + float temp; + + ggml_tensor * dep_step(ggml_tensor * x, int64_t iw, std::vector & k_all, std::vector & v_all); + ggml_tensor * feedback(const std::vector & codes); +}; + // one persisted state buffer used by code2wav, see qwen3tts-gen.cpp struct c2w_state_slot { std::string name; @@ -609,6 +661,9 @@ std::vector list_drama3_state_slots(const mtmd_hparams & hparams // same, for the streaming mimi decoder (pocket-tts GEN_WAV) std::vector list_pockettts_state_slots(const mtmd_hparams & hparams, const mtmd_model & model); +// streaming mimi encoder of moshi, "pos" leads +std::vector list_moshi_state_slots(const mtmd_hparams & hparams, const mtmd_model & model); + // // drama3 generation: // GEN_CODE = one codebook tower row, each layer attends over the whole sequence (KV in gen state) @@ -625,7 +680,7 @@ struct mtmd_graph_drama3_gen : mtmd_graph { mtmd_subctx_gen_process gen_process; mtmd_subctx_gen_state * gen_state; // nullptr on buffer reserve - int n_frames; // GEN_WAV only + int n_frames; // GEN_WAV: frames to decode; GEN_CODE: 2 when the caller gives the codes of the frame (teacher forcing) int top_k; float top_p; float temp; diff --git a/tools/mtmd/models/moshi.cpp b/tools/mtmd/models/moshi.cpp new file mode 100644 index 000000000000..ff99f10a07a9 --- /dev/null +++ b/tools/mtmd/models/moshi.cpp @@ -0,0 +1,265 @@ +#include "models.h" + +// Moshi family (e.g. Hibiki), see conversion/moshi.py +// +// encoder (audio stream): streaming mimi encoder -> RVQ -> backbone embeddings of the input codes +// GEN_CODE: depformer, the codes of one frame from the backbone hidden state and the text token, then their embedding +// GEN_WAV : RVQ decode -> streaming mimi decoder + +// 2D slice i of a tensor stacked on dim 2 +static ggml_tensor * moshi_slice(ggml_context * ctx0, ggml_tensor * w, int64_t i) { + return ggml_view_2d(ctx0, w, w->ne[0], w->ne[1], w->nb[1], (size_t) i * w->nb[2]); +} + +std::vector list_moshi_state_slots(const mtmd_hparams & hparams, const mtmd_model & model) { + std::vector slots; + const auto & seanet = model.seanet; + + slots.push_back({"pos", 1, 1}); + + const int64_t n_embd_a = model.layers[0].q_w->ne[1]; + const int64_t prefix = hparams.mimi_tfm_context - 1; + for (size_t il = 0; il < model.layers.size(); il++) { + slots.push_back({"tfm_k_" + std::to_string(il), n_embd_a, prefix}); + slots.push_back({"tfm_v_" + std::to_string(il), n_embd_a, prefix}); + } + + // left context of the causal convs, [kernel - stride, in channels] + slots.push_back({"enc_in", seanet.conv_in_w->ne[0] - 1, seanet.conv_in_w->ne[1]}); + for (int i = 0; i < hparams.seanet_n_stage; i++) { + const auto & stage = seanet.stages[i]; + slots.push_back({"enc_res_" + std::to_string(i), stage.res_conv1_w->ne[0] - 1, stage.res_conv1_w->ne[1]}); + slots.push_back({"enc_down_" + std::to_string(i), stage.scale_conv_w->ne[0] - hparams.seanet_ratios[i], stage.scale_conv_w->ne[1]}); + } + slots.push_back({"enc_out", seanet.conv_out_w->ne[0] - 1, seanet.conv_out_w->ne[1]}); + slots.push_back({"down", model.downsample_w->ne[0] - hparams.mimi_downsample, model.downsample_w->ne[1]}); + + return slots; +} + +// waveform of whole frames -> [n_embd, n_q, n_frames + 1]: the embedding of each input code, then of the initial codes +ggml_cgraph * mtmd_graph_moshi::build() { + // the waveform comes in as a single-row "mel", [n_samples, 1] + ggml_tensor * inp_raw = build_inp_raw(1); + ggml_tensor * cur = ggml_reshape_2d(ctx0, inp_raw, inp_raw->ne[0], inp_raw->ne[1]); + GGML_ASSERT(cur->ne[0] % n_samples_per_frame == 0); + + // the graph always streams, a zero state encodes a clip from its start + mtmd_graph_pockettts_seanet seanet(*this); + seanet.state_inputs(list_moshi_state_slots(hparams, model)); + ggml_tensor * pos_in = seanet.state_in.at("pos"); + + cur = seanet.encode(cur); + cb(cur, "mimi_enc", -1); + + cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur)); + cur = seanet.transformer(cur, model.layers, hparams.n_head, hparams.eps); + cb(cur, "mimi_enc_tfm", -1); + + // the downsample conv repeats the first frame on its left at the stream start, the state is zero then + cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur)); + { + const int64_t n_left = seanet.state_in.at("down")->ne[0]; + ggml_tensor * first = ggml_repeat_4d(ctx0, ggml_view_2d(ctx0, cur, 1, cur->ne[1], cur->nb[1], 0), n_left, cur->ne[1], 1, 1); + ggml_tensor * is_first = ggml_step(ctx0, ggml_scale_bias(ctx0, pos_in, -1.0f, 0.5f)); + seanet.state_in["down"] = ggml_add(ctx0, seanet.state_in.at("down"), ggml_mul(ctx0, first, is_first)); + } + cur = seanet.conv1d(cur, model.downsample_w, nullptr, hparams.mimi_downsample, 1, false, "down"); + cb(cur, "mimi_downsample", -1); + + seanet.state_outputs(gf); + + // split RVQ: the semantic codebook, then the residual acoustic ones, all from the same latent + cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur)); // [512, n_frames] + const auto & c2w = model.c2w; + const int64_t n_frames = cur->ne[1]; + const int64_t n_q = model.mm_a_code_embd->ne[2]; + const int64_t n_embd = model.mm_a_code_embd->ne[0]; + + const std::vector codes = mtmd_graph_qwen3tts_gen::rvq_encode(ctx0, + build_mm(c2w.quant_first_in_w, cur), c2w.quant_first_cb_w, build_mm(c2w.quant_rest_in_w, cur), c2w.quant_rest_cb_w); + GGML_ASSERT((int64_t) codes.size() == n_q); + + // [n_embd, n_frames, n_q] -> [n_embd, n_q, n_frames] + ggml_tensor * embd = nullptr; + for (int64_t k = 0; k < n_q; k++) { + cb(codes[k], "in_code", (int) k); + ggml_tensor * e = ggml_get_rows(ctx0, moshi_slice(ctx0, model.mm_a_code_embd, k), codes[k]); + e = ggml_reshape_3d(ctx0, e, n_embd, n_frames, 1); + embd = embd ? ggml_concat(ctx0, embd, e, 2) : e; + } + embd = ggml_cont(ctx0, ggml_permute(ctx0, embd, 0, 2, 1, 3)); + + // the initial code is the last entry of every table + const float code_initial = (float) (model.mm_a_code_embd->ne[1] - 1); + ggml_tensor * idx_initial = ggml_cast(ctx0, ggml_arange(ctx0, code_initial, code_initial + 1.0f, 1.0f), GGML_TYPE_I32); + ggml_tensor * init = nullptr; + for (int64_t k = 0; k < n_q; k++) { + ggml_tensor * e = ggml_get_rows(ctx0, moshi_slice(ctx0, model.mm_a_code_embd, k), idx_initial); + init = init ? ggml_concat(ctx0, init, e, 1) : e; + } + embd = ggml_concat(ctx0, embd, ggml_reshape_3d(ctx0, init, n_embd, n_q, 1), 2); + + embd = ggml_reshape_2d(ctx0, embd, n_embd, n_q * (n_frames + 1)); + cb(embd, "moshi_in_embd", -1); + ggml_build_forward_expand(gf, embd); + + return gf; +} + +// one depformer step: input row x [n_dep, 1], the K/V of the steps so far grow by one row per layer +ggml_tensor * mtmd_graph_moshi_gen::dep_step(ggml_tensor * x, int64_t iw, std::vector & k_all, std::vector & v_all) { + const int64_t n_dep = x->ne[0]; + const int64_t d_head = n_dep / n_head; + + for (size_t il = 0; il < model.layers.size(); il++) { + const auto & layer = model.layers[il]; + ggml_tensor * inp = x; + + ggml_tensor * cur = ggml_mul(ctx0, ggml_rms_norm(ctx0, x, eps), layer.ln_1_w); + ggml_tensor * q = ggml_mul_mat(ctx0, moshi_slice(ctx0, layer.q_w, iw), cur); + ggml_tensor * k = ggml_mul_mat(ctx0, moshi_slice(ctx0, layer.k_w, iw), cur); + ggml_tensor * v = ggml_mul_mat(ctx0, moshi_slice(ctx0, layer.v_w, iw), cur); + + // no positional embedding, causal over the steps of this frame + k_all[il] = k_all[il] ? ggml_concat(ctx0, k_all[il], k, 1) : k; + v_all[il] = v_all[il] ? ggml_concat(ctx0, v_all[il], v, 1) : v; + const int64_t n_kv = k_all[il]->ne[1]; + + cur = build_attn(nullptr, nullptr, + ggml_reshape_4d(ctx0, q, d_head, n_head, 1, 1), + ggml_reshape_4d(ctx0, k_all[il], d_head, n_head, n_kv, 1), + ggml_reshape_4d(ctx0, v_all[il], d_head, n_head, n_kv, 1), + nullptr, 1.0f / sqrtf((float) d_head), (int) il); + x = ggml_add(ctx0, inp, ggml_mul_mat(ctx0, moshi_slice(ctx0, layer.o_w, iw), cur)); + + cur = ggml_mul(ctx0, ggml_rms_norm(ctx0, x, eps), layer.ln_2_w); + cur = ggml_swiglu_split(ctx0, ggml_mul_mat(ctx0, moshi_slice(ctx0, layer.ff_gate_w, iw), cur), + ggml_mul_mat(ctx0, moshi_slice(ctx0, layer.ff_up_w, iw), cur)); + x = ggml_add(ctx0, x, ggml_mul_mat(ctx0, moshi_slice(ctx0, layer.ff_down_w, iw), cur)); + } + return x; +} + +// backbone input of the next frame: sum of the embeddings of the generated codes +ggml_tensor * mtmd_graph_moshi_gen::feedback(const std::vector & codes) { + ggml_tensor * fb = nullptr; + for (size_t k = 0; k < codes.size(); k++) { + ggml_tensor * e = ggml_get_rows(ctx0, moshi_slice(ctx0, model.gen_code_out_embd_w, (int64_t) k), codes[k]); + fb = fb ? ggml_add(ctx0, fb, e) : e; + } + return fb; +} + +ggml_cgraph * mtmd_graph_moshi_gen::build() { + const int64_t n_q = model.gen_code_head_w->ne[2]; + + if (gen_process == MTMD_SUBCTX_GEN_PROCESS_GEN_WAV) { + // codebook-major: row k holds codebook k of every frame + ggml_tensor * inp_codes = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_frames, n_q); + ggml_set_name(inp_codes, "inp_codes"); + ggml_set_input(inp_codes); + + auto codes_of = [&](int64_t k) { + return ggml_view_1d(ctx0, inp_codes, n_frames, (size_t) k * inp_codes->nb[1]); + }; + + // RVQ decode: output_proj(sum of the codebook entries) of the semantic and acoustic parts + const auto & c2w = model.c2w; + ggml_tensor * rest = nullptr; + for (int64_t k = 1; k < n_q; k++) { + ggml_tensor * e = ggml_get_rows(ctx0, moshi_slice(ctx0, c2w.quant_rest_cb_w, k - 1), codes_of(k)); + rest = rest ? ggml_add(ctx0, rest, e) : e; + } + ggml_tensor * cur = build_mm(c2w.quant_first_out_w, ggml_get_rows(ctx0, c2w.quant_first_cb_w, codes_of(0))); + cur = ggml_add(ctx0, cur, build_mm(c2w.quant_rest_out_w, rest)); + cb(cur, "rvq_decode", -1); + + mtmd_graph_pockettts_seanet seanet(*this); + seanet.state_inputs(list_pockettts_state_slots(hparams, model)); + + cur = seanet.mimi_decode(cur, mimi_n_head, mimi_eps); + + seanet.state_outputs(gf); + + cur = ggml_reshape_1d(ctx0, cur, cur->ne[0]); + ggml_set_name(cur, "out_audio"); + ggml_set_output(cur); + ggml_build_forward_expand(gf, cur); + return gf; + } + + // GEN_CODE with all codes known: only their embedding + if (fb_only) { + ggml_tensor * inp_codes = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_q); + ggml_set_name(inp_codes, "inp_codes"); + ggml_set_input(inp_codes); + + std::vector codes; + for (int64_t k = 0; k < n_q; k++) { + codes.push_back(ggml_view_1d(ctx0, inp_codes, 1, (size_t) k * sizeof(int32_t))); + } + ggml_tensor * fb = feedback(codes); + cb(fb, "gen_audio_out", -1); + ggml_build_forward_expand(gf, fb); + return gf; + } + + // the backbone hidden state arrives as the single batch entry + ggml_tensor * h = ggml_reshape_2d(ctx0, build_inp_raw(1), n_mmproj_embd, 1); + + ggml_tensor * inp_code0 = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, 1); // the sampled text token + ggml_set_name(inp_code0, "inp_code0"); + ggml_set_input(inp_code0); + + ggml_tensor * inp_rand = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_q); + ggml_set_name(inp_rand, "inp_rand"); + ggml_set_input(inp_rand); + + mtmd_graph_qwen3tts_gen::code_gen cg(*this, top_k, 1.0f); + + // steps past the last weight set reuse it + const int64_t n_w = model.gen_code_proj_in_w->ne[2]; + + std::vector k_all(model.layers.size(), nullptr); + std::vector v_all(model.layers.size(), nullptr); + std::vector codes; + ggml_tensor * out_codes = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, 1, n_q); + + for (int64_t k = 0; k < n_q; k++) { + const int64_t iw = std::min(k, n_w - 1); + + // the previous token: the text token, then the codes of this frame + ggml_tensor * prev = k == 0 ? ggml_get_rows(ctx0, model.gen_code_tok_embd_w, inp_code0) + : ggml_get_rows(ctx0, moshi_slice(ctx0, model.gen_code_embd_w, k - 1), codes.back()); + ggml_tensor * x = ggml_add(ctx0, ggml_mul_mat(ctx0, moshi_slice(ctx0, model.gen_code_proj_in_w, iw), h), prev); + + x = dep_step(x, iw, k_all, v_all); + + ggml_tensor * logits = ggml_mul_mat(ctx0, moshi_slice(ctx0, model.gen_code_head_w, k), x); + cb(logits, "dep_logits", (int) k); + + ggml_tensor * code; + if (temp <= 0.0f) { + code = ggml_argmax(ctx0, logits); + } else { + if (temp != 1.0f) { + logits = ggml_scale(ctx0, logits, 1.0f / temp); + } + code = cg.do_sampling(logits, ggml_view_1d(ctx0, inp_rand, 1, (size_t) k * sizeof(float))); + } + codes.push_back(code); + out_codes = cg.cache_set(out_codes, (int) k, code); + } + + out_codes = ggml_cont(ctx0, out_codes); + ggml_set_name(out_codes, "out_codes"); + ggml_set_output(out_codes); + ggml_build_forward_expand(gf, out_codes); + + ggml_tensor * fb = feedback(codes); + cb(fb, "gen_audio_out", -1); + ggml_build_forward_expand(gf, fb); + + return gf; +} diff --git a/tools/mtmd/models/parakeet.cpp b/tools/mtmd/models/parakeet.cpp index 4a2377b4cf87..a989e5839177 100644 --- a/tools/mtmd/models/parakeet.cpp +++ b/tools/mtmd/models/parakeet.cpp @@ -296,23 +296,16 @@ ggml_cgraph * mtmd_graph_parakeet::build() { int center = pos_window / 2; size_t offset = rel_pos_scores->nb[0] * (center+1); - rel_pos_scores = ggml_view_3d(ctx0, rel_pos_scores, - n_frame, pos_window, n_head, - (pos_window) * 4, - rel_pos_scores->nb[2], - offset); - rel_pos_scores = ggml_cont(ctx0, rel_pos_scores); - ggml_format_name(rel_pos_scores, "enc_%d_attn_rel_pos_shifted", il); - + // nb1 is the diagonal-extraction stride, not the source row stride rel_pos_scores = ggml_view_3d(ctx0, rel_pos_scores, content_scores->ne[0], content_scores->ne[1], - rel_pos_scores->ne[2], - rel_pos_scores->nb[1], + n_head, + (size_t) pos_window * rel_pos_scores->nb[0], rel_pos_scores->nb[2], - 0); + offset); rel_pos_scores = ggml_cont(ctx0, rel_pos_scores); - ggml_format_name(rel_pos_scores, "enc_%d_attn_rel_pos_shifted_view", il); + ggml_format_name(rel_pos_scores, "enc_%d_attn_rel_pos_shifted", il); } struct ggml_tensor * attn_scores = ggml_add(ctx0, content_scores, rel_pos_scores); diff --git a/tools/mtmd/models/pockettts-gen.cpp b/tools/mtmd/models/pockettts-gen.cpp index c5f340656d6a..db38b8b69dd4 100644 --- a/tools/mtmd/models/pockettts-gen.cpp +++ b/tools/mtmd/models/pockettts-gen.cpp @@ -112,7 +112,7 @@ std::vector list_pockettts_state_slots(const mtmd_hparams & hpar GGML_ASSERT((int) hparams.seanet_ratios.size() >= hparams.seanet_n_stage); GGML_ASSERT(hparams.mimi_tfm_context > 1 && hparams.mimi_downsample > 0); - slots.push_back({"tfm_pos", 1, 1}); + slots.push_back({"pos", 1, 1}); const int64_t n_embd_a = model.gen_tfm_layers[0].q_w->ne[1]; const int64_t prefix = hparams.mimi_tfm_context - 1; @@ -189,99 +189,11 @@ ggml_cgraph * mtmd_graph_pockettts_gen::build() { cb(cur, "quant_out", -1); mtmd_graph_pockettts_seanet seanet(*this); - for (const auto & slot : list_pockettts_state_slots(hparams, model)) { - ggml_tensor * t = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, slot.ne0, slot.ne1); - ggml_set_name(t, ("state_in_" + slot.name).c_str()); - ggml_set_input(t); - seanet.state_in[slot.name] = t; - } - - // model frame rate -> encoder frame rate, depthwise transposed conv - cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur)); - cur = seanet.conv_transpose1d(cur, model.gen_upsample_w, nullptr, hparams.mimi_downsample, "up"); - cb(cur, "mimi_upsample", -1); - - cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur)); - - // positions continue across calls, the counter lives in the state - const int64_t n_pos = cur->ne[1]; - const int64_t prefix = hparams.mimi_tfm_context - 1; - const int64_t n_kv = prefix + n_pos; - - ggml_tensor * base = ggml_reshape_1d(ctx0, seanet.state_in.at("tfm_pos"), 1); - ggml_tensor * inp_pos = ggml_cast(ctx0, ggml_add(ctx0, ggml_arange(ctx0, 0.0f, (float) n_pos, 1.0f), base), - GGML_TYPE_I32); - seanet.state_out.push_back({"tfm_pos", ggml_scale_bias(ctx0, seanet.state_in.at("tfm_pos"), 1.0f, (float) n_pos)}); - - // banded causal mask over [cached prefix | this chunk] - // the last factor masks out cache rows that hold no real frame yet - ggml_tensor * pos_k = ggml_reshape_2d(ctx0, ggml_arange(ctx0, 0.0f, (float) n_kv, 1.0f), n_kv, 1); - ggml_tensor * pos_q = ggml_reshape_2d(ctx0, ggml_arange(ctx0, (float) prefix, (float) (prefix + n_pos), 1.0f), 1, n_pos); - ggml_tensor * diff = ggml_sub(ctx0, ggml_repeat_4d(ctx0, pos_q, n_kv, n_pos, 1, 1), pos_k); - - ggml_tensor * keep = ggml_mul(ctx0, - ggml_step(ctx0, ggml_scale_bias(ctx0, diff, 1.0f, 0.5f)), // delta >= 0 - ggml_step(ctx0, ggml_scale_bias(ctx0, diff, -1.0f, (float) hparams.mimi_tfm_context - 0.5f))); // delta < context - keep = ggml_mul(ctx0, keep, - ggml_step(ctx0, ggml_scale_bias(ctx0, ggml_add(ctx0, pos_k, base), 1.0f, 0.5f - (float) prefix))); - ggml_tensor * kq_mask = ggml_reshape_4d(ctx0, ggml_log(ctx0, keep), n_kv, n_pos, 1, 1); - if (flash_attn_type == MTMD_FLASH_ATTN_TYPE_ENABLED) { - kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F16); - } + seanet.state_inputs(list_pockettts_state_slots(hparams, model)); - for (int il = 0; il < n_layer; il++) { - const auto & layer = model.gen_tfm_layers[il]; - ggml_tensor * inp = cur; - - cur = build_norm(cur, layer.ln_1_w, layer.ln_1_b, NORM_TYPE_NORMAL, eps, il); - - ggml_tensor * Qcur = build_mm(layer.q_w, cur); - ggml_tensor * Kcur = build_mm(layer.k_w, cur); - ggml_tensor * Vcur = build_mm(layer.v_w, cur); - - Qcur = ggml_reshape_3d(ctx0, Qcur, d_head, n_head, n_pos); - Kcur = ggml_reshape_3d(ctx0, Kcur, d_head, n_head, n_pos); - - Qcur = ggml_rope_ext(ctx0, Qcur, inp_pos, nullptr, d_head, GGML_ROPE_TYPE_NORMAL, 0, - hparams.rope_theta, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f); - Kcur = ggml_rope_ext(ctx0, Kcur, inp_pos, nullptr, d_head, GGML_ROPE_TYPE_NORMAL, 0, - hparams.rope_theta, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f); - - // prepend the cached window, then keep this chunk's tail for the next call - const std::string k_name = "tfm_k_" + std::to_string(il); - const std::string v_name = "tfm_v_" + std::to_string(il); - ggml_tensor * k_full = ggml_concat(ctx0, seanet.state_in.at(k_name), - ggml_reshape_2d(ctx0, Kcur, d_head * n_head, n_pos), 1); - ggml_tensor * v_full = ggml_concat(ctx0, seanet.state_in.at(v_name), Vcur, 1); - seanet.state_out.push_back({k_name, ggml_cont(ctx0, ggml_view_2d(ctx0, k_full, k_full->ne[0], prefix, - k_full->nb[1], (size_t) n_pos * k_full->nb[1]))}); - seanet.state_out.push_back({v_name, ggml_cont(ctx0, ggml_view_2d(ctx0, v_full, v_full->ne[0], prefix, - v_full->nb[1], (size_t) n_pos * v_full->nb[1]))}); - - ggml_tensor * q_cur = ggml_reshape_4d(ctx0, Qcur, d_head, n_head, n_pos, 1); - ggml_tensor * k_cur = ggml_reshape_4d(ctx0, k_full, d_head, n_head, n_kv, 1); - ggml_tensor * v_cur = ggml_reshape_4d(ctx0, v_full, d_head, n_head, n_kv, 1); - - cur = build_attn(layer.o_w, nullptr, q_cur, k_cur, v_cur, kq_mask, kq_scale, il); - cur = ggml_mul(ctx0, cur, layer.ls_1_w); - cur = ggml_add(ctx0, cur, inp); - - inp = cur; - cur = build_norm(cur, layer.ln_2_w, layer.ln_2_b, NORM_TYPE_NORMAL, eps, il); - cur = build_ffn(cur, layer.ff_up_w, nullptr, nullptr, nullptr, layer.ff_down_w, nullptr, FFN_GELU, il); - cur = ggml_mul(ctx0, cur, layer.ls_2_w); - cur = ggml_add(ctx0, cur, inp); - } - cb(cur, "mimi_dec_tfm", -1); - - cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur)); - cur = seanet.decode(cur); + cur = seanet.mimi_decode(cur, n_head, eps); - for (const auto & s : seanet.state_out) { - ggml_set_name(s.second, ("state_out_" + s.first).c_str()); - ggml_set_output(s.second); - ggml_build_forward_expand(gf, s.second); - } + seanet.state_outputs(gf); // [n_samples, 1] -> [n_samples], clamped like the reference output cur = ggml_reshape_1d(ctx0, cur, cur->ne[0]); diff --git a/tools/mtmd/models/pockettts-seanet.cpp b/tools/mtmd/models/pockettts-seanet.cpp index f1073c8442ff..e0a97bdc6a5b 100644 --- a/tools/mtmd/models/pockettts-seanet.cpp +++ b/tools/mtmd/models/pockettts-seanet.cpp @@ -125,22 +125,27 @@ ggml_tensor * mtmd_graph_pockettts_seanet::res_unit(ggml_tensor * x, const mtmd_ ggml_tensor * mtmd_graph_pockettts_seanet::encode(ggml_tensor * x) const { const auto & seanet = model.seanet; + const bool stream = !state_in.empty(); - ggml_tensor * cur = conv1d(x, seanet.conv_in_w, seanet.conv_in_b, 1, 1); + ggml_tensor * cur = conv1d(x, seanet.conv_in_w, seanet.conv_in_b, 1, 1, false, + stream ? "enc_in" : ""); cb(cur, "seanet_enc_in", -1); for (int i = 0; i < hparams.seanet_n_stage; i++) { const auto & stage = seanet.stages[i]; const int stride = hparams.seanet_ratios[i]; + const std::string id = std::to_string(i); - cur = res_unit(cur, stage, 1); + cur = res_unit(cur, stage, 1, stream ? "enc_res_" + id : ""); cur = ggml_elu(ctx0, cur); - cur = conv1d(cur, stage.scale_conv_w, stage.scale_conv_b, stride, 1); + cur = conv1d(cur, stage.scale_conv_w, stage.scale_conv_b, stride, 1, false, + stream ? "enc_down_" + id : ""); cb(cur, "seanet_enc_stage", i); } cur = ggml_elu(ctx0, cur); - cur = conv1d(cur, seanet.conv_out_w, seanet.conv_out_b, 1, 1); + cur = conv1d(cur, seanet.conv_out_w, seanet.conv_out_b, 1, 1, false, + stream ? "enc_out" : ""); cb(cur, "seanet_enc_out", -1); return cur; @@ -174,3 +179,112 @@ ggml_tensor * mtmd_graph_pockettts_seanet::decode(ggml_tensor * x) const { return cur; } + +// pre-norm blocks with layer scale on both residual paths, see mimi_transformer.py +// causal over a window of mimi_tfm_context frames, streams through the slots pos, tfm_k_, tfm_v_ +// x: [dim, n_pos] -> [dim, n_pos] +ggml_tensor * mtmd_graph_pockettts_seanet::transformer(ggml_tensor * cur, const std::vector & layers, int n_head, float eps) const { + const int64_t n_pos = cur->ne[1]; + const int64_t d_head = cur->ne[0] / n_head; + const int64_t prefix = hparams.mimi_tfm_context - 1; + const int64_t n_kv = prefix + n_pos; + const float scale = 1.0f / sqrtf((float) d_head); + + // positions continue across calls, the counter lives in the state + ggml_tensor * base = ggml_reshape_1d(ctx0, state_in.at("pos"), 1); + ggml_tensor * inp_pos = ggml_cast(ctx0, ggml_add(ctx0, ggml_arange(ctx0, 0.0f, (float) n_pos, 1.0f), base), + GGML_TYPE_I32); + state_out.push_back({"pos", ggml_scale_bias(ctx0, state_in.at("pos"), 1.0f, (float) n_pos)}); + + // banded causal mask over [cached prefix | this chunk] + // the last factor masks out cache rows that hold no real frame yet + ggml_tensor * pos_k = ggml_reshape_2d(ctx0, ggml_arange(ctx0, 0.0f, (float) n_kv, 1.0f), n_kv, 1); + ggml_tensor * pos_q = ggml_reshape_2d(ctx0, ggml_arange(ctx0, (float) prefix, (float) (prefix + n_pos), 1.0f), 1, n_pos); + ggml_tensor * diff = ggml_sub(ctx0, ggml_repeat_4d(ctx0, pos_q, n_kv, n_pos, 1, 1), pos_k); + + ggml_tensor * keep = ggml_mul(ctx0, + ggml_step(ctx0, ggml_scale_bias(ctx0, diff, 1.0f, 0.5f)), // delta >= 0 + ggml_step(ctx0, ggml_scale_bias(ctx0, diff, -1.0f, (float) hparams.mimi_tfm_context - 0.5f))); // delta < context + keep = ggml_mul(ctx0, keep, + ggml_step(ctx0, ggml_scale_bias(ctx0, ggml_add(ctx0, pos_k, base), 1.0f, 0.5f - (float) prefix))); + ggml_tensor * kq_mask = ggml_reshape_4d(ctx0, ggml_log(ctx0, keep), n_kv, n_pos, 1, 1); + if (flash_attn_type == MTMD_FLASH_ATTN_TYPE_ENABLED) { + kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F16); + } + + for (size_t il = 0; il < layers.size(); il++) { + const auto & layer = layers[il]; + ggml_tensor * inp = cur; + + cur = build_norm(cur, layer.ln_1_w, layer.ln_1_b, NORM_TYPE_NORMAL, eps, il); + + ggml_tensor * Qcur = build_mm(layer.q_w, cur); + ggml_tensor * Kcur = build_mm(layer.k_w, cur); + ggml_tensor * Vcur = build_mm(layer.v_w, cur); + + Qcur = ggml_reshape_3d(ctx0, Qcur, d_head, n_head, n_pos); + Kcur = ggml_reshape_3d(ctx0, Kcur, d_head, n_head, n_pos); + + Qcur = ggml_rope_ext(ctx0, Qcur, inp_pos, nullptr, d_head, GGML_ROPE_TYPE_NORMAL, 0, + hparams.rope_theta, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f); + Kcur = ggml_rope_ext(ctx0, Kcur, inp_pos, nullptr, d_head, GGML_ROPE_TYPE_NORMAL, 0, + hparams.rope_theta, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f); + + // prepend the cached window, then keep this chunk's tail for the next call + const std::string k_name = "tfm_k_" + std::to_string(il); + const std::string v_name = "tfm_v_" + std::to_string(il); + ggml_tensor * k_full = ggml_concat(ctx0, state_in.at(k_name), + ggml_reshape_2d(ctx0, Kcur, d_head * n_head, n_pos), 1); + ggml_tensor * v_full = ggml_concat(ctx0, state_in.at(v_name), Vcur, 1); + state_out.push_back({k_name, ggml_cont(ctx0, ggml_view_2d(ctx0, k_full, k_full->ne[0], prefix, + k_full->nb[1], (size_t) n_pos * k_full->nb[1]))}); + state_out.push_back({v_name, ggml_cont(ctx0, ggml_view_2d(ctx0, v_full, v_full->ne[0], prefix, + v_full->nb[1], (size_t) n_pos * v_full->nb[1]))}); + + ggml_tensor * q_cur = ggml_reshape_4d(ctx0, Qcur, d_head, n_head, n_pos, 1); + ggml_tensor * k_cur = ggml_reshape_4d(ctx0, k_full, d_head, n_head, n_kv, 1); + ggml_tensor * v_cur = ggml_reshape_4d(ctx0, v_full, d_head, n_head, n_kv, 1); + + cur = build_attn(layer.o_w, nullptr, q_cur, k_cur, v_cur, kq_mask, scale, il); + cur = ggml_mul(ctx0, cur, layer.ls_1_w); + cur = ggml_add(ctx0, cur, inp); + + inp = cur; + cur = build_norm(cur, layer.ln_2_w, layer.ln_2_b, NORM_TYPE_NORMAL, eps, il); + cur = build_ffn(cur, layer.ff_up_w, nullptr, nullptr, nullptr, layer.ff_down_w, nullptr, FFN_GELU, il); + cur = ggml_mul(ctx0, cur, layer.ls_2_w); + cur = ggml_add(ctx0, cur, inp); + } + return cur; +} + +ggml_tensor * mtmd_graph_pockettts_seanet::mimi_decode(ggml_tensor * x, int n_head, float eps) const { + // model frame rate -> encoder frame rate, depthwise transposed conv + ggml_tensor * cur = ggml_cont(ctx0, ggml_transpose(ctx0, x)); + cur = conv_transpose1d(cur, model.gen_upsample_w, nullptr, hparams.mimi_downsample, "up"); + cb(cur, "mimi_upsample", -1); + + cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur)); + cur = transformer(cur, model.gen_tfm_layers, n_head, eps); + cb(cur, "mimi_dec_tfm", -1); + + cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur)); + return decode(cur); +} + +void mtmd_graph_pockettts_seanet::state_inputs(const std::vector & slots) { + for (const auto & slot : slots) { + ggml_tensor * t = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, slot.ne0, slot.ne1); + ggml_set_name(t, ("state_in_" + slot.name).c_str()); + ggml_set_input(t); + state_in[slot.name] = t; + } +} + +void mtmd_graph_pockettts_seanet::state_outputs(ggml_cgraph * graph) const { + for (const auto & s : state_out) { + ggml_set_name(s.second, ("state_out_" + s.first).c_str()); + ggml_set_output(s.second); + ggml_build_forward_expand(graph, s.second); + } +} diff --git a/tools/mtmd/models/qwen3tts-gen.cpp b/tools/mtmd/models/qwen3tts-gen.cpp index a453b09f515a..8cee94407bb0 100644 --- a/tools/mtmd/models/qwen3tts-gen.cpp +++ b/tools/mtmd/models/qwen3tts-gen.cpp @@ -665,7 +665,7 @@ std::vector list_c2w_state_slots(const mtmd_hparams & hparams, c } // x: [dim, T], codebook: [dim, n_entries] -> [T] index of the nearest entry -ggml_tensor * mtmd_graph_qwen3tts_gen::nearest_code(ggml_tensor * x, ggml_tensor * codebook) const { +ggml_tensor * mtmd_graph_qwen3tts_gen::nearest_code(ggml_context * ctx0, ggml_tensor * x, ggml_tensor * codebook) { // argmin |x - e|^2 = argmax 2 x.e - |e|^2 ggml_tensor * dots = ggml_mul_mat(ctx0, codebook, x); // [n_entries, T] ggml_tensor * norms = ggml_sum_rows(ctx0, ggml_sqr(ctx0, codebook)); // [1, n_entries] @@ -673,6 +673,24 @@ ggml_tensor * mtmd_graph_qwen3tts_gen::nearest_code(ggml_tensor * x, ggml_tensor return ggml_argmax(ctx0, ggml_sub(ctx0, ggml_scale(ctx0, dots, 2.0f), norms)); } +std::vector mtmd_graph_qwen3tts_gen::rvq_encode(ggml_context * ctx0, ggml_tensor * x_first, ggml_tensor * cb_first, + ggml_tensor * x_rest, ggml_tensor * cb_rest) { + std::vector codes; + codes.push_back(nearest_code(ctx0, x_first, cb_first)); + + const int64_t n_rest = cb_rest->ne[2]; + ggml_tensor * residual = x_rest; + for (int64_t i = 0; i < n_rest; i++) { + ggml_tensor * codebook = ggml_view_2d(ctx0, cb_rest, cb_rest->ne[0], cb_rest->ne[1], cb_rest->nb[1], (size_t) i * cb_rest->nb[2]); + ggml_tensor * code = nearest_code(ctx0, residual, codebook); + codes.push_back(code); + if (i + 1 < n_rest) { + residual = ggml_sub(ctx0, residual, ggml_get_rows(ctx0, codebook, code)); + } + } + return codes; +} + // the mimi encoder of the speech tokenizer, then its RVQ: one semantic codebook and n_acoustic acoustic ones ggml_cgraph * mtmd_graph_qwen3tts_gen::build_ref_encoder() { // the waveform comes in as a single-row "mel", [n_samples, 1] @@ -694,20 +712,9 @@ ggml_cgraph * mtmd_graph_qwen3tts_gen::build_ref_encoder() { cur = mimi.encode(seanet, cur, model.ref_enc_layers); cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur)); // [512, T] - std::vector codes; - codes.push_back(nearest_code(build_mm(model.ref_quant_first_in_w, cur), model.ref_quant_first_cb)); - + const std::vector codes = rvq_encode(ctx0, build_mm(model.ref_quant_first_in_w, cur), model.ref_quant_first_cb, + build_mm(model.ref_quant_rest_in_w, cur), model.ref_quant_rest_cb); const int64_t n_acoustic = model.ref_quant_rest_cb->ne[2]; - ggml_tensor * residual = build_mm(model.ref_quant_rest_in_w, cur); - for (int64_t i = 0; i < n_acoustic; i++) { - ggml_tensor * codebook = ggml_view_2d(ctx0, model.ref_quant_rest_cb, model.ref_quant_rest_cb->ne[0], model.ref_quant_rest_cb->ne[1], - model.ref_quant_rest_cb->nb[1], (size_t) i * model.ref_quant_rest_cb->nb[2]); - ggml_tensor * code = nearest_code(residual, codebook); - codes.push_back(code); - if (i + 1 < n_acoustic) { - residual = ggml_sub(ctx0, residual, ggml_get_rows(ctx0, codebook, code)); - } - } // talker input rows of the reference frames: codebook 0 from the talker table, the rest from the code predictor's ggml_tensor * rows = ggml_get_rows(ctx0, model.gen_code_out_embd_w, codes[0]); diff --git a/tools/mtmd/mtmd-cli.cpp b/tools/mtmd/mtmd-cli.cpp index 4534527fc8a7..8fc8d1b892ce 100644 --- a/tools/mtmd/mtmd-cli.cpp +++ b/tools/mtmd/mtmd-cli.cpp @@ -120,6 +120,10 @@ struct mtmd_cli_context { init_vision_context(params); mtmd_cap = mtmd_helper_get_capabilities(model, ctx_vision.get()); + if (mtmd_cap.audio_duplex) { + LOG_ERR("Full duplex models only run in llama-server, see the /v1/realtime endpoint\n"); + exit(1); + } // a realtime transcription model has no chat, it streams the audio below if (!mtmd_cap.chat && !mtmd_cap.audio_stream) { LOG_ERR("Model does not support chat mode\n"); diff --git a/tools/mtmd/mtmd-graph.cpp b/tools/mtmd/mtmd-graph.cpp index 81ae155acefd..a22f41d372da 100644 --- a/tools/mtmd/mtmd-graph.cpp +++ b/tools/mtmd/mtmd-graph.cpp @@ -1000,6 +1000,24 @@ std::unique_ptr mtmd_get_graph_builder(mtmd_subcontext * ctx, const { builder = std::make_unique(ctx, img); } break; + case PROJECTOR_TYPE_MOSHI: + { + builder = std::make_unique(ctx, img); + } break; + case PROJECTOR_TYPE_MOSHI_GEN: + { + const auto gen_process = params ? params->gen_process : MTMD_SUBCTX_GEN_PROCESS_GEN_CODE; + const int64_t n_q = ctx->model.gen_code_head_w->ne[2]; + const bool has_codes = params && params->codes; + if (has_codes) { + GGML_ASSERT(params->codes->size() % (size_t) n_q == 0); + } + const int n_frames = has_codes ? (int) (params->codes->size() / n_q) : 1; + const int top_k = params ? params->top_k : 250; + const float temp = params ? params->temp : 0.8f; + const bool fb_only = gen_process == MTMD_SUBCTX_GEN_PROCESS_GEN_CODE && has_codes; + builder = std::make_unique(ctx, img, gen_process, fb_only, n_frames, top_k, temp); + } break; case PROJECTOR_TYPE_CHATTERBOX: { const auto gen_process = params ? params->gen_process : MTMD_SUBCTX_GEN_PROCESS_GEN_CODE; diff --git a/tools/mtmd/mtmd-helper-gen.cpp b/tools/mtmd/mtmd-helper-gen.cpp index 32f1d39d4356..03ab766d9f8d 100644 --- a/tools/mtmd/mtmd-helper-gen.cpp +++ b/tools/mtmd/mtmd-helper-gen.cpp @@ -2739,6 +2739,9 @@ class drama3_gen_audio_pipeline : public mtmd_gen_audio_pipeline { seq_id = 0; pos = 0; prompt_tokens.clear(); + ref_codes.clear(); + ref_embd.clear(); + ref_begin = 0; prompt_pos = 0; frame.clear(); main_logits.clear(); @@ -2758,8 +2761,16 @@ class drama3_gen_audio_pipeline : public mtmd_gen_audio_pipeline { seq_id = inp->seq_id; out_type = inp->out_type; stream = inp->stream; - if (inp->speaker_ref) { - LOG_WRN("mtmd_helper_gen_audio: voice cloning is not supported yet, the speaker file is ignored\n"); + + // voice cloning: backbone rows from the codec encoder, the codes of the clip go to the gen state + std::vector ref_rows; + if (inp->speaker_ref && !mtmd_bitmap_is_voice(inp->speaker_ref) && !mtmd_support_audio(mctx)) { + LOG_WRN("mtmd_helper_gen_audio: mmproj has no speaker encoder (re-convert it for voice cloning), the speaker file is ignored\n"); + } else if (inp->speaker_ref) { + if (!encode_speaker(inp->speaker_ref, ref_rows) || !init_gen_state(inp->seed) || + mtmd_gen_state_set_ref(mctx, gen_state.get()) != 0) { + return 1; + } } sem_begin = find_special_token(vocab, "<|semantic:0|>"); @@ -2770,7 +2781,12 @@ class drama3_gen_audio_pipeline : public mtmd_gen_audio_pipeline { return 1; } - if (!tokenize_segments(prompt_segments(std::string(inp->prompt, inp->prompt_len)), prompt_tokens)) { + const std::string text(inp->prompt, inp->prompt_len); + if (ref_rows.empty()) { + if (!tokenize_segments(prompt_segments(text), prompt_tokens)) { + return 1; + } + } else if (!build_reference_prompt(text, inp->speaker_ref_text ? inp->speaker_ref_text : "", std::move(ref_rows))) { return 1; } if (prompt_tokens.size() >= llama_n_ctx_seq(lctx) || prompt_tokens.size() > max_rows()) { @@ -2782,7 +2798,7 @@ class drama3_gen_audio_pipeline : public mtmd_gen_audio_pipeline { return 1; } rng.seed(inp->seed == UINT32_MAX ? std::random_device{}() : inp->seed); - return init_gen_state(inp->seed) ? 0 : 1; + return gen_state || init_gen_state(inp->seed) ? 0 : 1; } // run the tower on every prompt row to fill its KV @@ -2792,27 +2808,41 @@ class drama3_gen_audio_pipeline : public mtmd_gen_audio_pipeline { if (prompt_pos >= n_prompt) { return 0; } - // small batches: every row also outputs logits - const int n = std::min({ n_batch, n_prompt - prompt_pos, 64 }); - llama_batch_ext_ptr batch(llama_batch_ext_init(lctx)); - if (!batch_set_tokens(batch.get(), prompt_tokens.data() + prompt_pos, n, pos, seq_id)) { - return -1; + // small batches of rows of one kind (text tokens or reference frames): every row also outputs logits + const bool speech = is_speech_row(prompt_pos); + int n = std::min({ n_batch, n_prompt - prompt_pos, 64 }); + for (int i = 1; i < n; i++) { + if (is_speech_row(prompt_pos + i) != speech) { + n = i; + break; + } } - for (int i = 0; i < n; i++) { - llama_batch_ext_set_output_logits(batch.get(), i, true); + int ret = 0; + if (speech) { + ret = decode_embd_rows(ref_embd.data() + (size_t) (prompt_pos - ref_begin) * n_embd, n); + } else { + llama_batch_ext_ptr batch(llama_batch_ext_init(lctx)); + if (!batch_set_tokens(batch.get(), prompt_tokens.data() + prompt_pos, n, pos, seq_id)) { + return -1; + } + for (int i = 0; i < n; i++) { + llama_batch_ext_set_output_logits(batch.get(), i, true); + } + ret = llama_process(lctx, LLAMA_PROCESS_TYPE_DECODE, batch.get()); } - if (llama_process(lctx, LLAMA_PROCESS_TYPE_DECODE, batch.get()) != 0) { + if (ret != 0) { LOG_ERR("mtmd_helper_gen_audio: prompt decode failed\n"); return -1; } for (int i = 0; i < n; i++) { + const int row = prompt_pos + i; const float * h = llama_get_embeddings_ith(lctx, i); - if (prompt_pos + i == n_prompt - 1) { + if (row == n_prompt - 1) { h_state_buf.assign(h, h + n_embd); // first frame comes from the last prompt row save_main_logits(i); break; } - if (!run_tower(-1, h)) { + if (!run_prompt_tower(row, h)) { return -1; } } @@ -2845,17 +2875,7 @@ class drama3_gen_audio_pipeline : public mtmd_gen_audio_pipeline { } codes_buf.insert(codes_buf.end(), frame.begin(), frame.end()); - // text/speech stream: all mrope sections use the same position - const bool mrope = llama_model_rope_type(model) == LLAMA_ROPE_TYPE_MROPE || - llama_model_rope_type(model) == LLAMA_ROPE_TYPE_IMROPE; - decode_embd_batch batch(next_embd, 1, mrope ? 4 : 1, n_embd); - if (mrope) { - batch.set_position_mrope_1d(pos, seq_id); - } else { - batch.set_position_normal(pos, seq_id); - } - batch.logits[0] = 1; - if (llama_process(lctx, LLAMA_PROCESS_TYPE_DECODE, batch.render(lctx, 0, 1)) != 0) { + if (decode_embd_rows(next_embd, 1) != 0) { LOG_ERR("mtmd_helper_gen_audio: decode failed\n"); return 1; } @@ -2938,9 +2958,24 @@ class drama3_gen_audio_pipeline : public mtmd_gen_audio_pipeline { return true; } + // offset of the leading speaker tag <|speaker:N|> after optional whitespace, npos without one + static size_t speaker_tag_pos(const std::string & text) { + const size_t lead = text.find_first_not_of(" \t\n\r\f\v"); + static const std::string open = "<|speaker:"; + if (lead == std::string::npos || text.compare(lead, open.size(), open) != 0) { + return std::string::npos; + } + size_t i = lead + open.size(); + const size_t digits = i; + while (i < text.size() && text[i] >= '0' && text[i] <= '9') { + i++; + } + return i > digits && text.compare(i, 2, "|>") == 0 ? lead : std::string::npos; + } + // reference-bracket-v1 prompt without references virtual std::vector prompt_segments(std::string text) const { - if (text.rfind("<|speaker:", 0) != 0) { + if (speaker_tag_pos(text) == std::string::npos) { text = "<|speaker:0|> " + text; } return { @@ -2952,6 +2987,86 @@ class drama3_gen_audio_pipeline : public mtmd_gen_audio_pipeline { // prompt rows but the last + generated frames virtual size_t max_rows() const { return n_tower_rows; } + // n speech rows from pos, every row outputs logits + // text/speech stream: all mrope sections use the same position + int32_t decode_embd_rows(const float * embd, int n) { + const bool mrope = llama_model_rope_type(model) == LLAMA_ROPE_TYPE_MROPE || + llama_model_rope_type(model) == LLAMA_ROPE_TYPE_IMROPE; + decode_embd_batch batch(embd, n, mrope ? 4 : 1, n_embd); + if (mrope) { + batch.set_position_mrope_1d(pos, seq_id); + } else { + batch.set_position_normal(pos, seq_id); + } + for (int i = 0; i < n; i++) { + batch.logits[i] = 1; + } + return llama_process(lctx, LLAMA_PROCESS_TYPE_DECODE, batch.render(lctx, 0, n)); + } + + bool is_speech_row(int row) const { + return row >= ref_begin && (size_t) (row - ref_begin) < ref_embd.size() / n_embd; + } + + // reference-bracket-v1 with one reference, see vLLM-Omni fish_omni/prompt.py + // system: instruction, "\n\n[Reference 1]\nText: \nSpeech: " then one row per frame of the clip + bool build_reference_prompt(std::string text, std::string ref_text, std::vector && ref_rows) { + size_t n_codes = 0; + const int32_t * codes = mtmd_gen_state_get_ref_codes(gen_state.get(), &n_codes); + const size_t n_frames = ref_rows.size() / n_embd; + if (!codes || n_frames == 0 || n_codes != n_frames * n_cb || ref_rows.size() != n_frames * n_embd) { + LOG_ERR("mtmd_helper_gen_audio: the speaker encoder gave no codes for the clip\n"); + return false; + } + // the speaker tag follows "Text: " directly (default speaker 0), an untagged target reuses it + std::string tag = "<|speaker:0|>"; + const size_t lead = speaker_tag_pos(ref_text); + if (lead == std::string::npos) { + ref_text = tag + " " + ref_text; + } else { + ref_text = ref_text.substr(lead); + tag = ref_text.substr(0, ref_text.find("|>") + 2); + } + if (speaker_tag_pos(text) == std::string::npos) { + text = tag + " " + text; + } + + std::vector head, tail; + if (!tokenize_segments({ "<|im_start|>system\n", "convert the provided text to speech reference to the following:", + "\n\n[Reference 1]\nText: " + ref_text + "\nSpeech: " }, head) || + !tokenize_segments({ "<|im_end|>\n", "<|im_start|>user\n", text, "<|im_end|>\n", "<|im_start|>assistant\n<|voice|>" }, tail)) { + return false; + } + prompt_tokens.assign(head.begin(), head.end()); + prompt_tokens.insert(prompt_tokens.end(), n_frames, LLAMA_TOKEN_NULL); + prompt_tokens.insert(prompt_tokens.end(), tail.begin(), tail.end()); + ref_codes.assign(codes, codes + n_codes); + ref_embd = std::move(ref_rows); + ref_begin = (int) head.size(); + return true; + } + + // tower row of a prompt row: the input frame is the codes of this row (reference frame) or none, + // the codes of the next row are forced when it is a reference frame + bool run_prompt_tower(int row, const float * h) { + const bool cur = is_speech_row(row); + const bool next = is_speech_row(row + 1); + const auto ref_frame = [&](int r) { return ref_codes.begin() + (size_t) (r - ref_begin) * n_cb; }; + if (next) { + // [input frame, -1 for a text row | forced next frame] + frame.assign(n_cb, -1); + if (cur) { + std::copy(ref_frame(row), ref_frame(row + 1), frame.begin()); + } + frame.insert(frame.end(), ref_frame(row + 1), ref_frame(row + 2)); + } else if (cur) { + frame.assign(ref_frame(row), ref_frame(row + 1)); + } + const bool ok = run_tower(next ? frame[n_cb] : -1, h) != nullptr; + frame.clear(); + return ok; + } + // copy right after our own decode, other sequences may decode on lctx before the next step_gen // layout: eos, then semantic codes 0..n_cb_vocab-1 void save_main_logits(int32_t i) { @@ -3072,7 +3187,10 @@ class drama3_gen_audio_pipeline : public mtmd_gen_audio_pipeline { llama_seq_id seq_id = 0; llama_pos pos = 0; - std::vector prompt_tokens; + std::vector prompt_tokens; // one per prompt row, LLAMA_TOKEN_NULL for a reference frame + std::vector ref_codes; // codes of the reference frames, n_cb per frame + std::vector ref_embd; // backbone rows of the reference frames + int ref_begin = 0; // prompt row of the first reference frame int prompt_pos = 0; std::mt19937 rng; @@ -5341,6 +5459,141 @@ class voxcpm2_gen_audio_pipeline : public mtmd_gen_audio_pipeline { bool wav_header_sent = false; }; +// Moshi family (e.g. Hibiki): full duplex, the caller drives the backbone with the rows of an audio stream (mtmd_audio_stream) +// per frame: the caller decodes the stream row + h_state_out of the previous step, samples the text token from it, +// then step_gen() turns the text token and the hidden state into the codes of the frame (depformer) and decodes their audio +// h_state_out is the backbone embedding of the generated codes, to be added to the next stream row (zero before the first step) +class moshi_gen_audio_pipeline : public mtmd_gen_audio_pipeline { +public: + using mtmd_gen_audio_pipeline::mtmd_gen_audio_pipeline; + + // the acoustic codes lag the semantic one by this many frames, see "delays" of the checkpoint + static constexpr int acoustic_delay = 2; + + int32_t max_frames() const override { return 0; } + + void reset() override { + n_step = 0; + cb0_hist.clear(); + audio_pcm.clear(); + pcm_sent = 0; + h_state_buf.clear(); + gen_state.reset(); + } + + int32_t set_input(const mtmd_helper_gen_audio_inp * inp) override { + reset(); + if (inp->prompt_len > 0 || inp->speaker_ref) { + LOG_ERR("mtmd_helper_gen_audio: the model answers an audio stream, it takes no prompt or speaker\n"); + return 2; + } + if (!inp->stream || inp->out_type != MTMD_HELPER_GEN_AUDIO_OUTTYPE_PCM) { + LOG_ERR("mtmd_helper_gen_audio: the model only streams PCM\n"); + return 2; + } + const mtmd_gen_inp def = mtmd_gen_inp_default(mctx); + temp = inp->temp >= 0.0f ? inp->temp : def.temp; + top_k = def.top_k; + return init_gen_state(inp->seed) ? 0 : 1; + } + + int32_t step_prompt(int32_t n_batch) override { + GGML_UNUSED(n_batch); + return 0; + } + + bool next_is_text() const override { + return true; + } + + int32_t step_gen(llama_token sampled, const float * h_state_in, const float ** h_state_out, bool * out_stop) override { + if (out_stop) { + *out_stop = false; + } + mtmd_gen_inp inp = mtmd_gen_inp_default(mctx); + inp.type = MTMD_GEN_PROCESS_TYPE_GEN_CODE; + inp.embd = const_cast(h_state_in); + inp.code0 = sampled; + inp.top_k = top_k; + inp.temp = temp; + mtmd_gen_out out{}; + if (mtmd_gen_audio_process(mctx, gen_state.get(), &inp, &out) != 0 || out.n_codes == 0) { + LOG_ERR("mtmd_helper_gen_audio: depformer failed\n"); + return 1; + } + const std::vector codes(out.codes, out.codes + out.n_codes); + const int n_q = (int) codes.size(); + h_state_buf.assign(out.embd, out.embd + n_embd); + + // the next row is position n_step + 1, its acoustic codes are still the initial ones at the start + if (n_step + 1 <= acoustic_delay) { + std::vector fb = codes; + std::fill(fb.begin() + 1, fb.end(), code_initial); + inp.codes = fb.data(); + inp.n_codes = fb.size(); + if (mtmd_gen_audio_process(mctx, gen_state.get(), &inp, &out) != 0) { + LOG_ERR("mtmd_helper_gen_audio: code embedding failed\n"); + return 1; + } + h_state_buf.assign(out.embd, out.embd + n_embd); + } + + // frame f has the semantic code of step f and the acoustic codes of step f + acoustic_delay + cb0_hist.push_back(codes[0]); + if ((int) cb0_hist.size() > acoustic_delay) { + std::vector frame = codes; + frame[0] = cb0_hist.front(); + cb0_hist.erase(cb0_hist.begin()); + + mtmd_gen_inp winp = mtmd_gen_inp_default(mctx); + winp.type = MTMD_GEN_PROCESS_TYPE_GEN_WAV; + winp.codes = frame.data(); + winp.n_codes = (size_t) n_q; + mtmd_gen_out wout{}; + if (mtmd_gen_audio_process(mctx, gen_state.get(), &winp, &wout) != 0) { + LOG_ERR("mtmd_helper_gen_audio: mimi decode failed\n"); + return 1; + } + audio_pcm.insert(audio_pcm.end(), wout.audio, wout.audio + wout.n_samples); + } + + n_step++; + *h_state_out = h_state_buf.data(); + return 0; + } + + int32_t get_output(int32_t * out_sample_rate, const char ** out_data, size_t * out_data_len, int64_t * out_n_samples) override { + *out_sample_rate = info.sample_rate; + // the audio delivered by the previous call is not needed again + audio_pcm.erase(audio_pcm.begin(), audio_pcm.begin() + pcm_sent); + if (out_n_samples) { + *out_n_samples = (int64_t) audio_pcm.size(); + } + *out_data = (const char *) audio_pcm.data(); + *out_data_len = audio_pcm.size() * sizeof(float); + pcm_sent = audio_pcm.size(); + return 0; + } + + // every frame is decoded as soon as its codes are known + int32_t flush() override { + return 0; + } + +private: + // the extra entry after the mimi codebook, see _get_initial_token() of the reference + static constexpr int32_t code_initial = 2048; + + float temp = 0.8f; + int32_t top_k = 250; + + int64_t n_step = 0; + std::vector cb0_hist; // semantic codes waiting for the acoustic codes of their frame + std::vector audio_pcm; + size_t pcm_sent = 0; + std::vector h_state_buf; +}; + static std::unique_ptr make_pipeline(llama_context * lctx, mtmd_context * mctx) { switch (mtmd_gen_audio_get_info(mctx).type) { case MTMD_GEN_AUDIO_TYPE_QWEN3TTS: @@ -5367,6 +5620,8 @@ static std::unique_ptr make_pipeline(llama_context * lc return std::unique_ptr(new music3_gen_audio_pipeline(lctx, mctx)); case MTMD_GEN_AUDIO_TYPE_FISH_S2: return std::unique_ptr(new fish_s2_gen_audio_pipeline(lctx, mctx)); + case MTMD_GEN_AUDIO_TYPE_MOSHI: + return std::unique_ptr(new moshi_gen_audio_pipeline(lctx, mctx)); case MTMD_GEN_AUDIO_TYPE_VOXCPM2: return std::unique_ptr(new voxcpm2_gen_audio_pipeline(lctx, mctx)); default: diff --git a/tools/mtmd/mtmd-helper.cpp b/tools/mtmd/mtmd-helper.cpp index bce73a74e6de..165936d80c1a 100644 --- a/tools/mtmd/mtmd-helper.cpp +++ b/tools/mtmd/mtmd-helper.cpp @@ -1048,6 +1048,7 @@ mtmd_helper_cap mtmd_helper_get_capabilities(const llama_model * model, const mt cap.audio_gen = gen_audio_type != MTMD_GEN_AUDIO_TYPE_NONE; cap.audio_gen_spk_ref = gen_audio_type == MTMD_GEN_AUDIO_TYPE_QWEN3TTS || gen_audio_type == MTMD_GEN_AUDIO_TYPE_POCKETTTS; + cap.audio_duplex = cap.audio_stream && gen_audio_type == MTMD_GEN_AUDIO_TYPE_MOSHI; // a tts model without a chat template only outputs audio, it cannot be used for chat // neither can a realtime transcription model (e.g. Voxtral Realtime): its text follows the audio by a token delay diff --git a/tools/mtmd/mtmd-helper.h b/tools/mtmd/mtmd-helper.h index 3fb75e5a30df..c20cb0a20bbd 100644 --- a/tools/mtmd/mtmd-helper.h +++ b/tools/mtmd/mtmd-helper.h @@ -260,6 +260,7 @@ struct mtmd_helper_cap { // realtime capabilities bool audio_stream; // realtime transcription, see mtmd_audio_stream_init() + bool audio_duplex; // full duplex (e.g. Hibiki): the model speaks while it listens, see the moshi pipeline of mtmd_helper_gen_audio // output capabilities bool text_gen; // false for an audio-only model (tts-only, no chat template) diff --git a/tools/mtmd/mtmd-impl.h b/tools/mtmd/mtmd-impl.h index 582b11365fef..12bc9728da53 100644 --- a/tools/mtmd/mtmd-impl.h +++ b/tools/mtmd/mtmd-impl.h @@ -614,6 +614,8 @@ enum projector_type { PROJECTOR_TYPE_QWEN3TTS_GEN, PROJECTOR_TYPE_POCKETTTS_SPKENC, PROJECTOR_TYPE_POCKETTTS_GEN, + PROJECTOR_TYPE_MOSHI, + PROJECTOR_TYPE_MOSHI_GEN, PROJECTOR_TYPE_SOPRANO, PROJECTOR_TYPE_KOKORO, PROJECTOR_TYPE_TINY_VOCA, @@ -714,6 +716,8 @@ static std::map PROJECTOR_TYPE_NAMES = { { PROJECTOR_TYPE_QWEN3TTS_GEN, "qwen3tts_gen"}, { PROJECTOR_TYPE_POCKETTTS_SPKENC, "pockettts_spkenc"}, { PROJECTOR_TYPE_POCKETTTS_GEN, "pockettts_gen"}, + { PROJECTOR_TYPE_MOSHI, "moshi"}, + { PROJECTOR_TYPE_MOSHI_GEN, "moshi_gen"}, { PROJECTOR_TYPE_SOPRANO, "soprano"}, { PROJECTOR_TYPE_KOKORO, "kokoro"}, { PROJECTOR_TYPE_TINY_VOCA, "tiny_voca"}, diff --git a/tools/mtmd/mtmd-model.cpp b/tools/mtmd/mtmd-model.cpp index e26824d0f8e1..570750b9b988 100644 --- a/tools/mtmd/mtmd-model.cpp +++ b/tools/mtmd/mtmd-model.cpp @@ -1151,6 +1151,20 @@ struct mtmd_model_loader { hparams.flow_n_step = 1; hparams.gen_eos_threshold = -4.0f; } break; + case PROJECTOR_TYPE_MOSHI: + case PROJECTOR_TYPE_MOSHI_GEN: + { + // mimi of the moshi family, see _seanet_kwargs and _transformer_kwargs of the reference + hparams.audio_sample_rate = 24000; + // seanet ratios are [8,6,5,4] in the config, the encoder reverses them + hparams.seanet_ratios = { 4, 5, 6, 8 }; + hparams.seanet_n_stage = (int32_t) hparams.seanet_ratios.size(); + hparams.mimi_downsample = 2; + hparams.mimi_tfm_context = 250; + hparams.rope_theta = 10000.0f; + // one step of the audio stream + hparams.warmup_audio_size = 4 * mtmd_graph_moshi::n_samples_per_frame; + } break; case PROJECTOR_TYPE_VOXCPM2_SPKENC: { // AudioVAE encoder, one backbone row per patch of latents (checked against the strides at load) @@ -1171,6 +1185,10 @@ struct mtmd_model_loader { hparams.wav_tfm_n_head_kv = 16; hparams.wav_tfm_eps = 1e-5f; hparams.wav_tfm_rope_theta = 10000.0f; + // drama3 shares the codec, only the backbone rows of a frame differ + std::string gen_proj; + get_string(KEY_GEN_AUDIO_PROJ_TYPE, gen_proj, false); + hparams.spkenc_drama3_rows = projector_type_from_string(gen_proj) == PROJECTOR_TYPE_DRAMA3_GEN; } break; case PROJECTOR_TYPE_CHATTERBOX: { @@ -1425,6 +1443,7 @@ struct mtmd_model_loader { model.proj_type != PROJECTOR_TYPE_MUSE_SPARK_AUDIO && model.proj_type != PROJECTOR_TYPE_VIBEVOICE_ASR && model.proj_type != PROJECTOR_TYPE_POCKETTTS_SPKENC && + model.proj_type != PROJECTOR_TYPE_MOSHI && model.proj_type != PROJECTOR_TYPE_FISH_S2_SPKENC && model.proj_type != PROJECTOR_TYPE_VOXCPM2_SPKENC; @@ -1523,6 +1542,29 @@ struct mtmd_model_loader { } }; + // mimi decoder: upsample, transformer, SEANet decoder + auto load_mimi_decoder = [&](int n_tfm_layer) { + model.gen_upsample_w = get_tensor(mtmd_format(TN_A_GEN_WAV_UPSAMPLE, "weight")); + load_seanet(model.seanet, true); + model.gen_tfm_layers.resize(n_tfm_layer); + for (int il = 0; il < n_tfm_layer; il++) { + auto & layer = model.gen_tfm_layers[il]; + const char * p = "a.gen.wav.tfm"; + layer.ln_1_w = get_tensor(mtmd_format(TN_LN_1, p, il, "weight")); + layer.ln_1_b = get_tensor(mtmd_format(TN_LN_1, p, il, "bias")); + layer.q_w = get_tensor(mtmd_format(TN_ATTN_Q, p, il, "weight")); + layer.k_w = get_tensor(mtmd_format(TN_ATTN_K, p, il, "weight")); + layer.v_w = get_tensor(mtmd_format(TN_ATTN_V, p, il, "weight")); + layer.o_w = get_tensor(mtmd_format(TN_ATTN_OUTPUT, p, il, "weight")); + layer.ls_1_w = get_tensor(mtmd_format(TN_LS_1, p, il, "weight")); + layer.ln_2_w = get_tensor(mtmd_format(TN_LN_2, p, il, "weight")); + layer.ln_2_b = get_tensor(mtmd_format(TN_LN_2, p, il, "bias")); + layer.ff_up_w = get_tensor(mtmd_format(TN_FFN_UP, p, il, "weight")); + layer.ff_down_w = get_tensor(mtmd_format(TN_FFN_DOWN, p, il, "weight")); + layer.ls_2_w = get_tensor(mtmd_format(TN_LS_2, p, il, "weight")); + } + }; + auto get_vector = [&](const std::string & name) { std::vector result; auto it = tensor_offset.find(name); @@ -2755,25 +2797,7 @@ struct mtmd_model_loader { // mimi decoder model.gen_quant_out_w = get_tensor(mtmd_format(TN_A_GEN_WAV_QUANT_OUT, "weight")); - model.gen_upsample_w = get_tensor(mtmd_format(TN_A_GEN_WAV_UPSAMPLE, "weight")); - load_seanet(model.seanet, true); - model.gen_tfm_layers.resize(hparams.n_layer); - for (int il = 0; il < hparams.n_layer; il++) { - auto & layer = model.gen_tfm_layers[il]; - const char * p = "a.gen.wav.tfm"; - layer.ln_1_w = get_tensor(mtmd_format(TN_LN_1, p, il, "weight")); - layer.ln_1_b = get_tensor(mtmd_format(TN_LN_1, p, il, "bias")); - layer.q_w = get_tensor(mtmd_format(TN_ATTN_Q, p, il, "weight")); - layer.k_w = get_tensor(mtmd_format(TN_ATTN_K, p, il, "weight")); - layer.v_w = get_tensor(mtmd_format(TN_ATTN_V, p, il, "weight")); - layer.o_w = get_tensor(mtmd_format(TN_ATTN_OUTPUT, p, il, "weight")); - layer.ls_1_w = get_tensor(mtmd_format(TN_LS_1, p, il, "weight")); - layer.ln_2_w = get_tensor(mtmd_format(TN_LN_2, p, il, "weight")); - layer.ln_2_b = get_tensor(mtmd_format(TN_LN_2, p, il, "bias")); - layer.ff_up_w = get_tensor(mtmd_format(TN_FFN_UP, p, il, "weight")); - layer.ff_down_w = get_tensor(mtmd_format(TN_FFN_DOWN, p, il, "weight")); - layer.ls_2_w = get_tensor(mtmd_format(TN_LS_2, p, il, "weight")); - } + load_mimi_decoder(hparams.n_layer); for (int64_t i = 0; i < gguf_get_n_tensors(ctx_gguf.get()); ++i) { const char * name = gguf_get_tensor_name(ctx_gguf.get(), i); @@ -2795,6 +2819,43 @@ struct mtmd_model_loader { LOG_INF("%s: %zu predefined voices\n", __func__, model.gen_voices.size()); } } break; + case PROJECTOR_TYPE_MOSHI: + { + // streaming mimi encoder, its RVQ, then the backbone embeddings of the input codes + load_seanet(model.seanet, false); + model.downsample_w = get_tensor(mtmd_format(TN_A_DOWNSAMPLE_CONV, "weight")); + auto & c2w = model.c2w; + c2w.quant_first_in_w = get_tensor(mtmd_format(TN_A_CODEC_VQ_FIRST_IN, "weight")); + c2w.quant_first_cb_w = get_tensor(mtmd_format(TN_A_CODEC_VQ_FIRST_CB, "weight")); + c2w.quant_rest_in_w = get_tensor(mtmd_format(TN_A_CODEC_VQ_REST_IN, "weight")); + c2w.quant_rest_cb_w = get_tensor(mtmd_format(TN_A_CODEC_VQ_REST_CB, "weight")); + model.mm_a_code_embd = get_tensor(mtmd_format(TN_MM_A_CODE_EMBD, "weight")); + if (model.mm_a_code_embd->ne[2] != c2w.quant_rest_cb_w->ne[2] + 1) { + throw std::runtime_error(mtmd_format("%s: the input code embeddings do not match the codebooks\n", __func__)); + } + } break; + case PROJECTOR_TYPE_MOSHI_GEN: + { + // depformer, the generic loop above loaded the a.gen.code.blk.* tensors (per-step weights on dim 2) + model.gen_code_proj_in_w = get_tensor(mtmd_format(TN_A_GEN_CODE_PROJ_IN, "weight")); + model.gen_code_tok_embd_w = get_tensor(mtmd_format(TN_A_GEN_CODE_TOK_EMBD, "weight")); + model.gen_code_embd_w = get_tensor(mtmd_format(TN_A_GEN_CODE_EMBD, "weight")); + model.gen_code_head_w = get_tensor(mtmd_format(TN_A_GEN_CODE_HEAD, "weight")); + model.gen_code_out_embd_w = get_tensor(mtmd_format(TN_A_GEN_CODE_OUT_EMBD, "weight")); + const int64_t n_q = model.gen_code_head_w->ne[2]; + if (model.gen_code_embd_w->ne[2] != n_q - 1 || model.gen_code_out_embd_w->ne[2] != n_q || + model.gen_code_proj_in_w->ne[2] > n_q || (int64_t) n_q > mtmd_graph_moshi_gen::n_q_max) { + throw std::runtime_error(mtmd_format("%s: invalid depformer tensors\n", __func__)); + } + + // RVQ decode, then the mimi decoder + auto & c2w = model.c2w; + c2w.quant_first_out_w = get_tensor(mtmd_format(TN_A_GEN_WAV_QUANT_FIRST_OUT, "weight")); + c2w.quant_first_cb_w = get_tensor(mtmd_format(TN_A_GEN_WAV_QUANT_FIRST_CB, "weight")); + c2w.quant_rest_out_w = get_tensor(mtmd_format(TN_A_GEN_WAV_QUANT_REST_OUT, "weight")); + c2w.quant_rest_cb_w = get_tensor(mtmd_format(TN_A_GEN_WAV_QUANT_REST_CB, "weight")); + load_mimi_decoder(mtmd_graph_moshi_gen::mimi_n_layer); + } break; case PROJECTOR_TYPE_LFM3A_GEN: { // must match the "tts" chat template, see conversion/lfm3.py @@ -5019,6 +5080,16 @@ int mtmd_model::n_output_tokens(const mtmd_image_f32 * img) const { // one latent per call for GEN_CODE, GEN_WAV sizes its input from the caller n_patches = 1; } break; + case PROJECTOR_TYPE_MOSHI: + { + // one row per codebook and frame, then the rows of the initial codes, see mtmd_graph_moshi + const int n_q = (int) mm_a_code_embd->ne[2]; + n_patches = n_q * (img->nx() / mtmd_graph_moshi::n_samples_per_frame + 1); + } break; + case PROJECTOR_TYPE_MOSHI_GEN: + { + n_patches = 1; + } break; case PROJECTOR_TYPE_GRANITE4_VISION: { // Per-tile output token count: each projector block outputs @@ -5210,6 +5281,10 @@ int mtmd_model::n_mmproj_embd() const { return spk_proj_w->ne[1]; case PROJECTOR_TYPE_POCKETTTS_GEN: return gen_input_lin_w->ne[1]; + case PROJECTOR_TYPE_MOSHI: + return mm_a_code_embd->ne[0]; + case PROJECTOR_TYPE_MOSHI_GEN: + return gen_code_out_embd_w->ne[0]; case PROJECTOR_TYPE_CHATTERBOX: // talker width, carried by the speech table return cbx_tensors.at("a.gen.code.out_embd.weight")->ne[0]; diff --git a/tools/mtmd/mtmd-model.h b/tools/mtmd/mtmd-model.h index 893578b03b1e..10c3154e8b03 100644 --- a/tools/mtmd/mtmd-model.h +++ b/tools/mtmd/mtmd-model.h @@ -239,6 +239,9 @@ struct mtmd_hparams { int32_t wav_tfm_swa = 0; // pre_transformer's KV cache size, in frames int32_t wav_frame_stack = 0; // lfm3a codec: decoder positions per frame + // fish_s2_spkenc in a drama3_gen mmproj: backbone rows as drama3_gen builds them + bool spkenc_drama3_rows = false; + // mimo-v2.5: LLM-side connector (input_local_transformer) int32_t audio_local_n_layer = 0; int32_t audio_local_group_size = 0; diff --git a/tools/mtmd/mtmd-subcontext.cpp b/tools/mtmd/mtmd-subcontext.cpp index f754a913bbfc..078f154c7939 100644 --- a/tools/mtmd/mtmd-subcontext.cpp +++ b/tools/mtmd/mtmd-subcontext.cpp @@ -392,6 +392,7 @@ static std::vector list_gen_state_slots(const mtmd_hparams & hpa case PROJECTOR_TYPE_FISH_S2_GEN: return list_c2w_state_slots(hparams, model); case PROJECTOR_TYPE_DRAMA3_GEN: return list_drama3_state_slots(hparams, model); case PROJECTOR_TYPE_POCKETTTS_GEN: return list_pockettts_state_slots(hparams, model); + case PROJECTOR_TYPE_MOSHI_GEN: return list_pockettts_state_slots(hparams, model); case PROJECTOR_TYPE_LFM3A_GEN: return list_lfm3a_gen_state_slots(hparams, model); case PROJECTOR_TYPE_ZONOS3_GEN: return list_zonos3_gen_state_slots(hparams, model); case PROJECTOR_TYPE_VOXCPM2_GEN: return list_voxcpm2_state_slots(hparams, model); @@ -405,6 +406,7 @@ static std::vector list_enc_state_slots(const mtmd_hparams & hpa case PROJECTOR_TYPE_LFM3A: return list_lfm3a_state_slots(hparams, model); case PROJECTOR_TYPE_GEMMA4A: return list_gemma4a_state_slots(hparams, model); case PROJECTOR_TYPE_VIBEVOICE_ASR: return list_vibevoice_asr_state_slots(hparams, model); + case PROJECTOR_TYPE_MOSHI: return list_moshi_state_slots(hparams, model); default: return {}; } } @@ -454,7 +456,8 @@ mtmd_subctx_gen_state * mtmd_subcontext::gen_state_init(uint32_t seed) { mtmd_subctx_enc_state * mtmd_subcontext::enc_state_init(int32_t n_frames_max) { const auto & hparams = model.hparams; - if (model.proj_type == PROJECTOR_TYPE_LFM3A || model.proj_type == PROJECTOR_TYPE_GEMMA4A || model.proj_type == PROJECTOR_TYPE_VIBEVOICE_ASR) { + if (model.proj_type == PROJECTOR_TYPE_LFM3A || model.proj_type == PROJECTOR_TYPE_GEMMA4A || model.proj_type == PROJECTOR_TYPE_VIBEVOICE_ASR || + model.proj_type == PROJECTOR_TYPE_MOSHI) { // see list_enc_state_slots() const auto slots = list_enc_state_slots(hparams, model); auto st = std::make_unique(); @@ -2008,12 +2011,16 @@ bool mtmd_subcontext::encode(mtmd_subctx_encode_params * params) { } else { // code0 < 0: next row is text (prompt), the tower only fills its KV // codes: input frame codes for a speech row, empty for a text row + // then optionally the codes of the next frame (reference rows): teacher forcing, code0 must be its code 0 const bool next_speech = params->code0 >= 0; - const bool cur_speech = params->codes && (int64_t) params->codes->size() == n_cb; - if (params->code0 >= n_vocab) { - LOG_ERR("%s: code0 out of range (%d, vocab %lld)\n", __func__, params->code0, (long long) n_vocab); + const size_t n_given = params->codes ? params->codes->size() : 0; + const bool forced = n_given == (size_t) (2 * n_cb); + if (params->code0 >= n_vocab || (n_given != 0 && n_given != (size_t) n_cb && !forced) || + (forced && params->code0 != (*params->codes)[n_cb])) { + LOG_ERR("%s: invalid tower input (code0 %d, %zu codes)\n", __func__, params->code0, n_given); return false; } + const bool cur_speech = n_given != 0 && (*params->codes)[0] >= 0; std::vector code0 = { std::max(params->code0, 0) }; set_input_i32("inp_code0", code0); @@ -2030,12 +2037,20 @@ bool mtmd_subcontext::encode(mtmd_subctx_encode_params * params) { std::vector inp_pos = { (int32_t) pos }; set_input_i32("inp_pos", inp_pos); - std::uniform_real_distribution dist(0.0f, 1.0f); - std::vector r(model.gen_code_head_w->ne[2]); - for (auto & v : r) { - v = dist(params->gen_state->rng); + if (forced) { + std::vector force(model.gen_code_head_w->ne[2]); + for (size_t ih = 0; ih < force.size(); ih++) { + force[ih] = std::clamp((*params->codes)[n_cb + 1 + ih], 0, (int32_t) n_vocab - 1); + } + set_input_i32("inp_force", force); + } else { + std::uniform_real_distribution dist(0.0f, 1.0f); + std::vector r(model.gen_code_head_w->ne[2]); + for (auto & v : r) { + v = dist(params->gen_state->rng); + } + set_input_f32("inp_rand", r); } - set_input_f32("inp_rand", r); } } break; case PROJECTOR_TYPE_QWEN3TTS_GEN: @@ -2317,6 +2332,61 @@ bool mtmd_subcontext::encode(mtmd_subctx_encode_params * params) { } set_input_f32("pos_emb", pos_emb); } break; + case PROJECTOR_TYPE_MOSHI: + { + // positions and masks are derived in-graph from the "pos" slot + set_enc_state_in(); + } break; + case PROJECTOR_TYPE_MOSHI_GEN: + { + const int64_t n_q = model.gen_code_head_w->ne[2]; + if (params->gen_process == MTMD_SUBCTX_GEN_PROCESS_GEN_WAV) { + GGML_ASSERT(params->codes != nullptr); + // frame-major to codebook-major + const auto & in = *params->codes; + const int64_t n_frames = (int64_t) in.size() / n_q; + const int64_t n_codes = model.c2w.quant_first_cb_w->ne[1]; + std::vector codes(in.size()); + for (int64_t f = 0; f < n_frames; f++) { + for (int64_t k = 0; k < n_q; k++) { + const int32_t c = in[(size_t) (f * n_q + k)]; + if (c < 0 || c >= n_codes) { + LOG_ERR("%s: code out of range (%d, codebook size %lld)\n", __func__, c, (long long) n_codes); + return false; + } + codes[(size_t) (k * n_frames + f)] = c; + } + } + set_input_i32("inp_codes", codes); + set_gen_state_in(); + } else if (params->codes != nullptr) { + std::vector codes = *params->codes; + const int64_t n_rows = model.gen_code_out_embd_w->ne[1]; + for (int32_t c : codes) { + if (c < 0 || c >= n_rows) { + LOG_ERR("%s: code out of range (%d)\n", __func__, c); + return false; + } + } + set_input_i32("inp_codes", codes); + } else { + std::vector code0 = { params->code0 }; + if (code0[0] < 0 || code0[0] >= model.gen_code_tok_embd_w->ne[1]) { + LOG_ERR("%s: text token out of range (%d)\n", __func__, code0[0]); + return false; + } + set_input_i32("inp_code0", code0); + // greedy has no random input + if (ggml_graph_get_tensor(gf, "inp_rand") != nullptr) { + std::uniform_real_distribution dist(0.0f, 1.0f); + std::vector r(n_q); + for (auto & v : r) { + v = dist(params->gen_state->rng); + } + set_input_f32("inp_rand", r); + } + } + } break; case PROJECTOR_TYPE_LFM3A: { GGML_ASSERT(imgs.entries.size() == 1); @@ -2596,10 +2666,8 @@ bool mtmd_subcontext::encode(mtmd_subctx_encode_params * params) { // for audio gen models // - if (model.proj_type == PROJECTOR_TYPE_QWEN3TTS_GEN && params->gen_process == MTMD_SUBCTX_GEN_PROCESS_TOKENIZE) { - GGML_ASSERT(params->out_codes && params->out_code_embd); - - // frame-major codes, the layout of GEN_WAV's input + // reference clip codes, one out_ref_code_ tensor per codebook, read back frame-major (the layout of GEN_WAV's input) + auto read_ref_codes = [&gf](std::vector & out) -> size_t { std::vector> groups; for (int g = 0; ; g++) { ggml_tensor * t = ggml_graph_get_tensor(gf, ("out_ref_code_" + std::to_string(g)).c_str()); @@ -2611,12 +2679,23 @@ bool mtmd_subcontext::encode(mtmd_subctx_encode_params * params) { } GGML_ASSERT(!groups.empty()); const size_t n_frames = groups[0].size(); - params->out_codes->resize(n_frames * groups.size()); + out.resize(n_frames * groups.size()); for (size_t f = 0; f < n_frames; f++) { for (size_t g = 0; g < groups.size(); g++) { - (*params->out_codes)[f * groups.size() + g] = groups[g][f]; + out[f * groups.size() + g] = groups[g][f]; } } + return n_frames; + }; + + if (model.proj_type == PROJECTOR_TYPE_FISH_S2_SPKENC && params->out_codes) { + read_ref_codes(*params->out_codes); + return true; + } + + if (model.proj_type == PROJECTOR_TYPE_QWEN3TTS_GEN && params->gen_process == MTMD_SUBCTX_GEN_PROCESS_TOKENIZE) { + GGML_ASSERT(params->out_codes && params->out_code_embd); + const size_t n_frames = read_ref_codes(*params->out_codes); ggml_tensor * rows = ggml_graph_get_tensor(gf, "out_ref_rows"); GGML_ASSERT(rows && rows->type == GGML_TYPE_F32 && (size_t) rows->ne[1] == n_frames); @@ -2881,7 +2960,8 @@ bool mtmd_subcontext::encode(mtmd_subctx_encode_params * params) { } } } - if (params->enc_state != nullptr && (model.proj_type == PROJECTOR_TYPE_LFM3A || model.proj_type == PROJECTOR_TYPE_GEMMA4A || model.proj_type == PROJECTOR_TYPE_VIBEVOICE_ASR)) { + if (params->enc_state != nullptr && (model.proj_type == PROJECTOR_TYPE_LFM3A || model.proj_type == PROJECTOR_TYPE_GEMMA4A || model.proj_type == PROJECTOR_TYPE_VIBEVOICE_ASR || + model.proj_type == PROJECTOR_TYPE_MOSHI)) { const auto & slots = params->enc_state->slots; size_t i = 0; for (const auto & slot : list_enc_state_slots(hparams, model)) { diff --git a/tools/mtmd/mtmd.cpp b/tools/mtmd/mtmd.cpp index 1101d267ad01..fdac762ac98c 100644 --- a/tools/mtmd/mtmd.cpp +++ b/tools/mtmd/mtmd.cpp @@ -644,6 +644,7 @@ static void mtmd_owned_llama_set_tensor_data(ggml_tensor * t, void * user_data) return name.size() >= n && name.compare(name.size() - n, n, suffix) == 0; }; const bool optional = ends_with("scale") || ends_with(".bias") || name == "dense_2.weight" || + name == "cls.output.weight" || // Qwen3 reranking head, unused by YuE2 NAR name == "rope_freqs.weight" || // granite, voxcpm2 residual LM name == "token_embd.weight" || name == "output.weight"; // inputs are embedding rows, outputs are hidden states if (!optional || t->type != GGML_TYPE_F32) { @@ -1469,6 +1470,7 @@ struct mtmd_context { audio_preproc = std::make_unique(models.a.get()); } break; case PROJECTOR_TYPE_VOXTRAL_RT: + case PROJECTOR_TYPE_MOSHI: { // audio and text share positions, only usable via mtmd_audio_stream } break; @@ -2616,8 +2618,9 @@ static int32_t mtmd_encode_impl(mtmd_context * ctx, const mtmd_image_tokens * im static int32_t cbx_ref_encode(mtmd_context * ctx, const mtmd_audio_tokens * audio_tokens, std::vector & out_embd); static int32_t voxcpm2_ref_encode(mtmd_context * ctx, const mtmd_audio_tokens * audio_tokens, std::vector & out_embd); -static bool mtmd_audio_batch_encode(mtmd_context * ctx, const mtmd_image_f32_batch & batch_f32, mtmd_audio_preproc_out * source, uint32_t idx, std::vector & out_embd) { - mtmd_image_f32_batch batch = batch_f32.clone(); +// copy of batch_f32, the mel is computed from source when there is one +static bool mtmd_audio_batch_prepare(mtmd_context * ctx, const mtmd_image_f32_batch & batch_f32, mtmd_audio_preproc_out * source, uint32_t idx, mtmd_image_f32_batch & batch) { + batch = batch_f32.clone(); if (source) { if (!ctx->audio_preproc->compute(*source)) { LOG_ERR("%s: unable to compute the mel\n", __func__); @@ -2626,7 +2629,38 @@ static bool mtmd_audio_batch_encode(mtmd_context * ctx, const mtmd_image_f32_bat GGML_ASSERT(idx < source->entries.size()); batch.entries[0] = source->entries[idx]; } - return ctx->ctx_a->encode_batch(ctx->n_threads, &batch, out_embd); + return true; +} + +static bool mtmd_audio_batch_encode(mtmd_context * ctx, const mtmd_image_f32_batch & batch_f32, mtmd_audio_preproc_out * source, uint32_t idx, std::vector & out_embd) { + mtmd_image_f32_batch batch; + return mtmd_audio_batch_prepare(ctx, batch_f32, source, idx, batch) && ctx->ctx_a->encode_batch(ctx->n_threads, &batch, out_embd); +} + +// fish_s2_spkenc: one backbone row per reference frame, the codes go to ctx->gen_ref, see mtmd_gen_state_set_ref() +static int32_t mtmd_fish_s2_ref_encode(mtmd_context * ctx, const mtmd_audio_tokens * audio_tokens, std::vector & out_embd) { + mtmd_image_f32_batch batch; + if (!mtmd_audio_batch_prepare(ctx, audio_tokens->batch_f32, audio_tokens->source.get(), audio_tokens->source_idx, batch)) { + return 1; + } + std::vector codes; + out_embd.resize((size_t) audio_tokens->n_tokens * ctx->n_embd_out()); + + mtmd_subctx_encode_params params; + params.imgs = &batch; + params.n_threads = ctx->n_threads; + params.out_embd = &out_embd; + params.out_codes = &codes; + if (!ctx->ctx_a->encode(¶ms)) { + return 1; + } + const size_t n_cb = ctx->ctx_a->model.gen_code_embd_w->ne[2]; + if (codes.size() != (size_t) audio_tokens->n_tokens * n_cb) { + LOG_ERR("%s: %zu reference codes for %u frames\n", __func__, codes.size(), audio_tokens->n_tokens); + return 1; + } + ctx->gen_ref.tokens = std::move(codes); + return 0; } // qwen3tts: the speaker row, then one talker input row per reference frame @@ -2731,6 +2765,9 @@ static int32_t mtmd_encode_chunk_impl(mtmd_context * ctx, const mtmd_input_chunk if (ctx->ctx_a->model.proj_type == PROJECTOR_TYPE_VOXCPM2_SPKENC) { return voxcpm2_ref_encode(ctx, chunk->tokens_audio.get(), out_embd); } + if (ctx->ctx_a->model.proj_type == PROJECTOR_TYPE_FISH_S2_SPKENC) { + return mtmd_fish_s2_ref_encode(ctx, chunk->tokens_audio.get(), out_embd); + } if (ctx->ctx_a->model.proj_type == PROJECTOR_TYPE_QWEN3TTS_SPKENC && chunk->tokens_audio->batch_f32.entries.size() == 2) { return mtmd_qwen3tts_ref_encode(ctx, chunk->tokens_audio.get(), out_embd); } @@ -2791,6 +2828,10 @@ mtmd_gen_audio_info mtmd_gen_audio_get_info(const mtmd_context * ctx) { info.type = MTMD_GEN_AUDIO_TYPE_POCKETTTS; info.sample_rate = 24000; break; + case PROJECTOR_TYPE_MOSHI_GEN: + info.type = MTMD_GEN_AUDIO_TYPE_MOSHI; + info.sample_rate = 24000; + break; case PROJECTOR_TYPE_SOPRANO: info.type = MTMD_GEN_AUDIO_TYPE_SOPRANO; info.sample_rate = 32000; @@ -3308,6 +3349,12 @@ mtmd_gen_inp mtmd_gen_inp_default(const mtmd_context * ctx) { case PROJECTOR_TYPE_TINY_VOCA: inp.type = MTMD_GEN_PROCESS_TYPE_GEN_WAV; break; + case PROJECTOR_TYPE_MOSHI_GEN: + // lm_gen_config of the checkpoint (audio codes), the text token is sampled by the caller + inp.top_k = 250; + inp.top_p = 1.0f; + inp.temp = 0.8f; + break; case PROJECTOR_TYPE_VOXCPM2_GEN: // UnifiedCFM.forward(): unit gaussian noise, see VoxCPM2Model._inference() for the steps and the guidance inp.temp = 1.0f; @@ -4213,6 +4260,13 @@ int32_t mtmd_gen_state_set_ref(mtmd_context * ctx, mtmd_gen_state * state) { return 0; } +const int32_t * mtmd_gen_state_get_ref_codes(const mtmd_gen_state * state, size_t * n_codes) { + if (n_codes) { + *n_codes = state ? state->ref.tokens.size() : 0; + } + return state && !state->ref.tokens.empty() ? state->ref.tokens.data() : nullptr; +} + static int32_t mtmd_gen_audio_process_impl(mtmd_context * ctx, mtmd_gen_state * state, const mtmd_gen_inp * inp, mtmd_gen_out * out) { mtmd_subcontext * sctx = ctx->ctx_gen_a.get(); if (!sctx) { @@ -5442,6 +5496,36 @@ struct mtmd_audio_stream_lfm3a : mtmd_audio_stream { int32_t step_live(llama_token last_token); }; +// Moshi family (e.g. Hibiki): full duplex, one row per 80 ms frame of input audio +// row = embeddings of the input codes (the acoustic ones lag by acoustic_delay frames) + the text token sampled from the previous row +// the codes the model generates are added by the caller, see the moshi pipeline of mtmd_helper_gen_audio +struct mtmd_audio_stream_moshi : mtmd_audio_stream { + static constexpr int acoustic_delay = 2; + static constexpr int n_frames_max = 4; // frames per encoder call + + mtmd_subctx_enc_state * enc_state = nullptr; + + int n_q = 0; + llama_token tok_text_start = LLAMA_TOKEN_NULL; + + std::vector codes_embd; // n_q rows per encoded frame, from frame codes_off + int64_t codes_off = 0; + int64_t n_frames_enc = 0; + std::vector init_embd; // n_q rows of the initial codes + std::vector tok_embd; + + ~mtmd_audio_stream_moshi() override { + delete enc_state; + } + + bool init(const mtmd_audio_stream_params & params) override; + int32_t flush(bool end) override; + int32_t step(llama_token last_token) override; + + bool encode(); + const float * code_row(int64_t frame, int k) const; +}; + // Gemma 4: the encoder is causal struct mtmd_audio_stream_gemma4a : mtmd_audio_stream { mtmd_subctx_enc_state * enc_state = nullptr; @@ -5521,7 +5605,7 @@ bool mtmd_support_audio_stream(const mtmd_context * ctx) { } const projector_type proj = ctx->ctx_a->model.proj_type; return proj == PROJECTOR_TYPE_VOXTRAL_RT || proj == PROJECTOR_TYPE_LFM3A || proj == PROJECTOR_TYPE_GEMMA4A || - proj == PROJECTOR_TYPE_HIGGS_AUDIO || proj == PROJECTOR_TYPE_VIBEVOICE_ASR; + proj == PROJECTOR_TYPE_HIGGS_AUDIO || proj == PROJECTOR_TYPE_VIBEVOICE_ASR || proj == PROJECTOR_TYPE_MOSHI; } mtmd_audio_stream_params mtmd_audio_stream_params_default(void) { @@ -5546,6 +5630,7 @@ mtmd_audio_stream * mtmd_audio_stream_init(mtmd_context * ctx, mtmd_audio_stream case PROJECTOR_TYPE_GEMMA4A: s = std::make_unique(); break; case PROJECTOR_TYPE_HIGGS_AUDIO: s = std::make_unique(); break; case PROJECTOR_TYPE_VIBEVOICE_ASR: s = std::make_unique(); break; + case PROJECTOR_TYPE_MOSHI: s = std::make_unique(); break; default: GGML_ABORT("unsupported projector"); } s->ctx = ctx; @@ -6495,3 +6580,120 @@ int64_t mtmd_audio_stream_get_n_rows(const mtmd_audio_stream * s) { int64_t mtmd_audio_stream_get_n_rows_flushed(const mtmd_audio_stream * s) { return s->n_rows_flushed; } + +// +// Moshi +// + +bool mtmd_audio_stream_moshi::init(const mtmd_audio_stream_params & params) { + if (params.n_prompt > 0) { + LOG_ERR("%s: moshi takes no prompt\n", __func__); + return false; + } + n_q = (int) sctx->model.mm_a_code_embd->ne[2]; + samples_per_tok = mtmd_graph_moshi::n_samples_per_frame; + + const std::string name = "<|text_start|>"; + std::vector toks(4); + if (llama_tokenize(ctx->vocab, name.c_str(), (int32_t) name.size(), toks.data(), (int32_t) toks.size(), false, true) != 1) { + LOG_ERR("%s: cannot find the %s token\n", __func__, name.c_str()); + return false; + } + tok_text_start = toks[0]; + + enc_state = sctx->enc_state_init(0); + return enc_state != nullptr; +} + +int32_t mtmd_audio_stream_moshi::flush(bool end) { + // pad to a whole frame + const int64_t n_align = (samples_per_tok - n_samples % samples_per_tok) % samples_per_tok; + add_silence(n_align); + n_rows_flushed = n_samples / samples_per_tok; + ended = end; + return 0; +} + +// encodes the whole frames of buf, n_frames_max per call +bool mtmd_audio_stream_moshi::encode() { + while (true) { + const int64_t n = std::min((int64_t) buf.size() / samples_per_tok, n_frames_max); + if (n <= 0) { + return true; + } + const size_t n_in = (size_t) (n * samples_per_tok); + + mtmd_image_f32 img; + img.set_size({(int) n_in, 1}, false, /* is_audio */ true); + img.cpy_buf(std::vector(buf.begin(), buf.begin() + n_in)); + mtmd_image_f32_batch batch; + batch.is_audio = true; + batch.entries.push_back(std::move(img)); + + std::vector res((size_t) n_embd * n_q * (n + 1)); + mtmd_subctx_encode_params params; + params.n_threads = ctx->n_threads; + params.imgs = &batch; + params.out_embd = &res; + params.enc_state = enc_state; + if (!sctx->encode(¶ms)) { + LOG_ERR("%s: failed to encode audio\n", __func__); + return false; + } + const size_t n_codes = (size_t) n_embd * n_q * n; + codes_embd.insert(codes_embd.end(), res.begin(), res.begin() + n_codes); + init_embd.assign(res.begin() + n_codes, res.end()); + n_frames_enc += n; + + buf.erase(buf.begin(), buf.begin() + n_in); + buf_pos += (int64_t) n_in; + } +} + +const float * mtmd_audio_stream_moshi::code_row(int64_t frame, int k) const { + return codes_embd.data() + ((size_t) (frame - codes_off) * n_q + k) * n_embd; +} + +int32_t mtmd_audio_stream_moshi::step(llama_token last_token) { + n_rows_done = n_rows; + out.clear(); + + if (!encode()) { + return -2; + } + // row p goes with frame p + if (n_rows >= n_frames_enc) { + return ended ? -1 : 0; + } + const int64_t p = n_rows; + + // the text of the previous row, see _get_initial_token() of the reference + const llama_token tok = p == 0 ? tok_text_start : last_token; + if (tok == LLAMA_TOKEN_NULL) { + LOG_ERR("%s: the token sampled from the previous row is required\n", __func__); + return -2; + } + tok_embd.resize(n_embd); + if (llama_model_get_tok_embd_rows(ctx->text_model, &tok, 1, tok_embd.data()) == 0) { + return -2; + } + + // the semantic code has no delay; a stream starts with initial codes, the first frame is never seen, like the reference + out = tok_embd; + for (int k = 0; k < n_q; k++) { + const int64_t delay = k == 0 ? 0 : acoustic_delay; + const float * row = p <= delay ? init_embd.data() + (size_t) k * n_embd : code_row(p - delay, k); + for (int i = 0; i < n_embd; i++) { + out[i] += row[i]; + } + } + n_rows++; + + // drop the frames no row will need again + const int64_t keep_from = std::max(0, n_rows - acoustic_delay); + if (keep_from - codes_off >= 64) { + codes_embd.erase(codes_embd.begin(), codes_embd.begin() + (size_t) (keep_from - codes_off) * n_q * n_embd); + codes_off = keep_from; + } + return 1; +} diff --git a/tools/mtmd/mtmd.h b/tools/mtmd/mtmd.h index 49fc8136e3bf..09cae0ad836b 100644 --- a/tools/mtmd/mtmd.h +++ b/tools/mtmd/mtmd.h @@ -478,6 +478,7 @@ enum mtmd_gen_audio_type { MTMD_GEN_AUDIO_TYPE_YUE2, MTMD_GEN_AUDIO_TYPE_MINIMAX_MUSIC3, MTMD_GEN_AUDIO_TYPE_FISH_S2, + MTMD_GEN_AUDIO_TYPE_MOSHI, MTMD_GEN_AUDIO_TYPE_KOKORO, MTMD_GEN_AUDIO_TYPE_TINY_VOCA, MTMD_GEN_AUDIO_TYPE_VOXCPM2, @@ -534,6 +535,7 @@ struct mtmd_gen_inp { // for MTMD_GEN_PROCESS_TYPE_GEN_WAV // pass either codes (discrete) or feats (continuous), depending on the pipeline // lfm3a GEN_CODE also takes codes: the codes revealed so far, -1 for a masked codebook + // moshi GEN_CODE: code0 is the sampled text token; with codes (all of the frame), only their backbone embedding is built // zonos3 GEN_WAV: -1 for a residual code not known yet, the frame is decoded without it // kokoro GEN_WAV takes both: codes are the phoneme tokens, feats is the voice row (256 values) then the backbone state of each token int32_t * codes; @@ -593,6 +595,10 @@ MTMD_API void mtmd_gen_state_reset(mtmd_gen_state * state); // returns non-zero if the last encode produced no such data MTMD_API int32_t mtmd_gen_state_set_ref(mtmd_context * ctx, mtmd_gen_state * state); +// codes of the reference held by the state (frame-major, e.g. drama3: 10 per frame), NULL if it has none +// valid until the next mtmd_gen_state_set_ref() / mtmd_gen_state_free() on this state +MTMD_API const int32_t * mtmd_gen_state_get_ref_codes(const mtmd_gen_state * state, size_t * n_codes); + // defaults tuned for the loaded pipeline, callers override only what they care about MTMD_API struct mtmd_gen_inp mtmd_gen_inp_default(const mtmd_context * ctx); diff --git a/tools/server/README.md b/tools/server/README.md index 278518dce75c..b0168b6d14dc 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -202,7 +202,8 @@ For the full list of features, please refer to [server's changelog](https://gith | `--api-prefix PREFIX` | prefix path the server serves from, without the trailing slash (default: )
(env: LLAMA_ARG_API_PREFIX) | | `--ui-config, --webui-config JSON` | JSON that provides default UI settings (overrides UI defaults)
(env: LLAMA_ARG_UI_CONFIG) | | `--ui-config-file, --webui-config-file PATH` | JSON file that provides default UI settings (overrides UI defaults)
(env: LLAMA_ARG_UI_CONFIG_FILE) | -| `--ui-mcp-proxy, --webui-mcp-proxy, --no-ui-mcp-proxy, --no-webui-mcp-proxy` | experimental: whether to enable MCP CORS proxy, for Llama Chat to reach public MCP servers without CORS headers; local and private addresses are refused - do not enable in untrusted environments (default: disabled)
note: for security reasons, this will limit --cors-origins to localhost by default
(env: LLAMA_ARG_UI_MCP_PROXY) | +| `--ui-mcp-proxy, --webui-mcp-proxy, --no-ui-mcp-proxy, --no-webui-mcp-proxy` | experimental: whether to enable MCP CORS proxy, for Llama Chat to reach public MCP servers without CORS headers; local and private addresses are refused unless --ui-mcp-proxy-allow-private-urls is set - do not enable in untrusted environments (default: disabled)
note: for security reasons, this will limit --cors-origins to localhost by default
(env: LLAMA_ARG_UI_MCP_PROXY) | +| `--ui-mcp-proxy-allow-private-urls` | allow the MCP CORS proxy to reach local or private addresses (e.g. MCP servers on localhost or LAN) - anyone who can reach the proxy can then reach your local network (default: disabled, only public addresses)
note: only has effect with --ui-mcp-proxy
(env: LLAMA_ARG_UI_MCP_PROXY_ALLOW_PRIVATE_URLS) | | `--tools TOOL1,TOOL2,...` | experimental: whether to enable built-in tools for AI agents - do not enable in untrusted environments (default: no tools)
specify "all" to enable all tools
available tools: read_file, file_glob_search, grep_search, exec_shell_command, write_file, edit_file, get_info
note: for security reasons, this will limit --cors-origins to localhost by default
(env: LLAMA_ARG_TOOLS) | | `--tools-runtime OPTION` | experimental: run tools in a separate runtime environment (default: none, use host environment)
available options:
'docker:', 'podman:': spin up a new container and reuse it for all invocations, clean up on server exit
'docker-container:', 'podman-container:': use an existing container by ID, won't stop on server exit
'ssh:': run tools on a remote POSIX host over SSH, key-based auth and a trusted host key are required

(env: LLAMA_ARG_TOOLS_RUNTIME) | | `--allow-unauthenticated-tools` | allow server tools, MCP servers or MCP proxy on a non-loopback address without an API key - only for trusted networks (default: disabled)
(env: LLAMA_ARG_ALLOW_UNAUTHENTICATED_TOOLS) | @@ -393,7 +394,7 @@ Every server is spawned once at startup to list its tools, then stopped, and res The child process runs with the same privileges as the server, so only declare commands you trust. As with `--tools`, `--cors-origins` then defaults to `localhost`. -Note: `--ui-mcp-proxy` is unrelated, it only lets Llama Chat reach public MCP servers that do not send CORS headers. It refuses local and private addresses (loopback, LAN, link-local); connect to those from Llama Chat directly. +Note: `--ui-mcp-proxy` is unrelated, it only lets Llama Chat reach public MCP servers that do not send CORS headers. By default it refuses local and private addresses (loopback, LAN, link-local); either connect to those from Llama Chat directly (the MCP server must send CORS headers), or add `--ui-mcp-proxy-allow-private-urls`. Any server written against the [MCP specification](https://modelcontextprotocol.io) works as is, whether it uses an official SDK or not: the transport is one JSON-RPC message per line on stdio, so a script wrapping an existing program is a valid server too. @@ -1666,6 +1667,12 @@ LFM3-Omni is not trained to reason, run it with `--reasoning off` so that its tu Tools go into the system prompt with the chat template, and the tool calls are parsed as in `/v1/chat/completions`. The client runs the calls of a response, sends their results as `function_call_output` items, then asks for the next response. +#### Full duplex + +Full duplex models, like Hibiki (French to English speech translation), speak while they listen on the same endpoint. There are no turns: the first `input_audio_buffer.append` opens a response, then every 80 ms of input audio gives 80 ms of output audio (`response.output_audio.delta`) and the text of the translation (`response.output_text.delta`). `response.cancel` ends the response with `response.done`, the next audio opens another one. Audio input and output are PCM16 mono, as for a realtime conversation. + +The model attends to the last 120 s of the stream, so the context of each slot only needs to hold that window (1500 frames for Hibiki, `-c` divided by `-np`). The model is trained on streams no longer than its window, so once the window is full the first frames of the stream stay in context and the oldest frames after them are dropped, 20 s at a time. This keeps Hibiki-1B going on long streams; Hibiki-2B still degrades after about 2 minutes, as the reference implementation does, cancel the response between long segments of speech. `input_audio_buffer.commit`, `conversation.item.create` and `response.create` are rejected. The text and the audio are sampled with the settings of the model, the text settings can be overridden with the server sampling options. + ### POST `/v1/audio/speech`: OpenAI-compatible Speech API Generates speech from text, for models that can generate audio. The request is converted to a [`/tts`](#post-tts-generate-speech-audio-from-text) request, so the `/tts` options such as `lang`, `seed` or `speaker_ref_b64` can also be used. diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp index eb5781e740d7..8d4c022e975d 100644 --- a/tools/server/server-common.cpp +++ b/tools/server/server-common.cpp @@ -1641,13 +1641,18 @@ json oaicompat_chat_params_parse( // Parse the OAI "reasoning_effort" field; "none" disables reasoning. if (body.contains("reasoning_effort")) { auto reasoning_effort = json_value(body, "reasoning_effort", std::string("")); + const auto levels = caps.at("reasoning_effort_levels").get>(); if (reasoning_effort == "none") { inputs.enable_thinking = false; - inputs.chat_template_kwargs.erase("reasoning_effort"); + // Some models use reasoning_effort = none and some throw an exception, so check the model's list of effort levels first + if (std::find(levels.begin(), levels.end(), reasoning_effort) != levels.end()) { + inputs.chat_template_kwargs["reasoning_effort"] = json(reasoning_effort).dump(); + } else { + inputs.chat_template_kwargs.erase("reasoning_effort"); + } } else if (!reasoning_effort.empty()) { const auto rejected = caps.at("reasoning_effort_rejected").get>(); if (std::find(rejected.begin(), rejected.end(), reasoning_effort) != rejected.end()) { - const auto levels = caps.at("reasoning_effort_levels").get>(); throw std::invalid_argument("reasoning_effort \"" + reasoning_effort + "\" is not supported by the chat template, supported levels: " + string_join(levels, ", ")); } inputs.chat_template_kwargs["reasoning_effort"] = json(reasoning_effort).dump(); diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 99c038ebf279..4f2a950dfece 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -353,6 +353,8 @@ struct server_slot { return false; } + const int64_t t_start = ggml_time_us(); + const size_t cur_size_tgt = llama_state_seq_get_size_ext(ctx_tgt, id, LLAMA_STATE_SEQ_FLAGS_NONE); const size_t cur_size_dft = ctx_dft ? llama_state_seq_get_size_ext(ctx_dft, id, LLAMA_STATE_SEQ_FLAGS_NONE) : 0; @@ -374,6 +376,8 @@ struct server_slot { return false; } + SLT_TRC(*this, "prompt cache save took %.2f ms\n", (ggml_time_us() - t_start) / 1000.0); + return true; } @@ -4322,7 +4326,9 @@ struct server_context_impl { if (!slot.can_split()) { // cannot fit the prompt in the current batch - will try next iter - if (batch.size() + slot.task->n_tokens() > n_batch) { + // with non-causal attention the whole batch must fit in one ubatch, see llama_decode + const int32_t n_batch_max = llama_get_causal_attn(ctx_tgt) ? n_batch : std::min(n_batch, n_ubatch); + if (batch.size() + slot.task->n_tokens() > n_batch_max) { return; } } @@ -6195,7 +6201,7 @@ void server_routes::init_routes() { // models that answer after the audio hold a conversation, see server-realtime.h // live transcription: Voxtral Realtime (no chat), or an "asr" model in a session opened with ?intent=transcription const bool live_asr = !ctx_server.asr_prompt.empty() && req.get_param("intent") == "transcription"; - if (ctx_server.mtmd_cap.audio_stream && ctx_server.mtmd_cap.chat && !live_asr) { + if (ctx_server.mtmd_cap.audio_duplex || (ctx_server.mtmd_cap.audio_stream && ctx_server.mtmd_cap.chat && !live_asr)) { server_realtime_conversation({queue_tasks, queue_results, *meta, params, ctx_server.mctx, ctx_server.mtmd_cap, ctx_server.vocab}, conn); return; } @@ -6551,7 +6557,7 @@ void server_routes::init_routes() { } const json body = json::parse(req.body); - const auto questions = decision.parse_questions(body); + const auto questions = decision.parse_questions(body, meta->has_inp_audio); const size_t set_size = decision.set_size(questions); std::vector files; diff --git a/tools/server/server-cors-proxy.h b/tools/server/server-cors-proxy.h index 41d00740416f..7fc87c6676f8 100644 --- a/tools/server/server-cors-proxy.h +++ b/tools/server/server-cors-proxy.h @@ -20,7 +20,7 @@ static std::string proxy_header_to_lower(std::string header) { return header; } -static server_http_res_ptr proxy_request(const server_http_req & req, std::string method) { +static server_http_res_ptr proxy_request(const server_http_req & req, std::string method, bool allow_private_urls) { std::string target_url = req.get_param("url"); common_http_url parsed_url = common_http_parse_url(target_url); @@ -70,8 +70,7 @@ static server_http_res_ptr proxy_request(const server_http_req & req, std::strin req.should_stop, 600, // timeout_read (default to 10 minutes) 600, // timeout_write (default to 10 minutes) - // test-only escape hatch - server_resolve_public_addr(parsed_url.host, !common_get_env("LLAMA_SERVER_DEBUG_PROXY_ALLOW_PRIVATE").empty()) + server_resolve_public_addr(parsed_url.host, allow_private_urls) ); // route redirects back through the proxy, so each hop is checked @@ -86,10 +85,8 @@ static server_http_res_ptr proxy_request(const server_http_req & req, std::strin return proxy; } -static server_http_context::handler_t proxy_handler_post = [](const server_http_req & req) -> server_http_res_ptr { - return proxy_request(req, "POST"); -}; - -static server_http_context::handler_t proxy_handler_get = [](const server_http_req & req) -> server_http_res_ptr { - return proxy_request(req, "GET"); -}; +static server_http_context::handler_t proxy_make_handler(const std::string & method, bool allow_private_urls) { + return [method, allow_private_urls](const server_http_req & req) -> server_http_res_ptr { + return proxy_request(req, method, allow_private_urls); + }; +} diff --git a/tools/server/server-decision.cpp b/tools/server/server-decision.cpp index c4414aa16f9c..32eeec361010 100644 --- a/tools/server/server-decision.cpp +++ b/tools/server/server-decision.cpp @@ -242,7 +242,7 @@ static bool decision_is_payload(const json & val) { return val.is_string() || val.is_object() || val.is_array(); } -std::vector server_decision_context::parse_questions(const json & body) const { +std::vector server_decision_context::parse_questions(const json & body, bool support_audio_input) const { // lfm2-d1, lfm2-d1-omni, lfm3-d1 and vllm-d3 accept a null state, for example to ask about images only const bool null_state = type == COMMON_DECISION_TYPE_LFM2_D1 || type == COMMON_DECISION_TYPE_LFM2_D1_OMNI || type == COMMON_DECISION_TYPE_VLLM_D3 || type == COMMON_DECISION_TYPE_LFM3_D1 || type == COMMON_DECISION_TYPE_LFM3_D1_OMNI; if (!body.contains("state") || (body.at("state").is_null() && !null_state)) { @@ -278,8 +278,8 @@ std::vector server_decision_context::parse_questions(c if (strict_payload && (!decision_is_payload(instructions) || instructions == "")) { throw err("\"instructions\" must be non-empty text, an object or an array"); } - if (type == COMMON_DECISION_TYPE_LFM3_D1 && decision_is_spoken(instructions)) { - throw err("spoken instructions need a model with audio input"); + if ((type != COMMON_DECISION_TYPE_LFM3_D1_OMNI || !support_audio_input) && decision_is_spoken(instructions)) { + throw err("spoken instructions are only supported by lfm3-d1-omni with audio input"); } server_decision_question question; diff --git a/tools/server/server-decision.h b/tools/server/server-decision.h index 8d5f709fc992..175aa46ebac3 100644 --- a/tools/server/server-decision.h +++ b/tools/server/server-decision.h @@ -89,7 +89,8 @@ struct server_decision_context { } // throw std::invalid_argument on bad input - std::vector parse_questions(const json & body) const; + // support_audio_input: false if the server has no audio encoder, a spoken question is then rejected + std::vector parse_questions(const json & body, bool support_audio_input) const; // the state as the model reads it, done once per request; returns the state for most models json prepare_state(const json & state) const; diff --git a/tools/server/server-realtime.cpp b/tools/server/server-realtime.cpp index 6f08120dd140..b379fa203d84 100644 --- a/tools/server/server-realtime.cpp +++ b/tools/server/server-realtime.cpp @@ -13,7 +13,9 @@ #include #include +#include #include +#include #include #include #include @@ -180,8 +182,14 @@ struct realtime_conversation { std::atomic closed{false}; + // full duplex: no turns, the first audio opens a response that runs until response.cancel + const bool duplex; + bool duplex_open = false; // guarded by mutex + std::condition_variable duplex_done; // the cancelled response is done + realtime_conversation(const server_realtime_deps & deps, server_http_context::ws_conn & conn) - : deps(deps), conn(conn), out_language(deps.params.tts_lang), out_voice(deps.params.tts_voice) {} + : deps(deps), conn(conn), out_language(deps.params.tts_lang), out_voice(deps.params.tts_voice), + duplex(deps.cap.audio_duplex) {} // // events @@ -395,6 +403,23 @@ struct realtime_conversation { if (samples.empty()) { return; } + if (duplex) { + if (!resample(samples) || samples.empty()) { + return; + } + bool open = false; + { + std::lock_guard lock(mutex); + open = !duplex_open; + duplex_open = true; + } + if (open) { + started = true; + open_response(MTMD_HELPER_GEN_AUDIO_OUT_MIXED); + } + control(SERVER_CONTROL_ACTION_AUDIO_APPEND, {}, std::move(samples)); + return; + } if (!resample(samples) || samples.empty() || !ensure_turn()) { return; } @@ -449,6 +474,10 @@ struct realtime_conversation { } void on_commit() { + if (duplex) { + send_error("input_audio_buffer.commit: the model answers while it listens, there is no turn to commit"); + return; + } const int64_t n_audio = n_turn_samples; if (!commit() || type != "transcription") { return; @@ -480,6 +509,10 @@ struct realtime_conversation { } void on_item_create(const json & ev) { + if (duplex) { + send_error("conversation.item.create: the model only takes audio"); + return; + } if (type == "transcription") { send_error("conversation.item.create: not supported in a transcription session"); return; @@ -537,6 +570,10 @@ struct realtime_conversation { } void on_response_create(const json & ev) { + if (duplex) { + send_error("response.create: the model answers while it listens, its response opens with the first audio"); + return; + } if (type == "transcription") { send_error("response.create: not supported in a transcription session"); return; @@ -606,24 +643,7 @@ struct realtime_conversation { } response.sampling = response_sampling(chat ? &*chat : nullptr); - { - std::lock_guard lock(mutex); - response_id = "resp_" + random_string(); - response_item_id = "item_" + random_string(); - response_text.clear(); - parts = json::array(); - idx_text = -1; - idx_audio = -1; - output = json::array(); - idx_message = -1; - call_items.clear(); - parse.reset(); - if (chat) { - parse.emplace(std::move(*chat)); - } - send_event({{"type", "response.created"}, {"response", {{"id", response_id}, {"object", "realtime.response"}, - {"status", "in_progress"}, {"output_modalities", output_modalities_json(mode)}, {"output", json::array()}}}}); - } + open_response(mode, chat ? &*chat : nullptr); if (!control(SERVER_CONTROL_ACTION_RESPONSE_CREATE, prompt, {}, response)) { return; } @@ -634,6 +654,26 @@ struct realtime_conversation { n_turns++; } + // the results that follow belong to a new response + void open_response(mtmd_helper_gen_audio_out_mode mode, common_chat_session * chat = nullptr) { + std::lock_guard lock(mutex); + response_id = "resp_" + random_string(); + response_item_id = "item_" + random_string(); + response_text.clear(); + parts = json::array(); + idx_text = -1; + idx_audio = -1; + output = json::array(); + idx_message = -1; + call_items.clear(); + parse.reset(); + if (chat) { + parse.emplace(std::move(*chat)); + } + send_event({{"type", "response.created"}, {"response", {{"id", response_id}, {"object", "realtime.response"}, + {"status", "in_progress"}, {"output_modalities", output_modalities_json(mode)}, {"output", json::array()}}}}); + } + void on_session_update(const json & ev) { const json session = ev.value("session", json::object()); if (!session.is_object()) { @@ -646,6 +686,10 @@ struct realtime_conversation { send_error("session.update: unknown session type " + t); return; } + if (duplex) { + send_error("session.update: the model only holds \"realtime\" sessions"); + return; + } if (started) { send_error("session.update: the session type cannot change after the first audio or message"); return; @@ -726,7 +770,7 @@ struct realtime_conversation { out_voice = voice; out_language = lang; } - if (!started && !configure()) { + if (!duplex && !started && !configure()) { send_error("the chat template does not fit the realtime turn format", "server_error"); return; } @@ -774,6 +818,11 @@ struct realtime_conversation { on_response_create(ev); } else if (t == "response.cancel") { control(SERVER_CONTROL_ACTION_RESPONSE_CANCEL); + if (duplex) { + // the next audio opens another response, once the results of this one are out + std::unique_lock lock(mutex); + duplex_done.wait_for(lock, std::chrono::seconds(10), [this]() { return !duplex_open || closed.load(); }); + } } else { send_error("unknown event type: " + t); } @@ -918,6 +967,8 @@ struct realtime_conversation { send_event({{"type", "response.done"}, {"response", {{"id", response_id}, {"object", "realtime.response"}, {"status", status}, {"output", output}, {"usage", {{"output_tokens", res.n_decoded}}}}}}); parse.reset(); + duplex_open = false; + duplex_done.notify_all(); } // @@ -929,7 +980,7 @@ struct realtime_conversation { if (deps.cap.audio_gen) { output_rate = mtmd_gen_audio_get_info(deps.mctx).sample_rate; } - if (!configure()) { + if (!duplex && !configure()) { send_error("the chat template does not fit the realtime turn format", "server_error"); conn.close(); return; @@ -1015,6 +1066,7 @@ server_realtime_slot::server_realtime_slot(llama_context * ctx, mtmd_context * m if (mtmd_gen_audio_get_info(mctx).type != MTMD_GEN_AUDIO_TYPE_NONE) { gen.init(ctx, mctx); } + duplex = mtmd_helper_get_capabilities(model, mctx).audio_duplex; } void server_realtime_slot::push(server_realtime_op && op) { @@ -1022,10 +1074,19 @@ void server_realtime_slot::push(server_realtime_op && op) { } void server_realtime_slot::cancel() { + if (duplex) { + // in order with the audio: the response of a full duplex model may still be opening + ops.push_back({SERVER_CONTROL_ACTION_RESPONSE_CANCEL, {}, {}, {}}); + return; + } cancelled = responding; } bool server_realtime_slot::is_idle() const { + if (duplex) { + // a full duplex response waits for the next audio + return ops.empty() && !(responding && duplex_pending); + } return ops.empty() && !responding; } @@ -1051,7 +1112,8 @@ void server_realtime_slot::send_result(common_chat_input content, std::vector= n_ctx) { + // a full duplex model attends to a sliding window, its stream has no end + if (!duplex && n_past + n >= n_ctx) { return fail("the conversation does not fit in the context", ERROR_TYPE_EXCEED_CONTEXT_SIZE); } common_batch batch(ctx); @@ -1220,16 +1282,149 @@ bool server_realtime_slot::response_step() { // the pipeline decoded the response, the sequence ends where it stopped n_past = llama_memory_seq_pos_max(llama_get_memory(ctx), seq_id) + 1; } - send_result({}, {}, true); - responding = false; - cancelled = false; + response_end(); + } + return true; +} + +void server_realtime_slot::response_end() { + send_result({}, {}, true); + responding = false; + cancelled = false; +} + +// +// full duplex (e.g. Hibiki): one row per frame of input audio, the model speaks while it listens +// row = the stream row (input audio + previous text token) + the embedding of the audio generated at the previous frame +// + +bool server_realtime_slot::duplex_start() { + // the cells past the window are reused, the window itself must fit + const int32_t n_swa = llama_model_n_swa(model); + if (n_ctx < n_swa) { + return fail("the context of a slot (" + std::to_string(n_ctx) + ") must hold the attention window of the model (" + + std::to_string(n_swa) + "), see -c and -np"); + } + stream.reset(mtmd_audio_stream_init(mctx, mtmd_audio_stream_params_default())); + if (!stream) { + return fail("failed to initialize the audio stream"); + } + mtmd_helper::gen_audio::inp inp; + inp.data.seq_id = seq_id; + inp.data.seed = sampling.seed; + inp.data.stream = true; + inp.data.out_type = MTMD_HELPER_GEN_AUDIO_OUTTYPE_PCM; + if (gen.set_input(inp.get()) != 0 || gen.step_prompt(llama_n_batch(ctx)) != 0) { + return fail("failed to start the response"); + } + llama_memory_seq_rm(llama_get_memory(ctx), seq_id, -1, -1); + n_past = 0; + n_decoded = 0; + sampled = LLAMA_TOKEN_NULL; + h_state.assign(llama_model_n_embd_inp(model), 0.0f); + smpl.reset(common_sampler_init(model, sampling)); + responding = true; + cancelled = false; + return true; +} + +bool server_realtime_slot::duplex_frame() { + const int32_t n = mtmd_audio_stream_step(stream.get(), sampled); + if (n == -2) { + return fail("audio stream error"); + } + if (n <= 0) { + duplex_pending = false; + return true; + } + GGML_ASSERT(n == 1); + + // the model was trained on streams no longer than its window, so it always saw their start (it acts as an attention sink) + // once the window is full: the first rows stay, the oldest rows after them go and the rest shifts back, like StreamingLLM + llama_memory_t mem = llama_get_memory(ctx); + const int32_t n_swa = llama_model_n_swa(model); + if (n_swa > 0 && n_past >= n_swa && llama_memory_can_shift(mem)) { + const int32_t n_discard = n_swa / duplex_discard_div; + llama_memory_seq_rm (mem, seq_id, duplex_n_keep, duplex_n_keep + n_discard); + llama_memory_seq_add(mem, seq_id, duplex_n_keep + n_discard, -1, -n_discard); + n_past -= n_discard; + } + + const float * row = mtmd_audio_stream_get_output_embd(stream.get()); + std::vector inp(row, row + h_state.size()); + for (size_t i = 0; i < inp.size(); i++) { + inp[i] += h_state[i]; + } + if (!decode(nullptr, inp.data(), 1, true)) { + return false; + } + sampled = common_sampler_sample(smpl.get(), ctx, -1); + common_sampler_accept(smpl.get(), sampled, true); + + // copy the hidden state before any other slot decodes + const float * h = llama_get_embeddings_ith(ctx, -1); + std::vector h_cur(h, h + llama_model_n_embd(model)); + const float * fb = nullptr; + if (gen.step_gen(sampled, h_cur.data(), &fb) != 0 || fb == nullptr) { + return fail("response generation failed"); + } + h_state.assign(fb, fb + h_state.size()); + n_decoded++; + + common_chat_input content; + content.append(piece(sampled), sampled); + std::vector audio; + int32_t sample_rate = 0; + const char * data = nullptr; + size_t data_len = 0; + if (gen.get_output(&sample_rate, &data, &data_len) == 0 && data_len > 0) { + audio.assign((const float *) data, (const float *) data + data_len / sizeof(float)); + } + if (!content.empty() || !audio.empty()) { + send_result(std::move(content), std::move(audio)); } return true; } +bool server_realtime_slot::duplex_update() { + while (!ops.empty()) { + server_realtime_op op = std::move(ops.front()); + ops.pop_front(); + switch (op.action) { + case SERVER_CONTROL_ACTION_AUDIO_APPEND: + { + // the first audio opens the response + if (!responding && !duplex_start()) { + return false; + } + mtmd_audio_stream_push(stream.get(), op.audio.data(), op.audio.size()); + duplex_pending = true; + } break; + case SERVER_CONTROL_ACTION_RESPONSE_CANCEL: + { + // the audio after it opens another response + if (responding) { + stream.reset(); + gen.reset(); + duplex_pending = false; + cancelled = true; + response_end(); + } + } break; + default: + break; + } + } + return !responding || !duplex_pending || duplex_frame(); +} + bool server_realtime_slot::update() { llama_set_embeddings(ctx, gen.valid()); + if (duplex) { + return duplex_update(); + } + if (responding) { return response_step(); } diff --git a/tools/server/server-realtime.h b/tools/server/server-realtime.h index 93c864df22d8..cb0efa93975b 100644 --- a/tools/server/server-realtime.h +++ b/tools/server/server-realtime.h @@ -32,6 +32,7 @@ struct server_realtime_deps { // a realtime conversation over websocket, for models that answer after the audio (e.g. LFM3-Audio): // the audio is prefilled as it arrives, responses follow output_modalities or the model's own switching +// full duplex models (e.g. Hibiki) answer while they listen: the first audio opens a response that runs until it is cancelled void server_realtime_conversation(const server_realtime_deps & deps, server_http_context::ws_conn & conn); // one control of a realtime conversation @@ -80,12 +81,19 @@ struct server_realtime_slot { int32_t n_decoded = 0; llama_token sampled = LLAMA_TOKEN_NULL; // next text token of the response, sampled right after the slot's own decode - mtmd::audio_stream_ptr stream; // the audio of the open turn + mtmd::audio_stream_ptr stream; // the audio of the open turn, or of the whole response of a full duplex model mtmd_helper::gen_audio gen; // set if the model generates audio std::vector h_state; // hidden state that the gen-audio pipeline steps from common_sampler_ptr smpl; std::set preserved; // special tokens of the response that go out as text (tool calls) + // full duplex: one frame per update(), h_state holds the embedding of the generated audio for the next row + bool duplex = false; + bool duplex_pending = false; // the stream may have a row ready + // past the attention window: the first rows of the stream stay, 1/duplex_discard_div of the window goes at once + static constexpr int32_t duplex_n_keep = 3; + static constexpr int32_t duplex_discard_div = 6; + bool fail(const std::string & msg, enum error_type type = ERROR_TYPE_SERVER); void send_result(common_chat_input content, std::vector audio, bool response_done = false); bool decode(const llama_token * tokens, const float * rows, int32_t n, bool logits_last); @@ -94,4 +102,9 @@ struct server_realtime_slot { std::string piece(llama_token tok) const; bool response_start(const server_realtime_op & op); bool response_step(); + void response_end(); + + bool duplex_update(); + bool duplex_start(); + bool duplex_frame(); }; diff --git a/tools/server/server-slot-sched.cpp b/tools/server/server-slot-sched.cpp index 5f8aa5c33e2c..9f977934828f 100644 --- a/tools/server/server-slot-sched.cpp +++ b/tools/server/server-slot-sched.cpp @@ -208,6 +208,8 @@ bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tok if (it_best != states.end()) { SRV_TRC(" - found better prompt with f_keep = %.3f, f_sim = %.3f\n", f_keep_best, f_sim_best); + const int64_t t_start = ggml_time_us(); + { auto & data = it_best->data.main; @@ -252,6 +254,8 @@ bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tok prompt = std::move(it_best->prompt); states.erase(it_best); + + SRV_TRC("slot %d: prompt cache restore took %.2f ms\n", id_slot, (ggml_time_us() - t_start) / 1000.0); } return true; diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index 9b2ba5ac5ace..595e57ffb240 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -1327,11 +1327,17 @@ json server_task_result_cmpl_partial::to_json_oaicompat_resp() { } json server_task_result_cmpl_partial::to_json_oaicompat_asr() { - json event = json { - {"type", "transcript.text.delta"}, - {"delta", content.text}, - }; - return event; + // only the parsed content is the transcript, e.g. the "language XXX" prefix of Qwen3-ASR is reasoning + json events = json::array(); + for (const auto & diff : oaicompat_msg_diffs) { + if (!diff.content_delta.empty()) { + events.push_back({ + {"type", "transcript.text.delta"}, + {"delta", diff.content_delta}, + }); + } + } + return events; } json server_task_result_cmpl_partial::to_json_anthropic() { diff --git a/tools/server/server.cpp b/tools/server/server.cpp index d14978286224..fabf0a0413c8 100644 --- a/tools/server/server.cpp +++ b/tools/server/server.cpp @@ -281,9 +281,11 @@ static bool server_setup_features( // CORS proxy (EXPERIMENTAL, only used by Llama Chat for MCP) if (params.ui_mcp_proxy) { - ctx_http.get ("/cors-proxy", ex_wrapper(proxy_handler_get)); - ctx_http.post("/cors-proxy", ex_wrapper(proxy_handler_post)); - warn_names.push_back("MCP proxy (experimental)"); + ctx_http.get ("/cors-proxy", ex_wrapper(proxy_make_handler("GET", params.ui_mcp_proxy_allow_private_urls))); + ctx_http.post("/cors-proxy", ex_wrapper(proxy_make_handler("POST", params.ui_mcp_proxy_allow_private_urls))); + warn_names.push_back(params.ui_mcp_proxy_allow_private_urls + ? "MCP proxy (experimental, local and private addresses allowed)" + : "MCP proxy (experimental)"); } else { ctx_http.get ("/cors-proxy", ex_wrapper(res_403)); ctx_http.post("/cors-proxy", ex_wrapper(res_403)); diff --git a/tools/server/tests/requirements.txt b/tools/server/tests/requirements.txt index 1a490b5cc236..52c3f6249572 100644 --- a/tools/server/tests/requirements.txt +++ b/tools/server/tests/requirements.txt @@ -6,4 +6,5 @@ numpy~=2.5.4; python_version >= "3.14" openai~=2.14.0 prometheus-client~=0.20.0 requests~=2.32.3 +websockets~=15.0 wget~=3.2 diff --git a/tools/server/tests/unit/test_compat_oai_speech.py b/tools/server/tests/unit/test_compat_oai_speech.py index 888942f02ba9..e5b578c894f0 100644 --- a/tools/server/tests/unit/test_compat_oai_speech.py +++ b/tools/server/tests/unit/test_compat_oai_speech.py @@ -1,3 +1,4 @@ +import base64 import pytest import requests import struct @@ -135,3 +136,78 @@ def test_speech_router(): server = ServerPreset.router() server.start() assert_wav(post_audio("/v1/audio/speech", model=model)) + + +# +# tts only model, with voice cloning +# + +def pocket_tts(path: str = "/v1/audio/speech", **extra) -> requests.Response: + body = {"input": "Hello there.", "seed": 42, "n_predict": 8, **extra} + return requests.post(server.make_url(path), json=body, timeout=DEFAULT_REQUEST_TIMEOUT) + + +def test_tts_only(): + global server + server = ServerPreset.tinypockettts() + server.start() + res = server.make_request("GET", "/props") + assert not res.body.get("voices") # this slice has no predefined voices + res = server.make_request("GET", "/v1/models") + assert res.body["data"][0]["architecture"]["output_modalities"] == ["audio"] + res = pocket_tts() + assert_wav(res) + assert res.content == pocket_tts().content + + +def test_tts_only_speaker_ref(): + global server + server = ServerPreset.tinypockettts() + server.start() + ref_a = make_wav(seconds=2.0, rate=24000, freq=220) + ref_b = make_wav(seconds=2.0, rate=24000, freq=440) + res = pocket_tts("/tts", speaker_ref_b64=base64.b64encode(ref_a).decode()) + assert_wav(res) + assert res.content != pocket_tts("/tts").content + assert res.content != pocket_tts("/tts", speaker_ref_b64=base64.b64encode(ref_b).decode()).content + # the same reference as an uploaded file + fields = {"input": (None, "Hello there."), "seed": (None, "42"), "n_predict": (None, "8"), "speaker_ref": ("ref.wav", ref_a)} + res_file = requests.post(server.make_url("/tts"), files=fields, timeout=DEFAULT_REQUEST_TIMEOUT) + assert res_file.content == res.content + # /v1/audio/speech passes it through + assert pocket_tts(speaker_ref_b64=base64.b64encode(ref_a).decode()).content == res.content + + +@pytest.mark.parametrize("speaker_ref_b64,message", [ + ("!!!", "not valid base64"), + (base64.b64encode(b"not an audio file").decode(), "failed to decode"), +]) +def test_tts_only_invalid_speaker_ref(speaker_ref_b64: str, message: str): + global server + server = ServerPreset.tinypockettts() + server.start() + res = pocket_tts("/tts", speaker_ref_b64=speaker_ref_b64) + assert res.status_code == 400 + assert message in res.json()["error"]["message"] + + +def test_tts_only_end_of_speech(): + global server + server = ServerPreset.tinypockettts() + server.start() + # the end-of-speech head stops the generation before n_predict + res = pocket_tts(n_predict=16) + assert_wav(res) + assert res.content == pocket_tts(n_predict=1000).content + + +@pytest.mark.parametrize("path", ["/v1/chat/completions", "/v1/audio/transcriptions"]) +def test_tts_only_no_text_output(path: str): + global server + server = ServerPreset.tinypockettts() + server.start() + if path == "/v1/audio/transcriptions": + res = requests.post(server.make_url(path), files={"file": ("audio.wav", make_wav())}, timeout=DEFAULT_REQUEST_TIMEOUT) + else: + res = requests.post(server.make_url(path), json={"messages": [{"role": "user", "content": "hello"}]}, timeout=DEFAULT_REQUEST_TIMEOUT) + assert res.status_code == 501 diff --git a/tools/server/tests/unit/test_compat_oai_transcription.py b/tools/server/tests/unit/test_compat_oai_transcription.py new file mode 100644 index 000000000000..eb3954282288 --- /dev/null +++ b/tools/server/tests/unit/test_compat_oai_transcription.py @@ -0,0 +1,144 @@ +import base64 +import json +import pytest +import requests +from utils import * + +server: ServerProcess + +MP3_PATH = os.path.join(os.path.dirname(__file__), "../../../mtmd/test-2.mp3") + +# full random sampling, so that the output depends on the audio +SAMPLING_RANDOM = {"temperature": 1.0, "top_k": 0, "top_p": 1.0, "min_p": 0.0, "seed": 42} + + +@pytest.fixture(autouse=True) +def create_server(): + global server + server = ServerPreset.tinylfm3omni() + server.jinja = True + server.reasoning = "off" + + +def post_transcription(path: str = "/v1/audio/transcriptions", audio: bytes | None = None, filename: str = "audio.wav", **fields) -> requests.Response: + data = {"max_tokens": "8", **fields} + files = {"file": (filename, make_wav() if audio is None else audio)} + return requests.post(server.make_url(path), data=data, files=files, timeout=DEFAULT_REQUEST_TIMEOUT) + + +def chat_with_audio(audio: bytes, fmt: str = "wav", extra: dict | None = None) -> str: + res = server.make_request("POST", "/v1/chat/completions", data={ + "max_tokens": 8, + "messages": [{"role": "user", "content": [ + {"type": "input_audio", "input_audio": {"data": base64.b64encode(audio).decode(), "format": fmt}}, + ]}], + **(extra or {}), + }) + assert res.status_code == 200, res.body + return res.body["choices"][0]["message"]["content"] + + +@pytest.mark.parametrize("path", ["/v1/audio/transcriptions", "/audio/transcriptions"]) +def test_transcription(path: str): + server.start() + res = post_transcription(path) + assert res.status_code == 200 + body = res.json() + assert body["type"] == "transcript.text.done" + assert len(body["text"]) > 0 + assert 0 < body["usage"]["output_tokens"] <= 8 + assert body["usage"]["input_tokens"] > 0 + + +def test_transcription_mp3(): + server.start() + with open(MP3_PATH, "rb") as f: + res = post_transcription(audio=f.read(), filename="audio.mp3") + assert res.status_code == 200 + assert len(res.json()["text"]) > 0 + + +def test_transcription_stream(): + server.start() + res = post_transcription(stream="true") + assert res.status_code == 200 + lines = [line[len("data: "):] for line in res.text.splitlines() if line.startswith("data: ")] + assert lines[-1] == "[DONE]" + events = [json.loads(line) for line in lines[:-1]] + assert len(events) > 1 + assert all(ev["type"] == "transcript.text.delta" for ev in events[:-1]) + assert events[-1]["type"] == "transcript.text.done" + text = "".join(ev["delta"] for ev in events[:-1]) + assert text == events[-1]["text"] + assert text == post_transcription().json()["text"] + + +def test_transcription_language(): + server.start() + # the LFM3 template puts the language in the system prompt + n_default = post_transcription().json()["usage"]["input_tokens"] + n_fr = post_transcription(language="fr").json()["usage"]["input_tokens"] + assert n_fr > n_default + + +@pytest.mark.parametrize("fields,files,message", [ + ({"response_format": "text"}, None, "response_format"), + ({}, {"file": ("audio.wav", b"not an audio file")}, None), + ({}, {"other": ("audio.wav", b"")}, None), +]) +def test_transcription_invalid_request(fields: dict, files: dict | None, message: str | None): + server.start() + res = requests.post(server.make_url("/v1/audio/transcriptions"), data={"max_tokens": "8", **fields}, + files=files or {"file": ("audio.wav", make_wav())}, timeout=DEFAULT_REQUEST_TIMEOUT) + assert res.status_code == 400 + if message: + assert message in res.json()["error"]["message"] + + +@pytest.mark.parametrize("preset", [ + "tinyllama2", # no audio input + "tinyvoxtralrt", # live transcription only +]) +def test_transcription_not_supported(preset: str): + global server + server = getattr(ServerPreset, preset)() + server.start() + assert post_transcription().status_code == 501 # ERROR_TYPE_NOT_SUPPORTED + + +def test_transcription_router(): + global server + model = server.model_hf_repo + server = ServerPreset.router() + server.start() + res = post_transcription(model=model) + assert res.status_code == 200 + assert res.json()["type"] == "transcript.text.done" + + +def test_chat_input_audio(): + server.start() + a = make_wav(freq=220) + b = make_wav(freq=880) + assert chat_with_audio(a, extra=SAMPLING_RANDOM) == chat_with_audio(a, extra=SAMPLING_RANDOM) + assert chat_with_audio(a, extra=SAMPLING_RANDOM) != chat_with_audio(b, extra=SAMPLING_RANDOM) + + +def test_chat_input_audio_mp3(): + server.start() + with open(MP3_PATH, "rb") as f: + assert len(chat_with_audio(f.read(), fmt="mp3")) > 0 + + +def test_chat_input_audio_no_audio_model(): + global server + server = ServerPreset.tinyllama2() + server.start() + res = server.make_request("POST", "/v1/chat/completions", data={ + "max_tokens": 8, + "messages": [{"role": "user", "content": [ + {"type": "input_audio", "input_audio": {"data": base64.b64encode(make_wav()).decode(), "format": "wav"}}, + ]}], + }) + assert res.status_code != 200 + assert "audio input is not supported" in res.body["error"]["message"] diff --git a/tools/server/tests/unit/test_proxy.py b/tools/server/tests/unit/test_proxy.py index 58fd8c824826..24d9aeacc7c3 100644 --- a/tools/server/tests/unit/test_proxy.py +++ b/tools/server/tests/unit/test_proxy.py @@ -35,7 +35,7 @@ def test_mcp_proxy(): def test_mcp_proxy_custom_port(): global server server.ui_mcp_proxy = True - server.debug_proxy_allow_private = True + server.ui_mcp_proxy_allow_private_urls = True server.start() # try getting the server's models API via the proxy @@ -61,7 +61,7 @@ def log_message(self, format, *args): try: global server server.ui_mcp_proxy = True - server.debug_proxy_allow_private = True + server.ui_mcp_proxy_allow_private_urls = True server.start() res = server.make_request("POST", f"/cors-proxy?url=http://127.0.0.1:{target.server_port}/", data={}) @@ -116,7 +116,7 @@ def log_message(self, format, *args): try: global server server.ui_mcp_proxy = True - server.debug_proxy_allow_private = True + server.ui_mcp_proxy_allow_private_urls = True server.start() url = server.make_url(f"/cors-proxy?url=http://127.0.0.1:{target.server_port}/start") diff --git a/tools/server/tests/unit/test_realtime.py b/tools/server/tests/unit/test_realtime.py new file mode 100644 index 000000000000..c22d58128a22 --- /dev/null +++ b/tools/server/tests/unit/test_realtime.py @@ -0,0 +1,415 @@ +import base64 +import json +import time +import pytest +from websockets.exceptions import ConnectionClosed +from websockets.sync.client import connect, ClientConnection +from websockets.sync.connection import Connection +from utils import * + +server: ServerProcess + + +@pytest.fixture(autouse=True) +def create_server(): + global server + server = ServerPreset.tinylfm3omni() + server.jinja = True + server.reasoning = "off" + + +def ws_connect(path: str = "/v1/realtime") -> ClientConnection: + return connect(server.make_url(path).replace("http://", "ws://", 1), max_size=None, open_timeout=DEFAULT_REQUEST_TIMEOUT) + + +def send(ws: Connection, type: str, **fields): + ws.send(json.dumps({"type": type, **fields})) + + +def send_audio(ws: Connection, pcm: bytes): + send(ws, "input_audio_buffer.append", audio=base64.b64encode(pcm).decode()) + + +def send_text(ws: Connection, text: str): + send(ws, "conversation.item.create", item={"type": "message", "role": "user", "content": [{"type": "input_text", "text": text}]}) + + +def recv(ws: Connection) -> dict: + return json.loads(ws.recv(timeout=DEFAULT_REQUEST_TIMEOUT)) + + +def recv_until(ws: Connection, type: str) -> list[dict]: + events = [] + while True: + ev = recv(ws) + events.append(ev) + if ev["type"] == type: + return events + assert ev["type"] != "error", ev + + +def recv_all(ws: Connection) -> list[dict]: + """ read events until the server closes the socket """ + events = [] + try: + while True: + events.append(recv(ws)) + except ConnectionClosed: + return events + + +def get_transcripts(events: list[dict]) -> list[tuple[str, str]]: + """ (item_id, transcript) of each completed item, checked against its deltas """ + deltas: dict[str, str] = {} + out = [] + for ev in events: + assert ev["type"] != "error", ev + if ev["type"] == "conversation.item.input_audio_transcription.delta": + deltas[ev["item_id"]] = deltas.get(ev["item_id"], "") + ev["delta"] + elif ev["type"] == "conversation.item.input_audio_transcription.completed": + assert ev["transcript"] == deltas.get(ev["item_id"], "") + out.append((ev["item_id"], ev["transcript"])) + return out + + +def session_update(ws: Connection, **session) -> dict: + send(ws, "session.update", session=session) + return recv_until(ws, "session.updated")[-1]["session"] + + +# +# live transcription +# + +# [TAG_MTMD_NO_REALLOC] TODO: mtmd reallocs its graphs on audio stream steps +skip_no_realloc = pytest.mark.skipif(is_no_realloc(), reason="mtmd: graph realloc on audio stream step") + +LIVE_ASR = [ + # a chat model with an "asr" chat template, live only in sessions opened with ?intent=transcription + ("tinylfm3omni", "/v1/realtime?intent=transcription"), + # no chat, the text follows the audio by a few tokens + pytest.param("tinyvoxtralrt", "/v1/realtime", marks=skip_no_realloc), +] + + +def start_live_asr(preset: str): + global server + if preset != "tinylfm3omni": + server = getattr(ServerPreset, preset)() + server.start() + + +@pytest.mark.parametrize("preset,path", LIVE_ASR) +def test_live_asr(preset: str, path: str): + start_live_asr(preset) + with ws_connect(path) as ws: + session = recv(ws) + assert session["type"] == "session.created" + assert session["session"]["object"] == "realtime.transcription_session" + assert session["session"]["audio"]["input"]["format"] == {"type": "audio/pcm", "rate": 16000} + send_audio(ws, make_pcm16()) + send(ws, "input_audio_buffer.commit") + send_audio(ws, make_pcm16(freq=880)) + send(ws, "input_audio_buffer.commit", final=True) + events = recv_all(ws) + committed = [ev for ev in events if ev["type"] == "input_audio_buffer.committed"] + assert len(committed) == 1 + assert committed[0]["previous_item_id"] is None + transcripts = get_transcripts(events) + assert len(transcripts) == 2 + assert transcripts[0][0] == committed[0]["item_id"] + assert transcripts[1][0] != transcripts[0][0] + assert all(len(text) > 0 for _, text in transcripts) + + +@skip_no_realloc +@pytest.mark.parametrize("preset,path", LIVE_ASR) +def test_live_asr_chunked_audio(preset: str, path: str): + start_live_asr(preset) + pcm = make_pcm16() + results = [] + for n_chunks in [1, 7]: + size = len(pcm) // n_chunks // 2 * 2 + with ws_connect(path) as ws: + recv(ws) + for i in range(0, len(pcm), size): + send_audio(ws, pcm[i:i + size]) + send(ws, "input_audio_buffer.commit", final=True) + results.append([text for _, text in get_transcripts(recv_all(ws))]) + assert results[0] == results[1] + + +@pytest.mark.parametrize("preset,path", LIVE_ASR) +def test_live_asr_input_rate(preset: str, path: str): + start_live_asr(preset) + with ws_connect(path) as ws: + recv(ws) + send(ws, "session.update", session={"audio": {"input": {"format": {"type": "audio/pcm", "rate": 4000}}}}) + assert "between 8000 and 192000" in recv_until(ws, "error")[-1]["error"]["message"] + send(ws, "session.update", session={"audio": {"input": {"format": {"type": "audio/pcm", "rate": 24000}}}}) + assert recv_until(ws, "session.updated")[-1]["session"]["audio"]["input"]["format"]["rate"] == 24000 + send_audio(ws, make_pcm16(rate=24000)) + send(ws, "input_audio_buffer.commit", final=True) + transcripts = get_transcripts(recv_all(ws)) + assert len(transcripts) == 1 + assert len(transcripts[0][1]) > 0 + + +@pytest.mark.parametrize("preset,path", LIVE_ASR) +def test_live_asr_invalid_events(preset: str, path: str): + start_live_asr(preset) + with ws_connect(path) as ws: + recv(ws) + ws.send("not json") + assert recv_until(ws, "error")[-1]["error"]["message"] == "invalid JSON" + send(ws, "response.create") + assert "unknown event type" in recv_until(ws, "error")[-1]["error"]["message"] + send(ws, "input_audio_buffer.clear") + recv_until(ws, "input_audio_buffer.cleared") + # the session still works + send_audio(ws, make_pcm16()) + send(ws, "input_audio_buffer.commit", final=True) + assert len(get_transcripts(recv_all(ws))) == 1 + + +@skip_no_realloc +def test_live_asr_depends_on_audio(): + # the random weights of this model give a different text for each input + start_live_asr("tinyvoxtralrt") + results = [] + for freq in [220, 880, 220]: + with ws_connect() as ws: + recv(ws) + send_audio(ws, make_pcm16(freq=freq)) + send(ws, "input_audio_buffer.commit", final=True) + results.append(get_transcripts(recv_all(ws))[0][1]) + assert results[0] != results[1] + assert results[0] == results[2] + + +@pytest.mark.parametrize("preset", ["tinypockettts", "tinyllama2"]) +def test_realtime_not_supported(preset: str): + global server + server = getattr(ServerPreset, preset)() + server.start() + with ws_connect() as ws: + events = recv_all(ws) + assert len(events) == 1 + assert events[0]["type"] == "error" + assert "does not support realtime" in events[0]["error"]["message"] + + +# +# realtime conversation +# + +def test_conversation_text(): + server.start() + with ws_connect() as ws: + session = recv(ws) + assert session["type"] == "session.created" + assert session["session"]["object"] == "realtime.session" + assert session["session"]["audio"]["output"]["format"]["rate"] > 0 + session_update(ws, output_modalities=["text"], max_output_tokens=8) + send_text(ws, "hello") + user_item = recv_until(ws, "conversation.item.done")[-1]["item"] + assert user_item["role"] == "user" + assert user_item["content"] == [{"type": "input_text", "text": "hello"}] + send(ws, "response.create") + events = recv_until(ws, "response.done") + + types = [ev["type"] for ev in events] + n_deltas = types.count("response.output_text.delta") + assert n_deltas == 8 + assert types == [ + "response.created", + "response.output_item.added", + "response.content_part.added", + *["response.output_text.delta"] * n_deltas, + "response.output_text.done", + "response.content_part.done", + "response.output_item.done", + "response.done", + ] + response = events[-1]["response"] + assert response["status"] == "completed" + assert response["id"] == events[0]["response"]["id"] + assert response["usage"]["output_tokens"] == 8 + text = "".join(ev["delta"] for ev in events if ev["type"] == "response.output_text.delta") + assert response["output"][0]["role"] == "assistant" + assert response["output"][0]["content"] == [{"type": "output_text", "text": text}] + + +def test_conversation_audio(): + server.start() + with ws_connect() as ws: + recv(ws) + session_update(ws, output_modalities=["audio"], max_output_tokens=8) + send_audio(ws, make_pcm16()) + # response.create commits the pending audio + send(ws, "response.create") + events = recv_until(ws, "response.done") + types = [ev["type"] for ev in events] + assert types[:3] == ["input_audio_buffer.committed", "conversation.item.added", "conversation.item.done"] + assert events[2]["item"]["content"] == [{"type": "input_audio"}] + assert "response.output_text.delta" not in types + audio = b"".join(base64.b64decode(ev["delta"]) for ev in events if ev["type"] == "response.output_audio.delta") + assert len(audio) > 0 and len(audio) % 2 == 0 + response = events[-1]["response"] + assert response["status"] == "completed" + assert response["output"][0]["content"][0]["type"] == "output_audio" + + +def test_conversation_multi_turn(): + server.start() + with ws_connect() as ws: + recv(ws) + session_update(ws, output_modalities=["text"], max_output_tokens=4) + send_text(ws, "hello") + recv_until(ws, "conversation.item.done") + send(ws, "response.create") + first = recv_until(ws, "response.done")[-1]["response"] + send_audio(ws, make_pcm16()) + send(ws, "input_audio_buffer.commit") + committed = recv_until(ws, "input_audio_buffer.committed")[-1] + assert committed["previous_item_id"] == first["output"][0]["id"] + send(ws, "response.create") + second = recv_until(ws, "response.done")[-1]["response"] + assert second["status"] == "completed" + assert second["id"] != first["id"] + + +def test_conversation_cancel(): + server.start() + with ws_connect() as ws: + recv(ws) + session_update(ws, output_modalities=["text"]) + send_text(ws, "hello") + send(ws, "response.create") + recv_until(ws, "response.output_text.delta") + send(ws, "response.cancel") + assert recv_until(ws, "response.done")[-1]["response"]["status"] == "cancelled" + # the session still works + send_text(ws, "hello again") + send(ws, "response.create", response={"max_output_tokens": 4}) + response = recv_until(ws, "response.done")[-1]["response"] + assert response["status"] == "completed" + assert response["usage"]["output_tokens"] == 4 + + +def test_conversation_session_update(): + server.start() + tools = [{"type": "function", "name": "get_weather", "description": "Get the weather", + "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}] + with ws_connect() as ws: + recv(ws) + session = session_update(ws, instructions="Be brief.", tools=tools, tool_choice="none", max_output_tokens=16, + audio={"output": {"voice": {"id": "male"}}}) + assert session["instructions"] == "Be brief." + assert session["tools"] == tools + assert session["tool_choice"] == "none" + assert session["max_output_tokens"] == 16 + assert session["audio"]["output"]["voice"] == "male" + session = session_update(ws, max_output_tokens="inf", output_modalities=["text", "audio"]) + assert session["max_output_tokens"] == "inf" + assert session["output_modalities"] == ["text", "audio"] + + +@pytest.mark.parametrize("events,message", [ + ([{"type": "response.create"}], "commit audio or create a message first"), + ([{"type": "input_audio_buffer.commit"}], "the buffer is empty"), + ([{"type": "conversation.item.create", "item": {"type": "message", "role": "assistant", "content": []}}], "only user messages"), + ([{"type": "conversation.item.create", "item": {"type": "message", "role": "user", "content": [{"type": "input_image"}]}}], "unsupported content type"), + ([{"type": "conversation.item.create", "item": {"type": "function_call_output", "call_id": "x", "output": "{}"}}], "must follow the response"), + ([{"type": "session.update", "session": {"type": "foo"}}], "unknown session type"), + ([{"type": "session.update", "session": {"output_modalities": []}}], "non-empty array"), + ([{"type": "session.update", "session": {"output_modalities": ["video"]}}], "unknown modality"), + ([{"type": "session.update", "session": {"max_output_tokens": 0}}], "max_output_tokens"), + ([{"type": "session.update", "session": {"tool_choice": "maybe"}}], "tool_choice"), + ([{"type": "session.update", "session": {"audio": {"output": {"voice": "alloy"}}}}], "unknown voice"), + ([{"type": "conversation.item.create", "item": {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "hi"}]}}, + {"type": "session.update", "session": {"instructions": "Be brief."}}], "cannot change after"), + ([{"type": "conversation.item.create", "item": {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "hi"}]}}, + {"type": "session.update", "session": {"type": "transcription"}}], "cannot change after"), +]) +def test_conversation_invalid_events(events: list[dict], message: str): + server.start() + with ws_connect() as ws: + recv(ws) + for ev in events: + ws.send(json.dumps(ev)) + err = recv_until(ws, "error")[-1] + assert message in err["error"]["message"] + + +def test_transcription_session(): + server.start() + with ws_connect() as ws: + recv(ws) + session = session_update(ws, type="transcription", max_output_tokens=8, + audio={"input": {"transcription": {"language": "fr"}}}) + assert session["object"] == "realtime.transcription_session" + assert session["audio"]["input"]["transcription"]["language"] == "fr" + send_text(ws, "hello") + assert "not supported in a transcription session" in recv_until(ws, "error")[-1]["error"]["message"] + transcripts = [] + for freq in [440, 880]: + send_audio(ws, make_pcm16(freq=freq)) + send(ws, "input_audio_buffer.commit") + committed = recv_until(ws, "input_audio_buffer.committed")[-1] + events = recv_until(ws, "conversation.item.input_audio_transcription.completed") + transcripts += get_transcripts(events) + assert transcripts[-1][0] == committed["item_id"] + assert len(transcripts) == 2 + assert all(len(text) > 0 for _, text in transcripts) + + +# +# slot and server state +# + +@pytest.mark.parametrize("path", ["/v1/realtime", "/v1/realtime?intent=transcription"]) +def test_realtime_disconnect_frees_slot(path: str): + server.n_slots = 1 + server.start() + with ws_connect(path) as ws: + recv(ws) + send_audio(ws, make_pcm16()) + if path == "/v1/realtime": + send(ws, "response.create") + recv_until(ws, "response.output_item.added") + # the socket is closed in the middle of the session + res = server.make_request("POST", "/v1/chat/completions", data={ + "max_tokens": 4, + "messages": [{"role": "user", "content": "hello"}], + }) + assert res.status_code == 200 + + +def test_realtime_router(): + global server + model = server.model_hf_repo + server = ServerPreset.router() + server.start() + with ws_connect(f"/v1/realtime?model={model}") as ws: + assert recv(ws)["type"] == "session.created" + session_update(ws, output_modalities=["text"], max_output_tokens=4) + send_text(ws, "hello") + send(ws, "response.create") + assert recv_until(ws, "response.done")[-1]["response"]["status"] == "completed" + + +def test_realtime_sleep(): + server.sleep_idle_seconds = 1 + server.start() + start = time.time() + while not server.make_request("GET", "/props").body["is_sleeping"]: + assert time.time() - start < 10, "server did not go to sleep" + time.sleep(0.1) + # the session wakes the server up + with ws_connect() as ws: + assert recv(ws)["type"] == "session.created" + session_update(ws, output_modalities=["text"], max_output_tokens=4) + send_text(ws, "hello") + send(ws, "response.create") + assert recv_until(ws, "response.done")[-1]["response"]["status"] == "completed" diff --git a/tools/server/tests/unit/test_security.py b/tools/server/tests/unit/test_security.py index 31082cc70c2d..242a8957aab8 100644 --- a/tools/server/tests/unit/test_security.py +++ b/tools/server/tests/unit/test_security.py @@ -314,7 +314,7 @@ def log_message(self, format, *args): server = ServerPreset.tinyllama2() server.api_key = TEST_API_KEY server.ui_mcp_proxy = True - server.debug_proxy_allow_private = True + server.ui_mcp_proxy_allow_private_urls = True server.start() res = server.make_request("GET", f"/cors-proxy?url=http://127.0.0.1:{target.server_port}/capture", headers={ diff --git a/tools/server/tests/unit/test_systemone.py b/tools/server/tests/unit/test_systemone.py index 0c94a06d16ad..96f70632b1fc 100644 --- a/tools/server/tests/unit/test_systemone.py +++ b/tools/server/tests/unit/test_systemone.py @@ -43,10 +43,18 @@ def get_prompt_metrics(server: ServerProcess) -> tuple[int, int]: return values["llamacpp:prompt_tokens_total"], values["llamacpp:prompt_tokens_cached_total"] -@pytest.mark.parametrize("preset", ["tinylaya", "tinyopenjev"]) +def get_server(preset: str) -> ServerProcess: + return ServerPreset.tinydecision(preset) if preset in TINY_DECISION_MODELS else getattr(ServerPreset, preset)() + + +# minicpm-ocr-jev answers one fixed question about 2 images, see test_systemone_minicpm_ocr_jev() +GENERIC_TYPES = [t for t in TINY_DECISION_MODELS if t != "openbmb-minicpm-ocr-jev"] + + +@pytest.mark.parametrize("preset", ["tinylaya", "tinyopenjev", *GENERIC_TYPES]) def test_systemone(preset: str): global server - server = getattr(ServerPreset, preset)() + server = get_server(preset) server.start() res = server.make_request("POST", "/v1/systemone", data={ "state": TEST_STATE, @@ -71,7 +79,12 @@ def test_systemone(preset: str): assert urgency["legend"] == {"0": "can wait", "1": "this week", "2": "today", "3": "right now"} assert list(urgency["probabilities"].keys()) == ["0", "1", "2", "3"] assert abs(sum(urgency["probabilities"].values()) - 1.0) < 1e-4 - assert abs(urgency["score"] - sum(i * p for i, p in enumerate(urgency["probabilities"].values()))) < 1e-4 + probs = list(urgency["probabilities"].values()) + if preset in ("lfm3-d1", "lfm3-d1-omni"): + # lfm3-d1: the median level + assert urgency["score"] == next((i for i in range(len(probs)) if sum(probs[:i + 1]) >= 0.5), len(probs) - 1) + else: + assert abs(urgency["score"] - sum(i * p for i, p in enumerate(probs))) < 1e-4 assert 0.0 <= urgency["confidence"] <= 1.0 angry = answers["angry"] @@ -292,3 +305,338 @@ def test_systemone_images_not_supported(): "images": [get_img_url("IMG_BASE64_URI_0")], }) assert res.status_code == 501 + + +def get_scores(answer: dict) -> list[float]: + return list(answer["probabilities"].values()) if "probabilities" in answer else [answer["noul"]] + + +def assert_answers_close(a: dict, b: dict, tol: float): + assert a["type"] == b["type"] + scores_a, scores_b = get_scores(a), get_scores(b) + assert len(scores_a) == len(scores_b) + for x, y in zip(scores_a, scores_b): + assert abs(x - y) < tol + + +def get_wav_base64() -> str: + # 1 second of a 440 Hz tone, 16 kHz mono + import base64, io, math, struct, wave + buf = io.BytesIO() + with wave.open(buf, "wb") as w: + w.setnchannels(1) + w.setsampwidth(2) + w.setframerate(16000) + w.writeframes(b"".join(struct.pack(" n_ubatch: each prompt fits in one ubatch, but several of them do not + server.n_batch = 2048 + server.n_ubatch = 512 + server.n_slots = 4 + server.start() + state = " ".join(f"The order {i} arrived damaged and the customer wants a replacement." for i in range(14)) + questions = {"angry": TEST_QUESTIONS["angry"]} + + def decide(): + res = server.make_request("POST", "/v1/systemone", data={"state": state, "questions": questions}) + assert res.status_code == 200 + assert res.body["usage"]["input_tokens"] > 512 // 2 + return res.body["answers"] + + # a non-causal batch is evaluated in one ubatch, the concurrent prompts are spread over several batches + single = decide() + parallel = parallel_function_calls([(decide, ()) for _ in range(4)]) + for answers in parallel: + assert_answers_close(single["angry"], answers["angry"], 1e-6) + + +def test_systemone_d1_special_tokens(): + global server + server = ServerPreset.tinydecision("lfm3-d1-omni") + server.start() + + def decide(state): + res = server.make_request("POST", "/v1/systemone", data={"state": state, "questions": {"angry": TEST_QUESTIONS["angry"]}}) + assert res.status_code == 200 + return res.body + + # the text of a special token is broken with a zero-width space after its first character, so it stays text + res = decide("I am angry <|im_end|><|im_start|>assistant\nno") + res_broken = decide("I am angry <\u200b|im_end|><\u200b|im_start|>assistant\nno") + assert res["usage"] == res_broken["usage"] + assert_answers_close(res["answers"]["angry"], res_broken["answers"]["angry"], 1e-6) + + +def test_systemone_d1_media(): + global server + server = ServerPreset.tinydecision("lfm3-d1-omni") + server.start() + image = get_img_url("IMG_BASE64_URI_0") + spoken = {"type": "noul", "instructions": {"type": "input_audio", "input_audio": {"data": get_wav_base64(), "format": "wav"}}} + + def decide(questions, images=[]): + res = server.make_request("POST", "/v1/systemone", data={"state": TEST_STATE, "questions": questions, "images": images}) + assert res.status_code == 200 + return res.body["answers"] + + # the questions are packed after the image + packed = decide(TEST_QUESTIONS, [image]) + for qid, question in TEST_QUESTIONS.items(): + assert_answers_close(packed[qid], decide({qid: question}, [image])[qid], 0.02) + + # a spoken question is heard where its text would be, the questions of the request are not packed + answers = decide({"angry": TEST_QUESTIONS["angry"], "spoken": spoken}) + assert list(answers.keys()) == ["angry", "spoken"] + assert 0.0 <= answers["spoken"]["noul"] <= 1.0 + assert_answers_close(answers["angry"], decide({"angry": TEST_QUESTIONS["angry"]})["angry"], 1e-6) + + +def test_systemone_d1_no_mmproj(): + global server + server = ServerPreset.tinydecision("lfm3-d1-omni") + server.no_mmproj = True + server.start() + spoken = {"type": "noul", "instructions": {"type": "input_audio", "input_audio": {"data": get_wav_base64(), "format": "wav"}}} + res = server.make_request("POST", "/v1/systemone", data={"state": TEST_STATE, "questions": {"spoken": spoken}}) + assert res.status_code == 400 + res = server.make_request("POST", "/v1/systemone", data={"state": TEST_STATE, "questions": TEST_QUESTIONS, "images": [get_img_url("IMG_BASE64_URI_0")]}) + assert res.status_code == 501 + + +@pytest.mark.parametrize("decision_type", GENERIC_TYPES) +def test_systemone_many_options(decision_type: str): + global server + server = ServerPreset.tinydecision(decision_type) + server.start() + # more than 26 options, the labels go past A..Z + criteria = {f"option {i}": None for i in range(30)} + res = server.make_request("POST", "/v1/systemone", data={ + "state": TEST_STATE, + "questions": {"q": {"type": "choice", "instructions": "Pick one.", "criteria": criteria}}, + }) + assert res.status_code == 200 + probs = res.body["answers"]["q"]["probabilities"] + assert sorted(probs.keys()) == sorted(criteria.keys()) + assert abs(sum(probs.values()) - 1.0) < 1e-4 + + +# a null state is accepted by the models that can decide about images only +NULL_STATE_TYPES = ["lfm3-d1", "lfm3-d1-omni", "lfm2-d1", "lfm2-d1-omni", "vllm-d3"] + + +@pytest.mark.parametrize("decision_type", GENERIC_TYPES) +def test_systemone_null_state(decision_type: str): + global server + server = ServerPreset.tinydecision(decision_type) + server.start() + res = server.make_request("POST", "/v1/systemone", data={ + "state": None, + "questions": {"angry": TEST_QUESTIONS["angry"]}, + "images": [get_img_url("IMG_BASE64_URI_0")], + }) + assert res.status_code == (200 if decision_type in NULL_STATE_TYPES else 400) + + +@pytest.mark.parametrize("decision_type", ["vllm-d3", "h2o-lightning"]) +def test_systemone_default_instructions(decision_type: str): + global server + server = ServerPreset.tinydecision(decision_type) + server.start() + # the template has a default question + res = server.make_request("POST", "/v1/systemone", data={ + "state": TEST_STATE, + "questions": {"q": {"type": "noul"}}, + }) + assert res.status_code == 200 + assert 0.0 <= res.body["answers"]["q"]["noul"] <= 1.0 + + +def test_systemone_h2o(): + global server + server = ServerPreset.tinydecision("h2o-lightning") + server.start() + + def decide(questions): + res = server.make_request("POST", "/v1/systemone", data={"state": TEST_STATE, "questions": questions}) + assert res.status_code == 200 + return res.body["answers"] + + # the type defaults to choice + assert decide({"q": {"criteria": {"a": None, "b": None}}})["q"]["type"] == "choice" + # a score can have a single level + assert list(decide({"q": {"type": "score", "criteria": ["only one"]}})["q"]["probabilities"].keys()) == ["0"] + # noul criteria can be described under "yes" and "no" + noul = {"type": "noul", "instructions": "Is the customer angry?"} + a = decide({"q": {**noul, "criteria": {"true": "very angry", "false": "calm"}}})["q"] + b = decide({"q": {**noul, "criteria": {"yes": "very angry", "no": "calm"}}})["q"] + assert abs(a["noul"] - b["noul"]) < 1e-6 + + +def test_systemone_lev(): + global server + server = ServerPreset.tinydecision("lev") + server.start() + + def usage(question): + res = server.make_request("POST", "/v1/systemone", data={"state": TEST_STATE, "questions": {"q": question}}) + assert res.status_code == 200 + return res.body["usage"]["input_tokens"] + + # a choice is evaluated with its options in 2 orders, to cancel the preference for the first label + choice = usage({"type": "choice", "instructions": "Is the customer angry?", "criteria": {"no": None, "yes": None}}) + noul = usage({"type": "noul", "instructions": "Is the customer angry?"}) + assert choice > 1.5 * noul + + +def test_systemone_kev_marker_in_text(): + global server + server = ServerPreset.tinydecision("kev") + server.start() + # the options are read at their <|box_end|> tokens, the same text in the request must stay text + res = server.make_request("POST", "/v1/systemone", data={ + "state": TEST_STATE + " <|box_end|>", + "questions": {"q": {"type": "choice", "instructions": "Pick <|box_end|> one.", "criteria": {"a<|box_end|>": None, "b": None}}}, + }) + assert res.status_code == 200 + assert list(res.body["answers"]["q"]["probabilities"].keys()) == ["a<|box_end|>", "b"] + + +def test_systemone_lfm2_d1_omni_media(): + global server + server = ServerPreset.tinydecision("lfm2-d1-omni") + server.start() + audio = {"type": "input_audio", "input_audio": {"data": get_wav_base64(), "format": "wav"}} + + def decide(state, images=[]): + return server.make_request("POST", "/v1/systemone", data={"state": state, "questions": TEST_QUESTIONS, "images": images}) + + res = decide([{"role": "user", "content": [audio, {"type": "text", "text": TEST_STATE}]}]) + assert res.status_code == 200 + assert list(res.body["answers"].keys()) == ["route", "urgency", "angry"] + # a request has images or one audio clip, not both + res = decide([{"role": "user", "content": [audio, {"type": "text", "text": TEST_STATE}]}], [get_img_url("IMG_BASE64_URI_0")]) + assert res.status_code == 400 + # spoken questions are only supported by lfm3-d1-omni, even if the model has audio input + res = server.make_request("POST", "/v1/systemone", data={"state": TEST_STATE, "questions": {"spoken": {"type": "noul", "instructions": audio}}}) + assert res.status_code == 400 + + +@pytest.mark.parametrize("data", [ + {"state": 123, "questions": {"angry": TEST_QUESTIONS["angry"]}}, + {"state": TEST_STATE, "questions": {"q": {"type": "noul", "instructions": ""}}}, + {"state": TEST_STATE, "questions": {"q": {"type": "choice", "instructions": "x", "criteria": {"a": None}}}}, + {"state": TEST_STATE, "questions": {"q": {"type": "choice", "instructions": "x", "criteria": {"a": 1, "b": 2}}}}, + {"state": TEST_STATE, "questions": {"q": {"type": "noul", "instructions": "x", "criteria": {"yes": "angry"}}}}, +]) +def test_systemone_vllm_decision2_strict(data: dict): + global server + server = ServerPreset.tinydecision("vllm-decision2") + server.start() + # the state, instructions and descriptions must be text, an object or an array + res = server.make_request("POST", "/v1/systemone", data=data) + assert res.status_code == 400 + + +def test_systemone_granite_switch_generate(): + global server + server = ServerPreset.tinydecision("granite-switch") + server.start() + # granite switch also generates text, the decision is one of its adapters + res = server.make_request("POST", "/completion", data={"prompt": "Once upon a time", "n_predict": 8}) + assert res.status_code == 200 + assert res.body["tokens_predicted"] > 0 + res = server.make_request("POST", "/v1/systemone", data={"state": TEST_STATE, "questions": TEST_QUESTIONS}) + assert res.status_code == 200 + + +def test_systemone_clef(): + global server + server = ServerPreset.tinydecision("clef") + server.start() + # all the questions are answered in one prompt by the joint head, the options of a choice are sorted by key + res = server.make_request("POST", "/v1/systemone", data={ + "state": TEST_STATE, + "questions": {"q": {"type": "choice", "instructions": "Pick one.", "criteria": {"b": None, "c": None, "a": None}}, "angry": TEST_QUESTIONS["angry"]}, + "images": [get_img_url("IMG_BASE64_URI_0")], + }) + assert res.status_code == 200 + assert list(res.body["answers"].keys()) == ["q", "angry"] + assert list(res.body["answers"]["q"]["probabilities"].keys()) == ["a", "b", "c"] + + +@pytest.mark.parametrize("n_images,questions,status", [ + (2, {"q": {"type": "choice", "criteria": {"0": None, "1": None}}}, 200), + (2, {"q": {"type": "noul"}}, 200), + (1, {"q": {"type": "noul"}}, 400), + (3, {"q": {"type": "noul"}}, 400), + (2, {"q": {"type": "noul"}, "r": {"type": "noul"}}, 400), + (2, {"q": {"type": "noul", "instructions": "x"}}, 400), + (2, {"q": {"type": "choice", "criteria": {"a": None, "b": None}}}, 400), + (2, {"q": {"type": "score", "criteria": ["a", "b"]}}, 400), +]) +def test_systemone_minicpm_ocr_jev(n_images: int, questions: dict, status: int): + global server + server = ServerPreset.tinydecision("openbmb-minicpm-ocr-jev") + server.start() + # is the OCR text (the state) consistent with the original image and the image rendered from the text + res = server.make_request("POST", "/v1/systemone", data={ + "state": "Invoice 42, total 12.50 EUR", + "questions": questions, + "images": [get_img_url("IMG_BASE64_URI_0")] * n_images, + }) + assert res.status_code == status + if status == 200: + answer = res.body["answers"]["q"] + if answer["type"] == "noul": + assert 0.0 <= answer["noul"] <= 1.0 + else: + assert abs(sum(answer["probabilities"].values()) - 1.0) < 1e-4 diff --git a/tools/server/tests/utils.py b/tools/server/tests/utils.py index f18b566aa879..6dbd540b94dc 100644 --- a/tools/server/tests/utils.py +++ b/tools/server/tests/utils.py @@ -5,6 +5,10 @@ import subprocess import os +import io +import math +import struct +import wave TMP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tmp") import re @@ -126,7 +130,7 @@ class ServerProcess: no_cache_idle_slots: bool = False log_path: str | None = None ui_mcp_proxy: bool = False - debug_proxy_allow_private: bool = False # test-only: lets the CORS proxy reach local servers + ui_mcp_proxy_allow_private_urls: bool = False media_allow_private_urls: bool = False allow_unauthenticated_tools: bool = False backend_sampling: bool = False @@ -155,8 +159,6 @@ def start(self, timeout_seconds: int = DEFAULT_HTTP_TIMEOUT) -> None: **os.environ, "LLAMA_SERVER_DEBUG_FAKE_TIMING": "1", } - if self.debug_proxy_allow_private: - env["LLAMA_SERVER_DEBUG_PROXY_ALLOW_PRIVATE"] = "1" if self.llama_cache is not None: env["LLAMA_CACHE"] = self.llama_cache elif "LLAMA_CACHE" not in os.environ: @@ -313,6 +315,8 @@ def start(self, timeout_seconds: int = DEFAULT_HTTP_TIMEOUT) -> None: server_args.append("--no-cache-idle-slots") if self.ui_mcp_proxy: server_args.append("--ui-mcp-proxy") + if self.ui_mcp_proxy_allow_private_urls: + server_args.append("--ui-mcp-proxy-allow-private-urls") if self.media_allow_private_urls: server_args.append("--media-allow-private-urls") if self.allow_unauthenticated_tools: @@ -562,6 +566,24 @@ def make_any_request( server_instances: Set[ServerProcess] = set() +# tiny decision models for the /v1/systemone tests, by decision type, see ServerPreset.tinydecision() +TINY_DECISION_MODELS = { + "lfm3-d1": "ggml-org-dev/tiny-d1-2B-for-testing-GGUF:Q4_0", + "lfm3-d1-omni": "ggml-org-dev/tiny-d1-Omni-2B-for-testing-GGUF:Q4_0", + "lfm2-d1": "ggml-org-dev/tiny-d1-3B-for-testing-GGUF:Q4_0", + "lfm2-d1-omni": "ggml-org-dev/tiny-d1-omni-600M-for-testing-GGUF:Q4_0", + "lev": "ggml-org-dev/tiny-lev-for-testing-GGUF:Q4_0", + "kev": "ggml-org-dev/tiny-kev-4b-for-testing-GGUF:Q4_0", + "nimble": "ggml-org-dev/tiny-Bespoke-Nimble-9B-v3-for-testing-GGUF:Q4_0", + "pplx-decider": "ggml-org-dev/tiny-pplx-decider-v1-27b-for-testing-GGUF:Q4_0", + "vllm-d3": "ggml-org-dev/tiny-d3-nano-for-testing-GGUF:Q4_0", + "h2o-lightning": "ggml-org-dev/tiny-h2o-lightning-4b-for-testing-GGUF:Q4_0", + "vllm-decision2": "ggml-org-dev/tiny-Decision-2.0-Kai-0.6B-for-testing-GGUF:Q4_0", + "granite-switch": "ggml-org-dev/tiny-granite-switch-4.1-8b-for-testing-GGUF:Q4_0", + "clef": "ggml-org-dev/tiny-clef-for-testing-GGUF:Q4_0", + "openbmb-minicpm-ocr-jev": "ggml-org-dev/tiny-MiniCPM-OCR-Jev-for-testing-GGUF:Q4_0", +} + class ServerPreset: @staticmethod @@ -570,8 +592,9 @@ def load_all() -> None: servers: List[ServerProcess] = [ method() for name, method in ServerPreset.__dict__.items() - if callable(method) and name != "load_all" + if callable(method) and name not in ("load_all", "tinydecision") ] + servers += [ServerPreset.tinydecision(decision_type) for decision_type in TINY_DECISION_MODELS] for server in servers: server.offline = False server.start() @@ -697,6 +720,21 @@ def tinyopenjev() -> ServerProcess: server.seed = 42 return server + @staticmethod + def tinydecision(decision_type: str) -> ServerProcess: + server = ServerProcess() + server.offline = True # will be downloaded by load_all() + # mmproj is already provided by HF registry API + server.model_hf_file = None + server.model_hf_repo = TINY_DECISION_MODELS[decision_type] + server.n_ctx = 4096 + # non-causal models: the whole prompt must fit in one ubatch + server.n_batch = 1024 + server.n_ubatch = 1024 + server.n_slots = 2 + server.seed = 42 + return server + @staticmethod def tinygemma3() -> ServerProcess: server = ServerProcess() @@ -726,6 +764,36 @@ def tinylfm3omni() -> ServerProcess: server.seed = 42 return server + @staticmethod + def tinypockettts() -> ServerProcess: + # tts only, with voice cloning + server = ServerProcess() + server.offline = True # will be downloaded by load_all() + # mmproj is already provided by HF registry API + server.model_hf_file = None + server.model_hf_repo = "ggml-org-dev/tinyPocketTTS-for-testing-gguf:Q8_0" + server.model_alias = "tinypockettts" + server.n_ctx = 1024 + server.n_batch = 512 + server.n_slots = 1 + server.seed = 42 + return server + + @staticmethod + def tinyvoxtralrt() -> ServerProcess: + # live transcription only, no chat + server = ServerProcess() + server.offline = True # will be downloaded by load_all() + # mmproj is already provided by HF registry API + server.model_hf_file = None + server.model_hf_repo = "ggml-org-dev/tinyVoxtral-Realtime-for-testing-gguf:Q8_0" + server.model_alias = "tinyvoxtralrt" + server.n_ctx = 1024 + server.n_batch = 512 + server.n_slots = 1 + server.seed = 42 + return server + @staticmethod def router() -> ServerProcess: server = ServerProcess() @@ -832,3 +900,24 @@ def get_lan_ip(server: ServerProcess) -> str | None: def is_slow_test_allowed(): return os.environ.get("SLOW_TESTS") == "1" or os.environ.get("SLOW_TESTS") == "ON" + + +# [TAG_MTMD_NO_REALLOC] TODO @ngxson : remove when mtmd side is fixed +def is_no_realloc(): + return os.environ.get("GGML_SCHED_NO_REALLOC") in ("1", "ON") or os.environ.get("GGML_SCHED_DEBUG_REALLOC", "0") != "0" + + +def make_pcm16(seconds: float = 1.0, rate: int = 16000, freq: float = 440.0) -> bytes: + """ sine tone as raw PCM16 mono samples """ + n = int(seconds * rate) + return struct.pack(f"<{n}h", *(int(0.3 * 32767 * math.sin(2 * math.pi * freq * i / rate)) for i in range(n))) + + +def make_wav(seconds: float = 1.0, rate: int = 16000, freq: float = 440.0) -> bytes: + buf = io.BytesIO() + with wave.open(buf, "wb") as w: + w.setnchannels(1) + w.setsampwidth(2) + w.setframerate(rate) + w.writeframes(make_pcm16(seconds, rate, freq)) + return buf.getvalue() diff --git a/tools/tts/tts.cpp b/tools/tts/tts.cpp index dbf618ac22f5..238cc828b097 100644 --- a/tools/tts/tts.cpp +++ b/tools/tts/tts.cpp @@ -86,8 +86,9 @@ int main(int argc, char ** argv) { } mtmd_context_params mtmd_params = mtmd_context_params_default(); - mtmd_params.use_gpu = params.mmproj_use_gpu; - mtmd_params.device = params.mmproj_device; + mtmd_params.use_gpu = params.mmproj_use_gpu; + mtmd_params.device = params.mmproj_device; + mtmd_params.n_threads = params.cpuparams.n_threads; mtmd::context_ptr mctx(mtmd_init_from_file(params.mmproj.path.c_str(), model, mtmd_params)); if (!mctx) { LOG_ERR("failed to load mmproj %s\n", params.mmproj.path.c_str()); diff --git a/ui/README.md b/ui/README.md index b70228d0de7c..0f210a40c80c 100644 --- a/ui/README.md +++ b/ui/README.md @@ -5,7 +5,8 @@ The UI of llama.cpp: the packages in `lib` and the apps built on them. ```text ui/ ├── lib/ -│ └── ui/ @ggml-org/llama-ui: design tokens, fonts, surfaces and components +│ ├── ui/ @ggml-org/llama-ui: design tokens, fonts, surfaces and components +│ └── voice/ @ggml-org/llama-voice: microphone capture, transcription and dictation └── apps/ └── chat/ Llama Chat, the chat app that llama-server serves ``` @@ -13,12 +14,15 @@ ui/ - [`lib/ui`](lib/ui/README.md) draws the parts and handles interaction, with no business logic. It is built with `@sveltejs/package` and published to npm as `@ggml-org/llama-ui`. Apps in this repo skip the package: they compile its sources as part of their own build, so they hold no copy of a component, a token or a font. +- [`lib/voice`](lib/voice/README.md) records the microphone and turns speech into text through llama-server, with no + UI: Llama UI draws the voice parts. It is plain TypeScript built with `tsc`, plus a Svelte entry + (`@ggml-org/llama-voice/svelte`). Apps in this repo compile its sources too. It is not published to npm yet. - [`apps/chat`](apps/chat/README.md) talks to llama-server, stores conversations and runs the agentic loop. 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`. +checking and testing `apps/chat` needs no install in `lib/ui` or `lib/voice`. ## Releases diff --git a/ui/apps/chat/.storybook/main.ts b/ui/apps/chat/.storybook/main.ts index 3e8c1a39d8dc..e2b8dad14377 100644 --- a/ui/apps/chat/.storybook/main.ts +++ b/ui/apps/chat/.storybook/main.ts @@ -16,7 +16,7 @@ const config: StorybookConfig = { '../tests/stories/**/*.stories.@(js|ts|svelte)', { directory: '../../../lib/ui/tests/stories', - files: '{foundations,components,app,models,mockups}/**/*.stories.svelte' + files: '{foundations,components,app,models,mockups,voice}/**/*.stories.svelte' } ], addons: [ diff --git a/ui/apps/chat/DESIGN.md b/ui/apps/chat/DESIGN.md index 971685e1bc51..efbc65d93685 100644 --- a/ui/apps/chat/DESIGN.md +++ b/ui/apps/chat/DESIGN.md @@ -38,35 +38,21 @@ colors: art-night-sky: 'oklch(0.33 0.07 256)' art-cinder: 'oklch(0.68 0.18 46)' art-cinder-light: 'oklch(0.85 0.065 46)' - cool-gray-50: 'oklch(0.958 0.002 250)' cool-gray-100: 'oklch(0.938 0.004 250)' cool-gray-200: 'oklch(0.91 0.005 250)' - cool-gray-300: 'oklch(0.86 0.007 250)' cool-gray-400: 'oklch(0.81 0.01 250)' - red-400: 'oklch(0.69 0.2 27)' red-450: 'oklch(0.635 0.229 28)' - red-500: 'oklch(0.6 0.235 27)' red-550: 'oklch(0.588 0.236 28)' red-600: 'oklch(0.55 0.22 27)' - red-800: 'oklch(0.43 0.17 27)' - yellow-300: 'oklch(0.9 0.14 84)' - yellow-400: 'oklch(0.85 0.17 84)' - yellow-800: 'oklch(0.5 0.1 84)' - green-400: 'oklch(0.81 0.16 148)' green-450: 'oklch(0.756 0.197 147)' - green-500: 'oklch(0.73 0.2 148)' green-550: 'oklch(0.669 0.197 147)' green-650: 'oklch(0.52 0.17 147)' - green-800: 'oklch(0.45 0.14 148)' amber-250: 'oklch(0.842 0.165 84)' amber-400: 'oklch(0.752 0.157 78)' amber-650: 'oklch(0.547 0.116 74)' - blue-400: 'oklch(0.7 0.163 255)' blue-450: 'oklch(0.67 0.173 256)' - blue-500: 'oklch(0.62 0.15 255)' blue-550: 'oklch(0.587 0.177 256)' blue-650: 'oklch(0.535 0.177 256)' - blue-800: 'oklch(0.42 0.11 255)' white-a2: 'oklch(1 0 0 / 0.02)' white-a4: 'oklch(1 0 0 / 0.04)' white-a6: 'oklch(1 0 0 / 0.06)' @@ -75,7 +61,6 @@ colors: white-a18: 'oklch(1 0 0 / 0.18)' white-a20: 'oklch(1 0 0 / 0.2)' white-a30: 'oklch(1 0 0 / 0.3)' - white-a40: 'oklch(1 0 0 / 0.4)' white-a50: 'oklch(1 0 0 / 0.5)' white-a85: 'oklch(1 0 0 / 0.85)' black-a3: 'oklch(0 0 0 / 0.03)' @@ -83,15 +68,8 @@ colors: black-a5: 'oklch(0 0 0 / 0.05)' black-a6: 'oklch(0 0 0 / 0.06)' black-a8: 'oklch(0 0 0 / 0.08)' - black-a10: 'oklch(0 0 0 / 0.1)' - black-a12: 'oklch(0 0 0 / 0.12)' - black-a18: 'oklch(0 0 0 / 0.18)' - black-a25: 'oklch(0 0 0 / 0.25)' - black-a30: 'oklch(0 0 0 / 0.3)' - black-a35: 'oklch(0 0 0 / 0.35)' black-a40: 'oklch(0 0 0 / 0.4)' black-a55: 'oklch(0 0 0 / 0.55)' - black-a60: 'oklch(0 0 0 / 0.6)' surface-page: '{colors.neutral-25}' surface-muted: '{colors.neutral-100}' surface-emphasis: '{colors.neutral-150}' @@ -103,6 +81,7 @@ colors: surface-code: '{colors.neutral-100}' surface-overlay: '{colors.black-a40}' fg-default: '{colors.neutral-950}' + fg-soft: 'color-mix(in oklch, {colors.fg-default} 70%, transparent)' fg-muted: '{colors.neutral-500}' fg-on-action: '{colors.neutral-50}' fg-on-danger: '{colors.neutral-0}' @@ -128,39 +107,21 @@ colors: line-warning-soft: 'color-mix(in oklab, {colors.fill-warning} 34%, {colors.line-default})' line-danger-soft: 'color-mix(in oklab, {colors.fill-danger} 34%, {colors.line-default})' line-info-soft: 'color-mix(in oklab, {colors.fill-info} 34%, {colors.line-default})' - edge-rest-side: '{colors.cool-gray-200}' - edge-rest-mid: '{colors.cool-gray-100}' - edge-focus-side: '{colors.cool-gray-400}' - edge-focus-mid: '{colors.cool-gray-300}' - edge-ambient-side: '{colors.cool-gray-100}' - edge-ambient-mid: '{colors.cool-gray-50}' - edge-faint: '{colors.cool-gray-100}' + edge-rest: '{colors.cool-gray-200}' + edge-focus: '{colors.cool-gray-400}' + edge-ambient: '{colors.cool-gray-100}' edge-raised: '{colors.cool-gray-200}' action-primary: '{colors.neutral-900}' - action-primary-hover: 'oklch(0.205 0 0 / 0.9)' + action-primary-hover: 'color-mix(in oklch, {colors.action-primary} 90%, transparent)' action-danger: '{colors.fill-danger}' - action-danger-hover: 'color-mix(in oklch, {colors.fill-danger} 90%, transparent)' + action-danger-hover: 'color-mix(in oklch, {colors.action-danger} 90%, transparent)' action-quiet: 'oklch(0.97 0 0 / 0.3)' action-quiet-hover: '{colors.neutral-100}' action-ghost-hover: 'oklch(0.556 0 0 / 0.1)' field-background: '{colors.neutral-0}' - field-shade: '{colors.black-a6}' - status-danger: '{colors.fill-danger}' - status-danger-rim: '{colors.red-400}' - status-danger-glyph: '{colors.red-800}' - status-warning: '{colors.fill-warning}' - status-warning-rim: '{colors.yellow-300}' - status-warning-glyph: '{colors.yellow-800}' - status-success: '{colors.fill-success}' - status-success-rim: '{colors.green-400}' - status-success-glyph: '{colors.green-800}' - status-info: '{colors.fill-info}' - status-info-rim: '{colors.blue-400}' - status-info-glyph: '{colors.blue-800}' highlight-inner: '{colors.white-a50}' highlight-inverse: '{colors.white-a12}' sheen-start: '{colors.white-a20}' - sheen-end: 'transparent' elevation-ring: '{colors.black-a5}' surface-page-matte: '{colors.neutral-0}' surface-glass-matte: 'oklch(0.97 0 0 / 0.6)' @@ -180,13 +141,14 @@ colors: surface-glass-dark: 'oklch(0.269 0 0 / 0.75)' surface-code-dark: '{colors.neutral-900}' fg-default-dark: '{colors.neutral-50}' + fg-soft-dark: 'color-mix(in oklch, {colors.fg-default-dark} 70%, transparent)' fg-muted-dark: '{colors.neutral-400}' fg-on-action-dark: '{colors.neutral-900}' fg-code-dark: '{colors.neutral-300}' - fg-danger-dark: '{colors.red-450}' - fg-success-dark: '{colors.green-450}' - fg-warning-dark: '{colors.amber-250}' - fg-info-dark: '{colors.blue-400}' + fg-danger-dark: '{colors.fill-danger-dark}' + fg-success-dark: '{colors.fill-success-dark}' + fg-warning-dark: '{colors.fill-warning-dark}' + fg-info-dark: '{colors.fill-info-dark}' line-default-dark: '{colors.white-a30}' line-field-dark: '{colors.white-a30}' line-control-dark: '{colors.white-a12}' @@ -204,27 +166,18 @@ colors: line-warning-soft-dark: 'color-mix(in oklab, {colors.fill-warning-dark} 38%, {colors.line-default-dark})' line-danger-soft-dark: 'color-mix(in oklab, {colors.fill-danger-dark} 38%, {colors.line-default-dark})' line-info-soft-dark: 'color-mix(in oklab, {colors.fill-info-dark} 38%, {colors.line-default-dark})' - edge-rest-side-dark: '{colors.white-a6}' - edge-rest-mid-dark: '{colors.white-a4}' - edge-focus-side-dark: '{colors.white-a18}' - edge-focus-mid-dark: '{colors.white-a12}' - edge-ambient-side-dark: '{colors.white-a4}' - edge-ambient-mid-dark: '{colors.white-a2}' - edge-faint-dark: '{colors.white-a4}' + edge-rest-dark: '{colors.white-a6}' + edge-focus-dark: '{colors.white-a18}' + edge-ambient-dark: '{colors.white-a4}' edge-raised-dark: '{colors.white-a9}' action-primary-dark: '{colors.neutral-200}' - action-primary-hover-dark: 'oklch(0.922 0 0 / 0.9)' + action-primary-hover-dark: 'color-mix(in oklch, {colors.action-primary-dark} 90%, transparent)' action-danger-dark: 'color-mix(in oklch, {colors.fill-danger-dark} 58%, transparent)' action-danger-hover-dark: 'color-mix(in oklch, {colors.fill-danger-dark} 68%, transparent)' action-quiet-dark: 'oklch(0.708 0 0 / 0.15)' action-quiet-hover-dark: 'oklch(0.708 0 0 / 0.25)' action-ghost-hover-dark: 'oklch(0.708 0 0 / 0.1)' field-background-dark: '{colors.white-a9}' - field-shade-dark: '{colors.black-a30}' - status-danger-dark: '{colors.fill-danger-dark}' - status-warning-dark: '{colors.fill-warning-dark}' - status-success-dark: '{colors.fill-success-dark}' - status-info-dark: '{colors.fill-info-dark}' highlight-inner-dark: '{colors.white-a4}' sheen-start-dark: '{colors.white-a2}' elevation-ring-dark: '{colors.white-a18}' @@ -254,6 +207,11 @@ typography: fontSize: 0.75rem fontWeight: 400 lineHeight: 1rem + caption-sm: + fontFamily: 'Llama Sans' + fontSize: 0.625rem + fontWeight: 400 + lineHeight: 0.875rem title: fontFamily: 'Llama Sans' fontSize: 1.125rem @@ -264,18 +222,24 @@ typography: fontSize: 1.5rem fontWeight: 600 lineHeight: 2rem + display: + fontFamily: 'Llama Sans' + fontSize: 1.875rem + fontWeight: 600 + lineHeight: 2.25rem code: fontFamily: 'Llama Mono' fontSize: 0.875rem fontWeight: 400 lineHeight: 1.25rem rounded: - control: 0.5rem - panel: 0.625rem - card: 0.875rem - container: 1rem - surface: 1.5rem - surface-lg: 2rem + sm: 6px + md: 8px + lg: 10px + xl: 14px + 2xl: 16px + 3xl: 24px + 4xl: 32px full: 9999px spacing: xs: 4px @@ -288,7 +252,7 @@ components: chat-form: backgroundColor: '#f9f9f9' textColor: '{colors.fg-default}' - rounded: '{rounded.surface}' + rounded: '{rounded.3xl}' typography: '{typography.body}' chat-form-dark: backgroundColor: '#202020' @@ -298,47 +262,47 @@ components: chat-form-placeholder-dark: textColor: '{colors.fg-muted-dark}' chat-form-edge: - backgroundColor: '{colors.edge-rest-side}' + backgroundColor: '{colors.edge-rest}' chat-form-edge-dark: - backgroundColor: '{colors.edge-rest-side-dark}' + backgroundColor: '{colors.edge-rest-dark}' chat-form-edge-focus: - backgroundColor: '{colors.edge-focus-side}' + backgroundColor: '{colors.edge-focus}' chat-form-edge-focus-dark: - backgroundColor: '{colors.edge-focus-side-dark}' + backgroundColor: '{colors.edge-focus-dark}' card: backgroundColor: '#f9f9f9' textColor: '{colors.fg-default}' - rounded: '{rounded.card}' + rounded: '{rounded.xl}' padding: '24px' card-dark: backgroundColor: '#202020' textColor: '{colors.fg-default-dark}' card-edge: - backgroundColor: '{colors.edge-rest-side}' + backgroundColor: '{colors.edge-rest}' card-edge-dark: - backgroundColor: '{colors.edge-rest-side-dark}' + backgroundColor: '{colors.edge-rest-dark}' sidebar: backgroundColor: '#f9f9f9' textColor: '{colors.fg-default}' - rounded: '{rounded.container}' + rounded: '{rounded.2xl}' sidebar-dark: backgroundColor: '#1c1c1c' textColor: '{colors.fg-default-dark}' sidebar-edge: - backgroundColor: '{colors.edge-ambient-side}' + backgroundColor: '{colors.edge-ambient}' sidebar-edge-dark: - backgroundColor: '{colors.edge-ambient-side-dark}' + backgroundColor: '{colors.edge-ambient-dark}' inset-group: backgroundColor: 'oklch(1 0 0 / 0.85)' textColor: '{colors.fg-default}' - rounded: '{rounded.card}' + rounded: '{rounded.xl}' inset-group-dark: backgroundColor: 'oklch(0.985 0 0 / 0.03)' textColor: '{colors.fg-default-dark}' inset-group-edge: - backgroundColor: '{colors.edge-ambient-side}' + backgroundColor: '{colors.edge-ambient}' inset-group-edge-dark: - backgroundColor: '{colors.edge-ambient-side-dark}' + backgroundColor: '{colors.edge-ambient-dark}' selected-row: backgroundColor: 'oklch(0.145 0 0 / 0.05)' textColor: '{colors.fg-default}' @@ -348,19 +312,19 @@ components: user-bubble: backgroundColor: '#f3f3f3' textColor: '{colors.fg-default}' - rounded: '{rounded.surface}' + rounded: '{rounded.2xl}' typography: '{typography.body}' user-bubble-dark: backgroundColor: '#181818' textColor: '{colors.fg-default-dark}' user-bubble-edge: - backgroundColor: '{colors.edge-faint}' + backgroundColor: '{colors.edge-ambient}' user-bubble-edge-dark: - backgroundColor: '{colors.edge-faint-dark}' + backgroundColor: '{colors.edge-ambient-dark}' floating-panel: backgroundColor: '#ffffff' textColor: '{colors.fg-default}' - rounded: '{rounded.panel}' + rounded: '{rounded.lg}' typography: '{typography.body-sm}' floating-panel-dark: backgroundColor: '#161616' @@ -376,14 +340,14 @@ components: dialog: backgroundColor: '#ffffff' textColor: '{colors.fg-default}' - rounded: '{rounded.panel}' + rounded: '{rounded.lg}' dialog-dark: backgroundColor: '#0d0d0d' textColor: '{colors.fg-default-dark}' tooltip: backgroundColor: '{colors.action-primary}' textColor: '{colors.fg-on-action}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.caption}' tooltip-dark: backgroundColor: '{colors.action-primary-dark}' @@ -391,7 +355,7 @@ components: button-primary: backgroundColor: '{colors.action-primary}' textColor: '{colors.fg-on-action}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label}' height: '36px' button-primary-dark: @@ -406,7 +370,7 @@ components: button-secondary: backgroundColor: '#f9f9f9' textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label}' height: '36px' button-secondary-dark: @@ -425,7 +389,7 @@ components: button-tertiary: backgroundColor: '#fcfcfc' textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label}' height: '36px' button-tertiary-dark: @@ -444,7 +408,7 @@ components: button-outline: backgroundColor: '{colors.field-background}' textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label}' height: '36px' button-outline-dark: @@ -462,7 +426,7 @@ components: textColor: '{colors.fg-default-dark}' button-ghost: textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label}' button-ghost-dark: textColor: '{colors.fg-default-dark}' @@ -475,7 +439,7 @@ components: button-destructive: backgroundColor: '{colors.action-danger}' textColor: '{colors.fg-on-danger}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label}' height: '36px' button-destructive-dark: @@ -490,7 +454,7 @@ components: toggle-on: backgroundColor: '{colors.surface-selected}' textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label}' height: '36px' toggle-on-dark: @@ -505,7 +469,7 @@ components: toggle-group: backgroundColor: '#f9f9f9' textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label}' height: '32px' toggle-group-dark: @@ -533,7 +497,7 @@ components: textColor: '{colors.fg-default-dark}' tabs-list: backgroundColor: '{colors.surface-muted}' - rounded: '{rounded.panel}' + rounded: '{rounded.lg}' height: '36px' padding: '2px' tabs-list-dark: @@ -541,7 +505,7 @@ components: tabs-trigger: backgroundColor: '{colors.surface-muted}' textColor: 'oklch(0.145 0 0 / 0.7)' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label}' tabs-trigger-dark: backgroundColor: '{colors.surface-muted-dark}' @@ -582,7 +546,7 @@ components: input: backgroundColor: '{colors.field-background}' textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.body-sm}' height: '36px' input-dark: @@ -607,7 +571,7 @@ components: badge-default: backgroundColor: '{colors.action-primary}' textColor: '{colors.fg-on-action}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label-sm}' padding: '2px 8px' badge-default-dark: @@ -616,14 +580,14 @@ components: badge-secondary: backgroundColor: '#dadada' textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label-sm}' badge-secondary-dark: backgroundColor: '#252525' textColor: '{colors.fg-default-dark}' badge-outline: textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label-sm}' badge-outline-dark: textColor: '{colors.fg-default-dark}' @@ -634,7 +598,7 @@ components: badge-destructive: backgroundColor: '{colors.action-danger}' textColor: '{colors.fg-on-danger}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label-sm}' badge-destructive-dark: backgroundColor: '#952420' @@ -642,7 +606,7 @@ components: badge-success: backgroundColor: '{colors.surface-success}' textColor: '{colors.fg-success}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label-sm}' badge-success-dark: backgroundColor: '{colors.surface-success-dark}' @@ -650,7 +614,7 @@ components: badge-warning: backgroundColor: '{colors.surface-warning}' textColor: '{colors.fg-warning}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label-sm}' badge-warning-dark: backgroundColor: '{colors.surface-warning-dark}' @@ -658,7 +622,7 @@ components: badge-danger: backgroundColor: '{colors.surface-danger}' textColor: '{colors.fg-danger}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label-sm}' badge-danger-dark: backgroundColor: '{colors.surface-danger-dark}' @@ -666,7 +630,7 @@ components: badge-info: backgroundColor: '{colors.surface-info}' textColor: '{colors.fg-info}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' typography: '{typography.label-sm}' badge-info-dark: backgroundColor: '{colors.surface-info-dark}' @@ -674,7 +638,7 @@ components: code-block: backgroundColor: '{colors.surface-code}' textColor: '{colors.fg-code}' - rounded: '{rounded.panel}' + rounded: '{rounded.lg}' typography: '{typography.code}' code-block-dark: backgroundColor: '{colors.surface-code-dark}' @@ -684,21 +648,21 @@ components: list-row-selected: backgroundColor: '{colors.surface-selected}' textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' list-row-selected-dark: backgroundColor: '{colors.surface-selected-dark}' textColor: '{colors.fg-default-dark}' panel-muted: backgroundColor: '{colors.surface-muted}' textColor: '{colors.fg-default}' - rounded: '{rounded.panel}' + rounded: '{rounded.lg}' panel-muted-dark: backgroundColor: '{colors.surface-muted-dark}' textColor: '{colors.fg-default-dark}' chip-emphasis: backgroundColor: '{colors.surface-emphasis}' textColor: '{colors.fg-default}' - rounded: '{rounded.control}' + rounded: '{rounded.md}' chip-emphasis-dark: backgroundColor: '{colors.surface-emphasis-dark}' textColor: '{colors.fg-default-dark}' @@ -708,22 +672,6 @@ components: page-dark: backgroundColor: '{colors.surface-page-dark}' textColor: '{colors.fg-default-dark}' - chat-form-edge-mid: - backgroundColor: '{colors.edge-rest-mid}' - chat-form-edge-mid-dark: - backgroundColor: '{colors.edge-rest-mid-dark}' - chat-form-edge-mid-focus: - backgroundColor: '{colors.edge-focus-mid}' - chat-form-edge-mid-focus-dark: - backgroundColor: '{colors.edge-focus-mid-dark}' - sidebar-edge-mid: - backgroundColor: '{colors.edge-ambient-mid}' - sidebar-edge-mid-dark: - backgroundColor: '{colors.edge-ambient-mid-dark}' - inset-group-edge-mid: - backgroundColor: '{colors.edge-ambient-mid}' - inset-group-edge-mid-dark: - backgroundColor: '{colors.edge-ambient-mid-dark}' glass-highlight: backgroundColor: '{colors.highlight-inner}' glass-highlight-dark: @@ -734,33 +682,61 @@ components: backgroundColor: '{colors.sheen-start}' user-bubble-sheen-dark: backgroundColor: '{colors.sheen-start-dark}' - field-shade: - backgroundColor: '{colors.field-shade}' - field-shade-dark: - backgroundColor: '{colors.field-shade-dark}' - status-lamp-danger-rim: - backgroundColor: '{colors.status-danger-rim}' - status-lamp-warning-rim: - backgroundColor: '{colors.status-warning-rim}' - status-lamp-success-rim: - backgroundColor: '{colors.status-success-rim}' status-lamp-danger: - backgroundColor: '{colors.status-danger}' - textColor: '{colors.status-danger-glyph}' + backgroundColor: '{colors.fill-danger}' rounded: '{rounded.full}' size: '8px' status-lamp-warning: - backgroundColor: '{colors.status-warning}' - textColor: '{colors.status-warning-glyph}' + backgroundColor: '{colors.fill-warning}' rounded: '{rounded.full}' size: '8px' status-lamp-success: - backgroundColor: '{colors.status-success}' - textColor: '{colors.status-success-glyph}' + backgroundColor: '{colors.fill-success}' rounded: '{rounded.full}' size: '8px' --- +## In short + +The rules most changes need. The sections below hold the detail and the reasons, and they +win where this list is too short. Before adding a token, a size or a component, use what is +here; if something really is missing, add it here first. + +- **Components:** take base components from Llama UI (`@ggml-org/llama-ui/ui/`); do not + build a new one when an existing one fits. Style them through their variants + (`variant="outline"`, `size="sm"`), not by overriding classes. +- **Colour:** greys build the UI; colour is for meaning only (status, destructive actions, + focus). Neutral colours go by shadcn's utility names (`bg-background`, `bg-muted`, `bg-card`, + `text-foreground`, `text-muted-foreground`, `border-border`), status by `bg-surface-*`, + `bg-fill-*`, `text-fg-*` and `border-line-*-soft` of `success`, `warning`, `danger` and + `info`, and any other semantic token as `bg-(--surface-lifted)`. In CSS, read the semantic + token (`var(--surface-page)`). No Tailwind palette classes, no hex. +- **Type:** Llama Sans, and Llama Mono for code, through roles: `text-body` (16px) for chat + messages and the chat input, `text-body-sm` (14px) for most text, `text-label` (14px, medium) + for buttons and labels, `text-label-sm` and `text-caption` (12px) for badges and hints, + `text-caption-sm` (10px) for tags and counts, `text-title` (18px) and `text-heading` (24px) + for the rare heading, `text-display` (30px) for the biggest headline. Never Tailwind's own sizes (`text-sm`, `text-xs`) or a size in + brackets. +- **Shape:** one corner scale, `rounded-sm` to `rounded-4xl`: `rounded-md` (8px) for controls, + fields and badges, `rounded-lg` (10px) for menus and dialogs, `rounded-xl` (14px) for cards, + `rounded-2xl` (16px) and `rounded-3xl` (24px) for the larger surfaces, `rounded-full` for + pills, avatars and lamps. +- **Sizes:** Tailwind's 4px spacing scale. Icons are Lucide, `size-icon-md` (16px), or + `size-icon-sm` (14px) in compact controls. Controls are `h-control-sm`, `h-control-md` or + `h-control-lg` (32, 36, 40px). +- **Surfaces:** one surface utility per element (`card-surface`, `matte-float`, `matte-key`, + `matte-well`), never raw `shadow-*`, `border-*` and `backdrop-blur-*` combinations. +- **Tokens:** read a semantic token directly. A component token is only for a value the + component decides itself. A value that follows from another token is mixed from it, not + picked again. +- **No arbitrary values** (`text-[11px]`, `rounded-[1.125rem]`, `p-[7px]`, `z-[20]`): pick the + nearest from the scale (`z-20`, `max-w-4/5`, `min-w-32`). Brackets are for what no scale can + hold: a `calc()`, a grid template, a list of transition properties. +- **Motion:** `ease-out-quint` for what enters or answers a press, `ease-sheet` for a sheet + or a page that slides. +- **Phones:** every dialog is full screen; only alerts stay small and centred. +- **The conversation is the loudest thing on screen;** everything around it stays quiet. + ## Overview **Llama UI** is the design system and component library this file describes. **Llama Chat**, @@ -793,7 +769,7 @@ This file is the how, written for agents first. Its principles, as rules to appl - **Colour has one job.** Greys build everything; status colours show status and nothing else; art colours and cinder are for artwork and the odd brand detail, never for the UI's controls. - **Recognisable, easy to change.** Keep the character in the icon, the type and one - accent, so an app built on Llama UI can restyle it through component tokens alone. + accent, so an app built on Llama UI can restyle it through semantic and component tokens alone. - **Design lives in code.** The CSS is the source of truth; prefer what is generated or derived over hand-tuned values, and record the reason next to the value. Content pages are Markdown with Svelte components in them, as `.svx` (see `AGENTS.md`). @@ -802,18 +778,35 @@ This file is the how, written for agents first. Its principles, as rules to appl Design tokens come in three tiers, each in its own file under `ui/lib/ui/src/lib/styles/tokens/`: -1. **Primitives** (`primitives.css`): raw values named by what they are, such as - `neutral-900`, `cool-gray-200`, `red-500`, `white-a30`, `font-size-14` or `length-24`. - Only semantic tokens point at them. +1. **Primitives** (`primitives.css`): raw colours named by what they are, such as + `neutral-900`, `cool-gray-200`, `red-550` or `white-a30`. Only semantic tokens point at + them. Sizes are not primitives: a role holds its own value, and spacing is Tailwind's 4px + grid. 2. **Semantic tokens** (`semantic.css`): named by purpose, such as `surface-glass`, - `fg-muted`, `line-field`, `edge-focus-side`, `action-primary` or `status-warning`. They - point at primitives and are the only tier that changes between light and dark. The type, - corner, icon size and control height roles live here too and are Tailwind utilities: - `text-label`, `rounded-control`, `size-icon-md`, `h-control-md`. -3. **Component tokens** (`components.css`): one group per component, named - `[component]-[variant]-[property]-[state]`, such as `chat-form-edge-side-focus` or - `button-secondary-background-hover`. They point at semantic tokens, and components read - them as `bg-(--button-primary-background)` and similar. + `fg-muted`, `line-field`, `edge-focus`, `action-primary` or `fill-warning`, and the only + tier that changes between light and dark. Each is either a pick, which names a primitive + per theme, or a derivation, which is mixed from another semantic token by a fixed rule and + so follows it through every theme with a single declaration: + - soft text is the text colour at 70% (`fg-soft`); + - a hover fill is the fill at 90% (`action-primary-hover`); + - a status surface is its fill mixed into the page, and a status line its fill mixed into + the default line, by a share the theme sets (11% and 34% in light, 16% and 38% in dark); + - a dark shadow is the light one, `elevation-strength` (1 in light, 5 in dark) times as + dense; + - the middle of a matte edge is its side at two thirds, and a lamp's rim and glyph are + its fill mixed 30% towards white and towards black (both in `surfaces.css`). + + The type, icon size and control height roles live here too and are Tailwind utilities: + `text-label`, `size-icon-md`, `h-control-md`. Corners are Tailwind's own `rounded-sm` to + `rounded-4xl`, computed from `--radius` in `theme.css`. shadcn's + colour names (`background`, `muted-foreground`, `border` ...) exist as Tailwind utilities + only, each mapped to a semantic token in `theme.css`. + +3. **Component tokens** (`components.css`): only what a component decides itself, named + `[component]-[variant]-[property]-[state]`, such as `button-secondary-background-hover` or + `float-panel-background-modal`: a value no semantic token has, or one that only this + component changes between themes. A component that takes a semantic token as it is reads + the semantic token, as `bg-(--action-primary)` and similar, and gets no alias here. The front matter's `colors`, `typography` and `rounded` are generated from the primitives, the semantic tokens and the font stacks by `npm run design:tokens` in `ui/apps/chat`, and CI fails @@ -860,16 +853,18 @@ the Surface switch in Storybook's toolbar, and only its surface tokens differ: ` `surface-raised` for menus and dialogs, `surface-lifted` for a selection raised on a recessed track, `surface-pressed` for a key pressed in, `surface-glass` for the translucent matte fill, `surface-code` for code and `surface-overlay` behind dialogs. -- **Foreground:** `fg-default` and `fg-muted` for text and icons, `fg-on-action` and +- **Foreground:** `fg-default` and `fg-muted` for text and icons, `fg-soft` (the text colour + at 70%) for the label of an option that is not the picked one, `fg-on-action` and `fg-on-danger` on filled buttons, `fg-code` for code, `fg-danger` for errors, `fg-success` for confirmations such as a copied check, `fg-warning` for cautions and `fg-info` for neutral notices. - **Lines:** `line-default` for dividers, `line-control` for outlined controls (soft in dark mode), `line-field` for inputs, `line-focus` for focus and `line-danger` for invalid fields. -- **Edges:** the hairlines of matte surfaces, darker at the sides than in the middle. - `edge-rest-*` at rest, `edge-focus-*` when focus is inside, `edge-ambient-*` for large - quiet containers whose edge never changes, `edge-faint` for the user bubble and - `edge-raised` for floating panels. +- **Edges:** the hairlines of matte surfaces, darker at the sides than in the middle (the + token is the side; the surface fades it to two thirds in the middle). `edge-rest` at rest, + `edge-focus` when focus is inside, `edge-ambient` for large quiet containers whose edge + never changes and, kept even all round, for the user bubble, and `edge-raised` for floating + panels. - **Actions:** `action-primary` (near black in light mode, near white in dark mode) and its hover, `action-danger` and its hover, and `action-ghost-hover`. - **Status fills:** `fill-success`, `fill-warning`, `fill-danger` and `fill-info` are each @@ -880,9 +875,9 @@ the Surface switch in Storybook's toolbar, and only its surface tokens differ: ` `surface-info` are soft tints of each status fill for alerts and soft badges, with `line-*-soft` hairlines to match. They are mixed in oklab so the hue holds over the page. Soft status badges are pills with a small dot in the status fill before the label. -- **Status:** `status-danger`, `status-warning`, `status-success` and `status-info` are the - lamp fills for error or stopped, loading or warning, ready or connected, and informational. They take the status - fills, and each has a lighter `-rim` and a darker `-glyph`. Known gap: the glyph on the red lamp +- **Status:** `fill-danger`, `fill-warning`, `fill-success` and `fill-info` are the + lamp fills for error or stopped, loading or warning, ready or connected, and informational. A lamp adds + a lighter rim and a darker glyph, both mixed from its fill. Known gap: the glyph on the red lamp reaches only about 2:1 and on the green lamp about 3.2:1, below WCAG AA, so the lamp colour must never be the only signal; pair it with a label or tooltip. @@ -895,14 +890,21 @@ is one variable font with an optical size axis: the browser sets it from the fon looser Small one, with a blend in between. Nothing needs choosing per element; pin a point only to show it, with `font-variation-settings: 'opsz' 16` or `36`. Its line box is 1.25 at every size, centred on the cap height; large headings set `line-height: 1.15` themselves. Llama Mono keeps every character, -its coding ligatures included, in one cell, so code and numbers line up in columns. Type is set through roles that fix size, line height and weight together: +its coding ligatures included, in one cell, so code and numbers line up in columns. Type is set through roles that fix size and line height together, and for labels and headings the weight too: -- `body` (16/24, 400): chat messages and the chat input. -- `body-sm` (14/20, 400): most text, fields and lists. +- `body` (16/24): chat messages and the chat input. +- `body-sm` (14/20): most text, fields and lists. - `label` (14/20, 500): buttons and field labels. - `label-sm` (12/16, 500): badges and compact labels. -- `caption` (12/16, 400): tooltips, hints and metadata. -- `title` (18/28, 600) and `heading` (24/32, 600): rare headings; there is no display size. +- `caption` (12/16): tooltips, hints and metadata. +- `caption-sm` (10/14): the smallest text, for tags, compact badges and counts. +- `title` (18/28, 600) and `heading` (24/32, 600): rare headings. +- `display` (30/36, 600): the biggest headline, such as the greeting on a new chat. + +Body and caption text takes the weight around it, regular unless a parent says otherwise; add +a weight class for anything else (`text-body-sm font-semibold`). The roles are the whole +scale: no `text-sm` or `text-xs`, and no size in brackets. On a phone a row that needs larger +text takes the next role up (`text-body-sm max-md:text-body`). When a component lets callers override the size, keep an explicit weight class next to the role (`text-label font-medium`) so a size override does not drop the weight. Placeholders @@ -978,8 +980,8 @@ matches the role of the surface instead of combining raw shadows. - **`matte-float`** and **`matte-float-modal`:** menus, popovers, select lists, hover cards and drawers, and dialogs over the page colour. An 86% opaque panel with blur, a faint edge, a rim and a deeper shadow. The edge is a hairline ring baked into the shadow as its last - layer (`float-panel-edge`). The panel's 1px border is its rim, the inner highlight - (`float-panel-highlight`) right inside the ring; an inset shadow for the rim would sit inside + layer (`edge-raised`). The panel's 1px border is its rim, the inner highlight + (`highlight-inner`) right inside the ring; an inset shadow for the rim would sit inside the border instead, and the 1px between the two would draw a double edge. In light mode dialogs are solid white instead: over the dimmed page a translucent white turns grey. - **`matte-key`:** buttons, selects, toggles and tabs. The matte finish: on top of the @@ -991,12 +993,12 @@ matches the role of the surface instead of combining raw shadows. (`--key-sheen-solid`), the same blur, and an even 1px hairline in a shade of the fill drawn inside the button (`--key-edge`), so the width does not change. The danger key stays matte glass rather than metal: its sheen is almost none (`--button-danger-sheen`), and in dark mode - it is a frosted, translucent red (`red-500` at 58%) whose edge is a soft tint of the red, never + it is a frosted, translucent red (`fill-danger` at 58%) whose edge is a soft tint of the red, never a lighter rim. - **`elevated-control`**, **`elevated-surface`** and **`elevated-raised`:** cards, floating bars and thumbnails. An elevation token with a hairline ring baked in as its last layer, so the edge melts into the shadow and the shadow deepens in dark mode. The ring is - `--elevation-ring` (black 5%, white 18% in dark) at `--elevation-ring-width` (1px). They + `--elevation-ring` (black 5%, white 18% in dark), 1px wide. They replace a border plus a shadow; never add a border to them. - **`matte-well`:** inputs, textareas and checkboxes. A shallow inset shade so fields read as recessed. @@ -1007,16 +1009,16 @@ matches the role of the surface instead of combining raw shadows. an even hairline, with no glow. The elevation tokens are `elevation-surface`, `elevation-control`, `elevation-raised`, -`elevation-inset` and `elevation-tooltip`. The drop shadows are smooth stacks: a few soft +`elevation-inset` and `elevation-pressed`; a tooltip takes `elevation-surface`. The drop shadows are smooth stacks: a few soft layers instead of one hard one, the closest the darkest and smallest, each further layer about twice the offset and blur and fainter, the far ones pulled in with a negative spread, so the -shadow fades out instead of ending in a visible edge. They stay as close as upstream's -Tailwind shadows: `elevation-surface` reaches about 20px, like `shadow-lg`, `elevation-raised` -about 38px, like `shadow-xl`, and `elevation-control` is three tight layers reaching no further -than 4px, so buttons and other controls sit close to the page. Two softer steps sit below them: `elevation-soft` for the chat form, +shadow fades out instead of ending in a visible edge. They are the only shadows: Tailwind's +own `shadow-sm` to `shadow-2xl` do not follow the theme and are not used. `elevation-surface` +reaches about 20px, `elevation-raised` about 38px, and `elevation-control` is three tight +layers reaching no further than 4px, so buttons and other controls sit close to the page. Two softer steps sit below them: `elevation-soft` for the chat form, which floats only a little, and `elevation-faint` for the user message bubble, which barely -lifts. The keys inside the chat form, the add key and the model selector, take `elevation-key` -(`--chat-form-key-shadow`): a 0.5px hairline all round and a 1px drop, since the control elevation's soft +lifts. The keys inside the chat form, the add key and the model selector, take `elevation-key`: +a 0.5px hairline all round and a 1px drop, since the control elevation's soft spread blends into the white form; in dark it is the control elevation. Dark mode deepens the same stacks. Tailwind's own `shadow-xs` to `shadow-2xl` are built the same way (`tokens/semantic.css`), each reaching about as far as Tailwind's default for it. Every @@ -1025,11 +1027,12 @@ with a 2px blur. ## Shapes -Corners are soft and consistent, set through roles: `control` (8px) for buttons, fields and -badges, `panel` (10px) for menus and dialogs, `card` (14px) for cards, `container` (16px) for -the sidebar, and `surface` (24px) for the chat form and message bubbles, rising to -`surface-lg` (32px) for the chat form on small screens. Status lamps, avatars and the round -icon buttons in the chat form are fully round. +Corners are soft and consistent, on one scale that is computed from a single base radius +(`--radius`, 10px, in `theme.css`), so changing the base moves every corner with it: `sm` +(6px) for small marks and chips, `md` (8px) for buttons, fields and badges, `lg` (10px) for +menus and dialogs, `xl` (14px) for cards, `2xl` (16px) for the sidebar and message bubbles, +and `3xl` (24px) for the chat form, rising to `4xl` (32px) for the chat form on small +screens. Status lamps, avatars and the round icon buttons in the chat form are fully round. ## Brand @@ -1071,15 +1074,15 @@ icon buttons in the chat form are fully round. - **Toggles:** the same corners, type, heights, padding and icon size as buttons, with square `icon-sm`, `icon` and `icon-lg` sizes for icon-only toggles. `default` has no fill until hovered; `outline` borrows the outline button. Pressed toggles take - `toggle-background-on`. + `surface-selected`. - **Button groups:** joined buttons share one shadow, drawn by the group, and one border at each seam. A group separator replaces the seam border. Filled buttons draw a seam in their - own text colour (`button-primary-seam`, `button-danger-seam`) instead. + own text colour at 25% instead. - **Selection on a track:** a choice that moves along a track is a recessed track with the selection raised on it, never a row of outlined buttons. The track is `surface-muted` with the inset shade (`elevation-inset`); the selection is a `surface-lifted` chip with - `elevation-control`, and unselected options are softened text with no fill. Tabs use the - same track for their list, with the active tab raised (`tabs-*`); a `line` variant + `elevation-control`, and unselected options are softened text (`fg-soft`) with no fill. Tabs use the + same track for their list, with the active tab raised; a `line` variant underlines the active tab instead. The chip or underline slides between tabs in 300ms on a plain ease-out, with a stretch of at most 5% along the move that is gone by the time it lands; with reduced motion it jumps instead. The switch is the same track with a raised @@ -1095,7 +1098,7 @@ icon buttons in the chat form are fully round. - **Chat form:** one `chat-form-surface` holding the input, attachments and actions. Its fill is the muted grey at 60% in light mode and 75% in dark mode. - **User message bubble:** the primary colour at 5% with `matte-sheen` and the very faint - `edge-faint` hairline, so it separates from the page without a visible border. + `edge-ambient` hairline, so it separates from the page without a visible border. - **Sidebar:** `sidebar-surface`, the muted fill at 60% with no inner highlight and the ambient edge. On small screens it keeps a plain `shadow-md` instead. - **Inset groups:** `inset-group-surface` gathers rows inside a glass panel, like the @@ -1151,6 +1154,12 @@ icon buttons in the chat form are fully round. (`--sidebar-reveal-x`), taking no taps while the page is aside. The page keeps room under its last row (`max-md:pb-safe-24`) so the key never covers it. One per page, only for its main action; from `md` up the action stays a button in the header. +- **Voice clips:** a recorded clip is a round primary play key, its waveform and the time in + `caption`: bars in the muted foreground at 40%, the played part in the primary colour, so + the clip stays neutral in both modes. The live waveform while recording is as tall as the + input's line (24px), the newest level on the right, and holds still with reduced motion. A + voice message's transcript opens under the clip on hover, keyboard focus or a tap, and + stays in the DOM for screen readers while closed. - **Copy feedback:** a copy action turns its icon into a `fg-success` check for 1.5s (`COPY_FEEDBACK_RESET_MS`), only when the copy succeeded, then back. The icon pops in with a 150ms fade and scale, skipped on first render and with reduced motion. @@ -1168,8 +1177,8 @@ icon buttons in the chat form are fully round. lifting the surface. - Do use the status colours only for status. Buttons keep their neutral colours, and the submit button stays black in light mode and white in dark mode. -- Do read component tokens in components, semantic tokens in shared styles, and primitives - only in semantic tokens. +- Do read a semantic token directly wherever a component takes it as it is. Add a component + token only for a value the component decides itself, never as an alias of a semantic token. - Do add a new colour as a primitive first, then give it a semantic name before any component uses it. - Do give motion a job: show where something went or what changed, like a selection sliding diff --git a/ui/apps/chat/README.md b/ui/apps/chat/README.md index 5fa37286aadf..abee5d43bb0d 100644 --- a/ui/apps/chat/README.md +++ b/ui/apps/chat/README.md @@ -89,6 +89,7 @@ The app imports the library as `@ggml-org/llama-ui/ui/` and compiles its s | Routes | `src/routes` | `/`, `/chat/[id]`, `/models`, `/mcp-servers`, `/settings`, `/search` | | App components | `src/lib/components/app` | Chat, navigation, models, MCP, settings and dialogs, grouped by area | | UI components | `ui/lib/ui` | shadcn-svelte on bits-ui, from Llama UI | +| Voice | `ui/lib/voice` | Microphone capture, transcription and dictation, from Llama Voice (`@ggml-org/llama-voice`) | | Hooks | `src/lib/hooks` | View logic between components and stores: scroll, drag and drop, pickers, keyboard | | Stores | `src/lib/stores` | Application state as Svelte 5 runes: chat, conversations, the agentic loop, tools, models, settings | | Services | `src/lib/services` | Stateless I/O: the llama-server API, IndexedDB, MCP, the Hugging Face Hub, the tool sandbox | diff --git a/ui/apps/chat/demo/README.md b/ui/apps/chat/demo/README.md index 8769da6ef4ff..e929626870d0 100644 --- a/ui/apps/chat/demo/README.md +++ b/ui/apps/chat/demo/README.md @@ -115,7 +115,7 @@ Records every `scripts/docs/*.demo.ts` from the storage target and uploads `vide ## 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. Use `test.use({ settings, startPath })` to seed other settings or start on another route. +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 diff --git a/ui/apps/chat/demo/fixtures/traces.ts b/ui/apps/chat/demo/fixtures/traces.ts index cc7ed8979a95..dc766458e478 100644 --- a/ui/apps/chat/demo/fixtures/traces.ts +++ b/ui/apps/chat/demo/fixtures/traces.ts @@ -301,9 +301,39 @@ function agenticDebugging(): Trace { return trace; } +/** A reply with a diagram, for diagram preview demos. */ +function diagrams(): Trace { + const trace = new Trace('How a request flows through llama-server'); + + trace.user('Can you draw how a chat request flows through llama-server?'); + trace.assistant( + [ + 'Here is the path a request takes:', + '', + '```mermaid', + 'flowchart LR', + ' U[Browser] -->|POST /v1/chat/completions| S(llama-server)', + ' S --> Q{Slot free?}', + ' Q -->|yes| P[Prompt processing]', + ' Q -->|no| W[Queue]', + ' W --> P', + ' P --> G[Sample token]', + ' G -->|more| G', + ' G -->|SSE tokens| U', + ' click S href "https://github.com/ggml-org/llama.cpp" "llama.cpp on GitHub" _blank', + '```', + '', + 'Requests wait in the queue until a slot is free, then tokens stream back as they are sampled.' + ].join('\n') + ); + + return trace; +} + /** Built-in traces, by name. */ export const DEMO_TRACES: Record Trace> = { 'agentic-debugging': agenticDebugging, + diagrams, 'long-chat': longChat }; diff --git a/ui/apps/chat/demo/helpers.ts b/ui/apps/chat/demo/helpers.ts index 1c0ad7734f4e..97e7bdb11c75 100644 --- a/ui/apps/chat/demo/helpers.ts +++ b/ui/apps/chat/demo/helpers.ts @@ -3,7 +3,15 @@ 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 { execFileSync } from 'node:child_process'; -import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { + appendFileSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync +} from 'node:fs'; +import { tmpdir } from 'node:os'; import { basename, join, resolve } from 'node:path'; const VIDEOS_DIR = resolve(import.meta.dirname, 'videos'); @@ -112,6 +120,68 @@ function seedSettings(config: Record): 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); @@ -143,19 +213,9 @@ export class Demo { /** Shows a caption at the top of the frame for `ms`, clear of the chat form. */ async caption(text: string, ms = 2200): Promise { - await this.page.evaluate((t) => { - const el = document.getElementById('demo-caption'); - - if (!el) return; - - el.textContent = t; - el.classList.add('visible'); - }, text); + await this.showCaption(text); await this.page.waitForTimeout(ms); - await this.page.evaluate(() => - document.getElementById('demo-caption')?.classList.remove('visible') - ); - await this.page.waitForTimeout(250); + await this.hideCaption(); } async click(target: Locator, ms = 400): Promise { @@ -182,6 +242,15 @@ export class Demo { 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 { + 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 { await target.scrollIntoViewIfNeeded(); @@ -240,6 +309,23 @@ export class Demo { 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 { + const wav = synthesizeSpeech(text, voice); + + await this.showCaption(`“${text}”`); + await this.page.evaluate( + (base64) => + (window as unknown as { demoSpeak(wav: string): Promise }).demoSpeak(base64), + wav + ); + await this.hideCaption(); + await this.pause(ms); + } + /** Types quickly with uneven key timing, a little slower after spaces and punctuation. */ async type(target: Locator, text: string, ms = 500): Promise { await this.click(target, 200); @@ -305,6 +391,13 @@ export class Demo { return { x: box.x + box.width / 2, y: box.y + box.height / 2 }; } + private async hideCaption(): Promise { + 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 { await this.page.evaluate(() => @@ -340,6 +433,17 @@ export class Demo { return this.cdp; } + + private async showCaption(text: string): Promise { + await this.page.evaluate((t) => { + const el = document.getElementById('demo-caption'); + + if (!el) return; + + el.textContent = t; + el.classList.add('visible'); + }, text); + } } interface DemoOptions { diff --git a/ui/apps/chat/scripts/design-md.js b/ui/apps/chat/scripts/design-md.js index 316bf9acdc2e..94c90b1f5452 100644 --- a/ui/apps/chat/scripts/design-md.js +++ b/ui/apps/chat/scripts/design-md.js @@ -34,9 +34,11 @@ const THEMES = [ ]; // the type roles, by the @theme names Tailwind turns into text-body, text-label-sm, ...: a size with a line height const TYPE_ROLE = /^--text-([a-z]+(?:-[a-z]+)*)$/; +// body and caption text takes the weight around it, which is regular unless a parent says otherwise +const DEFAULT_WEIGHT = '400'; // code takes the body-sm role in the mono stack (see `:where(code, pre, kbd, samp)` in theme.css) const CODE_ROLE = 'body-sm'; -// Tailwind's own `rounded-full`, for lamps, avatars and round buttons; the other corners are roles in semantic.css +// Tailwind's own `rounded-full`, for lamps, avatars and round buttons; the other corners are the scale in theme.css const ROUNDED_FULL = '9999px'; // the sections this script owns, in the order they appear in the front matter; the next one is written by hand const SECTIONS = ['colors', 'typography', 'rounded']; @@ -104,6 +106,8 @@ const isColorLiteral = (value) => /^(oklch|oklab|rgb|hsl)\([^()]*\)$/.test(value); /** @param {string} value */ const isColorMix = (value) => /^color-mix\(.*\)$/.test(value) && !/\)\s*,/.test(value); +/** a share a theme sets for a derivation, e.g. `--status-surface-share: 11%` @param {string} value */ +const isShare = (value) => /^\d+(?:\.\d+)?%$/.test(value); /** @param {string} value */ const varName = (value) => /^var\(--([\w-]+)\)$/.exec(value)?.[1]; @@ -136,7 +140,19 @@ function build() { return next !== undefined && isColor(next, scope); }; - const semanticColors = [...semantic].filter(([, value]) => isColor(value, semantic)); + /** + * A value with the shares it reads written out, as the theme whose declarations are `scope` sets them, so a + * derivation reads as the mix it is: `color-mix(in oklab, var(--fill-danger) 11%, var(--surface-page))`. + * @param {string} value + * @param {Map} [scope] + */ + const withShares = (value, scope) => + value.replace(/var\((--[\w-]+)\)/g, (reference, name) => { + const share = scope?.get(name) ?? semantic.get(name) ?? ''; + + return isShare(share) ? share : reference; + }); + const semanticColors = [...semantic].filter(([, value]) => isColor(withShares(value), semantic)); const semanticNames = new Set(semanticColors.map(([name]) => name.slice(2))); /** * A token's value as the front matter writes it: a reference to another token, a literal, or a mix of them. A @@ -166,7 +182,7 @@ function build() { const base = new Map(); for (const [name, value] of semanticColors) { - const rendered = render(value, (n) => n); + const rendered = render(withShares(value), (n) => n); base.set(name, rendered); colors.push([name.slice(2), rendered]); @@ -190,7 +206,9 @@ function build() { if (semanticNames.has(ref)) resolve(`--${ref}`); } - const result = render(value, (n) => (twins.has(n) ? `${n}${suffix}` : n)); + const result = render(withShares(value, overrides), (n) => + twins.has(n) ? `${n}${suffix}` : n + ); rendered.set(name, result); @@ -217,6 +235,13 @@ function build() { return (name && primitives.get(`--${name}`)) ?? value ?? ''; }; + // a line height is written as the line over the size, `calc(1.25 / 0.875)`: the line, in rem + /** @param {string | undefined} value */ + const lineHeight = (value) => { + const ratio = /^calc\(([\d.]+) \/ [\d.]+\)$/.exec(value ?? ''); + + return ratio ? `${ratio[1]}rem` : length(value); + }; /** @type {[string, Record][]} */ const typography = []; @@ -230,8 +255,8 @@ function build() { { fontFamily: sans, fontSize: length(value), - fontWeight: length(inline.get(`${name}--font-weight`)), - lineHeight: length(inline.get(`${name}--line-height`)) + fontWeight: inline.get(`${name}--font-weight`) ?? DEFAULT_WEIGHT, + lineHeight: lineHeight(inline.get(`${name}--line-height`)) } ]); } @@ -242,11 +267,17 @@ function build() { /** @type {[string, string][]} */ const rounded = []; + // the corner scale is computed from --radius: `calc(var(--radius) + 4px)`, with 1rem as 16px + const baseRadius = parseFloat(theme.get(':root')?.get('--radius') ?? '') * 16; - for (const [name, value] of inline) { - const role = /^--radius-([a-z-]+)$/.exec(name)?.[1]; + for (const [name, value] of theme.get('@theme inline') ?? []) { + const step = /^--radius-([a-z0-9]+)$/.exec(name)?.[1]; + const offset = /^calc\(var\(--radius\) ([+-]) ([\d.]+)px\)$/.exec(value); + + if (!step) continue; - if (role) rounded.push([role, length(value)]); + if (offset) rounded.push([step, `${baseRadius + Number(offset[1] + offset[2])}px`]); + else if (value === 'var(--radius)') rounded.push([step, `${baseRadius}px`]); } rounded.push(['full', ROUNDED_FULL]); diff --git a/ui/apps/chat/scripts/llama-ui.js b/ui/apps/chat/scripts/llama-ui.js index c4eb26af77c9..f8963593a33b 100644 --- a/ui/apps/chat/scripts/llama-ui.js +++ b/ui/apps/chat/scripts/llama-ui.js @@ -26,6 +26,7 @@ const LLAMA_UI_EXPORTS = [ ['@ggml-org/llama-ui/enums', `${source}/enums/index.ts`], ['@ggml-org/llama-ui/code', `${source}/utils/index.ts`], ['@ggml-org/llama-ui/utils', `${source}/components/ui/utils.ts`], + ['@ggml-org/llama-ui/voice', `${source}/components/voice/index.ts`], ['@ggml-org/llama-ui/styles/*', `${source}/styles/*`], ['@ggml-org/llama-ui/theme.css', `${source}/styles/theme.css`], ['@ggml-org/llama-ui/tokens.css', `${source}/styles/tokens.css`], diff --git a/ui/apps/chat/sources.cmake b/ui/apps/chat/sources.cmake index 7e506c0eccf9..d3daee6c9d37 100644 --- a/ui/apps/chat/sources.cmake +++ b/ui/apps/chat/sources.cmake @@ -5,6 +5,8 @@ set(UI_SOURCE_GLOBS static/* # Llama UI, which the app compiles from source ../../lib/ui/src/lib/* + # Llama Voice, also compiled from source + ../../lib/voice/src/* ) set(UI_SOURCE_FILES diff --git a/ui/apps/chat/src/app.css b/ui/apps/chat/src/app.css index cca440844162..24ba6cec44bb 100644 --- a/ui/apps/chat/src/app.css +++ b/ui/apps/chat/src/app.css @@ -30,7 +30,7 @@ /* phone sidebar width, which the page slides aside to reveal */ --sidebar-reveal: min(80dvw, 20rem); /* the desktop sidebar's muted/60 over the page, made opaque so the slid page's corners can match it */ - --sidebar-reveal-tint: color-mix(in oklab, var(--muted) 60%, var(--background)); + --sidebar-reveal-tint: color-mix(in oklab, var(--surface-muted) 60%, var(--surface-page)); /* how far the phone sidebar is open, 0 to 1, stepped every frame by useSidebarReveal */ --sidebar-reveal-progress: 0; /* the same on a log curve: the sidebar's contents hold on until the page nearly covers them */ @@ -39,7 +39,7 @@ --sidebar-reveal-bg: color-mix( in oklab, var(--sidebar-reveal-tint) calc(var(--sidebar-reveal-progress) * 100%), - var(--background) + var(--surface-page) ); --layer-popover: 1000000; @@ -63,7 +63,7 @@ /* the chat form's corners while its text and actions share one row */ --chat-form-single-row-radius: 1.25rem; /* the card's translucent fill over the page, made opaque: the phone sheet, and the page and Safari's bars around it */ - --chat-form-sheet-fill: color-mix(in oklab, var(--muted) 60%, var(--background)); + --chat-form-sheet-fill: color-mix(in oklab, var(--surface-muted) 60%, var(--surface-page)); --max-message-height: max(24rem, min(80dvh, calc(100dvh - var(--chat-form-area-height) - 12rem))); } @@ -91,7 +91,7 @@ } .dark { - --chat-form-sheet-fill: color-mix(in oklab, var(--muted) 75%, var(--background)); + --chat-form-sheet-fill: color-mix(in oklab, var(--surface-muted) 75%, var(--surface-page)); } @layer base { @@ -202,9 +202,9 @@ .chat-top-fade { background: linear-gradient( to bottom, - color-mix(in srgb, var(--background) 100%, transparent) 25%, - color-mix(in srgb, var(--background) 80%, transparent) 50%, - color-mix(in srgb, var(--background) 40%, transparent) 75%, + color-mix(in srgb, var(--surface-page) 100%, transparent) 25%, + color-mix(in srgb, var(--surface-page) 80%, transparent) 50%, + color-mix(in srgb, var(--surface-page) 40%, transparent) 75%, transparent 100% ); } @@ -219,8 +219,8 @@ height: var(--page-top); background: linear-gradient( to bottom, - var(--background) calc(var(--corner-control-top) + 1.25rem), - color-mix(in srgb, var(--background) 55%, transparent) + var(--surface-page) calc(var(--corner-control-top) + 1.25rem), + color-mix(in srgb, var(--surface-page) 55%, transparent) calc(var(--corner-control-top) + 2.5rem), transparent 100% ); @@ -234,14 +234,14 @@ 10px Safari ignores; what it covers sits under the fade's solid part anyway */ .status-bar-edge { height: 0.75rem; - background-color: var(--background); + background-color: var(--surface-page); } /* The bottom edge's counterpart, which Safari takes for its bottom toolbar the same way: without it, it finds the chat form there and takes the form's colour */ .screen-bottom-edge { height: 0.75rem; - background-color: var(--background); + background-color: var(--surface-page); } /* The same fade at the bottom of a phone's screen: solid behind the home indicator and @@ -251,8 +251,9 @@ height: calc(var(--safe-area-bottom) + 3rem); background: linear-gradient( to top, - var(--background) var(--safe-area-bottom), - color-mix(in srgb, var(--background) 60%, transparent) calc(var(--safe-area-bottom) + 1.5rem), + var(--surface-page) var(--safe-area-bottom), + color-mix(in srgb, var(--surface-page) 60%, transparent) + calc(var(--safe-area-bottom) + 1.5rem), transparent 100% ); } @@ -261,7 +262,7 @@ panel's translucent muted tint, and a fade above it, like the one under the tab bar, so the rows scrolling beneath end softly */ .sidebar-show-more { - --sidebar-surface: color-mix(in oklab, var(--muted) 60%, var(--background)); + --sidebar-surface: color-mix(in oklab, var(--surface-muted) 60%, var(--surface-page)); background: var(--sidebar-surface); &::before { @@ -284,14 +285,14 @@ over the other sections while dragged */ .sidebar-drag-surface, .sidebar-drag-overlay { - background: color-mix(in oklab, var(--muted) 60%, var(--background)); + background: color-mix(in oklab, var(--surface-muted) 60%, var(--surface-page)); } /* the copy of a chat row that follows the pointer, raised above the page */ .sidebar-drag-overlay { box-shadow: 0 10px 30px -10px rgb(0 0 0 / 0.35), - 0 0 0 1px color-mix(in srgb, var(--foreground) 12%, transparent); + 0 0 0 1px color-mix(in srgb, var(--fg-default) 12%, transparent); } /* While something is dragged, what it passes over takes no hover: only the @@ -329,12 +330,7 @@ } .shimmer-text { - background: linear-gradient( - 90deg, - var(--muted-foreground), - var(--foreground), - var(--muted-foreground) - ); + background: linear-gradient(90deg, var(--fg-muted), var(--fg-default), var(--fg-muted)); background-size: 200% 100%; background-clip: text; -webkit-background-clip: text; @@ -361,16 +357,16 @@ * so the svg also inherits them inside the preview dialog's shadow root, and follow the theme. */ :root { - --pele-bg: var(--code-background); - --pele-fg: var(--code-foreground); - --pele-muted: var(--muted-foreground); - --pele-line: var(--muted-foreground); - --pele-surface: var(--background); - --pele-surface-alt: var(--muted); - --pele-border: var(--border); - --pele-accent: var(--primary); - --pele-critical: var(--destructive); - --pele-error: var(--destructive); + --pele-bg: var(--surface-code); + --pele-fg: var(--fg-code); + --pele-muted: var(--fg-muted); + --pele-line: var(--fg-muted); + --pele-surface: var(--surface-page); + --pele-surface-alt: var(--surface-muted); + --pele-border: var(--line-default); + --pele-accent: var(--action-primary); + --pele-critical: var(--fg-danger); + --pele-error: var(--fg-danger); --pele-radius: calc(var(--radius) - 4px); } diff --git a/ui/apps/chat/src/lib/components/app/badges/BadgesModality.svelte b/ui/apps/chat/src/lib/components/app/badges/BadgesModality.svelte index 7c921732de6a..87cc59093779 100644 --- a/ui/apps/chat/src/lib/components/app/badges/BadgesModality.svelte +++ b/ui/apps/chat/src/lib/components/app/badges/BadgesModality.svelte @@ -18,7 +18,7 @@ {@const ModalityIcon = MODALITY_ICONS[modality]} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItem.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItem.svelte index 5bb7a47d71ea..5a0987154b27 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItem.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItem.svelte @@ -1,9 +1,11 @@ + +
+ {#key collapsed} + + + + {/key} + + {#if !source.voice} +

{source.name}

+ {/if} + + {#if !readonly && onRemove} +
+ onRemove?.(item.id)} + stopPropagationOnClick + tooltip="Remove" + /> +
+ {/if} +
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemAudio.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemAudio.svelte index 53653599f8a7..2d2ee228b19f 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemAudio.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemAudio.svelte @@ -1,12 +1,23 @@
@@ -21,6 +32,19 @@

Audio preview not available

{/if} -

{currentItem?.name || 'Audio'}

+

+ {source?.voice ? VOICE_MESSAGE_LABEL : currentItem?.name || 'Audio'} +

+ + {#if transcript} +

+ Transcript: {transcript} +

+ {:else if transcribing} +

Transcribing...

+ {/if}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemPdf.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemPdf.svelte index f270a0751e46..07a08026ca40 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemPdf.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemPdf.svelte @@ -206,7 +206,7 @@ {@render status('Failed to load PDF images', pdfImagesError)} {:else if pdfImages.length > 0} {#each pdfImages as image, index (index)} -

Page {index + 1}

+

Page {index + 1}

PDF Page {index + 1}{message}

{#if detail} -

{detail}

+

{detail}

{/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemVideo.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemVideo.svelte index ab0a2479ae3c..f3f4845d305a 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemVideo.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemVideo.svelte @@ -22,6 +22,6 @@

Video preview not available

{/if} -

{currentItem?.name || 'Video'}

+

{currentItem?.name || 'Video'}

diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewFileInfo.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewFileInfo.svelte index d27d54a4bae2..e51429a143fd 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewFileInfo.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewFileInfo.svelte @@ -7,10 +7,10 @@ let { displayName, fileSize }: Props = $props(); -
+

{displayName}

{#if fileSize} -

{fileSize}

+

{fileSize}

{/if}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewThumbnailStrip.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewThumbnailStrip.svelte index 513d97a124d6..2fa421520d3a 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewThumbnailStrip.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewThumbnailStrip.svelte @@ -61,7 +61,9 @@ {/if} - {getFileExtension(item.name)} + {getFileExtension(item.name)}
{/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte index 0c44d125fb9c..b9845cc866ba 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte @@ -1,10 +1,13 @@ + +
{ event.preventDefault(); - - if (!canSubmit || disabled || hasLoadingAttachments) return; - - onSubmit?.(); + void submit(); }} > @@ -678,9 +732,7 @@ bind:this={cardEl} class={[ 'chat-form-surface group/chat-form relative flex shrink flex-col overflow-hidden outline-none transition-[min-height,padding,border-radius,border-color,background-color] duration-400 ease-[var(--chat-form-resize-ease,cubic-bezier(0.3,1.12,0.5,1))] motion-reduce:transition-none', - isSingleRow - ? 'rounded-(--chat-form-single-row-radius)' - : 'rounded-(--chat-form-radius-compact) md:rounded-(--chat-form-radius)', + isSingleRow ? 'rounded-(--chat-form-single-row-radius)' : 'rounded-4xl md:rounded-3xl', // on a phone the sheet's animation moves it (see useChatFormExpansion): only its // border, hidden on the sheet, fades back in after 'max-md:transition-[border-color] max-md:duration-200', @@ -702,7 +754,7 @@ 'max-md:pt-safe', // no rim, ring or visible border along the screen's edges; the border stays // transparent so nothing inside shifts by its width - 'max-md:[--glass-edge-side:transparent] max-md:[--glass-edge-mid:transparent] max-md:[--glass-edge-side-focus:transparent] max-md:[--glass-edge-mid-focus:transparent] max-md:[--glass-highlight:transparent]', + 'max-md:[--glass-edge:transparent] max-md:[--glass-edge-focus:transparent] max-md:[--glass-highlight:transparent]', '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 ], @@ -734,7 +786,7 @@
{ + voice.handleUserInput(); expansion.handleInput(); pickers.handleInput(); onValueChange?.(value); }} onKeydown={handleKeydown} onPaste={handlePaste} - {placeholder} + placeholder={voicePlaceholder ?? placeholder} /> {#if mcpStore.resources.hasAttachments} @@ -776,34 +829,62 @@
- - onSystemPromptClick?.({ files: uploadedFiles, message: value })} - onWorkingDirectoryClick={isWorkingDirectoryInAddMenu - ? pickers.handleWorkingDirectoryOpen - : undefined} - {showAddButton} - {showModelSelector} - {uploadedFiles} - workingDirectory={cwd} - /> + {#if voice.isActive} + void handleStopAndSend()} + onStop={() => void voice.stop()} + quiet={voice.quiet} + state={voice.state} + /> + {/if} + + +
+ + onSystemPromptClick?.({ files: uploadedFiles, message: value })} + onWorkingDirectoryClick={isWorkingDirectoryInAddMenu + ? pickers.handleWorkingDirectoryOpen + : undefined} + {showAddButton} + {showModelSelector} + voice={{ + action: voice.label, + hint: voice.hint, + prepare: () => void voice.prepare(), + show: voice.showButton, + unavailableReason: voice.unavailableReason, + unprepare: voice.unprepare + }} + workingDirectory={cwd} + /> +
- + {#if deviceStore.isMobile} + + {/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddButton.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddButton.svelte index b22d03c7bda5..e25bcb56f72c 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddButton.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddButton.svelte @@ -15,7 +15,7 @@ diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionReasoning.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionReasoning.svelte index 04fd275fd590..91d4b7de03cf 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionReasoning.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionReasoning.svelte @@ -46,7 +46,7 @@ {/snippet} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte index 987c5a350cac..c895ef0c34b7 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte @@ -1,22 +1,24 @@ + + + {#snippet stop({ disabled })} + + {/snippet} + diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ChatFormContextGauge.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ChatFormContextGauge.svelte index 221e7b5116d3..4544d8fe4c1a 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ChatFormContextGauge.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ChatFormContextGauge.svelte @@ -1,25 +1,23 @@
-

Token usage details

+

Token usage details

-
+
{#if hasCumulative}

Across all turns

@@ -68,7 +68,7 @@ {#if hasCurrent}

This turn · KV cache

diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDrawer.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDrawer.svelte new file mode 100644 index 000000000000..55f76580e11d --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDrawer.svelte @@ -0,0 +1,20 @@ + + + + + + + Context + + + Context window usage of the model the chat runs + + + + + + diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeLoadModel.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeLoadModel.svelte index 3627c74197d3..d2dd96f79aa3 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeLoadModel.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeLoadModel.svelte @@ -12,13 +12,17 @@ {#if modelId !== null && !isLoading} -
+
Available context size is only visible once the model is loaded.
{:else if isLoading} -
+
Loading model... diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePanel.svelte similarity index 56% rename from ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePanel.svelte index 802dd7e8d081..5a0501947378 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePanel.svelte @@ -2,54 +2,29 @@ import { colorLevelBgClass, colorLevelTextClass } from './context-gauge'; import ContextGaugeDetails from './ContextGaugeDetails.svelte'; import ContextGaugeLoadModel from './ContextGaugeLoadModel.svelte'; - import { - gaugeCardEnter, - gaugeCardLeave, - gaugePopup, - gaugePopupClose - } from './gauge-popup.svelte'; + import { gaugePopupClose } from './gauge-popup.svelte'; import { Button } from '@ggml-org/llama-ui/ui/button'; - import * as Drawer from '@ggml-org/llama-ui/ui/drawer'; import { FoldVertical, Loader2 } from '@lucide/svelte'; import { useContextGauge } from '#lib/hooks/use-context-gauge.svelte.ts'; - import { agenticStore, chatStore, conversationsStore, deviceStore } from '#lib/stores/index.ts'; + import { agenticStore, chatStore, conversationsStore } from '#lib/stores/index.ts'; import { formatParameters } from '#lib/utils/formatters.ts'; + interface Props { + /** The drawer brings its own title, so the panel drops the inline one there. */ + inDrawer?: boolean; + } + + let { inDrawer = false }: Props = $props(); + const gauge = useContextGauge(); // The gauge hook wraps a processing state instance that only follows the - // live stream while its own monitoring flag is set, so the card instance + // live stream while its own monitoring flag is set, so the panel instance // starts monitoring like the dial does. $effect(() => { gauge.startMonitoring(); }); - let cardEl = $state(null); - - // Any press outside the card and outside the dial closes the card. - // Presses on the dial are excluded because the dial handles its own - // toggle; the listener only exists while the card is open. A phone shows - // the panel in a drawer instead, which brings its own dismissal. - $effect(() => { - if (!gaugePopup.open || deviceStore.isMobile) return; - - const onPointerDown = (event: PointerEvent) => { - const target = event.target; - - if (!(target instanceof Node)) return; - - if (cardEl?.contains(target)) return; - - if (target instanceof Element && target.closest('[data-context-gauge-trigger]')) return; - - gaugePopupClose(); - }; - - document.addEventListener('pointerdown', onPointerDown, true); - - return () => document.removeEventListener('pointerdown', onPointerDown, true); - }); - const showProgressBar = $derived( gauge.contextTotal !== null && gauge.contextTotal > 0 && @@ -60,7 +35,7 @@ const activeConvId = $derived(conversationsStore.activeConversation?.id ?? null); - // A summary in flight keeps the card open for the numbers, so the action + // A summary in flight keeps the panel open for the numbers, so the action // reports the run instead of inviting a second one. const isCompacting = $derived(activeConvId !== null && chatStore.isCompacting(activeConvId)); @@ -120,7 +95,7 @@ >
-
+
{gauge.contextPercent}% used @@ -130,7 +105,7 @@
{:else} -
No context info available
+
No context info available
{/if} {#if gauge.hasAnyUsage} @@ -149,47 +124,20 @@ {/if} {/snippet} -{#if deviceStore.isMobile} - - - - Context - - - Context window usage of the model the chat runs - - - -
- {@render usage()} - - {@render body()} - - {@render compactAction()} -
-
-
-{:else if gaugePopup.open} -
-
-
- Context - - · - - {@render usage()} -
- - {@render body()} - - {@render compactAction()} +
+ {#if inDrawer} + {@render usage()} + {:else} +
+ Context + + · + + {@render usage()}
-
-{/if} + {/if} + + {@render body()} + + {@render compactAction()} +
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/gauge-popup.svelte.ts b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/gauge-popup.svelte.ts index 4885326fbdfb..9e2f50cd9429 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/gauge-popup.svelte.ts +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/gauge-popup.svelte.ts @@ -1,99 +1,11 @@ -// Shared state for the context gauge popup. The dial and the card live in -// different DOM subtrees, so open state and placement are coordinated here. -// centerX and bottom place the card just above the dial: both are measured -// once at open time, relative to the closest form ancestor; the dial and -// the card share that positioning frame, so the values stay exact for the -// whole time the card is open. -// Mouse pointers open on hover with a short grace delay to travel from -// dial to card; touch pointers toggle on tap. -import { - CONTEXT_GAUGE_CARD_HALF_WIDTH_PX, - CONTEXT_GAUGE_CLOSE_GRACE_MS, - CONTEXT_GAUGE_DIAL_GAP_PX, - CONTEXT_GAUGE_EDGE_MARGIN_PX -} from '#lib/constants/index.ts'; +// Open state of the context panel, shared by the gauge's popover and the phone's drawer: the +// phone's corner key and the drawer live in different DOM subtrees. +export const gaugePopup = $state({ open: false }); -let closeTimer: ReturnType | undefined; -let lastPointerType = ''; - -export const gaugePopup = $state({ bottom: 0, centerX: 0, open: false }); - -function openFrom(trigger: HTMLElement): void { - clearTimeout(closeTimer); - const frame = trigger.closest('form'); - - if (frame) { - const frameRect = frame.getBoundingClientRect(); - const triggerRect = trigger.getBoundingClientRect(); - const centerX = triggerRect.left + triggerRect.width / 2 - frameRect.left; - const min = CONTEXT_GAUGE_CARD_HALF_WIDTH_PX + CONTEXT_GAUGE_EDGE_MARGIN_PX; - const max = frameRect.width - CONTEXT_GAUGE_CARD_HALF_WIDTH_PX - CONTEXT_GAUGE_EDGE_MARGIN_PX; - - gaugePopup.centerX = Math.min(Math.max(centerX, min), Math.max(min, max)); - gaugePopup.bottom = frameRect.bottom - triggerRect.top + CONTEXT_GAUGE_DIAL_GAP_PX; - } - - gaugePopup.open = true; -} - -function toggleFrom(trigger: HTMLElement): void { - if (gaugePopup.open) { - clearTimeout(closeTimer); - gaugePopup.open = false; - } else { - openFrom(trigger); - } +export function gaugePopupToggle(): void { + gaugePopup.open = !gaugePopup.open; } export function gaugePopupClose(): void { - clearTimeout(closeTimer); gaugePopup.open = false; } - -export function gaugeTriggerPointerDown(event: PointerEvent): void { - lastPointerType = event.pointerType; -} - -export function gaugeTriggerClick(event: MouseEvent): void { - if (lastPointerType !== 'touch') return; - - toggleFrom(event.currentTarget as HTMLElement); -} - -export function gaugeTriggerKeydown(event: KeyboardEvent): void { - if (event.key !== 'Enter' && event.key !== ' ') return; - - event.preventDefault(); - toggleFrom(event.currentTarget as HTMLElement); -} - -export function gaugeTriggerEnter(event: PointerEvent): void { - if (event.pointerType !== 'mouse') return; - - openFrom(event.currentTarget as HTMLElement); -} - -export function gaugeTriggerLeave(event: PointerEvent): void { - if (event.pointerType !== 'mouse') return; - - scheduleClose(); -} - -export function gaugeCardEnter(event: PointerEvent): void { - if (event.pointerType !== 'mouse') return; - - clearTimeout(closeTimer); -} - -export function gaugeCardLeave(event: PointerEvent): void { - if (event.pointerType !== 'mouse') return; - - scheduleClose(); -} - -function scheduleClose(): void { - clearTimeout(closeTimer); - closeTimer = setTimeout(() => { - gaugePopup.open = false; - }, CONTEXT_GAUGE_CLOSE_GRACE_MS); -} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectory.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectory.svelte index db49bdcf3983..2f9fe042eb48 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectory.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectory.svelte @@ -339,7 +339,7 @@ /> {#if !fileSearchEnabled} -
{searchUnavailableMessage}
+
{searchUnavailableMessage}
{:else if query.trim() && (search.isSearching || queryResults.length > 0 || searchError)}
- + Searching in: diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte index ef69d0f5aced..bc368ac74a14 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte @@ -38,18 +38,18 @@ class="max-h-48 overflow-y-auto py-2" > {#if isSearching && results.length === 0} -
Searching...
+
Searching...
{:else if error} -
{error}
+
{error}
{:else if results.length === 0} -
No matching folders
+
No matching folders
{:else} {#each results as path, index (path)}
- +
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte index c37b0447fd29..72679c8f1238 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte @@ -199,7 +199,7 @@ {#if displayedModel}
-
+
- + {modelLoadingText ?? processingState.getPromptProgressText() ?? processingState.getProcessingMessage() ?? diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantRawOutput.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantRawOutput.svelte index e5119ae358f8..f0afdc4b072c 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantRawOutput.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantRawOutput.svelte @@ -24,8 +24,8 @@ margin-top: 1.5rem; padding: 1rem 1.25rem; border-radius: 1rem; - background: hsl(var(--muted) / 0.3); - color: var(--foreground); + background: hsl(var(--surface-muted) / 0.3); + color: var(--fg-default); font-size: 0.875rem; line-height: 1.6; white-space: pre-wrap; diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageCwdChange.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageCwdChange.svelte index 959016a26538..b70fe2244cd5 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageCwdChange.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageCwdChange.svelte @@ -20,13 +20,13 @@ {#if info.path === null} - Working directory cleared + Working directory cleared {:else} - Set working directory to  + Set working directory to  - + {info.display} {/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPrompt.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPrompt.svelte index 32f5cceab6a8..2caaf6e4369a 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPrompt.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPrompt.svelte @@ -29,13 +29,13 @@ {:else} {#if message.timestamp} -
+
{/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPromptContent.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPromptContent.svelte index 27af803f0ccb..d1303379a391 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPromptContent.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageMcpPrompt/ChatMessageMcpPromptContent.svelte @@ -82,7 +82,7 @@ let showArgBadges = $derived(hasArguments && !isLoading && !loadError); let isAttachment = $derived(variant === McpPromptVariant.ATTACHMENT); - let textSizeClass = $derived(isAttachment ? 'text-xs' : 'text-md'); + let textSizeClass = $derived(isAttachment ? 'text-caption' : 'text-md'); let paddingClass = $derived(isAttachment ? 'px-3 py-2' : 'px-3.75 py-2.5'); let maxHeightStyle = $derived( isAttachment ? 'max-height: 6rem;' : 'max-height: var(--max-message-height);' @@ -94,7 +94,7 @@
-
+
{#if serverFavicon} @@ -124,7 +124,7 @@
{:else if isLoading}
{:else if hasContent}
{:else} - {message.content} + {message.content} {/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageSystem/ChatMessageSystem.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageSystem/ChatMessageSystem.svelte index df2097b5a7d9..2770f96d83dc 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageSystem/ChatMessageSystem.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageSystem/ChatMessageSystem.svelte @@ -81,10 +81,10 @@ role="group" > {#if editCtx.isEditing} -
+
x
'); + + for (const el of host.querySelectorAll('input, textarea, [contenteditable]')) { + el.focus(); + expect(shouldTypeToFocus(key('a'))).toBe(false); + } + }); + + it('leaves keys inside dialogs and menus', () => { + const host = mount( + '
' + ); + + for (const button of host.querySelectorAll('button')) { + button.focus(); + expect(shouldTypeToFocus(key('r'))).toBe(false); + } + }); +}); diff --git a/ui/apps/chat/tests/client/voice-capture.svelte.test.ts b/ui/apps/chat/tests/client/voice-capture.svelte.test.ts new file mode 100644 index 000000000000..3ce997a9216a --- /dev/null +++ b/ui/apps/chat/tests/client/voice-capture.svelte.test.ts @@ -0,0 +1,184 @@ +// Guards VoiceCapture in a real browser, fed by a synthesized microphone (an oscillator +// into a MediaStream, since the fake capture device flags are not available here): the +// levels move, the PCM worklet loads from its Blob URL and streams chunks, stop() returns +// a WAV clip with a plausible duration and peaks, and every path stops the tracks. + +import { + VOICE_MICROPHONE_MESSAGE, + VoiceCapture, + VoiceCaptureError, + VoiceCaptureState +} from '@ggml-org/llama-voice'; +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import { userEvent } from 'vitest/browser'; + +const sources: AudioContext[] = []; + +/** A 440 Hz tone as a microphone stream. */ +function toneStream(): MediaStream { + const context = new AudioContext(); + const oscillator = context.createOscillator(); + const destination = context.createMediaStreamDestination(); + + oscillator.frequency.value = 440; + oscillator.connect(destination); + oscillator.start(); + sources.push(context); + + return destination.stream; +} + +// audio contexts only run after a user gesture, as the mic button gives in the app +beforeAll(async () => { + const button = document.createElement('button'); + + button.textContent = 'Record'; + document.body.append(button); + await userEvent.click(button); + button.remove(); +}); + +const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** Waits for `done`, polling: a loaded test run can start the audio graph late. */ +async function waitFor(done: () => boolean, timeoutMs = 5000) { + const deadline = Date.now() + timeoutMs; + + while (!done()) { + if (Date.now() > deadline) throw new Error('timed out waiting for audio'); + + await wait(20); + } +} + +afterEach(async () => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + + for (const context of sources.splice(0)) await context.close(); +}); + +describe('VoiceCapture', () => { + it('streams levels and PCM chunks, and stops with a WAV clip', async () => { + const warn = vi.spyOn(console, 'warn'); + const stream = toneStream(); + const capture = new VoiceCapture({ levelsIntervalMs: 20, levelsLength: 16, stream }); + const levels: (readonly number[])[] = []; + const chunks: Int16Array[] = []; + + capture.onLevels((value) => levels.push(value)); + capture.onPcm((chunk) => chunks.push(chunk)); + + await capture.start(); + expect(capture.state).toBe(VoiceCaptureState.RECORDING); + + // at least 600 ms of tone recorded, however long the audio graph took to start + await waitFor(() => chunks.length >= 6 && levels.length > 5); + + const clip = await capture.stop(); + + // the worklet loaded from its Blob URL under COOP/COEP, as llama-server serves the UI, no fallback + expect(crossOriginIsolated).toBe(true); + expect(warn).not.toHaveBeenCalledWith( + expect.stringContaining('AudioWorklet unavailable'), + expect.anything() + ); + + expect(levels.length).toBeGreaterThan(5); + expect(levels.at(-1)).toHaveLength(16); + expect(Math.max(...levels.at(-1)!)).toBeGreaterThan(0.5); + + // 100 ms chunks at 16 kHz, the last one may be shorter + expect(chunks.length).toBeGreaterThan(3); + expect(chunks[0]).toHaveLength(1600); + + expect(clip.sampleRate).toBe(16_000); + expect(clip.durationMs).toBeGreaterThan(500); + expect(clip.durationMs).toBeLessThan(5000); + expect(clip.peaks).toHaveLength(64); + expect(Math.max(...clip.peaks)).toBe(1); + // a steady tone: once it reaches the capture, no span of the clip is silent. The capture + // starts with its first audio block, which can come before the tone stream's first sound + const toneFrom = clip.peaks.findIndex((peak) => peak > 0.5); + + expect(toneFrom).toBeGreaterThanOrEqual(0); + expect(clip.peaks.slice(toneFrom).every((peak) => peak > 0.5)).toBe(true); + expect(clip.peaks.length - toneFrom).toBeGreaterThan(16); + + const header = new DataView(await clip.blob.slice(0, 44).arrayBuffer()); + const pcmBytes = chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0); + + expect(clip.blob.type).toBe('audio/wav'); + expect(header.getUint16(22, true)).toBe(1); + expect(header.getUint32(24, true)).toBe(16_000); + expect(header.getUint16(34, true)).toBe(16); + expect(header.getUint32(40, true)).toBe(pcmBytes); + + // the clip decodes as audio + const decoded = await new OfflineAudioContext(1, 1, 16_000).decodeAudioData( + await clip.blob.arrayBuffer() + ); + + expect(decoded.duration * 1000).toBeCloseTo(clip.durationMs, 0); + expect(stream.getTracks().every((track) => track.readyState === 'ended')).toBe(true); + expect(capture.state).toBe(VoiceCaptureState.STOPPED); + }); + + it('cancel stops the tracks and drops the recording', async () => { + const stream = toneStream(); + const capture = new VoiceCapture({ stream }); + + await capture.start(); + await wait(200); + capture.cancel(); + + expect(stream.getTracks().every((track) => track.readyState === 'ended')).toBe(true); + expect(capture.state).toBe(VoiceCaptureState.IDLE); + await expect(capture.stop()).rejects.toThrow(); + }); + + it('cancel during start releases the microphone once it arrives', async () => { + const stream = toneStream(); + + let grant!: (value: MediaStream) => void; + + vi.spyOn(navigator.mediaDevices, 'getUserMedia').mockImplementation( + () => new Promise((resolve) => (grant = resolve)) + ); + + const capture = new VoiceCapture(); + const started = capture.start().catch((e) => e); + + capture.cancel(); + grant(stream); + + expect(await started).toBeInstanceOf(DOMException); + expect(stream.getTracks().every((track) => track.readyState === 'ended')).toBe(true); + }); + + it('a page hide tears the capture down', async () => { + const stream = toneStream(); + const capture = new VoiceCapture({ stream }); + + await capture.start(); + dispatchEvent(new PageTransitionEvent('pagehide')); + + expect(capture.state).toBe(VoiceCaptureState.IDLE); + expect(stream.getTracks().every((track) => track.readyState === 'ended')).toBe(true); + }); + + it('asks for the raw microphone signal and names a refusal', async () => { + const getUserMedia = vi + .spyOn(navigator.mediaDevices, 'getUserMedia') + .mockRejectedValue(new DOMException('denied', 'NotAllowedError')); + const capture = new VoiceCapture(); + const error = await capture.start().catch((e) => e); + + expect(getUserMedia).toHaveBeenCalledWith({ + audio: { autoGainControl: false, echoCancellation: false, noiseSuppression: false } + }); + expect(error).toBeInstanceOf(VoiceCaptureError); + expect(error.message).toBe(VOICE_MICROPHONE_MESSAGE.denied); + expect(capture.state).toBe(VoiceCaptureState.IDLE); + }); +}); diff --git a/ui/apps/chat/tests/client/voice-service.svelte.test.ts b/ui/apps/chat/tests/client/voice-service.svelte.test.ts new file mode 100644 index 000000000000..c36a842c7f01 --- /dev/null +++ b/ui/apps/chat/tests/client/voice-service.svelte.test.ts @@ -0,0 +1,136 @@ +// Guards the wiring every voice feature starts its session with: the Voice settings become +// capture options (boost, processing, a caller's own constraints), the language and the +// transcription model go where a router needs them, and an API key keeps the realtime +// socket off, since a browser websocket can not send it, which the app says of a model that +// only transcribes over that socket. + +import { seedStores } from '../stories/chat/form/fixtures'; +import { VOICE_MICROPHONE_DEFAULT, VoiceTranscriptionError } from '@ggml-org/llama-voice'; +import { SETTINGS_KEYS, VOICE_MODE_MESSAGE } from '#lib/constants/index.ts'; +import { SETTING_CONFIG_DEFAULT } from '#lib/constants/settings.constants.ts'; +import { VoiceService } from '#lib/services/voice.service.ts'; +import type { SettingsConfigType } from '#lib/types/index.ts'; +import { afterEach, describe, expect, it } from 'vitest'; + +let restore: (() => void) | undefined; + +afterEach(() => { + restore?.(); + restore = undefined; +}); + +/** The default settings with `changes`, on the system microphone so no device is listed. */ +function settings(changes: Record = {}): SettingsConfigType { + return { + ...SETTING_CONFIG_DEFAULT, + [SETTINGS_KEYS.VOICE_MICROPHONE]: VOICE_MICROPHONE_DEFAULT, + ...changes + } as SettingsConfigType; +} + +describe('VoiceService.sessionOptions', () => { + it('boosts the raw signal by default, and transcribes with the model a router routes on', async () => { + const options = await VoiceService.sessionOptions(settings(), { + isRouter: true, + model: 'org/hearing-model' + }); + + expect(options.capture).toEqual({ boost: true }); + expect(options.transcribe).toMatchObject({ language: undefined, model: 'org/hearing-model' }); + }); + + it('leaves the model out for a single-model server', async () => { + const options = await VoiceService.sessionOptions(settings(), { + isRouter: false, + model: 'org/hearing-model' + }); + + expect(options.transcribe?.model).toBeUndefined(); + }); + + it('follows the processing, boost and language settings', async () => { + const options = await VoiceService.sessionOptions( + settings({ + [SETTINGS_KEYS.VOICE_AUTO_GAIN]: true, + [SETTINGS_KEYS.VOICE_BOOST]: false, + [SETTINGS_KEYS.VOICE_NOISE_SUPPRESSION]: true, + [SETTINGS_KEYS.VOICE_TRANSCRIPTION_LANGUAGE]: ' de ' + }), + { isRouter: false, model: null } + ); + + expect(options.capture).toEqual({ + boost: false, + constraints: { autoGainControl: true, noiseSuppression: true } + }); + expect(options.transcribe?.language).toBe('de'); + }); + + it("takes a caller's own constraints over the processing settings", async () => { + const options = await VoiceService.sessionOptions( + settings({ [SETTINGS_KEYS.VOICE_NOISE_SUPPRESSION]: true }), + { constraints: { echoCancellation: true }, isRouter: false, model: null } + ); + + expect(options.capture).toMatchObject({ constraints: { echoCancellation: true } }); + }); + + it('records without transcribing when asked to', async () => { + const options = await VoiceService.sessionOptions(settings(), { + isRouter: false, + model: null, + transcribe: false + }); + + expect(options.transcribe).toBeUndefined(); + }); +}); + +describe('VoiceService.serverContext', () => { + it('uses the realtime socket when no API key is set', () => { + restore = seedStores({ config: { apiKey: '' } }); + + const { context, realtime } = VoiceService.serverContext(); + + expect(realtime).toBe(true); + expect(context.getHeaders?.()).toEqual({}); + expect(context.resolveUrl('./v1/realtime')).toMatch(/\/v1\/realtime$/); + }); + + it('keeps to HTTP, with the key, when the server needs one', () => { + restore = seedStores({ config: { apiKey: 'secret' } }); + + const { context, realtime } = VoiceService.serverContext(); + + expect(realtime).toBe(false); + expect(context.getHeaders?.()).toEqual({ Authorization: 'Bearer secret' }); + }); +}); + +describe('VoiceService.failureReason', () => { + const notSupported = new VoiceTranscriptionError( + 'this server does not support chat/completions', + 501 + ); + + it('says a live-only model cannot transcribe on a server with an API key', () => { + restore = seedStores({ config: { apiKey: 'secret' } }); + + expect(VoiceService.failureReason(notSupported)).toBe(VOICE_MODE_MESSAGE.realtimeOnlyBehindKey); + }); + + it("leaves other failures to the server's own words", () => { + restore = seedStores({ config: { apiKey: 'secret' } }); + + expect( + VoiceService.failureReason(new VoiceTranscriptionError('Loading model', 503)) + ).toBeNull(); + expect(VoiceService.failureReason(new Error('Failed to fetch'))).toBeNull(); + + restore(); + restore = seedStores({ config: { apiKey: '' } }); + + // without a key the realtime socket was tried first: the model simply cannot hear + expect(VoiceService.failureReason(notSupported)).toBeNull(); + }); +}); diff --git a/ui/apps/chat/tests/client/voice-waveform.svelte.test.ts b/ui/apps/chat/tests/client/voice-waveform.svelte.test.ts new file mode 100644 index 000000000000..202907756915 --- /dev/null +++ b/ui/apps/chat/tests/client/voice-waveform.svelte.test.ts @@ -0,0 +1,39 @@ +// Guards VoiceWaveform's playback with real clicks, which a browser needs before it plays audio (the stories' clicks +// are scripted, so their play functions cover the rest): play and pause toggle, and one clip plays at a time. + +import { demoClip } from '../stories/voice/fixtures'; +import { VoiceWaveform } from '@ggml-org/llama-ui/voice'; +import { describe, expect, it } from 'vitest'; +import { page, userEvent } from 'vitest/browser'; +import { render } from 'vitest-browser-svelte'; + +describe('VoiceWaveform playback', () => { + it('toggles between play and pause', async () => { + const clip = demoClip(3, 1); + + render(VoiceWaveform, { durationMs: clip.durationMs, peaks: clip.peaks, src: clip.src }); + + await userEvent.click(page.getByRole('button', { name: 'Play voice message' })); + await expect.element(page.getByRole('button', { name: 'Pause voice message' })).toBeVisible(); + + await userEvent.click(page.getByRole('button', { name: 'Pause voice message' })); + await expect.element(page.getByRole('button', { name: 'Play voice message' })).toBeVisible(); + }); + + it('pauses one clip when another starts', async () => { + const first = demoClip(3, 2); + const second = demoClip(3, 3); + + render(VoiceWaveform, { label: 'First clip', peaks: first.peaks, src: first.src }); + render(VoiceWaveform, { label: 'Second clip', peaks: second.peaks, src: second.src }); + + await userEvent.click(page.getByRole('button', { name: 'Play first clip' })); + await expect.element(page.getByRole('button', { name: 'Pause first clip' })).toBeVisible(); + + await userEvent.click(page.getByRole('button', { name: 'Play second clip' })); + await expect.element(page.getByRole('button', { name: 'Pause second clip' })).toBeVisible(); + await expect.element(page.getByRole('button', { name: 'Play first clip' })).toBeVisible(); + + await userEvent.click(page.getByRole('button', { name: 'Pause second clip' })); + }); +}); diff --git a/ui/apps/chat/tests/debug/ViewportProbe.svelte b/ui/apps/chat/tests/debug/ViewportProbe.svelte index aa3f7f2f252e..5318b31e00a4 100644 --- a/ui/apps/chat/tests/debug/ViewportProbe.svelte +++ b/ui/apps/chat/tests/debug/ViewportProbe.svelte @@ -69,6 +69,6 @@ diff --git a/ui/apps/chat/tests/stories/actions/GlassKey.stories.svelte b/ui/apps/chat/tests/stories/actions/GlassKey.stories.svelte index b2d2c510a89b..0287e4923ac1 100644 --- a/ui/apps/chat/tests/stories/actions/GlassKey.stories.svelte +++ b/ui/apps/chat/tests/stories/actions/GlassKey.stories.svelte @@ -20,7 +20,7 @@
-
+
{#each LINES as line (line)}

{line}

{/each} diff --git a/ui/apps/chat/tests/stories/brand/assets/OpticalCentre.svelte b/ui/apps/chat/tests/stories/brand/assets/OpticalCentre.svelte index d8c148915d37..6e9c66b272bc 100644 --- a/ui/apps/chat/tests/stories/brand/assets/OpticalCentre.svelte +++ b/ui/apps/chat/tests/stories/brand/assets/OpticalCentre.svelte @@ -221,9 +221,11 @@ {#each [shown] as panel (panel.key)}
-

{panel.label}

+

{panel.label}

-

{panel.note}

+

+ {panel.note} +

@@ -247,7 +249,7 @@
@@ -440,7 +442,7 @@ {/each} -
+
The icon fills {Math.round((side / placement.size) * 100)}% of the side; the numbers are pixels at {placement.size} × {placement.size}. Each circle fills the gap between the circle crop and one of the icon’s diff --git a/ui/apps/chat/tests/stories/chat/form/ChatFormActionRecord.stories.svelte b/ui/apps/chat/tests/stories/chat/form/ChatFormActionRecord.stories.svelte index 476e9397c469..66143acfa1f9 100644 --- a/ui/apps/chat/tests/stories/chat/form/ChatFormActionRecord.stories.svelte +++ b/ui/apps/chat/tests/stories/chat/form/ChatFormActionRecord.stories.svelte @@ -1,8 +1,10 @@ - - - + + + - - + + + + + + - + - + - - + + { + const button = canvas.getAllByRole('button', { name: VOICE_MODE_MESSAGE.voiceMessage }); + + await expect(button.at(-1)).toBeDisabled(); // the tooltip trigger wraps the disabled button, hover the trigger - await userEvent.hover(canvas.getAllByRole('button', { name: 'Start recording' })[0]); + await userEvent.hover(button[0]); + await expect( + (await screen.findAllByText(VOICE_MODE_MESSAGE.unavailable)).length + ).toBeGreaterThan(0); + }} +/> + + { + await userEvent.hover(canvas.getAllByRole('button', { name: VOICE_MODE_MESSAGE.dictate })[0]); + await expect((await screen.findAllByText(/alongside the chat model/)).length).toBeGreaterThan( + 0 + ); }} /> diff --git a/ui/apps/chat/tests/stories/chat/form/ChatFormContextGauge.stories.svelte b/ui/apps/chat/tests/stories/chat/form/ChatFormContextGauge.stories.svelte index a0416fd5d03d..b5939a48ea9c 100644 --- a/ui/apps/chat/tests/stories/chat/form/ChatFormContextGauge.stories.svelte +++ b/ui/apps/chat/tests/stories/chat/form/ChatFormContextGauge.stories.svelte @@ -10,8 +10,9 @@ } from './fixtures'; import { defineMeta } from '@storybook/addon-svelte-csf'; import ChatFormContextGauge from '#lib/components/app/chat/ChatForm/ChatFormContextGauge/ChatFormContextGauge.svelte'; - import ContextGaugePopup from '#lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte'; + import ContextGaugeDrawer from '#lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDrawer.svelte'; import { gaugePopupClose } from '#lib/components/app/chat/ChatForm/ChatFormContextGauge/gauge-popup.svelte.ts'; + import { deviceStore } from '#lib/stores/index.ts'; import { userEvent, within } from 'storybook/test'; const { Story } = defineMeta({ @@ -24,7 +25,7 @@ const N_CTX = 32768; - // the popup state is module-wide, so close it around each story + // the open state is module-wide, so close it around each story function seedUsage(promptTokens: number) { return () => { gaugePopupClose(); @@ -67,21 +68,22 @@ }; } + // the popover renders in a portal, so it is looked up on the whole page async function openPopup({ canvasElement }: { canvasElement: HTMLElement }) { - const canvas = within(canvasElement); - - canvas.getByRole('button', { name: 'Context usage' }).focus(); - await userEvent.keyboard('{Enter}'); - await canvas.findByRole('status'); + await userEvent.click(within(canvasElement).getByRole('button', { name: 'Context usage' })); + await within(document.body).findByRole('dialog'); } {#snippet frame()} - +
- + + {#if deviceStore.isMobile} + + {/if}
{/snippet} diff --git a/ui/apps/chat/tests/stories/chat/form/ChatFormVoice.stories.svelte b/ui/apps/chat/tests/stories/chat/form/ChatFormVoice.stories.svelte new file mode 100644 index 000000000000..adf4ce014db1 --- /dev/null +++ b/ui/apps/chat/tests/stories/chat/form/ChatFormVoice.stories.svelte @@ -0,0 +1,118 @@ + + + + audioServer(VoiceInputMode.AUTO)} + name="RecordingVoiceMessage" + play={async ({ canvas, canvasElement, userEvent }) => { + const mic = canvas.getAllByRole('button', { name: VOICE_MODE_MESSAGE.voiceMessage }); + + await userEvent.click(mic[mic.length - 1]); + + await expect(await canvas.findByText(VOICE_MODE_MESSAGE.recording)).toBeInTheDocument(); + await expect(canvas.getByRole('button', { name: 'Cancel recording' })).toBeInTheDocument(); + // the live text shows as the empty message box's placeholder, the message stays empty + await waitFor( + () => expect(canvasElement.querySelector('.cm-placeholder')).toHaveTextContent(/What is the/), + { timeout: 3000 } + ); + // a placeholder shows only while the message itself is empty + }} +/> + + + audioServer(VoiceInputMode.DICTATION)} + name="RecordingDictation" + play={async ({ canvas, userEvent }) => { + const mic = canvas.getAllByRole('button', { name: VOICE_MODE_MESSAGE.dictate }); + + await userEvent.click(mic[mic.length - 1]); + + await expect(await canvas.findByText(VOICE_MODE_MESSAGE.dictating)).toBeInTheDocument(); + await waitFor(() => expect(canvas.getByRole('textbox')).toHaveTextContent('What is the'), { + timeout: 3000 + }); + }} +/> + + + audioServer(VoiceInputMode.AUTO)} + name="VoiceMessageRecorded" + play={async ({ canvas, userEvent }) => { + const mic = canvas.getAllByRole('button', { name: VOICE_MODE_MESSAGE.voiceMessage }); + + await userEvent.click(mic[mic.length - 1]); + await canvas.findByText(VOICE_MODE_MESSAGE.recording); + await new Promise((resolve) => setTimeout(resolve, 1200)); + + const stop = canvas.getAllByRole('button', { name: 'Stop recording' }); + + await userEvent.click(stop[stop.length - 1]); + + await waitFor(() => + expect(canvas.getAllByRole('slider', { name: /Voice message/ }).length).toBeGreaterThan(0) + ); + }} +/> + + audioServer(VoiceInputMode.AUTO)} + name="WithVoiceMessage" +/> diff --git a/ui/apps/chat/tests/stories/chat/form/ChatFormVoiceStoryHost.svelte b/ui/apps/chat/tests/stories/chat/form/ChatFormVoiceStoryHost.svelte new file mode 100644 index 000000000000..0c0e7a2d6994 --- /dev/null +++ b/ui/apps/chat/tests/stories/chat/form/ChatFormVoiceStoryHost.svelte @@ -0,0 +1,33 @@ + + + + diff --git a/ui/apps/chat/tests/stories/chat/messages/ChatMessageVoice.stories.svelte b/ui/apps/chat/tests/stories/chat/messages/ChatMessageVoice.stories.svelte new file mode 100644 index 000000000000..285a7ccbbad7 --- /dev/null +++ b/ui/apps/chat/tests/stories/chat/messages/ChatMessageVoice.stories.svelte @@ -0,0 +1,162 @@ + + + + seedVoice({ transcript: TRANSCRIPT })} + name="VoiceMessage" + play={async ({ canvas, canvasElement }) => { + const reveal = await waitFor(() => { + const element = canvasElement.querySelector('[data-slot="voice-transcript-reveal"]'); + + if (!element) throw new Error('no voice message'); + + return element as HTMLElement; + }); + + await expect(reveal).toHaveAttribute('data-revealed'); + // drawn word by word, see VoiceSpokenText + await expect(reveal).toHaveTextContent(TRANSCRIPT); + await expect(canvas.getByRole('button', { name: 'Hide transcript' })).toBeInTheDocument(); + }} +> + + + + + + seedVoice({ transcript: TRANSCRIPT }, '', { [SETTINGS_KEYS.VOICE_COLLAPSE_TRANSCRIPTS]: true })} + name="VoiceMessageCollapsed" + play={async ({ canvasElement, userEvent }) => { + const reveal = await waitFor(() => { + const element = canvasElement.querySelector('[data-slot="voice-transcript-reveal"]'); + + if (!element) throw new Error('no voice message'); + + return element as HTMLElement; + }); + + await expect(reveal).not.toHaveAttribute('data-revealed'); + await userEvent.hover(reveal); + await waitFor(() => expect(reveal).toHaveAttribute('data-revealed')); + // drawn word by word, see VoiceSpokenText + await expect(reveal).toHaveTextContent(TRANSCRIPT); + }} +> + + + + seedVoice({ transcript: TRANSCRIPT }, 'Answer in two sentences.')} + name="VoiceMessageWithText" +> + + + + + { + const restore = await seedVoice({ name: 'voice-pending.wav' }); + + voiceTranscriptsStore.track('voice-pending.wav', new Promise(() => {})); + + return restore; + }} + name="VoiceMessageTranscribing" + play={async ({ canvasElement }) => { + await waitFor(() => + expect(canvasElement.querySelector('[data-slot="voice-transcript-reveal"]')).toHaveAttribute( + 'data-status', + VoiceTranscriptStatus.TRANSCRIBING + ) + ); + }} +> + + + + + seedVoice({ peaks: undefined, transcript: TRANSCRIPT })} + name="VoiceMessageWithoutPeaks" + play={async ({ canvasElement }) => { + await waitFor(() => + expect( + canvasElement.querySelectorAll('[data-slot="voice-waveform"] [aria-hidden] span').length + ).toBeGreaterThan(0) + ); + }} +> + + diff --git a/ui/apps/chat/tests/stories/content/CollapsibleTerminalBlock.stories.svelte b/ui/apps/chat/tests/stories/content/CollapsibleTerminalBlock.stories.svelte index 840eeb12e7b0..00a963fa2a7c 100644 --- a/ui/apps/chat/tests/stories/content/CollapsibleTerminalBlock.stories.svelte +++ b/ui/apps/chat/tests/stories/content/CollapsibleTerminalBlock.stories.svelte @@ -15,7 +15,7 @@
-
running 3 tests
+			
running 3 tests
 test borrow::longest ... ok
 test borrow::shorter ... ok
 test borrow::equal ... ok
diff --git a/ui/apps/chat/tests/stories/content/MarkdownContent.stories.svelte b/ui/apps/chat/tests/stories/content/MarkdownContent.stories.svelte
index dbc8481c5ac3..5cbd5697c88c 100644
--- a/ui/apps/chat/tests/stories/content/MarkdownContent.stories.svelte
+++ b/ui/apps/chat/tests/stories/content/MarkdownContent.stories.svelte
@@ -3,7 +3,7 @@
 	import { MERMAID_DIAGRAMS_MD } from '../fixtures/mermaid-diagrams.js';
 	import { defineMeta } from '@storybook/addon-svelte-csf';
 	import { MarkdownContent } from '#lib/components/app/index.ts';
-	import { expect, waitFor } from 'storybook/test';
+	import { expect, userEvent, waitFor } from 'storybook/test';
 
 	const { Story } = defineMeta({
 		component: MarkdownContent,
@@ -36,5 +36,31 @@
 
 		await expect(error?.textContent).toContain('line 2');
 		await expect(error?.closest('pre')).toBeVisible();
+
+		// `click ... href` must not turn a node into a live link, as under Mermaid's strict mode
+		const flowchart = canvasElement.querySelector('pre.mermaid svg.pele');
+
+		await expect(flowchart?.textContent).toContain('llama-server');
+		await expect(canvasElement.querySelector('pre.mermaid a')).toBeNull();
+		await expect(
+			canvasElement.querySelector('pre.mermaid [href], pre.mermaid [*|href]')
+		).toBeNull();
+
+		// The preview button opens the diagram in a dialog that fills the window
+		await userEvent.click(canvasElement.querySelector('.preview-code-btn')!);
+
+		const preview = await waitFor(() => {
+			const el = document.querySelector('.mermaid-preview');
+
+			expect(el).not.toBeNull();
+
+			return el!;
+		});
+
+		await expect(preview.getBoundingClientRect().width).toBeCloseTo(window.innerWidth, 0);
+		await expect(preview.getBoundingClientRect().height).toBeCloseTo(window.innerHeight, 0);
+
+		await userEvent.keyboard('{Escape}');
+		await waitFor(() => expect(document.querySelector('.mermaid-preview')).toBeNull());
 	}}
 />
diff --git a/ui/apps/chat/tests/stories/content/MermaidPreview.stories.svelte b/ui/apps/chat/tests/stories/content/MermaidPreview.stories.svelte
new file mode 100644
index 000000000000..5949dd983fbc
--- /dev/null
+++ b/ui/apps/chat/tests/stories/content/MermaidPreview.stories.svelte
@@ -0,0 +1,143 @@
+
+
+ {
+		const viewport = await waitFor(() => {
+			const el = canvasElement.querySelector('.mermaid-preview');
+
+			expect(el?.querySelector('.mermaid-preview-diagram')).toBeVisible();
+
+			return el!;
+		});
+
+		// a font that loads late changes the height of the diagram's box, and so the fit
+		await document.fonts.ready;
+
+		const rect = viewport.getBoundingClientRect();
+		const middle = { x: rect.width / 2, y: rect.height / 2 };
+		const fitted = readView(canvasElement);
+		// the wheel zooms around the pointer
+		const pointer = { x: rect.width * 0.7, y: rect.height * 0.35 };
+		const underPointer = pointUnder(fitted, pointer.x, pointer.y);
+
+		viewport.dispatchEvent(
+			new WheelEvent('wheel', {
+				bubbles: true,
+				cancelable: true,
+				clientX: rect.left + pointer.x,
+				clientY: rect.top + pointer.y,
+				deltaY: -200
+			})
+		);
+		await waitFor(() => expect(readView(canvasElement).scale).toBeGreaterThan(fitted.scale));
+		await expect(screenOf(readView(canvasElement), underPointer).x).toBeCloseTo(pointer.x, 0);
+		await expect(screenOf(readView(canvasElement), underPointer).y).toBeCloseTo(pointer.y, 0);
+
+		// after a pan, the zoom buttons zoom around the middle of the viewport
+		const zoomed = readView(canvasElement);
+		const drag = (type: string, x: number, y: number) =>
+			viewport.dispatchEvent(
+				new PointerEvent(type, {
+					bubbles: true,
+					button: 0,
+					clientX: rect.left + x,
+					clientY: rect.top + y,
+					pointerId: 1
+				})
+			);
+
+		drag('pointerdown', 100, 100);
+		drag('pointermove', 260, 180);
+		drag('pointerup', 260, 180);
+		await waitFor(() => expect(readView(canvasElement).x).toBeCloseTo(zoomed.x + 160, 0));
+
+		const panned = readView(canvasElement);
+		const underMiddle = pointUnder(panned, middle.x, middle.y);
+
+		await userEvent.click(canvasElement.querySelector('[aria-label="Zoom out"]')!);
+		await waitFor(() => expect(readView(canvasElement).scale).toBeLessThan(panned.scale));
+		await expect(screenOf(readView(canvasElement), underMiddle).x).toBeCloseTo(middle.x, 0);
+		await expect(screenOf(readView(canvasElement), underMiddle).y).toBeCloseTo(middle.y, 0);
+
+		// reset fits the diagram again
+		await userEvent.click(canvasElement.querySelector('[aria-label="Reset view"]')!);
+		await waitFor(() => expectSameView(readView(canvasElement), fitted));
+		await expect(canvasElement.querySelector('.mermaid-preview-zoom-label')?.textContent).toBe(
+			`${Math.round(fitted.scale * 100)}%`
+		);
+	}}
+>
+	
+ +
+
+ + { + // fitting shrinks a diagram wider than the screen so all of it shows + await waitFor(() => expect(readView(canvasElement).scale).toBeLessThan(1)); + }} +> +
+ +
+
+ + +
+ +
+
+ + +
+ +
+
diff --git a/ui/apps/chat/tests/stories/dialogs/DialogMermaidPreview.stories.svelte b/ui/apps/chat/tests/stories/dialogs/DialogMermaidPreview.stories.svelte new file mode 100644 index 000000000000..a49b14304698 --- /dev/null +++ b/ui/apps/chat/tests/stories/dialogs/DialogMermaidPreview.stories.svelte @@ -0,0 +1,41 @@ + + + + + { + const content = await waitFor(() => { + const el = document.querySelector('[data-slot="dialog-content"]'); + + expect(el?.querySelector('.mermaid-preview')).not.toBeNull(); + + return el!; + }); + const rect = content.getBoundingClientRect(); + + await expect(rect.left).toBe(0); + await expect(rect.top).toBe(0); + await expect(rect.width).toBeCloseTo(window.innerWidth, 0); + await expect(rect.height).toBeCloseTo(window.innerHeight, 0); + }} +> + + diff --git a/ui/apps/chat/tests/stories/fixtures/mermaid-diagrams.ts b/ui/apps/chat/tests/stories/fixtures/mermaid-diagrams.ts index 40798c5b8cf8..bb1e2f39f84b 100644 --- a/ui/apps/chat/tests/stories/fixtures/mermaid-diagrams.ts +++ b/ui/apps/chat/tests/stories/fixtures/mermaid-diagrams.ts @@ -1,4 +1,5 @@ -// Mermaid blocks of several diagram types, and one that can't be drawn +// Mermaid blocks of several diagram types, and one that can't be drawn. The flowchart's +// click directives must leave it inert. const fence = '```'; export const MERMAID_DIAGRAMS_MD = String.raw` @@ -12,6 +13,8 @@ flowchart LR Q -->|no| W[Queue] W --> D D -->|SSE tokens| U + click S href "https://github.com/ggml-org/llama.cpp" "llama.cpp on GitHub" _blank + click D call alert(1) ${fence} The same exchange over time: diff --git a/ui/apps/chat/tests/stories/fixtures/mermaid-preview.ts b/ui/apps/chat/tests/stories/fixtures/mermaid-preview.ts new file mode 100644 index 000000000000..136d28d69cff --- /dev/null +++ b/ui/apps/chat/tests/stories/fixtures/mermaid-preview.ts @@ -0,0 +1,30 @@ +// Diagrams drawn with Pele, as renderMermaidDiagrams() draws them, for the preview stories +import { render } from 'pele'; + +export const FLOWCHART_SVG = render(`flowchart LR + U[Browser] -->|POST /v1/chat/completions| S(llama-server) + S --> Q{Slot free?} + Q -->|yes| D[Decode] + Q -->|no| W[Queue] + W --> D + D -->|SSE tokens| U`).svg; + +// wider than any screen, so fitting it shrinks it +export const PIPELINE_SVG = render(`flowchart LR + A[Download GGUF] --> B[Read metadata] --> C[Load tensors] --> D[Build graph] + D --> E[Tokenize prompt] --> F[Prompt processing] --> G[Sample token] + G --> H[Detokenize] --> I[Stream to client] --> J{Stop?} + J -->|no| G + J -->|yes| K[Free slot]`).svg; + +// small enough that fitting it grows it, up to the fit cap +export const SMALL_SVG = render(`flowchart TD + A[Prompt] --> B[Answer]`).svg; + +export const SEQUENCE_SVG = render(`sequenceDiagram + participant C as Llama Chat + participant S as llama-server + C->>S: POST /v1/chat/completions + S-->>C: data: {"choices":[...]} + S-->>C: data: [DONE] + Note over C,S: the stream ends with DONE`).svg; diff --git a/ui/apps/chat/tests/stories/foundations/SafeAreas.stories.svelte b/ui/apps/chat/tests/stories/foundations/SafeAreas.stories.svelte index d4ae8c6529a9..c99ee1260376 100644 --- a/ui/apps/chat/tests/stories/foundations/SafeAreas.stories.svelte +++ b/ui/apps/chat/tests/stories/foundations/SafeAreas.stories.svelte @@ -25,13 +25,13 @@
status bar · --safe-area-top
home indicator · --safe-area-bottom
@@ -39,7 +39,7 @@ {/snippet} {#snippet unpadded()} -
+

Page title under the status bar

Bottom bar over the home indicator

@@ -47,7 +47,7 @@ {/snippet} {#snippet page()} -
+

Page title, 3rem below the status bar

@@ -57,12 +57,12 @@ {/snippet} {#snippet sheet()} -

+

Type a message...

⤡ diff --git a/ui/apps/chat/tests/stories/introduction/Principles.svelte b/ui/apps/chat/tests/stories/introduction/Principles.svelte index 326b03a6ed94..e3c2630e757c 100644 --- a/ui/apps/chat/tests/stories/introduction/Principles.svelte +++ b/ui/apps/chat/tests/stories/introduction/Principles.svelte @@ -11,7 +11,7 @@
-
+
-
+
-
+
Recommended Reads, sees and hears @@ -51,7 +51,7 @@

Choices made for you to start; every setting when you want it.

-
+

The icon, the type, one accent. The rest is neutral.

-
-
+
+
@@ -77,7 +77,7 @@

Every element has a job and a reason for its size.

-
+
--neutral-900 @@ -87,7 +87,7 @@ - --button-primary-background + --button-primary-edge

Design lives in code

diff --git a/ui/apps/chat/tests/stories/introduction/Products.svelte b/ui/apps/chat/tests/stories/introduction/Products.svelte index 88827eb2f877..0e8c4ed9fc2d 100644 --- a/ui/apps/chat/tests/stories/introduction/Products.svelte +++ b/ui/apps/chat/tests/stories/introduction/Products.svelte @@ -10,7 +10,7 @@
-
+
ggml-org/llama-brand @@ -40,7 +40,7 @@ The icon and the app icons
-
+
ggml-org/llama.cpp
@@ -48,7 +48,7 @@

llama.cpp

-
+
The engine
-
+
Llama UI → Llama Chat Run llama-server and open Llama Chat
-
+
The native Llama apps
-
+

Llama for Mac

ggml-org/Llama-macOS @@ -86,7 +86,7 @@ A menu bar app, in Swift
-
+

Llama for Windows

ggml-org/Llama-Windows diff --git a/ui/apps/chat/tests/stories/introduction/Sections.svelte b/ui/apps/chat/tests/stories/introduction/Sections.svelte index baa8b68dac70..ba2073c50ea1 100644 --- a/ui/apps/chat/tests/stories/introduction/Sections.svelte +++ b/ui/apps/chat/tests/stories/introduction/Sections.svelte @@ -25,7 +25,7 @@ {#each sections as section (section.name)}
  • {#if section.icon} -
    +

    {section.name} @@ -48,7 +48,7 @@ {#if section.pages.length}

      {#each section.pages as page (page)} -
    • {page}
    • +
    • {page}
    • {/each}
    {/if} diff --git a/ui/apps/chat/tests/stories/introduction/Stack.svelte b/ui/apps/chat/tests/stories/introduction/Stack.svelte index dc0564852488..375b514f1358 100644 --- a/ui/apps/chat/tests/stories/introduction/Stack.svelte +++ b/ui/apps/chat/tests/stories/introduction/Stack.svelte @@ -5,7 +5,7 @@ dashed, dimmed slot for the other apps anyone can build on Llama UI. -->
    -
    +
    03

    Llama Chat

    @@ -13,19 +13,19 @@

    The app, built from Llama UI

    -
    +

    Other apps

    Yours, built on Llama UI

    -
    +

    Communications

    Posts, store screenshots, link previews and swag, made from the brand and the app

    -
    +
    02

    Llama UI

    @@ -33,7 +33,7 @@

    The components and their tokens

    -
    +
    01 diff --git a/ui/apps/chat/tests/stories/introduction/Uses.svelte b/ui/apps/chat/tests/stories/introduction/Uses.svelte index 36f5d2686ca1..45f35b94a683 100644 --- a/ui/apps/chat/tests/stories/introduction/Uses.svelte +++ b/ui/apps/chat/tests/stories/introduction/Uses.svelte @@ -32,8 +32,8 @@
    {#each uses as use (use.name)} -
    - +
    + diff --git a/ui/apps/chat/tests/stories/misc/CollapsibleSection.stories.svelte b/ui/apps/chat/tests/stories/misc/CollapsibleSection.stories.svelte index 578550b49390..6acb5b21822c 100644 --- a/ui/apps/chat/tests/stories/misc/CollapsibleSection.stories.svelte +++ b/ui/apps/chat/tests/stories/misc/CollapsibleSection.stories.svelte @@ -23,7 +23,7 @@ Pinned {/snippet} -
      +
      • Explain quantization
      • Rust borrow checker notes
      • diff --git a/ui/apps/chat/tests/stories/misc/ScrollCarousel.stories.svelte b/ui/apps/chat/tests/stories/misc/ScrollCarousel.stories.svelte index 07cd2a030b08..c3f62d8ebe94 100644 --- a/ui/apps/chat/tests/stories/misc/ScrollCarousel.stories.svelte +++ b/ui/apps/chat/tests/stories/misc/ScrollCarousel.stories.svelte @@ -24,7 +24,7 @@ {#each items as item (item)}
        {item}
        diff --git a/ui/apps/chat/tests/stories/settings/SettingsSections.stories.svelte b/ui/apps/chat/tests/stories/settings/SettingsSections.stories.svelte index 24b2c5c13b9b..de2d6b8f9063 100644 --- a/ui/apps/chat/tests/stories/settings/SettingsSections.stories.svelte +++ b/ui/apps/chat/tests/stories/settings/SettingsSections.stories.svelte @@ -17,6 +17,8 @@ + + diff --git a/ui/apps/chat/tests/stories/voice/VoiceLiveDemo.svelte b/ui/apps/chat/tests/stories/voice/VoiceLiveDemo.svelte new file mode 100644 index 000000000000..23c93f33997f --- /dev/null +++ b/ui/apps/chat/tests/stories/voice/VoiceLiveDemo.svelte @@ -0,0 +1,54 @@ + + + +
        + + + + {formatClipTime(elapsedMs)} + + + +
        diff --git a/ui/apps/chat/tests/stories/voice/VoiceWaveformLive.stories.svelte b/ui/apps/chat/tests/stories/voice/VoiceWaveformLive.stories.svelte new file mode 100644 index 000000000000..78715741a567 --- /dev/null +++ b/ui/apps/chat/tests/stories/voice/VoiceWaveformLive.stories.svelte @@ -0,0 +1,82 @@ + + + { + const live = canvasElement.querySelector('[data-slot="voice-waveform-live"]')!; + + await expect(live.querySelector('.sr-only')).toHaveTextContent('Recording'); + await expect(live.querySelector('[aria-hidden="true"]')).toBeInTheDocument(); + + const before = barHeights(canvasElement); + + await waitFor(() => expect(barHeights(canvasElement)).not.toBe(before)); + }} +> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        + +
        +
        diff --git a/ui/apps/chat/tests/stories/voice/fake-voice-recorder.svelte.ts b/ui/apps/chat/tests/stories/voice/fake-voice-recorder.svelte.ts new file mode 100644 index 000000000000..abbb5470ce95 --- /dev/null +++ b/ui/apps/chat/tests/stories/voice/fake-voice-recorder.svelte.ts @@ -0,0 +1,154 @@ +import type { VoiceSessionOptions, VoiceSessionResult } from '@ggml-org/llama-voice'; +import { VoiceRecorderStatus } from '@ggml-org/llama-voice'; +import type { VoiceRecorderLike } from '#lib/hooks/use-chat-form-voice.svelte.ts'; + +/** A transcript the test resolves when it wants. */ +export function deferred() { + let resolve!: (value: T) => void; + let reject!: (error: unknown) => void; + + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + + return { promise, reject, resolve }; +} + +/** A silent 16-bit mono WAV of `ms`, a valid clip to attach and play. */ +export function silentWav(ms = 500, sampleRate = 8000): Blob { + const samples = Math.round((ms / 1000) * sampleRate); + const buffer = new ArrayBuffer(44 + samples * 2); + const view = new DataView(buffer); + const write = (offset: number, text: string) => { + for (let i = 0; i < text.length; i++) view.setUint8(offset + i, text.charCodeAt(i)); + }; + + write(0, 'RIFF'); + view.setUint32(4, 36 + samples * 2, true); + write(8, 'WAVE'); + write(12, 'fmt '); + view.setUint32(16, 16, true); + view.setUint16(20, 1, true); + view.setUint16(22, 1, true); + view.setUint32(24, sampleRate, true); + view.setUint32(28, sampleRate * 2, true); + view.setUint16(32, 2, true); + view.setUint16(34, 16, true); + write(36, 'data'); + view.setUint32(40, samples * 2, true); + + return new Blob([buffer], { type: 'audio/wav' }); +} + +/** + * A VoiceRecorder without a microphone: the test drives its levels and live text and + * decides the transcript, and reads the options the form started it with. + */ +export class FakeVoiceRecorder implements VoiceRecorderLike { + cancelled = 0; + levels = $state.raw(new Array(48).fill(0)); + live = $state(false); + liveText = $state(''); + options: VoiceSessionOptions | undefined; + + quiet = $state(false); + startError: Error | null = null; + status = $state(VoiceRecorderStatus.IDLE); + transcript: Promise | null = null; + + cancel(): void { + this.cancelled++; + this.status = VoiceRecorderStatus.IDLE; + } + + /** Live text as a realtime socket would stream it. */ + say(text: string): void { + this.live = true; + this.liveText = text; + this.options?.onText?.(text); + } + + setLevels(levels: number[]): void { + this.levels = levels; + this.options?.onLevels?.(levels); + } + + /** The speech turning too quiet, or loud enough again, as the capture would tell. */ + setQuiet(quiet: boolean): void { + this.quiet = quiet; + this.options?.onQuiet?.(quiet); + } + + async start(options: VoiceSessionOptions = {}): Promise { + if (this.startError) throw this.startError; + + this.options = options; + this.liveText = ''; + this.status = VoiceRecorderStatus.RECORDING; + } + + async stop(): Promise { + this.status = VoiceRecorderStatus.IDLE; + + return { + clip: { + blob: silentWav(), + durationMs: 2400, + peaks: Array.from({ length: 64 }, (_, i) => Math.abs(Math.sin(i / 4))), + sampleRate: 8000 + }, + liveText: this.liveText.trim() || null, + transcript: this.options?.transcribe ? this.transcript : null + }; + } +} + +/** + * A fake recorder for stories: once started it moves its levels like someone speaking + * and, when given a script, streams it word by word as a realtime model would. + */ +export class DemoVoiceRecorder extends FakeVoiceRecorder { + private timer: ReturnType | undefined; + + override cancel(): void { + clearInterval(this.timer); + super.cancel(); + } + + constructor( + private script = '', + private level: (t: number) => number = () => Math.random() + ) { + super(); + } + + override async start(options: VoiceSessionOptions = {}): Promise { + await super.start(options); + + const words = this.script.split(' ').filter(Boolean); + const startedAt = Date.now(); + + let history = new Array(48).fill(0); + + this.timer = setInterval(() => { + const t = (Date.now() - startedAt) / 1000; + const spoken = Math.min(Math.floor(t * 2.5), words.length); + + history = [...history.slice(1), this.level(t)]; + this.setLevels(history); + + if (spoken > 0 && words.slice(0, spoken).join(' ') !== this.liveText) { + this.say(words.slice(0, spoken).join(' ')); + } + }, 50); + } + + override async stop(): Promise { + clearInterval(this.timer); + + if (!this.transcript && this.script) this.transcript = Promise.resolve(this.script); + + return super.stop(); + } +} diff --git a/ui/apps/chat/tests/stories/voice/fixtures.ts b/ui/apps/chat/tests/stories/voice/fixtures.ts new file mode 100644 index 000000000000..47788fa85a5d --- /dev/null +++ b/ui/apps/chat/tests/stories/voice/fixtures.ts @@ -0,0 +1,2 @@ +// the demo audio lives with the voice components' stories in Llama UI +export * from '../../../../../lib/ui/tests/stories/voice/fixtures'; diff --git a/ui/apps/chat/tests/unit/agentic-hotpath.bench.ts b/ui/apps/chat/tests/unit/agentic-hotpath.bench.ts index 685ccdf686ea..c46f3fe4bf68 100644 --- a/ui/apps/chat/tests/unit/agentic-hotpath.bench.ts +++ b/ui/apps/chat/tests/unit/agentic-hotpath.bench.ts @@ -7,7 +7,11 @@ // Run: npx vitest bench --project=unit tests/unit/agentic-hotpath.bench.ts import { classifyToolResult, parseToolResultWithMedia } from '#lib/utils/agentic.ts'; -import { detectIncompleteCodeBlock, highlightCode } from '#lib/utils/code.ts'; +import { + detectIncompleteCodeBlock, + highlightCode, + loadHighlightLanguages +} from '#lib/utils/code.ts'; import { computeLineDiff } from '#lib/utils/compute-line-diff.ts'; import { preprocessLaTeX } from '#lib/utils/latex-protection.ts'; import { parsePartialJsonArgs } from '#lib/utils/parse-partial-json-args.ts'; @@ -228,6 +232,9 @@ describe('parsePartialJsonArgs', () => { // --- F / I: highlight.js --------------------------------------------------- +// highlightCode returns plain text until highlight.js has loaded +await loadHighlightLanguages(); + describe('highlightCode', () => { bench('short bash command (title row, per token)', () => { highlightCode('grep -rn "foo" src/ | head -50', 'bash'); diff --git a/ui/apps/chat/tests/unit/code.test.ts b/ui/apps/chat/tests/unit/code.test.ts index 2ecaf69f018e..31f0c1846379 100644 --- a/ui/apps/chat/tests/unit/code.test.ts +++ b/ui/apps/chat/tests/unit/code.test.ts @@ -1,5 +1,12 @@ -import { highlightCode, splitGluedClosingCodeFences, trimCodePadding } from '#lib/utils/code.ts'; -import { describe, expect, it } from 'vitest'; +import { + highlightCode, + loadHighlightLanguages, + splitGluedClosingCodeFences, + trimCodePadding +} from '#lib/utils/code.ts'; +import { beforeAll, describe, expect, it } from 'vitest'; + +beforeAll(() => loadHighlightLanguages()); describe('trimCodePadding', () => { it('removes a single leading newline', () => { diff --git a/ui/apps/chat/tests/unit/conversation-search.test.ts b/ui/apps/chat/tests/unit/conversation-search.test.ts new file mode 100644 index 000000000000..86f6a59c20d1 --- /dev/null +++ b/ui/apps/chat/tests/unit/conversation-search.test.ts @@ -0,0 +1,91 @@ +import { AttachmentType, MessageRole, MessageType } from '#lib/enums/index.ts'; +import type { DatabaseMessage } from '#lib/types/database.js'; +import { findMessageMatch, matchSnippet, searchableTexts } from '#lib/utils/conversation-search.ts'; +import { describe, expect, it } from 'vitest'; + +function message(fields: Partial): DatabaseMessage { + return { + children: [], + content: '', + convId: 'conv', + id: 'msg', + parent: null, + role: MessageRole.ASSISTANT, + timestamp: 0, + type: MessageType.TEXT, + ...fields + } as DatabaseMessage; +} + +describe('searchableTexts', () => { + it('reads reasoning, content, tool calls and attachments, but no ids or payloads', () => { + const texts = searchableTexts( + message({ + content: 'the answer', + extra: [ + { content: 'notes inside', name: 'notes.txt', type: AttachmentType.TEXT }, + { base64Url: 'data:image/png;base64,QUJD', name: 'cat.png', type: AttachmentType.IMAGE } + ] as DatabaseMessage['extra'], + reasoningContent: 'thinking it over', + toolCalls: JSON.stringify([ + { function: { arguments: '{"q":"weather"}', name: 'web_search' }, id: 'call_secret' } + ]) + }) + ); + + expect(texts).toEqual([ + 'thinking it over', + 'the answer', + 'web_search', + '{"q":"weather"}', + 'notes.txt', + 'notes inside', + 'cat.png' + ]); + expect(texts.join(' ')).not.toContain('call_secret'); + expect(texts.join(' ')).not.toContain('QUJD'); + }); + + it('skips synthetic messages and tolerates broken tool call JSON', () => { + expect(searchableTexts(message({ content: 'cwd changed', isSynthetic: true }))).toEqual([]); + expect(searchableTexts(message({ content: 'ok', toolCalls: '{not json' }))).toEqual(['ok']); + }); +}); + +describe('findMessageMatch', () => { + it('matches case-insensitively and reports where', () => { + expect(findMessageMatch(message({ content: 'Plan a trip to Paris' }), 'paris')).toEqual({ + at: 15, + text: 'Plan a trip to Paris' + }); + }); + + it('finds tool output and reasoning', () => { + const tool = message({ content: 'sunny, 21C', role: MessageRole.TOOL }); + const reasoning = message({ reasoningContent: 'user wants Lisbon' }); + + expect(findMessageMatch(tool, 'sunny')).not.toBeNull(); + expect(findMessageMatch(reasoning, 'lisbon')).not.toBeNull(); + expect(findMessageMatch(tool, 'rain')).toBeNull(); + }); +}); + +describe('matchSnippet', () => { + it('keeps short text whole', () => { + expect(matchSnippet('find me here', 5, 2)).toEqual({ + after: ' here', + before: 'find ', + match: 'me' + }); + }); + + it('cuts long text around the match on one line', () => { + const text = `${'a'.repeat(100)}\n\nneedle\n${'b'.repeat(200)}`; + const snippet = matchSnippet(text, 102, 6, 40); + + expect(snippet.match).toBe('needle'); + expect(snippet.before.startsWith('...')).toBe(true); + expect(snippet.after.endsWith('...')).toBe(true); + expect(snippet.before + snippet.match + snippet.after).not.toContain('\n'); + }); +}); diff --git a/ui/apps/chat/tests/unit/diagram-viewport.test.ts b/ui/apps/chat/tests/unit/diagram-viewport.test.ts new file mode 100644 index 000000000000..cace3f1fee8f --- /dev/null +++ b/ui/apps/chat/tests/unit/diagram-viewport.test.ts @@ -0,0 +1,111 @@ +import { + DIAGRAM_MAX_FIT_SCALE, + DIAGRAM_MAX_SCALE, + DIAGRAM_MIN_SCALE, + type DiagramView, + fitView, + wheelZoomFactor, + zoomAt, + zoomAtCenter +} from '#lib/utils/diagram-viewport.ts'; +import { describe, expect, it } from 'vitest'; + +// where the diagram point (x, y) shows on screen +function onScreen(view: DiagramView, x: number, y: number) { + return { x: x * view.scale + view.x, y: y * view.scale + view.y }; +} + +// the diagram point under the screen point (x, y) +function underScreen(view: DiagramView, x: number, y: number) { + return { x: (x - view.x) / view.scale, y: (y - view.y) / view.scale }; +} + +describe('zoomAt', () => { + it('keeps the diagram point under the zoom point in place', () => { + const view = { scale: 1.5, x: -120, y: 40 }; + const under = underScreen(view, 300, 200); + const zoomed = zoomAt(view, 2, 300, 200); + + expect(zoomed.scale).toBe(3); + expect(onScreen(zoomed, under.x, under.y).x).toBeCloseTo(300); + expect(onScreen(zoomed, under.x, under.y).y).toBeCloseTo(200); + }); + + it('clamps the scale and still keeps the point in place', () => { + const view = { scale: 8, x: 10, y: 10 }; + const under = underScreen(view, 50, 60); + const zoomed = zoomAt(view, 4, 50, 60); + + expect(zoomed.scale).toBe(DIAGRAM_MAX_SCALE); + expect(onScreen(zoomed, under.x, under.y).x).toBeCloseTo(50); + expect(zoomAt({ scale: 0.2, x: 0, y: 0 }, 0.1, 0, 0).scale).toBe(DIAGRAM_MIN_SCALE); + }); +}); + +describe('zoomAtCenter', () => { + it('zooms around the middle of the viewport after a pan, not the diagram origin', () => { + const viewport = { height: 600, width: 800 }; + // zoomed in and panned away from where the diagram started + const panned = { scale: 2, x: -500, y: -300 }; + const under = underScreen(panned, 400, 300); + const out = zoomAtCenter(panned, 0.5, viewport); + + expect(out.scale).toBe(1); + expect(onScreen(out, under.x, under.y).x).toBeCloseTo(400); + expect(onScreen(out, under.x, under.y).y).toBeCloseTo(300); + }); + + it('zooming in and out again returns to the same view', () => { + const viewport = { height: 600, width: 800 }; + const view = { scale: 1.3, x: 25, y: -70 }; + const back = zoomAtCenter(zoomAtCenter(view, 1.25, viewport), 1 / 1.25, viewport); + + expect(back.scale).toBeCloseTo(view.scale); + expect(back.x).toBeCloseTo(view.x); + expect(back.y).toBeCloseTo(view.y); + }); +}); + +describe('fitView', () => { + it('shrinks a large diagram to fit and centers it', () => { + const view = fitView({ height: 500, width: 2000 }, { height: 800, width: 1000 }, 50); + + expect(view.scale).toBeCloseTo(0.45); + expect(view.x).toBeCloseTo(50); + expect(view.y).toBeCloseTo((800 - 500 * 0.45) / 2); + }); + + it('grows a small diagram no more than the fit cap', () => { + expect(fitView({ height: 50, width: 100 }, { height: 800, width: 1000 }).scale).toBe( + DIAGRAM_MAX_FIT_SCALE + ); + }); + + it('leaves an unmeasured diagram at its own size', () => { + expect(fitView({ height: 0, width: 0 }, { height: 800, width: 1000 })).toEqual({ + scale: 1, + x: 0, + y: 0 + }); + }); +}); + +describe('wheelZoomFactor', () => { + it('zooms in on a wheel up and out on a wheel down', () => { + expect(wheelZoomFactor({ ctrlKey: false, deltaMode: 0, deltaY: -100 })).toBeGreaterThan(1); + expect(wheelZoomFactor({ ctrlKey: false, deltaMode: 0, deltaY: 100 })).toBeLessThan(1); + }); + + it('a wheel step up and back down cancel out', () => { + const up = wheelZoomFactor({ ctrlKey: false, deltaMode: 1, deltaY: -3 }); + const down = wheelZoomFactor({ ctrlKey: false, deltaMode: 1, deltaY: 3 }); + + expect(up * down).toBeCloseTo(1); + }); + + it('a trackpad pinch zooms faster per pixel than a wheel', () => { + expect(wheelZoomFactor({ ctrlKey: true, deltaMode: 0, deltaY: -10 })).toBeGreaterThan( + wheelZoomFactor({ ctrlKey: false, deltaMode: 0, deltaY: -10 }) + ); + }); +}); diff --git a/ui/apps/chat/tests/unit/lazy-highlight.test.ts b/ui/apps/chat/tests/unit/lazy-highlight.test.ts new file mode 100644 index 000000000000..f766706c2387 --- /dev/null +++ b/ui/apps/chat/tests/unit/lazy-highlight.test.ts @@ -0,0 +1,117 @@ +import { rehypeLazyHighlight } from '#lib/components/app/content/MarkdownContent/plugins/rehype/lazy-highlight.ts'; +import { + highlightCode, + isHighlightLanguageLoaded, + loadHighlightLanguages, + resolveHighlightLanguage +} from '#lib/utils/code.ts'; +import type { Root } from 'hast'; +import rehypeStringify from 'rehype-stringify'; +import { remark } from 'remark'; +import remarkRehype from 'remark-rehype'; +import { describe, expect, it } from 'vitest'; + +// one file, so these run in order against one fresh loader: nothing has loaded when it starts +describe('highlightCode before its language loads', () => { + it('resolves aliases to highlight.js names', () => { + expect(resolveHighlightLanguage('ts')).toBe('typescript'); + expect(resolveHighlightLanguage('SH')).toBe('bash'); + expect(resolveHighlightLanguage('yml')).toBe('yaml'); + expect(resolveHighlightLanguage('python')).toBe('python'); + expect(resolveHighlightLanguage('constructor')).toBeUndefined(); + expect(resolveHighlightLanguage('not-a-language')).toBeUndefined(); + }); + + it('returns plain text, then highlights once that language (and only it) has loaded', async () => { + expect(highlightCode('\nconst x = 1;\n', 'ts')).toBe('const x = 1;'); + + await loadHighlightLanguages(['ts']); + + expect(isHighlightLanguageLoaded('typescript')).toBe(true); + expect(highlightCode('const x = 1;', 'ts')).toContain('hljs-keyword'); + expect(isHighlightLanguageLoaded('python')).toBe(false); + }); + + it('loads the languages a language embeds with it', async () => { + await loadHighlightLanguages(['html']); + + expect(isHighlightLanguageLoaded('css')).toBe(true); + expect(highlightCode('', 'html')).toContain('hljs-attribute'); + }); + + it('leaves an unknown language plain without auto-detection', () => { + expect(highlightCode('a && b', 'not-a-language', false)).toBe( + '<b>a && b</b>' + ); + }); + + it('auto-detects an unknown language among the common languages once they load', async () => { + const code = 'def greet(name):\n return f"hi {name}"'; + + expect(highlightCode(code, 'not-a-language')).toBe(code); + + // that call started loading every common language + const html = await waitForHighlight(() => highlightCode(code, 'not-a-language')); + + expect(html).toContain('hljs-'); + }); +}); + +async function waitForHighlight(highlight: () => string): Promise { + for (let i = 0; i < 50; i++) { + const html = highlight(); + + if (html.includes('hljs-')) return html; + + await new Promise((resolve) => setTimeout(resolve, 20)); + } + + return highlight(); +} + +const processor = remark() + .use(remarkRehype) + .use(rehypeLazyHighlight, { aliases: { xml: ['svelte'] } }) + .use(rehypeStringify); + +async function render(markdown: string): Promise { + return processor.stringify((await processor.run(processor.parse(markdown))) as Root); +} + +describe('rehypeLazyHighlight', () => { + it('leaves a message without a code block as it is, in the same pass', () => { + const tree = processor.runSync(processor.parse('Just *text* and `code`')) as Root; + + expect(processor.stringify(tree)).toBe('

        Just text and code

        '); + }); + + it('loads a block language, then highlights it in the same pass', async () => { + const markdown = '```rust\nfn main() {}\n```'; + const first = await render(markdown); + + expect(first).toContain(''); + expect(first).toContain('hljs-keyword'); + + const second = processor.stringify(processor.runSync(processor.parse(markdown)) as Root); + + expect(second).toBe(first); + }); + + it('uses highlight.js definitions, not highlightCode bash changes', async () => { + const html = await render('```sh\ncurl -LsSf https://example.com\n```'); + + expect(html).toContain(''); + expect(html).not.toContain('hljs-built_in">curl'); + }); + + it('takes extra aliases', async () => { + expect(await render('```svelte\n
        {x}
        \n```')).toContain('hljs-tag'); + }); + + it('leaves unknown languages, no-highlight and blocks without a language plain', async () => { + expect(await render('```not-a-language\nx = 1\n```')).toBe( + '
        x = 1\n
        ' + ); + expect(await render('```\nx = 1\n```')).toBe('
        x = 1\n
        '); + }); +}); diff --git a/ui/apps/chat/tests/unit/token-roles.test.ts b/ui/apps/chat/tests/unit/token-roles.test.ts new file mode 100644 index 000000000000..5449c6b7d73f --- /dev/null +++ b/ui/apps/chat/tests/unit/token-roles.test.ts @@ -0,0 +1,56 @@ +import { readdirSync, readFileSync } from 'node:fs'; +import { join, relative } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; + +// Type is set through the roles in ui/lib/ui/src/lib/styles/tokens/semantic.css (text-body-sm, text-label, +// text-caption ...), never Tailwind's own sizes or a size in brackets: see Typography in DESIGN.md. +const ui = fileURLToPath(new URL('../../../../', import.meta.url)); +const ROOTS = ['apps/chat/src', 'apps/chat/tests/stories', 'lib/ui/src', 'lib/ui/tests/stories']; +const SOURCE = /\.(svelte|ts|js|css|svx)$/; +const TAILWIND_SIZE = /(? { + const path = join(dir, entry.name); + + if (entry.isDirectory()) return sources(path); + + return SOURCE.test(entry.name) ? [path] : []; + }); +} + +function matches(pattern: RegExp): string[] { + return ROOTS.flatMap((root) => sources(join(ui, root))).flatMap((path) => + [...readFileSync(path, 'utf8').matchAll(pattern)].map( + ([match]) => `${relative(ui, path)}: ${match}` + ) + ); +} + +describe('type roles', () => { + it('uses no Tailwind text size', () => { + expect(matches(TAILWIND_SIZE)).toEqual([]); + }); + + it('uses no text size in brackets', () => { + expect(matches(BRACKET_SIZE)).toEqual([]); + }); +}); + +describe('shadows and corners', () => { + it('uses no Tailwind shadow size', () => { + expect(matches(TAILWIND_SHADOW)).toEqual([]); + }); + + it('uses no corner role', () => { + expect(matches(CORNER_ROLE)).toEqual([]); + }); +}); diff --git a/ui/apps/chat/tests/unit/voice-message-send.test.ts b/ui/apps/chat/tests/unit/voice-message-send.test.ts new file mode 100644 index 000000000000..36858e504202 --- /dev/null +++ b/ui/apps/chat/tests/unit/voice-message-send.test.ts @@ -0,0 +1,119 @@ +// Guards how a voice message goes to a model: the audio alone to a model with audio input, +// its transcript as text to one without, and the copied message carrying the transcript. + +import { AttachmentType, ContentPartType, MessageRole, MessageType } from '#lib/enums/index.ts'; +import { ChatService } from '#lib/services/chat.service.ts'; +import { modelsStore } from '#lib/stores/models/index.svelte.ts'; +import { withTranscript } from '#lib/stores/voice-transcripts.svelte.ts'; +import type { DatabaseMessage, DatabaseMessageExtra } from '#lib/types/index.ts'; +import { formatMessageForClipboard } from '#lib/utils/clipboard.ts'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +const voiceClip: DatabaseMessageExtra = { + base64Data: 'UklGRg==', + durationMs: 2400, + mimeType: 'audio/wav', + name: 'voice-1.wav', + peaks: [0.2, 1, 0.4], + transcript: 'What is the weather like on Mars?', + type: AttachmentType.AUDIO, + voice: true +}; + +function userMessage(extra: DatabaseMessageExtra[], content = ''): DatabaseMessage { + return { + children: [], + content, + convId: 'c1', + extra, + id: 'm1', + parent: null, + role: MessageRole.USER, + timestamp: 0, + type: MessageType.TEXT + } as DatabaseMessage; +} + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('sending a voice message', () => { + it('sends the audio alone to a model with audio input', async () => { + const result = await ChatService.convertDbMessageToApiChatMessageData( + userMessage([voiceClip]), + { audioInput: true } + ); + const parts = result.content as { type: string; text?: string }[]; + + expect(parts).toHaveLength(1); + expect(parts[0].type).toBe(ContentPartType.INPUT_AUDIO); + expect(JSON.stringify(parts)).not.toContain('Mars'); + }); + + it('sends the transcript as text to a model without audio input', async () => { + const result = await ChatService.convertDbMessageToApiChatMessageData( + userMessage([voiceClip], 'Answer briefly.'), + { audioInput: false } + ); + const parts = result.content as { type: string; text?: string }[]; + + expect(parts.map((part) => part.type)).toEqual([ContentPartType.TEXT, ContentPartType.TEXT]); + expect(parts[0].text).toContain('Voice message transcript'); + expect(parts[0].text).toContain('What is the weather like on Mars?'); + expect(parts[1].text).toBe('Answer briefly.'); + }); + + it('keeps the audio when there is no transcript to send instead', async () => { + const { transcript: _transcript, ...withoutTranscript } = voiceClip as { + transcript?: string; + } & DatabaseMessageExtra; + const result = await ChatService.convertDbMessageToApiChatMessageData( + userMessage([withoutTranscript as DatabaseMessageExtra]), + { audioInput: false } + ); + + expect((result.content as { type: string }[])[0].type).toBe(ContentPartType.INPUT_AUDIO); + }); + + it('keeps the audio while the model modalities are unknown', () => { + vi.spyOn(modelsStore.props, 'getModelModalities').mockReturnValue(null); + + expect(ChatService.conversionOptionsFor('some-model')).toEqual({}); + }); + + it('reads the audio input from the model modalities', () => { + vi.spyOn(modelsStore.props, 'getModelModalities').mockReturnValue({ + audio: false, + video: false, + vision: true + }); + + expect(ChatService.conversionOptionsFor('text-model')).toEqual({ audioInput: false }); + }); +}); + +describe('a transcript that arrives after the send', () => { + it('fills in the clip it belongs to only', () => { + const pending = { ...voiceClip, transcript: undefined } as DatabaseMessageExtra; + const other = { ...pending, name: 'voice-2.wav' } as DatabaseMessageExtra; + const next = withTranscript([pending, other], 'voice-1.wav', 'Hello'); + + expect(next?.[0]).toMatchObject({ name: 'voice-1.wav', transcript: 'Hello' }); + expect(next?.[1]).toBe(other); + }); + + it('leaves a message without that clip alone', () => { + expect(withTranscript([voiceClip], 'voice-1.wav', 'Hello')).toBeNull(); + expect(withTranscript(undefined, 'voice-1.wav', 'Hello')).toBeNull(); + }); +}); + +describe('copying a voice message', () => { + it('copies the transcript as the text', () => { + expect(formatMessageForClipboard('', [voiceClip])).toBe('What is the weather like on Mars?'); + expect(formatMessageForClipboard('Briefly.', [voiceClip], true)).toBe( + 'What is the weather like on Mars?\n\nBriefly.' + ); + }); +}); diff --git a/ui/apps/chat/tests/unit/voice-microphone.test.ts b/ui/apps/chat/tests/unit/voice-microphone.test.ts new file mode 100644 index 000000000000..8662c449cabd --- /dev/null +++ b/ui/apps/chat/tests/unit/voice-microphone.test.ts @@ -0,0 +1,71 @@ +// Guards which microphone a recording uses: the system default, unless that is a +// Bluetooth headset and a built-in microphone exists, or the one picked in Settings. + +import { + pickMicrophone, + VOICE_MICROPHONE_AUTO, + VOICE_MICROPHONE_DEFAULT +} from '@ggml-org/llama-voice'; +import { SETTING_CONFIG_DEFAULT, SETTINGS_KEYS } from '#lib/constants/index.ts'; +import { describe, expect, it } from 'vitest'; + +const input = (deviceId: string, label: string) => ({ + deviceId, + kind: 'audioinput' as const, + label +}); +const output = (deviceId: string, label: string) => ({ + deviceId, + kind: 'audiooutput' as const, + label +}); +const BUILT_IN = input('built-in', 'MacBook Pro Microphone (Built-in)'); +const AIRPODS = input('airpods', 'AirPods Pro (Bluetooth)'); +const USB = input('usb', 'Yeti Stereo Microphone'); + +describe('pickMicrophone', () => { + it('defaults to Automatic', () => { + expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.VOICE_MICROPHONE]).toBe(VOICE_MICROPHONE_AUTO); + }); + + it('keeps the system default when it is not a Bluetooth headset', () => { + const devices = [input('default', 'Default - Yeti Stereo Microphone'), BUILT_IN, USB, AIRPODS]; + + expect(pickMicrophone(devices, VOICE_MICROPHONE_AUTO)).toBeUndefined(); + }); + + it('takes the built-in microphone over a Bluetooth headset that is the default', () => { + const devices = [ + input('default', 'Default - AirPods Pro (Bluetooth)'), + AIRPODS, + BUILT_IN, + output('airpods-out', 'AirPods Pro (Bluetooth)') + ]; + + expect(pickMicrophone(devices, VOICE_MICROPHONE_AUTO)).toBe('built-in'); + }); + + it('reads the first input as the default where the browser lists no default entry', () => { + expect(pickMicrophone([AIRPODS, BUILT_IN], VOICE_MICROPHONE_AUTO)).toBe('built-in'); + expect(pickMicrophone([USB, AIRPODS], VOICE_MICROPHONE_AUTO)).toBeUndefined(); + }); + + it('keeps a Bluetooth headset when there is no built-in microphone', () => { + const devices = [input('default', 'Default - AirPods Pro (Bluetooth)'), AIRPODS, USB]; + + expect(pickMicrophone(devices, VOICE_MICROPHONE_AUTO)).toBeUndefined(); + }); + + it('uses the system default when asked to', () => { + expect(pickMicrophone([AIRPODS, BUILT_IN], VOICE_MICROPHONE_DEFAULT)).toBeUndefined(); + }); + + it('uses a picked microphone while it is connected', () => { + expect(pickMicrophone([BUILT_IN, USB], 'usb')).toBe('usb'); + expect(pickMicrophone([BUILT_IN], 'usb')).toBeUndefined(); + }); + + it('knows nothing before the browser names the microphones', () => { + expect(pickMicrophone([input('', ''), input('', '')], VOICE_MICROPHONE_AUTO)).toBeUndefined(); + }); +}); diff --git a/ui/apps/chat/tests/unit/voice-mode.test.ts b/ui/apps/chat/tests/unit/voice-mode.test.ts new file mode 100644 index 000000000000..8b0e0b6beee6 --- /dev/null +++ b/ui/apps/chat/tests/unit/voice-mode.test.ts @@ -0,0 +1,240 @@ +// Guards what the microphone does for a conversation's model: a voice message for a model +// that hears, dictation otherwise, and why it can't when no model can transcribe; and each +// model's part in voice input, as the model lists show it. + +import { + SETTING_CONFIG_DEFAULT, + SETTINGS_CHAT_SECTIONS, + SETTINGS_KEYS, + SETTINGS_SECTION_SLUGS, + VOICE_MODE_MESSAGE, + VOICE_TRANSCRIPTION_MODEL_AUTO +} from '#lib/constants/index.ts'; +import { SettingsFieldType, VoiceInputMode, VoiceMode, VoiceModelRole } from '#lib/enums/index.ts'; +import { + dictationModelFor, + isTranscriptionOnlyModel, + resolveVoiceMode, + type VoiceModeInput, + voiceModeLabel, + voiceModelRole +} from '#lib/utils/voice-mode.ts'; +import { describe, expect, it } from 'vitest'; + +const base: VoiceModeInput = { + chatModel: 'gemma-3n', + chatModelHasAudio: true, + isRouter: true, + setting: VoiceInputMode.AUTO, + transcriptionModel: '', + transcriptionModelHasAudio: false +}; + +describe('resolveVoiceMode', () => { + it('sends a voice message to a chat model with audio, transcribed by that model', () => { + expect(resolveVoiceMode(base)).toEqual({ + mode: VoiceMode.VOICE_MESSAGE, + separateModel: false, + transcriptionModel: 'gemma-3n' + }); + }); + + it('dictates with a speech-to-text model picked for the conversation', () => { + expect(resolveVoiceMode({ ...base, chatModel: 'org/VibeVoice-ASR:Q8_0' })).toEqual({ + mode: VoiceMode.DICTATION, + separateModel: false, + transcriptionModel: 'org/VibeVoice-ASR:Q8_0' + }); + }); + + it('dictates with the chat model when the user always dictates', () => { + expect(resolveVoiceMode({ ...base, setting: VoiceInputMode.DICTATION })).toEqual({ + mode: VoiceMode.DICTATION, + separateModel: false, + transcriptionModel: 'gemma-3n' + }); + }); + + it('prefers the chat model over a chosen transcription model when it can hear', () => { + const result = resolveVoiceMode({ + ...base, + setting: VoiceInputMode.DICTATION, + transcriptionModel: 'voxtral', + transcriptionModelHasAudio: true + }); + + expect(result).toMatchObject({ separateModel: false, transcriptionModel: 'gemma-3n' }); + }); + + it('dictates with the chosen model for a chat model without audio, in router mode', () => { + expect( + resolveVoiceMode({ + ...base, + chatModel: 'qwen3', + chatModelHasAudio: false, + transcriptionModel: 'voxtral', + transcriptionModelHasAudio: true + }) + ).toEqual({ mode: VoiceMode.DICTATION, separateModel: true, transcriptionModel: 'voxtral' }); + }); + + it('is unavailable when no model can transcribe', () => { + const noAudio = { ...base, chatModel: 'qwen3', chatModelHasAudio: false }; + + expect(resolveVoiceMode(noAudio)).toEqual({ + mode: VoiceMode.UNAVAILABLE, + reason: VOICE_MODE_MESSAGE.unavailable + }); + // a chosen model without audio input does not count + expect( + resolveVoiceMode({ + ...noAudio, + transcriptionModel: 'llama', + transcriptionModelHasAudio: false + }).mode + ).toBe(VoiceMode.UNAVAILABLE); + }); + + it('falls back to a loaded model with audio input on Automatic, loading nothing', () => { + const noAudio = { ...base, chatModel: 'qwen3', chatModelHasAudio: false }; + + expect(resolveVoiceMode({ ...noAudio, loadedAudioModel: 'qwen3-asr' })).toEqual({ + mode: VoiceMode.DICTATION, + separateModel: false, + transcriptionModel: 'qwen3-asr' + }); + // a chosen model wins over the loaded one + expect( + resolveVoiceMode({ + ...noAudio, + loadedAudioModel: 'qwen3-asr', + transcriptionModel: 'voxtral', + transcriptionModelHasAudio: true + }) + ).toEqual({ mode: VoiceMode.DICTATION, separateModel: true, transcriptionModel: 'voxtral' }); + // so does the chat model, when it hears + expect(resolveVoiceMode({ ...base, loadedAudioModel: 'qwen3-asr' }).mode).toBe( + VoiceMode.VOICE_MESSAGE + ); + // and nothing is loaded behind the user's back + expect(resolveVoiceMode({ ...noAudio, loadedAudioModel: null }).mode).toBe( + VoiceMode.UNAVAILABLE + ); + expect( + resolveVoiceMode({ ...noAudio, isRouter: false, loadedAudioModel: 'qwen3-asr' }).mode + ).toBe(VoiceMode.UNAVAILABLE); + }); + + it('ignores the transcription model on a single-model server', () => { + expect( + resolveVoiceMode({ + ...base, + chatModelHasAudio: false, + isRouter: false, + transcriptionModel: 'voxtral', + transcriptionModelHasAudio: true + }).mode + ).toBe(VoiceMode.UNAVAILABLE); + }); + + it('labels the microphone with what it will do', () => { + expect(voiceModeLabel(resolveVoiceMode(base))).toBe('Send a voice message'); + expect(voiceModeLabel(resolveVoiceMode({ ...base, setting: VoiceInputMode.DICTATION }))).toBe( + 'Dictate' + ); + expect(voiceModeLabel(resolveVoiceMode({ ...base, chatModelHasAudio: false }))).toBe( + VOICE_MODE_MESSAGE.unavailable + ); + }); +}); + +describe('voice settings', () => { + const section = SETTINGS_CHAT_SECTIONS.find((s) => s.slug === SETTINGS_SECTION_SLUGS.VOICE); + + it('default to automatic voice input and transcription model', () => { + expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.VOICE_INPUT_MODE]).toBe(VoiceInputMode.AUTO); + expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.VOICE_TRANSCRIBE_MESSAGES]).toBe(true); + expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.VOICE_COLLAPSE_TRANSCRIPTS]).toBe(false); + expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.VOICE_BOOST]).toBe(true); + expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.VOICE_NOISE_SUPPRESSION]).toBe(false); + expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.VOICE_ECHO_CANCELLATION]).toBe(false); + expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.VOICE_AUTO_GAIN]).toBe(false); + expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.VOICE_TRANSCRIPTION_MODEL]).toBe( + VOICE_TRANSCRIPTION_MODEL_AUTO + ); + expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.VOICE_TRANSCRIPTION_LANGUAGE]).toBe(''); + }); + + it('have a section of their own, the model picker drawn by it', () => { + const keys = section?.fields?.map((field) => field.key); + + expect(keys).toEqual([ + SETTINGS_KEYS.VOICE_INPUT_MODE, + SETTINGS_KEYS.VOICE_TRANSCRIBE_MESSAGES, + SETTINGS_KEYS.VOICE_COLLAPSE_TRANSCRIPTS, + SETTINGS_KEYS.VOICE_BOOST, + SETTINGS_KEYS.VOICE_NOISE_SUPPRESSION, + SETTINGS_KEYS.VOICE_ECHO_CANCELLATION, + SETTINGS_KEYS.VOICE_AUTO_GAIN, + SETTINGS_KEYS.VOICE_TRANSCRIPTION_LANGUAGE + ]); + expect(section?.fields?.[0].type).toBe(SettingsFieldType.SELECT); + }); +}); + +describe('isTranscriptionOnlyModel', () => { + it('knows speech-to-text models by name', () => { + expect(isTranscriptionOnlyModel('ggml-org/Qwen3-ASR-0.6B-GGUF:Q8_0')).toBe(true); + expect(isTranscriptionOnlyModel('ggerganov/whisper-large-v3')).toBe(true); + expect(isTranscriptionOnlyModel('nvidia/parakeet-tdt-0.6b')).toBe(true); + }); + + it('leaves chat models with audio input alone, even with the letters inside a word', () => { + expect(isTranscriptionOnlyModel('ggml-org/LFM3-Omni-2B-GGUF:Q8_0')).toBe(false); + expect(isTranscriptionOnlyModel('google/gemma-3n-E4B')).toBe(false); + expect(isTranscriptionOnlyModel('org/Lasr-chat')).toBe(false); + }); +}); + +describe('dictationModelFor', () => { + const router = { isRouter: true, transcriptionModelHasAudio: true }; + + it('is the chosen transcription model when it hears', () => { + expect(dictationModelFor({ ...router, transcriptionModel: 'asr' })).toBe('asr'); + expect( + dictationModelFor({ ...router, transcriptionModel: 'asr', transcriptionModelHasAudio: false }) + ).toBeNull(); + }); + + it('is a loaded model with audio input on Automatic, none when nothing hears', () => { + expect( + dictationModelFor({ + ...router, + loadedAudioModel: 'omni', + transcriptionModel: VOICE_TRANSCRIPTION_MODEL_AUTO + }) + ).toBe('omni'); + expect( + dictationModelFor({ ...router, transcriptionModel: VOICE_TRANSCRIPTION_MODEL_AUTO }) + ).toBeNull(); + }); + + it("is a single-model server's model when it hears", () => { + const single = { isRouter: false, transcriptionModel: '', transcriptionModelHasAudio: false }; + + expect(dictationModelFor({ ...single, singleModel: 'omni', singleModelHasAudio: true })).toBe( + 'omni' + ); + expect( + dictationModelFor({ ...single, singleModel: 'text', singleModelHasAudio: false }) + ).toBeNull(); + }); +}); + +describe('voiceModelRole', () => { + it('tells speech-to-text models from chat models that hear, and leaves the rest out', () => { + expect(voiceModelRole('org/Qwen3-ASR', true)).toBe(VoiceModelRole.TRANSCRIPTION); + expect(voiceModelRole('omni', true)).toBe(VoiceModelRole.VOICE); + expect(voiceModelRole('text-only', false)).toBeNull(); + }); +}); diff --git a/ui/apps/chat/tsconfig.json b/ui/apps/chat/tsconfig.json index 574b1ab6acc9..74af0cce0360 100644 --- a/ui/apps/chat/tsconfig.json +++ b/ui/apps/chat/tsconfig.json @@ -9,12 +9,15 @@ "@ggml-org/llama-ui/enums": ["../../lib/ui/src/lib/enums/index.ts"], "@ggml-org/llama-ui/code": ["../../lib/ui/src/lib/utils/index.ts"], "@ggml-org/llama-ui/utils": ["../../lib/ui/src/lib/components/ui/utils.ts"], + "@ggml-org/llama-ui/voice": ["../../lib/ui/src/lib/components/voice/index.ts"], "@ggml-org/llama-ui/styles/*": ["../../lib/ui/src/lib/styles/*"], "@ggml-org/llama-ui/theme.css": ["../../lib/ui/src/lib/styles/theme.css"], "@ggml-org/llama-ui/tokens.css": ["../../lib/ui/src/lib/styles/tokens.css"], "@ggml-org/llama-ui/fonts.css": ["../../lib/ui/src/lib/styles/fonts.css"], "@ggml-org/llama-ui/surfaces.css": ["../../lib/ui/src/lib/styles/surfaces.css"], "@ggml-org/llama-ui": ["../../lib/ui/src/lib/index.ts"], + "@ggml-org/llama-voice": ["../../lib/voice/src/index.ts"], + "@ggml-org/llama-voice/svelte": ["../../lib/voice/src/svelte/index.ts"], "$llama-ui-stories/*": ["../../lib/ui/tests/stories/*"], "@internationalized/date": ["./node_modules/@internationalized/date"], "@internationalized/date/*": ["./node_modules/@internationalized/date/*"], diff --git a/ui/apps/chat/vite.config.ts b/ui/apps/chat/vite.config.ts index e88c853dacff..fb9c666a9577 100644 --- a/ui/apps/chat/vite.config.ts +++ b/ui/apps/chat/vite.config.ts @@ -16,6 +16,7 @@ import { fileURLToPath } from 'url'; import { defineConfig, loadEnv, searchForWorkspaceRoot } from 'vite'; const __dirname = dirname(fileURLToPath(import.meta.url)); +const LLAMA_VOICE_SOURCE = resolve(__dirname, '../../lib/voice/src'); // eslint-disable-next-line @typescript-eslint/no-explicit-any const browserBaseConfig: any = { enabled: true, @@ -76,14 +77,25 @@ export default defineConfig(({ mode }) => { ], resolve: { - alias: { - 'katex-fonts': resolve('node_modules/katex/dist/fonts') - } + alias: [ + // Llama Voice has no build step in the repo: the app compiles it from source. Exact + // matches, so the package's root does not swallow its ./svelte entry + { + find: /^@ggml-org\/llama-voice\/svelte$/, + replacement: resolve(LLAMA_VOICE_SOURCE, 'svelte/index.ts') + }, + { find: /^@ggml-org\/llama-voice$/, replacement: resolve(LLAMA_VOICE_SOURCE, 'index.ts') }, + { find: 'katex-fonts', replacement: resolve('node_modules/katex/dist/fonts') } + ] }, server: { fs: { - allow: [searchForWorkspaceRoot(process.cwd()), resolve(__dirname, 'tests')] + allow: [ + searchForWorkspaceRoot(process.cwd()), + resolve(__dirname, 'tests'), + LLAMA_VOICE_SOURCE + ] }, headers: { 'Cross-Origin-Embedder-Policy': 'require-corp', @@ -95,7 +107,8 @@ export default defineConfig(({ mode }) => { '/props': SERVER_ORIGIN, '/slots': SERVER_ORIGIN, '/tools': SERVER_ORIGIN, - '/v1': SERVER_ORIGIN + // ws: realtime transcription (/v1/realtime) is a WebSocket + '/v1': { target: SERVER_ORIGIN, ws: true } } }, diff --git a/ui/lib/ui/.storybook/docs.css b/ui/lib/ui/.storybook/docs.css index 4a2f1facc078..46145e1ecd2d 100644 --- a/ui/lib/ui/.storybook/docs.css +++ b/ui/lib/ui/.storybook/docs.css @@ -9,14 +9,14 @@ } .ds-docs { - @apply mx-auto max-w-3xl font-sans text-body text-fg-default; + @apply mx-auto max-w-3xl font-sans text-body text-foreground; & :where(h1) { @apply mb-4 text-heading; } & :where(h2) { - @apply mt-10 mb-3 border-b border-line-default pb-2 text-title; + @apply mt-10 mb-3 border-b border-border pb-2 text-title; } & :where(h3) { @@ -48,16 +48,16 @@ } & :where(a) { - @apply underline underline-offset-2 hover:text-fg-muted; + @apply underline underline-offset-2 hover:text-muted-foreground; } & :where(blockquote) { - @apply border-l-2 border-line-default pl-4 text-fg-muted; + @apply border-l-2 border-border pl-4 text-muted-foreground; } /* a note that stands out from the running text: a quiet panel with the accent on its edge */ & :where(.callout) { - @apply my-6 rounded-panel border-l-2 border-(--art-cinder) bg-surface-muted px-5 py-4; + @apply my-6 rounded-lg border-l-2 border-(--art-cinder) bg-muted px-5 py-4; & > :where(p) { @apply my-0; @@ -65,16 +65,16 @@ } & :where(hr) { - @apply my-8 border-line-default; + @apply my-8 border-border; } /* inline code only, with a selector that outranks the code the Markdown block renders */ & :not(pre) > code { - @apply rounded-control border-0 bg-surface-code px-1 py-0.5 font-mono text-[0.875em] text-(--fg-code); + @apply rounded-md border-0 bg-(--surface-code) px-1 py-0.5 font-mono text-[0.875em] text-(--fg-code); } & :where(pre) { - @apply overflow-x-auto rounded-panel bg-surface-code p-4 text-body-sm; + @apply overflow-x-auto rounded-lg bg-(--surface-code) p-4 text-body-sm; } & :where(table) { @@ -82,7 +82,7 @@ } & :where(th, td) { - @apply border-b border-line-default px-3 py-2 text-left align-top; + @apply border-b border-border px-3 py-2 text-left align-top; } & :where(th) { diff --git a/ui/lib/ui/README.md b/ui/lib/ui/README.md index 2c701d8a6331..60abf7592c04 100644 --- a/ui/lib/ui/README.md +++ b/ui/lib/ui/README.md @@ -44,12 +44,22 @@ beside the apps built on it in `ui/apps`. `ModelQuantOptions`, `ModelQuantChip`, `ModelQuantRow`, `ModelDraftSidecars`, `ModelDownloadProgressBar`, plus the formatters and `minMemoryTierGb` and `summarizeSizes`, at `@ggml-org/llama-ui/models`. They take model data in and report what the user did out; fetching and downloading stay in the app. +- **Voice UI** (also `@ggml-org/llama-ui/voice`): `VoiceWaveformLive` (the waveform while recording), `VoiceWaveform` (a + recorded clip: play, seek, time) and `VoiceTranscriptReveal` (a clip with its transcript, opened on hover, keyboard + focus or a tap), plus `formatClipTime` and the waveform math. They take levels, peaks, an audio URL and a transcript + in; recording and transcribing stay in the app. Next: llama.app's model page. The constants, enums and code helpers the components use are entry points too, for an app that shows the same things: `@ggml-org/llama-ui/constants` (the shared classes and code-block constants), `@ggml-org/llama-ui/enums` (`ColorMode`, -`TooltipSide`, `BooleanString`) and `@ggml-org/llama-ui/code` (`highlightCode`, `trimCodePadding`). The model data +`TooltipSide`, `BooleanString`) and `@ggml-org/llama-ui/code` (`highlightCode`, `trimCodePadding`, +`loadHighlightLanguages`, `isHighlightLanguageLoaded`, `resolveHighlightLanguage`, `getLoadedHighlightLanguages`). +highlight.js loads one language at a time, each its own chunk, so none is in an app's first load: until a language +has loaded, `highlightCode` returns the code escaped as plain text, and a `$derived` or `$effect` that called it runs +again once it has. A language loads with the ones it embeds (CSS and JavaScript inside HTML); auto-detection picks +among lowlight's common languages. Await `loadHighlightLanguages([...])` where highlighted output is needed at once. +`scripts/generate-highlight-languages.mjs` regenerates the language table after a highlight.js or lowlight update. The model data (constants, enums, formatters and types) comes with the Model UI at `@ggml-org/llama-ui/models`. ## How the apps in this repo use it diff --git a/ui/lib/ui/package-lock.json b/ui/lib/ui/package-lock.json index 133cb2bd3cfb..1de52e057ed0 100644 --- a/ui/lib/ui/package-lock.json +++ b/ui/lib/ui/package-lock.json @@ -1,12 +1,12 @@ { "name": "@ggml-org/llama-ui", - "version": "0.4.0", + "version": "0.5.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@ggml-org/llama-ui", - "version": "0.4.0", + "version": "0.5.0", "license": "MIT", "dependencies": { "@ggml-org/llama-brand": "0.1.0", diff --git a/ui/lib/ui/package.json b/ui/lib/ui/package.json index 6706dbaeed89..1def1aae4e15 100644 --- a/ui/lib/ui/package.json +++ b/ui/lib/ui/package.json @@ -1,6 +1,6 @@ { "name": "@ggml-org/llama-ui", - "version": "0.4.0", + "version": "0.5.0", "description": "Shared UI library for llama.cpp frontend apps.", "license": "MIT", "repository": { @@ -54,6 +54,10 @@ "types": "./dist/components/models/index.d.ts", "svelte": "./dist/components/models/index.js" }, + "./voice": { + "types": "./dist/components/voice/index.d.ts", + "svelte": "./dist/components/voice/index.js" + }, "./utils": { "types": "./dist/components/ui/utils.d.ts", "svelte": "./dist/components/ui/utils.js" diff --git a/ui/lib/ui/scripts/alias-package.mjs b/ui/lib/ui/scripts/alias-package.mjs new file mode 100644 index 000000000000..f3e94131edf0 --- /dev/null +++ b/ui/lib/ui/scripts/alias-package.mjs @@ -0,0 +1,43 @@ +#!/usr/bin/env node +// Turns this checkout of the library into its unscoped alias, llama-ui, for +// .github/workflows/ui-lib-publish.yml: the same build, published a second time under the +// name people type first. Only the name in package.json changes, and the readme gains a note +// saying which package is the real one. Run it after the scoped publish and never commit the +// result. + +import { readFileSync, writeFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +const ALIAS = 'llama-ui'; + +const pkgPath = fileURLToPath(new URL('../package.json', import.meta.url)); +const readmePath = fileURLToPath(new URL('../README.md', import.meta.url)); + +const raw = readFileSync(pkgPath, 'utf8'); +const pkg = JSON.parse(raw); +const scoped = pkg.name; + +if (scoped === ALIAS) { + console.log(`package.json is already named ${ALIAS}`); + process.exit(0); +} +if (!scoped?.endsWith(`/${ALIAS}`)) { + console.error(`expected a scoped ${ALIAS} package to alias, got ${scoped}`); + process.exit(1); +} + +pkg.name = ALIAS; +// keep the file's own indentation so the diff is the name alone +const indent = raw.match(/^[ \t]+/m)?.[0] ?? '\t'; +writeFileSync(pkgPath, JSON.stringify(pkg, null, indent) + '\n'); + +const note = [ + `> \`${ALIAS}\` is an alias of [\`${scoped}\`](https://www.npmjs.com/package/${scoped}): the same`, + `> build at the same version, published under both names. Prefer \`${scoped}\`; the examples`, + `> below use it, and work with \`${ALIAS}\` in its place.`, + '', + '', +].join('\n'); +writeFileSync(readmePath, note + readFileSync(readmePath, 'utf8')); + +console.log(`${scoped}@${pkg.version} is now named ${ALIAS}`); diff --git a/ui/lib/ui/scripts/generate-highlight-languages.mjs b/ui/lib/ui/scripts/generate-highlight-languages.mjs new file mode 100644 index 000000000000..38ca8551d06b --- /dev/null +++ b/ui/lib/ui/scripts/generate-highlight-languages.mjs @@ -0,0 +1,98 @@ +// Writes src/lib/utils/highlight-languages.ts: one loader per highlight.js language lowlight ships (each its own chunk +// in an app's build), the aliases that name them, and lowlight's common languages, which auto-detection picks from. +// Run it after updating highlight.js or lowlight: node scripts/generate-highlight-languages.mjs +import { execFileSync } from "node:child_process"; +import { writeFileSync } from "node:fs"; +import hljs from "highlight.js/lib/core"; +import { all, common } from "lowlight"; + +const OUTPUT = new URL( + "../src/lib/utils/highlight-languages.ts", + import.meta.url, +); + +const names = Object.keys(all).sort(); +const aliases = {}; +const subLanguages = {}; + +// the languages a definition embeds (`subLanguage`: CSS and JavaScript inside HTML, say), which highlight.js leaves +// plain unless they are registered too +function collectSubLanguages(mode, found, seen = new Set()) { + if (!mode || typeof mode !== "object" || seen.has(mode)) return found; + + seen.add(mode); + + for (const sub of [mode.subLanguage ?? []].flat()) + found.add(sub.toLowerCase()); + + for (const value of Object.values(mode)) { + if (Array.isArray(value)) + for (const item of value) collectSubLanguages(item, found, seen); + else if (value && typeof value === "object") + collectSubLanguages(value, found, seen); + } + + return found; +} + +// register in lowlight's order, so an alias two languages claim names the same one it does in lowlight +for (const name of names) { + const highlighter = hljs.newInstance(); + + highlighter.registerLanguage(name, all[name]); + + for (const alias of highlighter.getLanguage(name)?.aliases ?? []) { + const key = alias.toLowerCase(); + + if (key !== name && !(key in all)) aliases[key] = name; + } +} + +for (const name of names) { + const definition = all[name](hljs); + const found = [...collectSubLanguages(definition, new Set())] + .map((sub) => (sub in all ? sub : aliases[sub])) + .filter((sub) => sub && sub !== name); + + if (found.length) subLanguages[name] = [...new Set(found)].sort(); +} + +const quote = (s) => `'${s}'`; +const key = (s) => (/^[a-z_$][\w$]*$/i.test(s) ? s : quote(s)); + +const source = `// Generated by scripts/generate-highlight-languages.mjs from lowlight's languages; do not edit by hand. +import type { LanguageFn } from 'highlight.js'; + +/** Loads one highlight.js language, by its name. */ +export const HIGHLIGHT_LANGUAGE_LOADERS: Record Promise<{ default: LanguageFn }>> = { +${names.map((n) => `\t${key(n)}: () => import('highlight.js/lib/languages/${n}')`).join(",\n")} +}; + +/** The language each alias names (\`js\` -> \`javascript\`), as highlight.js resolves it. */ +export const HIGHLIGHT_LANGUAGE_ALIASES: Record = { +${Object.keys(aliases) + .sort() + .map((a) => `\t${key(a)}: ${quote(aliases[a])}`) + .join(",\n")} +}; + +/** The languages each language embeds, to load with it so its embedded code is highlighted too. */ +export const HIGHLIGHT_SUB_LANGUAGES: Record = { +${Object.keys(subLanguages) + .map((n) => `\t${key(n)}: [${subLanguages[n].map(quote).join(", ")}]`) + .join(",\n")} +}; + +/** lowlight's common languages: the ones auto-detection picks from. */ +export const HIGHLIGHT_AUTO_DETECT_LANGUAGES: readonly string[] = [ +${Object.keys(common) + .sort() + .map((n) => `\t${quote(n)}`) + .join(",\n")} +]; +`; + +writeFileSync(OUTPUT, source); +execFileSync("npx", ["prettier", "--write", OUTPUT.pathname], { + stdio: "inherit", +}); diff --git a/ui/lib/ui/src/lib/components/app/content/SyntaxHighlightedCode.svelte b/ui/lib/ui/src/lib/components/app/content/SyntaxHighlightedCode.svelte index 0facb87b1ea8..ebf33d8013b1 100644 --- a/ui/lib/ui/src/lib/components/app/content/SyntaxHighlightedCode.svelte +++ b/ui/lib/ui/src/lib/components/app/content/SyntaxHighlightedCode.svelte @@ -129,14 +129,14 @@
        -
        {@html highlightedHtml}
        +
        {@html highlightedHtml}
        diff --git a/ui/lib/ui/src/lib/components/models/ModelCapabilityIcons.svelte b/ui/lib/ui/src/lib/components/models/ModelCapabilityIcons.svelte index 93876fcf8088..5840a5cce778 100644 --- a/ui/lib/ui/src/lib/components/models/ModelCapabilityIcons.svelte +++ b/ui/lib/ui/src/lib/components/models/ModelCapabilityIcons.svelte @@ -58,7 +58,7 @@ {#each capabilities as capability (capability)} {@const Icon = CAPABILITY_ICONS[capability]} - + {CAPABILITY_LABELS[capability]} @@ -70,7 +70,7 @@ {#each shownModalities as modality (modality)} {@const Icon = MODALITY_ICONS[modality]} - + {MODALITY_LABELS[modality]} diff --git a/ui/lib/ui/src/lib/components/models/ModelCard.svelte b/ui/lib/ui/src/lib/components/models/ModelCard.svelte index f6fc5076f6e9..f59d5c2ed974 100644 --- a/ui/lib/ui/src/lib/components/models/ModelCard.svelte +++ b/ui/lib/ui/src/lib/components/models/ModelCard.svelte @@ -87,7 +87,7 @@ {@render children?.()} {#if footer || footerEnd} -
        +
        {@render footer?.()}
        diff --git a/ui/lib/ui/src/lib/components/models/ModelId.svelte b/ui/lib/ui/src/lib/components/models/ModelId.svelte index eb9f8a4fbf1a..f31da4c7804a 100644 --- a/ui/lib/ui/src/lib/components/models/ModelId.svelte +++ b/ui/lib/ui/src/lib/components/models/ModelId.svelte @@ -229,7 +229,7 @@ - {formatParameters(contextLength)} + {formatParameters(contextLength)} {/if} @@ -237,7 +237,7 @@ - {formatSizeRange(sizeRange.min, sizeRange.max)} + {formatSizeRange(sizeRange.min, sizeRange.max)} {/if} diff --git a/ui/lib/ui/src/lib/components/models/ModelMetadataItem.svelte b/ui/lib/ui/src/lib/components/models/ModelMetadataItem.svelte index b3e9a0c81552..ae91db77cadb 100644 --- a/ui/lib/ui/src/lib/components/models/ModelMetadataItem.svelte +++ b/ui/lib/ui/src/lib/components/models/ModelMetadataItem.svelte @@ -11,7 +11,7 @@ {label} diff --git a/ui/lib/ui/src/lib/components/models/ModelOrgAvatar.svelte b/ui/lib/ui/src/lib/components/models/ModelOrgAvatar.svelte index 8a983d4577c4..d5e0d251c7c7 100644 --- a/ui/lib/ui/src/lib/components/models/ModelOrgAvatar.svelte +++ b/ui/lib/ui/src/lib/components/models/ModelOrgAvatar.svelte @@ -72,7 +72,7 @@ {#if orgAvatarFailed}